OSDN Git Service

2004-04-07 H.J. Lu <hongjiu.lu@intel.com>
[pf3gnuchains/gcc-fork.git] / gcc / config / ia64 / ia64.c
1 /* Definitions of target machine for GNU compiler.
2    Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004
3    Free Software Foundation, Inc.
4    Contributed by James E. Wilson <wilson@cygnus.com> and
5                   David Mosberger <davidm@hpl.hp.com>.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING.  If not, write to
21 the Free Software Foundation, 59 Temple Place - Suite 330,
22 Boston, MA 02111-1307, USA.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "tm.h"
28 #include "rtl.h"
29 #include "tree.h"
30 #include "regs.h"
31 #include "hard-reg-set.h"
32 #include "real.h"
33 #include "insn-config.h"
34 #include "conditions.h"
35 #include "output.h"
36 #include "insn-attr.h"
37 #include "flags.h"
38 #include "recog.h"
39 #include "expr.h"
40 #include "optabs.h"
41 #include "except.h"
42 #include "function.h"
43 #include "ggc.h"
44 #include "basic-block.h"
45 #include "toplev.h"
46 #include "sched-int.h"
47 #include "timevar.h"
48 #include "target.h"
49 #include "target-def.h"
50 #include "tm_p.h"
51 #include "hashtab.h"
52 #include "langhooks.h"
53 #include "cfglayout.h"
54
55 /* This is used for communication between ASM_OUTPUT_LABEL and
56    ASM_OUTPUT_LABELREF.  */
57 int ia64_asm_output_label = 0;
58
59 /* Define the information needed to generate branch and scc insns.  This is
60    stored from the compare operation.  */
61 struct rtx_def * ia64_compare_op0;
62 struct rtx_def * ia64_compare_op1;
63
64 /* Register names for ia64_expand_prologue.  */
65 static const char * const ia64_reg_numbers[96] =
66 { "r32", "r33", "r34", "r35", "r36", "r37", "r38", "r39",
67   "r40", "r41", "r42", "r43", "r44", "r45", "r46", "r47",
68   "r48", "r49", "r50", "r51", "r52", "r53", "r54", "r55",
69   "r56", "r57", "r58", "r59", "r60", "r61", "r62", "r63",
70   "r64", "r65", "r66", "r67", "r68", "r69", "r70", "r71",
71   "r72", "r73", "r74", "r75", "r76", "r77", "r78", "r79",
72   "r80", "r81", "r82", "r83", "r84", "r85", "r86", "r87",
73   "r88", "r89", "r90", "r91", "r92", "r93", "r94", "r95",
74   "r96", "r97", "r98", "r99", "r100","r101","r102","r103",
75   "r104","r105","r106","r107","r108","r109","r110","r111",
76   "r112","r113","r114","r115","r116","r117","r118","r119",
77   "r120","r121","r122","r123","r124","r125","r126","r127"};
78
79 /* ??? These strings could be shared with REGISTER_NAMES.  */
80 static const char * const ia64_input_reg_names[8] =
81 { "in0",  "in1",  "in2",  "in3",  "in4",  "in5",  "in6",  "in7" };
82
83 /* ??? These strings could be shared with REGISTER_NAMES.  */
84 static const char * const ia64_local_reg_names[80] =
85 { "loc0", "loc1", "loc2", "loc3", "loc4", "loc5", "loc6", "loc7",
86   "loc8", "loc9", "loc10","loc11","loc12","loc13","loc14","loc15",
87   "loc16","loc17","loc18","loc19","loc20","loc21","loc22","loc23",
88   "loc24","loc25","loc26","loc27","loc28","loc29","loc30","loc31",
89   "loc32","loc33","loc34","loc35","loc36","loc37","loc38","loc39",
90   "loc40","loc41","loc42","loc43","loc44","loc45","loc46","loc47",
91   "loc48","loc49","loc50","loc51","loc52","loc53","loc54","loc55",
92   "loc56","loc57","loc58","loc59","loc60","loc61","loc62","loc63",
93   "loc64","loc65","loc66","loc67","loc68","loc69","loc70","loc71",
94   "loc72","loc73","loc74","loc75","loc76","loc77","loc78","loc79" };
95
96 /* ??? These strings could be shared with REGISTER_NAMES.  */
97 static const char * const ia64_output_reg_names[8] =
98 { "out0", "out1", "out2", "out3", "out4", "out5", "out6", "out7" };
99
100 /* String used with the -mfixed-range= option.  */
101 const char *ia64_fixed_range_string;
102
103 /* Determines whether we use adds, addl, or movl to generate our
104    TLS immediate offsets.  */
105 int ia64_tls_size = 22;
106
107 /* String used with the -mtls-size= option.  */
108 const char *ia64_tls_size_string;
109
110 /* Which cpu are we scheduling for.  */
111 enum processor_type ia64_tune;
112
113 /* String used with the -tune= option.  */
114 const char *ia64_tune_string;
115
116 /* Determines whether we run our final scheduling pass or not.  We always
117    avoid the normal second scheduling pass.  */
118 static int ia64_flag_schedule_insns2;
119
120 /* Determines whether we run variable tracking in machine dependent
121    reorganization.  */
122 static int ia64_flag_var_tracking;
123
124 /* Variables which are this size or smaller are put in the sdata/sbss
125    sections.  */
126
127 unsigned int ia64_section_threshold;
128
129 /* The following variable is used by the DFA insn scheduler.  The value is
130    TRUE if we do insn bundling instead of insn scheduling.  */
131 int bundling_p = 0;
132
133 /* Structure to be filled in by ia64_compute_frame_size with register
134    save masks and offsets for the current function.  */
135
136 struct ia64_frame_info
137 {
138   HOST_WIDE_INT total_size;     /* size of the stack frame, not including
139                                    the caller's scratch area.  */
140   HOST_WIDE_INT spill_cfa_off;  /* top of the reg spill area from the cfa.  */
141   HOST_WIDE_INT spill_size;     /* size of the gr/br/fr spill area.  */
142   HOST_WIDE_INT extra_spill_size;  /* size of spill area for others.  */
143   HARD_REG_SET mask;            /* mask of saved registers.  */
144   unsigned int gr_used_mask;    /* mask of registers in use as gr spill
145                                    registers or long-term scratches.  */
146   int n_spilled;                /* number of spilled registers.  */
147   int reg_fp;                   /* register for fp.  */
148   int reg_save_b0;              /* save register for b0.  */
149   int reg_save_pr;              /* save register for prs.  */
150   int reg_save_ar_pfs;          /* save register for ar.pfs.  */
151   int reg_save_ar_unat;         /* save register for ar.unat.  */
152   int reg_save_ar_lc;           /* save register for ar.lc.  */
153   int reg_save_gp;              /* save register for gp.  */
154   int n_input_regs;             /* number of input registers used.  */
155   int n_local_regs;             /* number of local registers used.  */
156   int n_output_regs;            /* number of output registers used.  */
157   int n_rotate_regs;            /* number of rotating registers used.  */
158
159   char need_regstk;             /* true if a .regstk directive needed.  */
160   char initialized;             /* true if the data is finalized.  */
161 };
162
163 /* Current frame information calculated by ia64_compute_frame_size.  */
164 static struct ia64_frame_info current_frame_info;
165 \f
166 static int ia64_use_dfa_pipeline_interface (void);
167 static int ia64_first_cycle_multipass_dfa_lookahead (void);
168 static void ia64_dependencies_evaluation_hook (rtx, rtx);
169 static void ia64_init_dfa_pre_cycle_insn (void);
170 static rtx ia64_dfa_pre_cycle_insn (void);
171 static int ia64_first_cycle_multipass_dfa_lookahead_guard (rtx);
172 static int ia64_dfa_new_cycle (FILE *, int, rtx, int, int, int *);
173 static rtx gen_tls_get_addr (void);
174 static rtx gen_thread_pointer (void);
175 static rtx ia64_expand_tls_address (enum tls_model, rtx, rtx);
176 static int find_gr_spill (int);
177 static int next_scratch_gr_reg (void);
178 static void mark_reg_gr_used_mask (rtx, void *);
179 static void ia64_compute_frame_size (HOST_WIDE_INT);
180 static void setup_spill_pointers (int, rtx, HOST_WIDE_INT);
181 static void finish_spill_pointers (void);
182 static rtx spill_restore_mem (rtx, HOST_WIDE_INT);
183 static void do_spill (rtx (*)(rtx, rtx, rtx), rtx, HOST_WIDE_INT, rtx);
184 static void do_restore (rtx (*)(rtx, rtx, rtx), rtx, HOST_WIDE_INT);
185 static rtx gen_movdi_x (rtx, rtx, rtx);
186 static rtx gen_fr_spill_x (rtx, rtx, rtx);
187 static rtx gen_fr_restore_x (rtx, rtx, rtx);
188
189 static enum machine_mode hfa_element_mode (tree, int);
190 static void ia64_setup_incoming_varargs (CUMULATIVE_ARGS *, enum machine_mode,
191                                          tree, int *, int);
192 static bool ia64_function_ok_for_sibcall (tree, tree);
193 static bool ia64_return_in_memory (tree, tree);
194 static bool ia64_rtx_costs (rtx, int, int, int *);
195 static void fix_range (const char *);
196 static struct machine_function * ia64_init_machine_status (void);
197 static void emit_insn_group_barriers (FILE *);
198 static void emit_all_insn_group_barriers (FILE *);
199 static void final_emit_insn_group_barriers (FILE *);
200 static void emit_predicate_relation_info (void);
201 static void ia64_reorg (void);
202 static bool ia64_in_small_data_p (tree);
203 static void process_epilogue (void);
204 static int process_set (FILE *, rtx);
205
206 static rtx ia64_expand_fetch_and_op (optab, enum machine_mode, tree, rtx);
207 static rtx ia64_expand_op_and_fetch (optab, enum machine_mode, tree, rtx);
208 static rtx ia64_expand_compare_and_swap (enum machine_mode, enum machine_mode,
209                                          int, tree, rtx);
210 static rtx ia64_expand_lock_test_and_set (enum machine_mode, tree, rtx);
211 static rtx ia64_expand_lock_release (enum machine_mode, tree, rtx);
212 static bool ia64_assemble_integer (rtx, unsigned int, int);
213 static void ia64_output_function_prologue (FILE *, HOST_WIDE_INT);
214 static void ia64_output_function_epilogue (FILE *, HOST_WIDE_INT);
215 static void ia64_output_function_end_prologue (FILE *);
216
217 static int ia64_issue_rate (void);
218 static int ia64_adjust_cost (rtx, rtx, rtx, int);
219 static void ia64_sched_init (FILE *, int, int);
220 static void ia64_sched_finish (FILE *, int);
221 static int ia64_dfa_sched_reorder (FILE *, int, rtx *, int *, int, int);
222 static int ia64_sched_reorder (FILE *, int, rtx *, int *, int);
223 static int ia64_sched_reorder2 (FILE *, int, rtx *, int *, int);
224 static int ia64_variable_issue (FILE *, int, rtx, int);
225
226 static struct bundle_state *get_free_bundle_state (void);
227 static void free_bundle_state (struct bundle_state *);
228 static void initiate_bundle_states (void);
229 static void finish_bundle_states (void);
230 static unsigned bundle_state_hash (const void *);
231 static int bundle_state_eq_p (const void *, const void *);
232 static int insert_bundle_state (struct bundle_state *);
233 static void initiate_bundle_state_table (void);
234 static void finish_bundle_state_table (void);
235 static int try_issue_nops (struct bundle_state *, int);
236 static int try_issue_insn (struct bundle_state *, rtx);
237 static void issue_nops_and_insn (struct bundle_state *, int, rtx, int, int);
238 static int get_max_pos (state_t);
239 static int get_template (state_t, int);
240
241 static rtx get_next_important_insn (rtx, rtx);
242 static void bundling (FILE *, int, rtx, rtx);
243
244 static void ia64_output_mi_thunk (FILE *, tree, HOST_WIDE_INT,
245                                   HOST_WIDE_INT, tree);
246 static void ia64_file_start (void);
247
248 static void ia64_select_rtx_section (enum machine_mode, rtx,
249                                      unsigned HOST_WIDE_INT);
250 static void ia64_rwreloc_select_section (tree, int, unsigned HOST_WIDE_INT)
251      ATTRIBUTE_UNUSED;
252 static void ia64_rwreloc_unique_section (tree, int)
253      ATTRIBUTE_UNUSED;
254 static void ia64_rwreloc_select_rtx_section (enum machine_mode, rtx,
255                                              unsigned HOST_WIDE_INT)
256      ATTRIBUTE_UNUSED;
257 static unsigned int ia64_rwreloc_section_type_flags (tree, const char *, int)
258      ATTRIBUTE_UNUSED;
259
260 static void ia64_hpux_add_extern_decl (tree decl)
261      ATTRIBUTE_UNUSED;
262 static void ia64_hpux_file_end (void)
263      ATTRIBUTE_UNUSED;
264 static void ia64_init_libfuncs (void)
265      ATTRIBUTE_UNUSED;
266 static void ia64_hpux_init_libfuncs (void)
267      ATTRIBUTE_UNUSED;
268 static void ia64_vms_init_libfuncs (void)
269      ATTRIBUTE_UNUSED;
270
271 static tree ia64_handle_model_attribute (tree *, tree, tree, int, bool *);
272 static void ia64_encode_section_info (tree, rtx, int);
273 static rtx ia64_struct_value_rtx (tree, int);
274
275 \f
276 /* Table of valid machine attributes.  */
277 static const struct attribute_spec ia64_attribute_table[] =
278 {
279   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
280   { "syscall_linkage", 0, 0, false, true,  true,  NULL },
281   { "model",           1, 1, true, false, false, ia64_handle_model_attribute },
282   { NULL,              0, 0, false, false, false, NULL }
283 };
284
285 /* Initialize the GCC target structure.  */
286 #undef TARGET_ATTRIBUTE_TABLE
287 #define TARGET_ATTRIBUTE_TABLE ia64_attribute_table
288
289 #undef TARGET_INIT_BUILTINS
290 #define TARGET_INIT_BUILTINS ia64_init_builtins
291
292 #undef TARGET_EXPAND_BUILTIN
293 #define TARGET_EXPAND_BUILTIN ia64_expand_builtin
294
295 #undef TARGET_ASM_BYTE_OP
296 #define TARGET_ASM_BYTE_OP "\tdata1\t"
297 #undef TARGET_ASM_ALIGNED_HI_OP
298 #define TARGET_ASM_ALIGNED_HI_OP "\tdata2\t"
299 #undef TARGET_ASM_ALIGNED_SI_OP
300 #define TARGET_ASM_ALIGNED_SI_OP "\tdata4\t"
301 #undef TARGET_ASM_ALIGNED_DI_OP
302 #define TARGET_ASM_ALIGNED_DI_OP "\tdata8\t"
303 #undef TARGET_ASM_UNALIGNED_HI_OP
304 #define TARGET_ASM_UNALIGNED_HI_OP "\tdata2.ua\t"
305 #undef TARGET_ASM_UNALIGNED_SI_OP
306 #define TARGET_ASM_UNALIGNED_SI_OP "\tdata4.ua\t"
307 #undef TARGET_ASM_UNALIGNED_DI_OP
308 #define TARGET_ASM_UNALIGNED_DI_OP "\tdata8.ua\t"
309 #undef TARGET_ASM_INTEGER
310 #define TARGET_ASM_INTEGER ia64_assemble_integer
311
312 #undef TARGET_ASM_FUNCTION_PROLOGUE
313 #define TARGET_ASM_FUNCTION_PROLOGUE ia64_output_function_prologue
314 #undef TARGET_ASM_FUNCTION_END_PROLOGUE
315 #define TARGET_ASM_FUNCTION_END_PROLOGUE ia64_output_function_end_prologue
316 #undef TARGET_ASM_FUNCTION_EPILOGUE
317 #define TARGET_ASM_FUNCTION_EPILOGUE ia64_output_function_epilogue
318
319 #undef TARGET_IN_SMALL_DATA_P
320 #define TARGET_IN_SMALL_DATA_P  ia64_in_small_data_p
321
322 #undef TARGET_SCHED_ADJUST_COST
323 #define TARGET_SCHED_ADJUST_COST ia64_adjust_cost
324 #undef TARGET_SCHED_ISSUE_RATE
325 #define TARGET_SCHED_ISSUE_RATE ia64_issue_rate
326 #undef TARGET_SCHED_VARIABLE_ISSUE
327 #define TARGET_SCHED_VARIABLE_ISSUE ia64_variable_issue
328 #undef TARGET_SCHED_INIT
329 #define TARGET_SCHED_INIT ia64_sched_init
330 #undef TARGET_SCHED_FINISH
331 #define TARGET_SCHED_FINISH ia64_sched_finish
332 #undef TARGET_SCHED_REORDER
333 #define TARGET_SCHED_REORDER ia64_sched_reorder
334 #undef TARGET_SCHED_REORDER2
335 #define TARGET_SCHED_REORDER2 ia64_sched_reorder2
336
337 #undef TARGET_SCHED_DEPENDENCIES_EVALUATION_HOOK
338 #define TARGET_SCHED_DEPENDENCIES_EVALUATION_HOOK ia64_dependencies_evaluation_hook
339
340 #undef TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE
341 #define TARGET_SCHED_USE_DFA_PIPELINE_INTERFACE ia64_use_dfa_pipeline_interface
342
343 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
344 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD ia64_first_cycle_multipass_dfa_lookahead
345
346 #undef TARGET_SCHED_INIT_DFA_PRE_CYCLE_INSN
347 #define TARGET_SCHED_INIT_DFA_PRE_CYCLE_INSN ia64_init_dfa_pre_cycle_insn
348 #undef TARGET_SCHED_DFA_PRE_CYCLE_INSN
349 #define TARGET_SCHED_DFA_PRE_CYCLE_INSN ia64_dfa_pre_cycle_insn
350
351 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD
352 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD\
353   ia64_first_cycle_multipass_dfa_lookahead_guard
354
355 #undef TARGET_SCHED_DFA_NEW_CYCLE
356 #define TARGET_SCHED_DFA_NEW_CYCLE ia64_dfa_new_cycle
357
358 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
359 #define TARGET_FUNCTION_OK_FOR_SIBCALL ia64_function_ok_for_sibcall
360
361 #undef TARGET_ASM_OUTPUT_MI_THUNK
362 #define TARGET_ASM_OUTPUT_MI_THUNK ia64_output_mi_thunk
363 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
364 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_tree_hwi_hwi_tree_true
365
366 #undef TARGET_ASM_FILE_START
367 #define TARGET_ASM_FILE_START ia64_file_start
368
369 #undef TARGET_RTX_COSTS
370 #define TARGET_RTX_COSTS ia64_rtx_costs
371 #undef TARGET_ADDRESS_COST
372 #define TARGET_ADDRESS_COST hook_int_rtx_0
373
374 #undef TARGET_MACHINE_DEPENDENT_REORG
375 #define TARGET_MACHINE_DEPENDENT_REORG ia64_reorg
376
377 #undef TARGET_ENCODE_SECTION_INFO
378 #define TARGET_ENCODE_SECTION_INFO ia64_encode_section_info
379
380 /* ??? ABI doesn't allow us to define this.  */
381 #if 0
382 #undef TARGET_PROMOTE_FUNCTION_ARGS
383 #define TARGET_PROMOTE_FUNCTION_ARGS hook_bool_tree_true
384 #endif
385
386 /* ??? ABI doesn't allow us to define this.  */
387 #if 0
388 #undef TARGET_PROMOTE_FUNCTION_RETURN
389 #define TARGET_PROMOTE_FUNCTION_RETURN hook_bool_tree_true
390 #endif
391
392 /* ??? Investigate.  */
393 #if 0
394 #undef TARGET_PROMOTE_PROTOTYPES
395 #define TARGET_PROMOTE_PROTOTYPES hook_bool_tree_true
396 #endif
397
398 #undef TARGET_STRUCT_VALUE_RTX
399 #define TARGET_STRUCT_VALUE_RTX ia64_struct_value_rtx
400 #undef TARGET_RETURN_IN_MEMORY
401 #define TARGET_RETURN_IN_MEMORY ia64_return_in_memory
402
403 #undef TARGET_SETUP_INCOMING_VARARGS
404 #define TARGET_SETUP_INCOMING_VARARGS ia64_setup_incoming_varargs
405 #undef TARGET_STRICT_ARGUMENT_NAMING
406 #define TARGET_STRICT_ARGUMENT_NAMING hook_bool_CUMULATIVE_ARGS_true
407
408 struct gcc_target targetm = TARGET_INITIALIZER;
409 \f
410 /* Return 1 if OP is a valid operand for the MEM of a CALL insn.  */
411
412 int
413 call_operand (rtx op, enum machine_mode mode)
414 {
415   if (mode != GET_MODE (op) && mode != VOIDmode)
416     return 0;
417
418   return (GET_CODE (op) == SYMBOL_REF || GET_CODE (op) == REG
419           || (GET_CODE (op) == SUBREG && GET_CODE (XEXP (op, 0)) == REG));
420 }
421
422 /* Return 1 if OP refers to a symbol in the sdata section.  */
423
424 int
425 sdata_symbolic_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
426 {
427   switch (GET_CODE (op))
428     {
429     case CONST:
430       if (GET_CODE (XEXP (op, 0)) != PLUS
431           || GET_CODE (XEXP (XEXP (op, 0), 0)) != SYMBOL_REF)
432         break;
433       op = XEXP (XEXP (op, 0), 0);
434       /* FALLTHRU */
435
436     case SYMBOL_REF:
437       if (CONSTANT_POOL_ADDRESS_P (op))
438         return GET_MODE_SIZE (get_pool_mode (op)) <= ia64_section_threshold;
439       else
440         return SYMBOL_REF_LOCAL_P (op) && SYMBOL_REF_SMALL_P (op);
441
442     default:
443       break;
444     }
445
446   return 0;
447 }
448
449 int
450 small_addr_symbolic_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
451 {
452   return SYMBOL_REF_SMALL_ADDR_P (op);
453 }
454
455 /* Return 1 if OP refers to a symbol, and is appropriate for a GOT load.  */
456
457 int
458 got_symbolic_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
459 {
460   switch (GET_CODE (op))
461     {
462     case CONST:
463       op = XEXP (op, 0);
464       if (GET_CODE (op) != PLUS)
465         return 0;
466       if (GET_CODE (XEXP (op, 0)) != SYMBOL_REF)
467         return 0;
468       op = XEXP (op, 1);
469       if (GET_CODE (op) != CONST_INT)
470         return 0;
471
472         return 1;
473
474       /* Ok if we're not using GOT entries at all.  */
475       if (TARGET_NO_PIC || TARGET_AUTO_PIC)
476         return 1;
477
478       /* "Ok" while emitting rtl, since otherwise we won't be provided
479          with the entire offset during emission, which makes it very
480          hard to split the offset into high and low parts.  */
481       if (rtx_equal_function_value_matters)
482         return 1;
483
484       /* Force the low 14 bits of the constant to zero so that we do not
485          use up so many GOT entries.  */
486       return (INTVAL (op) & 0x3fff) == 0;
487
488     case SYMBOL_REF:
489       if (SYMBOL_REF_SMALL_ADDR_P (op))
490         return 0;
491     case LABEL_REF:
492       return 1;
493
494     default:
495       break;
496     }
497   return 0;
498 }
499
500 /* Return 1 if OP refers to a symbol.  */
501
502 int
503 symbolic_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
504 {
505   switch (GET_CODE (op))
506     {
507     case CONST:
508     case SYMBOL_REF:
509     case LABEL_REF:
510       return 1;
511
512     default:
513       break;
514     }
515   return 0;
516 }
517
518 /* Return tls_model if OP refers to a TLS symbol.  */
519
520 int
521 tls_symbolic_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
522 {
523   if (GET_CODE (op) != SYMBOL_REF)
524     return 0;
525   return SYMBOL_REF_TLS_MODEL (op);
526 }
527
528
529 /* Return 1 if OP refers to a function.  */
530
531 int
532 function_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
533 {
534   if (GET_CODE (op) == SYMBOL_REF && SYMBOL_REF_FUNCTION_P (op))
535     return 1;
536   else
537     return 0;
538 }
539
540 /* Return 1 if OP is setjmp or a similar function.  */
541
542 /* ??? This is an unsatisfying solution.  Should rethink.  */
543
544 int
545 setjmp_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
546 {
547   const char *name;
548   int retval = 0;
549
550   if (GET_CODE (op) != SYMBOL_REF)
551     return 0;
552
553   name = XSTR (op, 0);
554
555   /* The following code is borrowed from special_function_p in calls.c.  */
556
557   /* Disregard prefix _, __ or __x.  */
558   if (name[0] == '_')
559     {
560       if (name[1] == '_' && name[2] == 'x')
561         name += 3;
562       else if (name[1] == '_')
563         name += 2;
564       else
565         name += 1;
566     }
567
568   if (name[0] == 's')
569     {
570       retval
571         = ((name[1] == 'e'
572             && (! strcmp (name, "setjmp")
573                 || ! strcmp (name, "setjmp_syscall")))
574            || (name[1] == 'i'
575                && ! strcmp (name, "sigsetjmp"))
576            || (name[1] == 'a'
577                && ! strcmp (name, "savectx")));
578     }
579   else if ((name[0] == 'q' && name[1] == 's'
580             && ! strcmp (name, "qsetjmp"))
581            || (name[0] == 'v' && name[1] == 'f'
582                && ! strcmp (name, "vfork")))
583     retval = 1;
584
585   return retval;
586 }
587
588 /* Return 1 if OP is a general operand, excluding tls symbolic operands.  */
589
590 int
591 move_operand (rtx op, enum machine_mode mode)
592 {
593   return general_operand (op, mode) && !tls_symbolic_operand (op, mode);
594 }
595
596 /* Return 1 if OP is a register operand that is (or could be) a GR reg.  */
597
598 int
599 gr_register_operand (rtx op, enum machine_mode mode)
600 {
601   if (! register_operand (op, mode))
602     return 0;
603   if (GET_CODE (op) == SUBREG)
604     op = SUBREG_REG (op);
605   if (GET_CODE (op) == REG)
606     {
607       unsigned int regno = REGNO (op);
608       if (regno < FIRST_PSEUDO_REGISTER)
609         return GENERAL_REGNO_P (regno);
610     }
611   return 1;
612 }
613
614 /* Return 1 if OP is a register operand that is (or could be) an FR reg.  */
615
616 int
617 fr_register_operand (rtx op, enum machine_mode mode)
618 {
619   if (! register_operand (op, mode))
620     return 0;
621   if (GET_CODE (op) == SUBREG)
622     op = SUBREG_REG (op);
623   if (GET_CODE (op) == REG)
624     {
625       unsigned int regno = REGNO (op);
626       if (regno < FIRST_PSEUDO_REGISTER)
627         return FR_REGNO_P (regno);
628     }
629   return 1;
630 }
631
632 /* Return 1 if OP is a register operand that is (or could be) a GR/FR reg.  */
633
634 int
635 grfr_register_operand (rtx op, enum machine_mode mode)
636 {
637   if (! register_operand (op, mode))
638     return 0;
639   if (GET_CODE (op) == SUBREG)
640     op = SUBREG_REG (op);
641   if (GET_CODE (op) == REG)
642     {
643       unsigned int regno = REGNO (op);
644       if (regno < FIRST_PSEUDO_REGISTER)
645         return GENERAL_REGNO_P (regno) || FR_REGNO_P (regno);
646     }
647   return 1;
648 }
649
650 /* Return 1 if OP is a nonimmediate operand that is (or could be) a GR reg.  */
651
652 int
653 gr_nonimmediate_operand (rtx op, enum machine_mode mode)
654 {
655   if (! nonimmediate_operand (op, mode))
656     return 0;
657   if (GET_CODE (op) == SUBREG)
658     op = SUBREG_REG (op);
659   if (GET_CODE (op) == REG)
660     {
661       unsigned int regno = REGNO (op);
662       if (regno < FIRST_PSEUDO_REGISTER)
663         return GENERAL_REGNO_P (regno);
664     }
665   return 1;
666 }
667
668 /* Return 1 if OP is a nonimmediate operand that is (or could be) a FR reg.  */
669
670 int
671 fr_nonimmediate_operand (rtx op, enum machine_mode mode)
672 {
673   if (! nonimmediate_operand (op, mode))
674     return 0;
675   if (GET_CODE (op) == SUBREG)
676     op = SUBREG_REG (op);
677   if (GET_CODE (op) == REG)
678     {
679       unsigned int regno = REGNO (op);
680       if (regno < FIRST_PSEUDO_REGISTER)
681         return FR_REGNO_P (regno);
682     }
683   return 1;
684 }
685
686 /* Return 1 if OP is a nonimmediate operand that is a GR/FR reg.  */
687
688 int
689 grfr_nonimmediate_operand (rtx op, enum machine_mode mode)
690 {
691   if (! nonimmediate_operand (op, mode))
692     return 0;
693   if (GET_CODE (op) == SUBREG)
694     op = SUBREG_REG (op);
695   if (GET_CODE (op) == REG)
696     {
697       unsigned int regno = REGNO (op);
698       if (regno < FIRST_PSEUDO_REGISTER)
699         return GENERAL_REGNO_P (regno) || FR_REGNO_P (regno);
700     }
701   return 1;
702 }
703
704 /* Return 1 if OP is a GR register operand, or zero.  */
705
706 int
707 gr_reg_or_0_operand (rtx op, enum machine_mode mode)
708 {
709   return (op == const0_rtx || gr_register_operand (op, mode));
710 }
711
712 /* Return 1 if OP is a GR register operand, or a 5 bit immediate operand.  */
713
714 int
715 gr_reg_or_5bit_operand (rtx op, enum machine_mode mode)
716 {
717   return ((GET_CODE (op) == CONST_INT && INTVAL (op) >= 0 && INTVAL (op) < 32)
718           || GET_CODE (op) == CONSTANT_P_RTX
719           || gr_register_operand (op, mode));
720 }
721
722 /* Return 1 if OP is a GR register operand, or a 6 bit immediate operand.  */
723
724 int
725 gr_reg_or_6bit_operand (rtx op, enum machine_mode mode)
726 {
727   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_M (INTVAL (op)))
728           || GET_CODE (op) == CONSTANT_P_RTX
729           || gr_register_operand (op, mode));
730 }
731
732 /* Return 1 if OP is a GR register operand, or an 8 bit immediate operand.  */
733
734 int
735 gr_reg_or_8bit_operand (rtx op, enum machine_mode mode)
736 {
737   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_K (INTVAL (op)))
738           || GET_CODE (op) == CONSTANT_P_RTX
739           || gr_register_operand (op, mode));
740 }
741
742 /* Return 1 if OP is a GR/FR register operand, or an 8 bit immediate.  */
743
744 int
745 grfr_reg_or_8bit_operand (rtx op, enum machine_mode mode)
746 {
747   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_K (INTVAL (op)))
748           || GET_CODE (op) == CONSTANT_P_RTX
749           || grfr_register_operand (op, mode));
750 }
751
752 /* Return 1 if OP is a register operand, or an 8 bit adjusted immediate
753    operand.  */
754
755 int
756 gr_reg_or_8bit_adjusted_operand (rtx op, enum machine_mode mode)
757 {
758   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_L (INTVAL (op)))
759           || GET_CODE (op) == CONSTANT_P_RTX
760           || gr_register_operand (op, mode));
761 }
762
763 /* Return 1 if OP is a register operand, or is valid for both an 8 bit
764    immediate and an 8 bit adjusted immediate operand.  This is necessary
765    because when we emit a compare, we don't know what the condition will be,
766    so we need the union of the immediates accepted by GT and LT.  */
767
768 int
769 gr_reg_or_8bit_and_adjusted_operand (rtx op, enum machine_mode mode)
770 {
771   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_K (INTVAL (op))
772            && CONST_OK_FOR_L (INTVAL (op)))
773           || GET_CODE (op) == CONSTANT_P_RTX
774           || gr_register_operand (op, mode));
775 }
776
777 /* Return 1 if OP is a register operand, or a 14 bit immediate operand.  */
778
779 int
780 gr_reg_or_14bit_operand (rtx op, enum machine_mode mode)
781 {
782   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_I (INTVAL (op)))
783           || GET_CODE (op) == CONSTANT_P_RTX
784           || gr_register_operand (op, mode));
785 }
786
787 /* Return 1 if OP is a register operand, or a 22 bit immediate operand.  */
788
789 int
790 gr_reg_or_22bit_operand (rtx op, enum machine_mode mode)
791 {
792   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_J (INTVAL (op)))
793           || GET_CODE (op) == CONSTANT_P_RTX
794           || gr_register_operand (op, mode));
795 }
796
797 /* Return 1 if OP is a 6 bit immediate operand.  */
798
799 int
800 shift_count_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
801 {
802   return ((GET_CODE (op) == CONST_INT && CONST_OK_FOR_M (INTVAL (op)))
803           || GET_CODE (op) == CONSTANT_P_RTX);
804 }
805
806 /* Return 1 if OP is a 5 bit immediate operand.  */
807
808 int
809 shift_32bit_count_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
810 {
811   return ((GET_CODE (op) == CONST_INT
812            && (INTVAL (op) >= 0 && INTVAL (op) < 32))
813           || GET_CODE (op) == CONSTANT_P_RTX);
814 }
815
816 /* Return 1 if OP is a 2, 4, 8, or 16 immediate operand.  */
817
818 int
819 shladd_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
820 {
821   return (GET_CODE (op) == CONST_INT
822           && (INTVAL (op) == 2 || INTVAL (op) == 4
823               || INTVAL (op) == 8 || INTVAL (op) == 16));
824 }
825
826 /* Return 1 if OP is a -16, -8, -4, -1, 1, 4, 8, or 16 immediate operand.  */
827
828 int
829 fetchadd_operand (rtx op, enum machine_mode mode ATTRIBUTE_UNUSED)
830 {
831   return (GET_CODE (op) == CONST_INT
832           && (INTVAL (op) == -16 || INTVAL (op) == -8 ||
833               INTVAL (op) == -4  || INTVAL (op) == -1 ||
834               INTVAL (op) == 1   || INTVAL (op) == 4  ||
835               INTVAL (op) == 8   || INTVAL (op) == 16));
836 }
837
838 /* Return 1 if OP is a floating-point constant zero, one, or a register.  */
839
840 int
841 fr_reg_or_fp01_operand (rtx op, enum machine_mode mode)
842 {
843   return ((GET_CODE (op) == CONST_DOUBLE && CONST_DOUBLE_OK_FOR_G (op))
844           || fr_register_operand (op, mode));
845 }
846
847 /* Like nonimmediate_operand, but don't allow MEMs that try to use a
848    POST_MODIFY with a REG as displacement.  */
849
850 int
851 destination_operand (rtx op, enum machine_mode mode)
852 {
853   if (! nonimmediate_operand (op, mode))
854     return 0;
855   if (GET_CODE (op) == MEM
856       && GET_CODE (XEXP (op, 0)) == POST_MODIFY
857       && GET_CODE (XEXP (XEXP (XEXP (op, 0), 1), 1)) == REG)
858     return 0;
859   return 1;
860 }
861
862 /* Like memory_operand, but don't allow post-increments.  */
863
864 int
865 not_postinc_memory_operand (rtx op, enum machine_mode mode)
866 {
867   return (memory_operand (op, mode)
868           && GET_RTX_CLASS (GET_CODE (XEXP (op, 0))) != RTX_AUTOINC);
869 }
870
871 /* Return 1 if this is a comparison operator, which accepts a normal 8-bit
872    signed immediate operand.  */
873
874 int
875 normal_comparison_operator (register rtx op, enum machine_mode mode)
876 {
877   enum rtx_code code = GET_CODE (op);
878   return ((mode == VOIDmode || GET_MODE (op) == mode)
879           && (code == EQ || code == NE
880               || code == GT || code == LE || code == GTU || code == LEU));
881 }
882
883 /* Return 1 if this is a comparison operator, which accepts an adjusted 8-bit
884    signed immediate operand.  */
885
886 int
887 adjusted_comparison_operator (register rtx op, enum machine_mode mode)
888 {
889   enum rtx_code code = GET_CODE (op);
890   return ((mode == VOIDmode || GET_MODE (op) == mode)
891           && (code == LT || code == GE || code == LTU || code == GEU));
892 }
893
894 /* Return 1 if this is a signed inequality operator.  */
895
896 int
897 signed_inequality_operator (register rtx op, enum machine_mode mode)
898 {
899   enum rtx_code code = GET_CODE (op);
900   return ((mode == VOIDmode || GET_MODE (op) == mode)
901           && (code == GE || code == GT
902               || code == LE || code == LT));
903 }
904
905 /* Return 1 if this operator is valid for predication.  */
906
907 int
908 predicate_operator (register rtx op, enum machine_mode mode)
909 {
910   enum rtx_code code = GET_CODE (op);
911   return ((GET_MODE (op) == mode || mode == VOIDmode)
912           && (code == EQ || code == NE));
913 }
914
915 /* Return 1 if this operator can be used in a conditional operation.  */
916
917 int
918 condop_operator (register rtx op, enum machine_mode mode)
919 {
920   enum rtx_code code = GET_CODE (op);
921   return ((GET_MODE (op) == mode || mode == VOIDmode)
922           && (code == PLUS || code == MINUS || code == AND
923               || code == IOR || code == XOR));
924 }
925
926 /* Return 1 if this is the ar.lc register.  */
927
928 int
929 ar_lc_reg_operand (register rtx op, enum machine_mode mode)
930 {
931   return (GET_MODE (op) == DImode
932           && (mode == DImode || mode == VOIDmode)
933           && GET_CODE (op) == REG
934           && REGNO (op) == AR_LC_REGNUM);
935 }
936
937 /* Return 1 if this is the ar.ccv register.  */
938
939 int
940 ar_ccv_reg_operand (register rtx op, enum machine_mode mode)
941 {
942   return ((GET_MODE (op) == mode || mode == VOIDmode)
943           && GET_CODE (op) == REG
944           && REGNO (op) == AR_CCV_REGNUM);
945 }
946
947 /* Return 1 if this is the ar.pfs register.  */
948
949 int
950 ar_pfs_reg_operand (register rtx op, enum machine_mode mode)
951 {
952   return ((GET_MODE (op) == mode || mode == VOIDmode)
953           && GET_CODE (op) == REG
954           && REGNO (op) == AR_PFS_REGNUM);
955 }
956
957 /* Like general_operand, but don't allow (mem (addressof)).  */
958
959 int
960 general_xfmode_operand (rtx op, enum machine_mode mode)
961 {
962   if (! general_operand (op, mode))
963     return 0;
964   if (GET_CODE (op) == MEM && GET_CODE (XEXP (op, 0)) == ADDRESSOF)
965     return 0;
966   return 1;
967 }
968
969 /* Similarly.  */
970
971 int
972 destination_xfmode_operand (rtx op, enum machine_mode mode)
973 {
974   if (! destination_operand (op, mode))
975     return 0;
976   if (GET_CODE (op) == MEM && GET_CODE (XEXP (op, 0)) == ADDRESSOF)
977     return 0;
978   return 1;
979 }
980
981 /* Similarly.  */
982
983 int
984 xfreg_or_fp01_operand (rtx op, enum machine_mode mode)
985 {
986   if (GET_CODE (op) == SUBREG)
987     return 0;
988   return fr_reg_or_fp01_operand (op, mode);
989 }
990
991 /* Return 1 if OP is valid as a base register in a reg + offset address.  */
992
993 int
994 basereg_operand (rtx op, enum machine_mode mode)
995 {
996   /* ??? Should I copy the flag_omit_frame_pointer and cse_not_expected
997      checks from pa.c basereg_operand as well?  Seems to be OK without them
998      in test runs.  */
999
1000   return (register_operand (op, mode) &&
1001           REG_POINTER ((GET_CODE (op) == SUBREG) ? SUBREG_REG (op) : op));
1002 }
1003 \f
1004 typedef enum
1005   {
1006     ADDR_AREA_NORMAL,   /* normal address area */
1007     ADDR_AREA_SMALL     /* addressable by "addl" (-2MB < addr < 2MB) */
1008   }
1009 ia64_addr_area;
1010
1011 static GTY(()) tree small_ident1;
1012 static GTY(()) tree small_ident2;
1013
1014 static void
1015 init_idents (void)
1016 {
1017   if (small_ident1 == 0)
1018     {
1019       small_ident1 = get_identifier ("small");
1020       small_ident2 = get_identifier ("__small__");
1021     }
1022 }
1023
1024 /* Retrieve the address area that has been chosen for the given decl.  */
1025
1026 static ia64_addr_area
1027 ia64_get_addr_area (tree decl)
1028 {
1029   tree model_attr;
1030
1031   model_attr = lookup_attribute ("model", DECL_ATTRIBUTES (decl));
1032   if (model_attr)
1033     {
1034       tree id;
1035
1036       init_idents ();
1037       id = TREE_VALUE (TREE_VALUE (model_attr));
1038       if (id == small_ident1 || id == small_ident2)
1039         return ADDR_AREA_SMALL;
1040     }
1041   return ADDR_AREA_NORMAL;
1042 }
1043
1044 static tree
1045 ia64_handle_model_attribute (tree *node, tree name, tree args, int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
1046 {
1047   ia64_addr_area addr_area = ADDR_AREA_NORMAL;
1048   ia64_addr_area area;
1049   tree arg, decl = *node;
1050
1051   init_idents ();
1052   arg = TREE_VALUE (args);
1053   if (arg == small_ident1 || arg == small_ident2)
1054     {
1055       addr_area = ADDR_AREA_SMALL;
1056     }
1057   else
1058     {
1059       warning ("invalid argument of `%s' attribute",
1060                IDENTIFIER_POINTER (name));
1061       *no_add_attrs = true;
1062     }
1063
1064   switch (TREE_CODE (decl))
1065     {
1066     case VAR_DECL:
1067       if ((DECL_CONTEXT (decl) && TREE_CODE (DECL_CONTEXT (decl))
1068            == FUNCTION_DECL)
1069           && !TREE_STATIC (decl))
1070         {
1071           error ("%Jan address area attribute cannot be specified for "
1072                  "local variables", decl, decl);
1073           *no_add_attrs = true;
1074         }
1075       area = ia64_get_addr_area (decl);
1076       if (area != ADDR_AREA_NORMAL && addr_area != area)
1077         {
1078           error ("%Jaddress area of '%s' conflicts with previous "
1079                  "declaration", decl, decl);
1080           *no_add_attrs = true;
1081         }
1082       break;
1083
1084     case FUNCTION_DECL:
1085       error ("%Jaddress area attribute cannot be specified for functions",
1086              decl, decl);
1087       *no_add_attrs = true;
1088       break;
1089
1090     default:
1091       warning ("`%s' attribute ignored", IDENTIFIER_POINTER (name));
1092       *no_add_attrs = true;
1093       break;
1094     }
1095
1096   return NULL_TREE;
1097 }
1098
1099 static void
1100 ia64_encode_addr_area (tree decl, rtx symbol)
1101 {
1102   int flags;
1103
1104   flags = SYMBOL_REF_FLAGS (symbol);
1105   switch (ia64_get_addr_area (decl))
1106     {
1107     case ADDR_AREA_NORMAL: break;
1108     case ADDR_AREA_SMALL: flags |= SYMBOL_FLAG_SMALL_ADDR; break;
1109     default: abort ();
1110     }
1111   SYMBOL_REF_FLAGS (symbol) = flags;
1112 }
1113
1114 static void
1115 ia64_encode_section_info (tree decl, rtx rtl, int first)
1116 {
1117   default_encode_section_info (decl, rtl, first);
1118
1119   /* Careful not to prod global register variables.  */
1120   if (TREE_CODE (decl) == VAR_DECL
1121       && GET_CODE (DECL_RTL (decl)) == MEM
1122       && GET_CODE (XEXP (DECL_RTL (decl), 0)) == SYMBOL_REF
1123       && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)))
1124     ia64_encode_addr_area (decl, XEXP (rtl, 0));
1125 }
1126 \f
1127 /* Return 1 if the operands of a move are ok.  */
1128
1129 int
1130 ia64_move_ok (rtx dst, rtx src)
1131 {
1132   /* If we're under init_recog_no_volatile, we'll not be able to use
1133      memory_operand.  So check the code directly and don't worry about
1134      the validity of the underlying address, which should have been
1135      checked elsewhere anyway.  */
1136   if (GET_CODE (dst) != MEM)
1137     return 1;
1138   if (GET_CODE (src) == MEM)
1139     return 0;
1140   if (register_operand (src, VOIDmode))
1141     return 1;
1142
1143   /* Otherwise, this must be a constant, and that either 0 or 0.0 or 1.0.  */
1144   if (INTEGRAL_MODE_P (GET_MODE (dst)))
1145     return src == const0_rtx;
1146   else
1147     return GET_CODE (src) == CONST_DOUBLE && CONST_DOUBLE_OK_FOR_G (src);
1148 }
1149
1150 int
1151 addp4_optimize_ok (rtx op1, rtx op2)
1152 {
1153   return (basereg_operand (op1, GET_MODE(op1)) !=
1154           basereg_operand (op2, GET_MODE(op2)));
1155 }
1156
1157 /* Check if OP is a mask suitable for use with SHIFT in a dep.z instruction.
1158    Return the length of the field, or <= 0 on failure.  */
1159
1160 int
1161 ia64_depz_field_mask (rtx rop, rtx rshift)
1162 {
1163   unsigned HOST_WIDE_INT op = INTVAL (rop);
1164   unsigned HOST_WIDE_INT shift = INTVAL (rshift);
1165
1166   /* Get rid of the zero bits we're shifting in.  */
1167   op >>= shift;
1168
1169   /* We must now have a solid block of 1's at bit 0.  */
1170   return exact_log2 (op + 1);
1171 }
1172
1173 /* Expand a symbolic constant load.  */
1174
1175 void
1176 ia64_expand_load_address (rtx dest, rtx src)
1177 {
1178   if (tls_symbolic_operand (src, VOIDmode))
1179     abort ();
1180   if (GET_CODE (dest) != REG)
1181     abort ();
1182
1183   /* ILP32 mode still loads 64-bits of data from the GOT.  This avoids
1184      having to pointer-extend the value afterward.  Other forms of address
1185      computation below are also more natural to compute as 64-bit quantities.
1186      If we've been given an SImode destination register, change it.  */
1187   if (GET_MODE (dest) != Pmode)
1188     dest = gen_rtx_REG (Pmode, REGNO (dest));
1189
1190   if (GET_CODE (src) == SYMBOL_REF && SYMBOL_REF_SMALL_ADDR_P (src))
1191     {
1192       emit_insn (gen_rtx_SET (VOIDmode, dest, src));
1193       return;
1194     }
1195   else if (TARGET_AUTO_PIC)
1196     {
1197       emit_insn (gen_load_gprel64 (dest, src));
1198       return;
1199     }
1200   else if (GET_CODE (src) == SYMBOL_REF && SYMBOL_REF_FUNCTION_P (src))
1201     {
1202       emit_insn (gen_load_fptr (dest, src));
1203       return;
1204     }
1205   else if (sdata_symbolic_operand (src, VOIDmode))
1206     {
1207       emit_insn (gen_load_gprel (dest, src));
1208       return;
1209     }
1210
1211   if (GET_CODE (src) == CONST
1212       && GET_CODE (XEXP (src, 0)) == PLUS
1213       && GET_CODE (XEXP (XEXP (src, 0), 1)) == CONST_INT
1214       && (INTVAL (XEXP (XEXP (src, 0), 1)) & 0x1fff) != 0)
1215     {
1216       rtx sym = XEXP (XEXP (src, 0), 0);
1217       HOST_WIDE_INT ofs, hi, lo;
1218
1219       /* Split the offset into a sign extended 14-bit low part
1220          and a complementary high part.  */
1221       ofs = INTVAL (XEXP (XEXP (src, 0), 1));
1222       lo = ((ofs & 0x3fff) ^ 0x2000) - 0x2000;
1223       hi = ofs - lo;
1224
1225       ia64_expand_load_address (dest, plus_constant (sym, hi));
1226       emit_insn (gen_adddi3 (dest, dest, GEN_INT (lo)));
1227     }
1228   else
1229     {
1230       rtx tmp;
1231
1232       tmp = gen_rtx_HIGH (Pmode, src);
1233       tmp = gen_rtx_PLUS (Pmode, tmp, pic_offset_table_rtx);
1234       emit_insn (gen_rtx_SET (VOIDmode, dest, tmp));
1235
1236       tmp = gen_rtx_LO_SUM (GET_MODE (dest), dest, src);
1237       emit_insn (gen_rtx_SET (VOIDmode, dest, tmp));
1238     }
1239 }
1240
1241 static GTY(()) rtx gen_tls_tga;
1242 static rtx
1243 gen_tls_get_addr (void)
1244 {
1245   if (!gen_tls_tga)
1246     gen_tls_tga = init_one_libfunc ("__tls_get_addr");
1247   return gen_tls_tga;
1248 }
1249
1250 static GTY(()) rtx thread_pointer_rtx;
1251 static rtx
1252 gen_thread_pointer (void)
1253 {
1254   if (!thread_pointer_rtx)
1255     {
1256       thread_pointer_rtx = gen_rtx_REG (Pmode, 13);
1257       RTX_UNCHANGING_P (thread_pointer_rtx) = 1;
1258     }
1259   return thread_pointer_rtx;
1260 }
1261
1262 static rtx
1263 ia64_expand_tls_address (enum tls_model tls_kind, rtx op0, rtx op1)
1264 {
1265   rtx tga_op1, tga_op2, tga_ret, tga_eqv, tmp, insns;
1266   rtx orig_op0 = op0;
1267
1268   switch (tls_kind)
1269     {
1270     case TLS_MODEL_GLOBAL_DYNAMIC:
1271       start_sequence ();
1272
1273       tga_op1 = gen_reg_rtx (Pmode);
1274       emit_insn (gen_load_ltoff_dtpmod (tga_op1, op1));
1275       tga_op1 = gen_rtx_MEM (Pmode, tga_op1);
1276       RTX_UNCHANGING_P (tga_op1) = 1;
1277
1278       tga_op2 = gen_reg_rtx (Pmode);
1279       emit_insn (gen_load_ltoff_dtprel (tga_op2, op1));
1280       tga_op2 = gen_rtx_MEM (Pmode, tga_op2);
1281       RTX_UNCHANGING_P (tga_op2) = 1;
1282
1283       tga_ret = emit_library_call_value (gen_tls_get_addr (), NULL_RTX,
1284                                          LCT_CONST, Pmode, 2, tga_op1,
1285                                          Pmode, tga_op2, Pmode);
1286
1287       insns = get_insns ();
1288       end_sequence ();
1289
1290       if (GET_MODE (op0) != Pmode)
1291         op0 = tga_ret;
1292       emit_libcall_block (insns, op0, tga_ret, op1);
1293       break;
1294
1295     case TLS_MODEL_LOCAL_DYNAMIC:
1296       /* ??? This isn't the completely proper way to do local-dynamic
1297          If the call to __tls_get_addr is used only by a single symbol,
1298          then we should (somehow) move the dtprel to the second arg
1299          to avoid the extra add.  */
1300       start_sequence ();
1301
1302       tga_op1 = gen_reg_rtx (Pmode);
1303       emit_insn (gen_load_ltoff_dtpmod (tga_op1, op1));
1304       tga_op1 = gen_rtx_MEM (Pmode, tga_op1);
1305       RTX_UNCHANGING_P (tga_op1) = 1;
1306
1307       tga_op2 = const0_rtx;
1308
1309       tga_ret = emit_library_call_value (gen_tls_get_addr (), NULL_RTX,
1310                                          LCT_CONST, Pmode, 2, tga_op1,
1311                                          Pmode, tga_op2, Pmode);
1312
1313       insns = get_insns ();
1314       end_sequence ();
1315
1316       tga_eqv = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx),
1317                                 UNSPEC_LD_BASE);
1318       tmp = gen_reg_rtx (Pmode);
1319       emit_libcall_block (insns, tmp, tga_ret, tga_eqv);
1320
1321       if (!register_operand (op0, Pmode))
1322         op0 = gen_reg_rtx (Pmode);
1323       if (TARGET_TLS64)
1324         {
1325           emit_insn (gen_load_dtprel (op0, op1));
1326           emit_insn (gen_adddi3 (op0, tmp, op0));
1327         }
1328       else
1329         emit_insn (gen_add_dtprel (op0, tmp, op1));
1330       break;
1331
1332     case TLS_MODEL_INITIAL_EXEC:
1333       tmp = gen_reg_rtx (Pmode);
1334       emit_insn (gen_load_ltoff_tprel (tmp, op1));
1335       tmp = gen_rtx_MEM (Pmode, tmp);
1336       RTX_UNCHANGING_P (tmp) = 1;
1337       tmp = force_reg (Pmode, tmp);
1338
1339       if (!register_operand (op0, Pmode))
1340         op0 = gen_reg_rtx (Pmode);
1341       emit_insn (gen_adddi3 (op0, tmp, gen_thread_pointer ()));
1342       break;
1343
1344     case TLS_MODEL_LOCAL_EXEC:
1345       if (!register_operand (op0, Pmode))
1346         op0 = gen_reg_rtx (Pmode);
1347       if (TARGET_TLS64)
1348         {
1349           emit_insn (gen_load_tprel (op0, op1));
1350           emit_insn (gen_adddi3 (op0, gen_thread_pointer (), op0));
1351         }
1352       else
1353         emit_insn (gen_add_tprel (op0, gen_thread_pointer (), op1));
1354       break;
1355
1356     default:
1357       abort ();
1358     }
1359
1360   if (orig_op0 == op0)
1361     return NULL_RTX;
1362   if (GET_MODE (orig_op0) == Pmode)
1363     return op0;
1364   return gen_lowpart (GET_MODE (orig_op0), op0);
1365 }
1366
1367 rtx
1368 ia64_expand_move (rtx op0, rtx op1)
1369 {
1370   enum machine_mode mode = GET_MODE (op0);
1371
1372   if (!reload_in_progress && !reload_completed && !ia64_move_ok (op0, op1))
1373     op1 = force_reg (mode, op1);
1374
1375   if ((mode == Pmode || mode == ptr_mode) && symbolic_operand (op1, VOIDmode))
1376     {
1377       enum tls_model tls_kind;
1378       if ((tls_kind = tls_symbolic_operand (op1, VOIDmode)))
1379         return ia64_expand_tls_address (tls_kind, op0, op1);
1380
1381       if (!TARGET_NO_PIC && reload_completed)
1382         {
1383           ia64_expand_load_address (op0, op1);
1384           return NULL_RTX;
1385         }
1386     }
1387
1388   return op1;
1389 }
1390
1391 /* Split a move from OP1 to OP0 conditional on COND.  */
1392
1393 void
1394 ia64_emit_cond_move (rtx op0, rtx op1, rtx cond)
1395 {
1396   rtx insn, first = get_last_insn ();
1397
1398   emit_move_insn (op0, op1);
1399
1400   for (insn = get_last_insn (); insn != first; insn = PREV_INSN (insn))
1401     if (INSN_P (insn))
1402       PATTERN (insn) = gen_rtx_COND_EXEC (VOIDmode, copy_rtx (cond),
1403                                           PATTERN (insn));
1404 }
1405
1406 /* Split a post-reload TImode or TFmode reference into two DImode
1407    components.  This is made extra difficult by the fact that we do
1408    not get any scratch registers to work with, because reload cannot
1409    be prevented from giving us a scratch that overlaps the register
1410    pair involved.  So instead, when addressing memory, we tweak the
1411    pointer register up and back down with POST_INCs.  Or up and not
1412    back down when we can get away with it.
1413
1414    REVERSED is true when the loads must be done in reversed order
1415    (high word first) for correctness.  DEAD is true when the pointer
1416    dies with the second insn we generate and therefore the second
1417    address must not carry a postmodify.
1418
1419    May return an insn which is to be emitted after the moves.  */
1420
1421 static rtx
1422 ia64_split_tmode (rtx out[2], rtx in, bool reversed, bool dead)
1423 {
1424   rtx fixup = 0;
1425
1426   switch (GET_CODE (in))
1427     {
1428     case REG:
1429       out[reversed] = gen_rtx_REG (DImode, REGNO (in));
1430       out[!reversed] = gen_rtx_REG (DImode, REGNO (in) + 1);
1431       break;
1432
1433     case CONST_INT:
1434     case CONST_DOUBLE:
1435       /* Cannot occur reversed.  */
1436       if (reversed) abort ();
1437       
1438       if (GET_MODE (in) != TFmode)
1439         split_double (in, &out[0], &out[1]);
1440       else
1441         /* split_double does not understand how to split a TFmode
1442            quantity into a pair of DImode constants.  */
1443         {
1444           REAL_VALUE_TYPE r;
1445           unsigned HOST_WIDE_INT p[2];
1446           long l[4];  /* TFmode is 128 bits */
1447
1448           REAL_VALUE_FROM_CONST_DOUBLE (r, in);
1449           real_to_target (l, &r, TFmode);
1450
1451           if (FLOAT_WORDS_BIG_ENDIAN)
1452             {
1453               p[0] = (((unsigned HOST_WIDE_INT) l[0]) << 32) + l[1];
1454               p[1] = (((unsigned HOST_WIDE_INT) l[2]) << 32) + l[3];
1455             }
1456           else
1457             {
1458               p[0] = (((unsigned HOST_WIDE_INT) l[3]) << 32) + l[2];
1459               p[1] = (((unsigned HOST_WIDE_INT) l[1]) << 32) + l[0];
1460             }
1461           out[0] = GEN_INT (p[0]);
1462           out[1] = GEN_INT (p[1]);
1463         }
1464       break;
1465
1466     case MEM:
1467       {
1468         rtx base = XEXP (in, 0);
1469         rtx offset;
1470
1471         switch (GET_CODE (base))
1472           {
1473           case REG:
1474             if (!reversed)
1475               {
1476                 out[0] = adjust_automodify_address
1477                   (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1478                 out[1] = adjust_automodify_address
1479                   (in, DImode, dead ? 0 : gen_rtx_POST_DEC (Pmode, base), 8);
1480               }
1481             else
1482               {
1483                 /* Reversal requires a pre-increment, which can only
1484                    be done as a separate insn.  */
1485                 emit_insn (gen_adddi3 (base, base, GEN_INT (8)));
1486                 out[0] = adjust_automodify_address
1487                   (in, DImode, gen_rtx_POST_DEC (Pmode, base), 8);
1488                 out[1] = adjust_address (in, DImode, 0);
1489               }
1490             break;
1491
1492           case POST_INC:
1493             if (reversed || dead) abort ();
1494             /* Just do the increment in two steps.  */
1495             out[0] = adjust_automodify_address (in, DImode, 0, 0);
1496             out[1] = adjust_automodify_address (in, DImode, 0, 8);
1497             break;
1498
1499           case POST_DEC:
1500             if (reversed || dead) abort ();
1501             /* Add 8, subtract 24.  */
1502             base = XEXP (base, 0);
1503             out[0] = adjust_automodify_address
1504               (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1505             out[1] = adjust_automodify_address
1506               (in, DImode,
1507                gen_rtx_POST_MODIFY (Pmode, base, plus_constant (base, -24)),
1508                8);
1509             break;
1510
1511           case POST_MODIFY:
1512             if (reversed || dead) abort ();
1513             /* Extract and adjust the modification.  This case is
1514                trickier than the others, because we might have an
1515                index register, or we might have a combined offset that
1516                doesn't fit a signed 9-bit displacement field.  We can
1517                assume the incoming expression is already legitimate.  */
1518             offset = XEXP (base, 1);
1519             base = XEXP (base, 0);
1520
1521             out[0] = adjust_automodify_address
1522               (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1523
1524             if (GET_CODE (XEXP (offset, 1)) == REG)
1525               {
1526                 /* Can't adjust the postmodify to match.  Emit the
1527                    original, then a separate addition insn.  */
1528                 out[1] = adjust_automodify_address (in, DImode, 0, 8);
1529                 fixup = gen_adddi3 (base, base, GEN_INT (-8));
1530               }
1531             else if (GET_CODE (XEXP (offset, 1)) != CONST_INT)
1532               abort ();
1533             else if (INTVAL (XEXP (offset, 1)) < -256 + 8)
1534               {
1535                 /* Again the postmodify cannot be made to match, but
1536                    in this case it's more efficient to get rid of the
1537                    postmodify entirely and fix up with an add insn.  */
1538                 out[1] = adjust_automodify_address (in, DImode, base, 8);
1539                 fixup = gen_adddi3 (base, base,
1540                                     GEN_INT (INTVAL (XEXP (offset, 1)) - 8));
1541               }
1542             else
1543               {
1544                 /* Combined offset still fits in the displacement field.
1545                    (We cannot overflow it at the high end.)  */
1546                 out[1] = adjust_automodify_address
1547                   (in, DImode,
1548                    gen_rtx_POST_MODIFY (Pmode, base,
1549                      gen_rtx_PLUS (Pmode, base,
1550                                    GEN_INT (INTVAL (XEXP (offset, 1)) - 8))),
1551                    8);
1552               }
1553             break;
1554
1555           default:
1556             abort ();
1557           }
1558         break;
1559       }
1560
1561     default:
1562       abort ();
1563     }
1564
1565   return fixup;
1566 }
1567
1568 /* Split a TImode or TFmode move instruction after reload.
1569    This is used by *movtf_internal and *movti_internal.  */
1570 void
1571 ia64_split_tmode_move (rtx operands[])
1572 {
1573   rtx in[2], out[2], insn;
1574   rtx fixup[2];
1575   bool dead = false;
1576   bool reversed = false;
1577
1578   /* It is possible for reload to decide to overwrite a pointer with
1579      the value it points to.  In that case we have to do the loads in
1580      the appropriate order so that the pointer is not destroyed too
1581      early.  Also we must not generate a postmodify for that second
1582      load, or rws_access_regno will abort.  */
1583   if (GET_CODE (operands[1]) == MEM
1584       && reg_overlap_mentioned_p (operands[0], operands[1]))
1585     {
1586       rtx base = XEXP (operands[1], 0);
1587       while (GET_CODE (base) != REG)
1588         base = XEXP (base, 0);
1589
1590       if (REGNO (base) == REGNO (operands[0]))
1591         reversed = true;
1592       dead = true;
1593     }
1594   /* Another reason to do the moves in reversed order is if the first
1595      element of the target register pair is also the second element of
1596      the source register pair.  */
1597   if (GET_CODE (operands[0]) == REG && GET_CODE (operands[1]) == REG
1598       && REGNO (operands[0]) == REGNO (operands[1]) + 1)
1599     reversed = true;
1600
1601   fixup[0] = ia64_split_tmode (in, operands[1], reversed, dead);
1602   fixup[1] = ia64_split_tmode (out, operands[0], reversed, dead);
1603
1604 #define MAYBE_ADD_REG_INC_NOTE(INSN, EXP)                               \
1605   if (GET_CODE (EXP) == MEM                                             \
1606       && (GET_CODE (XEXP (EXP, 0)) == POST_MODIFY                       \
1607           || GET_CODE (XEXP (EXP, 0)) == POST_INC                       \
1608           || GET_CODE (XEXP (EXP, 0)) == POST_DEC))                     \
1609     REG_NOTES (INSN) = gen_rtx_EXPR_LIST (REG_INC,                      \
1610                                           XEXP (XEXP (EXP, 0), 0),      \
1611                                           REG_NOTES (INSN))
1612
1613   insn = emit_insn (gen_rtx_SET (VOIDmode, out[0], in[0]));
1614   MAYBE_ADD_REG_INC_NOTE (insn, in[0]);
1615   MAYBE_ADD_REG_INC_NOTE (insn, out[0]);
1616
1617   insn = emit_insn (gen_rtx_SET (VOIDmode, out[1], in[1]));
1618   MAYBE_ADD_REG_INC_NOTE (insn, in[1]);
1619   MAYBE_ADD_REG_INC_NOTE (insn, out[1]);
1620
1621   if (fixup[0])
1622     emit_insn (fixup[0]);
1623   if (fixup[1])
1624     emit_insn (fixup[1]);
1625
1626 #undef MAYBE_ADD_REG_INC_NOTE
1627 }
1628
1629 /* ??? Fixing GR->FR XFmode moves during reload is hard.  You need to go
1630    through memory plus an extra GR scratch register.  Except that you can
1631    either get the first from SECONDARY_MEMORY_NEEDED or the second from
1632    SECONDARY_RELOAD_CLASS, but not both.
1633
1634    We got into problems in the first place by allowing a construct like
1635    (subreg:XF (reg:TI)), which we got from a union containing a long double.
1636    This solution attempts to prevent this situation from occurring.  When
1637    we see something like the above, we spill the inner register to memory.  */
1638
1639 rtx
1640 spill_xfmode_operand (rtx in, int force)
1641 {
1642   if (GET_CODE (in) == SUBREG
1643       && GET_MODE (SUBREG_REG (in)) == TImode
1644       && GET_CODE (SUBREG_REG (in)) == REG)
1645     {
1646       rtx mem = gen_mem_addressof (SUBREG_REG (in), NULL_TREE, /*rescan=*/true);
1647       return gen_rtx_MEM (XFmode, copy_to_reg (XEXP (mem, 0)));
1648     }
1649   else if (force && GET_CODE (in) == REG)
1650     {
1651       rtx mem = gen_mem_addressof (in, NULL_TREE, /*rescan=*/true);
1652       return gen_rtx_MEM (XFmode, copy_to_reg (XEXP (mem, 0)));
1653     }
1654   else if (GET_CODE (in) == MEM
1655            && GET_CODE (XEXP (in, 0)) == ADDRESSOF)
1656     return change_address (in, XFmode, copy_to_reg (XEXP (in, 0)));
1657   else
1658     return in;
1659 }
1660
1661 /* Emit comparison instruction if necessary, returning the expression
1662    that holds the compare result in the proper mode.  */
1663
1664 static GTY(()) rtx cmptf_libfunc;
1665
1666 rtx
1667 ia64_expand_compare (enum rtx_code code, enum machine_mode mode)
1668 {
1669   rtx op0 = ia64_compare_op0, op1 = ia64_compare_op1;
1670   rtx cmp;
1671
1672   /* If we have a BImode input, then we already have a compare result, and
1673      do not need to emit another comparison.  */
1674   if (GET_MODE (op0) == BImode)
1675     {
1676       if ((code == NE || code == EQ) && op1 == const0_rtx)
1677         cmp = op0;
1678       else
1679         abort ();
1680     }
1681   /* HPUX TFmode compare requires a library call to _U_Qfcmp, which takes a
1682      magic number as its third argument, that indicates what to do.
1683      The return value is an integer to be compared against zero.  */
1684   else if (TARGET_HPUX && GET_MODE (op0) == TFmode)
1685     {
1686       enum qfcmp_magic {
1687         QCMP_INV = 1,   /* Raise FP_INVALID on SNaN as a side effect.  */
1688         QCMP_UNORD = 2,
1689         QCMP_EQ = 4,
1690         QCMP_LT = 8,
1691         QCMP_GT = 16
1692       } magic;
1693       enum rtx_code ncode;
1694       rtx ret, insns;
1695       if (GET_MODE (op1) != TFmode)
1696         abort ();
1697       switch (code)
1698         {
1699           /* 1 = equal, 0 = not equal.  Equality operators do
1700              not raise FP_INVALID when given an SNaN operand.  */
1701         case EQ:        magic = QCMP_EQ;                  ncode = NE; break;
1702         case NE:        magic = QCMP_EQ;                  ncode = EQ; break;
1703           /* isunordered() from C99.  */
1704         case UNORDERED: magic = QCMP_UNORD;               ncode = NE; break;
1705           /* Relational operators raise FP_INVALID when given
1706              an SNaN operand.  */
1707         case LT:        magic = QCMP_LT        |QCMP_INV; ncode = NE; break;
1708         case LE:        magic = QCMP_LT|QCMP_EQ|QCMP_INV; ncode = NE; break;
1709         case GT:        magic = QCMP_GT        |QCMP_INV; ncode = NE; break;
1710         case GE:        magic = QCMP_GT|QCMP_EQ|QCMP_INV; ncode = NE; break;
1711           /* FUTURE: Implement UNEQ, UNLT, UNLE, UNGT, UNGE, LTGT.
1712              Expanders for buneq etc. weuld have to be added to ia64.md
1713              for this to be useful.  */
1714         default: abort ();
1715         }
1716
1717       start_sequence ();
1718
1719       ret = emit_library_call_value (cmptf_libfunc, 0, LCT_CONST, DImode, 3,
1720                                      op0, TFmode, op1, TFmode,
1721                                      GEN_INT (magic), DImode);
1722       cmp = gen_reg_rtx (BImode);
1723       emit_insn (gen_rtx_SET (VOIDmode, cmp,
1724                               gen_rtx_fmt_ee (ncode, BImode,
1725                                               ret, const0_rtx)));
1726
1727       insns = get_insns ();
1728       end_sequence ();
1729
1730       emit_libcall_block (insns, cmp, cmp,
1731                           gen_rtx_fmt_ee (code, BImode, op0, op1));
1732       code = NE;
1733     }
1734   else
1735     {
1736       cmp = gen_reg_rtx (BImode);
1737       emit_insn (gen_rtx_SET (VOIDmode, cmp,
1738                               gen_rtx_fmt_ee (code, BImode, op0, op1)));
1739       code = NE;
1740     }
1741
1742   return gen_rtx_fmt_ee (code, mode, cmp, const0_rtx);
1743 }
1744
1745 /* Emit the appropriate sequence for a call.  */
1746
1747 void
1748 ia64_expand_call (rtx retval, rtx addr, rtx nextarg ATTRIBUTE_UNUSED,
1749                   int sibcall_p)
1750 {
1751   rtx insn, b0;
1752
1753   addr = XEXP (addr, 0);
1754   addr = convert_memory_address (DImode, addr);
1755   b0 = gen_rtx_REG (DImode, R_BR (0));
1756
1757   /* ??? Should do this for functions known to bind local too.  */
1758   if (TARGET_NO_PIC || TARGET_AUTO_PIC)
1759     {
1760       if (sibcall_p)
1761         insn = gen_sibcall_nogp (addr);
1762       else if (! retval)
1763         insn = gen_call_nogp (addr, b0);
1764       else
1765         insn = gen_call_value_nogp (retval, addr, b0);
1766       insn = emit_call_insn (insn);
1767     }
1768   else
1769     {
1770       if (sibcall_p)
1771         insn = gen_sibcall_gp (addr);
1772       else if (! retval)
1773         insn = gen_call_gp (addr, b0);
1774       else
1775         insn = gen_call_value_gp (retval, addr, b0);
1776       insn = emit_call_insn (insn);
1777
1778       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
1779     }
1780
1781   if (sibcall_p)
1782     use_reg (&CALL_INSN_FUNCTION_USAGE (insn), b0);
1783 }
1784
1785 void
1786 ia64_reload_gp (void)
1787 {
1788   rtx tmp;
1789
1790   if (current_frame_info.reg_save_gp)
1791     tmp = gen_rtx_REG (DImode, current_frame_info.reg_save_gp);
1792   else
1793     {
1794       HOST_WIDE_INT offset;
1795
1796       offset = (current_frame_info.spill_cfa_off
1797                 + current_frame_info.spill_size);
1798       if (frame_pointer_needed)
1799         {
1800           tmp = hard_frame_pointer_rtx;
1801           offset = -offset;
1802         }
1803       else
1804         {
1805           tmp = stack_pointer_rtx;
1806           offset = current_frame_info.total_size - offset;
1807         }
1808
1809       if (CONST_OK_FOR_I (offset))
1810         emit_insn (gen_adddi3 (pic_offset_table_rtx,
1811                                tmp, GEN_INT (offset)));
1812       else
1813         {
1814           emit_move_insn (pic_offset_table_rtx, GEN_INT (offset));
1815           emit_insn (gen_adddi3 (pic_offset_table_rtx,
1816                                  pic_offset_table_rtx, tmp));
1817         }
1818
1819       tmp = gen_rtx_MEM (DImode, pic_offset_table_rtx);
1820     }
1821
1822   emit_move_insn (pic_offset_table_rtx, tmp);
1823 }
1824
1825 void
1826 ia64_split_call (rtx retval, rtx addr, rtx retaddr, rtx scratch_r,
1827                  rtx scratch_b, int noreturn_p, int sibcall_p)
1828 {
1829   rtx insn;
1830   bool is_desc = false;
1831
1832   /* If we find we're calling through a register, then we're actually
1833      calling through a descriptor, so load up the values.  */
1834   if (REG_P (addr) && GR_REGNO_P (REGNO (addr)))
1835     {
1836       rtx tmp;
1837       bool addr_dead_p;
1838
1839       /* ??? We are currently constrained to *not* use peep2, because
1840          we can legitimately change the global lifetime of the GP
1841          (in the form of killing where previously live).  This is
1842          because a call through a descriptor doesn't use the previous
1843          value of the GP, while a direct call does, and we do not
1844          commit to either form until the split here.
1845
1846          That said, this means that we lack precise life info for
1847          whether ADDR is dead after this call.  This is not terribly
1848          important, since we can fix things up essentially for free
1849          with the POST_DEC below, but it's nice to not use it when we
1850          can immediately tell it's not necessary.  */
1851       addr_dead_p = ((noreturn_p || sibcall_p
1852                       || TEST_HARD_REG_BIT (regs_invalidated_by_call,
1853                                             REGNO (addr)))
1854                      && !FUNCTION_ARG_REGNO_P (REGNO (addr)));
1855
1856       /* Load the code address into scratch_b.  */
1857       tmp = gen_rtx_POST_INC (Pmode, addr);
1858       tmp = gen_rtx_MEM (Pmode, tmp);
1859       emit_move_insn (scratch_r, tmp);
1860       emit_move_insn (scratch_b, scratch_r);
1861
1862       /* Load the GP address.  If ADDR is not dead here, then we must
1863          revert the change made above via the POST_INCREMENT.  */
1864       if (!addr_dead_p)
1865         tmp = gen_rtx_POST_DEC (Pmode, addr);
1866       else
1867         tmp = addr;
1868       tmp = gen_rtx_MEM (Pmode, tmp);
1869       emit_move_insn (pic_offset_table_rtx, tmp);
1870
1871       is_desc = true;
1872       addr = scratch_b;
1873     }
1874
1875   if (sibcall_p)
1876     insn = gen_sibcall_nogp (addr);
1877   else if (retval)
1878     insn = gen_call_value_nogp (retval, addr, retaddr);
1879   else
1880     insn = gen_call_nogp (addr, retaddr);
1881   emit_call_insn (insn);
1882
1883   if ((!TARGET_CONST_GP || is_desc) && !noreturn_p && !sibcall_p)
1884     ia64_reload_gp ();
1885 }
1886 \f
1887 /* Begin the assembly file.  */
1888
1889 static void
1890 ia64_file_start (void)
1891 {
1892   default_file_start ();
1893   emit_safe_across_calls ();
1894 }
1895
1896 void
1897 emit_safe_across_calls (void)
1898 {
1899   unsigned int rs, re;
1900   int out_state;
1901
1902   rs = 1;
1903   out_state = 0;
1904   while (1)
1905     {
1906       while (rs < 64 && call_used_regs[PR_REG (rs)])
1907         rs++;
1908       if (rs >= 64)
1909         break;
1910       for (re = rs + 1; re < 64 && ! call_used_regs[PR_REG (re)]; re++)
1911         continue;
1912       if (out_state == 0)
1913         {
1914           fputs ("\t.pred.safe_across_calls ", asm_out_file);
1915           out_state = 1;
1916         }
1917       else
1918         fputc (',', asm_out_file);
1919       if (re == rs + 1)
1920         fprintf (asm_out_file, "p%u", rs);
1921       else
1922         fprintf (asm_out_file, "p%u-p%u", rs, re - 1);
1923       rs = re + 1;
1924     }
1925   if (out_state)
1926     fputc ('\n', asm_out_file);
1927 }
1928
1929 /* Helper function for ia64_compute_frame_size: find an appropriate general
1930    register to spill some special register to.  SPECIAL_SPILL_MASK contains
1931    bits in GR0 to GR31 that have already been allocated by this routine.
1932    TRY_LOCALS is true if we should attempt to locate a local regnum.  */
1933
1934 static int
1935 find_gr_spill (int try_locals)
1936 {
1937   int regno;
1938
1939   /* If this is a leaf function, first try an otherwise unused
1940      call-clobbered register.  */
1941   if (current_function_is_leaf)
1942     {
1943       for (regno = GR_REG (1); regno <= GR_REG (31); regno++)
1944         if (! regs_ever_live[regno]
1945             && call_used_regs[regno]
1946             && ! fixed_regs[regno]
1947             && ! global_regs[regno]
1948             && ((current_frame_info.gr_used_mask >> regno) & 1) == 0)
1949           {
1950             current_frame_info.gr_used_mask |= 1 << regno;
1951             return regno;
1952           }
1953     }
1954
1955   if (try_locals)
1956     {
1957       regno = current_frame_info.n_local_regs;
1958       /* If there is a frame pointer, then we can't use loc79, because
1959          that is HARD_FRAME_POINTER_REGNUM.  In particular, see the
1960          reg_name switching code in ia64_expand_prologue.  */
1961       if (regno < (80 - frame_pointer_needed))
1962         {
1963           current_frame_info.n_local_regs = regno + 1;
1964           return LOC_REG (0) + regno;
1965         }
1966     }
1967
1968   /* Failed to find a general register to spill to.  Must use stack.  */
1969   return 0;
1970 }
1971
1972 /* In order to make for nice schedules, we try to allocate every temporary
1973    to a different register.  We must of course stay away from call-saved,
1974    fixed, and global registers.  We must also stay away from registers
1975    allocated in current_frame_info.gr_used_mask, since those include regs
1976    used all through the prologue.
1977
1978    Any register allocated here must be used immediately.  The idea is to
1979    aid scheduling, not to solve data flow problems.  */
1980
1981 static int last_scratch_gr_reg;
1982
1983 static int
1984 next_scratch_gr_reg (void)
1985 {
1986   int i, regno;
1987
1988   for (i = 0; i < 32; ++i)
1989     {
1990       regno = (last_scratch_gr_reg + i + 1) & 31;
1991       if (call_used_regs[regno]
1992           && ! fixed_regs[regno]
1993           && ! global_regs[regno]
1994           && ((current_frame_info.gr_used_mask >> regno) & 1) == 0)
1995         {
1996           last_scratch_gr_reg = regno;
1997           return regno;
1998         }
1999     }
2000
2001   /* There must be _something_ available.  */
2002   abort ();
2003 }
2004
2005 /* Helper function for ia64_compute_frame_size, called through
2006    diddle_return_value.  Mark REG in current_frame_info.gr_used_mask.  */
2007
2008 static void
2009 mark_reg_gr_used_mask (rtx reg, void *data ATTRIBUTE_UNUSED)
2010 {
2011   unsigned int regno = REGNO (reg);
2012   if (regno < 32)
2013     {
2014       unsigned int i, n = HARD_REGNO_NREGS (regno, GET_MODE (reg));
2015       for (i = 0; i < n; ++i)
2016         current_frame_info.gr_used_mask |= 1 << (regno + i);
2017     }
2018 }
2019
2020 /* Returns the number of bytes offset between the frame pointer and the stack
2021    pointer for the current function.  SIZE is the number of bytes of space
2022    needed for local variables.  */
2023
2024 static void
2025 ia64_compute_frame_size (HOST_WIDE_INT size)
2026 {
2027   HOST_WIDE_INT total_size;
2028   HOST_WIDE_INT spill_size = 0;
2029   HOST_WIDE_INT extra_spill_size = 0;
2030   HOST_WIDE_INT pretend_args_size;
2031   HARD_REG_SET mask;
2032   int n_spilled = 0;
2033   int spilled_gr_p = 0;
2034   int spilled_fr_p = 0;
2035   unsigned int regno;
2036   int i;
2037
2038   if (current_frame_info.initialized)
2039     return;
2040
2041   memset (&current_frame_info, 0, sizeof current_frame_info);
2042   CLEAR_HARD_REG_SET (mask);
2043
2044   /* Don't allocate scratches to the return register.  */
2045   diddle_return_value (mark_reg_gr_used_mask, NULL);
2046
2047   /* Don't allocate scratches to the EH scratch registers.  */
2048   if (cfun->machine->ia64_eh_epilogue_sp)
2049     mark_reg_gr_used_mask (cfun->machine->ia64_eh_epilogue_sp, NULL);
2050   if (cfun->machine->ia64_eh_epilogue_bsp)
2051     mark_reg_gr_used_mask (cfun->machine->ia64_eh_epilogue_bsp, NULL);
2052
2053   /* Find the size of the register stack frame.  We have only 80 local
2054      registers, because we reserve 8 for the inputs and 8 for the
2055      outputs.  */
2056
2057   /* Skip HARD_FRAME_POINTER_REGNUM (loc79) when frame_pointer_needed,
2058      since we'll be adjusting that down later.  */
2059   regno = LOC_REG (78) + ! frame_pointer_needed;
2060   for (; regno >= LOC_REG (0); regno--)
2061     if (regs_ever_live[regno])
2062       break;
2063   current_frame_info.n_local_regs = regno - LOC_REG (0) + 1;
2064
2065   /* For functions marked with the syscall_linkage attribute, we must mark
2066      all eight input registers as in use, so that locals aren't visible to
2067      the caller.  */
2068
2069   if (cfun->machine->n_varargs > 0
2070       || lookup_attribute ("syscall_linkage",
2071                            TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))))
2072     current_frame_info.n_input_regs = 8;
2073   else
2074     {
2075       for (regno = IN_REG (7); regno >= IN_REG (0); regno--)
2076         if (regs_ever_live[regno])
2077           break;
2078       current_frame_info.n_input_regs = regno - IN_REG (0) + 1;
2079     }
2080
2081   for (regno = OUT_REG (7); regno >= OUT_REG (0); regno--)
2082     if (regs_ever_live[regno])
2083       break;
2084   i = regno - OUT_REG (0) + 1;
2085
2086   /* When -p profiling, we need one output register for the mcount argument.
2087      Likewise for -a profiling for the bb_init_func argument.  For -ax
2088      profiling, we need two output registers for the two bb_init_trace_func
2089      arguments.  */
2090   if (current_function_profile)
2091     i = MAX (i, 1);
2092   current_frame_info.n_output_regs = i;
2093
2094   /* ??? No rotating register support yet.  */
2095   current_frame_info.n_rotate_regs = 0;
2096
2097   /* Discover which registers need spilling, and how much room that
2098      will take.  Begin with floating point and general registers,
2099      which will always wind up on the stack.  */
2100
2101   for (regno = FR_REG (2); regno <= FR_REG (127); regno++)
2102     if (regs_ever_live[regno] && ! call_used_regs[regno])
2103       {
2104         SET_HARD_REG_BIT (mask, regno);
2105         spill_size += 16;
2106         n_spilled += 1;
2107         spilled_fr_p = 1;
2108       }
2109
2110   for (regno = GR_REG (1); regno <= GR_REG (31); regno++)
2111     if (regs_ever_live[regno] && ! call_used_regs[regno])
2112       {
2113         SET_HARD_REG_BIT (mask, regno);
2114         spill_size += 8;
2115         n_spilled += 1;
2116         spilled_gr_p = 1;
2117       }
2118
2119   for (regno = BR_REG (1); regno <= BR_REG (7); regno++)
2120     if (regs_ever_live[regno] && ! call_used_regs[regno])
2121       {
2122         SET_HARD_REG_BIT (mask, regno);
2123         spill_size += 8;
2124         n_spilled += 1;
2125       }
2126
2127   /* Now come all special registers that might get saved in other
2128      general registers.  */
2129
2130   if (frame_pointer_needed)
2131     {
2132       current_frame_info.reg_fp = find_gr_spill (1);
2133       /* If we did not get a register, then we take LOC79.  This is guaranteed
2134          to be free, even if regs_ever_live is already set, because this is
2135          HARD_FRAME_POINTER_REGNUM.  This requires incrementing n_local_regs,
2136          as we don't count loc79 above.  */
2137       if (current_frame_info.reg_fp == 0)
2138         {
2139           current_frame_info.reg_fp = LOC_REG (79);
2140           current_frame_info.n_local_regs++;
2141         }
2142     }
2143
2144   if (! current_function_is_leaf)
2145     {
2146       /* Emit a save of BR0 if we call other functions.  Do this even
2147          if this function doesn't return, as EH depends on this to be
2148          able to unwind the stack.  */
2149       SET_HARD_REG_BIT (mask, BR_REG (0));
2150
2151       current_frame_info.reg_save_b0 = find_gr_spill (1);
2152       if (current_frame_info.reg_save_b0 == 0)
2153         {
2154           spill_size += 8;
2155           n_spilled += 1;
2156         }
2157
2158       /* Similarly for ar.pfs.  */
2159       SET_HARD_REG_BIT (mask, AR_PFS_REGNUM);
2160       current_frame_info.reg_save_ar_pfs = find_gr_spill (1);
2161       if (current_frame_info.reg_save_ar_pfs == 0)
2162         {
2163           extra_spill_size += 8;
2164           n_spilled += 1;
2165         }
2166
2167       /* Similarly for gp.  Note that if we're calling setjmp, the stacked
2168          registers are clobbered, so we fall back to the stack.  */
2169       current_frame_info.reg_save_gp
2170         = (current_function_calls_setjmp ? 0 : find_gr_spill (1));
2171       if (current_frame_info.reg_save_gp == 0)
2172         {
2173           SET_HARD_REG_BIT (mask, GR_REG (1));
2174           spill_size += 8;
2175           n_spilled += 1;
2176         }
2177     }
2178   else
2179     {
2180       if (regs_ever_live[BR_REG (0)] && ! call_used_regs[BR_REG (0)])
2181         {
2182           SET_HARD_REG_BIT (mask, BR_REG (0));
2183           spill_size += 8;
2184           n_spilled += 1;
2185         }
2186
2187       if (regs_ever_live[AR_PFS_REGNUM])
2188         {
2189           SET_HARD_REG_BIT (mask, AR_PFS_REGNUM);
2190           current_frame_info.reg_save_ar_pfs = find_gr_spill (1);
2191           if (current_frame_info.reg_save_ar_pfs == 0)
2192             {
2193               extra_spill_size += 8;
2194               n_spilled += 1;
2195             }
2196         }
2197     }
2198
2199   /* Unwind descriptor hackery: things are most efficient if we allocate
2200      consecutive GR save registers for RP, PFS, FP in that order. However,
2201      it is absolutely critical that FP get the only hard register that's
2202      guaranteed to be free, so we allocated it first.  If all three did
2203      happen to be allocated hard regs, and are consecutive, rearrange them
2204      into the preferred order now.  */
2205   if (current_frame_info.reg_fp != 0
2206       && current_frame_info.reg_save_b0 == current_frame_info.reg_fp + 1
2207       && current_frame_info.reg_save_ar_pfs == current_frame_info.reg_fp + 2)
2208     {
2209       current_frame_info.reg_save_b0 = current_frame_info.reg_fp;
2210       current_frame_info.reg_save_ar_pfs = current_frame_info.reg_fp + 1;
2211       current_frame_info.reg_fp = current_frame_info.reg_fp + 2;
2212     }
2213
2214   /* See if we need to store the predicate register block.  */
2215   for (regno = PR_REG (0); regno <= PR_REG (63); regno++)
2216     if (regs_ever_live[regno] && ! call_used_regs[regno])
2217       break;
2218   if (regno <= PR_REG (63))
2219     {
2220       SET_HARD_REG_BIT (mask, PR_REG (0));
2221       current_frame_info.reg_save_pr = find_gr_spill (1);
2222       if (current_frame_info.reg_save_pr == 0)
2223         {
2224           extra_spill_size += 8;
2225           n_spilled += 1;
2226         }
2227
2228       /* ??? Mark them all as used so that register renaming and such
2229          are free to use them.  */
2230       for (regno = PR_REG (0); regno <= PR_REG (63); regno++)
2231         regs_ever_live[regno] = 1;
2232     }
2233
2234   /* If we're forced to use st8.spill, we're forced to save and restore
2235      ar.unat as well.  The check for existing liveness allows inline asm
2236      to touch ar.unat.  */
2237   if (spilled_gr_p || cfun->machine->n_varargs
2238       || regs_ever_live[AR_UNAT_REGNUM])
2239     {
2240       regs_ever_live[AR_UNAT_REGNUM] = 1;
2241       SET_HARD_REG_BIT (mask, AR_UNAT_REGNUM);
2242       current_frame_info.reg_save_ar_unat = find_gr_spill (spill_size == 0);
2243       if (current_frame_info.reg_save_ar_unat == 0)
2244         {
2245           extra_spill_size += 8;
2246           n_spilled += 1;
2247         }
2248     }
2249
2250   if (regs_ever_live[AR_LC_REGNUM])
2251     {
2252       SET_HARD_REG_BIT (mask, AR_LC_REGNUM);
2253       current_frame_info.reg_save_ar_lc = find_gr_spill (spill_size == 0);
2254       if (current_frame_info.reg_save_ar_lc == 0)
2255         {
2256           extra_spill_size += 8;
2257           n_spilled += 1;
2258         }
2259     }
2260
2261   /* If we have an odd number of words of pretend arguments written to
2262      the stack, then the FR save area will be unaligned.  We round the
2263      size of this area up to keep things 16 byte aligned.  */
2264   if (spilled_fr_p)
2265     pretend_args_size = IA64_STACK_ALIGN (current_function_pretend_args_size);
2266   else
2267     pretend_args_size = current_function_pretend_args_size;
2268
2269   total_size = (spill_size + extra_spill_size + size + pretend_args_size
2270                 + current_function_outgoing_args_size);
2271   total_size = IA64_STACK_ALIGN (total_size);
2272
2273   /* We always use the 16-byte scratch area provided by the caller, but
2274      if we are a leaf function, there's no one to which we need to provide
2275      a scratch area.  */
2276   if (current_function_is_leaf)
2277     total_size = MAX (0, total_size - 16);
2278
2279   current_frame_info.total_size = total_size;
2280   current_frame_info.spill_cfa_off = pretend_args_size - 16;
2281   current_frame_info.spill_size = spill_size;
2282   current_frame_info.extra_spill_size = extra_spill_size;
2283   COPY_HARD_REG_SET (current_frame_info.mask, mask);
2284   current_frame_info.n_spilled = n_spilled;
2285   current_frame_info.initialized = reload_completed;
2286 }
2287
2288 /* Compute the initial difference between the specified pair of registers.  */
2289
2290 HOST_WIDE_INT
2291 ia64_initial_elimination_offset (int from, int to)
2292 {
2293   HOST_WIDE_INT offset;
2294
2295   ia64_compute_frame_size (get_frame_size ());
2296   switch (from)
2297     {
2298     case FRAME_POINTER_REGNUM:
2299       if (to == HARD_FRAME_POINTER_REGNUM)
2300         {
2301           if (current_function_is_leaf)
2302             offset = -current_frame_info.total_size;
2303           else
2304             offset = -(current_frame_info.total_size
2305                        - current_function_outgoing_args_size - 16);
2306         }
2307       else if (to == STACK_POINTER_REGNUM)
2308         {
2309           if (current_function_is_leaf)
2310             offset = 0;
2311           else
2312             offset = 16 + current_function_outgoing_args_size;
2313         }
2314       else
2315         abort ();
2316       break;
2317
2318     case ARG_POINTER_REGNUM:
2319       /* Arguments start above the 16 byte save area, unless stdarg
2320          in which case we store through the 16 byte save area.  */
2321       if (to == HARD_FRAME_POINTER_REGNUM)
2322         offset = 16 - current_function_pretend_args_size;
2323       else if (to == STACK_POINTER_REGNUM)
2324         offset = (current_frame_info.total_size
2325                   + 16 - current_function_pretend_args_size);
2326       else
2327         abort ();
2328       break;
2329
2330     default:
2331       abort ();
2332     }
2333
2334   return offset;
2335 }
2336
2337 /* If there are more than a trivial number of register spills, we use
2338    two interleaved iterators so that we can get two memory references
2339    per insn group.
2340
2341    In order to simplify things in the prologue and epilogue expanders,
2342    we use helper functions to fix up the memory references after the
2343    fact with the appropriate offsets to a POST_MODIFY memory mode.
2344    The following data structure tracks the state of the two iterators
2345    while insns are being emitted.  */
2346
2347 struct spill_fill_data
2348 {
2349   rtx init_after;               /* point at which to emit initializations */
2350   rtx init_reg[2];              /* initial base register */
2351   rtx iter_reg[2];              /* the iterator registers */
2352   rtx *prev_addr[2];            /* address of last memory use */
2353   rtx prev_insn[2];             /* the insn corresponding to prev_addr */
2354   HOST_WIDE_INT prev_off[2];    /* last offset */
2355   int n_iter;                   /* number of iterators in use */
2356   int next_iter;                /* next iterator to use */
2357   unsigned int save_gr_used_mask;
2358 };
2359
2360 static struct spill_fill_data spill_fill_data;
2361
2362 static void
2363 setup_spill_pointers (int n_spills, rtx init_reg, HOST_WIDE_INT cfa_off)
2364 {
2365   int i;
2366
2367   spill_fill_data.init_after = get_last_insn ();
2368   spill_fill_data.init_reg[0] = init_reg;
2369   spill_fill_data.init_reg[1] = init_reg;
2370   spill_fill_data.prev_addr[0] = NULL;
2371   spill_fill_data.prev_addr[1] = NULL;
2372   spill_fill_data.prev_insn[0] = NULL;
2373   spill_fill_data.prev_insn[1] = NULL;
2374   spill_fill_data.prev_off[0] = cfa_off;
2375   spill_fill_data.prev_off[1] = cfa_off;
2376   spill_fill_data.next_iter = 0;
2377   spill_fill_data.save_gr_used_mask = current_frame_info.gr_used_mask;
2378
2379   spill_fill_data.n_iter = 1 + (n_spills > 2);
2380   for (i = 0; i < spill_fill_data.n_iter; ++i)
2381     {
2382       int regno = next_scratch_gr_reg ();
2383       spill_fill_data.iter_reg[i] = gen_rtx_REG (DImode, regno);
2384       current_frame_info.gr_used_mask |= 1 << regno;
2385     }
2386 }
2387
2388 static void
2389 finish_spill_pointers (void)
2390 {
2391   current_frame_info.gr_used_mask = spill_fill_data.save_gr_used_mask;
2392 }
2393
2394 static rtx
2395 spill_restore_mem (rtx reg, HOST_WIDE_INT cfa_off)
2396 {
2397   int iter = spill_fill_data.next_iter;
2398   HOST_WIDE_INT disp = spill_fill_data.prev_off[iter] - cfa_off;
2399   rtx disp_rtx = GEN_INT (disp);
2400   rtx mem;
2401
2402   if (spill_fill_data.prev_addr[iter])
2403     {
2404       if (CONST_OK_FOR_N (disp))
2405         {
2406           *spill_fill_data.prev_addr[iter]
2407             = gen_rtx_POST_MODIFY (DImode, spill_fill_data.iter_reg[iter],
2408                                    gen_rtx_PLUS (DImode,
2409                                                  spill_fill_data.iter_reg[iter],
2410                                                  disp_rtx));
2411           REG_NOTES (spill_fill_data.prev_insn[iter])
2412             = gen_rtx_EXPR_LIST (REG_INC, spill_fill_data.iter_reg[iter],
2413                                  REG_NOTES (spill_fill_data.prev_insn[iter]));
2414         }
2415       else
2416         {
2417           /* ??? Could use register post_modify for loads.  */
2418           if (! CONST_OK_FOR_I (disp))
2419             {
2420               rtx tmp = gen_rtx_REG (DImode, next_scratch_gr_reg ());
2421               emit_move_insn (tmp, disp_rtx);
2422               disp_rtx = tmp;
2423             }
2424           emit_insn (gen_adddi3 (spill_fill_data.iter_reg[iter],
2425                                  spill_fill_data.iter_reg[iter], disp_rtx));
2426         }
2427     }
2428   /* Micro-optimization: if we've created a frame pointer, it's at
2429      CFA 0, which may allow the real iterator to be initialized lower,
2430      slightly increasing parallelism.  Also, if there are few saves
2431      it may eliminate the iterator entirely.  */
2432   else if (disp == 0
2433            && spill_fill_data.init_reg[iter] == stack_pointer_rtx
2434            && frame_pointer_needed)
2435     {
2436       mem = gen_rtx_MEM (GET_MODE (reg), hard_frame_pointer_rtx);
2437       set_mem_alias_set (mem, get_varargs_alias_set ());
2438       return mem;
2439     }
2440   else
2441     {
2442       rtx seq, insn;
2443
2444       if (disp == 0)
2445         seq = gen_movdi (spill_fill_data.iter_reg[iter],
2446                          spill_fill_data.init_reg[iter]);
2447       else
2448         {
2449           start_sequence ();
2450
2451           if (! CONST_OK_FOR_I (disp))
2452             {
2453               rtx tmp = gen_rtx_REG (DImode, next_scratch_gr_reg ());
2454               emit_move_insn (tmp, disp_rtx);
2455               disp_rtx = tmp;
2456             }
2457
2458           emit_insn (gen_adddi3 (spill_fill_data.iter_reg[iter],
2459                                  spill_fill_data.init_reg[iter],
2460                                  disp_rtx));
2461
2462           seq = get_insns ();
2463           end_sequence ();
2464         }
2465
2466       /* Careful for being the first insn in a sequence.  */
2467       if (spill_fill_data.init_after)
2468         insn = emit_insn_after (seq, spill_fill_data.init_after);
2469       else
2470         {
2471           rtx first = get_insns ();
2472           if (first)
2473             insn = emit_insn_before (seq, first);
2474           else
2475             insn = emit_insn (seq);
2476         }
2477       spill_fill_data.init_after = insn;
2478
2479       /* If DISP is 0, we may or may not have a further adjustment
2480          afterward.  If we do, then the load/store insn may be modified
2481          to be a post-modify.  If we don't, then this copy may be
2482          eliminated by copyprop_hardreg_forward, which makes this
2483          insn garbage, which runs afoul of the sanity check in
2484          propagate_one_insn.  So mark this insn as legal to delete.  */
2485       if (disp == 0)
2486         REG_NOTES(insn) = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD, const0_rtx,
2487                                              REG_NOTES (insn));
2488     }
2489
2490   mem = gen_rtx_MEM (GET_MODE (reg), spill_fill_data.iter_reg[iter]);
2491
2492   /* ??? Not all of the spills are for varargs, but some of them are.
2493      The rest of the spills belong in an alias set of their own.  But
2494      it doesn't actually hurt to include them here.  */
2495   set_mem_alias_set (mem, get_varargs_alias_set ());
2496
2497   spill_fill_data.prev_addr[iter] = &XEXP (mem, 0);
2498   spill_fill_data.prev_off[iter] = cfa_off;
2499
2500   if (++iter >= spill_fill_data.n_iter)
2501     iter = 0;
2502   spill_fill_data.next_iter = iter;
2503
2504   return mem;
2505 }
2506
2507 static void
2508 do_spill (rtx (*move_fn) (rtx, rtx, rtx), rtx reg, HOST_WIDE_INT cfa_off,
2509           rtx frame_reg)
2510 {
2511   int iter = spill_fill_data.next_iter;
2512   rtx mem, insn;
2513
2514   mem = spill_restore_mem (reg, cfa_off);
2515   insn = emit_insn ((*move_fn) (mem, reg, GEN_INT (cfa_off)));
2516   spill_fill_data.prev_insn[iter] = insn;
2517
2518   if (frame_reg)
2519     {
2520       rtx base;
2521       HOST_WIDE_INT off;
2522
2523       RTX_FRAME_RELATED_P (insn) = 1;
2524
2525       /* Don't even pretend that the unwind code can intuit its way
2526          through a pair of interleaved post_modify iterators.  Just
2527          provide the correct answer.  */
2528
2529       if (frame_pointer_needed)
2530         {
2531           base = hard_frame_pointer_rtx;
2532           off = - cfa_off;
2533         }
2534       else
2535         {
2536           base = stack_pointer_rtx;
2537           off = current_frame_info.total_size - cfa_off;
2538         }
2539
2540       REG_NOTES (insn)
2541         = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
2542                 gen_rtx_SET (VOIDmode,
2543                              gen_rtx_MEM (GET_MODE (reg),
2544                                           plus_constant (base, off)),
2545                              frame_reg),
2546                 REG_NOTES (insn));
2547     }
2548 }
2549
2550 static void
2551 do_restore (rtx (*move_fn) (rtx, rtx, rtx), rtx reg, HOST_WIDE_INT cfa_off)
2552 {
2553   int iter = spill_fill_data.next_iter;
2554   rtx insn;
2555
2556   insn = emit_insn ((*move_fn) (reg, spill_restore_mem (reg, cfa_off),
2557                                 GEN_INT (cfa_off)));
2558   spill_fill_data.prev_insn[iter] = insn;
2559 }
2560
2561 /* Wrapper functions that discards the CONST_INT spill offset.  These
2562    exist so that we can give gr_spill/gr_fill the offset they need and
2563    use a consistent function interface.  */
2564
2565 static rtx
2566 gen_movdi_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
2567 {
2568   return gen_movdi (dest, src);
2569 }
2570
2571 static rtx
2572 gen_fr_spill_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
2573 {
2574   return gen_fr_spill (dest, src);
2575 }
2576
2577 static rtx
2578 gen_fr_restore_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
2579 {
2580   return gen_fr_restore (dest, src);
2581 }
2582
2583 /* Called after register allocation to add any instructions needed for the
2584    prologue.  Using a prologue insn is favored compared to putting all of the
2585    instructions in output_function_prologue(), since it allows the scheduler
2586    to intermix instructions with the saves of the caller saved registers.  In
2587    some cases, it might be necessary to emit a barrier instruction as the last
2588    insn to prevent such scheduling.
2589
2590    Also any insns generated here should have RTX_FRAME_RELATED_P(insn) = 1
2591    so that the debug info generation code can handle them properly.
2592
2593    The register save area is layed out like so:
2594    cfa+16
2595         [ varargs spill area ]
2596         [ fr register spill area ]
2597         [ br register spill area ]
2598         [ ar register spill area ]
2599         [ pr register spill area ]
2600         [ gr register spill area ] */
2601
2602 /* ??? Get inefficient code when the frame size is larger than can fit in an
2603    adds instruction.  */
2604
2605 void
2606 ia64_expand_prologue (void)
2607 {
2608   rtx insn, ar_pfs_save_reg, ar_unat_save_reg;
2609   int i, epilogue_p, regno, alt_regno, cfa_off, n_varargs;
2610   rtx reg, alt_reg;
2611
2612   ia64_compute_frame_size (get_frame_size ());
2613   last_scratch_gr_reg = 15;
2614
2615   /* If there is no epilogue, then we don't need some prologue insns.
2616      We need to avoid emitting the dead prologue insns, because flow
2617      will complain about them.  */
2618   if (optimize)
2619     {
2620       edge e;
2621
2622       for (e = EXIT_BLOCK_PTR->pred; e ; e = e->pred_next)
2623         if ((e->flags & EDGE_FAKE) == 0
2624             && (e->flags & EDGE_FALLTHRU) != 0)
2625           break;
2626       epilogue_p = (e != NULL);
2627     }
2628   else
2629     epilogue_p = 1;
2630
2631   /* Set the local, input, and output register names.  We need to do this
2632      for GNU libc, which creates crti.S/crtn.S by splitting initfini.c in
2633      half.  If we use in/loc/out register names, then we get assembler errors
2634      in crtn.S because there is no alloc insn or regstk directive in there.  */
2635   if (! TARGET_REG_NAMES)
2636     {
2637       int inputs = current_frame_info.n_input_regs;
2638       int locals = current_frame_info.n_local_regs;
2639       int outputs = current_frame_info.n_output_regs;
2640
2641       for (i = 0; i < inputs; i++)
2642         reg_names[IN_REG (i)] = ia64_reg_numbers[i];
2643       for (i = 0; i < locals; i++)
2644         reg_names[LOC_REG (i)] = ia64_reg_numbers[inputs + i];
2645       for (i = 0; i < outputs; i++)
2646         reg_names[OUT_REG (i)] = ia64_reg_numbers[inputs + locals + i];
2647     }
2648
2649   /* Set the frame pointer register name.  The regnum is logically loc79,
2650      but of course we'll not have allocated that many locals.  Rather than
2651      worrying about renumbering the existing rtxs, we adjust the name.  */
2652   /* ??? This code means that we can never use one local register when
2653      there is a frame pointer.  loc79 gets wasted in this case, as it is
2654      renamed to a register that will never be used.  See also the try_locals
2655      code in find_gr_spill.  */
2656   if (current_frame_info.reg_fp)
2657     {
2658       const char *tmp = reg_names[HARD_FRAME_POINTER_REGNUM];
2659       reg_names[HARD_FRAME_POINTER_REGNUM]
2660         = reg_names[current_frame_info.reg_fp];
2661       reg_names[current_frame_info.reg_fp] = tmp;
2662     }
2663
2664   /* We don't need an alloc instruction if we've used no outputs or locals.  */
2665   if (current_frame_info.n_local_regs == 0
2666       && current_frame_info.n_output_regs == 0
2667       && current_frame_info.n_input_regs <= current_function_args_info.int_regs
2668       && !TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM))
2669     {
2670       /* If there is no alloc, but there are input registers used, then we
2671          need a .regstk directive.  */
2672       current_frame_info.need_regstk = (TARGET_REG_NAMES != 0);
2673       ar_pfs_save_reg = NULL_RTX;
2674     }
2675   else
2676     {
2677       current_frame_info.need_regstk = 0;
2678
2679       if (current_frame_info.reg_save_ar_pfs)
2680         regno = current_frame_info.reg_save_ar_pfs;
2681       else
2682         regno = next_scratch_gr_reg ();
2683       ar_pfs_save_reg = gen_rtx_REG (DImode, regno);
2684
2685       insn = emit_insn (gen_alloc (ar_pfs_save_reg,
2686                                    GEN_INT (current_frame_info.n_input_regs),
2687                                    GEN_INT (current_frame_info.n_local_regs),
2688                                    GEN_INT (current_frame_info.n_output_regs),
2689                                    GEN_INT (current_frame_info.n_rotate_regs)));
2690       RTX_FRAME_RELATED_P (insn) = (current_frame_info.reg_save_ar_pfs != 0);
2691     }
2692
2693   /* Set up frame pointer, stack pointer, and spill iterators.  */
2694
2695   n_varargs = cfun->machine->n_varargs;
2696   setup_spill_pointers (current_frame_info.n_spilled + n_varargs,
2697                         stack_pointer_rtx, 0);
2698
2699   if (frame_pointer_needed)
2700     {
2701       insn = emit_move_insn (hard_frame_pointer_rtx, stack_pointer_rtx);
2702       RTX_FRAME_RELATED_P (insn) = 1;
2703     }
2704
2705   if (current_frame_info.total_size != 0)
2706     {
2707       rtx frame_size_rtx = GEN_INT (- current_frame_info.total_size);
2708       rtx offset;
2709
2710       if (CONST_OK_FOR_I (- current_frame_info.total_size))
2711         offset = frame_size_rtx;
2712       else
2713         {
2714           regno = next_scratch_gr_reg ();
2715           offset = gen_rtx_REG (DImode, regno);
2716           emit_move_insn (offset, frame_size_rtx);
2717         }
2718
2719       insn = emit_insn (gen_adddi3 (stack_pointer_rtx,
2720                                     stack_pointer_rtx, offset));
2721
2722       if (! frame_pointer_needed)
2723         {
2724           RTX_FRAME_RELATED_P (insn) = 1;
2725           if (GET_CODE (offset) != CONST_INT)
2726             {
2727               REG_NOTES (insn)
2728                 = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
2729                         gen_rtx_SET (VOIDmode,
2730                                      stack_pointer_rtx,
2731                                      gen_rtx_PLUS (DImode,
2732                                                    stack_pointer_rtx,
2733                                                    frame_size_rtx)),
2734                         REG_NOTES (insn));
2735             }
2736         }
2737
2738       /* ??? At this point we must generate a magic insn that appears to
2739          modify the stack pointer, the frame pointer, and all spill
2740          iterators.  This would allow the most scheduling freedom.  For
2741          now, just hard stop.  */
2742       emit_insn (gen_blockage ());
2743     }
2744
2745   /* Must copy out ar.unat before doing any integer spills.  */
2746   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
2747     {
2748       if (current_frame_info.reg_save_ar_unat)
2749         ar_unat_save_reg
2750           = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_unat);
2751       else
2752         {
2753           alt_regno = next_scratch_gr_reg ();
2754           ar_unat_save_reg = gen_rtx_REG (DImode, alt_regno);
2755           current_frame_info.gr_used_mask |= 1 << alt_regno;
2756         }
2757
2758       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
2759       insn = emit_move_insn (ar_unat_save_reg, reg);
2760       RTX_FRAME_RELATED_P (insn) = (current_frame_info.reg_save_ar_unat != 0);
2761
2762       /* Even if we're not going to generate an epilogue, we still
2763          need to save the register so that EH works.  */
2764       if (! epilogue_p && current_frame_info.reg_save_ar_unat)
2765         emit_insn (gen_prologue_use (ar_unat_save_reg));
2766     }
2767   else
2768     ar_unat_save_reg = NULL_RTX;
2769
2770   /* Spill all varargs registers.  Do this before spilling any GR registers,
2771      since we want the UNAT bits for the GR registers to override the UNAT
2772      bits from varargs, which we don't care about.  */
2773
2774   cfa_off = -16;
2775   for (regno = GR_ARG_FIRST + 7; n_varargs > 0; --n_varargs, --regno)
2776     {
2777       reg = gen_rtx_REG (DImode, regno);
2778       do_spill (gen_gr_spill, reg, cfa_off += 8, NULL_RTX);
2779     }
2780
2781   /* Locate the bottom of the register save area.  */
2782   cfa_off = (current_frame_info.spill_cfa_off
2783              + current_frame_info.spill_size
2784              + current_frame_info.extra_spill_size);
2785
2786   /* Save the predicate register block either in a register or in memory.  */
2787   if (TEST_HARD_REG_BIT (current_frame_info.mask, PR_REG (0)))
2788     {
2789       reg = gen_rtx_REG (DImode, PR_REG (0));
2790       if (current_frame_info.reg_save_pr != 0)
2791         {
2792           alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_pr);
2793           insn = emit_move_insn (alt_reg, reg);
2794
2795           /* ??? Denote pr spill/fill by a DImode move that modifies all
2796              64 hard registers.  */
2797           RTX_FRAME_RELATED_P (insn) = 1;
2798           REG_NOTES (insn)
2799             = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
2800                         gen_rtx_SET (VOIDmode, alt_reg, reg),
2801                         REG_NOTES (insn));
2802
2803           /* Even if we're not going to generate an epilogue, we still
2804              need to save the register so that EH works.  */
2805           if (! epilogue_p)
2806             emit_insn (gen_prologue_use (alt_reg));
2807         }
2808       else
2809         {
2810           alt_regno = next_scratch_gr_reg ();
2811           alt_reg = gen_rtx_REG (DImode, alt_regno);
2812           insn = emit_move_insn (alt_reg, reg);
2813           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
2814           cfa_off -= 8;
2815         }
2816     }
2817
2818   /* Handle AR regs in numerical order.  All of them get special handling.  */
2819   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM)
2820       && current_frame_info.reg_save_ar_unat == 0)
2821     {
2822       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
2823       do_spill (gen_movdi_x, ar_unat_save_reg, cfa_off, reg);
2824       cfa_off -= 8;
2825     }
2826
2827   /* The alloc insn already copied ar.pfs into a general register.  The
2828      only thing we have to do now is copy that register to a stack slot
2829      if we'd not allocated a local register for the job.  */
2830   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM)
2831       && current_frame_info.reg_save_ar_pfs == 0)
2832     {
2833       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
2834       do_spill (gen_movdi_x, ar_pfs_save_reg, cfa_off, reg);
2835       cfa_off -= 8;
2836     }
2837
2838   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_LC_REGNUM))
2839     {
2840       reg = gen_rtx_REG (DImode, AR_LC_REGNUM);
2841       if (current_frame_info.reg_save_ar_lc != 0)
2842         {
2843           alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_lc);
2844           insn = emit_move_insn (alt_reg, reg);
2845           RTX_FRAME_RELATED_P (insn) = 1;
2846
2847           /* Even if we're not going to generate an epilogue, we still
2848              need to save the register so that EH works.  */
2849           if (! epilogue_p)
2850             emit_insn (gen_prologue_use (alt_reg));
2851         }
2852       else
2853         {
2854           alt_regno = next_scratch_gr_reg ();
2855           alt_reg = gen_rtx_REG (DImode, alt_regno);
2856           emit_move_insn (alt_reg, reg);
2857           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
2858           cfa_off -= 8;
2859         }
2860     }
2861
2862   if (current_frame_info.reg_save_gp)
2863     {
2864       insn = emit_move_insn (gen_rtx_REG (DImode,
2865                                           current_frame_info.reg_save_gp),
2866                              pic_offset_table_rtx);
2867       /* We don't know for sure yet if this is actually needed, since
2868          we've not split the PIC call patterns.  If all of the calls
2869          are indirect, and not followed by any uses of the gp, then
2870          this save is dead.  Allow it to go away.  */
2871       REG_NOTES (insn)
2872         = gen_rtx_EXPR_LIST (REG_MAYBE_DEAD, const0_rtx, REG_NOTES (insn));
2873     }
2874
2875   /* We should now be at the base of the gr/br/fr spill area.  */
2876   if (cfa_off != (current_frame_info.spill_cfa_off
2877                   + current_frame_info.spill_size))
2878     abort ();
2879
2880   /* Spill all general registers.  */
2881   for (regno = GR_REG (1); regno <= GR_REG (31); ++regno)
2882     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
2883       {
2884         reg = gen_rtx_REG (DImode, regno);
2885         do_spill (gen_gr_spill, reg, cfa_off, reg);
2886         cfa_off -= 8;
2887       }
2888
2889   /* Handle BR0 specially -- it may be getting stored permanently in
2890      some GR register.  */
2891   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
2892     {
2893       reg = gen_rtx_REG (DImode, BR_REG (0));
2894       if (current_frame_info.reg_save_b0 != 0)
2895         {
2896           alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_b0);
2897           insn = emit_move_insn (alt_reg, reg);
2898           RTX_FRAME_RELATED_P (insn) = 1;
2899
2900           /* Even if we're not going to generate an epilogue, we still
2901              need to save the register so that EH works.  */
2902           if (! epilogue_p)
2903             emit_insn (gen_prologue_use (alt_reg));
2904         }
2905       else
2906         {
2907           alt_regno = next_scratch_gr_reg ();
2908           alt_reg = gen_rtx_REG (DImode, alt_regno);
2909           emit_move_insn (alt_reg, reg);
2910           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
2911           cfa_off -= 8;
2912         }
2913     }
2914
2915   /* Spill the rest of the BR registers.  */
2916   for (regno = BR_REG (1); regno <= BR_REG (7); ++regno)
2917     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
2918       {
2919         alt_regno = next_scratch_gr_reg ();
2920         alt_reg = gen_rtx_REG (DImode, alt_regno);
2921         reg = gen_rtx_REG (DImode, regno);
2922         emit_move_insn (alt_reg, reg);
2923         do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
2924         cfa_off -= 8;
2925       }
2926
2927   /* Align the frame and spill all FR registers.  */
2928   for (regno = FR_REG (2); regno <= FR_REG (127); ++regno)
2929     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
2930       {
2931         if (cfa_off & 15)
2932           abort ();
2933         reg = gen_rtx_REG (XFmode, regno);
2934         do_spill (gen_fr_spill_x, reg, cfa_off, reg);
2935         cfa_off -= 16;
2936       }
2937
2938   if (cfa_off != current_frame_info.spill_cfa_off)
2939     abort ();
2940
2941   finish_spill_pointers ();
2942 }
2943
2944 /* Called after register allocation to add any instructions needed for the
2945    epilogue.  Using an epilogue insn is favored compared to putting all of the
2946    instructions in output_function_prologue(), since it allows the scheduler
2947    to intermix instructions with the saves of the caller saved registers.  In
2948    some cases, it might be necessary to emit a barrier instruction as the last
2949    insn to prevent such scheduling.  */
2950
2951 void
2952 ia64_expand_epilogue (int sibcall_p)
2953 {
2954   rtx insn, reg, alt_reg, ar_unat_save_reg;
2955   int regno, alt_regno, cfa_off;
2956
2957   ia64_compute_frame_size (get_frame_size ());
2958
2959   /* If there is a frame pointer, then we use it instead of the stack
2960      pointer, so that the stack pointer does not need to be valid when
2961      the epilogue starts.  See EXIT_IGNORE_STACK.  */
2962   if (frame_pointer_needed)
2963     setup_spill_pointers (current_frame_info.n_spilled,
2964                           hard_frame_pointer_rtx, 0);
2965   else
2966     setup_spill_pointers (current_frame_info.n_spilled, stack_pointer_rtx,
2967                           current_frame_info.total_size);
2968
2969   if (current_frame_info.total_size != 0)
2970     {
2971       /* ??? At this point we must generate a magic insn that appears to
2972          modify the spill iterators and the frame pointer.  This would
2973          allow the most scheduling freedom.  For now, just hard stop.  */
2974       emit_insn (gen_blockage ());
2975     }
2976
2977   /* Locate the bottom of the register save area.  */
2978   cfa_off = (current_frame_info.spill_cfa_off
2979              + current_frame_info.spill_size
2980              + current_frame_info.extra_spill_size);
2981
2982   /* Restore the predicate registers.  */
2983   if (TEST_HARD_REG_BIT (current_frame_info.mask, PR_REG (0)))
2984     {
2985       if (current_frame_info.reg_save_pr != 0)
2986         alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_pr);
2987       else
2988         {
2989           alt_regno = next_scratch_gr_reg ();
2990           alt_reg = gen_rtx_REG (DImode, alt_regno);
2991           do_restore (gen_movdi_x, alt_reg, cfa_off);
2992           cfa_off -= 8;
2993         }
2994       reg = gen_rtx_REG (DImode, PR_REG (0));
2995       emit_move_insn (reg, alt_reg);
2996     }
2997
2998   /* Restore the application registers.  */
2999
3000   /* Load the saved unat from the stack, but do not restore it until
3001      after the GRs have been restored.  */
3002   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
3003     {
3004       if (current_frame_info.reg_save_ar_unat != 0)
3005         ar_unat_save_reg
3006           = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_unat);
3007       else
3008         {
3009           alt_regno = next_scratch_gr_reg ();
3010           ar_unat_save_reg = gen_rtx_REG (DImode, alt_regno);
3011           current_frame_info.gr_used_mask |= 1 << alt_regno;
3012           do_restore (gen_movdi_x, ar_unat_save_reg, cfa_off);
3013           cfa_off -= 8;
3014         }
3015     }
3016   else
3017     ar_unat_save_reg = NULL_RTX;
3018
3019   if (current_frame_info.reg_save_ar_pfs != 0)
3020     {
3021       alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_pfs);
3022       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
3023       emit_move_insn (reg, alt_reg);
3024     }
3025   else if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM))
3026     {
3027       alt_regno = next_scratch_gr_reg ();
3028       alt_reg = gen_rtx_REG (DImode, alt_regno);
3029       do_restore (gen_movdi_x, alt_reg, cfa_off);
3030       cfa_off -= 8;
3031       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
3032       emit_move_insn (reg, alt_reg);
3033     }
3034
3035   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_LC_REGNUM))
3036     {
3037       if (current_frame_info.reg_save_ar_lc != 0)
3038         alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_ar_lc);
3039       else
3040         {
3041           alt_regno = next_scratch_gr_reg ();
3042           alt_reg = gen_rtx_REG (DImode, alt_regno);
3043           do_restore (gen_movdi_x, alt_reg, cfa_off);
3044           cfa_off -= 8;
3045         }
3046       reg = gen_rtx_REG (DImode, AR_LC_REGNUM);
3047       emit_move_insn (reg, alt_reg);
3048     }
3049
3050   /* We should now be at the base of the gr/br/fr spill area.  */
3051   if (cfa_off != (current_frame_info.spill_cfa_off
3052                   + current_frame_info.spill_size))
3053     abort ();
3054
3055   /* The GP may be stored on the stack in the prologue, but it's
3056      never restored in the epilogue.  Skip the stack slot.  */
3057   if (TEST_HARD_REG_BIT (current_frame_info.mask, GR_REG (1)))
3058     cfa_off -= 8;
3059
3060   /* Restore all general registers.  */
3061   for (regno = GR_REG (2); regno <= GR_REG (31); ++regno)
3062     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3063       {
3064         reg = gen_rtx_REG (DImode, regno);
3065         do_restore (gen_gr_restore, reg, cfa_off);
3066         cfa_off -= 8;
3067       }
3068
3069   /* Restore the branch registers.  Handle B0 specially, as it may
3070      have gotten stored in some GR register.  */
3071   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
3072     {
3073       if (current_frame_info.reg_save_b0 != 0)
3074         alt_reg = gen_rtx_REG (DImode, current_frame_info.reg_save_b0);
3075       else
3076         {
3077           alt_regno = next_scratch_gr_reg ();
3078           alt_reg = gen_rtx_REG (DImode, alt_regno);
3079           do_restore (gen_movdi_x, alt_reg, cfa_off);
3080           cfa_off -= 8;
3081         }
3082       reg = gen_rtx_REG (DImode, BR_REG (0));
3083       emit_move_insn (reg, alt_reg);
3084     }
3085
3086   for (regno = BR_REG (1); regno <= BR_REG (7); ++regno)
3087     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3088       {
3089         alt_regno = next_scratch_gr_reg ();
3090         alt_reg = gen_rtx_REG (DImode, alt_regno);
3091         do_restore (gen_movdi_x, alt_reg, cfa_off);
3092         cfa_off -= 8;
3093         reg = gen_rtx_REG (DImode, regno);
3094         emit_move_insn (reg, alt_reg);
3095       }
3096
3097   /* Restore floating point registers.  */
3098   for (regno = FR_REG (2); regno <= FR_REG (127); ++regno)
3099     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3100       {
3101         if (cfa_off & 15)
3102           abort ();
3103         reg = gen_rtx_REG (XFmode, regno);
3104         do_restore (gen_fr_restore_x, reg, cfa_off);
3105         cfa_off -= 16;
3106       }
3107
3108   /* Restore ar.unat for real.  */
3109   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
3110     {
3111       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
3112       emit_move_insn (reg, ar_unat_save_reg);
3113     }
3114
3115   if (cfa_off != current_frame_info.spill_cfa_off)
3116     abort ();
3117
3118   finish_spill_pointers ();
3119
3120   if (current_frame_info.total_size || cfun->machine->ia64_eh_epilogue_sp)
3121     {
3122       /* ??? At this point we must generate a magic insn that appears to
3123          modify the spill iterators, the stack pointer, and the frame
3124          pointer.  This would allow the most scheduling freedom.  For now,
3125          just hard stop.  */
3126       emit_insn (gen_blockage ());
3127     }
3128
3129   if (cfun->machine->ia64_eh_epilogue_sp)
3130     emit_move_insn (stack_pointer_rtx, cfun->machine->ia64_eh_epilogue_sp);
3131   else if (frame_pointer_needed)
3132     {
3133       insn = emit_move_insn (stack_pointer_rtx, hard_frame_pointer_rtx);
3134       RTX_FRAME_RELATED_P (insn) = 1;
3135     }
3136   else if (current_frame_info.total_size)
3137     {
3138       rtx offset, frame_size_rtx;
3139
3140       frame_size_rtx = GEN_INT (current_frame_info.total_size);
3141       if (CONST_OK_FOR_I (current_frame_info.total_size))
3142         offset = frame_size_rtx;
3143       else
3144         {
3145           regno = next_scratch_gr_reg ();
3146           offset = gen_rtx_REG (DImode, regno);
3147           emit_move_insn (offset, frame_size_rtx);
3148         }
3149
3150       insn = emit_insn (gen_adddi3 (stack_pointer_rtx, stack_pointer_rtx,
3151                                     offset));
3152
3153       RTX_FRAME_RELATED_P (insn) = 1;
3154       if (GET_CODE (offset) != CONST_INT)
3155         {
3156           REG_NOTES (insn)
3157             = gen_rtx_EXPR_LIST (REG_FRAME_RELATED_EXPR,
3158                         gen_rtx_SET (VOIDmode,
3159                                      stack_pointer_rtx,
3160                                      gen_rtx_PLUS (DImode,
3161                                                    stack_pointer_rtx,
3162                                                    frame_size_rtx)),
3163                         REG_NOTES (insn));
3164         }
3165     }
3166
3167   if (cfun->machine->ia64_eh_epilogue_bsp)
3168     emit_insn (gen_set_bsp (cfun->machine->ia64_eh_epilogue_bsp));
3169
3170   if (! sibcall_p)
3171     emit_jump_insn (gen_return_internal (gen_rtx_REG (DImode, BR_REG (0))));
3172   else
3173     {
3174       int fp = GR_REG (2);
3175       /* We need a throw away register here, r0 and r1 are reserved, so r2 is the
3176          first available call clobbered register.  If there was a frame_pointer
3177          register, we may have swapped the names of r2 and HARD_FRAME_POINTER_REGNUM,
3178          so we have to make sure we're using the string "r2" when emitting
3179          the register name for the assembler.  */
3180       if (current_frame_info.reg_fp && current_frame_info.reg_fp == GR_REG (2))
3181         fp = HARD_FRAME_POINTER_REGNUM;
3182
3183       /* We must emit an alloc to force the input registers to become output
3184          registers.  Otherwise, if the callee tries to pass its parameters
3185          through to another call without an intervening alloc, then these
3186          values get lost.  */
3187       /* ??? We don't need to preserve all input registers.  We only need to
3188          preserve those input registers used as arguments to the sibling call.
3189          It is unclear how to compute that number here.  */
3190       if (current_frame_info.n_input_regs != 0)
3191         emit_insn (gen_alloc (gen_rtx_REG (DImode, fp),
3192                               const0_rtx, const0_rtx,
3193                               GEN_INT (current_frame_info.n_input_regs),
3194                               const0_rtx));
3195     }
3196 }
3197
3198 /* Return 1 if br.ret can do all the work required to return from a
3199    function.  */
3200
3201 int
3202 ia64_direct_return (void)
3203 {
3204   if (reload_completed && ! frame_pointer_needed)
3205     {
3206       ia64_compute_frame_size (get_frame_size ());
3207
3208       return (current_frame_info.total_size == 0
3209               && current_frame_info.n_spilled == 0
3210               && current_frame_info.reg_save_b0 == 0
3211               && current_frame_info.reg_save_pr == 0
3212               && current_frame_info.reg_save_ar_pfs == 0
3213               && current_frame_info.reg_save_ar_unat == 0
3214               && current_frame_info.reg_save_ar_lc == 0);
3215     }
3216   return 0;
3217 }
3218
3219 /* Return the magic cookie that we use to hold the return address
3220    during early compilation.  */
3221
3222 rtx
3223 ia64_return_addr_rtx (HOST_WIDE_INT count, rtx frame ATTRIBUTE_UNUSED)
3224 {
3225   if (count != 0)
3226     return NULL;
3227   return gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx), UNSPEC_RET_ADDR);
3228 }
3229
3230 /* Split this value after reload, now that we know where the return
3231    address is saved.  */
3232
3233 void
3234 ia64_split_return_addr_rtx (rtx dest)
3235 {
3236   rtx src;
3237
3238   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
3239     {
3240       if (current_frame_info.reg_save_b0 != 0)
3241         src = gen_rtx_REG (DImode, current_frame_info.reg_save_b0);
3242       else
3243         {
3244           HOST_WIDE_INT off;
3245           unsigned int regno;
3246
3247           /* Compute offset from CFA for BR0.  */
3248           /* ??? Must be kept in sync with ia64_expand_prologue.  */
3249           off = (current_frame_info.spill_cfa_off
3250                  + current_frame_info.spill_size);
3251           for (regno = GR_REG (1); regno <= GR_REG (31); ++regno)
3252             if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3253               off -= 8;
3254
3255           /* Convert CFA offset to a register based offset.  */
3256           if (frame_pointer_needed)
3257             src = hard_frame_pointer_rtx;
3258           else
3259             {
3260               src = stack_pointer_rtx;
3261               off += current_frame_info.total_size;
3262             }
3263
3264           /* Load address into scratch register.  */
3265           if (CONST_OK_FOR_I (off))
3266             emit_insn (gen_adddi3 (dest, src, GEN_INT (off)));
3267           else
3268             {
3269               emit_move_insn (dest, GEN_INT (off));
3270               emit_insn (gen_adddi3 (dest, src, dest));
3271             }
3272
3273           src = gen_rtx_MEM (Pmode, dest);
3274         }
3275     }
3276   else
3277     src = gen_rtx_REG (DImode, BR_REG (0));
3278
3279   emit_move_insn (dest, src);
3280 }
3281
3282 int
3283 ia64_hard_regno_rename_ok (int from, int to)
3284 {
3285   /* Don't clobber any of the registers we reserved for the prologue.  */
3286   if (to == current_frame_info.reg_fp
3287       || to == current_frame_info.reg_save_b0
3288       || to == current_frame_info.reg_save_pr
3289       || to == current_frame_info.reg_save_ar_pfs
3290       || to == current_frame_info.reg_save_ar_unat
3291       || to == current_frame_info.reg_save_ar_lc)
3292     return 0;
3293
3294   if (from == current_frame_info.reg_fp
3295       || from == current_frame_info.reg_save_b0
3296       || from == current_frame_info.reg_save_pr
3297       || from == current_frame_info.reg_save_ar_pfs
3298       || from == current_frame_info.reg_save_ar_unat
3299       || from == current_frame_info.reg_save_ar_lc)
3300     return 0;
3301
3302   /* Don't use output registers outside the register frame.  */
3303   if (OUT_REGNO_P (to) && to >= OUT_REG (current_frame_info.n_output_regs))
3304     return 0;
3305
3306   /* Retain even/oddness on predicate register pairs.  */
3307   if (PR_REGNO_P (from) && PR_REGNO_P (to))
3308     return (from & 1) == (to & 1);
3309
3310   return 1;
3311 }
3312
3313 /* Target hook for assembling integer objects.  Handle word-sized
3314    aligned objects and detect the cases when @fptr is needed.  */
3315
3316 static bool
3317 ia64_assemble_integer (rtx x, unsigned int size, int aligned_p)
3318 {
3319   if (size == POINTER_SIZE / BITS_PER_UNIT
3320       && aligned_p
3321       && !(TARGET_NO_PIC || TARGET_AUTO_PIC)
3322       && GET_CODE (x) == SYMBOL_REF
3323       && SYMBOL_REF_FUNCTION_P (x))
3324     {
3325       if (POINTER_SIZE == 32)
3326         fputs ("\tdata4\t@fptr(", asm_out_file);
3327       else
3328         fputs ("\tdata8\t@fptr(", asm_out_file);
3329       output_addr_const (asm_out_file, x);
3330       fputs (")\n", asm_out_file);
3331       return true;
3332     }
3333   return default_assemble_integer (x, size, aligned_p);
3334 }
3335
3336 /* Emit the function prologue.  */
3337
3338 static void
3339 ia64_output_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
3340 {
3341   int mask, grsave, grsave_prev;
3342
3343   if (current_frame_info.need_regstk)
3344     fprintf (file, "\t.regstk %d, %d, %d, %d\n",
3345              current_frame_info.n_input_regs,
3346              current_frame_info.n_local_regs,
3347              current_frame_info.n_output_regs,
3348              current_frame_info.n_rotate_regs);
3349
3350   if (!flag_unwind_tables && (!flag_exceptions || USING_SJLJ_EXCEPTIONS))
3351     return;
3352
3353   /* Emit the .prologue directive.  */
3354
3355   mask = 0;
3356   grsave = grsave_prev = 0;
3357   if (current_frame_info.reg_save_b0 != 0)
3358     {
3359       mask |= 8;
3360       grsave = grsave_prev = current_frame_info.reg_save_b0;
3361     }
3362   if (current_frame_info.reg_save_ar_pfs != 0
3363       && (grsave_prev == 0
3364           || current_frame_info.reg_save_ar_pfs == grsave_prev + 1))
3365     {
3366       mask |= 4;
3367       if (grsave_prev == 0)
3368         grsave = current_frame_info.reg_save_ar_pfs;
3369       grsave_prev = current_frame_info.reg_save_ar_pfs;
3370     }
3371   if (current_frame_info.reg_fp != 0
3372       && (grsave_prev == 0
3373           || current_frame_info.reg_fp == grsave_prev + 1))
3374     {
3375       mask |= 2;
3376       if (grsave_prev == 0)
3377         grsave = HARD_FRAME_POINTER_REGNUM;
3378       grsave_prev = current_frame_info.reg_fp;
3379     }
3380   if (current_frame_info.reg_save_pr != 0
3381       && (grsave_prev == 0
3382           || current_frame_info.reg_save_pr == grsave_prev + 1))
3383     {
3384       mask |= 1;
3385       if (grsave_prev == 0)
3386         grsave = current_frame_info.reg_save_pr;
3387     }
3388
3389   if (mask && TARGET_GNU_AS)
3390     fprintf (file, "\t.prologue %d, %d\n", mask,
3391              ia64_dbx_register_number (grsave));
3392   else
3393     fputs ("\t.prologue\n", file);
3394
3395   /* Emit a .spill directive, if necessary, to relocate the base of
3396      the register spill area.  */
3397   if (current_frame_info.spill_cfa_off != -16)
3398     fprintf (file, "\t.spill %ld\n",
3399              (long) (current_frame_info.spill_cfa_off
3400                      + current_frame_info.spill_size));
3401 }
3402
3403 /* Emit the .body directive at the scheduled end of the prologue.  */
3404
3405 static void
3406 ia64_output_function_end_prologue (FILE *file)
3407 {
3408   if (!flag_unwind_tables && (!flag_exceptions || USING_SJLJ_EXCEPTIONS))
3409     return;
3410
3411   fputs ("\t.body\n", file);
3412 }
3413
3414 /* Emit the function epilogue.  */
3415
3416 static void
3417 ia64_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
3418                                HOST_WIDE_INT size ATTRIBUTE_UNUSED)
3419 {
3420   int i;
3421
3422   if (current_frame_info.reg_fp)
3423     {
3424       const char *tmp = reg_names[HARD_FRAME_POINTER_REGNUM];
3425       reg_names[HARD_FRAME_POINTER_REGNUM]
3426         = reg_names[current_frame_info.reg_fp];
3427       reg_names[current_frame_info.reg_fp] = tmp;
3428     }
3429   if (! TARGET_REG_NAMES)
3430     {
3431       for (i = 0; i < current_frame_info.n_input_regs; i++)
3432         reg_names[IN_REG (i)] = ia64_input_reg_names[i];
3433       for (i = 0; i < current_frame_info.n_local_regs; i++)
3434         reg_names[LOC_REG (i)] = ia64_local_reg_names[i];
3435       for (i = 0; i < current_frame_info.n_output_regs; i++)
3436         reg_names[OUT_REG (i)] = ia64_output_reg_names[i];
3437     }
3438
3439   current_frame_info.initialized = 0;
3440 }
3441
3442 int
3443 ia64_dbx_register_number (int regno)
3444 {
3445   /* In ia64_expand_prologue we quite literally renamed the frame pointer
3446      from its home at loc79 to something inside the register frame.  We
3447      must perform the same renumbering here for the debug info.  */
3448   if (current_frame_info.reg_fp)
3449     {
3450       if (regno == HARD_FRAME_POINTER_REGNUM)
3451         regno = current_frame_info.reg_fp;
3452       else if (regno == current_frame_info.reg_fp)
3453         regno = HARD_FRAME_POINTER_REGNUM;
3454     }
3455
3456   if (IN_REGNO_P (regno))
3457     return 32 + regno - IN_REG (0);
3458   else if (LOC_REGNO_P (regno))
3459     return 32 + current_frame_info.n_input_regs + regno - LOC_REG (0);
3460   else if (OUT_REGNO_P (regno))
3461     return (32 + current_frame_info.n_input_regs
3462             + current_frame_info.n_local_regs + regno - OUT_REG (0));
3463   else
3464     return regno;
3465 }
3466
3467 void
3468 ia64_initialize_trampoline (rtx addr, rtx fnaddr, rtx static_chain)
3469 {
3470   rtx addr_reg, eight = GEN_INT (8);
3471
3472   /* The Intel assembler requires that the global __ia64_trampoline symbol
3473      be declared explicitly */
3474   if (!TARGET_GNU_AS)
3475     {
3476       static bool declared_ia64_trampoline = false;
3477
3478       if (!declared_ia64_trampoline)
3479         {
3480           declared_ia64_trampoline = true;
3481           (*targetm.asm_out.globalize_label) (asm_out_file,
3482                                               "__ia64_trampoline");
3483         }
3484     }
3485
3486   /* Load up our iterator.  */
3487   addr_reg = gen_reg_rtx (Pmode);
3488   emit_move_insn (addr_reg, addr);
3489
3490   /* The first two words are the fake descriptor:
3491      __ia64_trampoline, ADDR+16.  */
3492   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg),
3493                   gen_rtx_SYMBOL_REF (Pmode, "__ia64_trampoline"));
3494   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
3495
3496   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg),
3497                   copy_to_reg (plus_constant (addr, 16)));
3498   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
3499
3500   /* The third word is the target descriptor.  */
3501   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg), fnaddr);
3502   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
3503
3504   /* The fourth word is the static chain.  */
3505   emit_move_insn (gen_rtx_MEM (Pmode, addr_reg), static_chain);
3506 }
3507 \f
3508 /* Do any needed setup for a variadic function.  CUM has not been updated
3509    for the last named argument which has type TYPE and mode MODE.
3510
3511    We generate the actual spill instructions during prologue generation.  */
3512
3513 static void
3514 ia64_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
3515                              tree type, int * pretend_size,
3516                              int second_time ATTRIBUTE_UNUSED)
3517 {
3518   CUMULATIVE_ARGS next_cum = *cum;
3519
3520   /* Skip the current argument.  */
3521   ia64_function_arg_advance (&next_cum, mode, type, 1);
3522
3523   if (next_cum.words < MAX_ARGUMENT_SLOTS)
3524     {
3525       int n = MAX_ARGUMENT_SLOTS - next_cum.words;
3526       *pretend_size = n * UNITS_PER_WORD;
3527       cfun->machine->n_varargs = n;
3528     }
3529 }
3530
3531 /* Check whether TYPE is a homogeneous floating point aggregate.  If
3532    it is, return the mode of the floating point type that appears
3533    in all leafs.  If it is not, return VOIDmode.
3534
3535    An aggregate is a homogeneous floating point aggregate is if all
3536    fields/elements in it have the same floating point type (e.g,
3537    SFmode).  128-bit quad-precision floats are excluded.  */
3538
3539 static enum machine_mode
3540 hfa_element_mode (tree type, int nested)
3541 {
3542   enum machine_mode element_mode = VOIDmode;
3543   enum machine_mode mode;
3544   enum tree_code code = TREE_CODE (type);
3545   int know_element_mode = 0;
3546   tree t;
3547
3548   switch (code)
3549     {
3550     case VOID_TYPE:     case INTEGER_TYPE:      case ENUMERAL_TYPE:
3551     case BOOLEAN_TYPE:  case CHAR_TYPE:         case POINTER_TYPE:
3552     case OFFSET_TYPE:   case REFERENCE_TYPE:    case METHOD_TYPE:
3553     case FILE_TYPE:     case SET_TYPE:          case LANG_TYPE:
3554     case FUNCTION_TYPE:
3555       return VOIDmode;
3556
3557       /* Fortran complex types are supposed to be HFAs, so we need to handle
3558          gcc's COMPLEX_TYPEs as HFAs.  We need to exclude the integral complex
3559          types though.  */
3560     case COMPLEX_TYPE:
3561       if (GET_MODE_CLASS (TYPE_MODE (type)) == MODE_COMPLEX_FLOAT
3562           && TYPE_MODE (type) != TCmode)
3563         return GET_MODE_INNER (TYPE_MODE (type));
3564       else
3565         return VOIDmode;
3566
3567     case REAL_TYPE:
3568       /* We want to return VOIDmode for raw REAL_TYPEs, but the actual
3569          mode if this is contained within an aggregate.  */
3570       if (nested && TYPE_MODE (type) != TFmode)
3571         return TYPE_MODE (type);
3572       else
3573         return VOIDmode;
3574
3575     case ARRAY_TYPE:
3576       return hfa_element_mode (TREE_TYPE (type), 1);
3577
3578     case RECORD_TYPE:
3579     case UNION_TYPE:
3580     case QUAL_UNION_TYPE:
3581       for (t = TYPE_FIELDS (type); t; t = TREE_CHAIN (t))
3582         {
3583           if (TREE_CODE (t) != FIELD_DECL)
3584             continue;
3585
3586           mode = hfa_element_mode (TREE_TYPE (t), 1);
3587           if (know_element_mode)
3588             {
3589               if (mode != element_mode)
3590                 return VOIDmode;
3591             }
3592           else if (GET_MODE_CLASS (mode) != MODE_FLOAT)
3593             return VOIDmode;
3594           else
3595             {
3596               know_element_mode = 1;
3597               element_mode = mode;
3598             }
3599         }
3600       return element_mode;
3601
3602     default:
3603       /* If we reach here, we probably have some front-end specific type
3604          that the backend doesn't know about.  This can happen via the
3605          aggregate_value_p call in init_function_start.  All we can do is
3606          ignore unknown tree types.  */
3607       return VOIDmode;
3608     }
3609
3610   return VOIDmode;
3611 }
3612
3613 /* Return the number of words required to hold a quantity of TYPE and MODE
3614    when passed as an argument.  */
3615 static int
3616 ia64_function_arg_words (tree type, enum machine_mode mode)
3617 {
3618   int words;
3619
3620   if (mode == BLKmode)
3621     words = int_size_in_bytes (type);
3622   else
3623     words = GET_MODE_SIZE (mode);
3624
3625   return (words + UNITS_PER_WORD - 1) / UNITS_PER_WORD;  /* round up */
3626 }
3627
3628 /* Return the number of registers that should be skipped so the current
3629    argument (described by TYPE and WORDS) will be properly aligned.
3630
3631    Integer and float arguments larger than 8 bytes start at the next
3632    even boundary.  Aggregates larger than 8 bytes start at the next
3633    even boundary if the aggregate has 16 byte alignment.  Note that
3634    in the 32-bit ABI, TImode and TFmode have only 8-byte alignment
3635    but are still to be aligned in registers.
3636
3637    ??? The ABI does not specify how to handle aggregates with
3638    alignment from 9 to 15 bytes, or greater than 16.  We handle them
3639    all as if they had 16 byte alignment.  Such aggregates can occur
3640    only if gcc extensions are used.  */
3641 static int
3642 ia64_function_arg_offset (CUMULATIVE_ARGS *cum, tree type, int words)
3643 {
3644   if ((cum->words & 1) == 0)
3645     return 0;
3646
3647   if (type
3648       && TREE_CODE (type) != INTEGER_TYPE
3649       && TREE_CODE (type) != REAL_TYPE)
3650     return TYPE_ALIGN (type) > 8 * BITS_PER_UNIT;
3651   else
3652     return words > 1;
3653 }
3654
3655 /* Return rtx for register where argument is passed, or zero if it is passed
3656    on the stack.  */
3657 /* ??? 128-bit quad-precision floats are always passed in general
3658    registers.  */
3659
3660 rtx
3661 ia64_function_arg (CUMULATIVE_ARGS *cum, enum machine_mode mode, tree type,
3662                    int named, int incoming)
3663 {
3664   int basereg = (incoming ? GR_ARG_FIRST : AR_ARG_FIRST);
3665   int words = ia64_function_arg_words (type, mode);
3666   int offset = ia64_function_arg_offset (cum, type, words);
3667   enum machine_mode hfa_mode = VOIDmode;
3668
3669   /* If all argument slots are used, then it must go on the stack.  */
3670   if (cum->words + offset >= MAX_ARGUMENT_SLOTS)
3671     return 0;
3672
3673   /* Check for and handle homogeneous FP aggregates.  */
3674   if (type)
3675     hfa_mode = hfa_element_mode (type, 0);
3676
3677   /* Unnamed prototyped hfas are passed as usual.  Named prototyped hfas
3678      and unprototyped hfas are passed specially.  */
3679   if (hfa_mode != VOIDmode && (! cum->prototype || named))
3680     {
3681       rtx loc[16];
3682       int i = 0;
3683       int fp_regs = cum->fp_regs;
3684       int int_regs = cum->words + offset;
3685       int hfa_size = GET_MODE_SIZE (hfa_mode);
3686       int byte_size;
3687       int args_byte_size;
3688
3689       /* If prototyped, pass it in FR regs then GR regs.
3690          If not prototyped, pass it in both FR and GR regs.
3691
3692          If this is an SFmode aggregate, then it is possible to run out of
3693          FR regs while GR regs are still left.  In that case, we pass the
3694          remaining part in the GR regs.  */
3695
3696       /* Fill the FP regs.  We do this always.  We stop if we reach the end
3697          of the argument, the last FP register, or the last argument slot.  */
3698
3699       byte_size = ((mode == BLKmode)
3700                    ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
3701       args_byte_size = int_regs * UNITS_PER_WORD;
3702       offset = 0;
3703       for (; (offset < byte_size && fp_regs < MAX_ARGUMENT_SLOTS
3704               && args_byte_size < (MAX_ARGUMENT_SLOTS * UNITS_PER_WORD)); i++)
3705         {
3706           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
3707                                       gen_rtx_REG (hfa_mode, (FR_ARG_FIRST
3708                                                               + fp_regs)),
3709                                       GEN_INT (offset));
3710           offset += hfa_size;
3711           args_byte_size += hfa_size;
3712           fp_regs++;
3713         }
3714
3715       /* If no prototype, then the whole thing must go in GR regs.  */
3716       if (! cum->prototype)
3717         offset = 0;
3718       /* If this is an SFmode aggregate, then we might have some left over
3719          that needs to go in GR regs.  */
3720       else if (byte_size != offset)
3721         int_regs += offset / UNITS_PER_WORD;
3722
3723       /* Fill in the GR regs.  We must use DImode here, not the hfa mode.  */
3724
3725       for (; offset < byte_size && int_regs < MAX_ARGUMENT_SLOTS; i++)
3726         {
3727           enum machine_mode gr_mode = DImode;
3728           unsigned int gr_size;
3729
3730           /* If we have an odd 4 byte hunk because we ran out of FR regs,
3731              then this goes in a GR reg left adjusted/little endian, right
3732              adjusted/big endian.  */
3733           /* ??? Currently this is handled wrong, because 4-byte hunks are
3734              always right adjusted/little endian.  */
3735           if (offset & 0x4)
3736             gr_mode = SImode;
3737           /* If we have an even 4 byte hunk because the aggregate is a
3738              multiple of 4 bytes in size, then this goes in a GR reg right
3739              adjusted/little endian.  */
3740           else if (byte_size - offset == 4)
3741             gr_mode = SImode;
3742
3743           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
3744                                       gen_rtx_REG (gr_mode, (basereg
3745                                                              + int_regs)),
3746                                       GEN_INT (offset));
3747
3748           gr_size = GET_MODE_SIZE (gr_mode);
3749           offset += gr_size;
3750           if (gr_size == UNITS_PER_WORD
3751               || (gr_size < UNITS_PER_WORD && offset % UNITS_PER_WORD == 0))
3752             int_regs++;
3753           else if (gr_size > UNITS_PER_WORD)
3754             int_regs += gr_size / UNITS_PER_WORD;
3755         }
3756
3757       /* If we ended up using just one location, just return that one loc, but
3758          change the mode back to the argument mode.  */
3759       if (i == 1)
3760         return gen_rtx_REG (mode, REGNO (XEXP (loc[0], 0)));
3761       else
3762         return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
3763     }
3764
3765   /* Integral and aggregates go in general registers.  If we have run out of
3766      FR registers, then FP values must also go in general registers.  This can
3767      happen when we have a SFmode HFA.  */
3768   else if (mode == TFmode || mode == TCmode
3769            || (! FLOAT_MODE_P (mode) || cum->fp_regs == MAX_ARGUMENT_SLOTS))
3770     {
3771       int byte_size = ((mode == BLKmode)
3772                        ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
3773       if (BYTES_BIG_ENDIAN
3774         && (mode == BLKmode || (type && AGGREGATE_TYPE_P (type)))
3775         && byte_size < UNITS_PER_WORD
3776         && byte_size > 0)
3777         {
3778           rtx gr_reg = gen_rtx_EXPR_LIST (VOIDmode,
3779                                           gen_rtx_REG (DImode,
3780                                                        (basereg + cum->words
3781                                                         + offset)),
3782                                           const0_rtx);
3783           return gen_rtx_PARALLEL (mode, gen_rtvec (1, gr_reg));
3784         }
3785       else
3786         return gen_rtx_REG (mode, basereg + cum->words + offset);
3787
3788     }
3789
3790   /* If there is a prototype, then FP values go in a FR register when
3791      named, and in a GR register when unnamed.  */
3792   else if (cum->prototype)
3793     {
3794       if (named)
3795         return gen_rtx_REG (mode, FR_ARG_FIRST + cum->fp_regs);
3796       /* In big-endian mode, an anonymous SFmode value must be represented
3797          as (parallel:SF [(expr_list (reg:DI n) (const_int 0))]) to force
3798          the value into the high half of the general register.  */
3799       else if (BYTES_BIG_ENDIAN && mode == SFmode)
3800         return gen_rtx_PARALLEL (mode,
3801                  gen_rtvec (1,
3802                    gen_rtx_EXPR_LIST (VOIDmode,
3803                      gen_rtx_REG (DImode, basereg + cum->words + offset),
3804                                       const0_rtx)));
3805       else
3806         return gen_rtx_REG (mode, basereg + cum->words + offset);
3807     }
3808   /* If there is no prototype, then FP values go in both FR and GR
3809      registers.  */
3810   else
3811     {
3812       /* See comment above.  */
3813       enum machine_mode inner_mode =
3814         (BYTES_BIG_ENDIAN && mode == SFmode) ? DImode : mode;
3815
3816       rtx fp_reg = gen_rtx_EXPR_LIST (VOIDmode,
3817                                       gen_rtx_REG (mode, (FR_ARG_FIRST
3818                                                           + cum->fp_regs)),
3819                                       const0_rtx);
3820       rtx gr_reg = gen_rtx_EXPR_LIST (VOIDmode,
3821                                       gen_rtx_REG (inner_mode,
3822                                                    (basereg + cum->words
3823                                                     + offset)),
3824                                       const0_rtx);
3825
3826       return gen_rtx_PARALLEL (mode, gen_rtvec (2, fp_reg, gr_reg));
3827     }
3828 }
3829
3830 /* Return number of words, at the beginning of the argument, that must be
3831    put in registers.  0 is the argument is entirely in registers or entirely
3832    in memory.  */
3833
3834 int
3835 ia64_function_arg_partial_nregs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
3836                                  tree type, int named ATTRIBUTE_UNUSED)
3837 {
3838   int words = ia64_function_arg_words (type, mode);
3839   int offset = ia64_function_arg_offset (cum, type, words);
3840
3841   /* If all argument slots are used, then it must go on the stack.  */
3842   if (cum->words + offset >= MAX_ARGUMENT_SLOTS)
3843     return 0;
3844
3845   /* It doesn't matter whether the argument goes in FR or GR regs.  If
3846      it fits within the 8 argument slots, then it goes entirely in
3847      registers.  If it extends past the last argument slot, then the rest
3848      goes on the stack.  */
3849
3850   if (words + cum->words + offset <= MAX_ARGUMENT_SLOTS)
3851     return 0;
3852
3853   return MAX_ARGUMENT_SLOTS - cum->words - offset;
3854 }
3855
3856 /* Update CUM to point after this argument.  This is patterned after
3857    ia64_function_arg.  */
3858
3859 void
3860 ia64_function_arg_advance (CUMULATIVE_ARGS *cum, enum machine_mode mode,
3861                            tree type, int named)
3862 {
3863   int words = ia64_function_arg_words (type, mode);
3864   int offset = ia64_function_arg_offset (cum, type, words);
3865   enum machine_mode hfa_mode = VOIDmode;
3866
3867   /* If all arg slots are already full, then there is nothing to do.  */
3868   if (cum->words >= MAX_ARGUMENT_SLOTS)
3869     return;
3870
3871   cum->words += words + offset;
3872
3873   /* Check for and handle homogeneous FP aggregates.  */
3874   if (type)
3875     hfa_mode = hfa_element_mode (type, 0);
3876
3877   /* Unnamed prototyped hfas are passed as usual.  Named prototyped hfas
3878      and unprototyped hfas are passed specially.  */
3879   if (hfa_mode != VOIDmode && (! cum->prototype || named))
3880     {
3881       int fp_regs = cum->fp_regs;
3882       /* This is the original value of cum->words + offset.  */
3883       int int_regs = cum->words - words;
3884       int hfa_size = GET_MODE_SIZE (hfa_mode);
3885       int byte_size;
3886       int args_byte_size;
3887
3888       /* If prototyped, pass it in FR regs then GR regs.
3889          If not prototyped, pass it in both FR and GR regs.
3890
3891          If this is an SFmode aggregate, then it is possible to run out of
3892          FR regs while GR regs are still left.  In that case, we pass the
3893          remaining part in the GR regs.  */
3894
3895       /* Fill the FP regs.  We do this always.  We stop if we reach the end
3896          of the argument, the last FP register, or the last argument slot.  */
3897
3898       byte_size = ((mode == BLKmode)
3899                    ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
3900       args_byte_size = int_regs * UNITS_PER_WORD;
3901       offset = 0;
3902       for (; (offset < byte_size && fp_regs < MAX_ARGUMENT_SLOTS
3903               && args_byte_size < (MAX_ARGUMENT_SLOTS * UNITS_PER_WORD));)
3904         {
3905           offset += hfa_size;
3906           args_byte_size += hfa_size;
3907           fp_regs++;
3908         }
3909
3910       cum->fp_regs = fp_regs;
3911     }
3912
3913   /* Integral and aggregates go in general registers.  If we have run out of
3914      FR registers, then FP values must also go in general registers.  This can
3915      happen when we have a SFmode HFA.  */
3916   else if (! FLOAT_MODE_P (mode) || cum->fp_regs == MAX_ARGUMENT_SLOTS)
3917     cum->int_regs = cum->words;
3918
3919   /* If there is a prototype, then FP values go in a FR register when
3920      named, and in a GR register when unnamed.  */
3921   else if (cum->prototype)
3922     {
3923       if (! named)
3924         cum->int_regs = cum->words;
3925       else
3926         /* ??? Complex types should not reach here.  */
3927         cum->fp_regs += (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT ? 2 : 1);
3928     }
3929   /* If there is no prototype, then FP values go in both FR and GR
3930      registers.  */
3931   else
3932     {
3933       /* ??? Complex types should not reach here.  */
3934       cum->fp_regs += (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT ? 2 : 1);
3935       cum->int_regs = cum->words;
3936     }
3937 }
3938
3939 /* Variable sized types are passed by reference.  */
3940 /* ??? At present this is a GCC extension to the IA-64 ABI.  */
3941
3942 int
3943 ia64_function_arg_pass_by_reference (CUMULATIVE_ARGS *cum ATTRIBUTE_UNUSED,
3944                                      enum machine_mode mode ATTRIBUTE_UNUSED,
3945                                      tree type, int named ATTRIBUTE_UNUSED)
3946 {
3947   return type && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST;
3948 }
3949
3950 /* True if it is OK to do sibling call optimization for the specified
3951    call expression EXP.  DECL will be the called function, or NULL if
3952    this is an indirect call.  */
3953 static bool
3954 ia64_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
3955 {
3956   /* We must always return with our current GP.  This means we can
3957      only sibcall to functions defined in the current module.  */
3958   return decl && (*targetm.binds_local_p) (decl);
3959 }
3960 \f
3961
3962 /* Implement va_arg.  */
3963
3964 rtx
3965 ia64_va_arg (tree valist, tree type)
3966 {
3967   tree t;
3968
3969   /* Variable sized types are passed by reference.  */
3970   if (TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
3971     {
3972       rtx addr = force_reg (ptr_mode,
3973             std_expand_builtin_va_arg (valist, build_pointer_type (type)));
3974 #ifdef POINTERS_EXTEND_UNSIGNED
3975       addr = convert_memory_address (Pmode, addr);
3976 #endif
3977       return gen_rtx_MEM (ptr_mode, addr);
3978     }
3979
3980   /* Aggregate arguments with alignment larger than 8 bytes start at
3981      the next even boundary.  Integer and floating point arguments
3982      do so if they are larger than 8 bytes, whether or not they are
3983      also aligned larger than 8 bytes.  */
3984   if ((TREE_CODE (type) == REAL_TYPE || TREE_CODE (type) == INTEGER_TYPE)
3985       ? int_size_in_bytes (type) > 8 : TYPE_ALIGN (type) > 8 * BITS_PER_UNIT)
3986     {
3987       t = build (PLUS_EXPR, TREE_TYPE (valist), valist,
3988                  build_int_2 (2 * UNITS_PER_WORD - 1, 0));
3989       t = build (BIT_AND_EXPR, TREE_TYPE (t), t,
3990                  build_int_2 (-2 * UNITS_PER_WORD, -1));
3991       t = build (MODIFY_EXPR, TREE_TYPE (valist), valist, t);
3992       TREE_SIDE_EFFECTS (t) = 1;
3993       expand_expr (t, const0_rtx, VOIDmode, EXPAND_NORMAL);
3994     }
3995
3996   return std_expand_builtin_va_arg (valist, type);
3997 }
3998 \f
3999 /* Return 1 if function return value returned in memory.  Return 0 if it is
4000    in a register.  */
4001
4002 static bool
4003 ia64_return_in_memory (tree valtype, tree fntype ATTRIBUTE_UNUSED)
4004 {
4005   enum machine_mode mode;
4006   enum machine_mode hfa_mode;
4007   HOST_WIDE_INT byte_size;
4008
4009   mode = TYPE_MODE (valtype);
4010   byte_size = GET_MODE_SIZE (mode);
4011   if (mode == BLKmode)
4012     {
4013       byte_size = int_size_in_bytes (valtype);
4014       if (byte_size < 0)
4015         return true;
4016     }
4017
4018   /* Hfa's with up to 8 elements are returned in the FP argument registers.  */
4019
4020   hfa_mode = hfa_element_mode (valtype, 0);
4021   if (hfa_mode != VOIDmode)
4022     {
4023       int hfa_size = GET_MODE_SIZE (hfa_mode);
4024
4025       if (byte_size / hfa_size > MAX_ARGUMENT_SLOTS)
4026         return true;
4027       else
4028         return false;
4029     }
4030   else if (byte_size > UNITS_PER_WORD * MAX_INT_RETURN_SLOTS)
4031     return true;
4032   else
4033     return false;
4034 }
4035
4036 /* Return rtx for register that holds the function return value.  */
4037
4038 rtx
4039 ia64_function_value (tree valtype, tree func ATTRIBUTE_UNUSED)
4040 {
4041   enum machine_mode mode;
4042   enum machine_mode hfa_mode;
4043
4044   mode = TYPE_MODE (valtype);
4045   hfa_mode = hfa_element_mode (valtype, 0);
4046
4047   if (hfa_mode != VOIDmode)
4048     {
4049       rtx loc[8];
4050       int i;
4051       int hfa_size;
4052       int byte_size;
4053       int offset;
4054
4055       hfa_size = GET_MODE_SIZE (hfa_mode);
4056       byte_size = ((mode == BLKmode)
4057                    ? int_size_in_bytes (valtype) : GET_MODE_SIZE (mode));
4058       offset = 0;
4059       for (i = 0; offset < byte_size; i++)
4060         {
4061           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4062                                       gen_rtx_REG (hfa_mode, FR_ARG_FIRST + i),
4063                                       GEN_INT (offset));
4064           offset += hfa_size;
4065         }
4066
4067       if (i == 1)
4068         return XEXP (loc[0], 0);
4069       else
4070         return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
4071     }
4072   else if (FLOAT_TYPE_P (valtype) && mode != TFmode && mode != TCmode)
4073     return gen_rtx_REG (mode, FR_ARG_FIRST);
4074   else
4075     {
4076       if (BYTES_BIG_ENDIAN
4077           && (mode == BLKmode || (valtype && AGGREGATE_TYPE_P (valtype))))
4078         {
4079           rtx loc[8];
4080           int offset;
4081           int bytesize;
4082           int i;
4083
4084           offset = 0;
4085           bytesize = int_size_in_bytes (valtype);
4086           for (i = 0; offset < bytesize; i++)
4087             {
4088               loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4089                                           gen_rtx_REG (DImode,
4090                                                        GR_RET_FIRST + i),
4091                                           GEN_INT (offset));
4092               offset += UNITS_PER_WORD;
4093             }
4094           return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
4095         }
4096       else
4097         return gen_rtx_REG (mode, GR_RET_FIRST);
4098     }
4099 }
4100
4101 /* This is called from dwarf2out.c via ASM_OUTPUT_DWARF_DTPREL.
4102    We need to emit DTP-relative relocations.  */
4103
4104 void
4105 ia64_output_dwarf_dtprel (FILE *file, int size, rtx x)
4106 {
4107   if (size != 8)
4108     abort ();
4109   fputs ("\tdata8.ua\t@dtprel(", file);
4110   output_addr_const (file, x);
4111   fputs (")", file);
4112 }
4113
4114 /* Print a memory address as an operand to reference that memory location.  */
4115
4116 /* ??? Do we need this?  It gets used only for 'a' operands.  We could perhaps
4117    also call this from ia64_print_operand for memory addresses.  */
4118
4119 void
4120 ia64_print_operand_address (FILE * stream ATTRIBUTE_UNUSED,
4121                             rtx address ATTRIBUTE_UNUSED)
4122 {
4123 }
4124
4125 /* Print an operand to an assembler instruction.
4126    C    Swap and print a comparison operator.
4127    D    Print an FP comparison operator.
4128    E    Print 32 - constant, for SImode shifts as extract.
4129    e    Print 64 - constant, for DImode rotates.
4130    F    A floating point constant 0.0 emitted as f0, or 1.0 emitted as f1, or
4131         a floating point register emitted normally.
4132    I    Invert a predicate register by adding 1.
4133    J    Select the proper predicate register for a condition.
4134    j    Select the inverse predicate register for a condition.
4135    O    Append .acq for volatile load.
4136    P    Postincrement of a MEM.
4137    Q    Append .rel for volatile store.
4138    S    Shift amount for shladd instruction.
4139    T    Print an 8-bit sign extended number (K) as a 32-bit unsigned number
4140         for Intel assembler.
4141    U    Print an 8-bit sign extended number (K) as a 64-bit unsigned number
4142         for Intel assembler.
4143    r    Print register name, or constant 0 as r0.  HP compatibility for
4144         Linux kernel.  */
4145 void
4146 ia64_print_operand (FILE * file, rtx x, int code)
4147 {
4148   const char *str;
4149
4150   switch (code)
4151     {
4152     case 0:
4153       /* Handled below.  */
4154       break;
4155
4156     case 'C':
4157       {
4158         enum rtx_code c = swap_condition (GET_CODE (x));
4159         fputs (GET_RTX_NAME (c), file);
4160         return;
4161       }
4162
4163     case 'D':
4164       switch (GET_CODE (x))
4165         {
4166         case NE:
4167           str = "neq";
4168           break;
4169         case UNORDERED:
4170           str = "unord";
4171           break;
4172         case ORDERED:
4173           str = "ord";
4174           break;
4175         default:
4176           str = GET_RTX_NAME (GET_CODE (x));
4177           break;
4178         }
4179       fputs (str, file);
4180       return;
4181
4182     case 'E':
4183       fprintf (file, HOST_WIDE_INT_PRINT_DEC, 32 - INTVAL (x));
4184       return;
4185
4186     case 'e':
4187       fprintf (file, HOST_WIDE_INT_PRINT_DEC, 64 - INTVAL (x));
4188       return;
4189
4190     case 'F':
4191       if (x == CONST0_RTX (GET_MODE (x)))
4192         str = reg_names [FR_REG (0)];
4193       else if (x == CONST1_RTX (GET_MODE (x)))
4194         str = reg_names [FR_REG (1)];
4195       else if (GET_CODE (x) == REG)
4196         str = reg_names [REGNO (x)];
4197       else
4198         abort ();
4199       fputs (str, file);
4200       return;
4201
4202     case 'I':
4203       fputs (reg_names [REGNO (x) + 1], file);
4204       return;
4205
4206     case 'J':
4207     case 'j':
4208       {
4209         unsigned int regno = REGNO (XEXP (x, 0));
4210         if (GET_CODE (x) == EQ)
4211           regno += 1;
4212         if (code == 'j')
4213           regno ^= 1;
4214         fputs (reg_names [regno], file);
4215       }
4216       return;
4217
4218     case 'O':
4219       if (MEM_VOLATILE_P (x))
4220         fputs(".acq", file);
4221       return;
4222
4223     case 'P':
4224       {
4225         HOST_WIDE_INT value;
4226
4227         switch (GET_CODE (XEXP (x, 0)))
4228           {
4229           default:
4230             return;
4231
4232           case POST_MODIFY:
4233             x = XEXP (XEXP (XEXP (x, 0), 1), 1);
4234             if (GET_CODE (x) == CONST_INT)
4235               value = INTVAL (x);
4236             else if (GET_CODE (x) == REG)
4237               {
4238                 fprintf (file, ", %s", reg_names[REGNO (x)]);
4239                 return;
4240               }
4241             else
4242               abort ();
4243             break;
4244
4245           case POST_INC:
4246             value = GET_MODE_SIZE (GET_MODE (x));
4247             break;
4248
4249           case POST_DEC:
4250             value = - (HOST_WIDE_INT) GET_MODE_SIZE (GET_MODE (x));
4251             break;
4252           }
4253
4254         fprintf (file, ", " HOST_WIDE_INT_PRINT_DEC, value);
4255         return;
4256       }
4257
4258     case 'Q':
4259       if (MEM_VOLATILE_P (x))
4260         fputs(".rel", file);
4261       return;
4262
4263     case 'S':
4264       fprintf (file, "%d", exact_log2 (INTVAL (x)));
4265       return;
4266
4267     case 'T':
4268       if (! TARGET_GNU_AS && GET_CODE (x) == CONST_INT)
4269         {
4270           fprintf (file, "0x%x", (int) INTVAL (x) & 0xffffffff);
4271           return;
4272         }
4273       break;
4274
4275     case 'U':
4276       if (! TARGET_GNU_AS && GET_CODE (x) == CONST_INT)
4277         {
4278           const char *prefix = "0x";
4279           if (INTVAL (x) & 0x80000000)
4280             {
4281               fprintf (file, "0xffffffff");
4282               prefix = "";
4283             }
4284           fprintf (file, "%s%x", prefix, (int) INTVAL (x) & 0xffffffff);
4285           return;
4286         }
4287       break;
4288
4289     case 'r':
4290       /* If this operand is the constant zero, write it as register zero.
4291          Any register, zero, or CONST_INT value is OK here.  */
4292       if (GET_CODE (x) == REG)
4293         fputs (reg_names[REGNO (x)], file);
4294       else if (x == CONST0_RTX (GET_MODE (x)))
4295         fputs ("r0", file);
4296       else if (GET_CODE (x) == CONST_INT)
4297         output_addr_const (file, x);
4298       else
4299         output_operand_lossage ("invalid %%r value");
4300       return;
4301
4302     case '+':
4303       {
4304         const char *which;
4305
4306         /* For conditional branches, returns or calls, substitute
4307            sptk, dptk, dpnt, or spnt for %s.  */
4308         x = find_reg_note (current_output_insn, REG_BR_PROB, 0);
4309         if (x)
4310           {
4311             int pred_val = INTVAL (XEXP (x, 0));
4312
4313             /* Guess top and bottom 10% statically predicted.  */
4314             if (pred_val < REG_BR_PROB_BASE / 50)
4315               which = ".spnt";
4316             else if (pred_val < REG_BR_PROB_BASE / 2)
4317               which = ".dpnt";
4318             else if (pred_val < REG_BR_PROB_BASE / 100 * 98)
4319               which = ".dptk";
4320             else
4321               which = ".sptk";
4322           }
4323         else if (GET_CODE (current_output_insn) == CALL_INSN)
4324           which = ".sptk";
4325         else
4326           which = ".dptk";
4327
4328         fputs (which, file);
4329         return;
4330       }
4331
4332     case ',':
4333       x = current_insn_predicate;
4334       if (x)
4335         {
4336           unsigned int regno = REGNO (XEXP (x, 0));
4337           if (GET_CODE (x) == EQ)
4338             regno += 1;
4339           fprintf (file, "(%s) ", reg_names [regno]);
4340         }
4341       return;
4342
4343     default:
4344       output_operand_lossage ("ia64_print_operand: unknown code");
4345       return;
4346     }
4347
4348   switch (GET_CODE (x))
4349     {
4350       /* This happens for the spill/restore instructions.  */
4351     case POST_INC:
4352     case POST_DEC:
4353     case POST_MODIFY:
4354       x = XEXP (x, 0);
4355       /* ... fall through ...  */
4356
4357     case REG:
4358       fputs (reg_names [REGNO (x)], file);
4359       break;
4360
4361     case MEM:
4362       {
4363         rtx addr = XEXP (x, 0);
4364         if (GET_RTX_CLASS (GET_CODE (addr)) == RTX_AUTOINC)
4365           addr = XEXP (addr, 0);
4366         fprintf (file, "[%s]", reg_names [REGNO (addr)]);
4367         break;
4368       }
4369
4370     default:
4371       output_addr_const (file, x);
4372       break;
4373     }
4374
4375   return;
4376 }
4377 \f
4378 /* Compute a (partial) cost for rtx X.  Return true if the complete
4379    cost has been computed, and false if subexpressions should be
4380    scanned.  In either case, *TOTAL contains the cost result.  */
4381 /* ??? This is incomplete.  */
4382
4383 static bool
4384 ia64_rtx_costs (rtx x, int code, int outer_code, int *total)
4385 {
4386   switch (code)
4387     {
4388     case CONST_INT:
4389       switch (outer_code)
4390         {
4391         case SET:
4392           *total = CONST_OK_FOR_J (INTVAL (x)) ? 0 : COSTS_N_INSNS (1);
4393           return true;
4394         case PLUS:
4395           if (CONST_OK_FOR_I (INTVAL (x)))
4396             *total = 0;
4397           else if (CONST_OK_FOR_J (INTVAL (x)))
4398             *total = 1;
4399           else
4400             *total = COSTS_N_INSNS (1);
4401           return true;
4402         default:
4403           if (CONST_OK_FOR_K (INTVAL (x)) || CONST_OK_FOR_L (INTVAL (x)))
4404             *total = 0;
4405           else
4406             *total = COSTS_N_INSNS (1);
4407           return true;
4408         }
4409
4410     case CONST_DOUBLE:
4411       *total = COSTS_N_INSNS (1);
4412       return true;
4413
4414     case CONST:
4415     case SYMBOL_REF:
4416     case LABEL_REF:
4417       *total = COSTS_N_INSNS (3);
4418       return true;
4419
4420     case MULT:
4421       /* For multiplies wider than HImode, we have to go to the FPU,
4422          which normally involves copies.  Plus there's the latency
4423          of the multiply itself, and the latency of the instructions to
4424          transfer integer regs to FP regs.  */
4425       /* ??? Check for FP mode.  */
4426       if (GET_MODE_SIZE (GET_MODE (x)) > 2)
4427         *total = COSTS_N_INSNS (10);
4428       else
4429         *total = COSTS_N_INSNS (2);
4430       return true;
4431
4432     case PLUS:
4433     case MINUS:
4434     case ASHIFT:
4435     case ASHIFTRT:
4436     case LSHIFTRT:
4437       *total = COSTS_N_INSNS (1);
4438       return true;
4439
4440     case DIV:
4441     case UDIV:
4442     case MOD:
4443     case UMOD:
4444       /* We make divide expensive, so that divide-by-constant will be
4445          optimized to a multiply.  */
4446       *total = COSTS_N_INSNS (60);
4447       return true;
4448
4449     default:
4450       return false;
4451     }
4452 }
4453
4454 /* Calculate the cost of moving data from a register in class FROM to
4455    one in class TO, using MODE.  */
4456
4457 int
4458 ia64_register_move_cost (enum machine_mode mode, enum reg_class from,
4459                          enum reg_class to)
4460 {
4461   /* ADDL_REGS is the same as GR_REGS for movement purposes.  */
4462   if (to == ADDL_REGS)
4463     to = GR_REGS;
4464   if (from == ADDL_REGS)
4465     from = GR_REGS;
4466
4467   /* All costs are symmetric, so reduce cases by putting the
4468      lower number class as the destination.  */
4469   if (from < to)
4470     {
4471       enum reg_class tmp = to;
4472       to = from, from = tmp;
4473     }
4474
4475   /* Moving from FR<->GR in XFmode must be more expensive than 2,
4476      so that we get secondary memory reloads.  Between FR_REGS,
4477      we have to make this at least as expensive as MEMORY_MOVE_COST
4478      to avoid spectacularly poor register class preferencing.  */
4479   if (mode == XFmode)
4480     {
4481       if (to != GR_REGS || from != GR_REGS)
4482         return MEMORY_MOVE_COST (mode, to, 0);
4483       else
4484         return 3;
4485     }
4486
4487   switch (to)
4488     {
4489     case PR_REGS:
4490       /* Moving between PR registers takes two insns.  */
4491       if (from == PR_REGS)
4492         return 3;
4493       /* Moving between PR and anything but GR is impossible.  */
4494       if (from != GR_REGS)
4495         return MEMORY_MOVE_COST (mode, to, 0);
4496       break;
4497
4498     case BR_REGS:
4499       /* Moving between BR and anything but GR is impossible.  */
4500       if (from != GR_REGS && from != GR_AND_BR_REGS)
4501         return MEMORY_MOVE_COST (mode, to, 0);
4502       break;
4503
4504     case AR_I_REGS:
4505     case AR_M_REGS:
4506       /* Moving between AR and anything but GR is impossible.  */
4507       if (from != GR_REGS)
4508         return MEMORY_MOVE_COST (mode, to, 0);
4509       break;
4510
4511     case GR_REGS:
4512     case FR_REGS:
4513     case GR_AND_FR_REGS:
4514     case GR_AND_BR_REGS:
4515     case ALL_REGS:
4516       break;
4517
4518     default:
4519       abort ();
4520     }
4521
4522   return 2;
4523 }
4524
4525 /* This function returns the register class required for a secondary
4526    register when copying between one of the registers in CLASS, and X,
4527    using MODE.  A return value of NO_REGS means that no secondary register
4528    is required.  */
4529
4530 enum reg_class
4531 ia64_secondary_reload_class (enum reg_class class,
4532                              enum machine_mode mode ATTRIBUTE_UNUSED, rtx x)
4533 {
4534   int regno = -1;
4535
4536   if (GET_CODE (x) == REG || GET_CODE (x) == SUBREG)
4537     regno = true_regnum (x);
4538
4539   switch (class)
4540     {
4541     case BR_REGS:
4542     case AR_M_REGS:
4543     case AR_I_REGS:
4544       /* ??? BR<->BR register copies can happen due to a bad gcse/cse/global
4545          interaction.  We end up with two pseudos with overlapping lifetimes
4546          both of which are equiv to the same constant, and both which need
4547          to be in BR_REGS.  This seems to be a cse bug.  cse_basic_block_end
4548          changes depending on the path length, which means the qty_first_reg
4549          check in make_regs_eqv can give different answers at different times.
4550          At some point I'll probably need a reload_indi pattern to handle
4551          this.
4552
4553          We can also get GR_AND_FR_REGS to BR_REGS/AR_REGS copies, where we
4554          wound up with a FP register from GR_AND_FR_REGS.  Extend that to all
4555          non-general registers for good measure.  */
4556       if (regno >= 0 && ! GENERAL_REGNO_P (regno))
4557         return GR_REGS;
4558
4559       /* This is needed if a pseudo used as a call_operand gets spilled to a
4560          stack slot.  */
4561       if (GET_CODE (x) == MEM)
4562         return GR_REGS;
4563       break;
4564
4565     case FR_REGS:
4566       /* Need to go through general registers to get to other class regs.  */
4567       if (regno >= 0 && ! (FR_REGNO_P (regno) || GENERAL_REGNO_P (regno)))
4568         return GR_REGS;
4569
4570       /* This can happen when a paradoxical subreg is an operand to the
4571          muldi3 pattern.  */
4572       /* ??? This shouldn't be necessary after instruction scheduling is
4573          enabled, because paradoxical subregs are not accepted by
4574          register_operand when INSN_SCHEDULING is defined.  Or alternatively,
4575          stop the paradoxical subreg stupidity in the *_operand functions
4576          in recog.c.  */
4577       if (GET_CODE (x) == MEM
4578           && (GET_MODE (x) == SImode || GET_MODE (x) == HImode
4579               || GET_MODE (x) == QImode))
4580         return GR_REGS;
4581
4582       /* This can happen because of the ior/and/etc patterns that accept FP
4583          registers as operands.  If the third operand is a constant, then it
4584          needs to be reloaded into a FP register.  */
4585       if (GET_CODE (x) == CONST_INT)
4586         return GR_REGS;
4587
4588       /* This can happen because of register elimination in a muldi3 insn.
4589          E.g. `26107 * (unsigned long)&u'.  */
4590       if (GET_CODE (x) == PLUS)
4591         return GR_REGS;
4592       break;
4593
4594     case PR_REGS:
4595       /* ??? This happens if we cse/gcse a BImode value across a call,
4596          and the function has a nonlocal goto.  This is because global
4597          does not allocate call crossing pseudos to hard registers when
4598          current_function_has_nonlocal_goto is true.  This is relatively
4599          common for C++ programs that use exceptions.  To reproduce,
4600          return NO_REGS and compile libstdc++.  */
4601       if (GET_CODE (x) == MEM)
4602         return GR_REGS;
4603
4604       /* This can happen when we take a BImode subreg of a DImode value,
4605          and that DImode value winds up in some non-GR register.  */
4606       if (regno >= 0 && ! GENERAL_REGNO_P (regno) && ! PR_REGNO_P (regno))
4607         return GR_REGS;
4608       break;
4609
4610     default:
4611       break;
4612     }
4613
4614   return NO_REGS;
4615 }
4616
4617 \f
4618 /* Emit text to declare externally defined variables and functions, because
4619    the Intel assembler does not support undefined externals.  */
4620
4621 void
4622 ia64_asm_output_external (FILE *file, tree decl, const char *name)
4623 {
4624   int save_referenced;
4625
4626   /* GNU as does not need anything here, but the HP linker does need
4627      something for external functions.  */
4628
4629   if (TARGET_GNU_AS
4630       && (!TARGET_HPUX_LD
4631           || TREE_CODE (decl) != FUNCTION_DECL
4632           || strstr (name, "__builtin_") == name))
4633     return;
4634
4635   /* ??? The Intel assembler creates a reference that needs to be satisfied by
4636      the linker when we do this, so we need to be careful not to do this for
4637      builtin functions which have no library equivalent.  Unfortunately, we
4638      can't tell here whether or not a function will actually be called by
4639      expand_expr, so we pull in library functions even if we may not need
4640      them later.  */
4641   if (! strcmp (name, "__builtin_next_arg")
4642       || ! strcmp (name, "alloca")
4643       || ! strcmp (name, "__builtin_constant_p")
4644       || ! strcmp (name, "__builtin_args_info"))
4645     return;
4646
4647   if (TARGET_HPUX_LD)
4648     ia64_hpux_add_extern_decl (decl);
4649   else
4650     {
4651       /* assemble_name will set TREE_SYMBOL_REFERENCED, so we must save and
4652          restore it.  */
4653       save_referenced = TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl));
4654       if (TREE_CODE (decl) == FUNCTION_DECL)
4655         ASM_OUTPUT_TYPE_DIRECTIVE (file, name, "function");
4656       (*targetm.asm_out.globalize_label) (file, name);
4657       TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)) = save_referenced;
4658     }
4659 }
4660 \f
4661 /* Parse the -mfixed-range= option string.  */
4662
4663 static void
4664 fix_range (const char *const_str)
4665 {
4666   int i, first, last;
4667   char *str, *dash, *comma;
4668
4669   /* str must be of the form REG1'-'REG2{,REG1'-'REG} where REG1 and
4670      REG2 are either register names or register numbers.  The effect
4671      of this option is to mark the registers in the range from REG1 to
4672      REG2 as ``fixed'' so they won't be used by the compiler.  This is
4673      used, e.g., to ensure that kernel mode code doesn't use f32-f127.  */
4674
4675   i = strlen (const_str);
4676   str = (char *) alloca (i + 1);
4677   memcpy (str, const_str, i + 1);
4678
4679   while (1)
4680     {
4681       dash = strchr (str, '-');
4682       if (!dash)
4683         {
4684           warning ("value of -mfixed-range must have form REG1-REG2");
4685           return;
4686         }
4687       *dash = '\0';
4688
4689       comma = strchr (dash + 1, ',');
4690       if (comma)
4691         *comma = '\0';
4692
4693       first = decode_reg_name (str);
4694       if (first < 0)
4695         {
4696           warning ("unknown register name: %s", str);
4697           return;
4698         }
4699
4700       last = decode_reg_name (dash + 1);
4701       if (last < 0)
4702         {
4703           warning ("unknown register name: %s", dash + 1);
4704           return;
4705         }
4706
4707       *dash = '-';
4708
4709       if (first > last)
4710         {
4711           warning ("%s-%s is an empty range", str, dash + 1);
4712           return;
4713         }
4714
4715       for (i = first; i <= last; ++i)
4716         fixed_regs[i] = call_used_regs[i] = 1;
4717
4718       if (!comma)
4719         break;
4720
4721       *comma = ',';
4722       str = comma + 1;
4723     }
4724 }
4725
4726 static struct machine_function *
4727 ia64_init_machine_status (void)
4728 {
4729   return ggc_alloc_cleared (sizeof (struct machine_function));
4730 }
4731
4732 /* Handle TARGET_OPTIONS switches.  */
4733
4734 void
4735 ia64_override_options (void)
4736 {
4737   static struct pta
4738     {
4739       const char *const name;           /* processor name or nickname.  */
4740       const enum processor_type processor;
4741     }
4742   const processor_alias_table[] =
4743     {
4744       {"itanium", PROCESSOR_ITANIUM},
4745       {"itanium1", PROCESSOR_ITANIUM},
4746       {"merced", PROCESSOR_ITANIUM},
4747       {"itanium2", PROCESSOR_ITANIUM2},
4748       {"mckinley", PROCESSOR_ITANIUM2},
4749     };
4750
4751   int const pta_size = ARRAY_SIZE (processor_alias_table);
4752   int i;
4753
4754   if (TARGET_AUTO_PIC)
4755     target_flags |= MASK_CONST_GP;
4756
4757   if (TARGET_INLINE_FLOAT_DIV_LAT && TARGET_INLINE_FLOAT_DIV_THR)
4758     {
4759       if ((target_flags_explicit & MASK_INLINE_FLOAT_DIV_LAT)
4760            && (target_flags_explicit & MASK_INLINE_FLOAT_DIV_THR))
4761         {
4762           warning ("cannot optimize floating point division for both latency and throughput");
4763           target_flags &= ~MASK_INLINE_FLOAT_DIV_THR;
4764         }
4765       else 
4766         {
4767           if (target_flags_explicit & MASK_INLINE_FLOAT_DIV_THR)
4768             target_flags &= ~MASK_INLINE_FLOAT_DIV_LAT;
4769           else
4770             target_flags &= ~MASK_INLINE_FLOAT_DIV_THR;
4771         }
4772     }
4773
4774   if (TARGET_INLINE_INT_DIV_LAT && TARGET_INLINE_INT_DIV_THR)
4775     {
4776       if ((target_flags_explicit & MASK_INLINE_INT_DIV_LAT)
4777            && (target_flags_explicit & MASK_INLINE_INT_DIV_THR))
4778         {
4779           warning ("cannot optimize integer division for both latency and throughput");
4780           target_flags &= ~MASK_INLINE_INT_DIV_THR;
4781         }
4782       else 
4783         {
4784           if (target_flags_explicit & MASK_INLINE_INT_DIV_THR)
4785             target_flags &= ~MASK_INLINE_INT_DIV_LAT;
4786           else
4787             target_flags &= ~MASK_INLINE_INT_DIV_THR;
4788         }
4789     }
4790
4791   if (TARGET_INLINE_SQRT_LAT && TARGET_INLINE_SQRT_THR)
4792     {
4793       if ((target_flags_explicit & MASK_INLINE_SQRT_LAT)
4794            && (target_flags_explicit & MASK_INLINE_SQRT_THR))
4795         {
4796           warning ("cannot optimize square root for both latency and throughput");
4797           target_flags &= ~MASK_INLINE_SQRT_THR;
4798         }
4799       else 
4800         {
4801           if (target_flags_explicit & MASK_INLINE_SQRT_THR)
4802             target_flags &= ~MASK_INLINE_SQRT_LAT;
4803           else
4804             target_flags &= ~MASK_INLINE_SQRT_THR;
4805         }
4806     }
4807
4808   if (TARGET_INLINE_SQRT_LAT)
4809     {
4810       warning ("not yet implemented: latency-optimized inline square root");
4811       target_flags &= ~MASK_INLINE_SQRT_LAT;
4812     }
4813
4814   if (ia64_fixed_range_string)
4815     fix_range (ia64_fixed_range_string);
4816
4817   if (ia64_tls_size_string)
4818     {
4819       char *end;
4820       unsigned long tmp = strtoul (ia64_tls_size_string, &end, 10);
4821       if (*end || (tmp != 14 && tmp != 22 && tmp != 64))
4822         error ("bad value (%s) for -mtls-size= switch", ia64_tls_size_string);
4823       else
4824         ia64_tls_size = tmp;
4825     }
4826
4827   if (!ia64_tune_string)
4828     ia64_tune_string = "itanium2";
4829
4830   for (i = 0; i < pta_size; i++)
4831     if (! strcmp (ia64_tune_string, processor_alias_table[i].name))
4832       {
4833         ia64_tune = processor_alias_table[i].processor;
4834         break;
4835       }
4836
4837   if (i == pta_size)
4838     error ("bad value (%s) for -tune= switch", ia64_tune_string);
4839
4840   ia64_flag_schedule_insns2 = flag_schedule_insns_after_reload;
4841   flag_schedule_insns_after_reload = 0;
4842
4843   /* Variable tracking should be run after all optimizations which change order
4844      of insns.  It also needs a valid CFG.  */
4845   ia64_flag_var_tracking = flag_var_tracking;
4846   flag_var_tracking = 0;
4847
4848   ia64_section_threshold = g_switch_set ? g_switch_value : IA64_DEFAULT_GVALUE;
4849
4850   init_machine_status = ia64_init_machine_status;
4851 }
4852 \f
4853 static enum attr_itanium_class ia64_safe_itanium_class (rtx);
4854 static enum attr_type ia64_safe_type (rtx);
4855
4856 static enum attr_itanium_class
4857 ia64_safe_itanium_class (rtx insn)
4858 {
4859   if (recog_memoized (insn) >= 0)
4860     return get_attr_itanium_class (insn);
4861   else
4862     return ITANIUM_CLASS_UNKNOWN;
4863 }
4864
4865 static enum attr_type
4866 ia64_safe_type (rtx insn)
4867 {
4868   if (recog_memoized (insn) >= 0)
4869     return get_attr_type (insn);
4870   else
4871     return TYPE_UNKNOWN;
4872 }
4873 \f
4874 /* The following collection of routines emit instruction group stop bits as
4875    necessary to avoid dependencies.  */
4876
4877 /* Need to track some additional registers as far as serialization is
4878    concerned so we can properly handle br.call and br.ret.  We could
4879    make these registers visible to gcc, but since these registers are
4880    never explicitly used in gcc generated code, it seems wasteful to
4881    do so (plus it would make the call and return patterns needlessly
4882    complex).  */
4883 #define REG_RP          (BR_REG (0))
4884 #define REG_AR_CFM      (FIRST_PSEUDO_REGISTER + 1)
4885 /* This is used for volatile asms which may require a stop bit immediately
4886    before and after them.  */
4887 #define REG_VOLATILE    (FIRST_PSEUDO_REGISTER + 2)
4888 #define AR_UNAT_BIT_0   (FIRST_PSEUDO_REGISTER + 3)
4889 #define NUM_REGS        (AR_UNAT_BIT_0 + 64)
4890
4891 /* For each register, we keep track of how it has been written in the
4892    current instruction group.
4893
4894    If a register is written unconditionally (no qualifying predicate),
4895    WRITE_COUNT is set to 2 and FIRST_PRED is ignored.
4896
4897    If a register is written if its qualifying predicate P is true, we
4898    set WRITE_COUNT to 1 and FIRST_PRED to P.  Later on, the same register
4899    may be written again by the complement of P (P^1) and when this happens,
4900    WRITE_COUNT gets set to 2.
4901
4902    The result of this is that whenever an insn attempts to write a register
4903    whose WRITE_COUNT is two, we need to issue an insn group barrier first.
4904
4905    If a predicate register is written by a floating-point insn, we set
4906    WRITTEN_BY_FP to true.
4907
4908    If a predicate register is written by an AND.ORCM we set WRITTEN_BY_AND
4909    to true; if it was written by an OR.ANDCM we set WRITTEN_BY_OR to true.  */
4910
4911 struct reg_write_state
4912 {
4913   unsigned int write_count : 2;
4914   unsigned int first_pred : 16;
4915   unsigned int written_by_fp : 1;
4916   unsigned int written_by_and : 1;
4917   unsigned int written_by_or : 1;
4918 };
4919
4920 /* Cumulative info for the current instruction group.  */
4921 struct reg_write_state rws_sum[NUM_REGS];
4922 /* Info for the current instruction.  This gets copied to rws_sum after a
4923    stop bit is emitted.  */
4924 struct reg_write_state rws_insn[NUM_REGS];
4925
4926 /* Indicates whether this is the first instruction after a stop bit,
4927    in which case we don't need another stop bit.  Without this, we hit
4928    the abort in ia64_variable_issue when scheduling an alloc.  */
4929 static int first_instruction;
4930
4931 /* Misc flags needed to compute RAW/WAW dependencies while we are traversing
4932    RTL for one instruction.  */
4933 struct reg_flags
4934 {
4935   unsigned int is_write : 1;    /* Is register being written?  */
4936   unsigned int is_fp : 1;       /* Is register used as part of an fp op?  */
4937   unsigned int is_branch : 1;   /* Is register used as part of a branch?  */
4938   unsigned int is_and : 1;      /* Is register used as part of and.orcm?  */
4939   unsigned int is_or : 1;       /* Is register used as part of or.andcm?  */
4940   unsigned int is_sibcall : 1;  /* Is this a sibling or normal call?  */
4941 };
4942
4943 static void rws_update (struct reg_write_state *, int, struct reg_flags, int);
4944 static int rws_access_regno (int, struct reg_flags, int);
4945 static int rws_access_reg (rtx, struct reg_flags, int);
4946 static void update_set_flags (rtx, struct reg_flags *, int *, rtx *);
4947 static int set_src_needs_barrier (rtx, struct reg_flags, int, rtx);
4948 static int rtx_needs_barrier (rtx, struct reg_flags, int);
4949 static void init_insn_group_barriers (void);
4950 static int group_barrier_needed_p (rtx);
4951 static int safe_group_barrier_needed_p (rtx);
4952
4953 /* Update *RWS for REGNO, which is being written by the current instruction,
4954    with predicate PRED, and associated register flags in FLAGS.  */
4955
4956 static void
4957 rws_update (struct reg_write_state *rws, int regno, struct reg_flags flags, int pred)
4958 {
4959   if (pred)
4960     rws[regno].write_count++;
4961   else
4962     rws[regno].write_count = 2;
4963   rws[regno].written_by_fp |= flags.is_fp;
4964   /* ??? Not tracking and/or across differing predicates.  */
4965   rws[regno].written_by_and = flags.is_and;
4966   rws[regno].written_by_or = flags.is_or;
4967   rws[regno].first_pred = pred;
4968 }
4969
4970 /* Handle an access to register REGNO of type FLAGS using predicate register
4971    PRED.  Update rws_insn and rws_sum arrays.  Return 1 if this access creates
4972    a dependency with an earlier instruction in the same group.  */
4973
4974 static int
4975 rws_access_regno (int regno, struct reg_flags flags, int pred)
4976 {
4977   int need_barrier = 0;
4978
4979   if (regno >= NUM_REGS)
4980     abort ();
4981
4982   if (! PR_REGNO_P (regno))
4983     flags.is_and = flags.is_or = 0;
4984
4985   if (flags.is_write)
4986     {
4987       int write_count;
4988
4989       /* One insn writes same reg multiple times?  */
4990       if (rws_insn[regno].write_count > 0)
4991         abort ();
4992
4993       /* Update info for current instruction.  */
4994       rws_update (rws_insn, regno, flags, pred);
4995       write_count = rws_sum[regno].write_count;
4996
4997       switch (write_count)
4998         {
4999         case 0:
5000           /* The register has not been written yet.  */
5001           rws_update (rws_sum, regno, flags, pred);
5002           break;
5003
5004         case 1:
5005           /* The register has been written via a predicate.  If this is
5006              not a complementary predicate, then we need a barrier.  */
5007           /* ??? This assumes that P and P+1 are always complementary
5008              predicates for P even.  */
5009           if (flags.is_and && rws_sum[regno].written_by_and)
5010             ;
5011           else if (flags.is_or && rws_sum[regno].written_by_or)
5012             ;
5013           else if ((rws_sum[regno].first_pred ^ 1) != pred)
5014             need_barrier = 1;
5015           rws_update (rws_sum, regno, flags, pred);
5016           break;
5017
5018         case 2:
5019           /* The register has been unconditionally written already.  We
5020              need a barrier.  */
5021           if (flags.is_and && rws_sum[regno].written_by_and)
5022             ;
5023           else if (flags.is_or && rws_sum[regno].written_by_or)
5024             ;
5025           else
5026             need_barrier = 1;
5027           rws_sum[regno].written_by_and = flags.is_and;
5028           rws_sum[regno].written_by_or = flags.is_or;
5029           break;
5030
5031         default:
5032           abort ();
5033         }
5034     }
5035   else
5036     {
5037       if (flags.is_branch)
5038         {
5039           /* Branches have several RAW exceptions that allow to avoid
5040              barriers.  */
5041
5042           if (REGNO_REG_CLASS (regno) == BR_REGS || regno == AR_PFS_REGNUM)
5043             /* RAW dependencies on branch regs are permissible as long
5044                as the writer is a non-branch instruction.  Since we
5045                never generate code that uses a branch register written
5046                by a branch instruction, handling this case is
5047                easy.  */
5048             return 0;
5049
5050           if (REGNO_REG_CLASS (regno) == PR_REGS
5051               && ! rws_sum[regno].written_by_fp)
5052             /* The predicates of a branch are available within the
5053                same insn group as long as the predicate was written by
5054                something other than a floating-point instruction.  */
5055             return 0;
5056         }
5057
5058       if (flags.is_and && rws_sum[regno].written_by_and)
5059         return 0;
5060       if (flags.is_or && rws_sum[regno].written_by_or)
5061         return 0;
5062
5063       switch (rws_sum[regno].write_count)
5064         {
5065         case 0:
5066           /* The register has not been written yet.  */
5067           break;
5068
5069         case 1:
5070           /* The register has been written via a predicate.  If this is
5071              not a complementary predicate, then we need a barrier.  */
5072           /* ??? This assumes that P and P+1 are always complementary
5073              predicates for P even.  */
5074           if ((rws_sum[regno].first_pred ^ 1) != pred)
5075             need_barrier = 1;
5076           break;
5077
5078         case 2:
5079           /* The register has been unconditionally written already.  We
5080              need a barrier.  */
5081           need_barrier = 1;
5082           break;
5083
5084         default:
5085           abort ();
5086         }
5087     }
5088
5089   return need_barrier;
5090 }
5091
5092 static int
5093 rws_access_reg (rtx reg, struct reg_flags flags, int pred)
5094 {
5095   int regno = REGNO (reg);
5096   int n = HARD_REGNO_NREGS (REGNO (reg), GET_MODE (reg));
5097
5098   if (n == 1)
5099     return rws_access_regno (regno, flags, pred);
5100   else
5101     {
5102       int need_barrier = 0;
5103       while (--n >= 0)
5104         need_barrier |= rws_access_regno (regno + n, flags, pred);
5105       return need_barrier;
5106     }
5107 }
5108
5109 /* Examine X, which is a SET rtx, and update the flags, the predicate, and
5110    the condition, stored in *PFLAGS, *PPRED and *PCOND.  */
5111
5112 static void
5113 update_set_flags (rtx x, struct reg_flags *pflags, int *ppred, rtx *pcond)
5114 {
5115   rtx src = SET_SRC (x);
5116
5117   *pcond = 0;
5118
5119   switch (GET_CODE (src))
5120     {
5121     case CALL:
5122       return;
5123
5124     case IF_THEN_ELSE:
5125       if (SET_DEST (x) == pc_rtx)
5126         /* X is a conditional branch.  */
5127         return;
5128       else
5129         {
5130           int is_complemented = 0;
5131
5132           /* X is a conditional move.  */
5133           rtx cond = XEXP (src, 0);
5134           if (GET_CODE (cond) == EQ)
5135             is_complemented = 1;
5136           cond = XEXP (cond, 0);
5137           if (GET_CODE (cond) != REG
5138               && REGNO_REG_CLASS (REGNO (cond)) != PR_REGS)
5139             abort ();
5140           *pcond = cond;
5141           if (XEXP (src, 1) == SET_DEST (x)
5142               || XEXP (src, 2) == SET_DEST (x))
5143             {
5144               /* X is a conditional move that conditionally writes the
5145                  destination.  */
5146
5147               /* We need another complement in this case.  */
5148               if (XEXP (src, 1) == SET_DEST (x))
5149                 is_complemented = ! is_complemented;
5150
5151               *ppred = REGNO (cond);
5152               if (is_complemented)
5153                 ++*ppred;
5154             }
5155
5156           /* ??? If this is a conditional write to the dest, then this
5157              instruction does not actually read one source.  This probably
5158              doesn't matter, because that source is also the dest.  */
5159           /* ??? Multiple writes to predicate registers are allowed
5160              if they are all AND type compares, or if they are all OR
5161              type compares.  We do not generate such instructions
5162              currently.  */
5163         }
5164       /* ... fall through ...  */
5165
5166     default:
5167       if (COMPARISON_P (src)
5168           && GET_MODE_CLASS (GET_MODE (XEXP (src, 0))) == MODE_FLOAT)
5169         /* Set pflags->is_fp to 1 so that we know we're dealing
5170            with a floating point comparison when processing the
5171            destination of the SET.  */
5172         pflags->is_fp = 1;
5173
5174       /* Discover if this is a parallel comparison.  We only handle
5175          and.orcm and or.andcm at present, since we must retain a
5176          strict inverse on the predicate pair.  */
5177       else if (GET_CODE (src) == AND)
5178         pflags->is_and = 1;
5179       else if (GET_CODE (src) == IOR)
5180         pflags->is_or = 1;
5181
5182       break;
5183     }
5184 }
5185
5186 /* Subroutine of rtx_needs_barrier; this function determines whether the
5187    source of a given SET rtx found in X needs a barrier.  FLAGS and PRED
5188    are as in rtx_needs_barrier.  COND is an rtx that holds the condition
5189    for this insn.  */
5190
5191 static int
5192 set_src_needs_barrier (rtx x, struct reg_flags flags, int pred, rtx cond)
5193 {
5194   int need_barrier = 0;
5195   rtx dst;
5196   rtx src = SET_SRC (x);
5197
5198   if (GET_CODE (src) == CALL)
5199     /* We don't need to worry about the result registers that
5200        get written by subroutine call.  */
5201     return rtx_needs_barrier (src, flags, pred);
5202   else if (SET_DEST (x) == pc_rtx)
5203     {
5204       /* X is a conditional branch.  */
5205       /* ??? This seems redundant, as the caller sets this bit for
5206          all JUMP_INSNs.  */
5207       flags.is_branch = 1;
5208       return rtx_needs_barrier (src, flags, pred);
5209     }
5210
5211   need_barrier = rtx_needs_barrier (src, flags, pred);
5212
5213   /* This instruction unconditionally uses a predicate register.  */
5214   if (cond)
5215     need_barrier |= rws_access_reg (cond, flags, 0);
5216
5217   dst = SET_DEST (x);
5218   if (GET_CODE (dst) == ZERO_EXTRACT)
5219     {
5220       need_barrier |= rtx_needs_barrier (XEXP (dst, 1), flags, pred);
5221       need_barrier |= rtx_needs_barrier (XEXP (dst, 2), flags, pred);
5222       dst = XEXP (dst, 0);
5223     }
5224   return need_barrier;
5225 }
5226
5227 /* Handle an access to rtx X of type FLAGS using predicate register
5228    PRED.  Return 1 if this access creates a dependency with an earlier
5229    instruction in the same group.  */
5230
5231 static int
5232 rtx_needs_barrier (rtx x, struct reg_flags flags, int pred)
5233 {
5234   int i, j;
5235   int is_complemented = 0;
5236   int need_barrier = 0;
5237   const char *format_ptr;
5238   struct reg_flags new_flags;
5239   rtx cond = 0;
5240
5241   if (! x)
5242     return 0;
5243
5244   new_flags = flags;
5245
5246   switch (GET_CODE (x))
5247     {
5248     case SET:
5249       update_set_flags (x, &new_flags, &pred, &cond);
5250       need_barrier = set_src_needs_barrier (x, new_flags, pred, cond);
5251       if (GET_CODE (SET_SRC (x)) != CALL)
5252         {
5253           new_flags.is_write = 1;
5254           need_barrier |= rtx_needs_barrier (SET_DEST (x), new_flags, pred);
5255         }
5256       break;
5257
5258     case CALL:
5259       new_flags.is_write = 0;
5260       need_barrier |= rws_access_regno (AR_EC_REGNUM, new_flags, pred);
5261
5262       /* Avoid multiple register writes, in case this is a pattern with
5263          multiple CALL rtx.  This avoids an abort in rws_access_reg.  */
5264       if (! flags.is_sibcall && ! rws_insn[REG_AR_CFM].write_count)
5265         {
5266           new_flags.is_write = 1;
5267           need_barrier |= rws_access_regno (REG_RP, new_flags, pred);
5268           need_barrier |= rws_access_regno (AR_PFS_REGNUM, new_flags, pred);
5269           need_barrier |= rws_access_regno (REG_AR_CFM, new_flags, pred);
5270         }
5271       break;
5272
5273     case COND_EXEC:
5274       /* X is a predicated instruction.  */
5275
5276       cond = COND_EXEC_TEST (x);
5277       if (pred)
5278         abort ();
5279       need_barrier = rtx_needs_barrier (cond, flags, 0);
5280
5281       if (GET_CODE (cond) == EQ)
5282         is_complemented = 1;
5283       cond = XEXP (cond, 0);
5284       if (GET_CODE (cond) != REG
5285           && REGNO_REG_CLASS (REGNO (cond)) != PR_REGS)
5286         abort ();
5287       pred = REGNO (cond);
5288       if (is_complemented)
5289         ++pred;
5290
5291       need_barrier |= rtx_needs_barrier (COND_EXEC_CODE (x), flags, pred);
5292       return need_barrier;
5293
5294     case CLOBBER:
5295     case USE:
5296       /* Clobber & use are for earlier compiler-phases only.  */
5297       break;
5298
5299     case ASM_OPERANDS:
5300     case ASM_INPUT:
5301       /* We always emit stop bits for traditional asms.  We emit stop bits
5302          for volatile extended asms if TARGET_VOL_ASM_STOP is true.  */
5303       if (GET_CODE (x) != ASM_OPERANDS
5304           || (MEM_VOLATILE_P (x) && TARGET_VOL_ASM_STOP))
5305         {
5306           /* Avoid writing the register multiple times if we have multiple
5307              asm outputs.  This avoids an abort in rws_access_reg.  */
5308           if (! rws_insn[REG_VOLATILE].write_count)
5309             {
5310               new_flags.is_write = 1;
5311               rws_access_regno (REG_VOLATILE, new_flags, pred);
5312             }
5313           return 1;
5314         }
5315
5316       /* For all ASM_OPERANDS, we must traverse the vector of input operands.
5317          We can not just fall through here since then we would be confused
5318          by the ASM_INPUT rtx inside ASM_OPERANDS, which do not indicate
5319          traditional asms unlike their normal usage.  */
5320
5321       for (i = ASM_OPERANDS_INPUT_LENGTH (x) - 1; i >= 0; --i)
5322         if (rtx_needs_barrier (ASM_OPERANDS_INPUT (x, i), flags, pred))
5323           need_barrier = 1;
5324       break;
5325
5326     case PARALLEL:
5327       for (i = XVECLEN (x, 0) - 1; i >= 0; --i)
5328         {
5329           rtx pat = XVECEXP (x, 0, i);
5330           if (GET_CODE (pat) == SET)
5331             {
5332               update_set_flags (pat, &new_flags, &pred, &cond);
5333               need_barrier |= set_src_needs_barrier (pat, new_flags, pred, cond);
5334             }
5335           else if (GET_CODE (pat) == USE
5336                    || GET_CODE (pat) == CALL
5337                    || GET_CODE (pat) == ASM_OPERANDS)
5338             need_barrier |= rtx_needs_barrier (pat, flags, pred);
5339           else if (GET_CODE (pat) != CLOBBER && GET_CODE (pat) != RETURN)
5340             abort ();
5341         }
5342       for (i = XVECLEN (x, 0) - 1; i >= 0; --i)
5343         {
5344           rtx pat = XVECEXP (x, 0, i);
5345           if (GET_CODE (pat) == SET)
5346             {
5347               if (GET_CODE (SET_SRC (pat)) != CALL)
5348                 {
5349                   new_flags.is_write = 1;
5350                   need_barrier |= rtx_needs_barrier (SET_DEST (pat), new_flags,
5351                                                      pred);
5352                 }
5353             }
5354           else if (GET_CODE (pat) == CLOBBER || GET_CODE (pat) == RETURN)
5355             need_barrier |= rtx_needs_barrier (pat, flags, pred);
5356         }
5357       break;
5358
5359     case SUBREG:
5360       x = SUBREG_REG (x);
5361       /* FALLTHRU */
5362     case REG:
5363       if (REGNO (x) == AR_UNAT_REGNUM)
5364         {
5365           for (i = 0; i < 64; ++i)
5366             need_barrier |= rws_access_regno (AR_UNAT_BIT_0 + i, flags, pred);
5367         }
5368       else
5369         need_barrier = rws_access_reg (x, flags, pred);
5370       break;
5371
5372     case MEM:
5373       /* Find the regs used in memory address computation.  */
5374       new_flags.is_write = 0;
5375       need_barrier = rtx_needs_barrier (XEXP (x, 0), new_flags, pred);
5376       break;
5377
5378     case CONST_INT:   case CONST_DOUBLE:
5379     case SYMBOL_REF:  case LABEL_REF:     case CONST:
5380       break;
5381
5382       /* Operators with side-effects.  */
5383     case POST_INC:    case POST_DEC:
5384       if (GET_CODE (XEXP (x, 0)) != REG)
5385         abort ();
5386
5387       new_flags.is_write = 0;
5388       need_barrier  = rws_access_reg (XEXP (x, 0), new_flags, pred);
5389       new_flags.is_write = 1;
5390       need_barrier |= rws_access_reg (XEXP (x, 0), new_flags, pred);
5391       break;
5392
5393     case POST_MODIFY:
5394       if (GET_CODE (XEXP (x, 0)) != REG)
5395         abort ();
5396
5397       new_flags.is_write = 0;
5398       need_barrier  = rws_access_reg (XEXP (x, 0), new_flags, pred);
5399       need_barrier |= rtx_needs_barrier (XEXP (x, 1), new_flags, pred);
5400       new_flags.is_write = 1;
5401       need_barrier |= rws_access_reg (XEXP (x, 0), new_flags, pred);
5402       break;
5403
5404       /* Handle common unary and binary ops for efficiency.  */
5405     case COMPARE:  case PLUS:    case MINUS:   case MULT:      case DIV:
5406     case MOD:      case UDIV:    case UMOD:    case AND:       case IOR:
5407     case XOR:      case ASHIFT:  case ROTATE:  case ASHIFTRT:  case LSHIFTRT:
5408     case ROTATERT: case SMIN:    case SMAX:    case UMIN:      case UMAX:
5409     case NE:       case EQ:      case GE:      case GT:        case LE:
5410     case LT:       case GEU:     case GTU:     case LEU:       case LTU:
5411       need_barrier = rtx_needs_barrier (XEXP (x, 0), new_flags, pred);
5412       need_barrier |= rtx_needs_barrier (XEXP (x, 1), new_flags, pred);
5413       break;
5414
5415     case NEG:      case NOT:            case SIGN_EXTEND:     case ZERO_EXTEND:
5416     case TRUNCATE: case FLOAT_EXTEND:   case FLOAT_TRUNCATE:  case FLOAT:
5417     case FIX:      case UNSIGNED_FLOAT: case UNSIGNED_FIX:    case ABS:
5418     case SQRT:     case FFS:            case POPCOUNT:
5419       need_barrier = rtx_needs_barrier (XEXP (x, 0), flags, pred);
5420       break;
5421
5422     case UNSPEC:
5423       switch (XINT (x, 1))
5424         {
5425         case UNSPEC_LTOFF_DTPMOD:
5426         case UNSPEC_LTOFF_DTPREL:
5427         case UNSPEC_DTPREL:
5428         case UNSPEC_LTOFF_TPREL:
5429         case UNSPEC_TPREL:
5430         case UNSPEC_PRED_REL_MUTEX:
5431         case UNSPEC_PIC_CALL:
5432         case UNSPEC_MF:
5433         case UNSPEC_FETCHADD_ACQ:
5434         case UNSPEC_BSP_VALUE:
5435         case UNSPEC_FLUSHRS:
5436         case UNSPEC_BUNDLE_SELECTOR:
5437           break;
5438
5439         case UNSPEC_GR_SPILL:
5440         case UNSPEC_GR_RESTORE:
5441           {
5442             HOST_WIDE_INT offset = INTVAL (XVECEXP (x, 0, 1));
5443             HOST_WIDE_INT bit = (offset >> 3) & 63;
5444
5445             need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
5446             new_flags.is_write = (XINT (x, 1) == 1);
5447             need_barrier |= rws_access_regno (AR_UNAT_BIT_0 + bit,
5448                                               new_flags, pred);
5449             break;
5450           }
5451
5452         case UNSPEC_FR_SPILL:
5453         case UNSPEC_FR_RESTORE:
5454         case UNSPEC_GETF_EXP:
5455         case UNSPEC_SETF_EXP:
5456         case UNSPEC_ADDP4:
5457         case UNSPEC_FR_SQRT_RECIP_APPROX:
5458           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
5459           break;
5460
5461         case UNSPEC_FR_RECIP_APPROX:
5462           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
5463           need_barrier |= rtx_needs_barrier (XVECEXP (x, 0, 1), flags, pred);
5464           break;
5465
5466         case UNSPEC_CMPXCHG_ACQ:
5467           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 1), flags, pred);
5468           need_barrier |= rtx_needs_barrier (XVECEXP (x, 0, 2), flags, pred);
5469           break;
5470
5471         default:
5472           abort ();
5473         }
5474       break;
5475
5476     case UNSPEC_VOLATILE:
5477       switch (XINT (x, 1))
5478         {
5479         case UNSPECV_ALLOC:
5480           /* Alloc must always be the first instruction of a group.
5481              We force this by always returning true.  */
5482           /* ??? We might get better scheduling if we explicitly check for
5483              input/local/output register dependencies, and modify the
5484              scheduler so that alloc is always reordered to the start of
5485              the current group.  We could then eliminate all of the
5486              first_instruction code.  */
5487           rws_access_regno (AR_PFS_REGNUM, flags, pred);
5488
5489           new_flags.is_write = 1;
5490           rws_access_regno (REG_AR_CFM, new_flags, pred);
5491           return 1;
5492
5493         case UNSPECV_SET_BSP:
5494           need_barrier = 1;
5495           break;
5496
5497         case UNSPECV_BLOCKAGE:
5498         case UNSPECV_INSN_GROUP_BARRIER:
5499         case UNSPECV_BREAK:
5500         case UNSPECV_PSAC_ALL:
5501         case UNSPECV_PSAC_NORMAL:
5502           return 0;
5503
5504         default:
5505           abort ();
5506         }
5507       break;
5508
5509     case RETURN:
5510       new_flags.is_write = 0;
5511       need_barrier  = rws_access_regno (REG_RP, flags, pred);
5512       need_barrier |= rws_access_regno (AR_PFS_REGNUM, flags, pred);
5513
5514       new_flags.is_write = 1;
5515       need_barrier |= rws_access_regno (AR_EC_REGNUM, new_flags, pred);
5516       need_barrier |= rws_access_regno (REG_AR_CFM, new_flags, pred);
5517       break;
5518
5519     default:
5520       format_ptr = GET_RTX_FORMAT (GET_CODE (x));
5521       for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
5522         switch (format_ptr[i])
5523           {
5524           case '0':     /* unused field */
5525           case 'i':     /* integer */
5526           case 'n':     /* note */
5527           case 'w':     /* wide integer */
5528           case 's':     /* pointer to string */
5529           case 'S':     /* optional pointer to string */
5530             break;
5531
5532           case 'e':
5533             if (rtx_needs_barrier (XEXP (x, i), flags, pred))
5534               need_barrier = 1;
5535             break;
5536
5537           case 'E':
5538             for (j = XVECLEN (x, i) - 1; j >= 0; --j)
5539               if (rtx_needs_barrier (XVECEXP (x, i, j), flags, pred))
5540                 need_barrier = 1;
5541             break;
5542
5543           default:
5544             abort ();
5545           }
5546       break;
5547     }
5548   return need_barrier;
5549 }
5550
5551 /* Clear out the state for group_barrier_needed_p at the start of a
5552    sequence of insns.  */
5553
5554 static void
5555 init_insn_group_barriers (void)
5556 {
5557   memset (rws_sum, 0, sizeof (rws_sum));
5558   first_instruction = 1;
5559 }
5560
5561 /* Given the current state, recorded by previous calls to this function,
5562    determine whether a group barrier (a stop bit) is necessary before INSN.
5563    Return nonzero if so.  */
5564
5565 static int
5566 group_barrier_needed_p (rtx insn)
5567 {
5568   rtx pat;
5569   int need_barrier = 0;
5570   struct reg_flags flags;
5571
5572   memset (&flags, 0, sizeof (flags));
5573   switch (GET_CODE (insn))
5574     {
5575     case NOTE:
5576       break;
5577
5578     case BARRIER:
5579       /* A barrier doesn't imply an instruction group boundary.  */
5580       break;
5581
5582     case CODE_LABEL:
5583       memset (rws_insn, 0, sizeof (rws_insn));
5584       return 1;
5585
5586     case CALL_INSN:
5587       flags.is_branch = 1;
5588       flags.is_sibcall = SIBLING_CALL_P (insn);
5589       memset (rws_insn, 0, sizeof (rws_insn));
5590
5591       /* Don't bundle a call following another call.  */
5592       if ((pat = prev_active_insn (insn))
5593           && GET_CODE (pat) == CALL_INSN)
5594         {
5595           need_barrier = 1;
5596           break;
5597         }
5598
5599       need_barrier = rtx_needs_barrier (PATTERN (insn), flags, 0);
5600       break;
5601
5602     case JUMP_INSN:
5603       flags.is_branch = 1;
5604
5605       /* Don't bundle a jump following a call.  */
5606       if ((pat = prev_active_insn (insn))
5607           && GET_CODE (pat) == CALL_INSN)
5608         {
5609           need_barrier = 1;
5610           break;
5611         }
5612       /* FALLTHRU */
5613
5614     case INSN:
5615       if (GET_CODE (PATTERN (insn)) == USE
5616           || GET_CODE (PATTERN (insn)) == CLOBBER)
5617         /* Don't care about USE and CLOBBER "insns"---those are used to
5618            indicate to the optimizer that it shouldn't get rid of
5619            certain operations.  */
5620         break;
5621
5622       pat = PATTERN (insn);
5623
5624       /* Ug.  Hack hacks hacked elsewhere.  */
5625       switch (recog_memoized (insn))
5626         {
5627           /* We play dependency tricks with the epilogue in order
5628              to get proper schedules.  Undo this for dv analysis.  */
5629         case CODE_FOR_epilogue_deallocate_stack:
5630         case CODE_FOR_prologue_allocate_stack:
5631           pat = XVECEXP (pat, 0, 0);
5632           break;
5633
5634           /* The pattern we use for br.cloop confuses the code above.
5635              The second element of the vector is representative.  */
5636         case CODE_FOR_doloop_end_internal:
5637           pat = XVECEXP (pat, 0, 1);
5638           break;
5639
5640           /* Doesn't generate code.  */
5641         case CODE_FOR_pred_rel_mutex:
5642         case CODE_FOR_prologue_use:
5643           return 0;
5644
5645         default:
5646           break;
5647         }
5648
5649       memset (rws_insn, 0, sizeof (rws_insn));
5650       need_barrier = rtx_needs_barrier (pat, flags, 0);
5651
5652       /* Check to see if the previous instruction was a volatile
5653          asm.  */
5654       if (! need_barrier)
5655         need_barrier = rws_access_regno (REG_VOLATILE, flags, 0);
5656       break;
5657
5658     default:
5659       abort ();
5660     }
5661
5662   if (first_instruction && INSN_P (insn)
5663       && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
5664       && GET_CODE (PATTERN (insn)) != USE
5665       && GET_CODE (PATTERN (insn)) != CLOBBER)
5666     {
5667       need_barrier = 0;
5668       first_instruction = 0;
5669     }
5670
5671   return need_barrier;
5672 }
5673
5674 /* Like group_barrier_needed_p, but do not clobber the current state.  */
5675
5676 static int
5677 safe_group_barrier_needed_p (rtx insn)
5678 {
5679   struct reg_write_state rws_saved[NUM_REGS];
5680   int saved_first_instruction;
5681   int t;
5682
5683   memcpy (rws_saved, rws_sum, NUM_REGS * sizeof *rws_saved);
5684   saved_first_instruction = first_instruction;
5685
5686   t = group_barrier_needed_p (insn);
5687
5688   memcpy (rws_sum, rws_saved, NUM_REGS * sizeof *rws_saved);
5689   first_instruction = saved_first_instruction;
5690
5691   return t;
5692 }
5693
5694 /* Scan the current function and insert stop bits as necessary to
5695    eliminate dependencies.  This function assumes that a final
5696    instruction scheduling pass has been run which has already
5697    inserted most of the necessary stop bits.  This function only
5698    inserts new ones at basic block boundaries, since these are
5699    invisible to the scheduler.  */
5700
5701 static void
5702 emit_insn_group_barriers (FILE *dump)
5703 {
5704   rtx insn;
5705   rtx last_label = 0;
5706   int insns_since_last_label = 0;
5707
5708   init_insn_group_barriers ();
5709
5710   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
5711     {
5712       if (GET_CODE (insn) == CODE_LABEL)
5713         {
5714           if (insns_since_last_label)
5715             last_label = insn;
5716           insns_since_last_label = 0;
5717         }
5718       else if (GET_CODE (insn) == NOTE
5719                && NOTE_LINE_NUMBER (insn) == NOTE_INSN_BASIC_BLOCK)
5720         {
5721           if (insns_since_last_label)
5722             last_label = insn;
5723           insns_since_last_label = 0;
5724         }
5725       else if (GET_CODE (insn) == INSN
5726                && GET_CODE (PATTERN (insn)) == UNSPEC_VOLATILE
5727                && XINT (PATTERN (insn), 1) == UNSPECV_INSN_GROUP_BARRIER)
5728         {
5729           init_insn_group_barriers ();
5730           last_label = 0;
5731         }
5732       else if (INSN_P (insn))
5733         {
5734           insns_since_last_label = 1;
5735
5736           if (group_barrier_needed_p (insn))
5737             {
5738               if (last_label)
5739                 {
5740                   if (dump)
5741                     fprintf (dump, "Emitting stop before label %d\n",
5742                              INSN_UID (last_label));
5743                   emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), last_label);
5744                   insn = last_label;
5745
5746                   init_insn_group_barriers ();
5747                   last_label = 0;
5748                 }
5749             }
5750         }
5751     }
5752 }
5753
5754 /* Like emit_insn_group_barriers, but run if no final scheduling pass was run.
5755    This function has to emit all necessary group barriers.  */
5756
5757 static void
5758 emit_all_insn_group_barriers (FILE *dump ATTRIBUTE_UNUSED)
5759 {
5760   rtx insn;
5761
5762   init_insn_group_barriers ();
5763
5764   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
5765     {
5766       if (GET_CODE (insn) == BARRIER)
5767         {
5768           rtx last = prev_active_insn (insn);
5769
5770           if (! last)
5771             continue;
5772           if (GET_CODE (last) == JUMP_INSN
5773               && GET_CODE (PATTERN (last)) == ADDR_DIFF_VEC)
5774             last = prev_active_insn (last);
5775           if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
5776             emit_insn_after (gen_insn_group_barrier (GEN_INT (3)), last);
5777
5778           init_insn_group_barriers ();
5779         }
5780       else if (INSN_P (insn))
5781         {
5782           if (recog_memoized (insn) == CODE_FOR_insn_group_barrier)
5783             init_insn_group_barriers ();
5784           else if (group_barrier_needed_p (insn))
5785             {
5786               emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), insn);
5787               init_insn_group_barriers ();
5788               group_barrier_needed_p (insn);
5789             }
5790         }
5791     }
5792 }
5793
5794 \f
5795 static int errata_find_address_regs (rtx *, void *);
5796 static void errata_emit_nops (rtx);
5797 static void fixup_errata (void);
5798
5799 /* This structure is used to track some details about the previous insns
5800    groups so we can determine if it may be necessary to insert NOPs to
5801    workaround hardware errata.  */
5802 static struct group
5803 {
5804   HARD_REG_SET p_reg_set;
5805   HARD_REG_SET gr_reg_conditionally_set;
5806 } last_group[2];
5807
5808 /* Index into the last_group array.  */
5809 static int group_idx;
5810
5811 /* Called through for_each_rtx; determines if a hard register that was
5812    conditionally set in the previous group is used as an address register.
5813    It ensures that for_each_rtx returns 1 in that case.  */
5814 static int
5815 errata_find_address_regs (rtx *xp, void *data ATTRIBUTE_UNUSED)
5816 {
5817   rtx x = *xp;
5818   if (GET_CODE (x) != MEM)
5819     return 0;
5820   x = XEXP (x, 0);
5821   if (GET_CODE (x) == POST_MODIFY)
5822     x = XEXP (x, 0);
5823   if (GET_CODE (x) == REG)
5824     {
5825       struct group *prev_group = last_group + (group_idx ^ 1);
5826       if (TEST_HARD_REG_BIT (prev_group->gr_reg_conditionally_set,
5827                              REGNO (x)))
5828         return 1;
5829       return -1;
5830     }
5831   return 0;
5832 }
5833
5834 /* Called for each insn; this function keeps track of the state in
5835    last_group and emits additional NOPs if necessary to work around
5836    an Itanium A/B step erratum.  */
5837 static void
5838 errata_emit_nops (rtx insn)
5839 {
5840   struct group *this_group = last_group + group_idx;
5841   struct group *prev_group = last_group + (group_idx ^ 1);
5842   rtx pat = PATTERN (insn);
5843   rtx cond = GET_CODE (pat) == COND_EXEC ? COND_EXEC_TEST (pat) : 0;
5844   rtx real_pat = cond ? COND_EXEC_CODE (pat) : pat;
5845   enum attr_type type;
5846   rtx set = real_pat;
5847
5848   if (GET_CODE (real_pat) == USE
5849       || GET_CODE (real_pat) == CLOBBER
5850       || GET_CODE (real_pat) == ASM_INPUT
5851       || GET_CODE (real_pat) == ADDR_VEC
5852       || GET_CODE (real_pat) == ADDR_DIFF_VEC
5853       || asm_noperands (PATTERN (insn)) >= 0)
5854     return;
5855
5856   /* single_set doesn't work for COND_EXEC insns, so we have to duplicate
5857      parts of it.  */
5858
5859   if (GET_CODE (set) == PARALLEL)
5860     {
5861       int i;
5862       set = XVECEXP (real_pat, 0, 0);
5863       for (i = 1; i < XVECLEN (real_pat, 0); i++)
5864         if (GET_CODE (XVECEXP (real_pat, 0, i)) != USE
5865             && GET_CODE (XVECEXP (real_pat, 0, i)) != CLOBBER)
5866           {
5867             set = 0;
5868             break;
5869           }
5870     }
5871
5872   if (set && GET_CODE (set) != SET)
5873     set = 0;
5874
5875   type  = get_attr_type (insn);
5876
5877   if (type == TYPE_F
5878       && set && REG_P (SET_DEST (set)) && PR_REGNO_P (REGNO (SET_DEST (set))))
5879     SET_HARD_REG_BIT (this_group->p_reg_set, REGNO (SET_DEST (set)));
5880
5881   if ((type == TYPE_M || type == TYPE_A) && cond && set
5882       && REG_P (SET_DEST (set))
5883       && GET_CODE (SET_SRC (set)) != PLUS
5884       && GET_CODE (SET_SRC (set)) != MINUS
5885       && (GET_CODE (SET_SRC (set)) != ASHIFT
5886           || !shladd_operand (XEXP (SET_SRC (set), 1), VOIDmode))
5887       && (GET_CODE (SET_SRC (set)) != MEM
5888           || GET_CODE (XEXP (SET_SRC (set), 0)) != POST_MODIFY)
5889       && GENERAL_REGNO_P (REGNO (SET_DEST (set))))
5890     {
5891       if (!COMPARISON_P (cond)
5892           || !REG_P (XEXP (cond, 0)))
5893         abort ();
5894
5895       if (TEST_HARD_REG_BIT (prev_group->p_reg_set, REGNO (XEXP (cond, 0))))
5896         SET_HARD_REG_BIT (this_group->gr_reg_conditionally_set, REGNO (SET_DEST (set)));
5897     }
5898   if (for_each_rtx (&real_pat, errata_find_address_regs, NULL))
5899     {
5900       emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), insn);
5901       emit_insn_before (gen_nop (), insn);
5902       emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), insn);
5903       group_idx = 0;
5904       memset (last_group, 0, sizeof last_group);
5905     }
5906 }
5907
5908 /* Emit extra nops if they are required to work around hardware errata.  */
5909
5910 static void
5911 fixup_errata (void)
5912 {
5913   rtx insn;
5914
5915   if (! TARGET_B_STEP)
5916     return;
5917
5918   group_idx = 0;
5919   memset (last_group, 0, sizeof last_group);
5920
5921   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
5922     {
5923       if (!INSN_P (insn))
5924         continue;
5925
5926       if (ia64_safe_type (insn) == TYPE_S)
5927         {
5928           group_idx ^= 1;
5929           memset (last_group + group_idx, 0, sizeof last_group[group_idx]);
5930         }
5931       else
5932         errata_emit_nops (insn);
5933     }
5934 }
5935 \f
5936
5937 /* Instruction scheduling support.  */
5938
5939 #define NR_BUNDLES 10
5940
5941 /* A list of names of all available bundles.  */
5942
5943 static const char *bundle_name [NR_BUNDLES] =
5944 {
5945   ".mii",
5946   ".mmi",
5947   ".mfi",
5948   ".mmf",
5949 #if NR_BUNDLES == 10
5950   ".bbb",
5951   ".mbb",
5952 #endif
5953   ".mib",
5954   ".mmb",
5955   ".mfb",
5956   ".mlx"
5957 };
5958
5959 /* Nonzero if we should insert stop bits into the schedule.  */
5960
5961 int ia64_final_schedule = 0;
5962
5963 /* Codes of the corresponding quieryied units: */
5964
5965 static int _0mii_, _0mmi_, _0mfi_, _0mmf_;
5966 static int _0bbb_, _0mbb_, _0mib_, _0mmb_, _0mfb_, _0mlx_;
5967
5968 static int _1mii_, _1mmi_, _1mfi_, _1mmf_;
5969 static int _1bbb_, _1mbb_, _1mib_, _1mmb_, _1mfb_, _1mlx_;
5970
5971 static int pos_1, pos_2, pos_3, pos_4, pos_5, pos_6;
5972
5973 /* The following variable value is an insn group barrier.  */
5974
5975 static rtx dfa_stop_insn;
5976
5977 /* The following variable value is the last issued insn.  */
5978
5979 static rtx last_scheduled_insn;
5980
5981 /* The following variable value is size of the DFA state.  */
5982
5983 static size_t dfa_state_size;
5984
5985 /* The following variable value is pointer to a DFA state used as
5986    temporary variable.  */
5987
5988 static state_t temp_dfa_state = NULL;
5989
5990 /* The following variable value is DFA state after issuing the last
5991    insn.  */
5992
5993 static state_t prev_cycle_state = NULL;
5994
5995 /* The following array element values are TRUE if the corresponding
5996    insn requires to add stop bits before it.  */
5997
5998 static char *stops_p;
5999
6000 /* The following variable is used to set up the mentioned above array.  */
6001
6002 static int stop_before_p = 0;
6003
6004 /* The following variable value is length of the arrays `clocks' and
6005    `add_cycles'. */
6006
6007 static int clocks_length;
6008
6009 /* The following array element values are cycles on which the
6010    corresponding insn will be issued.  The array is used only for
6011    Itanium1.  */
6012
6013 static int *clocks;
6014
6015 /* The following array element values are numbers of cycles should be
6016    added to improve insn scheduling for MM_insns for Itanium1.  */
6017
6018 static int *add_cycles;
6019
6020 static rtx ia64_single_set (rtx);
6021 static void ia64_emit_insn_before (rtx, rtx);
6022
6023 /* Map a bundle number to its pseudo-op.  */
6024
6025 const char *
6026 get_bundle_name (int b)
6027 {
6028   return bundle_name[b];
6029 }
6030
6031
6032 /* Return the maximum number of instructions a cpu can issue.  */
6033
6034 static int
6035 ia64_issue_rate (void)
6036 {
6037   return 6;
6038 }
6039
6040 /* Helper function - like single_set, but look inside COND_EXEC.  */
6041
6042 static rtx
6043 ia64_single_set (rtx insn)
6044 {
6045   rtx x = PATTERN (insn), ret;
6046   if (GET_CODE (x) == COND_EXEC)
6047     x = COND_EXEC_CODE (x);
6048   if (GET_CODE (x) == SET)
6049     return x;
6050
6051   /* Special case here prologue_allocate_stack and epilogue_deallocate_stack.
6052      Although they are not classical single set, the second set is there just
6053      to protect it from moving past FP-relative stack accesses.  */
6054   switch (recog_memoized (insn))
6055     {
6056     case CODE_FOR_prologue_allocate_stack:
6057     case CODE_FOR_epilogue_deallocate_stack:
6058       ret = XVECEXP (x, 0, 0);
6059       break;
6060
6061     default:
6062       ret = single_set_2 (insn, x);
6063       break;
6064     }
6065
6066   return ret;
6067 }
6068
6069 /* Adjust the cost of a scheduling dependency.  Return the new cost of
6070    a dependency LINK or INSN on DEP_INSN.  COST is the current cost.  */
6071
6072 static int
6073 ia64_adjust_cost (rtx insn, rtx link, rtx dep_insn, int cost)
6074 {
6075   enum attr_itanium_class dep_class;
6076   enum attr_itanium_class insn_class;
6077
6078   if (REG_NOTE_KIND (link) != REG_DEP_OUTPUT)
6079     return cost;
6080
6081   insn_class = ia64_safe_itanium_class (insn);
6082   dep_class = ia64_safe_itanium_class (dep_insn);
6083   if (dep_class == ITANIUM_CLASS_ST || dep_class == ITANIUM_CLASS_STF
6084       || insn_class == ITANIUM_CLASS_ST || insn_class == ITANIUM_CLASS_STF)
6085     return 0;
6086
6087   return cost;
6088 }
6089
6090 /* Like emit_insn_before, but skip cycle_display notes.
6091    ??? When cycle display notes are implemented, update this.  */
6092
6093 static void
6094 ia64_emit_insn_before (rtx insn, rtx before)
6095 {
6096   emit_insn_before (insn, before);
6097 }
6098
6099 /* The following function marks insns who produce addresses for load
6100    and store insns.  Such insns will be placed into M slots because it
6101    decrease latency time for Itanium1 (see function
6102    `ia64_produce_address_p' and the DFA descriptions).  */
6103
6104 static void
6105 ia64_dependencies_evaluation_hook (rtx head, rtx tail)
6106 {
6107   rtx insn, link, next, next_tail;
6108
6109   next_tail = NEXT_INSN (tail);
6110   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6111     if (INSN_P (insn))
6112       insn->call = 0;
6113   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6114     if (INSN_P (insn)
6115         && ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IALU)
6116       {
6117         for (link = INSN_DEPEND (insn); link != 0; link = XEXP (link, 1))
6118           {
6119             next = XEXP (link, 0);
6120             if ((ia64_safe_itanium_class (next) == ITANIUM_CLASS_ST
6121                  || ia64_safe_itanium_class (next) == ITANIUM_CLASS_STF)
6122                 && ia64_st_address_bypass_p (insn, next))
6123               break;
6124             else if ((ia64_safe_itanium_class (next) == ITANIUM_CLASS_LD
6125                       || ia64_safe_itanium_class (next)
6126                       == ITANIUM_CLASS_FLD)
6127                      && ia64_ld_address_bypass_p (insn, next))
6128               break;
6129           }
6130         insn->call = link != 0;
6131       }
6132 }
6133
6134 /* We're beginning a new block.  Initialize data structures as necessary.  */
6135
6136 static void
6137 ia64_sched_init (FILE *dump ATTRIBUTE_UNUSED,
6138                  int sched_verbose ATTRIBUTE_UNUSED,
6139                  int max_ready ATTRIBUTE_UNUSED)
6140 {
6141 #ifdef ENABLE_CHECKING
6142   rtx insn;
6143
6144   if (reload_completed)
6145     for (insn = NEXT_INSN (current_sched_info->prev_head);
6146          insn != current_sched_info->next_tail;
6147          insn = NEXT_INSN (insn))
6148       if (SCHED_GROUP_P (insn))
6149         abort ();
6150 #endif
6151   last_scheduled_insn = NULL_RTX;
6152   init_insn_group_barriers ();
6153 }
6154
6155 /* We are about to being issuing insns for this clock cycle.
6156    Override the default sort algorithm to better slot instructions.  */
6157
6158 static int
6159 ia64_dfa_sched_reorder (FILE *dump, int sched_verbose, rtx *ready,
6160                         int *pn_ready, int clock_var ATTRIBUTE_UNUSED,
6161                         int reorder_type)
6162 {
6163   int n_asms;
6164   int n_ready = *pn_ready;
6165   rtx *e_ready = ready + n_ready;
6166   rtx *insnp;
6167
6168   if (sched_verbose)
6169     fprintf (dump, "// ia64_dfa_sched_reorder (type %d):\n", reorder_type);
6170
6171   if (reorder_type == 0)
6172     {
6173       /* First, move all USEs, CLOBBERs and other crud out of the way.  */
6174       n_asms = 0;
6175       for (insnp = ready; insnp < e_ready; insnp++)
6176         if (insnp < e_ready)
6177           {
6178             rtx insn = *insnp;
6179             enum attr_type t = ia64_safe_type (insn);
6180             if (t == TYPE_UNKNOWN)
6181               {
6182                 if (GET_CODE (PATTERN (insn)) == ASM_INPUT
6183                     || asm_noperands (PATTERN (insn)) >= 0)
6184                   {
6185                     rtx lowest = ready[n_asms];
6186                     ready[n_asms] = insn;
6187                     *insnp = lowest;
6188                     n_asms++;
6189                   }
6190                 else
6191                   {
6192                     rtx highest = ready[n_ready - 1];
6193                     ready[n_ready - 1] = insn;
6194                     *insnp = highest;
6195                     return 1;
6196                   }
6197               }
6198           }
6199
6200       if (n_asms < n_ready)
6201         {
6202           /* Some normal insns to process.  Skip the asms.  */
6203           ready += n_asms;
6204           n_ready -= n_asms;
6205         }
6206       else if (n_ready > 0)
6207         return 1;
6208     }
6209
6210   if (ia64_final_schedule)
6211     {
6212       int deleted = 0;
6213       int nr_need_stop = 0;
6214
6215       for (insnp = ready; insnp < e_ready; insnp++)
6216         if (safe_group_barrier_needed_p (*insnp))
6217           nr_need_stop++;
6218
6219       if (reorder_type == 1 && n_ready == nr_need_stop)
6220         return 0;
6221       if (reorder_type == 0)
6222         return 1;
6223       insnp = e_ready;
6224       /* Move down everything that needs a stop bit, preserving
6225          relative order.  */
6226       while (insnp-- > ready + deleted)
6227         while (insnp >= ready + deleted)
6228           {
6229             rtx insn = *insnp;
6230             if (! safe_group_barrier_needed_p (insn))
6231               break;
6232             memmove (ready + 1, ready, (insnp - ready) * sizeof (rtx));
6233             *ready = insn;
6234             deleted++;
6235           }
6236       n_ready -= deleted;
6237       ready += deleted;
6238     }
6239
6240   return 1;
6241 }
6242
6243 /* We are about to being issuing insns for this clock cycle.  Override
6244    the default sort algorithm to better slot instructions.  */
6245
6246 static int
6247 ia64_sched_reorder (FILE *dump, int sched_verbose, rtx *ready, int *pn_ready,
6248                     int clock_var)
6249 {
6250   return ia64_dfa_sched_reorder (dump, sched_verbose, ready,
6251                                  pn_ready, clock_var, 0);
6252 }
6253
6254 /* Like ia64_sched_reorder, but called after issuing each insn.
6255    Override the default sort algorithm to better slot instructions.  */
6256
6257 static int
6258 ia64_sched_reorder2 (FILE *dump ATTRIBUTE_UNUSED,
6259                      int sched_verbose ATTRIBUTE_UNUSED, rtx *ready,
6260                      int *pn_ready, int clock_var)
6261 {
6262   if (ia64_tune == PROCESSOR_ITANIUM && reload_completed && last_scheduled_insn)
6263     clocks [INSN_UID (last_scheduled_insn)] = clock_var;
6264   return ia64_dfa_sched_reorder (dump, sched_verbose, ready, pn_ready,
6265                                  clock_var, 1);
6266 }
6267
6268 /* We are about to issue INSN.  Return the number of insns left on the
6269    ready queue that can be issued this cycle.  */
6270
6271 static int
6272 ia64_variable_issue (FILE *dump ATTRIBUTE_UNUSED,
6273                      int sched_verbose ATTRIBUTE_UNUSED,
6274                      rtx insn ATTRIBUTE_UNUSED,
6275                      int can_issue_more ATTRIBUTE_UNUSED)
6276 {
6277   last_scheduled_insn = insn;
6278   memcpy (prev_cycle_state, curr_state, dfa_state_size);
6279   if (reload_completed)
6280     {
6281       if (group_barrier_needed_p (insn))
6282         abort ();
6283       if (GET_CODE (insn) == CALL_INSN)
6284         init_insn_group_barriers ();
6285       stops_p [INSN_UID (insn)] = stop_before_p;
6286       stop_before_p = 0;
6287     }
6288   return 1;
6289 }
6290
6291 /* We are choosing insn from the ready queue.  Return nonzero if INSN
6292    can be chosen.  */
6293
6294 static int
6295 ia64_first_cycle_multipass_dfa_lookahead_guard (rtx insn)
6296 {
6297   if (insn == NULL_RTX || !INSN_P (insn))
6298     abort ();
6299   return (!reload_completed
6300           || !safe_group_barrier_needed_p (insn));
6301 }
6302
6303 /* The following variable value is pseudo-insn used by the DFA insn
6304    scheduler to change the DFA state when the simulated clock is
6305    increased.  */
6306
6307 static rtx dfa_pre_cycle_insn;
6308
6309 /* We are about to being issuing INSN.  Return nonzero if we can not
6310    issue it on given cycle CLOCK and return zero if we should not sort
6311    the ready queue on the next clock start.  */
6312
6313 static int
6314 ia64_dfa_new_cycle (FILE *dump, int verbose, rtx insn, int last_clock,
6315                     int clock, int *sort_p)
6316 {
6317   int setup_clocks_p = FALSE;
6318
6319   if (insn == NULL_RTX || !INSN_P (insn))
6320     abort ();
6321   if ((reload_completed && safe_group_barrier_needed_p (insn))
6322       || (last_scheduled_insn
6323           && (GET_CODE (last_scheduled_insn) == CALL_INSN
6324               || GET_CODE (PATTERN (last_scheduled_insn)) == ASM_INPUT
6325               || asm_noperands (PATTERN (last_scheduled_insn)) >= 0)))
6326     {
6327       init_insn_group_barriers ();
6328       if (verbose && dump)
6329         fprintf (dump, "//    Stop should be before %d%s\n", INSN_UID (insn),
6330                  last_clock == clock ? " + cycle advance" : "");
6331       stop_before_p = 1;
6332       if (last_clock == clock)
6333         {
6334           state_transition (curr_state, dfa_stop_insn);
6335           if (TARGET_EARLY_STOP_BITS)
6336             *sort_p = (last_scheduled_insn == NULL_RTX
6337                        || GET_CODE (last_scheduled_insn) != CALL_INSN);
6338           else
6339             *sort_p = 0;
6340           return 1;
6341         }
6342       else if (reload_completed)
6343         setup_clocks_p = TRUE;
6344       memcpy (curr_state, prev_cycle_state, dfa_state_size);
6345       state_transition (curr_state, dfa_stop_insn);
6346       state_transition (curr_state, dfa_pre_cycle_insn);
6347       state_transition (curr_state, NULL);
6348     }
6349   else if (reload_completed)
6350     setup_clocks_p = TRUE;
6351   if (setup_clocks_p && ia64_tune == PROCESSOR_ITANIUM)
6352     {
6353       enum attr_itanium_class c = ia64_safe_itanium_class (insn);
6354
6355       if (c != ITANIUM_CLASS_MMMUL && c != ITANIUM_CLASS_MMSHF)
6356         {
6357           rtx link;
6358           int d = -1;
6359
6360           for (link = LOG_LINKS (insn); link; link = XEXP (link, 1))
6361             if (REG_NOTE_KIND (link) == 0)
6362               {
6363                 enum attr_itanium_class dep_class;
6364                 rtx dep_insn = XEXP (link, 0);
6365
6366                 dep_class = ia64_safe_itanium_class (dep_insn);
6367                 if ((dep_class == ITANIUM_CLASS_MMMUL
6368                      || dep_class == ITANIUM_CLASS_MMSHF)
6369                     && last_clock - clocks [INSN_UID (dep_insn)] < 4
6370                     && (d < 0
6371                         || last_clock - clocks [INSN_UID (dep_insn)] < d))
6372                   d = last_clock - clocks [INSN_UID (dep_insn)];
6373               }
6374           if (d >= 0)
6375             add_cycles [INSN_UID (insn)] = 3 - d;
6376         }
6377     }
6378   return 0;
6379 }
6380
6381 \f
6382
6383 /* The following page contains abstract data `bundle states' which are
6384    used for bundling insns (inserting nops and template generation).  */
6385
6386 /* The following describes state of insn bundling.  */
6387
6388 struct bundle_state
6389 {
6390   /* Unique bundle state number to identify them in the debugging
6391      output  */
6392   int unique_num;
6393   rtx insn;     /* corresponding insn, NULL for the 1st and the last state  */
6394   /* number nops before and after the insn  */
6395   short before_nops_num, after_nops_num;
6396   int insn_num; /* insn number (0 - for initial state, 1 - for the 1st
6397                    insn */
6398   int cost;     /* cost of the state in cycles */
6399   int accumulated_insns_num; /* number of all previous insns including
6400                                 nops.  L is considered as 2 insns */
6401   int branch_deviation; /* deviation of previous branches from 3rd slots  */
6402   struct bundle_state *next;  /* next state with the same insn_num  */
6403   struct bundle_state *originator; /* originator (previous insn state)  */
6404   /* All bundle states are in the following chain.  */
6405   struct bundle_state *allocated_states_chain;
6406   /* The DFA State after issuing the insn and the nops.  */
6407   state_t dfa_state;
6408 };
6409
6410 /* The following is map insn number to the corresponding bundle state.  */
6411
6412 static struct bundle_state **index_to_bundle_states;
6413
6414 /* The unique number of next bundle state.  */
6415
6416 static int bundle_states_num;
6417
6418 /* All allocated bundle states are in the following chain.  */
6419
6420 static struct bundle_state *allocated_bundle_states_chain;
6421
6422 /* All allocated but not used bundle states are in the following
6423    chain.  */
6424
6425 static struct bundle_state *free_bundle_state_chain;
6426
6427
6428 /* The following function returns a free bundle state.  */
6429
6430 static struct bundle_state *
6431 get_free_bundle_state (void)
6432 {
6433   struct bundle_state *result;
6434
6435   if (free_bundle_state_chain != NULL)
6436     {
6437       result = free_bundle_state_chain;
6438       free_bundle_state_chain = result->next;
6439     }
6440   else
6441     {
6442       result = xmalloc (sizeof (struct bundle_state));
6443       result->dfa_state = xmalloc (dfa_state_size);
6444       result->allocated_states_chain = allocated_bundle_states_chain;
6445       allocated_bundle_states_chain = result;
6446     }
6447   result->unique_num = bundle_states_num++;
6448   return result;
6449
6450 }
6451
6452 /* The following function frees given bundle state.  */
6453
6454 static void
6455 free_bundle_state (struct bundle_state *state)
6456 {
6457   state->next = free_bundle_state_chain;
6458   free_bundle_state_chain = state;
6459 }
6460
6461 /* Start work with abstract data `bundle states'.  */
6462
6463 static void
6464 initiate_bundle_states (void)
6465 {
6466   bundle_states_num = 0;
6467   free_bundle_state_chain = NULL;
6468   allocated_bundle_states_chain = NULL;
6469 }
6470
6471 /* Finish work with abstract data `bundle states'.  */
6472
6473 static void
6474 finish_bundle_states (void)
6475 {
6476   struct bundle_state *curr_state, *next_state;
6477
6478   for (curr_state = allocated_bundle_states_chain;
6479        curr_state != NULL;
6480        curr_state = next_state)
6481     {
6482       next_state = curr_state->allocated_states_chain;
6483       free (curr_state->dfa_state);
6484       free (curr_state);
6485     }
6486 }
6487
6488 /* Hash table of the bundle states.  The key is dfa_state and insn_num
6489    of the bundle states.  */
6490
6491 static htab_t bundle_state_table;
6492
6493 /* The function returns hash of BUNDLE_STATE.  */
6494
6495 static unsigned
6496 bundle_state_hash (const void *bundle_state)
6497 {
6498   const struct bundle_state *state = (struct bundle_state *) bundle_state;
6499   unsigned result, i;
6500
6501   for (result = i = 0; i < dfa_state_size; i++)
6502     result += (((unsigned char *) state->dfa_state) [i]
6503                << ((i % CHAR_BIT) * 3 + CHAR_BIT));
6504   return result + state->insn_num;
6505 }
6506
6507 /* The function returns nonzero if the bundle state keys are equal.  */
6508
6509 static int
6510 bundle_state_eq_p (const void *bundle_state_1, const void *bundle_state_2)
6511 {
6512   const struct bundle_state * state1 = (struct bundle_state *) bundle_state_1;
6513   const struct bundle_state * state2 = (struct bundle_state *) bundle_state_2;
6514
6515   return (state1->insn_num == state2->insn_num
6516           && memcmp (state1->dfa_state, state2->dfa_state,
6517                      dfa_state_size) == 0);
6518 }
6519
6520 /* The function inserts the BUNDLE_STATE into the hash table.  The
6521    function returns nonzero if the bundle has been inserted into the
6522    table.  The table contains the best bundle state with given key.  */
6523
6524 static int
6525 insert_bundle_state (struct bundle_state *bundle_state)
6526 {
6527   void **entry_ptr;
6528
6529   entry_ptr = htab_find_slot (bundle_state_table, bundle_state, 1);
6530   if (*entry_ptr == NULL)
6531     {
6532       bundle_state->next = index_to_bundle_states [bundle_state->insn_num];
6533       index_to_bundle_states [bundle_state->insn_num] = bundle_state;
6534       *entry_ptr = (void *) bundle_state;
6535       return TRUE;
6536     }
6537   else if (bundle_state->cost < ((struct bundle_state *) *entry_ptr)->cost
6538            || (bundle_state->cost == ((struct bundle_state *) *entry_ptr)->cost
6539                && (((struct bundle_state *)*entry_ptr)->accumulated_insns_num
6540                    > bundle_state->accumulated_insns_num
6541                    || (((struct bundle_state *)
6542                         *entry_ptr)->accumulated_insns_num
6543                        == bundle_state->accumulated_insns_num
6544                        && ((struct bundle_state *)
6545                            *entry_ptr)->branch_deviation
6546                        > bundle_state->branch_deviation))))
6547
6548     {
6549       struct bundle_state temp;
6550
6551       temp = *(struct bundle_state *) *entry_ptr;
6552       *(struct bundle_state *) *entry_ptr = *bundle_state;
6553       ((struct bundle_state *) *entry_ptr)->next = temp.next;
6554       *bundle_state = temp;
6555     }
6556   return FALSE;
6557 }
6558
6559 /* Start work with the hash table.  */
6560
6561 static void
6562 initiate_bundle_state_table (void)
6563 {
6564   bundle_state_table = htab_create (50, bundle_state_hash, bundle_state_eq_p,
6565                                     (htab_del) 0);
6566 }
6567
6568 /* Finish work with the hash table.  */
6569
6570 static void
6571 finish_bundle_state_table (void)
6572 {
6573   htab_delete (bundle_state_table);
6574 }
6575
6576 \f
6577
6578 /* The following variable is a insn `nop' used to check bundle states
6579    with different number of inserted nops.  */
6580
6581 static rtx ia64_nop;
6582
6583 /* The following function tries to issue NOPS_NUM nops for the current
6584    state without advancing processor cycle.  If it failed, the
6585    function returns FALSE and frees the current state.  */
6586
6587 static int
6588 try_issue_nops (struct bundle_state *curr_state, int nops_num)
6589 {
6590   int i;
6591
6592   for (i = 0; i < nops_num; i++)
6593     if (state_transition (curr_state->dfa_state, ia64_nop) >= 0)
6594       {
6595         free_bundle_state (curr_state);
6596         return FALSE;
6597       }
6598   return TRUE;
6599 }
6600
6601 /* The following function tries to issue INSN for the current
6602    state without advancing processor cycle.  If it failed, the
6603    function returns FALSE and frees the current state.  */
6604
6605 static int
6606 try_issue_insn (struct bundle_state *curr_state, rtx insn)
6607 {
6608   if (insn && state_transition (curr_state->dfa_state, insn) >= 0)
6609     {
6610       free_bundle_state (curr_state);
6611       return FALSE;
6612     }
6613   return TRUE;
6614 }
6615
6616 /* The following function tries to issue BEFORE_NOPS_NUM nops and INSN
6617    starting with ORIGINATOR without advancing processor cycle.  If
6618    TRY_BUNDLE_END_P is TRUE, the function also/only (if
6619    ONLY_BUNDLE_END_P is TRUE) tries to issue nops to fill all bundle.
6620    If it was successful, the function creates new bundle state and
6621    insert into the hash table and into `index_to_bundle_states'.  */
6622
6623 static void
6624 issue_nops_and_insn (struct bundle_state *originator, int before_nops_num,
6625                      rtx insn, int try_bundle_end_p, int only_bundle_end_p)
6626 {
6627   struct bundle_state *curr_state;
6628
6629   curr_state = get_free_bundle_state ();
6630   memcpy (curr_state->dfa_state, originator->dfa_state, dfa_state_size);
6631   curr_state->insn = insn;
6632   curr_state->insn_num = originator->insn_num + 1;
6633   curr_state->cost = originator->cost;
6634   curr_state->originator = originator;
6635   curr_state->before_nops_num = before_nops_num;
6636   curr_state->after_nops_num = 0;
6637   curr_state->accumulated_insns_num
6638     = originator->accumulated_insns_num + before_nops_num;
6639   curr_state->branch_deviation = originator->branch_deviation;
6640   if (insn == NULL_RTX)
6641     abort ();
6642   else if (INSN_CODE (insn) == CODE_FOR_insn_group_barrier)
6643     {
6644       if (GET_MODE (insn) == TImode)
6645         abort ();
6646       if (!try_issue_nops (curr_state, before_nops_num))
6647         return;
6648       if (!try_issue_insn (curr_state, insn))
6649         return;
6650       memcpy (temp_dfa_state, curr_state->dfa_state, dfa_state_size);
6651       if (state_transition (temp_dfa_state, dfa_pre_cycle_insn) >= 0
6652           && curr_state->accumulated_insns_num % 3 != 0)
6653         {
6654           free_bundle_state (curr_state);
6655           return;
6656         }
6657     }
6658   else if (GET_MODE (insn) != TImode)
6659     {
6660       if (!try_issue_nops (curr_state, before_nops_num))
6661         return;
6662       if (!try_issue_insn (curr_state, insn))
6663         return;
6664       curr_state->accumulated_insns_num++;
6665       if (GET_CODE (PATTERN (insn)) == ASM_INPUT
6666           || asm_noperands (PATTERN (insn)) >= 0)
6667         abort ();
6668       if (ia64_safe_type (insn) == TYPE_L)
6669         curr_state->accumulated_insns_num++;
6670     }
6671   else
6672     {
6673       state_transition (curr_state->dfa_state, dfa_pre_cycle_insn);
6674       state_transition (curr_state->dfa_state, NULL);
6675       curr_state->cost++;
6676       if (!try_issue_nops (curr_state, before_nops_num))
6677         return;
6678       if (!try_issue_insn (curr_state, insn))
6679         return;
6680       curr_state->accumulated_insns_num++;
6681       if (GET_CODE (PATTERN (insn)) == ASM_INPUT
6682           || asm_noperands (PATTERN (insn)) >= 0)
6683         {
6684           /* Finish bundle containing asm insn.  */
6685           curr_state->after_nops_num
6686             = 3 - curr_state->accumulated_insns_num % 3;
6687           curr_state->accumulated_insns_num
6688             += 3 - curr_state->accumulated_insns_num % 3;
6689         }
6690       else if (ia64_safe_type (insn) == TYPE_L)
6691         curr_state->accumulated_insns_num++;
6692     }
6693   if (ia64_safe_type (insn) == TYPE_B)
6694     curr_state->branch_deviation
6695       += 2 - (curr_state->accumulated_insns_num - 1) % 3;
6696   if (try_bundle_end_p && curr_state->accumulated_insns_num % 3 != 0)
6697     {
6698       if (!only_bundle_end_p && insert_bundle_state (curr_state))
6699         {
6700           state_t dfa_state;
6701           struct bundle_state *curr_state1;
6702           struct bundle_state *allocated_states_chain;
6703
6704           curr_state1 = get_free_bundle_state ();
6705           dfa_state = curr_state1->dfa_state;
6706           allocated_states_chain = curr_state1->allocated_states_chain;
6707           *curr_state1 = *curr_state;
6708           curr_state1->dfa_state = dfa_state;
6709           curr_state1->allocated_states_chain = allocated_states_chain;
6710           memcpy (curr_state1->dfa_state, curr_state->dfa_state,
6711                   dfa_state_size);
6712           curr_state = curr_state1;
6713         }
6714       if (!try_issue_nops (curr_state,
6715                            3 - curr_state->accumulated_insns_num % 3))
6716         return;
6717       curr_state->after_nops_num
6718         = 3 - curr_state->accumulated_insns_num % 3;
6719       curr_state->accumulated_insns_num
6720         += 3 - curr_state->accumulated_insns_num % 3;
6721     }
6722   if (!insert_bundle_state (curr_state))
6723     free_bundle_state (curr_state);
6724   return;
6725 }
6726
6727 /* The following function returns position in the two window bundle
6728    for given STATE.  */
6729
6730 static int
6731 get_max_pos (state_t state)
6732 {
6733   if (cpu_unit_reservation_p (state, pos_6))
6734     return 6;
6735   else if (cpu_unit_reservation_p (state, pos_5))
6736     return 5;
6737   else if (cpu_unit_reservation_p (state, pos_4))
6738     return 4;
6739   else if (cpu_unit_reservation_p (state, pos_3))
6740     return 3;
6741   else if (cpu_unit_reservation_p (state, pos_2))
6742     return 2;
6743   else if (cpu_unit_reservation_p (state, pos_1))
6744     return 1;
6745   else
6746     return 0;
6747 }
6748
6749 /* The function returns code of a possible template for given position
6750    and state.  The function should be called only with 2 values of
6751    position equal to 3 or 6.  */
6752
6753 static int
6754 get_template (state_t state, int pos)
6755 {
6756   switch (pos)
6757     {
6758     case 3:
6759       if (cpu_unit_reservation_p (state, _0mii_))
6760         return 0;
6761       else if (cpu_unit_reservation_p (state, _0mmi_))
6762         return 1;
6763       else if (cpu_unit_reservation_p (state, _0mfi_))
6764         return 2;
6765       else if (cpu_unit_reservation_p (state, _0mmf_))
6766         return 3;
6767       else if (cpu_unit_reservation_p (state, _0bbb_))
6768         return 4;
6769       else if (cpu_unit_reservation_p (state, _0mbb_))
6770         return 5;
6771       else if (cpu_unit_reservation_p (state, _0mib_))
6772         return 6;
6773       else if (cpu_unit_reservation_p (state, _0mmb_))
6774         return 7;
6775       else if (cpu_unit_reservation_p (state, _0mfb_))
6776         return 8;
6777       else if (cpu_unit_reservation_p (state, _0mlx_))
6778         return 9;
6779       else
6780         abort ();
6781     case 6:
6782       if (cpu_unit_reservation_p (state, _1mii_))
6783         return 0;
6784       else if (cpu_unit_reservation_p (state, _1mmi_))
6785         return 1;
6786       else if (cpu_unit_reservation_p (state, _1mfi_))
6787         return 2;
6788       else if (_1mmf_ >= 0 && cpu_unit_reservation_p (state, _1mmf_))
6789         return 3;
6790       else if (cpu_unit_reservation_p (state, _1bbb_))
6791         return 4;
6792       else if (cpu_unit_reservation_p (state, _1mbb_))
6793         return 5;
6794       else if (cpu_unit_reservation_p (state, _1mib_))
6795         return 6;
6796       else if (cpu_unit_reservation_p (state, _1mmb_))
6797         return 7;
6798       else if (cpu_unit_reservation_p (state, _1mfb_))
6799         return 8;
6800       else if (cpu_unit_reservation_p (state, _1mlx_))
6801         return 9;
6802       else
6803         abort ();
6804     default:
6805       abort ();
6806     }
6807 }
6808
6809 /* The following function returns an insn important for insn bundling
6810    followed by INSN and before TAIL.  */
6811
6812 static rtx
6813 get_next_important_insn (rtx insn, rtx tail)
6814 {
6815   for (; insn && insn != tail; insn = NEXT_INSN (insn))
6816     if (INSN_P (insn)
6817         && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
6818         && GET_CODE (PATTERN (insn)) != USE
6819         && GET_CODE (PATTERN (insn)) != CLOBBER)
6820       return insn;
6821   return NULL_RTX;
6822 }
6823
6824 /* The following function does insn bundling.  Bundling means
6825    inserting templates and nop insns to fit insn groups into permitted
6826    templates.  Instruction scheduling uses NDFA (non-deterministic
6827    finite automata) encoding informations about the templates and the
6828    inserted nops.  Nondeterminism of the automata permits follows
6829    all possible insn sequences very fast.
6830
6831    Unfortunately it is not possible to get information about inserting
6832    nop insns and used templates from the automata states.  The
6833    automata only says that we can issue an insn possibly inserting
6834    some nops before it and using some template.  Therefore insn
6835    bundling in this function is implemented by using DFA
6836    (deterministic finite automata).  We follows all possible insn
6837    sequences by inserting 0-2 nops (that is what the NDFA describe for
6838    insn scheduling) before/after each insn being bundled.  We know the
6839    start of simulated processor cycle from insn scheduling (insn
6840    starting a new cycle has TImode).
6841
6842    Simple implementation of insn bundling would create enormous
6843    number of possible insn sequences satisfying information about new
6844    cycle ticks taken from the insn scheduling.  To make the algorithm
6845    practical we use dynamic programming.  Each decision (about
6846    inserting nops and implicitly about previous decisions) is described
6847    by structure bundle_state (see above).  If we generate the same
6848    bundle state (key is automaton state after issuing the insns and
6849    nops for it), we reuse already generated one.  As consequence we
6850    reject some decisions which can not improve the solution and
6851    reduce memory for the algorithm.
6852
6853    When we reach the end of EBB (extended basic block), we choose the
6854    best sequence and then, moving back in EBB, insert templates for
6855    the best alternative.  The templates are taken from querying
6856    automaton state for each insn in chosen bundle states.
6857
6858    So the algorithm makes two (forward and backward) passes through
6859    EBB.  There is an additional forward pass through EBB for Itanium1
6860    processor.  This pass inserts more nops to make dependency between
6861    a producer insn and MMMUL/MMSHF at least 4 cycles long.  */
6862
6863 static void
6864 bundling (FILE *dump, int verbose, rtx prev_head_insn, rtx tail)
6865 {
6866   struct bundle_state *curr_state, *next_state, *best_state;
6867   rtx insn, next_insn;
6868   int insn_num;
6869   int i, bundle_end_p, only_bundle_end_p, asm_p;
6870   int pos = 0, max_pos, template0, template1;
6871   rtx b;
6872   rtx nop;
6873   enum attr_type type;
6874
6875   insn_num = 0;
6876   /* Count insns in the EBB.  */
6877   for (insn = NEXT_INSN (prev_head_insn);
6878        insn && insn != tail;
6879        insn = NEXT_INSN (insn))
6880     if (INSN_P (insn))
6881       insn_num++;
6882   if (insn_num == 0)
6883     return;
6884   bundling_p = 1;
6885   dfa_clean_insn_cache ();
6886   initiate_bundle_state_table ();
6887   index_to_bundle_states = xmalloc ((insn_num + 2)
6888                                     * sizeof (struct bundle_state *));
6889   /* First (forward) pass -- generation of bundle states.  */
6890   curr_state = get_free_bundle_state ();
6891   curr_state->insn = NULL;
6892   curr_state->before_nops_num = 0;
6893   curr_state->after_nops_num = 0;
6894   curr_state->insn_num = 0;
6895   curr_state->cost = 0;
6896   curr_state->accumulated_insns_num = 0;
6897   curr_state->branch_deviation = 0;
6898   curr_state->next = NULL;
6899   curr_state->originator = NULL;
6900   state_reset (curr_state->dfa_state);
6901   index_to_bundle_states [0] = curr_state;
6902   insn_num = 0;
6903   /* Shift cycle mark if it is put on insn which could be ignored.  */
6904   for (insn = NEXT_INSN (prev_head_insn);
6905        insn != tail;
6906        insn = NEXT_INSN (insn))
6907     if (INSN_P (insn)
6908         && (ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IGNORE
6909             || GET_CODE (PATTERN (insn)) == USE
6910             || GET_CODE (PATTERN (insn)) == CLOBBER)
6911         && GET_MODE (insn) == TImode)
6912       {
6913         PUT_MODE (insn, VOIDmode);
6914         for (next_insn = NEXT_INSN (insn);
6915              next_insn != tail;
6916              next_insn = NEXT_INSN (next_insn))
6917           if (INSN_P (next_insn)
6918               && ia64_safe_itanium_class (next_insn) != ITANIUM_CLASS_IGNORE
6919               && GET_CODE (PATTERN (next_insn)) != USE
6920               && GET_CODE (PATTERN (next_insn)) != CLOBBER)
6921             {
6922               PUT_MODE (next_insn, TImode);
6923               break;
6924             }
6925       }
6926   /* Froward pass: generation of bundle states.  */
6927   for (insn = get_next_important_insn (NEXT_INSN (prev_head_insn), tail);
6928        insn != NULL_RTX;
6929        insn = next_insn)
6930     {
6931       if (!INSN_P (insn)
6932           || ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IGNORE
6933           || GET_CODE (PATTERN (insn)) == USE
6934           || GET_CODE (PATTERN (insn)) == CLOBBER)
6935         abort ();
6936       type = ia64_safe_type (insn);
6937       next_insn = get_next_important_insn (NEXT_INSN (insn), tail);
6938       insn_num++;
6939       index_to_bundle_states [insn_num] = NULL;
6940       for (curr_state = index_to_bundle_states [insn_num - 1];
6941            curr_state != NULL;
6942            curr_state = next_state)
6943         {
6944           pos = curr_state->accumulated_insns_num % 3;
6945           next_state = curr_state->next;
6946           /* We must fill up the current bundle in order to start a
6947              subsequent asm insn in a new bundle.  Asm insn is always
6948              placed in a separate bundle.  */
6949           only_bundle_end_p
6950             = (next_insn != NULL_RTX
6951                && INSN_CODE (insn) == CODE_FOR_insn_group_barrier
6952                && ia64_safe_type (next_insn) == TYPE_UNKNOWN);
6953           /* We may fill up the current bundle if it is the cycle end
6954              without a group barrier.  */
6955           bundle_end_p
6956             = (only_bundle_end_p || next_insn == NULL_RTX
6957                || (GET_MODE (next_insn) == TImode
6958                    && INSN_CODE (insn) != CODE_FOR_insn_group_barrier));
6959           if (type == TYPE_F || type == TYPE_B || type == TYPE_L
6960               || type == TYPE_S
6961               /* We need to insert 2 nops for cases like M_MII.  To
6962                  guarantee issuing all insns on the same cycle for
6963                  Itanium 1, we need to issue 2 nops after the first M
6964                  insn (MnnMII where n is a nop insn).  */
6965               || (type == TYPE_M && ia64_tune == PROCESSOR_ITANIUM
6966                   && !bundle_end_p && pos == 1))
6967             issue_nops_and_insn (curr_state, 2, insn, bundle_end_p,
6968                                  only_bundle_end_p);
6969           issue_nops_and_insn (curr_state, 1, insn, bundle_end_p,
6970                                only_bundle_end_p);
6971           issue_nops_and_insn (curr_state, 0, insn, bundle_end_p,
6972                                only_bundle_end_p);
6973         }
6974       if (index_to_bundle_states [insn_num] == NULL)
6975         abort ();
6976       for (curr_state = index_to_bundle_states [insn_num];
6977            curr_state != NULL;
6978            curr_state = curr_state->next)
6979         if (verbose >= 2 && dump)
6980           {
6981             /* This structure is taken from generated code of the
6982                pipeline hazard recognizer (see file insn-attrtab.c).
6983                Please don't forget to change the structure if a new
6984                automaton is added to .md file.  */
6985             struct DFA_chip
6986             {
6987               unsigned short one_automaton_state;
6988               unsigned short oneb_automaton_state;
6989               unsigned short two_automaton_state;
6990               unsigned short twob_automaton_state;
6991             };
6992
6993             fprintf
6994               (dump,
6995                "//    Bundle state %d (orig %d, cost %d, nops %d/%d, insns %d, branch %d, state %d) for %d\n",
6996                curr_state->unique_num,
6997                (curr_state->originator == NULL
6998                 ? -1 : curr_state->originator->unique_num),
6999                curr_state->cost,
7000                curr_state->before_nops_num, curr_state->after_nops_num,
7001                curr_state->accumulated_insns_num, curr_state->branch_deviation,
7002                (ia64_tune == PROCESSOR_ITANIUM
7003                 ? ((struct DFA_chip *) curr_state->dfa_state)->oneb_automaton_state
7004                 : ((struct DFA_chip *) curr_state->dfa_state)->twob_automaton_state),
7005                INSN_UID (insn));
7006           }
7007     }
7008   if (index_to_bundle_states [insn_num] == NULL)
7009     /* We should find a solution because the 2nd insn scheduling has
7010        found one.  */
7011     abort ();
7012   /* Find a state corresponding to the best insn sequence.  */
7013   best_state = NULL;
7014   for (curr_state = index_to_bundle_states [insn_num];
7015        curr_state != NULL;
7016        curr_state = curr_state->next)
7017     /* We are just looking at the states with fully filled up last
7018        bundle.  The first we prefer insn sequences with minimal cost
7019        then with minimal inserted nops and finally with branch insns
7020        placed in the 3rd slots.  */
7021     if (curr_state->accumulated_insns_num % 3 == 0
7022         && (best_state == NULL || best_state->cost > curr_state->cost
7023             || (best_state->cost == curr_state->cost
7024                 && (curr_state->accumulated_insns_num
7025                     < best_state->accumulated_insns_num
7026                     || (curr_state->accumulated_insns_num
7027                         == best_state->accumulated_insns_num
7028                         && curr_state->branch_deviation
7029                         < best_state->branch_deviation)))))
7030       best_state = curr_state;
7031   /* Second (backward) pass: adding nops and templates.  */
7032   insn_num = best_state->before_nops_num;
7033   template0 = template1 = -1;
7034   for (curr_state = best_state;
7035        curr_state->originator != NULL;
7036        curr_state = curr_state->originator)
7037     {
7038       insn = curr_state->insn;
7039       asm_p = (GET_CODE (PATTERN (insn)) == ASM_INPUT
7040                || asm_noperands (PATTERN (insn)) >= 0);
7041       insn_num++;
7042       if (verbose >= 2 && dump)
7043         {
7044           struct DFA_chip
7045           {
7046             unsigned short one_automaton_state;
7047             unsigned short oneb_automaton_state;
7048             unsigned short two_automaton_state;
7049             unsigned short twob_automaton_state;
7050           };
7051
7052           fprintf
7053             (dump,
7054              "//    Best %d (orig %d, cost %d, nops %d/%d, insns %d, branch %d, state %d) for %d\n",
7055              curr_state->unique_num,
7056              (curr_state->originator == NULL
7057               ? -1 : curr_state->originator->unique_num),
7058              curr_state->cost,
7059              curr_state->before_nops_num, curr_state->after_nops_num,
7060              curr_state->accumulated_insns_num, curr_state->branch_deviation,
7061              (ia64_tune == PROCESSOR_ITANIUM
7062               ? ((struct DFA_chip *) curr_state->dfa_state)->oneb_automaton_state
7063               : ((struct DFA_chip *) curr_state->dfa_state)->twob_automaton_state),
7064              INSN_UID (insn));
7065         }
7066       /* Find the position in the current bundle window.  The window can
7067          contain at most two bundles.  Two bundle window means that
7068          the processor will make two bundle rotation.  */
7069       max_pos = get_max_pos (curr_state->dfa_state);
7070       if (max_pos == 6
7071           /* The following (negative template number) means that the
7072              processor did one bundle rotation.  */
7073           || (max_pos == 3 && template0 < 0))
7074         {
7075           /* We are at the end of the window -- find template(s) for
7076              its bundle(s).  */
7077           pos = max_pos;
7078           if (max_pos == 3)
7079             template0 = get_template (curr_state->dfa_state, 3);
7080           else
7081             {
7082               template1 = get_template (curr_state->dfa_state, 3);
7083               template0 = get_template (curr_state->dfa_state, 6);
7084             }
7085         }
7086       if (max_pos > 3 && template1 < 0)
7087         /* It may happen when we have the stop inside a bundle.  */
7088         {
7089           if (pos > 3)
7090             abort ();
7091           template1 = get_template (curr_state->dfa_state, 3);
7092           pos += 3;
7093         }
7094       if (!asm_p)
7095         /* Emit nops after the current insn.  */
7096         for (i = 0; i < curr_state->after_nops_num; i++)
7097           {
7098             nop = gen_nop ();
7099             emit_insn_after (nop, insn);
7100             pos--;
7101             if (pos < 0)
7102               abort ();
7103             if (pos % 3 == 0)
7104               {
7105                 /* We are at the start of a bundle: emit the template
7106                    (it should be defined).  */
7107                 if (template0 < 0)
7108                   abort ();
7109                 b = gen_bundle_selector (GEN_INT (template0));
7110                 ia64_emit_insn_before (b, nop);
7111                 /* If we have two bundle window, we make one bundle
7112                    rotation.  Otherwise template0 will be undefined
7113                    (negative value).  */
7114                 template0 = template1;
7115                 template1 = -1;
7116               }
7117           }
7118       /* Move the position backward in the window.  Group barrier has
7119          no slot.  Asm insn takes all bundle.  */
7120       if (INSN_CODE (insn) != CODE_FOR_insn_group_barrier
7121           && GET_CODE (PATTERN (insn)) != ASM_INPUT
7122           && asm_noperands (PATTERN (insn)) < 0)
7123         pos--;
7124       /* Long insn takes 2 slots.  */
7125       if (ia64_safe_type (insn) == TYPE_L)
7126         pos--;
7127       if (pos < 0)
7128         abort ();
7129       if (pos % 3 == 0
7130           && INSN_CODE (insn) != CODE_FOR_insn_group_barrier
7131           && GET_CODE (PATTERN (insn)) != ASM_INPUT
7132           && asm_noperands (PATTERN (insn)) < 0)
7133         {
7134           /* The current insn is at the bundle start: emit the
7135              template.  */
7136           if (template0 < 0)
7137             abort ();
7138           b = gen_bundle_selector (GEN_INT (template0));
7139           ia64_emit_insn_before (b, insn);
7140           b = PREV_INSN (insn);
7141           insn = b;
7142           /* See comment above in analogous place for emitting nops
7143              after the insn.  */
7144           template0 = template1;
7145           template1 = -1;
7146         }
7147       /* Emit nops after the current insn.  */
7148       for (i = 0; i < curr_state->before_nops_num; i++)
7149         {
7150           nop = gen_nop ();
7151           ia64_emit_insn_before (nop, insn);
7152           nop = PREV_INSN (insn);
7153           insn = nop;
7154           pos--;
7155           if (pos < 0)
7156             abort ();
7157           if (pos % 3 == 0)
7158             {
7159               /* See comment above in analogous place for emitting nops
7160                  after the insn.  */
7161               if (template0 < 0)
7162                 abort ();
7163               b = gen_bundle_selector (GEN_INT (template0));
7164               ia64_emit_insn_before (b, insn);
7165               b = PREV_INSN (insn);
7166               insn = b;
7167               template0 = template1;
7168               template1 = -1;
7169             }
7170         }
7171     }
7172   if (ia64_tune == PROCESSOR_ITANIUM)
7173     /* Insert additional cycles for MM-insns (MMMUL and MMSHF).
7174        Itanium1 has a strange design, if the distance between an insn
7175        and dependent MM-insn is less 4 then we have a 6 additional
7176        cycles stall.  So we make the distance equal to 4 cycles if it
7177        is less.  */
7178     for (insn = get_next_important_insn (NEXT_INSN (prev_head_insn), tail);
7179          insn != NULL_RTX;
7180          insn = next_insn)
7181       {
7182         if (!INSN_P (insn)
7183             || ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IGNORE
7184             || GET_CODE (PATTERN (insn)) == USE
7185             || GET_CODE (PATTERN (insn)) == CLOBBER)
7186           abort ();
7187         next_insn = get_next_important_insn (NEXT_INSN (insn), tail);
7188         if (INSN_UID (insn) < clocks_length && add_cycles [INSN_UID (insn)])
7189           /* We found a MM-insn which needs additional cycles.  */
7190           {
7191             rtx last;
7192             int i, j, n;
7193             int pred_stop_p;
7194
7195             /* Now we are searching for a template of the bundle in
7196                which the MM-insn is placed and the position of the
7197                insn in the bundle (0, 1, 2).  Also we are searching
7198                for that there is a stop before the insn.  */
7199             last = prev_active_insn (insn);
7200             pred_stop_p = recog_memoized (last) == CODE_FOR_insn_group_barrier;
7201             if (pred_stop_p)
7202               last = prev_active_insn (last);
7203             n = 0;
7204             for (;; last = prev_active_insn (last))
7205               if (recog_memoized (last) == CODE_FOR_bundle_selector)
7206                 {
7207                   template0 = XINT (XVECEXP (PATTERN (last), 0, 0), 0);
7208                   if (template0 == 9)
7209                     /* The insn is in MLX bundle.  Change the template
7210                        onto MFI because we will add nops before the
7211                        insn.  It simplifies subsequent code a lot.  */
7212                     PATTERN (last)
7213                       = gen_bundle_selector (const2_rtx); /* -> MFI */
7214                   break;
7215                 }
7216               else if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
7217                 n++;
7218             /* Some check of correctness: the stop is not at the
7219                bundle start, there are no more 3 insns in the bundle,
7220                and the MM-insn is not at the start of bundle with
7221                template MLX.  */
7222             if ((pred_stop_p && n == 0) || n > 2
7223                 || (template0 == 9 && n != 0))
7224               abort ();
7225             /* Put nops after the insn in the bundle.  */
7226             for (j = 3 - n; j > 0; j --)
7227               ia64_emit_insn_before (gen_nop (), insn);
7228             /* It takes into account that we will add more N nops
7229                before the insn lately -- please see code below.  */
7230             add_cycles [INSN_UID (insn)]--;
7231             if (!pred_stop_p || add_cycles [INSN_UID (insn)])
7232               ia64_emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
7233                                      insn);
7234             if (pred_stop_p)
7235               add_cycles [INSN_UID (insn)]--;
7236             for (i = add_cycles [INSN_UID (insn)]; i > 0; i--)
7237               {
7238                 /* Insert "MII;" template.  */
7239                 ia64_emit_insn_before (gen_bundle_selector (const0_rtx),
7240                                        insn);
7241                 ia64_emit_insn_before (gen_nop (), insn);
7242                 ia64_emit_insn_before (gen_nop (), insn);
7243                 if (i > 1)
7244                   {
7245                     /* To decrease code size, we use "MI;I;"
7246                        template.  */
7247                     ia64_emit_insn_before
7248                       (gen_insn_group_barrier (GEN_INT (3)), insn);
7249                     i--;
7250                   }
7251                 ia64_emit_insn_before (gen_nop (), insn);
7252                 ia64_emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
7253                                        insn);
7254               }
7255             /* Put the MM-insn in the same slot of a bundle with the
7256                same template as the original one.  */
7257             ia64_emit_insn_before (gen_bundle_selector (GEN_INT (template0)),
7258                                    insn);
7259             /* To put the insn in the same slot, add necessary number
7260                of nops.  */
7261             for (j = n; j > 0; j --)
7262               ia64_emit_insn_before (gen_nop (), insn);
7263             /* Put the stop if the original bundle had it.  */
7264             if (pred_stop_p)
7265               ia64_emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
7266                                      insn);
7267           }
7268       }
7269   free (index_to_bundle_states);
7270   finish_bundle_state_table ();
7271   bundling_p = 0;
7272   dfa_clean_insn_cache ();
7273 }
7274
7275 /* The following function is called at the end of scheduling BB or
7276    EBB.  After reload, it inserts stop bits and does insn bundling.  */
7277
7278 static void
7279 ia64_sched_finish (FILE *dump, int sched_verbose)
7280 {
7281   if (sched_verbose)
7282     fprintf (dump, "// Finishing schedule.\n");
7283   if (!reload_completed)
7284     return;
7285   if (reload_completed)
7286     {
7287       final_emit_insn_group_barriers (dump);
7288       bundling (dump, sched_verbose, current_sched_info->prev_head,
7289                 current_sched_info->next_tail);
7290       if (sched_verbose && dump)
7291         fprintf (dump, "//    finishing %d-%d\n",
7292                  INSN_UID (NEXT_INSN (current_sched_info->prev_head)),
7293                  INSN_UID (PREV_INSN (current_sched_info->next_tail)));
7294
7295       return;
7296     }
7297 }
7298
7299 /* The following function inserts stop bits in scheduled BB or EBB.  */
7300
7301 static void
7302 final_emit_insn_group_barriers (FILE *dump ATTRIBUTE_UNUSED)
7303 {
7304   rtx insn;
7305   int need_barrier_p = 0;
7306   rtx prev_insn = NULL_RTX;
7307
7308   init_insn_group_barriers ();
7309
7310   for (insn = NEXT_INSN (current_sched_info->prev_head);
7311        insn != current_sched_info->next_tail;
7312        insn = NEXT_INSN (insn))
7313     {
7314       if (GET_CODE (insn) == BARRIER)
7315         {
7316           rtx last = prev_active_insn (insn);
7317
7318           if (! last)
7319             continue;
7320           if (GET_CODE (last) == JUMP_INSN
7321               && GET_CODE (PATTERN (last)) == ADDR_DIFF_VEC)
7322             last = prev_active_insn (last);
7323           if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
7324             emit_insn_after (gen_insn_group_barrier (GEN_INT (3)), last);
7325
7326           init_insn_group_barriers ();
7327           need_barrier_p = 0;
7328           prev_insn = NULL_RTX;
7329         }
7330       else if (INSN_P (insn))
7331         {
7332           if (recog_memoized (insn) == CODE_FOR_insn_group_barrier)
7333             {
7334               init_insn_group_barriers ();
7335               need_barrier_p = 0;
7336               prev_insn = NULL_RTX;
7337             }
7338           else if (need_barrier_p || group_barrier_needed_p (insn))
7339             {
7340               if (TARGET_EARLY_STOP_BITS)
7341                 {
7342                   rtx last;
7343
7344                   for (last = insn;
7345                        last != current_sched_info->prev_head;
7346                        last = PREV_INSN (last))
7347                     if (INSN_P (last) && GET_MODE (last) == TImode
7348                         && stops_p [INSN_UID (last)])
7349                       break;
7350                   if (last == current_sched_info->prev_head)
7351                     last = insn;
7352                   last = prev_active_insn (last);
7353                   if (last
7354                       && recog_memoized (last) != CODE_FOR_insn_group_barrier)
7355                     emit_insn_after (gen_insn_group_barrier (GEN_INT (3)),
7356                                      last);
7357                   init_insn_group_barriers ();
7358                   for (last = NEXT_INSN (last);
7359                        last != insn;
7360                        last = NEXT_INSN (last))
7361                     if (INSN_P (last))
7362                       group_barrier_needed_p (last);
7363                 }
7364               else
7365                 {
7366                   emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
7367                                     insn);
7368                   init_insn_group_barriers ();
7369                 }
7370               group_barrier_needed_p (insn);
7371               prev_insn = NULL_RTX;
7372             }
7373           else if (recog_memoized (insn) >= 0)
7374             prev_insn = insn;
7375           need_barrier_p = (GET_CODE (insn) == CALL_INSN
7376                             || GET_CODE (PATTERN (insn)) == ASM_INPUT
7377                             || asm_noperands (PATTERN (insn)) >= 0);
7378         }
7379     }
7380 }
7381
7382 \f
7383
7384 /* If the following function returns TRUE, we will use the the DFA
7385    insn scheduler.  */
7386
7387 static int
7388 ia64_use_dfa_pipeline_interface (void)
7389 {
7390   return 1;
7391 }
7392
7393 /* If the following function returns TRUE, we will use the the DFA
7394    insn scheduler.  */
7395
7396 static int
7397 ia64_first_cycle_multipass_dfa_lookahead (void)
7398 {
7399   return (reload_completed ? 6 : 4);
7400 }
7401
7402 /* The following function initiates variable `dfa_pre_cycle_insn'.  */
7403
7404 static void
7405 ia64_init_dfa_pre_cycle_insn (void)
7406 {
7407   if (temp_dfa_state == NULL)
7408     {
7409       dfa_state_size = state_size ();
7410       temp_dfa_state = xmalloc (dfa_state_size);
7411       prev_cycle_state = xmalloc (dfa_state_size);
7412     }
7413   dfa_pre_cycle_insn = make_insn_raw (gen_pre_cycle ());
7414   PREV_INSN (dfa_pre_cycle_insn) = NEXT_INSN (dfa_pre_cycle_insn) = NULL_RTX;
7415   recog_memoized (dfa_pre_cycle_insn);
7416   dfa_stop_insn = make_insn_raw (gen_insn_group_barrier (GEN_INT (3)));
7417   PREV_INSN (dfa_stop_insn) = NEXT_INSN (dfa_stop_insn) = NULL_RTX;
7418   recog_memoized (dfa_stop_insn);
7419 }
7420
7421 /* The following function returns the pseudo insn DFA_PRE_CYCLE_INSN
7422    used by the DFA insn scheduler.  */
7423
7424 static rtx
7425 ia64_dfa_pre_cycle_insn (void)
7426 {
7427   return dfa_pre_cycle_insn;
7428 }
7429
7430 /* The following function returns TRUE if PRODUCER (of type ilog or
7431    ld) produces address for CONSUMER (of type st or stf). */
7432
7433 int
7434 ia64_st_address_bypass_p (rtx producer, rtx consumer)
7435 {
7436   rtx dest, reg, mem;
7437
7438   if (producer == NULL_RTX || consumer == NULL_RTX)
7439     abort ();
7440   dest = ia64_single_set (producer);
7441   if (dest == NULL_RTX || (reg = SET_DEST (dest)) == NULL_RTX
7442       || (GET_CODE (reg) != REG && GET_CODE (reg) != SUBREG))
7443     abort ();
7444   if (GET_CODE (reg) == SUBREG)
7445     reg = SUBREG_REG (reg);
7446   dest = ia64_single_set (consumer);
7447   if (dest == NULL_RTX || (mem = SET_DEST (dest)) == NULL_RTX
7448       || GET_CODE (mem) != MEM)
7449     abort ();
7450   return reg_mentioned_p (reg, mem);
7451 }
7452
7453 /* The following function returns TRUE if PRODUCER (of type ilog or
7454    ld) produces address for CONSUMER (of type ld or fld). */
7455
7456 int
7457 ia64_ld_address_bypass_p (rtx producer, rtx consumer)
7458 {
7459   rtx dest, src, reg, mem;
7460
7461   if (producer == NULL_RTX || consumer == NULL_RTX)
7462     abort ();
7463   dest = ia64_single_set (producer);
7464   if (dest == NULL_RTX || (reg = SET_DEST (dest)) == NULL_RTX
7465       || (GET_CODE (reg) != REG && GET_CODE (reg) != SUBREG))
7466     abort ();
7467   if (GET_CODE (reg) == SUBREG)
7468     reg = SUBREG_REG (reg);
7469   src = ia64_single_set (consumer);
7470   if (src == NULL_RTX || (mem = SET_SRC (src)) == NULL_RTX)
7471     abort ();
7472   if (GET_CODE (mem) == UNSPEC && XVECLEN (mem, 0) > 0)
7473     mem = XVECEXP (mem, 0, 0);
7474   while (GET_CODE (mem) == SUBREG || GET_CODE (mem) == ZERO_EXTEND)
7475     mem = XEXP (mem, 0);
7476
7477   /* Note that LO_SUM is used for GOT loads.  */
7478   if (GET_CODE (mem) != LO_SUM && GET_CODE (mem) != MEM)
7479     abort ();
7480
7481   return reg_mentioned_p (reg, mem);
7482 }
7483
7484 /* The following function returns TRUE if INSN produces address for a
7485    load/store insn.  We will place such insns into M slot because it
7486    decreases its latency time.  */
7487
7488 int
7489 ia64_produce_address_p (rtx insn)
7490 {
7491   return insn->call;
7492 }
7493
7494 \f
7495 /* Emit pseudo-ops for the assembler to describe predicate relations.
7496    At present this assumes that we only consider predicate pairs to
7497    be mutex, and that the assembler can deduce proper values from
7498    straight-line code.  */
7499
7500 static void
7501 emit_predicate_relation_info (void)
7502 {
7503   basic_block bb;
7504
7505   FOR_EACH_BB_REVERSE (bb)
7506     {
7507       int r;
7508       rtx head = BB_HEAD (bb);
7509
7510       /* We only need such notes at code labels.  */
7511       if (GET_CODE (head) != CODE_LABEL)
7512         continue;
7513       if (GET_CODE (NEXT_INSN (head)) == NOTE
7514           && NOTE_LINE_NUMBER (NEXT_INSN (head)) == NOTE_INSN_BASIC_BLOCK)
7515         head = NEXT_INSN (head);
7516
7517       for (r = PR_REG (0); r < PR_REG (64); r += 2)
7518         if (REGNO_REG_SET_P (bb->global_live_at_start, r))
7519           {
7520             rtx p = gen_rtx_REG (BImode, r);
7521             rtx n = emit_insn_after (gen_pred_rel_mutex (p), head);
7522             if (head == BB_END (bb))
7523               BB_END (bb) = n;
7524             head = n;
7525           }
7526     }
7527
7528   /* Look for conditional calls that do not return, and protect predicate
7529      relations around them.  Otherwise the assembler will assume the call
7530      returns, and complain about uses of call-clobbered predicates after
7531      the call.  */
7532   FOR_EACH_BB_REVERSE (bb)
7533     {
7534       rtx insn = BB_HEAD (bb);
7535
7536       while (1)
7537         {
7538           if (GET_CODE (insn) == CALL_INSN
7539               && GET_CODE (PATTERN (insn)) == COND_EXEC
7540               && find_reg_note (insn, REG_NORETURN, NULL_RTX))
7541             {
7542               rtx b = emit_insn_before (gen_safe_across_calls_all (), insn);
7543               rtx a = emit_insn_after (gen_safe_across_calls_normal (), insn);
7544               if (BB_HEAD (bb) == insn)
7545                 BB_HEAD (bb) = b;
7546               if (BB_END (bb) == insn)
7547                 BB_END (bb) = a;
7548             }
7549
7550           if (insn == BB_END (bb))
7551             break;
7552           insn = NEXT_INSN (insn);
7553         }
7554     }
7555 }
7556
7557 /* Perform machine dependent operations on the rtl chain INSNS.  */
7558
7559 static void
7560 ia64_reorg (void)
7561 {
7562   /* We are freeing block_for_insn in the toplev to keep compatibility
7563      with old MDEP_REORGS that are not CFG based.  Recompute it now.  */
7564   compute_bb_for_insn ();
7565
7566   /* If optimizing, we'll have split before scheduling.  */
7567   if (optimize == 0)
7568     split_all_insns (0);
7569
7570   /* ??? update_life_info_in_dirty_blocks fails to terminate during
7571      non-optimizing bootstrap.  */
7572   update_life_info (NULL, UPDATE_LIFE_GLOBAL_RM_NOTES, PROP_DEATH_NOTES);
7573
7574   if (ia64_flag_schedule_insns2)
7575     {
7576       timevar_push (TV_SCHED2);
7577       ia64_final_schedule = 1;
7578
7579       initiate_bundle_states ();
7580       ia64_nop = make_insn_raw (gen_nop ());
7581       PREV_INSN (ia64_nop) = NEXT_INSN (ia64_nop) = NULL_RTX;
7582       recog_memoized (ia64_nop);
7583       clocks_length = get_max_uid () + 1;
7584       stops_p = xcalloc (1, clocks_length);
7585       if (ia64_tune == PROCESSOR_ITANIUM)
7586         {
7587           clocks = xcalloc (clocks_length, sizeof (int));
7588           add_cycles = xcalloc (clocks_length, sizeof (int));
7589         }
7590       if (ia64_tune == PROCESSOR_ITANIUM2)
7591         {
7592           pos_1 = get_cpu_unit_code ("2_1");
7593           pos_2 = get_cpu_unit_code ("2_2");
7594           pos_3 = get_cpu_unit_code ("2_3");
7595           pos_4 = get_cpu_unit_code ("2_4");
7596           pos_5 = get_cpu_unit_code ("2_5");
7597           pos_6 = get_cpu_unit_code ("2_6");
7598           _0mii_ = get_cpu_unit_code ("2b_0mii.");
7599           _0mmi_ = get_cpu_unit_code ("2b_0mmi.");
7600           _0mfi_ = get_cpu_unit_code ("2b_0mfi.");
7601           _0mmf_ = get_cpu_unit_code ("2b_0mmf.");
7602           _0bbb_ = get_cpu_unit_code ("2b_0bbb.");
7603           _0mbb_ = get_cpu_unit_code ("2b_0mbb.");
7604           _0mib_ = get_cpu_unit_code ("2b_0mib.");
7605           _0mmb_ = get_cpu_unit_code ("2b_0mmb.");
7606           _0mfb_ = get_cpu_unit_code ("2b_0mfb.");
7607           _0mlx_ = get_cpu_unit_code ("2b_0mlx.");
7608           _1mii_ = get_cpu_unit_code ("2b_1mii.");
7609           _1mmi_ = get_cpu_unit_code ("2b_1mmi.");
7610           _1mfi_ = get_cpu_unit_code ("2b_1mfi.");
7611           _1mmf_ = get_cpu_unit_code ("2b_1mmf.");
7612           _1bbb_ = get_cpu_unit_code ("2b_1bbb.");
7613           _1mbb_ = get_cpu_unit_code ("2b_1mbb.");
7614           _1mib_ = get_cpu_unit_code ("2b_1mib.");
7615           _1mmb_ = get_cpu_unit_code ("2b_1mmb.");
7616           _1mfb_ = get_cpu_unit_code ("2b_1mfb.");
7617           _1mlx_ = get_cpu_unit_code ("2b_1mlx.");
7618         }
7619       else
7620         {
7621           pos_1 = get_cpu_unit_code ("1_1");
7622           pos_2 = get_cpu_unit_code ("1_2");
7623           pos_3 = get_cpu_unit_code ("1_3");
7624           pos_4 = get_cpu_unit_code ("1_4");
7625           pos_5 = get_cpu_unit_code ("1_5");
7626           pos_6 = get_cpu_unit_code ("1_6");
7627           _0mii_ = get_cpu_unit_code ("1b_0mii.");
7628           _0mmi_ = get_cpu_unit_code ("1b_0mmi.");
7629           _0mfi_ = get_cpu_unit_code ("1b_0mfi.");
7630           _0mmf_ = get_cpu_unit_code ("1b_0mmf.");
7631           _0bbb_ = get_cpu_unit_code ("1b_0bbb.");
7632           _0mbb_ = get_cpu_unit_code ("1b_0mbb.");
7633           _0mib_ = get_cpu_unit_code ("1b_0mib.");
7634           _0mmb_ = get_cpu_unit_code ("1b_0mmb.");
7635           _0mfb_ = get_cpu_unit_code ("1b_0mfb.");
7636           _0mlx_ = get_cpu_unit_code ("1b_0mlx.");
7637           _1mii_ = get_cpu_unit_code ("1b_1mii.");
7638           _1mmi_ = get_cpu_unit_code ("1b_1mmi.");
7639           _1mfi_ = get_cpu_unit_code ("1b_1mfi.");
7640           _1mmf_ = get_cpu_unit_code ("1b_1mmf.");
7641           _1bbb_ = get_cpu_unit_code ("1b_1bbb.");
7642           _1mbb_ = get_cpu_unit_code ("1b_1mbb.");
7643           _1mib_ = get_cpu_unit_code ("1b_1mib.");
7644           _1mmb_ = get_cpu_unit_code ("1b_1mmb.");
7645           _1mfb_ = get_cpu_unit_code ("1b_1mfb.");
7646           _1mlx_ = get_cpu_unit_code ("1b_1mlx.");
7647         }
7648       schedule_ebbs (dump_file);
7649       finish_bundle_states ();
7650       if (ia64_tune == PROCESSOR_ITANIUM)
7651         {
7652           free (add_cycles);
7653           free (clocks);
7654         }
7655       free (stops_p);
7656       emit_insn_group_barriers (dump_file);
7657
7658       ia64_final_schedule = 0;
7659       timevar_pop (TV_SCHED2);
7660     }
7661   else
7662     emit_all_insn_group_barriers (dump_file);
7663
7664   /* A call must not be the last instruction in a function, so that the
7665      return address is still within the function, so that unwinding works
7666      properly.  Note that IA-64 differs from dwarf2 on this point.  */
7667   if (flag_unwind_tables || (flag_exceptions && !USING_SJLJ_EXCEPTIONS))
7668     {
7669       rtx insn;
7670       int saw_stop = 0;
7671
7672       insn = get_last_insn ();
7673       if (! INSN_P (insn))
7674         insn = prev_active_insn (insn);
7675       if (GET_CODE (insn) == INSN
7676           && GET_CODE (PATTERN (insn)) == UNSPEC_VOLATILE
7677           && XINT (PATTERN (insn), 1) == UNSPECV_INSN_GROUP_BARRIER)
7678         {
7679           saw_stop = 1;
7680           insn = prev_active_insn (insn);
7681         }
7682       if (GET_CODE (insn) == CALL_INSN)
7683         {
7684           if (! saw_stop)
7685             emit_insn (gen_insn_group_barrier (GEN_INT (3)));
7686           emit_insn (gen_break_f ());
7687           emit_insn (gen_insn_group_barrier (GEN_INT (3)));
7688         }
7689     }
7690
7691   fixup_errata ();
7692   emit_predicate_relation_info ();
7693
7694   if (ia64_flag_var_tracking)
7695     {
7696       timevar_push (TV_VAR_TRACKING);
7697       variable_tracking_main ();
7698       timevar_pop (TV_VAR_TRACKING);
7699     }
7700 }
7701 \f
7702 /* Return true if REGNO is used by the epilogue.  */
7703
7704 int
7705 ia64_epilogue_uses (int regno)
7706 {
7707   switch (regno)
7708     {
7709     case R_GR (1):
7710       /* With a call to a function in another module, we will write a new
7711          value to "gp".  After returning from such a call, we need to make
7712          sure the function restores the original gp-value, even if the
7713          function itself does not use the gp anymore.  */
7714       return !(TARGET_AUTO_PIC || TARGET_NO_PIC);
7715
7716     case IN_REG (0): case IN_REG (1): case IN_REG (2): case IN_REG (3):
7717     case IN_REG (4): case IN_REG (5): case IN_REG (6): case IN_REG (7):
7718       /* For functions defined with the syscall_linkage attribute, all
7719          input registers are marked as live at all function exits.  This
7720          prevents the register allocator from using the input registers,
7721          which in turn makes it possible to restart a system call after
7722          an interrupt without having to save/restore the input registers.
7723          This also prevents kernel data from leaking to application code.  */
7724       return lookup_attribute ("syscall_linkage",
7725            TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))) != NULL;
7726
7727     case R_BR (0):
7728       /* Conditional return patterns can't represent the use of `b0' as
7729          the return address, so we force the value live this way.  */
7730       return 1;
7731
7732     case AR_PFS_REGNUM:
7733       /* Likewise for ar.pfs, which is used by br.ret.  */
7734       return 1;
7735
7736     default:
7737       return 0;
7738     }
7739 }
7740
7741 /* Return true if REGNO is used by the frame unwinder.  */
7742
7743 int
7744 ia64_eh_uses (int regno)
7745 {
7746   if (! reload_completed)
7747     return 0;
7748
7749   if (current_frame_info.reg_save_b0
7750       && regno == current_frame_info.reg_save_b0)
7751     return 1;
7752   if (current_frame_info.reg_save_pr
7753       && regno == current_frame_info.reg_save_pr)
7754     return 1;
7755   if (current_frame_info.reg_save_ar_pfs
7756       && regno == current_frame_info.reg_save_ar_pfs)
7757     return 1;
7758   if (current_frame_info.reg_save_ar_unat
7759       && regno == current_frame_info.reg_save_ar_unat)
7760     return 1;
7761   if (current_frame_info.reg_save_ar_lc
7762       && regno == current_frame_info.reg_save_ar_lc)
7763     return 1;
7764
7765   return 0;
7766 }
7767 \f
7768 /* Return true if this goes in small data/bss.  */
7769
7770 /* ??? We could also support own long data here.  Generating movl/add/ld8
7771    instead of addl,ld8/ld8.  This makes the code bigger, but should make the
7772    code faster because there is one less load.  This also includes incomplete
7773    types which can't go in sdata/sbss.  */
7774
7775 static bool
7776 ia64_in_small_data_p (tree exp)
7777 {
7778   if (TARGET_NO_SDATA)
7779     return false;
7780
7781   /* We want to merge strings, so we never consider them small data.  */
7782   if (TREE_CODE (exp) == STRING_CST)
7783     return false;
7784
7785   /* Functions are never small data.  */
7786   if (TREE_CODE (exp) == FUNCTION_DECL)
7787     return false;
7788
7789   if (TREE_CODE (exp) == VAR_DECL && DECL_SECTION_NAME (exp))
7790     {
7791       const char *section = TREE_STRING_POINTER (DECL_SECTION_NAME (exp));
7792       if (strcmp (section, ".sdata") == 0
7793           || strcmp (section, ".sbss") == 0)
7794         return true;
7795     }
7796   else
7797     {
7798       HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (exp));
7799
7800       /* If this is an incomplete type with size 0, then we can't put it
7801          in sdata because it might be too big when completed.  */
7802       if (size > 0 && size <= ia64_section_threshold)
7803         return true;
7804     }
7805
7806   return false;
7807 }
7808 \f
7809 /* Output assembly directives for prologue regions.  */
7810
7811 /* The current basic block number.  */
7812
7813 static bool last_block;
7814
7815 /* True if we need a copy_state command at the start of the next block.  */
7816
7817 static bool need_copy_state;
7818
7819 /* The function emits unwind directives for the start of an epilogue.  */
7820
7821 static void
7822 process_epilogue (void)
7823 {
7824   /* If this isn't the last block of the function, then we need to label the
7825      current state, and copy it back in at the start of the next block.  */
7826
7827   if (!last_block)
7828     {
7829       fprintf (asm_out_file, "\t.label_state 1\n");
7830       need_copy_state = true;
7831     }
7832
7833   fprintf (asm_out_file, "\t.restore sp\n");
7834 }
7835
7836 /* This function processes a SET pattern looking for specific patterns
7837    which result in emitting an assembly directive required for unwinding.  */
7838
7839 static int
7840 process_set (FILE *asm_out_file, rtx pat)
7841 {
7842   rtx src = SET_SRC (pat);
7843   rtx dest = SET_DEST (pat);
7844   int src_regno, dest_regno;
7845
7846   /* Look for the ALLOC insn.  */
7847   if (GET_CODE (src) == UNSPEC_VOLATILE
7848       && XINT (src, 1) == UNSPECV_ALLOC
7849       && GET_CODE (dest) == REG)
7850     {
7851       dest_regno = REGNO (dest);
7852
7853       /* If this isn't the final destination for ar.pfs, the alloc
7854          shouldn't have been marked frame related.  */
7855       if (dest_regno != current_frame_info.reg_save_ar_pfs)
7856         abort ();
7857
7858       fprintf (asm_out_file, "\t.save ar.pfs, r%d\n",
7859                ia64_dbx_register_number (dest_regno));
7860       return 1;
7861     }
7862
7863   /* Look for SP = ....  */
7864   if (GET_CODE (dest) == REG && REGNO (dest) == STACK_POINTER_REGNUM)
7865     {
7866       if (GET_CODE (src) == PLUS)
7867         {
7868           rtx op0 = XEXP (src, 0);
7869           rtx op1 = XEXP (src, 1);
7870           if (op0 == dest && GET_CODE (op1) == CONST_INT)
7871             {
7872               if (INTVAL (op1) < 0)
7873                 fprintf (asm_out_file, "\t.fframe "HOST_WIDE_INT_PRINT_DEC"\n",
7874                          -INTVAL (op1));
7875               else
7876                 process_epilogue ();
7877             }
7878           else
7879             abort ();
7880         }
7881       else if (GET_CODE (src) == REG
7882                && REGNO (src) == HARD_FRAME_POINTER_REGNUM)
7883         process_epilogue ();
7884       else
7885         abort ();
7886
7887       return 1;
7888     }
7889
7890   /* Register move we need to look at.  */
7891   if (GET_CODE (dest) == REG && GET_CODE (src) == REG)
7892     {
7893       src_regno = REGNO (src);
7894       dest_regno = REGNO (dest);
7895
7896       switch (src_regno)
7897         {
7898         case BR_REG (0):
7899           /* Saving return address pointer.  */
7900           if (dest_regno != current_frame_info.reg_save_b0)
7901             abort ();
7902           fprintf (asm_out_file, "\t.save rp, r%d\n",
7903                    ia64_dbx_register_number (dest_regno));
7904           return 1;
7905
7906         case PR_REG (0):
7907           if (dest_regno != current_frame_info.reg_save_pr)
7908             abort ();
7909           fprintf (asm_out_file, "\t.save pr, r%d\n",
7910                    ia64_dbx_register_number (dest_regno));
7911           return 1;
7912
7913         case AR_UNAT_REGNUM:
7914           if (dest_regno != current_frame_info.reg_save_ar_unat)
7915             abort ();
7916           fprintf (asm_out_file, "\t.save ar.unat, r%d\n",
7917                    ia64_dbx_register_number (dest_regno));
7918           return 1;
7919
7920         case AR_LC_REGNUM:
7921           if (dest_regno != current_frame_info.reg_save_ar_lc)
7922             abort ();
7923           fprintf (asm_out_file, "\t.save ar.lc, r%d\n",
7924                    ia64_dbx_register_number (dest_regno));
7925           return 1;
7926
7927         case STACK_POINTER_REGNUM:
7928           if (dest_regno != HARD_FRAME_POINTER_REGNUM
7929               || ! frame_pointer_needed)
7930             abort ();
7931           fprintf (asm_out_file, "\t.vframe r%d\n",
7932                    ia64_dbx_register_number (dest_regno));
7933           return 1;
7934
7935         default:
7936           /* Everything else should indicate being stored to memory.  */
7937           abort ();
7938         }
7939     }
7940
7941   /* Memory store we need to look at.  */
7942   if (GET_CODE (dest) == MEM && GET_CODE (src) == REG)
7943     {
7944       long off;
7945       rtx base;
7946       const char *saveop;
7947
7948       if (GET_CODE (XEXP (dest, 0)) == REG)
7949         {
7950           base = XEXP (dest, 0);
7951           off = 0;
7952         }
7953       else if (GET_CODE (XEXP (dest, 0)) == PLUS
7954                && GET_CODE (XEXP (XEXP (dest, 0), 1)) == CONST_INT)
7955         {
7956           base = XEXP (XEXP (dest, 0), 0);
7957           off = INTVAL (XEXP (XEXP (dest, 0), 1));
7958         }
7959       else
7960         abort ();
7961
7962       if (base == hard_frame_pointer_rtx)
7963         {
7964           saveop = ".savepsp";
7965           off = - off;
7966         }
7967       else if (base == stack_pointer_rtx)
7968         saveop = ".savesp";
7969       else
7970         abort ();
7971
7972       src_regno = REGNO (src);
7973       switch (src_regno)
7974         {
7975         case BR_REG (0):
7976           if (current_frame_info.reg_save_b0 != 0)
7977             abort ();
7978           fprintf (asm_out_file, "\t%s rp, %ld\n", saveop, off);
7979           return 1;
7980
7981         case PR_REG (0):
7982           if (current_frame_info.reg_save_pr != 0)
7983             abort ();
7984           fprintf (asm_out_file, "\t%s pr, %ld\n", saveop, off);
7985           return 1;
7986
7987         case AR_LC_REGNUM:
7988           if (current_frame_info.reg_save_ar_lc != 0)
7989             abort ();
7990           fprintf (asm_out_file, "\t%s ar.lc, %ld\n", saveop, off);
7991           return 1;
7992
7993         case AR_PFS_REGNUM:
7994           if (current_frame_info.reg_save_ar_pfs != 0)
7995             abort ();
7996           fprintf (asm_out_file, "\t%s ar.pfs, %ld\n", saveop, off);
7997           return 1;
7998
7999         case AR_UNAT_REGNUM:
8000           if (current_frame_info.reg_save_ar_unat != 0)
8001             abort ();
8002           fprintf (asm_out_file, "\t%s ar.unat, %ld\n", saveop, off);
8003           return 1;
8004
8005         case GR_REG (4):
8006         case GR_REG (5):
8007         case GR_REG (6):
8008         case GR_REG (7):
8009           fprintf (asm_out_file, "\t.save.g 0x%x\n",
8010                    1 << (src_regno - GR_REG (4)));
8011           return 1;
8012
8013         case BR_REG (1):
8014         case BR_REG (2):
8015         case BR_REG (3):
8016         case BR_REG (4):
8017         case BR_REG (5):
8018           fprintf (asm_out_file, "\t.save.b 0x%x\n",
8019                    1 << (src_regno - BR_REG (1)));
8020           return 1;
8021
8022         case FR_REG (2):
8023         case FR_REG (3):
8024         case FR_REG (4):
8025         case FR_REG (5):
8026           fprintf (asm_out_file, "\t.save.f 0x%x\n",
8027                    1 << (src_regno - FR_REG (2)));
8028           return 1;
8029
8030         case FR_REG (16): case FR_REG (17): case FR_REG (18): case FR_REG (19):
8031         case FR_REG (20): case FR_REG (21): case FR_REG (22): case FR_REG (23):
8032         case FR_REG (24): case FR_REG (25): case FR_REG (26): case FR_REG (27):
8033         case FR_REG (28): case FR_REG (29): case FR_REG (30): case FR_REG (31):
8034           fprintf (asm_out_file, "\t.save.gf 0x0, 0x%x\n",
8035                    1 << (src_regno - FR_REG (12)));
8036           return 1;
8037
8038         default:
8039           return 0;
8040         }
8041     }
8042
8043   return 0;
8044 }
8045
8046
8047 /* This function looks at a single insn and emits any directives
8048    required to unwind this insn.  */
8049 void
8050 process_for_unwind_directive (FILE *asm_out_file, rtx insn)
8051 {
8052   if (flag_unwind_tables
8053       || (flag_exceptions && !USING_SJLJ_EXCEPTIONS))
8054     {
8055       rtx pat;
8056
8057       if (GET_CODE (insn) == NOTE
8058           && NOTE_LINE_NUMBER (insn) == NOTE_INSN_BASIC_BLOCK)
8059         {
8060           last_block = NOTE_BASIC_BLOCK (insn)->next_bb == EXIT_BLOCK_PTR;
8061
8062           /* Restore unwind state from immediately before the epilogue.  */
8063           if (need_copy_state)
8064             {
8065               fprintf (asm_out_file, "\t.body\n");
8066               fprintf (asm_out_file, "\t.copy_state 1\n");
8067               need_copy_state = false;
8068             }
8069         }
8070
8071       if (GET_CODE (insn) == NOTE || ! RTX_FRAME_RELATED_P (insn))
8072         return;
8073
8074       pat = find_reg_note (insn, REG_FRAME_RELATED_EXPR, NULL_RTX);
8075       if (pat)
8076         pat = XEXP (pat, 0);
8077       else
8078         pat = PATTERN (insn);
8079
8080       switch (GET_CODE (pat))
8081         {
8082         case SET:
8083           process_set (asm_out_file, pat);
8084           break;
8085
8086         case PARALLEL:
8087           {
8088             int par_index;
8089             int limit = XVECLEN (pat, 0);
8090             for (par_index = 0; par_index < limit; par_index++)
8091               {
8092                 rtx x = XVECEXP (pat, 0, par_index);
8093                 if (GET_CODE (x) == SET)
8094                   process_set (asm_out_file, x);
8095               }
8096             break;
8097           }
8098
8099         default:
8100           abort ();
8101         }
8102     }
8103 }
8104
8105 \f
8106 void
8107 ia64_init_builtins (void)
8108 {
8109   tree psi_type_node = build_pointer_type (integer_type_node);
8110   tree pdi_type_node = build_pointer_type (long_integer_type_node);
8111
8112   /* __sync_val_compare_and_swap_si, __sync_bool_compare_and_swap_si */
8113   tree si_ftype_psi_si_si
8114     = build_function_type_list (integer_type_node,
8115                                 psi_type_node, integer_type_node,
8116                                 integer_type_node, NULL_TREE);
8117
8118   /* __sync_val_compare_and_swap_di */
8119   tree di_ftype_pdi_di_di
8120     = build_function_type_list (long_integer_type_node,
8121                                 pdi_type_node, long_integer_type_node,
8122                                 long_integer_type_node, NULL_TREE);
8123   /* __sync_bool_compare_and_swap_di */
8124   tree si_ftype_pdi_di_di
8125     = build_function_type_list (integer_type_node,
8126                                 pdi_type_node, long_integer_type_node,
8127                                 long_integer_type_node, NULL_TREE);
8128   /* __sync_synchronize */
8129   tree void_ftype_void
8130     = build_function_type (void_type_node, void_list_node);
8131
8132   /* __sync_lock_test_and_set_si */
8133   tree si_ftype_psi_si
8134     = build_function_type_list (integer_type_node,
8135                                 psi_type_node, integer_type_node, NULL_TREE);
8136
8137   /* __sync_lock_test_and_set_di */
8138   tree di_ftype_pdi_di
8139     = build_function_type_list (long_integer_type_node,
8140                                 pdi_type_node, long_integer_type_node,
8141                                 NULL_TREE);
8142
8143   /* __sync_lock_release_si */
8144   tree void_ftype_psi
8145     = build_function_type_list (void_type_node, psi_type_node, NULL_TREE);
8146
8147   /* __sync_lock_release_di */
8148   tree void_ftype_pdi
8149     = build_function_type_list (void_type_node, pdi_type_node, NULL_TREE);
8150
8151   tree fpreg_type;
8152   tree float80_type;
8153
8154   /* The __fpreg type.  */
8155   fpreg_type = make_node (REAL_TYPE);
8156   /* ??? The back end should know to load/save __fpreg variables using
8157      the ldf.fill and stf.spill instructions.  */
8158   TYPE_PRECISION (fpreg_type) = 96;
8159   layout_type (fpreg_type);
8160   (*lang_hooks.types.register_builtin_type) (fpreg_type, "__fpreg");
8161
8162   /* The __float80 type.  */
8163   float80_type = make_node (REAL_TYPE);
8164   TYPE_PRECISION (float80_type) = 96;
8165   layout_type (float80_type);
8166   (*lang_hooks.types.register_builtin_type) (float80_type, "__float80");
8167
8168   /* The __float128 type.  */
8169   if (!TARGET_HPUX)
8170     {
8171       tree float128_type = make_node (REAL_TYPE);
8172       TYPE_PRECISION (float128_type) = 128;
8173       layout_type (float128_type);
8174       (*lang_hooks.types.register_builtin_type) (float128_type, "__float128");
8175     }
8176   else
8177     /* Under HPUX, this is a synonym for "long double".  */
8178     (*lang_hooks.types.register_builtin_type) (long_double_type_node,
8179                                                "__float128");
8180
8181 #define def_builtin(name, type, code) \
8182   builtin_function ((name), (type), (code), BUILT_IN_MD, NULL, NULL_TREE)
8183
8184   def_builtin ("__sync_val_compare_and_swap_si", si_ftype_psi_si_si,
8185                IA64_BUILTIN_VAL_COMPARE_AND_SWAP_SI);
8186   def_builtin ("__sync_val_compare_and_swap_di", di_ftype_pdi_di_di,
8187                IA64_BUILTIN_VAL_COMPARE_AND_SWAP_DI);
8188   def_builtin ("__sync_bool_compare_and_swap_si", si_ftype_psi_si_si,
8189                IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_SI);
8190   def_builtin ("__sync_bool_compare_and_swap_di", si_ftype_pdi_di_di,
8191                IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_DI);
8192
8193   def_builtin ("__sync_synchronize", void_ftype_void,
8194                IA64_BUILTIN_SYNCHRONIZE);
8195
8196   def_builtin ("__sync_lock_test_and_set_si", si_ftype_psi_si,
8197                IA64_BUILTIN_LOCK_TEST_AND_SET_SI);
8198   def_builtin ("__sync_lock_test_and_set_di", di_ftype_pdi_di,
8199                IA64_BUILTIN_LOCK_TEST_AND_SET_DI);
8200   def_builtin ("__sync_lock_release_si", void_ftype_psi,
8201                IA64_BUILTIN_LOCK_RELEASE_SI);
8202   def_builtin ("__sync_lock_release_di", void_ftype_pdi,
8203                IA64_BUILTIN_LOCK_RELEASE_DI);
8204
8205   def_builtin ("__builtin_ia64_bsp",
8206                build_function_type (ptr_type_node, void_list_node),
8207                IA64_BUILTIN_BSP);
8208
8209   def_builtin ("__builtin_ia64_flushrs",
8210                build_function_type (void_type_node, void_list_node),
8211                IA64_BUILTIN_FLUSHRS);
8212
8213   def_builtin ("__sync_fetch_and_add_si", si_ftype_psi_si,
8214                IA64_BUILTIN_FETCH_AND_ADD_SI);
8215   def_builtin ("__sync_fetch_and_sub_si", si_ftype_psi_si,
8216                IA64_BUILTIN_FETCH_AND_SUB_SI);
8217   def_builtin ("__sync_fetch_and_or_si", si_ftype_psi_si,
8218                IA64_BUILTIN_FETCH_AND_OR_SI);
8219   def_builtin ("__sync_fetch_and_and_si", si_ftype_psi_si,
8220                IA64_BUILTIN_FETCH_AND_AND_SI);
8221   def_builtin ("__sync_fetch_and_xor_si", si_ftype_psi_si,
8222                IA64_BUILTIN_FETCH_AND_XOR_SI);
8223   def_builtin ("__sync_fetch_and_nand_si", si_ftype_psi_si,
8224                IA64_BUILTIN_FETCH_AND_NAND_SI);
8225
8226   def_builtin ("__sync_add_and_fetch_si", si_ftype_psi_si,
8227                IA64_BUILTIN_ADD_AND_FETCH_SI);
8228   def_builtin ("__sync_sub_and_fetch_si", si_ftype_psi_si,
8229                IA64_BUILTIN_SUB_AND_FETCH_SI);
8230   def_builtin ("__sync_or_and_fetch_si", si_ftype_psi_si,
8231                IA64_BUILTIN_OR_AND_FETCH_SI);
8232   def_builtin ("__sync_and_and_fetch_si", si_ftype_psi_si,
8233                IA64_BUILTIN_AND_AND_FETCH_SI);
8234   def_builtin ("__sync_xor_and_fetch_si", si_ftype_psi_si,
8235                IA64_BUILTIN_XOR_AND_FETCH_SI);
8236   def_builtin ("__sync_nand_and_fetch_si", si_ftype_psi_si,
8237                IA64_BUILTIN_NAND_AND_FETCH_SI);
8238
8239   def_builtin ("__sync_fetch_and_add_di", di_ftype_pdi_di,
8240                IA64_BUILTIN_FETCH_AND_ADD_DI);
8241   def_builtin ("__sync_fetch_and_sub_di", di_ftype_pdi_di,
8242                IA64_BUILTIN_FETCH_AND_SUB_DI);
8243   def_builtin ("__sync_fetch_and_or_di", di_ftype_pdi_di,
8244                IA64_BUILTIN_FETCH_AND_OR_DI);
8245   def_builtin ("__sync_fetch_and_and_di", di_ftype_pdi_di,
8246                IA64_BUILTIN_FETCH_AND_AND_DI);
8247   def_builtin ("__sync_fetch_and_xor_di", di_ftype_pdi_di,
8248                IA64_BUILTIN_FETCH_AND_XOR_DI);
8249   def_builtin ("__sync_fetch_and_nand_di", di_ftype_pdi_di,
8250                IA64_BUILTIN_FETCH_AND_NAND_DI);
8251
8252   def_builtin ("__sync_add_and_fetch_di", di_ftype_pdi_di,
8253                IA64_BUILTIN_ADD_AND_FETCH_DI);
8254   def_builtin ("__sync_sub_and_fetch_di", di_ftype_pdi_di,
8255                IA64_BUILTIN_SUB_AND_FETCH_DI);
8256   def_builtin ("__sync_or_and_fetch_di", di_ftype_pdi_di,
8257                IA64_BUILTIN_OR_AND_FETCH_DI);
8258   def_builtin ("__sync_and_and_fetch_di", di_ftype_pdi_di,
8259                IA64_BUILTIN_AND_AND_FETCH_DI);
8260   def_builtin ("__sync_xor_and_fetch_di", di_ftype_pdi_di,
8261                IA64_BUILTIN_XOR_AND_FETCH_DI);
8262   def_builtin ("__sync_nand_and_fetch_di", di_ftype_pdi_di,
8263                IA64_BUILTIN_NAND_AND_FETCH_DI);
8264
8265 #undef def_builtin
8266 }
8267
8268 /* Expand fetch_and_op intrinsics.  The basic code sequence is:
8269
8270      mf
8271      tmp = [ptr];
8272      do {
8273        ret = tmp;
8274        ar.ccv = tmp;
8275        tmp <op>= value;
8276        cmpxchgsz.acq tmp = [ptr], tmp
8277      } while (tmp != ret)
8278 */
8279
8280 static rtx
8281 ia64_expand_fetch_and_op (optab binoptab, enum machine_mode mode,
8282                           tree arglist, rtx target)
8283 {
8284   rtx ret, label, tmp, ccv, insn, mem, value;
8285   tree arg0, arg1;
8286
8287   arg0 = TREE_VALUE (arglist);
8288   arg1 = TREE_VALUE (TREE_CHAIN (arglist));
8289   mem = expand_expr (arg0, NULL_RTX, Pmode, 0);
8290 #ifdef POINTERS_EXTEND_UNSIGNED
8291   if (GET_MODE(mem) != Pmode)
8292     mem = convert_memory_address (Pmode, mem);
8293 #endif
8294   value = expand_expr (arg1, NULL_RTX, mode, 0);
8295
8296   mem = gen_rtx_MEM (mode, force_reg (Pmode, mem));
8297   MEM_VOLATILE_P (mem) = 1;
8298
8299   if (target && register_operand (target, mode))
8300     ret = target;
8301   else
8302     ret = gen_reg_rtx (mode);
8303
8304   emit_insn (gen_mf ());
8305
8306   /* Special case for fetchadd instructions.  */
8307   if (binoptab == add_optab && fetchadd_operand (value, VOIDmode))
8308     {
8309       if (mode == SImode)
8310         insn = gen_fetchadd_acq_si (ret, mem, value);
8311       else
8312         insn = gen_fetchadd_acq_di (ret, mem, value);
8313       emit_insn (insn);
8314       return ret;
8315     }
8316
8317   tmp = gen_reg_rtx (mode);
8318   /* ar.ccv must always be loaded with a zero-extended DImode value.  */
8319   ccv = gen_rtx_REG (DImode, AR_CCV_REGNUM);
8320   emit_move_insn (tmp, mem);
8321
8322   label = gen_label_rtx ();
8323   emit_label (label);
8324   emit_move_insn (ret, tmp);
8325   convert_move (ccv, tmp, /*unsignedp=*/1);
8326
8327   /* Perform the specific operation.  Special case NAND by noticing
8328      one_cmpl_optab instead.  */
8329   if (binoptab == one_cmpl_optab)
8330     {
8331       tmp = expand_unop (mode, binoptab, tmp, NULL, OPTAB_WIDEN);
8332       binoptab = and_optab;
8333     }
8334   tmp = expand_binop (mode, binoptab, tmp, value, tmp, 1, OPTAB_WIDEN);
8335
8336   if (mode == SImode)
8337     insn = gen_cmpxchg_acq_si (tmp, mem, tmp, ccv);
8338   else
8339     insn = gen_cmpxchg_acq_di (tmp, mem, tmp, ccv);
8340   emit_insn (insn);
8341
8342   emit_cmp_and_jump_insns (tmp, ret, NE, 0, mode, 1, label);
8343
8344   return ret;
8345 }
8346
8347 /* Expand op_and_fetch intrinsics.  The basic code sequence is:
8348
8349      mf
8350      tmp = [ptr];
8351      do {
8352        old = tmp;
8353        ar.ccv = tmp;
8354        ret = tmp <op> value;
8355        cmpxchgsz.acq tmp = [ptr], ret
8356      } while (tmp != old)
8357 */
8358
8359 static rtx
8360 ia64_expand_op_and_fetch (optab binoptab, enum machine_mode mode,
8361                           tree arglist, rtx target)
8362 {
8363   rtx old, label, tmp, ret, ccv, insn, mem, value;
8364   tree arg0, arg1;
8365
8366   arg0 = TREE_VALUE (arglist);
8367   arg1 = TREE_VALUE (TREE_CHAIN (arglist));
8368   mem = expand_expr (arg0, NULL_RTX, Pmode, 0);
8369 #ifdef POINTERS_EXTEND_UNSIGNED
8370   if (GET_MODE(mem) != Pmode)
8371     mem = convert_memory_address (Pmode, mem);
8372 #endif
8373
8374   value = expand_expr (arg1, NULL_RTX, mode, 0);
8375
8376   mem = gen_rtx_MEM (mode, force_reg (Pmode, mem));
8377   MEM_VOLATILE_P (mem) = 1;
8378
8379   if (target && ! register_operand (target, mode))
8380     target = NULL_RTX;
8381
8382   emit_insn (gen_mf ());
8383   tmp = gen_reg_rtx (mode);
8384   old = gen_reg_rtx (mode);
8385   /* ar.ccv must always be loaded with a zero-extended DImode value.  */
8386   ccv = gen_rtx_REG (DImode, AR_CCV_REGNUM);
8387
8388   emit_move_insn (tmp, mem);
8389
8390   label = gen_label_rtx ();
8391   emit_label (label);
8392   emit_move_insn (old, tmp);
8393   convert_move (ccv, tmp, /*unsignedp=*/1);
8394
8395   /* Perform the specific operation.  Special case NAND by noticing
8396      one_cmpl_optab instead.  */
8397   if (binoptab == one_cmpl_optab)
8398     {
8399       tmp = expand_unop (mode, binoptab, tmp, NULL, OPTAB_WIDEN);
8400       binoptab = and_optab;
8401     }
8402   ret = expand_binop (mode, binoptab, tmp, value, target, 1, OPTAB_WIDEN);
8403
8404   if (mode == SImode)
8405     insn = gen_cmpxchg_acq_si (tmp, mem, ret, ccv);
8406   else
8407     insn = gen_cmpxchg_acq_di (tmp, mem, ret, ccv);
8408   emit_insn (insn);
8409
8410   emit_cmp_and_jump_insns (tmp, old, NE, 0, mode, 1, label);
8411
8412   return ret;
8413 }
8414
8415 /* Expand val_ and bool_compare_and_swap.  For val_ we want:
8416
8417      ar.ccv = oldval
8418      mf
8419      cmpxchgsz.acq ret = [ptr], newval, ar.ccv
8420      return ret
8421
8422    For bool_ it's the same except return ret == oldval.
8423 */
8424
8425 static rtx
8426 ia64_expand_compare_and_swap (enum machine_mode rmode, enum machine_mode mode,
8427                               int boolp, tree arglist, rtx target)
8428 {
8429   tree arg0, arg1, arg2;
8430   rtx mem, old, new, ccv, tmp, insn;
8431
8432   arg0 = TREE_VALUE (arglist);
8433   arg1 = TREE_VALUE (TREE_CHAIN (arglist));
8434   arg2 = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (arglist)));
8435   mem = expand_expr (arg0, NULL_RTX, ptr_mode, 0);
8436   old = expand_expr (arg1, NULL_RTX, mode, 0);
8437   new = expand_expr (arg2, NULL_RTX, mode, 0);
8438
8439   mem = gen_rtx_MEM (mode, force_reg (ptr_mode, mem));
8440   MEM_VOLATILE_P (mem) = 1;
8441
8442   if (GET_MODE (old) != mode)
8443     old = convert_to_mode (mode, old, /*unsignedp=*/1);
8444   if (GET_MODE (new) != mode)
8445     new = convert_to_mode (mode, new, /*unsignedp=*/1);
8446
8447   if (! register_operand (old, mode))
8448     old = copy_to_mode_reg (mode, old);
8449   if (! register_operand (new, mode))
8450     new = copy_to_mode_reg (mode, new);
8451
8452   if (! boolp && target && register_operand (target, mode))
8453     tmp = target;
8454   else
8455     tmp = gen_reg_rtx (mode);
8456
8457   ccv = gen_rtx_REG (DImode, AR_CCV_REGNUM);
8458   convert_move (ccv, old, /*unsignedp=*/1);
8459   emit_insn (gen_mf ());
8460   if (mode == SImode)
8461     insn = gen_cmpxchg_acq_si (tmp, mem, new, ccv);
8462   else
8463     insn = gen_cmpxchg_acq_di (tmp, mem, new, ccv);
8464   emit_insn (insn);
8465
8466   if (boolp)
8467     {
8468       if (! target)
8469         target = gen_reg_rtx (rmode);
8470       return emit_store_flag_force (target, EQ, tmp, old, mode, 1, 1);
8471     }
8472   else
8473     return tmp;
8474 }
8475
8476 /* Expand lock_test_and_set.  I.e. `xchgsz ret = [ptr], new'.  */
8477
8478 static rtx
8479 ia64_expand_lock_test_and_set (enum machine_mode mode, tree arglist,
8480                                rtx target)
8481 {
8482   tree arg0, arg1;
8483   rtx mem, new, ret, insn;
8484
8485   arg0 = TREE_VALUE (arglist);
8486   arg1 = TREE_VALUE (TREE_CHAIN (arglist));
8487   mem = expand_expr (arg0, NULL_RTX, ptr_mode, 0);
8488   new = expand_expr (arg1, NULL_RTX, mode, 0);
8489
8490   mem = gen_rtx_MEM (mode, force_reg (ptr_mode, mem));
8491   MEM_VOLATILE_P (mem) = 1;
8492   if (! register_operand (new, mode))
8493     new = copy_to_mode_reg (mode, new);
8494
8495   if (target && register_operand (target, mode))
8496     ret = target;
8497   else
8498     ret = gen_reg_rtx (mode);
8499
8500   if (mode == SImode)
8501     insn = gen_xchgsi (ret, mem, new);
8502   else
8503     insn = gen_xchgdi (ret, mem, new);
8504   emit_insn (insn);
8505
8506   return ret;
8507 }
8508
8509 /* Expand lock_release.  I.e. `stsz.rel [ptr] = r0'.  */
8510
8511 static rtx
8512 ia64_expand_lock_release (enum machine_mode mode, tree arglist,
8513                           rtx target ATTRIBUTE_UNUSED)
8514 {
8515   tree arg0;
8516   rtx mem;
8517
8518   arg0 = TREE_VALUE (arglist);
8519   mem = expand_expr (arg0, NULL_RTX, ptr_mode, 0);
8520
8521   mem = gen_rtx_MEM (mode, force_reg (ptr_mode, mem));
8522   MEM_VOLATILE_P (mem) = 1;
8523
8524   emit_move_insn (mem, const0_rtx);
8525
8526   return const0_rtx;
8527 }
8528
8529 rtx
8530 ia64_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
8531                      enum machine_mode mode ATTRIBUTE_UNUSED,
8532                      int ignore ATTRIBUTE_UNUSED)
8533 {
8534   tree fndecl = TREE_OPERAND (TREE_OPERAND (exp, 0), 0);
8535   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
8536   tree arglist = TREE_OPERAND (exp, 1);
8537   enum machine_mode rmode = VOIDmode;
8538
8539   switch (fcode)
8540     {
8541     case IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_SI:
8542     case IA64_BUILTIN_VAL_COMPARE_AND_SWAP_SI:
8543       mode = SImode;
8544       rmode = SImode;
8545       break;
8546
8547     case IA64_BUILTIN_LOCK_TEST_AND_SET_SI:
8548     case IA64_BUILTIN_LOCK_RELEASE_SI:
8549     case IA64_BUILTIN_FETCH_AND_ADD_SI:
8550     case IA64_BUILTIN_FETCH_AND_SUB_SI:
8551     case IA64_BUILTIN_FETCH_AND_OR_SI:
8552     case IA64_BUILTIN_FETCH_AND_AND_SI:
8553     case IA64_BUILTIN_FETCH_AND_XOR_SI:
8554     case IA64_BUILTIN_FETCH_AND_NAND_SI:
8555     case IA64_BUILTIN_ADD_AND_FETCH_SI:
8556     case IA64_BUILTIN_SUB_AND_FETCH_SI:
8557     case IA64_BUILTIN_OR_AND_FETCH_SI:
8558     case IA64_BUILTIN_AND_AND_FETCH_SI:
8559     case IA64_BUILTIN_XOR_AND_FETCH_SI:
8560     case IA64_BUILTIN_NAND_AND_FETCH_SI:
8561       mode = SImode;
8562       break;
8563
8564     case IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_DI:
8565       mode = DImode;
8566       rmode = SImode;
8567       break;
8568
8569     case IA64_BUILTIN_VAL_COMPARE_AND_SWAP_DI:
8570       mode = DImode;
8571       rmode = DImode;
8572       break;
8573
8574     case IA64_BUILTIN_LOCK_TEST_AND_SET_DI:
8575     case IA64_BUILTIN_LOCK_RELEASE_DI:
8576     case IA64_BUILTIN_FETCH_AND_ADD_DI:
8577     case IA64_BUILTIN_FETCH_AND_SUB_DI:
8578     case IA64_BUILTIN_FETCH_AND_OR_DI:
8579     case IA64_BUILTIN_FETCH_AND_AND_DI:
8580     case IA64_BUILTIN_FETCH_AND_XOR_DI:
8581     case IA64_BUILTIN_FETCH_AND_NAND_DI:
8582     case IA64_BUILTIN_ADD_AND_FETCH_DI:
8583     case IA64_BUILTIN_SUB_AND_FETCH_DI:
8584     case IA64_BUILTIN_OR_AND_FETCH_DI:
8585     case IA64_BUILTIN_AND_AND_FETCH_DI:
8586     case IA64_BUILTIN_XOR_AND_FETCH_DI:
8587     case IA64_BUILTIN_NAND_AND_FETCH_DI:
8588       mode = DImode;
8589       break;
8590
8591     default:
8592       break;
8593     }
8594
8595   switch (fcode)
8596     {
8597     case IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_SI:
8598     case IA64_BUILTIN_BOOL_COMPARE_AND_SWAP_DI:
8599       return ia64_expand_compare_and_swap (rmode, mode, 1, arglist,
8600                                            target);
8601
8602     case IA64_BUILTIN_VAL_COMPARE_AND_SWAP_SI:
8603     case IA64_BUILTIN_VAL_COMPARE_AND_SWAP_DI:
8604       return ia64_expand_compare_and_swap (rmode, mode, 0, arglist,
8605                                            target);
8606
8607     case IA64_BUILTIN_SYNCHRONIZE:
8608       emit_insn (gen_mf ());
8609       return const0_rtx;
8610
8611     case IA64_BUILTIN_LOCK_TEST_AND_SET_SI:
8612     case IA64_BUILTIN_LOCK_TEST_AND_SET_DI:
8613       return ia64_expand_lock_test_and_set (mode, arglist, target);
8614
8615     case IA64_BUILTIN_LOCK_RELEASE_SI:
8616     case IA64_BUILTIN_LOCK_RELEASE_DI:
8617       return ia64_expand_lock_release (mode, arglist, target);
8618
8619     case IA64_BUILTIN_BSP:
8620       if (! target || ! register_operand (target, DImode))
8621         target = gen_reg_rtx (DImode);
8622       emit_insn (gen_bsp_value (target));
8623 #ifdef POINTERS_EXTEND_UNSIGNED
8624       target = convert_memory_address (ptr_mode, target);
8625 #endif
8626       return target;
8627
8628     case IA64_BUILTIN_FLUSHRS:
8629       emit_insn (gen_flushrs ());
8630       return const0_rtx;
8631
8632     case IA64_BUILTIN_FETCH_AND_ADD_SI:
8633     case IA64_BUILTIN_FETCH_AND_ADD_DI:
8634       return ia64_expand_fetch_and_op (add_optab, mode, arglist, target);
8635
8636     case IA64_BUILTIN_FETCH_AND_SUB_SI:
8637     case IA64_BUILTIN_FETCH_AND_SUB_DI:
8638       return ia64_expand_fetch_and_op (sub_optab, mode, arglist, target);
8639
8640     case IA64_BUILTIN_FETCH_AND_OR_SI:
8641     case IA64_BUILTIN_FETCH_AND_OR_DI:
8642       return ia64_expand_fetch_and_op (ior_optab, mode, arglist, target);
8643
8644     case IA64_BUILTIN_FETCH_AND_AND_SI:
8645     case IA64_BUILTIN_FETCH_AND_AND_DI:
8646       return ia64_expand_fetch_and_op (and_optab, mode, arglist, target);
8647
8648     case IA64_BUILTIN_FETCH_AND_XOR_SI:
8649     case IA64_BUILTIN_FETCH_AND_XOR_DI:
8650       return ia64_expand_fetch_and_op (xor_optab, mode, arglist, target);
8651
8652     case IA64_BUILTIN_FETCH_AND_NAND_SI:
8653     case IA64_BUILTIN_FETCH_AND_NAND_DI:
8654       return ia64_expand_fetch_and_op (one_cmpl_optab, mode, arglist, target);
8655
8656     case IA64_BUILTIN_ADD_AND_FETCH_SI:
8657     case IA64_BUILTIN_ADD_AND_FETCH_DI:
8658       return ia64_expand_op_and_fetch (add_optab, mode, arglist, target);
8659
8660     case IA64_BUILTIN_SUB_AND_FETCH_SI:
8661     case IA64_BUILTIN_SUB_AND_FETCH_DI:
8662       return ia64_expand_op_and_fetch (sub_optab, mode, arglist, target);
8663
8664     case IA64_BUILTIN_OR_AND_FETCH_SI:
8665     case IA64_BUILTIN_OR_AND_FETCH_DI:
8666       return ia64_expand_op_and_fetch (ior_optab, mode, arglist, target);
8667
8668     case IA64_BUILTIN_AND_AND_FETCH_SI:
8669     case IA64_BUILTIN_AND_AND_FETCH_DI:
8670       return ia64_expand_op_and_fetch (and_optab, mode, arglist, target);
8671
8672     case IA64_BUILTIN_XOR_AND_FETCH_SI:
8673     case IA64_BUILTIN_XOR_AND_FETCH_DI:
8674       return ia64_expand_op_and_fetch (xor_optab, mode, arglist, target);
8675
8676     case IA64_BUILTIN_NAND_AND_FETCH_SI:
8677     case IA64_BUILTIN_NAND_AND_FETCH_DI:
8678       return ia64_expand_op_and_fetch (one_cmpl_optab, mode, arglist, target);
8679
8680     default:
8681       break;
8682     }
8683
8684   return NULL_RTX;
8685 }
8686
8687 /* For the HP-UX IA64 aggregate parameters are passed stored in the
8688    most significant bits of the stack slot.  */
8689
8690 enum direction
8691 ia64_hpux_function_arg_padding (enum machine_mode mode, tree type)
8692 {
8693    /* Exception to normal case for structures/unions/etc.  */
8694
8695    if (type && AGGREGATE_TYPE_P (type)
8696        && int_size_in_bytes (type) < UNITS_PER_WORD)
8697      return upward;
8698
8699    /* Fall back to the default.  */
8700    return DEFAULT_FUNCTION_ARG_PADDING (mode, type);
8701 }
8702
8703 /* Linked list of all external functions that are to be emitted by GCC.
8704    We output the name if and only if TREE_SYMBOL_REFERENCED is set in
8705    order to avoid putting out names that are never really used.  */
8706
8707 struct extern_func_list GTY(())
8708 {
8709   struct extern_func_list *next;
8710   tree decl;
8711 };
8712
8713 static GTY(()) struct extern_func_list *extern_func_head;
8714
8715 static void
8716 ia64_hpux_add_extern_decl (tree decl)
8717 {
8718   struct extern_func_list *p = ggc_alloc (sizeof (struct extern_func_list));
8719
8720   p->decl = decl;
8721   p->next = extern_func_head;
8722   extern_func_head = p;
8723 }
8724
8725 /* Print out the list of used global functions.  */
8726
8727 static void
8728 ia64_hpux_file_end (void)
8729 {
8730   struct extern_func_list *p;
8731
8732   for (p = extern_func_head; p; p = p->next)
8733     {
8734       tree decl = p->decl;
8735       tree id = DECL_NAME (decl);
8736
8737       if (!id)
8738         abort ();
8739
8740       if (!TREE_ASM_WRITTEN (decl) && TREE_SYMBOL_REFERENCED (id))
8741         {
8742           const char *name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
8743
8744           TREE_ASM_WRITTEN (decl) = 1;
8745           (*targetm.asm_out.globalize_label) (asm_out_file, name);
8746           fputs (TYPE_ASM_OP, asm_out_file);
8747           assemble_name (asm_out_file, name);
8748           fprintf (asm_out_file, "," TYPE_OPERAND_FMT "\n", "function");
8749         }
8750     }
8751
8752   extern_func_head = 0;
8753 }
8754
8755 /* Set SImode div/mod functions, init_integral_libfuncs only initializes
8756    modes of word_mode and larger.  */
8757
8758 static void
8759 ia64_init_libfuncs (void)
8760 {
8761   set_optab_libfunc (sdiv_optab, SImode, "__divsi3");
8762   set_optab_libfunc (udiv_optab, SImode, "__udivsi3");
8763   set_optab_libfunc (smod_optab, SImode, "__modsi3");
8764   set_optab_libfunc (umod_optab, SImode, "__umodsi3");
8765 }
8766
8767 /* Rename all the TFmode libfuncs using the HPUX conventions.  */
8768
8769 static void
8770 ia64_hpux_init_libfuncs (void)
8771 {
8772   ia64_init_libfuncs ();
8773
8774   set_optab_libfunc (add_optab, TFmode, "_U_Qfadd");
8775   set_optab_libfunc (sub_optab, TFmode, "_U_Qfsub");
8776   set_optab_libfunc (smul_optab, TFmode, "_U_Qfmpy");
8777   set_optab_libfunc (sdiv_optab, TFmode, "_U_Qfdiv");
8778   set_optab_libfunc (smin_optab, TFmode, "_U_Qfmin");
8779   set_optab_libfunc (smax_optab, TFmode, "_U_Qfmax");
8780   set_optab_libfunc (abs_optab, TFmode, "_U_Qfabs");
8781   set_optab_libfunc (neg_optab, TFmode, "_U_Qfneg");
8782
8783   /* ia64_expand_compare uses this.  */
8784   cmptf_libfunc = init_one_libfunc ("_U_Qfcmp");
8785
8786   /* These should never be used.  */
8787   set_optab_libfunc (eq_optab, TFmode, 0);
8788   set_optab_libfunc (ne_optab, TFmode, 0);
8789   set_optab_libfunc (gt_optab, TFmode, 0);
8790   set_optab_libfunc (ge_optab, TFmode, 0);
8791   set_optab_libfunc (lt_optab, TFmode, 0);
8792   set_optab_libfunc (le_optab, TFmode, 0);
8793
8794   set_conv_libfunc (sext_optab,   TFmode, SFmode, "_U_Qfcnvff_sgl_to_quad");
8795   set_conv_libfunc (sext_optab,   TFmode, DFmode, "_U_Qfcnvff_dbl_to_quad");
8796   set_conv_libfunc (sext_optab,   TFmode, XFmode, "_U_Qfcnvff_f80_to_quad");
8797   set_conv_libfunc (trunc_optab,  SFmode, TFmode, "_U_Qfcnvff_quad_to_sgl");
8798   set_conv_libfunc (trunc_optab,  DFmode, TFmode, "_U_Qfcnvff_quad_to_dbl");
8799   set_conv_libfunc (trunc_optab,  XFmode, TFmode, "_U_Qfcnvff_quad_to_f80");
8800
8801   set_conv_libfunc (sfix_optab,   SImode, TFmode, "_U_Qfcnvfxt_quad_to_sgl");
8802   set_conv_libfunc (sfix_optab,   DImode, TFmode, "_U_Qfcnvfxt_quad_to_dbl");
8803   set_conv_libfunc (ufix_optab,   SImode, TFmode, "_U_Qfcnvfxut_quad_to_sgl");
8804   set_conv_libfunc (ufix_optab,   DImode, TFmode, "_U_Qfcnvfxut_quad_to_dbl");
8805
8806   set_conv_libfunc (sfloat_optab, TFmode, SImode, "_U_Qfcnvxf_sgl_to_quad");
8807   set_conv_libfunc (sfloat_optab, TFmode, DImode, "_U_Qfcnvxf_dbl_to_quad");
8808 }
8809
8810 /* Rename the division and modulus functions in VMS.  */
8811
8812 static void
8813 ia64_vms_init_libfuncs (void)
8814 {
8815   set_optab_libfunc (sdiv_optab, SImode, "OTS$DIV_I");
8816   set_optab_libfunc (sdiv_optab, DImode, "OTS$DIV_L");
8817   set_optab_libfunc (udiv_optab, SImode, "OTS$DIV_UI");
8818   set_optab_libfunc (udiv_optab, DImode, "OTS$DIV_UL");
8819   set_optab_libfunc (smod_optab, SImode, "OTS$REM_I");
8820   set_optab_libfunc (smod_optab, DImode, "OTS$REM_L");
8821   set_optab_libfunc (umod_optab, SImode, "OTS$REM_UI");
8822   set_optab_libfunc (umod_optab, DImode, "OTS$REM_UL");
8823 }
8824 \f
8825 /* Switch to the section to which we should output X.  The only thing
8826    special we do here is to honor small data.  */
8827
8828 static void
8829 ia64_select_rtx_section (enum machine_mode mode, rtx x,
8830                          unsigned HOST_WIDE_INT align)
8831 {
8832   if (GET_MODE_SIZE (mode) > 0
8833       && GET_MODE_SIZE (mode) <= ia64_section_threshold)
8834     sdata_section ();
8835   else
8836     default_elf_select_rtx_section (mode, x, align);
8837 }
8838
8839 /* It is illegal to have relocations in shared segments on AIX and HPUX.
8840    Pretend flag_pic is always set.  */
8841
8842 static void
8843 ia64_rwreloc_select_section (tree exp, int reloc, unsigned HOST_WIDE_INT align)
8844 {
8845   default_elf_select_section_1 (exp, reloc, align, true);
8846 }
8847
8848 static void
8849 ia64_rwreloc_unique_section (tree decl, int reloc)
8850 {
8851   default_unique_section_1 (decl, reloc, true);
8852 }
8853
8854 static void
8855 ia64_rwreloc_select_rtx_section (enum machine_mode mode, rtx x,
8856                                  unsigned HOST_WIDE_INT align)
8857 {
8858   int save_pic = flag_pic;
8859   flag_pic = 1;
8860   ia64_select_rtx_section (mode, x, align);
8861   flag_pic = save_pic;
8862 }
8863
8864 static unsigned int
8865 ia64_rwreloc_section_type_flags (tree decl, const char *name, int reloc)
8866 {
8867   return default_section_type_flags_1 (decl, name, reloc, true);
8868 }
8869
8870 /* Returns true if FNTYPE (a FUNCTION_TYPE or a METHOD_TYPE) returns a
8871    structure type and that the address of that type should be passed
8872    in out0, rather than in r8.  */
8873
8874 static bool
8875 ia64_struct_retval_addr_is_first_parm_p (tree fntype)
8876 {
8877   tree ret_type = TREE_TYPE (fntype);
8878
8879   /* The Itanium C++ ABI requires that out0, rather than r8, be used
8880      as the structure return address parameter, if the return value
8881      type has a non-trivial copy constructor or destructor.  It is not
8882      clear if this same convention should be used for other
8883      programming languages.  Until G++ 3.4, we incorrectly used r8 for
8884      these return values.  */
8885   return (abi_version_at_least (2)
8886           && ret_type
8887           && TYPE_MODE (ret_type) == BLKmode 
8888           && TREE_ADDRESSABLE (ret_type)
8889           && strcmp (lang_hooks.name, "GNU C++") == 0);
8890 }
8891
8892 /* Output the assembler code for a thunk function.  THUNK_DECL is the
8893    declaration for the thunk function itself, FUNCTION is the decl for
8894    the target function.  DELTA is an immediate constant offset to be
8895    added to THIS.  If VCALL_OFFSET is nonzero, the word at
8896    *(*this + vcall_offset) should be added to THIS.  */
8897
8898 static void
8899 ia64_output_mi_thunk (FILE *file, tree thunk ATTRIBUTE_UNUSED,
8900                       HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
8901                       tree function)
8902 {
8903   rtx this, insn, funexp;
8904   unsigned int this_parmno;
8905   unsigned int this_regno;
8906
8907   reload_completed = 1;
8908   epilogue_completed = 1;
8909   no_new_pseudos = 1;
8910
8911   /* Set things up as ia64_expand_prologue might.  */
8912   last_scratch_gr_reg = 15;
8913
8914   memset (&current_frame_info, 0, sizeof (current_frame_info));
8915   current_frame_info.spill_cfa_off = -16;
8916   current_frame_info.n_input_regs = 1;
8917   current_frame_info.need_regstk = (TARGET_REG_NAMES != 0);
8918
8919   /* Mark the end of the (empty) prologue.  */
8920   emit_note (NOTE_INSN_PROLOGUE_END);
8921
8922   /* Figure out whether "this" will be the first parameter (the
8923      typical case) or the second parameter (as happens when the
8924      virtual function returns certain class objects).  */
8925   this_parmno
8926     = (ia64_struct_retval_addr_is_first_parm_p (TREE_TYPE (thunk))
8927        ? 1 : 0);
8928   this_regno = IN_REG (this_parmno);
8929   if (!TARGET_REG_NAMES)
8930     reg_names[this_regno] = ia64_reg_numbers[this_parmno];
8931
8932   this = gen_rtx_REG (Pmode, this_regno);
8933   if (TARGET_ILP32)
8934     {
8935       rtx tmp = gen_rtx_REG (ptr_mode, this_regno);
8936       REG_POINTER (tmp) = 1;
8937       if (delta && CONST_OK_FOR_I (delta))
8938         {
8939           emit_insn (gen_ptr_extend_plus_imm (this, tmp, GEN_INT (delta)));
8940           delta = 0;
8941         }
8942       else
8943         emit_insn (gen_ptr_extend (this, tmp));
8944     }
8945
8946   /* Apply the constant offset, if required.  */
8947   if (delta)
8948     {
8949       rtx delta_rtx = GEN_INT (delta);
8950
8951       if (!CONST_OK_FOR_I (delta))
8952         {
8953           rtx tmp = gen_rtx_REG (Pmode, 2);
8954           emit_move_insn (tmp, delta_rtx);
8955           delta_rtx = tmp;
8956         }
8957       emit_insn (gen_adddi3 (this, this, delta_rtx));
8958     }
8959
8960   /* Apply the offset from the vtable, if required.  */
8961   if (vcall_offset)
8962     {
8963       rtx vcall_offset_rtx = GEN_INT (vcall_offset);
8964       rtx tmp = gen_rtx_REG (Pmode, 2);
8965
8966       if (TARGET_ILP32)
8967         {
8968           rtx t = gen_rtx_REG (ptr_mode, 2);
8969           REG_POINTER (t) = 1;
8970           emit_move_insn (t, gen_rtx_MEM (ptr_mode, this));
8971           if (CONST_OK_FOR_I (vcall_offset))
8972             {
8973               emit_insn (gen_ptr_extend_plus_imm (tmp, t, 
8974                                                   vcall_offset_rtx));
8975               vcall_offset = 0;
8976             }
8977           else
8978             emit_insn (gen_ptr_extend (tmp, t));
8979         }
8980       else
8981         emit_move_insn (tmp, gen_rtx_MEM (Pmode, this));
8982
8983       if (vcall_offset)
8984         {
8985           if (!CONST_OK_FOR_J (vcall_offset))
8986             {
8987               rtx tmp2 = gen_rtx_REG (Pmode, next_scratch_gr_reg ());
8988               emit_move_insn (tmp2, vcall_offset_rtx);
8989               vcall_offset_rtx = tmp2;
8990             }
8991           emit_insn (gen_adddi3 (tmp, tmp, vcall_offset_rtx));
8992         }
8993
8994       if (TARGET_ILP32)
8995         emit_move_insn (gen_rtx_REG (ptr_mode, 2), 
8996                         gen_rtx_MEM (ptr_mode, tmp));
8997       else
8998         emit_move_insn (tmp, gen_rtx_MEM (Pmode, tmp));
8999
9000       emit_insn (gen_adddi3 (this, this, tmp));
9001     }
9002
9003   /* Generate a tail call to the target function.  */
9004   if (! TREE_USED (function))
9005     {
9006       assemble_external (function);
9007       TREE_USED (function) = 1;
9008     }
9009   funexp = XEXP (DECL_RTL (function), 0);
9010   funexp = gen_rtx_MEM (FUNCTION_MODE, funexp);
9011   ia64_expand_call (NULL_RTX, funexp, NULL_RTX, 1);
9012   insn = get_last_insn ();
9013   SIBLING_CALL_P (insn) = 1;
9014
9015   /* Code generation for calls relies on splitting.  */
9016   reload_completed = 1;
9017   epilogue_completed = 1;
9018   try_split (PATTERN (insn), insn, 0);
9019
9020   emit_barrier ();
9021
9022   /* Run just enough of rest_of_compilation to get the insns emitted.
9023      There's not really enough bulk here to make other passes such as
9024      instruction scheduling worth while.  Note that use_thunk calls
9025      assemble_start_function and assemble_end_function.  */
9026
9027   insn_locators_initialize ();
9028   emit_all_insn_group_barriers (NULL);
9029   insn = get_insns ();
9030   shorten_branches (insn);
9031   final_start_function (insn, file, 1);
9032   final (insn, file, 1, 0);
9033   final_end_function ();
9034
9035   reload_completed = 0;
9036   epilogue_completed = 0;
9037   no_new_pseudos = 0;
9038 }
9039
9040 /* Worker function for TARGET_STRUCT_VALUE_RTX.  */
9041
9042 static rtx
9043 ia64_struct_value_rtx (tree fntype,
9044                        int incoming ATTRIBUTE_UNUSED)
9045 {
9046   if (fntype && ia64_struct_retval_addr_is_first_parm_p (fntype))
9047     return NULL_RTX;
9048   return gen_rtx_REG (Pmode, GR_REG (8));
9049 }
9050
9051 #include "gt-ia64.h"