OSDN Git Service

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