OSDN Git Service

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