OSDN Git Service

* config/ia64/ia64.c (ia64_expand_builtin): Use the correct mode
[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, 2005, 2006, 2007, 2008,
3    2009, 2010
4    Free Software Foundation, Inc.
5    Contributed by James E. Wilson <wilson@cygnus.com> and
6                   David Mosberger <davidm@hpl.hp.com>.
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
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 "insn-config.h"
33 #include "conditions.h"
34 #include "output.h"
35 #include "insn-attr.h"
36 #include "flags.h"
37 #include "recog.h"
38 #include "expr.h"
39 #include "optabs.h"
40 #include "except.h"
41 #include "function.h"
42 #include "ggc.h"
43 #include "basic-block.h"
44 #include "libfuncs.h"
45 #include "diagnostic-core.h"
46 #include "toplev.h"
47 #include "sched-int.h"
48 #include "timevar.h"
49 #include "target.h"
50 #include "target-def.h"
51 #include "tm_p.h"
52 #include "hashtab.h"
53 #include "langhooks.h"
54 #include "cfglayout.h"
55 #include "gimple.h"
56 #include "intl.h"
57 #include "df.h"
58 #include "debug.h"
59 #include "params.h"
60 #include "dbgcnt.h"
61 #include "tm-constrs.h"
62 #include "sel-sched.h"
63 #include "reload.h"
64
65 /* This is used for communication between ASM_OUTPUT_LABEL and
66    ASM_OUTPUT_LABELREF.  */
67 int ia64_asm_output_label = 0;
68
69 /* Register names for ia64_expand_prologue.  */
70 static const char * const ia64_reg_numbers[96] =
71 { "r32", "r33", "r34", "r35", "r36", "r37", "r38", "r39",
72   "r40", "r41", "r42", "r43", "r44", "r45", "r46", "r47",
73   "r48", "r49", "r50", "r51", "r52", "r53", "r54", "r55",
74   "r56", "r57", "r58", "r59", "r60", "r61", "r62", "r63",
75   "r64", "r65", "r66", "r67", "r68", "r69", "r70", "r71",
76   "r72", "r73", "r74", "r75", "r76", "r77", "r78", "r79",
77   "r80", "r81", "r82", "r83", "r84", "r85", "r86", "r87",
78   "r88", "r89", "r90", "r91", "r92", "r93", "r94", "r95",
79   "r96", "r97", "r98", "r99", "r100","r101","r102","r103",
80   "r104","r105","r106","r107","r108","r109","r110","r111",
81   "r112","r113","r114","r115","r116","r117","r118","r119",
82   "r120","r121","r122","r123","r124","r125","r126","r127"};
83
84 /* ??? These strings could be shared with REGISTER_NAMES.  */
85 static const char * const ia64_input_reg_names[8] =
86 { "in0",  "in1",  "in2",  "in3",  "in4",  "in5",  "in6",  "in7" };
87
88 /* ??? These strings could be shared with REGISTER_NAMES.  */
89 static const char * const ia64_local_reg_names[80] =
90 { "loc0", "loc1", "loc2", "loc3", "loc4", "loc5", "loc6", "loc7",
91   "loc8", "loc9", "loc10","loc11","loc12","loc13","loc14","loc15",
92   "loc16","loc17","loc18","loc19","loc20","loc21","loc22","loc23",
93   "loc24","loc25","loc26","loc27","loc28","loc29","loc30","loc31",
94   "loc32","loc33","loc34","loc35","loc36","loc37","loc38","loc39",
95   "loc40","loc41","loc42","loc43","loc44","loc45","loc46","loc47",
96   "loc48","loc49","loc50","loc51","loc52","loc53","loc54","loc55",
97   "loc56","loc57","loc58","loc59","loc60","loc61","loc62","loc63",
98   "loc64","loc65","loc66","loc67","loc68","loc69","loc70","loc71",
99   "loc72","loc73","loc74","loc75","loc76","loc77","loc78","loc79" };
100
101 /* ??? These strings could be shared with REGISTER_NAMES.  */
102 static const char * const ia64_output_reg_names[8] =
103 { "out0", "out1", "out2", "out3", "out4", "out5", "out6", "out7" };
104
105 /* Which cpu are we scheduling for.  */
106 enum processor_type ia64_tune = PROCESSOR_ITANIUM2;
107
108 /* Determines whether we run our final scheduling pass or not.  We always
109    avoid the normal second scheduling pass.  */
110 static int ia64_flag_schedule_insns2;
111
112 /* Determines whether we run variable tracking in machine dependent
113    reorganization.  */
114 static int ia64_flag_var_tracking;
115
116 /* Variables which are this size or smaller are put in the sdata/sbss
117    sections.  */
118
119 unsigned int ia64_section_threshold;
120
121 /* The following variable is used by the DFA insn scheduler.  The value is
122    TRUE if we do insn bundling instead of insn scheduling.  */
123 int bundling_p = 0;
124
125 enum ia64_frame_regs
126 {
127    reg_fp,
128    reg_save_b0,
129    reg_save_pr,
130    reg_save_ar_pfs,
131    reg_save_ar_unat,
132    reg_save_ar_lc,
133    reg_save_gp,
134    number_of_ia64_frame_regs
135 };
136
137 /* Structure to be filled in by ia64_compute_frame_size with register
138    save masks and offsets for the current function.  */
139
140 struct ia64_frame_info
141 {
142   HOST_WIDE_INT total_size;     /* size of the stack frame, not including
143                                    the caller's scratch area.  */
144   HOST_WIDE_INT spill_cfa_off;  /* top of the reg spill area from the cfa.  */
145   HOST_WIDE_INT spill_size;     /* size of the gr/br/fr spill area.  */
146   HOST_WIDE_INT extra_spill_size;  /* size of spill area for others.  */
147   HARD_REG_SET mask;            /* mask of saved registers.  */
148   unsigned int gr_used_mask;    /* mask of registers in use as gr spill
149                                    registers or long-term scratches.  */
150   int n_spilled;                /* number of spilled registers.  */
151   int r[number_of_ia64_frame_regs];  /* Frame related registers.  */
152   int n_input_regs;             /* number of input registers used.  */
153   int n_local_regs;             /* number of local registers used.  */
154   int n_output_regs;            /* number of output registers used.  */
155   int n_rotate_regs;            /* number of rotating registers used.  */
156
157   char need_regstk;             /* true if a .regstk directive needed.  */
158   char initialized;             /* true if the data is finalized.  */
159 };
160
161 /* Current frame information calculated by ia64_compute_frame_size.  */
162 static struct ia64_frame_info current_frame_info;
163 /* The actual registers that are emitted.  */
164 static int emitted_frame_related_regs[number_of_ia64_frame_regs];
165 \f
166 static int ia64_first_cycle_multipass_dfa_lookahead (void);
167 static void ia64_dependencies_evaluation_hook (rtx, rtx);
168 static void ia64_init_dfa_pre_cycle_insn (void);
169 static rtx ia64_dfa_pre_cycle_insn (void);
170 static int ia64_first_cycle_multipass_dfa_lookahead_guard (rtx);
171 static bool ia64_first_cycle_multipass_dfa_lookahead_guard_spec (const_rtx);
172 static int ia64_dfa_new_cycle (FILE *, int, rtx, int, int, int *);
173 static void ia64_h_i_d_extended (void);
174 static void * ia64_alloc_sched_context (void);
175 static void ia64_init_sched_context (void *, bool);
176 static void ia64_set_sched_context (void *);
177 static void ia64_clear_sched_context (void *);
178 static void ia64_free_sched_context (void *);
179 static int ia64_mode_to_int (enum machine_mode);
180 static void ia64_set_sched_flags (spec_info_t);
181 static ds_t ia64_get_insn_spec_ds (rtx);
182 static ds_t ia64_get_insn_checked_ds (rtx);
183 static bool ia64_skip_rtx_p (const_rtx);
184 static int ia64_speculate_insn (rtx, ds_t, rtx *);
185 static bool ia64_needs_block_p (int);
186 static rtx ia64_gen_spec_check (rtx, rtx, ds_t);
187 static int ia64_spec_check_p (rtx);
188 static int ia64_spec_check_src_p (rtx);
189 static rtx gen_tls_get_addr (void);
190 static rtx gen_thread_pointer (void);
191 static int find_gr_spill (enum ia64_frame_regs, int);
192 static int next_scratch_gr_reg (void);
193 static void mark_reg_gr_used_mask (rtx, void *);
194 static void ia64_compute_frame_size (HOST_WIDE_INT);
195 static void setup_spill_pointers (int, rtx, HOST_WIDE_INT);
196 static void finish_spill_pointers (void);
197 static rtx spill_restore_mem (rtx, HOST_WIDE_INT);
198 static void do_spill (rtx (*)(rtx, rtx, rtx), rtx, HOST_WIDE_INT, rtx);
199 static void do_restore (rtx (*)(rtx, rtx, rtx), rtx, HOST_WIDE_INT);
200 static rtx gen_movdi_x (rtx, rtx, rtx);
201 static rtx gen_fr_spill_x (rtx, rtx, rtx);
202 static rtx gen_fr_restore_x (rtx, rtx, rtx);
203
204 static void ia64_option_override (void);
205 static void ia64_option_default_params (void);
206 static bool ia64_can_eliminate (const int, const int);
207 static enum machine_mode hfa_element_mode (const_tree, bool);
208 static void ia64_setup_incoming_varargs (CUMULATIVE_ARGS *, enum machine_mode,
209                                          tree, int *, int);
210 static int ia64_arg_partial_bytes (CUMULATIVE_ARGS *, enum machine_mode,
211                                    tree, bool);
212 static rtx ia64_function_arg_1 (const CUMULATIVE_ARGS *, enum machine_mode,
213                                 const_tree, bool, bool);
214 static rtx ia64_function_arg (CUMULATIVE_ARGS *, enum machine_mode,
215                               const_tree, bool);
216 static rtx ia64_function_incoming_arg (CUMULATIVE_ARGS *,
217                                        enum machine_mode, const_tree, bool);
218 static void ia64_function_arg_advance (CUMULATIVE_ARGS *, enum machine_mode,
219                                        const_tree, bool);
220 static unsigned int ia64_function_arg_boundary (enum machine_mode,
221                                                 const_tree);
222 static bool ia64_function_ok_for_sibcall (tree, tree);
223 static bool ia64_return_in_memory (const_tree, const_tree);
224 static rtx ia64_function_value (const_tree, const_tree, bool);
225 static rtx ia64_libcall_value (enum machine_mode, const_rtx);
226 static bool ia64_function_value_regno_p (const unsigned int);
227 static int ia64_register_move_cost (enum machine_mode, reg_class_t,
228                                     reg_class_t);
229 static int ia64_memory_move_cost (enum machine_mode mode, reg_class_t,
230                                   bool);
231 static bool ia64_rtx_costs (rtx, int, int, int *, bool);
232 static int ia64_unspec_may_trap_p (const_rtx, unsigned);
233 static void fix_range (const char *);
234 static bool ia64_handle_option (size_t, const char *, int);
235 static struct machine_function * ia64_init_machine_status (void);
236 static void emit_insn_group_barriers (FILE *);
237 static void emit_all_insn_group_barriers (FILE *);
238 static void final_emit_insn_group_barriers (FILE *);
239 static void emit_predicate_relation_info (void);
240 static void ia64_reorg (void);
241 static bool ia64_in_small_data_p (const_tree);
242 static void process_epilogue (FILE *, rtx, bool, bool);
243
244 static bool ia64_assemble_integer (rtx, unsigned int, int);
245 static void ia64_output_function_prologue (FILE *, HOST_WIDE_INT);
246 static void ia64_output_function_epilogue (FILE *, HOST_WIDE_INT);
247 static void ia64_output_function_end_prologue (FILE *);
248
249 static int ia64_issue_rate (void);
250 static int ia64_adjust_cost_2 (rtx, int, rtx, int, dw_t);
251 static void ia64_sched_init (FILE *, int, int);
252 static void ia64_sched_init_global (FILE *, int, int);
253 static void ia64_sched_finish_global (FILE *, int);
254 static void ia64_sched_finish (FILE *, int);
255 static int ia64_dfa_sched_reorder (FILE *, int, rtx *, int *, int, int);
256 static int ia64_sched_reorder (FILE *, int, rtx *, int *, int);
257 static int ia64_sched_reorder2 (FILE *, int, rtx *, int *, int);
258 static int ia64_variable_issue (FILE *, int, rtx, int);
259
260 static void ia64_asm_unwind_emit (FILE *, rtx);
261 static void ia64_asm_emit_except_personality (rtx);
262 static void ia64_asm_init_sections (void);
263
264 static enum unwind_info_type ia64_debug_unwind_info (void);
265 static enum unwind_info_type ia64_except_unwind_info (void);
266
267 static struct bundle_state *get_free_bundle_state (void);
268 static void free_bundle_state (struct bundle_state *);
269 static void initiate_bundle_states (void);
270 static void finish_bundle_states (void);
271 static unsigned bundle_state_hash (const void *);
272 static int bundle_state_eq_p (const void *, const void *);
273 static int insert_bundle_state (struct bundle_state *);
274 static void initiate_bundle_state_table (void);
275 static void finish_bundle_state_table (void);
276 static int try_issue_nops (struct bundle_state *, int);
277 static int try_issue_insn (struct bundle_state *, rtx);
278 static void issue_nops_and_insn (struct bundle_state *, int, rtx, int, int);
279 static int get_max_pos (state_t);
280 static int get_template (state_t, int);
281
282 static rtx get_next_important_insn (rtx, rtx);
283 static bool important_for_bundling_p (rtx);
284 static void bundling (FILE *, int, rtx, rtx);
285
286 static void ia64_output_mi_thunk (FILE *, tree, HOST_WIDE_INT,
287                                   HOST_WIDE_INT, tree);
288 static void ia64_file_start (void);
289 static void ia64_globalize_decl_name (FILE *, tree);
290
291 static int ia64_hpux_reloc_rw_mask (void) ATTRIBUTE_UNUSED;
292 static int ia64_reloc_rw_mask (void) ATTRIBUTE_UNUSED;
293 static section *ia64_select_rtx_section (enum machine_mode, rtx,
294                                          unsigned HOST_WIDE_INT);
295 static void ia64_output_dwarf_dtprel (FILE *, int, rtx)
296      ATTRIBUTE_UNUSED;
297 static unsigned int ia64_section_type_flags (tree, const char *, int);
298 static void ia64_init_libfuncs (void)
299      ATTRIBUTE_UNUSED;
300 static void ia64_hpux_init_libfuncs (void)
301      ATTRIBUTE_UNUSED;
302 static void ia64_sysv4_init_libfuncs (void)
303      ATTRIBUTE_UNUSED;
304 static void ia64_vms_init_libfuncs (void)
305      ATTRIBUTE_UNUSED;
306 static void ia64_soft_fp_init_libfuncs (void)
307      ATTRIBUTE_UNUSED;
308 static bool ia64_vms_valid_pointer_mode (enum machine_mode mode)
309      ATTRIBUTE_UNUSED;
310 static tree ia64_vms_common_object_attribute (tree *, tree, tree, int, bool *)
311      ATTRIBUTE_UNUSED;
312
313 static tree ia64_handle_model_attribute (tree *, tree, tree, int, bool *);
314 static tree ia64_handle_version_id_attribute (tree *, tree, tree, int, bool *);
315 static void ia64_encode_section_info (tree, rtx, int);
316 static rtx ia64_struct_value_rtx (tree, int);
317 static tree ia64_gimplify_va_arg (tree, tree, gimple_seq *, gimple_seq *);
318 static bool ia64_scalar_mode_supported_p (enum machine_mode mode);
319 static bool ia64_vector_mode_supported_p (enum machine_mode mode);
320 static bool ia64_cannot_force_const_mem (rtx);
321 static const char *ia64_mangle_type (const_tree);
322 static const char *ia64_invalid_conversion (const_tree, const_tree);
323 static const char *ia64_invalid_unary_op (int, const_tree);
324 static const char *ia64_invalid_binary_op (int, const_tree, const_tree);
325 static enum machine_mode ia64_c_mode_for_suffix (char);
326 static enum machine_mode ia64_promote_function_mode (const_tree,
327                                                      enum machine_mode,
328                                                      int *,
329                                                      const_tree,
330                                                      int);
331 static void ia64_trampoline_init (rtx, tree, rtx);
332 static void ia64_override_options_after_change (void);
333
334 static void ia64_dwarf_handle_frame_unspec (const char *, rtx, int);
335 static tree ia64_builtin_decl (unsigned, bool);
336
337 static reg_class_t ia64_preferred_reload_class (rtx, reg_class_t);
338 static enum machine_mode ia64_get_reg_raw_mode (int regno);
339 \f
340 /* Table of valid machine attributes.  */
341 static const struct attribute_spec ia64_attribute_table[] =
342 {
343   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
344   { "syscall_linkage", 0, 0, false, true,  true,  NULL },
345   { "model",           1, 1, true, false, false, ia64_handle_model_attribute },
346 #if TARGET_ABI_OPEN_VMS
347   { "common_object",   1, 1, true, false, false, ia64_vms_common_object_attribute},
348 #endif
349   { "version_id",      1, 1, true, false, false,
350     ia64_handle_version_id_attribute },
351   { NULL,              0, 0, false, false, false, NULL }
352 };
353
354 /* Implement overriding of the optimization options.  */
355 static const struct default_options ia64_option_optimization_table[] =
356   {
357     { OPT_LEVELS_1_PLUS, OPT_fomit_frame_pointer, NULL, 1 },
358 #ifdef SUBTARGET_OPTIMIZATION_OPTIONS
359     SUBTARGET_OPTIMIZATION_OPTIONS,
360 #endif
361     { OPT_LEVELS_NONE, 0, NULL, 0 }
362   };
363
364 /* Initialize the GCC target structure.  */
365 #undef TARGET_ATTRIBUTE_TABLE
366 #define TARGET_ATTRIBUTE_TABLE ia64_attribute_table
367
368 #undef TARGET_INIT_BUILTINS
369 #define TARGET_INIT_BUILTINS ia64_init_builtins
370
371 #undef TARGET_EXPAND_BUILTIN
372 #define TARGET_EXPAND_BUILTIN ia64_expand_builtin
373
374 #undef TARGET_BUILTIN_DECL
375 #define TARGET_BUILTIN_DECL ia64_builtin_decl
376
377 #undef TARGET_ASM_BYTE_OP
378 #define TARGET_ASM_BYTE_OP "\tdata1\t"
379 #undef TARGET_ASM_ALIGNED_HI_OP
380 #define TARGET_ASM_ALIGNED_HI_OP "\tdata2\t"
381 #undef TARGET_ASM_ALIGNED_SI_OP
382 #define TARGET_ASM_ALIGNED_SI_OP "\tdata4\t"
383 #undef TARGET_ASM_ALIGNED_DI_OP
384 #define TARGET_ASM_ALIGNED_DI_OP "\tdata8\t"
385 #undef TARGET_ASM_UNALIGNED_HI_OP
386 #define TARGET_ASM_UNALIGNED_HI_OP "\tdata2.ua\t"
387 #undef TARGET_ASM_UNALIGNED_SI_OP
388 #define TARGET_ASM_UNALIGNED_SI_OP "\tdata4.ua\t"
389 #undef TARGET_ASM_UNALIGNED_DI_OP
390 #define TARGET_ASM_UNALIGNED_DI_OP "\tdata8.ua\t"
391 #undef TARGET_ASM_INTEGER
392 #define TARGET_ASM_INTEGER ia64_assemble_integer
393
394 #undef TARGET_OPTION_OVERRIDE
395 #define TARGET_OPTION_OVERRIDE ia64_option_override
396 #undef TARGET_OPTION_OPTIMIZATION_TABLE
397 #define TARGET_OPTION_OPTIMIZATION_TABLE ia64_option_optimization_table
398 #undef TARGET_OPTION_DEFAULT_PARAMS
399 #define TARGET_OPTION_DEFAULT_PARAMS ia64_option_default_params
400
401 #undef TARGET_ASM_FUNCTION_PROLOGUE
402 #define TARGET_ASM_FUNCTION_PROLOGUE ia64_output_function_prologue
403 #undef TARGET_ASM_FUNCTION_END_PROLOGUE
404 #define TARGET_ASM_FUNCTION_END_PROLOGUE ia64_output_function_end_prologue
405 #undef TARGET_ASM_FUNCTION_EPILOGUE
406 #define TARGET_ASM_FUNCTION_EPILOGUE ia64_output_function_epilogue
407
408 #undef TARGET_IN_SMALL_DATA_P
409 #define TARGET_IN_SMALL_DATA_P  ia64_in_small_data_p
410
411 #undef TARGET_SCHED_ADJUST_COST_2
412 #define TARGET_SCHED_ADJUST_COST_2 ia64_adjust_cost_2
413 #undef TARGET_SCHED_ISSUE_RATE
414 #define TARGET_SCHED_ISSUE_RATE ia64_issue_rate
415 #undef TARGET_SCHED_VARIABLE_ISSUE
416 #define TARGET_SCHED_VARIABLE_ISSUE ia64_variable_issue
417 #undef TARGET_SCHED_INIT
418 #define TARGET_SCHED_INIT ia64_sched_init
419 #undef TARGET_SCHED_FINISH
420 #define TARGET_SCHED_FINISH ia64_sched_finish
421 #undef TARGET_SCHED_INIT_GLOBAL
422 #define TARGET_SCHED_INIT_GLOBAL ia64_sched_init_global
423 #undef TARGET_SCHED_FINISH_GLOBAL
424 #define TARGET_SCHED_FINISH_GLOBAL ia64_sched_finish_global
425 #undef TARGET_SCHED_REORDER
426 #define TARGET_SCHED_REORDER ia64_sched_reorder
427 #undef TARGET_SCHED_REORDER2
428 #define TARGET_SCHED_REORDER2 ia64_sched_reorder2
429
430 #undef TARGET_SCHED_DEPENDENCIES_EVALUATION_HOOK
431 #define TARGET_SCHED_DEPENDENCIES_EVALUATION_HOOK ia64_dependencies_evaluation_hook
432
433 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD
434 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD ia64_first_cycle_multipass_dfa_lookahead
435
436 #undef TARGET_SCHED_INIT_DFA_PRE_CYCLE_INSN
437 #define TARGET_SCHED_INIT_DFA_PRE_CYCLE_INSN ia64_init_dfa_pre_cycle_insn
438 #undef TARGET_SCHED_DFA_PRE_CYCLE_INSN
439 #define TARGET_SCHED_DFA_PRE_CYCLE_INSN ia64_dfa_pre_cycle_insn
440
441 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD
442 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD\
443   ia64_first_cycle_multipass_dfa_lookahead_guard
444
445 #undef TARGET_SCHED_DFA_NEW_CYCLE
446 #define TARGET_SCHED_DFA_NEW_CYCLE ia64_dfa_new_cycle
447
448 #undef TARGET_SCHED_H_I_D_EXTENDED
449 #define TARGET_SCHED_H_I_D_EXTENDED ia64_h_i_d_extended
450
451 #undef TARGET_SCHED_ALLOC_SCHED_CONTEXT
452 #define TARGET_SCHED_ALLOC_SCHED_CONTEXT ia64_alloc_sched_context
453
454 #undef TARGET_SCHED_INIT_SCHED_CONTEXT
455 #define TARGET_SCHED_INIT_SCHED_CONTEXT ia64_init_sched_context
456
457 #undef TARGET_SCHED_SET_SCHED_CONTEXT
458 #define TARGET_SCHED_SET_SCHED_CONTEXT ia64_set_sched_context
459
460 #undef TARGET_SCHED_CLEAR_SCHED_CONTEXT
461 #define TARGET_SCHED_CLEAR_SCHED_CONTEXT ia64_clear_sched_context
462
463 #undef TARGET_SCHED_FREE_SCHED_CONTEXT
464 #define TARGET_SCHED_FREE_SCHED_CONTEXT ia64_free_sched_context
465
466 #undef TARGET_SCHED_SET_SCHED_FLAGS
467 #define TARGET_SCHED_SET_SCHED_FLAGS ia64_set_sched_flags
468
469 #undef TARGET_SCHED_GET_INSN_SPEC_DS
470 #define TARGET_SCHED_GET_INSN_SPEC_DS ia64_get_insn_spec_ds
471
472 #undef TARGET_SCHED_GET_INSN_CHECKED_DS
473 #define TARGET_SCHED_GET_INSN_CHECKED_DS ia64_get_insn_checked_ds
474
475 #undef TARGET_SCHED_SPECULATE_INSN
476 #define TARGET_SCHED_SPECULATE_INSN ia64_speculate_insn
477
478 #undef TARGET_SCHED_NEEDS_BLOCK_P
479 #define TARGET_SCHED_NEEDS_BLOCK_P ia64_needs_block_p
480
481 #undef TARGET_SCHED_GEN_SPEC_CHECK
482 #define TARGET_SCHED_GEN_SPEC_CHECK ia64_gen_spec_check
483
484 #undef TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD_SPEC
485 #define TARGET_SCHED_FIRST_CYCLE_MULTIPASS_DFA_LOOKAHEAD_GUARD_SPEC\
486   ia64_first_cycle_multipass_dfa_lookahead_guard_spec
487
488 #undef TARGET_SCHED_SKIP_RTX_P
489 #define TARGET_SCHED_SKIP_RTX_P ia64_skip_rtx_p
490
491 #undef TARGET_FUNCTION_OK_FOR_SIBCALL
492 #define TARGET_FUNCTION_OK_FOR_SIBCALL ia64_function_ok_for_sibcall
493 #undef TARGET_ARG_PARTIAL_BYTES
494 #define TARGET_ARG_PARTIAL_BYTES ia64_arg_partial_bytes
495 #undef TARGET_FUNCTION_ARG
496 #define TARGET_FUNCTION_ARG ia64_function_arg
497 #undef TARGET_FUNCTION_INCOMING_ARG
498 #define TARGET_FUNCTION_INCOMING_ARG ia64_function_incoming_arg
499 #undef TARGET_FUNCTION_ARG_ADVANCE
500 #define TARGET_FUNCTION_ARG_ADVANCE ia64_function_arg_advance
501 #undef TARGET_FUNCTION_ARG_BOUNDARY
502 #define TARGET_FUNCTION_ARG_BOUNDARY ia64_function_arg_boundary
503
504 #undef TARGET_ASM_OUTPUT_MI_THUNK
505 #define TARGET_ASM_OUTPUT_MI_THUNK ia64_output_mi_thunk
506 #undef TARGET_ASM_CAN_OUTPUT_MI_THUNK
507 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK hook_bool_const_tree_hwi_hwi_const_tree_true
508
509 #undef TARGET_ASM_FILE_START
510 #define TARGET_ASM_FILE_START ia64_file_start
511
512 #undef TARGET_ASM_GLOBALIZE_DECL_NAME
513 #define TARGET_ASM_GLOBALIZE_DECL_NAME ia64_globalize_decl_name
514
515 #undef TARGET_REGISTER_MOVE_COST
516 #define TARGET_REGISTER_MOVE_COST ia64_register_move_cost
517 #undef TARGET_MEMORY_MOVE_COST
518 #define TARGET_MEMORY_MOVE_COST ia64_memory_move_cost
519 #undef TARGET_RTX_COSTS
520 #define TARGET_RTX_COSTS ia64_rtx_costs
521 #undef TARGET_ADDRESS_COST
522 #define TARGET_ADDRESS_COST hook_int_rtx_bool_0
523
524 #undef TARGET_UNSPEC_MAY_TRAP_P
525 #define TARGET_UNSPEC_MAY_TRAP_P ia64_unspec_may_trap_p
526
527 #undef TARGET_MACHINE_DEPENDENT_REORG
528 #define TARGET_MACHINE_DEPENDENT_REORG ia64_reorg
529
530 #undef TARGET_ENCODE_SECTION_INFO
531 #define TARGET_ENCODE_SECTION_INFO ia64_encode_section_info
532
533 #undef  TARGET_SECTION_TYPE_FLAGS
534 #define TARGET_SECTION_TYPE_FLAGS  ia64_section_type_flags
535
536 #ifdef HAVE_AS_TLS
537 #undef TARGET_ASM_OUTPUT_DWARF_DTPREL
538 #define TARGET_ASM_OUTPUT_DWARF_DTPREL ia64_output_dwarf_dtprel
539 #endif
540
541 #undef TARGET_PROMOTE_FUNCTION_MODE
542 #define TARGET_PROMOTE_FUNCTION_MODE ia64_promote_function_mode
543
544 /* ??? Investigate.  */
545 #if 0
546 #undef TARGET_PROMOTE_PROTOTYPES
547 #define TARGET_PROMOTE_PROTOTYPES hook_bool_tree_true
548 #endif
549
550 #undef TARGET_FUNCTION_VALUE
551 #define TARGET_FUNCTION_VALUE ia64_function_value
552 #undef TARGET_LIBCALL_VALUE
553 #define TARGET_LIBCALL_VALUE ia64_libcall_value
554 #undef TARGET_FUNCTION_VALUE_REGNO_P
555 #define TARGET_FUNCTION_VALUE_REGNO_P ia64_function_value_regno_p
556
557 #undef TARGET_STRUCT_VALUE_RTX
558 #define TARGET_STRUCT_VALUE_RTX ia64_struct_value_rtx
559 #undef TARGET_RETURN_IN_MEMORY
560 #define TARGET_RETURN_IN_MEMORY ia64_return_in_memory
561 #undef TARGET_SETUP_INCOMING_VARARGS
562 #define TARGET_SETUP_INCOMING_VARARGS ia64_setup_incoming_varargs
563 #undef TARGET_STRICT_ARGUMENT_NAMING
564 #define TARGET_STRICT_ARGUMENT_NAMING hook_bool_CUMULATIVE_ARGS_true
565 #undef TARGET_MUST_PASS_IN_STACK
566 #define TARGET_MUST_PASS_IN_STACK must_pass_in_stack_var_size
567 #undef TARGET_GET_RAW_RESULT_MODE
568 #define TARGET_GET_RAW_RESULT_MODE ia64_get_reg_raw_mode
569 #undef TARGET_GET_RAW_ARG_MODE
570 #define TARGET_GET_RAW_ARG_MODE ia64_get_reg_raw_mode
571
572 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
573 #define TARGET_GIMPLIFY_VA_ARG_EXPR ia64_gimplify_va_arg
574
575 #undef TARGET_DWARF_HANDLE_FRAME_UNSPEC
576 #define TARGET_DWARF_HANDLE_FRAME_UNSPEC  ia64_dwarf_handle_frame_unspec
577 #undef TARGET_ASM_UNWIND_EMIT
578 #define TARGET_ASM_UNWIND_EMIT ia64_asm_unwind_emit
579 #undef TARGET_ASM_EMIT_EXCEPT_PERSONALITY
580 #define TARGET_ASM_EMIT_EXCEPT_PERSONALITY  ia64_asm_emit_except_personality
581 #undef TARGET_ASM_INIT_SECTIONS
582 #define TARGET_ASM_INIT_SECTIONS  ia64_asm_init_sections
583
584 #undef TARGET_DEBUG_UNWIND_INFO
585 #define TARGET_DEBUG_UNWIND_INFO  ia64_debug_unwind_info
586 #undef TARGET_EXCEPT_UNWIND_INFO
587 #define TARGET_EXCEPT_UNWIND_INFO  ia64_except_unwind_info
588
589 #undef TARGET_SCALAR_MODE_SUPPORTED_P
590 #define TARGET_SCALAR_MODE_SUPPORTED_P ia64_scalar_mode_supported_p
591 #undef TARGET_VECTOR_MODE_SUPPORTED_P
592 #define TARGET_VECTOR_MODE_SUPPORTED_P ia64_vector_mode_supported_p
593
594 /* ia64 architecture manual 4.4.7: ... reads, writes, and flushes may occur
595    in an order different from the specified program order.  */
596 #undef TARGET_RELAXED_ORDERING
597 #define TARGET_RELAXED_ORDERING true
598
599 #undef TARGET_DEFAULT_TARGET_FLAGS
600 #define TARGET_DEFAULT_TARGET_FLAGS (TARGET_DEFAULT | TARGET_CPU_DEFAULT)
601 #undef TARGET_HANDLE_OPTION
602 #define TARGET_HANDLE_OPTION ia64_handle_option
603
604 #undef TARGET_CANNOT_FORCE_CONST_MEM
605 #define TARGET_CANNOT_FORCE_CONST_MEM ia64_cannot_force_const_mem
606
607 #undef TARGET_MANGLE_TYPE
608 #define TARGET_MANGLE_TYPE ia64_mangle_type
609
610 #undef TARGET_INVALID_CONVERSION
611 #define TARGET_INVALID_CONVERSION ia64_invalid_conversion
612 #undef TARGET_INVALID_UNARY_OP
613 #define TARGET_INVALID_UNARY_OP ia64_invalid_unary_op
614 #undef TARGET_INVALID_BINARY_OP
615 #define TARGET_INVALID_BINARY_OP ia64_invalid_binary_op
616
617 #undef TARGET_C_MODE_FOR_SUFFIX
618 #define TARGET_C_MODE_FOR_SUFFIX ia64_c_mode_for_suffix
619
620 #undef TARGET_CAN_ELIMINATE
621 #define TARGET_CAN_ELIMINATE ia64_can_eliminate
622
623 #undef TARGET_TRAMPOLINE_INIT
624 #define TARGET_TRAMPOLINE_INIT ia64_trampoline_init
625
626 #undef TARGET_INVALID_WITHIN_DOLOOP
627 #define TARGET_INVALID_WITHIN_DOLOOP hook_constcharptr_const_rtx_null
628
629 #undef TARGET_OVERRIDE_OPTIONS_AFTER_CHANGE
630 #define TARGET_OVERRIDE_OPTIONS_AFTER_CHANGE ia64_override_options_after_change
631
632 #undef TARGET_PREFERRED_RELOAD_CLASS
633 #define TARGET_PREFERRED_RELOAD_CLASS ia64_preferred_reload_class
634
635 struct gcc_target targetm = TARGET_INITIALIZER;
636 \f
637 typedef enum
638   {
639     ADDR_AREA_NORMAL,   /* normal address area */
640     ADDR_AREA_SMALL     /* addressable by "addl" (-2MB < addr < 2MB) */
641   }
642 ia64_addr_area;
643
644 static GTY(()) tree small_ident1;
645 static GTY(()) tree small_ident2;
646
647 static void
648 init_idents (void)
649 {
650   if (small_ident1 == 0)
651     {
652       small_ident1 = get_identifier ("small");
653       small_ident2 = get_identifier ("__small__");
654     }
655 }
656
657 /* Retrieve the address area that has been chosen for the given decl.  */
658
659 static ia64_addr_area
660 ia64_get_addr_area (tree decl)
661 {
662   tree model_attr;
663
664   model_attr = lookup_attribute ("model", DECL_ATTRIBUTES (decl));
665   if (model_attr)
666     {
667       tree id;
668
669       init_idents ();
670       id = TREE_VALUE (TREE_VALUE (model_attr));
671       if (id == small_ident1 || id == small_ident2)
672         return ADDR_AREA_SMALL;
673     }
674   return ADDR_AREA_NORMAL;
675 }
676
677 static tree
678 ia64_handle_model_attribute (tree *node, tree name, tree args,
679                              int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
680 {
681   ia64_addr_area addr_area = ADDR_AREA_NORMAL;
682   ia64_addr_area area;
683   tree arg, decl = *node;
684
685   init_idents ();
686   arg = TREE_VALUE (args);
687   if (arg == small_ident1 || arg == small_ident2)
688     {
689       addr_area = ADDR_AREA_SMALL;
690     }
691   else
692     {
693       warning (OPT_Wattributes, "invalid argument of %qE attribute",
694                name);
695       *no_add_attrs = true;
696     }
697
698   switch (TREE_CODE (decl))
699     {
700     case VAR_DECL:
701       if ((DECL_CONTEXT (decl) && TREE_CODE (DECL_CONTEXT (decl))
702            == FUNCTION_DECL)
703           && !TREE_STATIC (decl))
704         {
705           error_at (DECL_SOURCE_LOCATION (decl),
706                     "an address area attribute cannot be specified for "
707                     "local variables");
708           *no_add_attrs = true;
709         }
710       area = ia64_get_addr_area (decl);
711       if (area != ADDR_AREA_NORMAL && addr_area != area)
712         {
713           error ("address area of %q+D conflicts with previous "
714                  "declaration", decl);
715           *no_add_attrs = true;
716         }
717       break;
718
719     case FUNCTION_DECL:
720       error_at (DECL_SOURCE_LOCATION (decl),
721                 "address area attribute cannot be specified for "
722                 "functions");
723       *no_add_attrs = true;
724       break;
725
726     default:
727       warning (OPT_Wattributes, "%qE attribute ignored",
728                name);
729       *no_add_attrs = true;
730       break;
731     }
732
733   return NULL_TREE;
734 }
735
736 /* The section must have global and overlaid attributes.  */
737 #define SECTION_VMS_OVERLAY SECTION_MACH_DEP
738
739 /* Part of the low level implementation of DEC Ada pragma Common_Object which
740    enables the shared use of variables stored in overlaid linker areas
741    corresponding to the use of Fortran COMMON.  */
742
743 static tree
744 ia64_vms_common_object_attribute (tree *node, tree name, tree args,
745                                   int flags ATTRIBUTE_UNUSED,
746                                   bool *no_add_attrs)
747 {
748     tree decl = *node;
749     tree id, val;
750     if (! DECL_P (decl))
751       abort ();
752   
753     DECL_COMMON (decl) = 1;
754     id = TREE_VALUE (args);
755     if (TREE_CODE (id) == IDENTIFIER_NODE)
756       val = build_string (IDENTIFIER_LENGTH (id), IDENTIFIER_POINTER (id));
757     else if (TREE_CODE (id) == STRING_CST)
758       val = id;
759     else
760       {
761         warning (OPT_Wattributes,
762                  "%qE attribute requires a string constant argument", name);
763         *no_add_attrs = true;
764         return NULL_TREE;
765       }
766     DECL_SECTION_NAME (decl) = val;
767     return NULL_TREE;
768 }
769
770 /* Part of the low level implementation of DEC Ada pragma Common_Object.  */
771
772 void
773 ia64_vms_output_aligned_decl_common (FILE *file, tree decl, const char *name,
774                                      unsigned HOST_WIDE_INT size,
775                                      unsigned int align)
776 {
777   tree attr = DECL_ATTRIBUTES (decl);
778
779   /* As common_object attribute set DECL_SECTION_NAME check it before
780      looking up the attribute.  */
781   if (DECL_SECTION_NAME (decl) && attr)
782     attr = lookup_attribute ("common_object", attr);
783   else
784     attr = NULL_TREE;
785
786   if (!attr)
787     {
788       /*  Code from elfos.h.  */
789       fprintf (file, "%s", COMMON_ASM_OP);
790       assemble_name (file, name);
791       fprintf (file, ","HOST_WIDE_INT_PRINT_UNSIGNED",%u\n",
792                size, align / BITS_PER_UNIT);
793     }
794   else
795     {
796       ASM_OUTPUT_ALIGN (file, floor_log2 (align / BITS_PER_UNIT));
797       ASM_OUTPUT_LABEL (file, name);
798       ASM_OUTPUT_SKIP (file, size ? size : 1);
799     }
800 }
801
802 /* Definition of TARGET_ASM_NAMED_SECTION for VMS.  */
803
804 void
805 ia64_vms_elf_asm_named_section (const char *name, unsigned int flags,
806                                 tree decl)
807 {
808   if (!(flags & SECTION_VMS_OVERLAY))
809     {
810       default_elf_asm_named_section (name, flags, decl);
811       return;
812     }
813   if (flags != (SECTION_VMS_OVERLAY | SECTION_WRITE))
814     abort ();
815
816   if (flags & SECTION_DECLARED)
817     {
818       fprintf (asm_out_file, "\t.section\t%s\n", name);
819       return;
820     }
821
822   fprintf (asm_out_file, "\t.section\t%s,\"awgO\"\n", name);
823 }
824
825 static void
826 ia64_encode_addr_area (tree decl, rtx symbol)
827 {
828   int flags;
829
830   flags = SYMBOL_REF_FLAGS (symbol);
831   switch (ia64_get_addr_area (decl))
832     {
833     case ADDR_AREA_NORMAL: break;
834     case ADDR_AREA_SMALL: flags |= SYMBOL_FLAG_SMALL_ADDR; break;
835     default: gcc_unreachable ();
836     }
837   SYMBOL_REF_FLAGS (symbol) = flags;
838 }
839
840 static void
841 ia64_encode_section_info (tree decl, rtx rtl, int first)
842 {
843   default_encode_section_info (decl, rtl, first);
844
845   /* Careful not to prod global register variables.  */
846   if (TREE_CODE (decl) == VAR_DECL
847       && GET_CODE (DECL_RTL (decl)) == MEM
848       && GET_CODE (XEXP (DECL_RTL (decl), 0)) == SYMBOL_REF
849       && (TREE_STATIC (decl) || DECL_EXTERNAL (decl)))
850     ia64_encode_addr_area (decl, XEXP (rtl, 0));
851 }
852 \f
853 /* Return 1 if the operands of a move are ok.  */
854
855 int
856 ia64_move_ok (rtx dst, rtx src)
857 {
858   /* If we're under init_recog_no_volatile, we'll not be able to use
859      memory_operand.  So check the code directly and don't worry about
860      the validity of the underlying address, which should have been
861      checked elsewhere anyway.  */
862   if (GET_CODE (dst) != MEM)
863     return 1;
864   if (GET_CODE (src) == MEM)
865     return 0;
866   if (register_operand (src, VOIDmode))
867     return 1;
868
869   /* Otherwise, this must be a constant, and that either 0 or 0.0 or 1.0.  */
870   if (INTEGRAL_MODE_P (GET_MODE (dst)))
871     return src == const0_rtx;
872   else
873     return satisfies_constraint_G (src);
874 }
875
876 /* Return 1 if the operands are ok for a floating point load pair.  */
877
878 int
879 ia64_load_pair_ok (rtx dst, rtx src)
880 {
881   if (GET_CODE (dst) != REG || !FP_REGNO_P (REGNO (dst)))
882     return 0;
883   if (GET_CODE (src) != MEM || MEM_VOLATILE_P (src))
884     return 0;
885   switch (GET_CODE (XEXP (src, 0)))
886     {
887     case REG:
888     case POST_INC:
889       break;
890     case POST_DEC:
891       return 0;
892     case POST_MODIFY:
893       {
894         rtx adjust = XEXP (XEXP (XEXP (src, 0), 1), 1);
895
896         if (GET_CODE (adjust) != CONST_INT
897             || INTVAL (adjust) != GET_MODE_SIZE (GET_MODE (src)))
898           return 0;
899       }
900       break;
901     default:
902       abort ();
903     }
904   return 1;
905 }
906
907 int
908 addp4_optimize_ok (rtx op1, rtx op2)
909 {
910   return (basereg_operand (op1, GET_MODE(op1)) !=
911           basereg_operand (op2, GET_MODE(op2)));
912 }
913
914 /* Check if OP is a mask suitable for use with SHIFT in a dep.z instruction.
915    Return the length of the field, or <= 0 on failure.  */
916
917 int
918 ia64_depz_field_mask (rtx rop, rtx rshift)
919 {
920   unsigned HOST_WIDE_INT op = INTVAL (rop);
921   unsigned HOST_WIDE_INT shift = INTVAL (rshift);
922
923   /* Get rid of the zero bits we're shifting in.  */
924   op >>= shift;
925
926   /* We must now have a solid block of 1's at bit 0.  */
927   return exact_log2 (op + 1);
928 }
929
930 /* Return the TLS model to use for ADDR.  */
931
932 static enum tls_model
933 tls_symbolic_operand_type (rtx addr)
934 {
935   enum tls_model tls_kind = TLS_MODEL_NONE;
936
937   if (GET_CODE (addr) == CONST)
938     {
939       if (GET_CODE (XEXP (addr, 0)) == PLUS
940           && GET_CODE (XEXP (XEXP (addr, 0), 0)) == SYMBOL_REF)
941         tls_kind = SYMBOL_REF_TLS_MODEL (XEXP (XEXP (addr, 0), 0));
942     }
943   else if (GET_CODE (addr) == SYMBOL_REF)
944     tls_kind = SYMBOL_REF_TLS_MODEL (addr);
945
946   return tls_kind;
947 }
948
949 /* Return true if X is a constant that is valid for some immediate
950    field in an instruction.  */
951
952 bool
953 ia64_legitimate_constant_p (rtx x)
954 {
955   switch (GET_CODE (x))
956     {
957     case CONST_INT:
958     case LABEL_REF:
959       return true;
960
961     case CONST_DOUBLE:
962       if (GET_MODE (x) == VOIDmode || GET_MODE (x) == SFmode
963           || GET_MODE (x) == DFmode)
964         return true;
965       return satisfies_constraint_G (x);
966
967     case CONST:
968     case SYMBOL_REF:
969       /* ??? Short term workaround for PR 28490.  We must make the code here
970          match the code in ia64_expand_move and move_operand, even though they
971          are both technically wrong.  */
972       if (tls_symbolic_operand_type (x) == 0)
973         {
974           HOST_WIDE_INT addend = 0;
975           rtx op = x;
976
977           if (GET_CODE (op) == CONST
978               && GET_CODE (XEXP (op, 0)) == PLUS
979               && GET_CODE (XEXP (XEXP (op, 0), 1)) == CONST_INT)
980             {
981               addend = INTVAL (XEXP (XEXP (op, 0), 1));
982               op = XEXP (XEXP (op, 0), 0);
983             }
984
985           if (any_offset_symbol_operand (op, GET_MODE (op))
986               || function_operand (op, GET_MODE (op)))
987             return true;
988           if (aligned_offset_symbol_operand (op, GET_MODE (op)))
989             return (addend & 0x3fff) == 0;
990           return false;
991         }
992       return false;
993
994     case CONST_VECTOR:
995       {
996         enum machine_mode mode = GET_MODE (x);
997
998         if (mode == V2SFmode)
999           return satisfies_constraint_Y (x);
1000
1001         return (GET_MODE_CLASS (mode) == MODE_VECTOR_INT
1002                 && GET_MODE_SIZE (mode) <= 8);
1003       }
1004
1005     default:
1006       return false;
1007     }
1008 }
1009
1010 /* Don't allow TLS addresses to get spilled to memory.  */
1011
1012 static bool
1013 ia64_cannot_force_const_mem (rtx x)
1014 {
1015   if (GET_MODE (x) == RFmode)
1016     return true;
1017   return tls_symbolic_operand_type (x) != 0;
1018 }
1019
1020 /* Expand a symbolic constant load.  */
1021
1022 bool
1023 ia64_expand_load_address (rtx dest, rtx src)
1024 {
1025   gcc_assert (GET_CODE (dest) == REG);
1026
1027   /* ILP32 mode still loads 64-bits of data from the GOT.  This avoids
1028      having to pointer-extend the value afterward.  Other forms of address
1029      computation below are also more natural to compute as 64-bit quantities.
1030      If we've been given an SImode destination register, change it.  */
1031   if (GET_MODE (dest) != Pmode)
1032     dest = gen_rtx_REG_offset (dest, Pmode, REGNO (dest),
1033                                byte_lowpart_offset (Pmode, GET_MODE (dest)));
1034
1035   if (TARGET_NO_PIC)
1036     return false;
1037   if (small_addr_symbolic_operand (src, VOIDmode))
1038     return false;
1039
1040   if (TARGET_AUTO_PIC)
1041     emit_insn (gen_load_gprel64 (dest, src));
1042   else if (GET_CODE (src) == SYMBOL_REF && SYMBOL_REF_FUNCTION_P (src))
1043     emit_insn (gen_load_fptr (dest, src));
1044   else if (sdata_symbolic_operand (src, VOIDmode))
1045     emit_insn (gen_load_gprel (dest, src));
1046   else
1047     {
1048       HOST_WIDE_INT addend = 0;
1049       rtx tmp;
1050
1051       /* We did split constant offsets in ia64_expand_move, and we did try
1052          to keep them split in move_operand, but we also allowed reload to
1053          rematerialize arbitrary constants rather than spill the value to
1054          the stack and reload it.  So we have to be prepared here to split
1055          them apart again.  */
1056       if (GET_CODE (src) == CONST)
1057         {
1058           HOST_WIDE_INT hi, lo;
1059
1060           hi = INTVAL (XEXP (XEXP (src, 0), 1));
1061           lo = ((hi & 0x3fff) ^ 0x2000) - 0x2000;
1062           hi = hi - lo;
1063
1064           if (lo != 0)
1065             {
1066               addend = lo;
1067               src = plus_constant (XEXP (XEXP (src, 0), 0), hi);
1068             }
1069         }
1070
1071       tmp = gen_rtx_HIGH (Pmode, src);
1072       tmp = gen_rtx_PLUS (Pmode, tmp, pic_offset_table_rtx);
1073       emit_insn (gen_rtx_SET (VOIDmode, dest, tmp));
1074
1075       tmp = gen_rtx_LO_SUM (Pmode, dest, src);
1076       emit_insn (gen_rtx_SET (VOIDmode, dest, tmp));
1077
1078       if (addend)
1079         {
1080           tmp = gen_rtx_PLUS (Pmode, dest, GEN_INT (addend));
1081           emit_insn (gen_rtx_SET (VOIDmode, dest, tmp));
1082         }
1083     }
1084
1085   return true;
1086 }
1087
1088 static GTY(()) rtx gen_tls_tga;
1089 static rtx
1090 gen_tls_get_addr (void)
1091 {
1092   if (!gen_tls_tga)
1093     gen_tls_tga = init_one_libfunc ("__tls_get_addr");
1094   return gen_tls_tga;
1095 }
1096
1097 static GTY(()) rtx thread_pointer_rtx;
1098 static rtx
1099 gen_thread_pointer (void)
1100 {
1101   if (!thread_pointer_rtx)
1102     thread_pointer_rtx = gen_rtx_REG (Pmode, 13);
1103   return thread_pointer_rtx;
1104 }
1105
1106 static rtx
1107 ia64_expand_tls_address (enum tls_model tls_kind, rtx op0, rtx op1,
1108                          rtx orig_op1, HOST_WIDE_INT addend)
1109 {
1110   rtx tga_op1, tga_op2, tga_ret, tga_eqv, tmp, insns;
1111   rtx orig_op0 = op0;
1112   HOST_WIDE_INT addend_lo, addend_hi;
1113
1114   switch (tls_kind)
1115     {
1116     case TLS_MODEL_GLOBAL_DYNAMIC:
1117       start_sequence ();
1118
1119       tga_op1 = gen_reg_rtx (Pmode);
1120       emit_insn (gen_load_dtpmod (tga_op1, op1));
1121
1122       tga_op2 = gen_reg_rtx (Pmode);
1123       emit_insn (gen_load_dtprel (tga_op2, op1));
1124
1125       tga_ret = emit_library_call_value (gen_tls_get_addr (), NULL_RTX,
1126                                          LCT_CONST, Pmode, 2, tga_op1,
1127                                          Pmode, tga_op2, Pmode);
1128
1129       insns = get_insns ();
1130       end_sequence ();
1131
1132       if (GET_MODE (op0) != Pmode)
1133         op0 = tga_ret;
1134       emit_libcall_block (insns, op0, tga_ret, op1);
1135       break;
1136
1137     case TLS_MODEL_LOCAL_DYNAMIC:
1138       /* ??? This isn't the completely proper way to do local-dynamic
1139          If the call to __tls_get_addr is used only by a single symbol,
1140          then we should (somehow) move the dtprel to the second arg
1141          to avoid the extra add.  */
1142       start_sequence ();
1143
1144       tga_op1 = gen_reg_rtx (Pmode);
1145       emit_insn (gen_load_dtpmod (tga_op1, op1));
1146
1147       tga_op2 = const0_rtx;
1148
1149       tga_ret = emit_library_call_value (gen_tls_get_addr (), NULL_RTX,
1150                                          LCT_CONST, Pmode, 2, tga_op1,
1151                                          Pmode, tga_op2, Pmode);
1152
1153       insns = get_insns ();
1154       end_sequence ();
1155
1156       tga_eqv = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx),
1157                                 UNSPEC_LD_BASE);
1158       tmp = gen_reg_rtx (Pmode);
1159       emit_libcall_block (insns, tmp, tga_ret, tga_eqv);
1160
1161       if (!register_operand (op0, Pmode))
1162         op0 = gen_reg_rtx (Pmode);
1163       if (TARGET_TLS64)
1164         {
1165           emit_insn (gen_load_dtprel (op0, op1));
1166           emit_insn (gen_adddi3 (op0, tmp, op0));
1167         }
1168       else
1169         emit_insn (gen_add_dtprel (op0, op1, tmp));
1170       break;
1171
1172     case TLS_MODEL_INITIAL_EXEC:
1173       addend_lo = ((addend & 0x3fff) ^ 0x2000) - 0x2000;
1174       addend_hi = addend - addend_lo;
1175
1176       op1 = plus_constant (op1, addend_hi);
1177       addend = addend_lo;
1178
1179       tmp = gen_reg_rtx (Pmode);
1180       emit_insn (gen_load_tprel (tmp, op1));
1181
1182       if (!register_operand (op0, Pmode))
1183         op0 = gen_reg_rtx (Pmode);
1184       emit_insn (gen_adddi3 (op0, tmp, gen_thread_pointer ()));
1185       break;
1186
1187     case TLS_MODEL_LOCAL_EXEC:
1188       if (!register_operand (op0, Pmode))
1189         op0 = gen_reg_rtx (Pmode);
1190
1191       op1 = orig_op1;
1192       addend = 0;
1193       if (TARGET_TLS64)
1194         {
1195           emit_insn (gen_load_tprel (op0, op1));
1196           emit_insn (gen_adddi3 (op0, op0, gen_thread_pointer ()));
1197         }
1198       else
1199         emit_insn (gen_add_tprel (op0, op1, gen_thread_pointer ()));
1200       break;
1201
1202     default:
1203       gcc_unreachable ();
1204     }
1205
1206   if (addend)
1207     op0 = expand_simple_binop (Pmode, PLUS, op0, GEN_INT (addend),
1208                                orig_op0, 1, OPTAB_DIRECT);
1209   if (orig_op0 == op0)
1210     return NULL_RTX;
1211   if (GET_MODE (orig_op0) == Pmode)
1212     return op0;
1213   return gen_lowpart (GET_MODE (orig_op0), op0);
1214 }
1215
1216 rtx
1217 ia64_expand_move (rtx op0, rtx op1)
1218 {
1219   enum machine_mode mode = GET_MODE (op0);
1220
1221   if (!reload_in_progress && !reload_completed && !ia64_move_ok (op0, op1))
1222     op1 = force_reg (mode, op1);
1223
1224   if ((mode == Pmode || mode == ptr_mode) && symbolic_operand (op1, VOIDmode))
1225     {
1226       HOST_WIDE_INT addend = 0;
1227       enum tls_model tls_kind;
1228       rtx sym = op1;
1229
1230       if (GET_CODE (op1) == CONST
1231           && GET_CODE (XEXP (op1, 0)) == PLUS
1232           && GET_CODE (XEXP (XEXP (op1, 0), 1)) == CONST_INT)
1233         {
1234           addend = INTVAL (XEXP (XEXP (op1, 0), 1));
1235           sym = XEXP (XEXP (op1, 0), 0);
1236         }
1237
1238       tls_kind = tls_symbolic_operand_type (sym);
1239       if (tls_kind)
1240         return ia64_expand_tls_address (tls_kind, op0, sym, op1, addend);
1241
1242       if (any_offset_symbol_operand (sym, mode))
1243         addend = 0;
1244       else if (aligned_offset_symbol_operand (sym, mode))
1245         {
1246           HOST_WIDE_INT addend_lo, addend_hi;
1247               
1248           addend_lo = ((addend & 0x3fff) ^ 0x2000) - 0x2000;
1249           addend_hi = addend - addend_lo;
1250
1251           if (addend_lo != 0)
1252             {
1253               op1 = plus_constant (sym, addend_hi);
1254               addend = addend_lo;
1255             }
1256           else
1257             addend = 0;
1258         }
1259       else
1260         op1 = sym;
1261
1262       if (reload_completed)
1263         {
1264           /* We really should have taken care of this offset earlier.  */
1265           gcc_assert (addend == 0);
1266           if (ia64_expand_load_address (op0, op1))
1267             return NULL_RTX;
1268         }
1269
1270       if (addend)
1271         {
1272           rtx subtarget = !can_create_pseudo_p () ? op0 : gen_reg_rtx (mode);
1273
1274           emit_insn (gen_rtx_SET (VOIDmode, subtarget, op1));
1275
1276           op1 = expand_simple_binop (mode, PLUS, subtarget,
1277                                      GEN_INT (addend), op0, 1, OPTAB_DIRECT);
1278           if (op0 == op1)
1279             return NULL_RTX;
1280         }
1281     }
1282
1283   return op1;
1284 }
1285
1286 /* Split a move from OP1 to OP0 conditional on COND.  */
1287
1288 void
1289 ia64_emit_cond_move (rtx op0, rtx op1, rtx cond)
1290 {
1291   rtx insn, first = get_last_insn ();
1292
1293   emit_move_insn (op0, op1);
1294
1295   for (insn = get_last_insn (); insn != first; insn = PREV_INSN (insn))
1296     if (INSN_P (insn))
1297       PATTERN (insn) = gen_rtx_COND_EXEC (VOIDmode, copy_rtx (cond),
1298                                           PATTERN (insn));
1299 }
1300
1301 /* Split a post-reload TImode or TFmode reference into two DImode
1302    components.  This is made extra difficult by the fact that we do
1303    not get any scratch registers to work with, because reload cannot
1304    be prevented from giving us a scratch that overlaps the register
1305    pair involved.  So instead, when addressing memory, we tweak the
1306    pointer register up and back down with POST_INCs.  Or up and not
1307    back down when we can get away with it.
1308
1309    REVERSED is true when the loads must be done in reversed order
1310    (high word first) for correctness.  DEAD is true when the pointer
1311    dies with the second insn we generate and therefore the second
1312    address must not carry a postmodify.
1313
1314    May return an insn which is to be emitted after the moves.  */
1315
1316 static rtx
1317 ia64_split_tmode (rtx out[2], rtx in, bool reversed, bool dead)
1318 {
1319   rtx fixup = 0;
1320
1321   switch (GET_CODE (in))
1322     {
1323     case REG:
1324       out[reversed] = gen_rtx_REG (DImode, REGNO (in));
1325       out[!reversed] = gen_rtx_REG (DImode, REGNO (in) + 1);
1326       break;
1327
1328     case CONST_INT:
1329     case CONST_DOUBLE:
1330       /* Cannot occur reversed.  */
1331       gcc_assert (!reversed);
1332       
1333       if (GET_MODE (in) != TFmode)
1334         split_double (in, &out[0], &out[1]);
1335       else
1336         /* split_double does not understand how to split a TFmode
1337            quantity into a pair of DImode constants.  */
1338         {
1339           REAL_VALUE_TYPE r;
1340           unsigned HOST_WIDE_INT p[2];
1341           long l[4];  /* TFmode is 128 bits */
1342
1343           REAL_VALUE_FROM_CONST_DOUBLE (r, in);
1344           real_to_target (l, &r, TFmode);
1345
1346           if (FLOAT_WORDS_BIG_ENDIAN)
1347             {
1348               p[0] = (((unsigned HOST_WIDE_INT) l[0]) << 32) + l[1];
1349               p[1] = (((unsigned HOST_WIDE_INT) l[2]) << 32) + l[3];
1350             }
1351           else
1352             {
1353               p[0] = (((unsigned HOST_WIDE_INT) l[1]) << 32) + l[0];
1354               p[1] = (((unsigned HOST_WIDE_INT) l[3]) << 32) + l[2];
1355             }
1356           out[0] = GEN_INT (p[0]);
1357           out[1] = GEN_INT (p[1]);
1358         }
1359       break;
1360
1361     case MEM:
1362       {
1363         rtx base = XEXP (in, 0);
1364         rtx offset;
1365
1366         switch (GET_CODE (base))
1367           {
1368           case REG:
1369             if (!reversed)
1370               {
1371                 out[0] = adjust_automodify_address
1372                   (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1373                 out[1] = adjust_automodify_address
1374                   (in, DImode, dead ? 0 : gen_rtx_POST_DEC (Pmode, base), 8);
1375               }
1376             else
1377               {
1378                 /* Reversal requires a pre-increment, which can only
1379                    be done as a separate insn.  */
1380                 emit_insn (gen_adddi3 (base, base, GEN_INT (8)));
1381                 out[0] = adjust_automodify_address
1382                   (in, DImode, gen_rtx_POST_DEC (Pmode, base), 8);
1383                 out[1] = adjust_address (in, DImode, 0);
1384               }
1385             break;
1386
1387           case POST_INC:
1388             gcc_assert (!reversed && !dead);
1389             
1390             /* Just do the increment in two steps.  */
1391             out[0] = adjust_automodify_address (in, DImode, 0, 0);
1392             out[1] = adjust_automodify_address (in, DImode, 0, 8);
1393             break;
1394
1395           case POST_DEC:
1396             gcc_assert (!reversed && !dead);
1397             
1398             /* Add 8, subtract 24.  */
1399             base = XEXP (base, 0);
1400             out[0] = adjust_automodify_address
1401               (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1402             out[1] = adjust_automodify_address
1403               (in, DImode,
1404                gen_rtx_POST_MODIFY (Pmode, base, plus_constant (base, -24)),
1405                8);
1406             break;
1407
1408           case POST_MODIFY:
1409             gcc_assert (!reversed && !dead);
1410
1411             /* Extract and adjust the modification.  This case is
1412                trickier than the others, because we might have an
1413                index register, or we might have a combined offset that
1414                doesn't fit a signed 9-bit displacement field.  We can
1415                assume the incoming expression is already legitimate.  */
1416             offset = XEXP (base, 1);
1417             base = XEXP (base, 0);
1418
1419             out[0] = adjust_automodify_address
1420               (in, DImode, gen_rtx_POST_INC (Pmode, base), 0);
1421
1422             if (GET_CODE (XEXP (offset, 1)) == REG)
1423               {
1424                 /* Can't adjust the postmodify to match.  Emit the
1425                    original, then a separate addition insn.  */
1426                 out[1] = adjust_automodify_address (in, DImode, 0, 8);
1427                 fixup = gen_adddi3 (base, base, GEN_INT (-8));
1428               }
1429             else
1430               {
1431                 gcc_assert (GET_CODE (XEXP (offset, 1)) == CONST_INT);
1432                 if (INTVAL (XEXP (offset, 1)) < -256 + 8)
1433                   {
1434                     /* Again the postmodify cannot be made to match,
1435                        but in this case it's more efficient to get rid
1436                        of the postmodify entirely and fix up with an
1437                        add insn.  */
1438                     out[1] = adjust_automodify_address (in, DImode, base, 8);
1439                     fixup = gen_adddi3
1440                       (base, base, GEN_INT (INTVAL (XEXP (offset, 1)) - 8));
1441                   }
1442                 else
1443                   {
1444                     /* Combined offset still fits in the displacement field.
1445                        (We cannot overflow it at the high end.)  */
1446                     out[1] = adjust_automodify_address
1447                       (in, DImode, gen_rtx_POST_MODIFY
1448                        (Pmode, base, gen_rtx_PLUS
1449                         (Pmode, base,
1450                          GEN_INT (INTVAL (XEXP (offset, 1)) - 8))),
1451                        8);
1452                   }
1453               }
1454             break;
1455
1456           default:
1457             gcc_unreachable ();
1458           }
1459         break;
1460       }
1461
1462     default:
1463       gcc_unreachable ();
1464     }
1465
1466   return fixup;
1467 }
1468
1469 /* Split a TImode or TFmode move instruction after reload.
1470    This is used by *movtf_internal and *movti_internal.  */
1471 void
1472 ia64_split_tmode_move (rtx operands[])
1473 {
1474   rtx in[2], out[2], insn;
1475   rtx fixup[2];
1476   bool dead = false;
1477   bool reversed = false;
1478
1479   /* It is possible for reload to decide to overwrite a pointer with
1480      the value it points to.  In that case we have to do the loads in
1481      the appropriate order so that the pointer is not destroyed too
1482      early.  Also we must not generate a postmodify for that second
1483      load, or rws_access_regno will die.  */
1484   if (GET_CODE (operands[1]) == MEM
1485       && reg_overlap_mentioned_p (operands[0], operands[1]))
1486     {
1487       rtx base = XEXP (operands[1], 0);
1488       while (GET_CODE (base) != REG)
1489         base = XEXP (base, 0);
1490
1491       if (REGNO (base) == REGNO (operands[0]))
1492         reversed = true;
1493       dead = true;
1494     }
1495   /* Another reason to do the moves in reversed order is if the first
1496      element of the target register pair is also the second element of
1497      the source register pair.  */
1498   if (GET_CODE (operands[0]) == REG && GET_CODE (operands[1]) == REG
1499       && REGNO (operands[0]) == REGNO (operands[1]) + 1)
1500     reversed = true;
1501
1502   fixup[0] = ia64_split_tmode (in, operands[1], reversed, dead);
1503   fixup[1] = ia64_split_tmode (out, operands[0], reversed, dead);
1504
1505 #define MAYBE_ADD_REG_INC_NOTE(INSN, EXP)                               \
1506   if (GET_CODE (EXP) == MEM                                             \
1507       && (GET_CODE (XEXP (EXP, 0)) == POST_MODIFY                       \
1508           || GET_CODE (XEXP (EXP, 0)) == POST_INC                       \
1509           || GET_CODE (XEXP (EXP, 0)) == POST_DEC))                     \
1510     add_reg_note (insn, REG_INC, XEXP (XEXP (EXP, 0), 0))
1511
1512   insn = emit_insn (gen_rtx_SET (VOIDmode, out[0], in[0]));
1513   MAYBE_ADD_REG_INC_NOTE (insn, in[0]);
1514   MAYBE_ADD_REG_INC_NOTE (insn, out[0]);
1515
1516   insn = emit_insn (gen_rtx_SET (VOIDmode, out[1], in[1]));
1517   MAYBE_ADD_REG_INC_NOTE (insn, in[1]);
1518   MAYBE_ADD_REG_INC_NOTE (insn, out[1]);
1519
1520   if (fixup[0])
1521     emit_insn (fixup[0]);
1522   if (fixup[1])
1523     emit_insn (fixup[1]);
1524
1525 #undef MAYBE_ADD_REG_INC_NOTE
1526 }
1527
1528 /* ??? Fixing GR->FR XFmode moves during reload is hard.  You need to go
1529    through memory plus an extra GR scratch register.  Except that you can
1530    either get the first from SECONDARY_MEMORY_NEEDED or the second from
1531    SECONDARY_RELOAD_CLASS, but not both.
1532
1533    We got into problems in the first place by allowing a construct like
1534    (subreg:XF (reg:TI)), which we got from a union containing a long double.
1535    This solution attempts to prevent this situation from occurring.  When
1536    we see something like the above, we spill the inner register to memory.  */
1537
1538 static rtx
1539 spill_xfmode_rfmode_operand (rtx in, int force, enum machine_mode mode)
1540 {
1541   if (GET_CODE (in) == SUBREG
1542       && GET_MODE (SUBREG_REG (in)) == TImode
1543       && GET_CODE (SUBREG_REG (in)) == REG)
1544     {
1545       rtx memt = assign_stack_temp (TImode, 16, 0);
1546       emit_move_insn (memt, SUBREG_REG (in));
1547       return adjust_address (memt, mode, 0);
1548     }
1549   else if (force && GET_CODE (in) == REG)
1550     {
1551       rtx memx = assign_stack_temp (mode, 16, 0);
1552       emit_move_insn (memx, in);
1553       return memx;
1554     }
1555   else
1556     return in;
1557 }
1558
1559 /* Expand the movxf or movrf pattern (MODE says which) with the given
1560    OPERANDS, returning true if the pattern should then invoke
1561    DONE.  */
1562
1563 bool
1564 ia64_expand_movxf_movrf (enum machine_mode mode, rtx operands[])
1565 {
1566   rtx op0 = operands[0];
1567
1568   if (GET_CODE (op0) == SUBREG)
1569     op0 = SUBREG_REG (op0);
1570
1571   /* We must support XFmode loads into general registers for stdarg/vararg,
1572      unprototyped calls, and a rare case where a long double is passed as
1573      an argument after a float HFA fills the FP registers.  We split them into
1574      DImode loads for convenience.  We also need to support XFmode stores
1575      for the last case.  This case does not happen for stdarg/vararg routines,
1576      because we do a block store to memory of unnamed arguments.  */
1577
1578   if (GET_CODE (op0) == REG && GR_REGNO_P (REGNO (op0)))
1579     {
1580       rtx out[2];
1581
1582       /* We're hoping to transform everything that deals with XFmode
1583          quantities and GR registers early in the compiler.  */
1584       gcc_assert (can_create_pseudo_p ());
1585
1586       /* Struct to register can just use TImode instead.  */
1587       if ((GET_CODE (operands[1]) == SUBREG
1588            && GET_MODE (SUBREG_REG (operands[1])) == TImode)
1589           || (GET_CODE (operands[1]) == REG
1590               && GR_REGNO_P (REGNO (operands[1]))))
1591         {
1592           rtx op1 = operands[1];
1593
1594           if (GET_CODE (op1) == SUBREG)
1595             op1 = SUBREG_REG (op1);
1596           else
1597             op1 = gen_rtx_REG (TImode, REGNO (op1));
1598
1599           emit_move_insn (gen_rtx_REG (TImode, REGNO (op0)), op1);
1600           return true;
1601         }
1602
1603       if (GET_CODE (operands[1]) == CONST_DOUBLE)
1604         {
1605           /* Don't word-swap when reading in the constant.  */
1606           emit_move_insn (gen_rtx_REG (DImode, REGNO (op0)),
1607                           operand_subword (operands[1], WORDS_BIG_ENDIAN,
1608                                            0, mode));
1609           emit_move_insn (gen_rtx_REG (DImode, REGNO (op0) + 1),
1610                           operand_subword (operands[1], !WORDS_BIG_ENDIAN,
1611                                            0, mode));
1612           return true;
1613         }
1614
1615       /* If the quantity is in a register not known to be GR, spill it.  */
1616       if (register_operand (operands[1], mode))
1617         operands[1] = spill_xfmode_rfmode_operand (operands[1], 1, mode);
1618
1619       gcc_assert (GET_CODE (operands[1]) == MEM);
1620
1621       /* Don't word-swap when reading in the value.  */
1622       out[0] = gen_rtx_REG (DImode, REGNO (op0));
1623       out[1] = gen_rtx_REG (DImode, REGNO (op0) + 1);
1624
1625       emit_move_insn (out[0], adjust_address (operands[1], DImode, 0));
1626       emit_move_insn (out[1], adjust_address (operands[1], DImode, 8));
1627       return true;
1628     }
1629
1630   if (GET_CODE (operands[1]) == REG && GR_REGNO_P (REGNO (operands[1])))
1631     {
1632       /* We're hoping to transform everything that deals with XFmode
1633          quantities and GR registers early in the compiler.  */
1634       gcc_assert (can_create_pseudo_p ());
1635
1636       /* Op0 can't be a GR_REG here, as that case is handled above.
1637          If op0 is a register, then we spill op1, so that we now have a
1638          MEM operand.  This requires creating an XFmode subreg of a TImode reg
1639          to force the spill.  */
1640       if (register_operand (operands[0], mode))
1641         {
1642           rtx op1 = gen_rtx_REG (TImode, REGNO (operands[1]));
1643           op1 = gen_rtx_SUBREG (mode, op1, 0);
1644           operands[1] = spill_xfmode_rfmode_operand (op1, 0, mode);
1645         }
1646
1647       else
1648         {
1649           rtx in[2];
1650
1651           gcc_assert (GET_CODE (operands[0]) == MEM);
1652
1653           /* Don't word-swap when writing out the value.  */
1654           in[0] = gen_rtx_REG (DImode, REGNO (operands[1]));
1655           in[1] = gen_rtx_REG (DImode, REGNO (operands[1]) + 1);
1656
1657           emit_move_insn (adjust_address (operands[0], DImode, 0), in[0]);
1658           emit_move_insn (adjust_address (operands[0], DImode, 8), in[1]);
1659           return true;
1660         }
1661     }
1662
1663   if (!reload_in_progress && !reload_completed)
1664     {
1665       operands[1] = spill_xfmode_rfmode_operand (operands[1], 0, mode);
1666
1667       if (GET_MODE (op0) == TImode && GET_CODE (op0) == REG)
1668         {
1669           rtx memt, memx, in = operands[1];
1670           if (CONSTANT_P (in))
1671             in = validize_mem (force_const_mem (mode, in));
1672           if (GET_CODE (in) == MEM)
1673             memt = adjust_address (in, TImode, 0);
1674           else
1675             {
1676               memt = assign_stack_temp (TImode, 16, 0);
1677               memx = adjust_address (memt, mode, 0);
1678               emit_move_insn (memx, in);
1679             }
1680           emit_move_insn (op0, memt);
1681           return true;
1682         }
1683
1684       if (!ia64_move_ok (operands[0], operands[1]))
1685         operands[1] = force_reg (mode, operands[1]);
1686     }
1687
1688   return false;
1689 }
1690
1691 /* Emit comparison instruction if necessary, replacing *EXPR, *OP0, *OP1
1692    with the expression that holds the compare result (in VOIDmode).  */
1693
1694 static GTY(()) rtx cmptf_libfunc;
1695
1696 void
1697 ia64_expand_compare (rtx *expr, rtx *op0, rtx *op1)
1698 {
1699   enum rtx_code code = GET_CODE (*expr);
1700   rtx cmp;
1701
1702   /* If we have a BImode input, then we already have a compare result, and
1703      do not need to emit another comparison.  */
1704   if (GET_MODE (*op0) == BImode)
1705     {
1706       gcc_assert ((code == NE || code == EQ) && *op1 == const0_rtx);
1707       cmp = *op0;
1708     }
1709   /* HPUX TFmode compare requires a library call to _U_Qfcmp, which takes a
1710      magic number as its third argument, that indicates what to do.
1711      The return value is an integer to be compared against zero.  */
1712   else if (TARGET_HPUX && GET_MODE (*op0) == TFmode)
1713     {
1714       enum qfcmp_magic {
1715         QCMP_INV = 1,   /* Raise FP_INVALID on SNaN as a side effect.  */
1716         QCMP_UNORD = 2,
1717         QCMP_EQ = 4,
1718         QCMP_LT = 8,
1719         QCMP_GT = 16
1720       };
1721       int magic;
1722       enum rtx_code ncode;
1723       rtx ret, insns;
1724       
1725       gcc_assert (cmptf_libfunc && GET_MODE (*op1) == TFmode);
1726       switch (code)
1727         {
1728           /* 1 = equal, 0 = not equal.  Equality operators do
1729              not raise FP_INVALID when given an SNaN operand.  */
1730         case EQ:        magic = QCMP_EQ;                  ncode = NE; break;
1731         case NE:        magic = QCMP_EQ;                  ncode = EQ; break;
1732           /* isunordered() from C99.  */
1733         case UNORDERED: magic = QCMP_UNORD;               ncode = NE; break;
1734         case ORDERED:   magic = QCMP_UNORD;               ncode = EQ; break;
1735           /* Relational operators raise FP_INVALID when given
1736              an SNaN operand.  */
1737         case LT:        magic = QCMP_LT        |QCMP_INV; ncode = NE; break;
1738         case LE:        magic = QCMP_LT|QCMP_EQ|QCMP_INV; ncode = NE; break;
1739         case GT:        magic = QCMP_GT        |QCMP_INV; ncode = NE; break;
1740         case GE:        magic = QCMP_GT|QCMP_EQ|QCMP_INV; ncode = NE; break;
1741           /* FUTURE: Implement UNEQ, UNLT, UNLE, UNGT, UNGE, LTGT.
1742              Expanders for buneq etc. weuld have to be added to ia64.md
1743              for this to be useful.  */
1744         default: gcc_unreachable ();
1745         }
1746
1747       start_sequence ();
1748
1749       ret = emit_library_call_value (cmptf_libfunc, 0, LCT_CONST, DImode, 3,
1750                                      *op0, TFmode, *op1, TFmode,
1751                                      GEN_INT (magic), DImode);
1752       cmp = gen_reg_rtx (BImode);
1753       emit_insn (gen_rtx_SET (VOIDmode, cmp,
1754                               gen_rtx_fmt_ee (ncode, BImode,
1755                                               ret, const0_rtx)));
1756
1757       insns = get_insns ();
1758       end_sequence ();
1759
1760       emit_libcall_block (insns, cmp, cmp,
1761                           gen_rtx_fmt_ee (code, BImode, *op0, *op1));
1762       code = NE;
1763     }
1764   else
1765     {
1766       cmp = gen_reg_rtx (BImode);
1767       emit_insn (gen_rtx_SET (VOIDmode, cmp,
1768                               gen_rtx_fmt_ee (code, BImode, *op0, *op1)));
1769       code = NE;
1770     }
1771
1772   *expr = gen_rtx_fmt_ee (code, VOIDmode, cmp, const0_rtx);
1773   *op0 = cmp;
1774   *op1 = const0_rtx;
1775 }
1776
1777 /* Generate an integral vector comparison.  Return true if the condition has
1778    been reversed, and so the sense of the comparison should be inverted.  */
1779
1780 static bool
1781 ia64_expand_vecint_compare (enum rtx_code code, enum machine_mode mode,
1782                             rtx dest, rtx op0, rtx op1)
1783 {
1784   bool negate = false;
1785   rtx x;
1786
1787   /* Canonicalize the comparison to EQ, GT, GTU.  */
1788   switch (code)
1789     {
1790     case EQ:
1791     case GT:
1792     case GTU:
1793       break;
1794
1795     case NE:
1796     case LE:
1797     case LEU:
1798       code = reverse_condition (code);
1799       negate = true;
1800       break;
1801
1802     case GE:
1803     case GEU:
1804       code = reverse_condition (code);
1805       negate = true;
1806       /* FALLTHRU */
1807
1808     case LT:
1809     case LTU:
1810       code = swap_condition (code);
1811       x = op0, op0 = op1, op1 = x;
1812       break;
1813
1814     default:
1815       gcc_unreachable ();
1816     }
1817
1818   /* Unsigned parallel compare is not supported by the hardware.  Play some
1819      tricks to turn this into a signed comparison against 0.  */
1820   if (code == GTU)
1821     {
1822       switch (mode)
1823         {
1824         case V2SImode:
1825           {
1826             rtx t1, t2, mask;
1827
1828             /* Subtract (-(INT MAX) - 1) from both operands to make
1829                them signed.  */
1830             mask = GEN_INT (0x80000000);
1831             mask = gen_rtx_CONST_VECTOR (V2SImode, gen_rtvec (2, mask, mask));
1832             mask = force_reg (mode, mask);
1833             t1 = gen_reg_rtx (mode);
1834             emit_insn (gen_subv2si3 (t1, op0, mask));
1835             t2 = gen_reg_rtx (mode);
1836             emit_insn (gen_subv2si3 (t2, op1, mask));
1837             op0 = t1;
1838             op1 = t2;
1839             code = GT;
1840           }
1841           break;
1842
1843         case V8QImode:
1844         case V4HImode:
1845           /* Perform a parallel unsigned saturating subtraction.  */
1846           x = gen_reg_rtx (mode);
1847           emit_insn (gen_rtx_SET (VOIDmode, x,
1848                                   gen_rtx_US_MINUS (mode, op0, op1)));
1849
1850           code = EQ;
1851           op0 = x;
1852           op1 = CONST0_RTX (mode);
1853           negate = !negate;
1854           break;
1855
1856         default:
1857           gcc_unreachable ();
1858         }
1859     }
1860
1861   x = gen_rtx_fmt_ee (code, mode, op0, op1);
1862   emit_insn (gen_rtx_SET (VOIDmode, dest, x));
1863
1864   return negate;
1865 }
1866
1867 /* Emit an integral vector conditional move.  */
1868
1869 void
1870 ia64_expand_vecint_cmov (rtx operands[])
1871 {
1872   enum machine_mode mode = GET_MODE (operands[0]);
1873   enum rtx_code code = GET_CODE (operands[3]);
1874   bool negate;
1875   rtx cmp, x, ot, of;
1876
1877   cmp = gen_reg_rtx (mode);
1878   negate = ia64_expand_vecint_compare (code, mode, cmp,
1879                                        operands[4], operands[5]);
1880
1881   ot = operands[1+negate];
1882   of = operands[2-negate];
1883
1884   if (ot == CONST0_RTX (mode))
1885     {
1886       if (of == CONST0_RTX (mode))
1887         {
1888           emit_move_insn (operands[0], ot);
1889           return;
1890         }
1891
1892       x = gen_rtx_NOT (mode, cmp);
1893       x = gen_rtx_AND (mode, x, of);
1894       emit_insn (gen_rtx_SET (VOIDmode, operands[0], x));
1895     }
1896   else if (of == CONST0_RTX (mode))
1897     {
1898       x = gen_rtx_AND (mode, cmp, ot);
1899       emit_insn (gen_rtx_SET (VOIDmode, operands[0], x));
1900     }
1901   else
1902     {
1903       rtx t, f;
1904
1905       t = gen_reg_rtx (mode);
1906       x = gen_rtx_AND (mode, cmp, operands[1+negate]);
1907       emit_insn (gen_rtx_SET (VOIDmode, t, x));
1908
1909       f = gen_reg_rtx (mode);
1910       x = gen_rtx_NOT (mode, cmp);
1911       x = gen_rtx_AND (mode, x, operands[2-negate]);
1912       emit_insn (gen_rtx_SET (VOIDmode, f, x));
1913
1914       x = gen_rtx_IOR (mode, t, f);
1915       emit_insn (gen_rtx_SET (VOIDmode, operands[0], x));
1916     }
1917 }
1918
1919 /* Emit an integral vector min or max operation.  Return true if all done.  */
1920
1921 bool
1922 ia64_expand_vecint_minmax (enum rtx_code code, enum machine_mode mode,
1923                            rtx operands[])
1924 {
1925   rtx xops[6];
1926
1927   /* These four combinations are supported directly.  */
1928   if (mode == V8QImode && (code == UMIN || code == UMAX))
1929     return false;
1930   if (mode == V4HImode && (code == SMIN || code == SMAX))
1931     return false;
1932
1933   /* This combination can be implemented with only saturating subtraction.  */
1934   if (mode == V4HImode && code == UMAX)
1935     {
1936       rtx x, tmp = gen_reg_rtx (mode);
1937
1938       x = gen_rtx_US_MINUS (mode, operands[1], operands[2]);
1939       emit_insn (gen_rtx_SET (VOIDmode, tmp, x));
1940
1941       emit_insn (gen_addv4hi3 (operands[0], tmp, operands[2]));
1942       return true;
1943     }
1944
1945   /* Everything else implemented via vector comparisons.  */
1946   xops[0] = operands[0];
1947   xops[4] = xops[1] = operands[1];
1948   xops[5] = xops[2] = operands[2];
1949
1950   switch (code)
1951     {
1952     case UMIN:
1953       code = LTU;
1954       break;
1955     case UMAX:
1956       code = GTU;
1957       break;
1958     case SMIN:
1959       code = LT;
1960       break;
1961     case SMAX:
1962       code = GT;
1963       break;
1964     default:
1965       gcc_unreachable ();
1966     }
1967   xops[3] = gen_rtx_fmt_ee (code, VOIDmode, operands[1], operands[2]);
1968
1969   ia64_expand_vecint_cmov (xops);
1970   return true;
1971 }
1972
1973 /* Emit an integral vector widening sum operations.  */
1974
1975 void
1976 ia64_expand_widen_sum (rtx operands[3], bool unsignedp)
1977 {
1978   rtx l, h, x, s;
1979   enum machine_mode wmode, mode;
1980   rtx (*unpack_l) (rtx, rtx, rtx);
1981   rtx (*unpack_h) (rtx, rtx, rtx);
1982   rtx (*plus) (rtx, rtx, rtx);
1983
1984   wmode = GET_MODE (operands[0]);
1985   mode = GET_MODE (operands[1]);
1986
1987   switch (mode)
1988     {
1989     case V8QImode:
1990       unpack_l = gen_unpack1_l;
1991       unpack_h = gen_unpack1_h;
1992       plus = gen_addv4hi3;
1993       break;
1994     case V4HImode:
1995       unpack_l = gen_unpack2_l;
1996       unpack_h = gen_unpack2_h;
1997       plus = gen_addv2si3;
1998       break;
1999     default:
2000       gcc_unreachable ();
2001     }
2002
2003   /* Fill in x with the sign extension of each element in op1.  */
2004   if (unsignedp)
2005     x = CONST0_RTX (mode);
2006   else
2007     {
2008       bool neg;
2009
2010       x = gen_reg_rtx (mode);
2011
2012       neg = ia64_expand_vecint_compare (LT, mode, x, operands[1],
2013                                         CONST0_RTX (mode));
2014       gcc_assert (!neg);
2015     }
2016
2017   l = gen_reg_rtx (wmode);
2018   h = gen_reg_rtx (wmode);
2019   s = gen_reg_rtx (wmode);
2020
2021   emit_insn (unpack_l (gen_lowpart (mode, l), operands[1], x));
2022   emit_insn (unpack_h (gen_lowpart (mode, h), operands[1], x));
2023   emit_insn (plus (s, l, operands[2]));
2024   emit_insn (plus (operands[0], h, s));
2025 }
2026
2027 /* Emit a signed or unsigned V8QI dot product operation.  */
2028
2029 void
2030 ia64_expand_dot_prod_v8qi (rtx operands[4], bool unsignedp)
2031 {
2032   rtx l1, l2, h1, h2, x1, x2, p1, p2, p3, p4, s1, s2, s3;
2033
2034   /* Fill in x1 and x2 with the sign extension of each element.  */
2035   if (unsignedp)
2036     x1 = x2 = CONST0_RTX (V8QImode);
2037   else
2038     {
2039       bool neg;
2040
2041       x1 = gen_reg_rtx (V8QImode);
2042       x2 = gen_reg_rtx (V8QImode);
2043
2044       neg = ia64_expand_vecint_compare (LT, V8QImode, x1, operands[1],
2045                                         CONST0_RTX (V8QImode));
2046       gcc_assert (!neg);
2047       neg = ia64_expand_vecint_compare (LT, V8QImode, x2, operands[2],
2048                                         CONST0_RTX (V8QImode));
2049       gcc_assert (!neg);
2050     }
2051
2052   l1 = gen_reg_rtx (V4HImode);
2053   l2 = gen_reg_rtx (V4HImode);
2054   h1 = gen_reg_rtx (V4HImode);
2055   h2 = gen_reg_rtx (V4HImode);
2056
2057   emit_insn (gen_unpack1_l (gen_lowpart (V8QImode, l1), operands[1], x1));
2058   emit_insn (gen_unpack1_l (gen_lowpart (V8QImode, l2), operands[2], x2));
2059   emit_insn (gen_unpack1_h (gen_lowpart (V8QImode, h1), operands[1], x1));
2060   emit_insn (gen_unpack1_h (gen_lowpart (V8QImode, h2), operands[2], x2));
2061
2062   p1 = gen_reg_rtx (V2SImode);
2063   p2 = gen_reg_rtx (V2SImode);
2064   p3 = gen_reg_rtx (V2SImode);
2065   p4 = gen_reg_rtx (V2SImode);
2066   emit_insn (gen_pmpy2_r (p1, l1, l2));
2067   emit_insn (gen_pmpy2_l (p2, l1, l2));
2068   emit_insn (gen_pmpy2_r (p3, h1, h2));
2069   emit_insn (gen_pmpy2_l (p4, h1, h2));
2070
2071   s1 = gen_reg_rtx (V2SImode);
2072   s2 = gen_reg_rtx (V2SImode);
2073   s3 = gen_reg_rtx (V2SImode);
2074   emit_insn (gen_addv2si3 (s1, p1, p2));
2075   emit_insn (gen_addv2si3 (s2, p3, p4));
2076   emit_insn (gen_addv2si3 (s3, s1, operands[3]));
2077   emit_insn (gen_addv2si3 (operands[0], s2, s3));
2078 }
2079
2080 /* Emit the appropriate sequence for a call.  */
2081
2082 void
2083 ia64_expand_call (rtx retval, rtx addr, rtx nextarg ATTRIBUTE_UNUSED,
2084                   int sibcall_p)
2085 {
2086   rtx insn, b0;
2087
2088   addr = XEXP (addr, 0);
2089   addr = convert_memory_address (DImode, addr);
2090   b0 = gen_rtx_REG (DImode, R_BR (0));
2091
2092   /* ??? Should do this for functions known to bind local too.  */
2093   if (TARGET_NO_PIC || TARGET_AUTO_PIC)
2094     {
2095       if (sibcall_p)
2096         insn = gen_sibcall_nogp (addr);
2097       else if (! retval)
2098         insn = gen_call_nogp (addr, b0);
2099       else
2100         insn = gen_call_value_nogp (retval, addr, b0);
2101       insn = emit_call_insn (insn);
2102     }
2103   else
2104     {
2105       if (sibcall_p)
2106         insn = gen_sibcall_gp (addr);
2107       else if (! retval)
2108         insn = gen_call_gp (addr, b0);
2109       else
2110         insn = gen_call_value_gp (retval, addr, b0);
2111       insn = emit_call_insn (insn);
2112
2113       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), pic_offset_table_rtx);
2114     }
2115
2116   if (sibcall_p)
2117     use_reg (&CALL_INSN_FUNCTION_USAGE (insn), b0);
2118
2119   if (TARGET_ABI_OPEN_VMS)
2120     use_reg (&CALL_INSN_FUNCTION_USAGE (insn),
2121              gen_rtx_REG (DImode, GR_REG (25)));
2122 }
2123
2124 static void
2125 reg_emitted (enum ia64_frame_regs r)
2126 {
2127   if (emitted_frame_related_regs[r] == 0)
2128     emitted_frame_related_regs[r] = current_frame_info.r[r];
2129   else
2130     gcc_assert (emitted_frame_related_regs[r] == current_frame_info.r[r]);
2131 }
2132
2133 static int
2134 get_reg (enum ia64_frame_regs r)
2135 {
2136   reg_emitted (r);
2137   return current_frame_info.r[r];
2138 }
2139
2140 static bool
2141 is_emitted (int regno)
2142 {
2143   unsigned int r;
2144
2145   for (r = reg_fp; r < number_of_ia64_frame_regs; r++)
2146     if (emitted_frame_related_regs[r] == regno)
2147       return true;
2148   return false;
2149 }
2150
2151 void
2152 ia64_reload_gp (void)
2153 {
2154   rtx tmp;
2155
2156   if (current_frame_info.r[reg_save_gp])
2157     {
2158       tmp = gen_rtx_REG (DImode, get_reg (reg_save_gp));
2159     }
2160   else
2161     {
2162       HOST_WIDE_INT offset;
2163       rtx offset_r;
2164
2165       offset = (current_frame_info.spill_cfa_off
2166                 + current_frame_info.spill_size);
2167       if (frame_pointer_needed)
2168         {
2169           tmp = hard_frame_pointer_rtx;
2170           offset = -offset;
2171         }
2172       else
2173         {
2174           tmp = stack_pointer_rtx;
2175           offset = current_frame_info.total_size - offset;
2176         }
2177
2178       offset_r = GEN_INT (offset);
2179       if (satisfies_constraint_I (offset_r))
2180         emit_insn (gen_adddi3 (pic_offset_table_rtx, tmp, offset_r));
2181       else
2182         {
2183           emit_move_insn (pic_offset_table_rtx, offset_r);
2184           emit_insn (gen_adddi3 (pic_offset_table_rtx,
2185                                  pic_offset_table_rtx, tmp));
2186         }
2187
2188       tmp = gen_rtx_MEM (DImode, pic_offset_table_rtx);
2189     }
2190
2191   emit_move_insn (pic_offset_table_rtx, tmp);
2192 }
2193
2194 void
2195 ia64_split_call (rtx retval, rtx addr, rtx retaddr, rtx scratch_r,
2196                  rtx scratch_b, int noreturn_p, int sibcall_p)
2197 {
2198   rtx insn;
2199   bool is_desc = false;
2200
2201   /* If we find we're calling through a register, then we're actually
2202      calling through a descriptor, so load up the values.  */
2203   if (REG_P (addr) && GR_REGNO_P (REGNO (addr)))
2204     {
2205       rtx tmp;
2206       bool addr_dead_p;
2207
2208       /* ??? We are currently constrained to *not* use peep2, because
2209          we can legitimately change the global lifetime of the GP
2210          (in the form of killing where previously live).  This is
2211          because a call through a descriptor doesn't use the previous
2212          value of the GP, while a direct call does, and we do not
2213          commit to either form until the split here.
2214
2215          That said, this means that we lack precise life info for
2216          whether ADDR is dead after this call.  This is not terribly
2217          important, since we can fix things up essentially for free
2218          with the POST_DEC below, but it's nice to not use it when we
2219          can immediately tell it's not necessary.  */
2220       addr_dead_p = ((noreturn_p || sibcall_p
2221                       || TEST_HARD_REG_BIT (regs_invalidated_by_call,
2222                                             REGNO (addr)))
2223                      && !FUNCTION_ARG_REGNO_P (REGNO (addr)));
2224
2225       /* Load the code address into scratch_b.  */
2226       tmp = gen_rtx_POST_INC (Pmode, addr);
2227       tmp = gen_rtx_MEM (Pmode, tmp);
2228       emit_move_insn (scratch_r, tmp);
2229       emit_move_insn (scratch_b, scratch_r);
2230
2231       /* Load the GP address.  If ADDR is not dead here, then we must
2232          revert the change made above via the POST_INCREMENT.  */
2233       if (!addr_dead_p)
2234         tmp = gen_rtx_POST_DEC (Pmode, addr);
2235       else
2236         tmp = addr;
2237       tmp = gen_rtx_MEM (Pmode, tmp);
2238       emit_move_insn (pic_offset_table_rtx, tmp);
2239
2240       is_desc = true;
2241       addr = scratch_b;
2242     }
2243
2244   if (sibcall_p)
2245     insn = gen_sibcall_nogp (addr);
2246   else if (retval)
2247     insn = gen_call_value_nogp (retval, addr, retaddr);
2248   else
2249     insn = gen_call_nogp (addr, retaddr);
2250   emit_call_insn (insn);
2251
2252   if ((!TARGET_CONST_GP || is_desc) && !noreturn_p && !sibcall_p)
2253     ia64_reload_gp ();
2254 }
2255
2256 /* Expand an atomic operation.  We want to perform MEM <CODE>= VAL atomically.
2257
2258    This differs from the generic code in that we know about the zero-extending
2259    properties of cmpxchg, and the zero-extending requirements of ar.ccv.  We
2260    also know that ld.acq+cmpxchg.rel equals a full barrier.
2261
2262    The loop we want to generate looks like
2263
2264         cmp_reg = mem;
2265       label:
2266         old_reg = cmp_reg;
2267         new_reg = cmp_reg op val;
2268         cmp_reg = compare-and-swap(mem, old_reg, new_reg)
2269         if (cmp_reg != old_reg)
2270           goto label;
2271
2272    Note that we only do the plain load from memory once.  Subsequent
2273    iterations use the value loaded by the compare-and-swap pattern.  */
2274
2275 void
2276 ia64_expand_atomic_op (enum rtx_code code, rtx mem, rtx val,
2277                        rtx old_dst, rtx new_dst)
2278 {
2279   enum machine_mode mode = GET_MODE (mem);
2280   rtx old_reg, new_reg, cmp_reg, ar_ccv, label;
2281   enum insn_code icode;
2282
2283   /* Special case for using fetchadd.  */
2284   if ((mode == SImode || mode == DImode)
2285       && (code == PLUS || code == MINUS)
2286       && fetchadd_operand (val, mode))
2287     {
2288       if (code == MINUS)
2289         val = GEN_INT (-INTVAL (val));
2290
2291       if (!old_dst)
2292         old_dst = gen_reg_rtx (mode);
2293
2294       emit_insn (gen_memory_barrier ());
2295
2296       if (mode == SImode)
2297         icode = CODE_FOR_fetchadd_acq_si;
2298       else
2299         icode = CODE_FOR_fetchadd_acq_di;
2300       emit_insn (GEN_FCN (icode) (old_dst, mem, val));
2301
2302       if (new_dst)
2303         {
2304           new_reg = expand_simple_binop (mode, PLUS, old_dst, val, new_dst,
2305                                          true, OPTAB_WIDEN);
2306           if (new_reg != new_dst)
2307             emit_move_insn (new_dst, new_reg);
2308         }
2309       return;
2310     }
2311
2312   /* Because of the volatile mem read, we get an ld.acq, which is the
2313      front half of the full barrier.  The end half is the cmpxchg.rel.  */
2314   gcc_assert (MEM_VOLATILE_P (mem));
2315
2316   old_reg = gen_reg_rtx (DImode);
2317   cmp_reg = gen_reg_rtx (DImode);
2318   label = gen_label_rtx ();
2319
2320   if (mode != DImode)
2321     {
2322       val = simplify_gen_subreg (DImode, val, mode, 0);
2323       emit_insn (gen_extend_insn (cmp_reg, mem, DImode, mode, 1));
2324     }
2325   else
2326     emit_move_insn (cmp_reg, mem);
2327
2328   emit_label (label);
2329
2330   ar_ccv = gen_rtx_REG (DImode, AR_CCV_REGNUM);
2331   emit_move_insn (old_reg, cmp_reg);
2332   emit_move_insn (ar_ccv, cmp_reg);
2333
2334   if (old_dst)
2335     emit_move_insn (old_dst, gen_lowpart (mode, cmp_reg));
2336
2337   new_reg = cmp_reg;
2338   if (code == NOT)
2339     {
2340       new_reg = expand_simple_binop (DImode, AND, new_reg, val, NULL_RTX,
2341                                      true, OPTAB_DIRECT);
2342       new_reg = expand_simple_unop (DImode, code, new_reg, NULL_RTX, true);
2343     }
2344   else
2345     new_reg = expand_simple_binop (DImode, code, new_reg, val, NULL_RTX,
2346                                    true, OPTAB_DIRECT);
2347
2348   if (mode != DImode)
2349     new_reg = gen_lowpart (mode, new_reg);
2350   if (new_dst)
2351     emit_move_insn (new_dst, new_reg);
2352
2353   switch (mode)
2354     {
2355     case QImode:  icode = CODE_FOR_cmpxchg_rel_qi;  break;
2356     case HImode:  icode = CODE_FOR_cmpxchg_rel_hi;  break;
2357     case SImode:  icode = CODE_FOR_cmpxchg_rel_si;  break;
2358     case DImode:  icode = CODE_FOR_cmpxchg_rel_di;  break;
2359     default:
2360       gcc_unreachable ();
2361     }
2362
2363   emit_insn (GEN_FCN (icode) (cmp_reg, mem, ar_ccv, new_reg));
2364
2365   emit_cmp_and_jump_insns (cmp_reg, old_reg, NE, NULL, DImode, true, label);
2366 }
2367 \f
2368 /* Begin the assembly file.  */
2369
2370 static void
2371 ia64_file_start (void)
2372 {
2373   /* Variable tracking should be run after all optimizations which change order
2374      of insns.  It also needs a valid CFG.  This can't be done in
2375      ia64_option_override, because flag_var_tracking is finalized after
2376      that.  */
2377   ia64_flag_var_tracking = flag_var_tracking;
2378   flag_var_tracking = 0;
2379
2380   default_file_start ();
2381   emit_safe_across_calls ();
2382 }
2383
2384 void
2385 emit_safe_across_calls (void)
2386 {
2387   unsigned int rs, re;
2388   int out_state;
2389
2390   rs = 1;
2391   out_state = 0;
2392   while (1)
2393     {
2394       while (rs < 64 && call_used_regs[PR_REG (rs)])
2395         rs++;
2396       if (rs >= 64)
2397         break;
2398       for (re = rs + 1; re < 64 && ! call_used_regs[PR_REG (re)]; re++)
2399         continue;
2400       if (out_state == 0)
2401         {
2402           fputs ("\t.pred.safe_across_calls ", asm_out_file);
2403           out_state = 1;
2404         }
2405       else
2406         fputc (',', asm_out_file);
2407       if (re == rs + 1)
2408         fprintf (asm_out_file, "p%u", rs);
2409       else
2410         fprintf (asm_out_file, "p%u-p%u", rs, re - 1);
2411       rs = re + 1;
2412     }
2413   if (out_state)
2414     fputc ('\n', asm_out_file);
2415 }
2416
2417 /* Globalize a declaration.  */
2418
2419 static void
2420 ia64_globalize_decl_name (FILE * stream, tree decl)
2421 {
2422   const char *name = XSTR (XEXP (DECL_RTL (decl), 0), 0);
2423   tree version_attr = lookup_attribute ("version_id", DECL_ATTRIBUTES (decl));
2424   if (version_attr)
2425     {
2426       tree v = TREE_VALUE (TREE_VALUE (version_attr));
2427       const char *p = TREE_STRING_POINTER (v);
2428       fprintf (stream, "\t.alias %s#, \"%s{%s}\"\n", name, name, p);
2429     }
2430   targetm.asm_out.globalize_label (stream, name);
2431   if (TREE_CODE (decl) == FUNCTION_DECL)
2432     ASM_OUTPUT_TYPE_DIRECTIVE (stream, name, "function");
2433 }
2434
2435 /* Helper function for ia64_compute_frame_size: find an appropriate general
2436    register to spill some special register to.  SPECIAL_SPILL_MASK contains
2437    bits in GR0 to GR31 that have already been allocated by this routine.
2438    TRY_LOCALS is true if we should attempt to locate a local regnum.  */
2439
2440 static int
2441 find_gr_spill (enum ia64_frame_regs r, int try_locals)
2442 {
2443   int regno;
2444
2445   if (emitted_frame_related_regs[r] != 0)
2446     {
2447       regno = emitted_frame_related_regs[r];
2448       if (regno >= LOC_REG (0) && regno < LOC_REG (80 - frame_pointer_needed)
2449           && current_frame_info.n_local_regs < regno - LOC_REG (0) + 1)
2450         current_frame_info.n_local_regs = regno - LOC_REG (0) + 1;
2451       else if (current_function_is_leaf 
2452                && regno >= GR_REG (1) && regno <= GR_REG (31))
2453         current_frame_info.gr_used_mask |= 1 << regno;
2454
2455       return regno;
2456     }
2457
2458   /* If this is a leaf function, first try an otherwise unused
2459      call-clobbered register.  */
2460   if (current_function_is_leaf)
2461     {
2462       for (regno = GR_REG (1); regno <= GR_REG (31); regno++)
2463         if (! df_regs_ever_live_p (regno)
2464             && call_used_regs[regno]
2465             && ! fixed_regs[regno]
2466             && ! global_regs[regno]
2467             && ((current_frame_info.gr_used_mask >> regno) & 1) == 0
2468             && ! is_emitted (regno))
2469           {
2470             current_frame_info.gr_used_mask |= 1 << regno;
2471             return regno;
2472           }
2473     }
2474
2475   if (try_locals)
2476     {
2477       regno = current_frame_info.n_local_regs;
2478       /* If there is a frame pointer, then we can't use loc79, because
2479          that is HARD_FRAME_POINTER_REGNUM.  In particular, see the
2480          reg_name switching code in ia64_expand_prologue.  */
2481       while (regno < (80 - frame_pointer_needed))
2482         if (! is_emitted (LOC_REG (regno++)))
2483           {
2484             current_frame_info.n_local_regs = regno;
2485             return LOC_REG (regno - 1);
2486           }
2487     }
2488
2489   /* Failed to find a general register to spill to.  Must use stack.  */
2490   return 0;
2491 }
2492
2493 /* In order to make for nice schedules, we try to allocate every temporary
2494    to a different register.  We must of course stay away from call-saved,
2495    fixed, and global registers.  We must also stay away from registers
2496    allocated in current_frame_info.gr_used_mask, since those include regs
2497    used all through the prologue.
2498
2499    Any register allocated here must be used immediately.  The idea is to
2500    aid scheduling, not to solve data flow problems.  */
2501
2502 static int last_scratch_gr_reg;
2503
2504 static int
2505 next_scratch_gr_reg (void)
2506 {
2507   int i, regno;
2508
2509   for (i = 0; i < 32; ++i)
2510     {
2511       regno = (last_scratch_gr_reg + i + 1) & 31;
2512       if (call_used_regs[regno]
2513           && ! fixed_regs[regno]
2514           && ! global_regs[regno]
2515           && ((current_frame_info.gr_used_mask >> regno) & 1) == 0)
2516         {
2517           last_scratch_gr_reg = regno;
2518           return regno;
2519         }
2520     }
2521
2522   /* There must be _something_ available.  */
2523   gcc_unreachable ();
2524 }
2525
2526 /* Helper function for ia64_compute_frame_size, called through
2527    diddle_return_value.  Mark REG in current_frame_info.gr_used_mask.  */
2528
2529 static void
2530 mark_reg_gr_used_mask (rtx reg, void *data ATTRIBUTE_UNUSED)
2531 {
2532   unsigned int regno = REGNO (reg);
2533   if (regno < 32)
2534     {
2535       unsigned int i, n = hard_regno_nregs[regno][GET_MODE (reg)];
2536       for (i = 0; i < n; ++i)
2537         current_frame_info.gr_used_mask |= 1 << (regno + i);
2538     }
2539 }
2540
2541
2542 /* Returns the number of bytes offset between the frame pointer and the stack
2543    pointer for the current function.  SIZE is the number of bytes of space
2544    needed for local variables.  */
2545
2546 static void
2547 ia64_compute_frame_size (HOST_WIDE_INT size)
2548 {
2549   HOST_WIDE_INT total_size;
2550   HOST_WIDE_INT spill_size = 0;
2551   HOST_WIDE_INT extra_spill_size = 0;
2552   HOST_WIDE_INT pretend_args_size;
2553   HARD_REG_SET mask;
2554   int n_spilled = 0;
2555   int spilled_gr_p = 0;
2556   int spilled_fr_p = 0;
2557   unsigned int regno;
2558   int min_regno;
2559   int max_regno;
2560   int i;
2561
2562   if (current_frame_info.initialized)
2563     return;
2564
2565   memset (&current_frame_info, 0, sizeof current_frame_info);
2566   CLEAR_HARD_REG_SET (mask);
2567
2568   /* Don't allocate scratches to the return register.  */
2569   diddle_return_value (mark_reg_gr_used_mask, NULL);
2570
2571   /* Don't allocate scratches to the EH scratch registers.  */
2572   if (cfun->machine->ia64_eh_epilogue_sp)
2573     mark_reg_gr_used_mask (cfun->machine->ia64_eh_epilogue_sp, NULL);
2574   if (cfun->machine->ia64_eh_epilogue_bsp)
2575     mark_reg_gr_used_mask (cfun->machine->ia64_eh_epilogue_bsp, NULL);
2576
2577   /* Find the size of the register stack frame.  We have only 80 local
2578      registers, because we reserve 8 for the inputs and 8 for the
2579      outputs.  */
2580
2581   /* Skip HARD_FRAME_POINTER_REGNUM (loc79) when frame_pointer_needed,
2582      since we'll be adjusting that down later.  */
2583   regno = LOC_REG (78) + ! frame_pointer_needed;
2584   for (; regno >= LOC_REG (0); regno--)
2585     if (df_regs_ever_live_p (regno) && !is_emitted (regno))
2586       break;
2587   current_frame_info.n_local_regs = regno - LOC_REG (0) + 1;
2588
2589   /* For functions marked with the syscall_linkage attribute, we must mark
2590      all eight input registers as in use, so that locals aren't visible to
2591      the caller.  */
2592
2593   if (cfun->machine->n_varargs > 0
2594       || lookup_attribute ("syscall_linkage",
2595                            TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))))
2596     current_frame_info.n_input_regs = 8;
2597   else
2598     {
2599       for (regno = IN_REG (7); regno >= IN_REG (0); regno--)
2600         if (df_regs_ever_live_p (regno))
2601           break;
2602       current_frame_info.n_input_regs = regno - IN_REG (0) + 1;
2603     }
2604
2605   for (regno = OUT_REG (7); regno >= OUT_REG (0); regno--)
2606     if (df_regs_ever_live_p (regno))
2607       break;
2608   i = regno - OUT_REG (0) + 1;
2609
2610 #ifndef PROFILE_HOOK
2611   /* When -p profiling, we need one output register for the mcount argument.
2612      Likewise for -a profiling for the bb_init_func argument.  For -ax
2613      profiling, we need two output registers for the two bb_init_trace_func
2614      arguments.  */
2615   if (crtl->profile)
2616     i = MAX (i, 1);
2617 #endif
2618   current_frame_info.n_output_regs = i;
2619
2620   /* ??? No rotating register support yet.  */
2621   current_frame_info.n_rotate_regs = 0;
2622
2623   /* Discover which registers need spilling, and how much room that
2624      will take.  Begin with floating point and general registers,
2625      which will always wind up on the stack.  */
2626
2627   for (regno = FR_REG (2); regno <= FR_REG (127); regno++)
2628     if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
2629       {
2630         SET_HARD_REG_BIT (mask, regno);
2631         spill_size += 16;
2632         n_spilled += 1;
2633         spilled_fr_p = 1;
2634       }
2635
2636   for (regno = GR_REG (1); regno <= GR_REG (31); regno++)
2637     if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
2638       {
2639         SET_HARD_REG_BIT (mask, regno);
2640         spill_size += 8;
2641         n_spilled += 1;
2642         spilled_gr_p = 1;
2643       }
2644
2645   for (regno = BR_REG (1); regno <= BR_REG (7); regno++)
2646     if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
2647       {
2648         SET_HARD_REG_BIT (mask, regno);
2649         spill_size += 8;
2650         n_spilled += 1;
2651       }
2652
2653   /* Now come all special registers that might get saved in other
2654      general registers.  */
2655
2656   if (frame_pointer_needed)
2657     {
2658       current_frame_info.r[reg_fp] = find_gr_spill (reg_fp, 1);
2659       /* If we did not get a register, then we take LOC79.  This is guaranteed
2660          to be free, even if regs_ever_live is already set, because this is
2661          HARD_FRAME_POINTER_REGNUM.  This requires incrementing n_local_regs,
2662          as we don't count loc79 above.  */
2663       if (current_frame_info.r[reg_fp] == 0)
2664         {
2665           current_frame_info.r[reg_fp] = LOC_REG (79);
2666           current_frame_info.n_local_regs = LOC_REG (79) - LOC_REG (0) + 1;
2667         }
2668     }
2669
2670   if (! current_function_is_leaf)
2671     {
2672       /* Emit a save of BR0 if we call other functions.  Do this even
2673          if this function doesn't return, as EH depends on this to be
2674          able to unwind the stack.  */
2675       SET_HARD_REG_BIT (mask, BR_REG (0));
2676
2677       current_frame_info.r[reg_save_b0] = find_gr_spill (reg_save_b0, 1);
2678       if (current_frame_info.r[reg_save_b0] == 0)
2679         {
2680           extra_spill_size += 8;
2681           n_spilled += 1;
2682         }
2683
2684       /* Similarly for ar.pfs.  */
2685       SET_HARD_REG_BIT (mask, AR_PFS_REGNUM);
2686       current_frame_info.r[reg_save_ar_pfs] = find_gr_spill (reg_save_ar_pfs, 1);
2687       if (current_frame_info.r[reg_save_ar_pfs] == 0)
2688         {
2689           extra_spill_size += 8;
2690           n_spilled += 1;
2691         }
2692
2693       /* Similarly for gp.  Note that if we're calling setjmp, the stacked
2694          registers are clobbered, so we fall back to the stack.  */
2695       current_frame_info.r[reg_save_gp]
2696         = (cfun->calls_setjmp ? 0 : find_gr_spill (reg_save_gp, 1));
2697       if (current_frame_info.r[reg_save_gp] == 0)
2698         {
2699           SET_HARD_REG_BIT (mask, GR_REG (1));
2700           spill_size += 8;
2701           n_spilled += 1;
2702         }
2703     }
2704   else
2705     {
2706       if (df_regs_ever_live_p (BR_REG (0)) && ! call_used_regs[BR_REG (0)])
2707         {
2708           SET_HARD_REG_BIT (mask, BR_REG (0));
2709           extra_spill_size += 8;
2710           n_spilled += 1;
2711         }
2712
2713       if (df_regs_ever_live_p (AR_PFS_REGNUM))
2714         {
2715           SET_HARD_REG_BIT (mask, AR_PFS_REGNUM);
2716           current_frame_info.r[reg_save_ar_pfs] 
2717             = find_gr_spill (reg_save_ar_pfs, 1);
2718           if (current_frame_info.r[reg_save_ar_pfs] == 0)
2719             {
2720               extra_spill_size += 8;
2721               n_spilled += 1;
2722             }
2723         }
2724     }
2725
2726   /* Unwind descriptor hackery: things are most efficient if we allocate
2727      consecutive GR save registers for RP, PFS, FP in that order. However,
2728      it is absolutely critical that FP get the only hard register that's
2729      guaranteed to be free, so we allocated it first.  If all three did
2730      happen to be allocated hard regs, and are consecutive, rearrange them
2731      into the preferred order now.  
2732      
2733      If we have already emitted code for any of those registers,
2734      then it's already too late to change.  */
2735   min_regno = MIN (current_frame_info.r[reg_fp],
2736                    MIN (current_frame_info.r[reg_save_b0],
2737                         current_frame_info.r[reg_save_ar_pfs]));
2738   max_regno = MAX (current_frame_info.r[reg_fp],
2739                    MAX (current_frame_info.r[reg_save_b0],
2740                         current_frame_info.r[reg_save_ar_pfs]));
2741   if (min_regno > 0
2742       && min_regno + 2 == max_regno
2743       && (current_frame_info.r[reg_fp] == min_regno + 1
2744           || current_frame_info.r[reg_save_b0] == min_regno + 1
2745           || current_frame_info.r[reg_save_ar_pfs] == min_regno + 1)
2746       && (emitted_frame_related_regs[reg_save_b0] == 0
2747           || emitted_frame_related_regs[reg_save_b0] == min_regno)
2748       && (emitted_frame_related_regs[reg_save_ar_pfs] == 0
2749           || emitted_frame_related_regs[reg_save_ar_pfs] == min_regno + 1)
2750       && (emitted_frame_related_regs[reg_fp] == 0
2751           || emitted_frame_related_regs[reg_fp] == min_regno + 2))
2752     {
2753       current_frame_info.r[reg_save_b0] = min_regno;
2754       current_frame_info.r[reg_save_ar_pfs] = min_regno + 1;
2755       current_frame_info.r[reg_fp] = min_regno + 2;
2756     }
2757
2758   /* See if we need to store the predicate register block.  */
2759   for (regno = PR_REG (0); regno <= PR_REG (63); regno++)
2760     if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
2761       break;
2762   if (regno <= PR_REG (63))
2763     {
2764       SET_HARD_REG_BIT (mask, PR_REG (0));
2765       current_frame_info.r[reg_save_pr] = find_gr_spill (reg_save_pr, 1);
2766       if (current_frame_info.r[reg_save_pr] == 0)
2767         {
2768           extra_spill_size += 8;
2769           n_spilled += 1;
2770         }
2771
2772       /* ??? Mark them all as used so that register renaming and such
2773          are free to use them.  */
2774       for (regno = PR_REG (0); regno <= PR_REG (63); regno++)
2775         df_set_regs_ever_live (regno, true);
2776     }
2777
2778   /* If we're forced to use st8.spill, we're forced to save and restore
2779      ar.unat as well.  The check for existing liveness allows inline asm
2780      to touch ar.unat.  */
2781   if (spilled_gr_p || cfun->machine->n_varargs
2782       || df_regs_ever_live_p (AR_UNAT_REGNUM))
2783     {
2784       df_set_regs_ever_live (AR_UNAT_REGNUM, true);
2785       SET_HARD_REG_BIT (mask, AR_UNAT_REGNUM);
2786       current_frame_info.r[reg_save_ar_unat] 
2787         = find_gr_spill (reg_save_ar_unat, spill_size == 0);
2788       if (current_frame_info.r[reg_save_ar_unat] == 0)
2789         {
2790           extra_spill_size += 8;
2791           n_spilled += 1;
2792         }
2793     }
2794
2795   if (df_regs_ever_live_p (AR_LC_REGNUM))
2796     {
2797       SET_HARD_REG_BIT (mask, AR_LC_REGNUM);
2798       current_frame_info.r[reg_save_ar_lc] 
2799         = find_gr_spill (reg_save_ar_lc, spill_size == 0);
2800       if (current_frame_info.r[reg_save_ar_lc] == 0)
2801         {
2802           extra_spill_size += 8;
2803           n_spilled += 1;
2804         }
2805     }
2806
2807   /* If we have an odd number of words of pretend arguments written to
2808      the stack, then the FR save area will be unaligned.  We round the
2809      size of this area up to keep things 16 byte aligned.  */
2810   if (spilled_fr_p)
2811     pretend_args_size = IA64_STACK_ALIGN (crtl->args.pretend_args_size);
2812   else
2813     pretend_args_size = crtl->args.pretend_args_size;
2814
2815   total_size = (spill_size + extra_spill_size + size + pretend_args_size
2816                 + crtl->outgoing_args_size);
2817   total_size = IA64_STACK_ALIGN (total_size);
2818
2819   /* We always use the 16-byte scratch area provided by the caller, but
2820      if we are a leaf function, there's no one to which we need to provide
2821      a scratch area.  */
2822   if (current_function_is_leaf)
2823     total_size = MAX (0, total_size - 16);
2824
2825   current_frame_info.total_size = total_size;
2826   current_frame_info.spill_cfa_off = pretend_args_size - 16;
2827   current_frame_info.spill_size = spill_size;
2828   current_frame_info.extra_spill_size = extra_spill_size;
2829   COPY_HARD_REG_SET (current_frame_info.mask, mask);
2830   current_frame_info.n_spilled = n_spilled;
2831   current_frame_info.initialized = reload_completed;
2832 }
2833
2834 /* Worker function for TARGET_CAN_ELIMINATE.  */
2835
2836 bool
2837 ia64_can_eliminate (const int from ATTRIBUTE_UNUSED, const int to)
2838 {
2839   return (to == BR_REG (0) ? current_function_is_leaf : true);
2840 }
2841
2842 /* Compute the initial difference between the specified pair of registers.  */
2843
2844 HOST_WIDE_INT
2845 ia64_initial_elimination_offset (int from, int to)
2846 {
2847   HOST_WIDE_INT offset;
2848
2849   ia64_compute_frame_size (get_frame_size ());
2850   switch (from)
2851     {
2852     case FRAME_POINTER_REGNUM:
2853       switch (to)
2854         {
2855         case HARD_FRAME_POINTER_REGNUM:
2856           if (current_function_is_leaf)
2857             offset = -current_frame_info.total_size;
2858           else
2859             offset = -(current_frame_info.total_size
2860                        - crtl->outgoing_args_size - 16);
2861           break;
2862
2863         case STACK_POINTER_REGNUM:
2864           if (current_function_is_leaf)
2865             offset = 0;
2866           else
2867             offset = 16 + crtl->outgoing_args_size;
2868           break;
2869
2870         default:
2871           gcc_unreachable ();
2872         }
2873       break;
2874
2875     case ARG_POINTER_REGNUM:
2876       /* Arguments start above the 16 byte save area, unless stdarg
2877          in which case we store through the 16 byte save area.  */
2878       switch (to)
2879         {
2880         case HARD_FRAME_POINTER_REGNUM:
2881           offset = 16 - crtl->args.pretend_args_size;
2882           break;
2883
2884         case STACK_POINTER_REGNUM:
2885           offset = (current_frame_info.total_size
2886                     + 16 - crtl->args.pretend_args_size);
2887           break;
2888
2889         default:
2890           gcc_unreachable ();
2891         }
2892       break;
2893
2894     default:
2895       gcc_unreachable ();
2896     }
2897
2898   return offset;
2899 }
2900
2901 /* If there are more than a trivial number of register spills, we use
2902    two interleaved iterators so that we can get two memory references
2903    per insn group.
2904
2905    In order to simplify things in the prologue and epilogue expanders,
2906    we use helper functions to fix up the memory references after the
2907    fact with the appropriate offsets to a POST_MODIFY memory mode.
2908    The following data structure tracks the state of the two iterators
2909    while insns are being emitted.  */
2910
2911 struct spill_fill_data
2912 {
2913   rtx init_after;               /* point at which to emit initializations */
2914   rtx init_reg[2];              /* initial base register */
2915   rtx iter_reg[2];              /* the iterator registers */
2916   rtx *prev_addr[2];            /* address of last memory use */
2917   rtx prev_insn[2];             /* the insn corresponding to prev_addr */
2918   HOST_WIDE_INT prev_off[2];    /* last offset */
2919   int n_iter;                   /* number of iterators in use */
2920   int next_iter;                /* next iterator to use */
2921   unsigned int save_gr_used_mask;
2922 };
2923
2924 static struct spill_fill_data spill_fill_data;
2925
2926 static void
2927 setup_spill_pointers (int n_spills, rtx init_reg, HOST_WIDE_INT cfa_off)
2928 {
2929   int i;
2930
2931   spill_fill_data.init_after = get_last_insn ();
2932   spill_fill_data.init_reg[0] = init_reg;
2933   spill_fill_data.init_reg[1] = init_reg;
2934   spill_fill_data.prev_addr[0] = NULL;
2935   spill_fill_data.prev_addr[1] = NULL;
2936   spill_fill_data.prev_insn[0] = NULL;
2937   spill_fill_data.prev_insn[1] = NULL;
2938   spill_fill_data.prev_off[0] = cfa_off;
2939   spill_fill_data.prev_off[1] = cfa_off;
2940   spill_fill_data.next_iter = 0;
2941   spill_fill_data.save_gr_used_mask = current_frame_info.gr_used_mask;
2942
2943   spill_fill_data.n_iter = 1 + (n_spills > 2);
2944   for (i = 0; i < spill_fill_data.n_iter; ++i)
2945     {
2946       int regno = next_scratch_gr_reg ();
2947       spill_fill_data.iter_reg[i] = gen_rtx_REG (DImode, regno);
2948       current_frame_info.gr_used_mask |= 1 << regno;
2949     }
2950 }
2951
2952 static void
2953 finish_spill_pointers (void)
2954 {
2955   current_frame_info.gr_used_mask = spill_fill_data.save_gr_used_mask;
2956 }
2957
2958 static rtx
2959 spill_restore_mem (rtx reg, HOST_WIDE_INT cfa_off)
2960 {
2961   int iter = spill_fill_data.next_iter;
2962   HOST_WIDE_INT disp = spill_fill_data.prev_off[iter] - cfa_off;
2963   rtx disp_rtx = GEN_INT (disp);
2964   rtx mem;
2965
2966   if (spill_fill_data.prev_addr[iter])
2967     {
2968       if (satisfies_constraint_N (disp_rtx))
2969         {
2970           *spill_fill_data.prev_addr[iter]
2971             = gen_rtx_POST_MODIFY (DImode, spill_fill_data.iter_reg[iter],
2972                                    gen_rtx_PLUS (DImode,
2973                                                  spill_fill_data.iter_reg[iter],
2974                                                  disp_rtx));
2975           add_reg_note (spill_fill_data.prev_insn[iter],
2976                         REG_INC, spill_fill_data.iter_reg[iter]);
2977         }
2978       else
2979         {
2980           /* ??? Could use register post_modify for loads.  */
2981           if (!satisfies_constraint_I (disp_rtx))
2982             {
2983               rtx tmp = gen_rtx_REG (DImode, next_scratch_gr_reg ());
2984               emit_move_insn (tmp, disp_rtx);
2985               disp_rtx = tmp;
2986             }
2987           emit_insn (gen_adddi3 (spill_fill_data.iter_reg[iter],
2988                                  spill_fill_data.iter_reg[iter], disp_rtx));
2989         }
2990     }
2991   /* Micro-optimization: if we've created a frame pointer, it's at
2992      CFA 0, which may allow the real iterator to be initialized lower,
2993      slightly increasing parallelism.  Also, if there are few saves
2994      it may eliminate the iterator entirely.  */
2995   else if (disp == 0
2996            && spill_fill_data.init_reg[iter] == stack_pointer_rtx
2997            && frame_pointer_needed)
2998     {
2999       mem = gen_rtx_MEM (GET_MODE (reg), hard_frame_pointer_rtx);
3000       set_mem_alias_set (mem, get_varargs_alias_set ());
3001       return mem;
3002     }
3003   else
3004     {
3005       rtx seq, insn;
3006
3007       if (disp == 0)
3008         seq = gen_movdi (spill_fill_data.iter_reg[iter],
3009                          spill_fill_data.init_reg[iter]);
3010       else
3011         {
3012           start_sequence ();
3013
3014           if (!satisfies_constraint_I (disp_rtx))
3015             {
3016               rtx tmp = gen_rtx_REG (DImode, next_scratch_gr_reg ());
3017               emit_move_insn (tmp, disp_rtx);
3018               disp_rtx = tmp;
3019             }
3020
3021           emit_insn (gen_adddi3 (spill_fill_data.iter_reg[iter],
3022                                  spill_fill_data.init_reg[iter],
3023                                  disp_rtx));
3024
3025           seq = get_insns ();
3026           end_sequence ();
3027         }
3028
3029       /* Careful for being the first insn in a sequence.  */
3030       if (spill_fill_data.init_after)
3031         insn = emit_insn_after (seq, spill_fill_data.init_after);
3032       else
3033         {
3034           rtx first = get_insns ();
3035           if (first)
3036             insn = emit_insn_before (seq, first);
3037           else
3038             insn = emit_insn (seq);
3039         }
3040       spill_fill_data.init_after = insn;
3041     }
3042
3043   mem = gen_rtx_MEM (GET_MODE (reg), spill_fill_data.iter_reg[iter]);
3044
3045   /* ??? Not all of the spills are for varargs, but some of them are.
3046      The rest of the spills belong in an alias set of their own.  But
3047      it doesn't actually hurt to include them here.  */
3048   set_mem_alias_set (mem, get_varargs_alias_set ());
3049
3050   spill_fill_data.prev_addr[iter] = &XEXP (mem, 0);
3051   spill_fill_data.prev_off[iter] = cfa_off;
3052
3053   if (++iter >= spill_fill_data.n_iter)
3054     iter = 0;
3055   spill_fill_data.next_iter = iter;
3056
3057   return mem;
3058 }
3059
3060 static void
3061 do_spill (rtx (*move_fn) (rtx, rtx, rtx), rtx reg, HOST_WIDE_INT cfa_off,
3062           rtx frame_reg)
3063 {
3064   int iter = spill_fill_data.next_iter;
3065   rtx mem, insn;
3066
3067   mem = spill_restore_mem (reg, cfa_off);
3068   insn = emit_insn ((*move_fn) (mem, reg, GEN_INT (cfa_off)));
3069   spill_fill_data.prev_insn[iter] = insn;
3070
3071   if (frame_reg)
3072     {
3073       rtx base;
3074       HOST_WIDE_INT off;
3075
3076       RTX_FRAME_RELATED_P (insn) = 1;
3077
3078       /* Don't even pretend that the unwind code can intuit its way
3079          through a pair of interleaved post_modify iterators.  Just
3080          provide the correct answer.  */
3081
3082       if (frame_pointer_needed)
3083         {
3084           base = hard_frame_pointer_rtx;
3085           off = - cfa_off;
3086         }
3087       else
3088         {
3089           base = stack_pointer_rtx;
3090           off = current_frame_info.total_size - cfa_off;
3091         }
3092
3093       add_reg_note (insn, REG_CFA_OFFSET,
3094                     gen_rtx_SET (VOIDmode,
3095                                  gen_rtx_MEM (GET_MODE (reg),
3096                                               plus_constant (base, off)),
3097                                  frame_reg));
3098     }
3099 }
3100
3101 static void
3102 do_restore (rtx (*move_fn) (rtx, rtx, rtx), rtx reg, HOST_WIDE_INT cfa_off)
3103 {
3104   int iter = spill_fill_data.next_iter;
3105   rtx insn;
3106
3107   insn = emit_insn ((*move_fn) (reg, spill_restore_mem (reg, cfa_off),
3108                                 GEN_INT (cfa_off)));
3109   spill_fill_data.prev_insn[iter] = insn;
3110 }
3111
3112 /* Wrapper functions that discards the CONST_INT spill offset.  These
3113    exist so that we can give gr_spill/gr_fill the offset they need and
3114    use a consistent function interface.  */
3115
3116 static rtx
3117 gen_movdi_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
3118 {
3119   return gen_movdi (dest, src);
3120 }
3121
3122 static rtx
3123 gen_fr_spill_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
3124 {
3125   return gen_fr_spill (dest, src);
3126 }
3127
3128 static rtx
3129 gen_fr_restore_x (rtx dest, rtx src, rtx offset ATTRIBUTE_UNUSED)
3130 {
3131   return gen_fr_restore (dest, src);
3132 }
3133
3134 /* Called after register allocation to add any instructions needed for the
3135    prologue.  Using a prologue insn is favored compared to putting all of the
3136    instructions in output_function_prologue(), since it allows the scheduler
3137    to intermix instructions with the saves of the caller saved registers.  In
3138    some cases, it might be necessary to emit a barrier instruction as the last
3139    insn to prevent such scheduling.
3140
3141    Also any insns generated here should have RTX_FRAME_RELATED_P(insn) = 1
3142    so that the debug info generation code can handle them properly.
3143
3144    The register save area is layed out like so:
3145    cfa+16
3146         [ varargs spill area ]
3147         [ fr register spill area ]
3148         [ br register spill area ]
3149         [ ar register spill area ]
3150         [ pr register spill area ]
3151         [ gr register spill area ] */
3152
3153 /* ??? Get inefficient code when the frame size is larger than can fit in an
3154    adds instruction.  */
3155
3156 void
3157 ia64_expand_prologue (void)
3158 {
3159   rtx insn, ar_pfs_save_reg, ar_unat_save_reg;
3160   int i, epilogue_p, regno, alt_regno, cfa_off, n_varargs;
3161   rtx reg, alt_reg;
3162
3163   ia64_compute_frame_size (get_frame_size ());
3164   last_scratch_gr_reg = 15;
3165
3166   if (flag_stack_usage)
3167     current_function_static_stack_size = current_frame_info.total_size;
3168
3169   if (dump_file) 
3170     {
3171       fprintf (dump_file, "ia64 frame related registers "
3172                "recorded in current_frame_info.r[]:\n");
3173 #define PRINTREG(a) if (current_frame_info.r[a]) \
3174         fprintf(dump_file, "%s = %d\n", #a, current_frame_info.r[a])
3175       PRINTREG(reg_fp);
3176       PRINTREG(reg_save_b0);
3177       PRINTREG(reg_save_pr);
3178       PRINTREG(reg_save_ar_pfs);
3179       PRINTREG(reg_save_ar_unat);
3180       PRINTREG(reg_save_ar_lc);
3181       PRINTREG(reg_save_gp);
3182 #undef PRINTREG
3183     }
3184
3185   /* If there is no epilogue, then we don't need some prologue insns.
3186      We need to avoid emitting the dead prologue insns, because flow
3187      will complain about them.  */
3188   if (optimize)
3189     {
3190       edge e;
3191       edge_iterator ei;
3192
3193       FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
3194         if ((e->flags & EDGE_FAKE) == 0
3195             && (e->flags & EDGE_FALLTHRU) != 0)
3196           break;
3197       epilogue_p = (e != NULL);
3198     }
3199   else
3200     epilogue_p = 1;
3201
3202   /* Set the local, input, and output register names.  We need to do this
3203      for GNU libc, which creates crti.S/crtn.S by splitting initfini.c in
3204      half.  If we use in/loc/out register names, then we get assembler errors
3205      in crtn.S because there is no alloc insn or regstk directive in there.  */
3206   if (! TARGET_REG_NAMES)
3207     {
3208       int inputs = current_frame_info.n_input_regs;
3209       int locals = current_frame_info.n_local_regs;
3210       int outputs = current_frame_info.n_output_regs;
3211
3212       for (i = 0; i < inputs; i++)
3213         reg_names[IN_REG (i)] = ia64_reg_numbers[i];
3214       for (i = 0; i < locals; i++)
3215         reg_names[LOC_REG (i)] = ia64_reg_numbers[inputs + i];
3216       for (i = 0; i < outputs; i++)
3217         reg_names[OUT_REG (i)] = ia64_reg_numbers[inputs + locals + i];
3218     }
3219
3220   /* Set the frame pointer register name.  The regnum is logically loc79,
3221      but of course we'll not have allocated that many locals.  Rather than
3222      worrying about renumbering the existing rtxs, we adjust the name.  */
3223   /* ??? This code means that we can never use one local register when
3224      there is a frame pointer.  loc79 gets wasted in this case, as it is
3225      renamed to a register that will never be used.  See also the try_locals
3226      code in find_gr_spill.  */
3227   if (current_frame_info.r[reg_fp])
3228     {
3229       const char *tmp = reg_names[HARD_FRAME_POINTER_REGNUM];
3230       reg_names[HARD_FRAME_POINTER_REGNUM]
3231         = reg_names[current_frame_info.r[reg_fp]];
3232       reg_names[current_frame_info.r[reg_fp]] = tmp;
3233     }
3234
3235   /* We don't need an alloc instruction if we've used no outputs or locals.  */
3236   if (current_frame_info.n_local_regs == 0
3237       && current_frame_info.n_output_regs == 0
3238       && current_frame_info.n_input_regs <= crtl->args.info.int_regs
3239       && !TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM))
3240     {
3241       /* If there is no alloc, but there are input registers used, then we
3242          need a .regstk directive.  */
3243       current_frame_info.need_regstk = (TARGET_REG_NAMES != 0);
3244       ar_pfs_save_reg = NULL_RTX;
3245     }
3246   else
3247     {
3248       current_frame_info.need_regstk = 0;
3249
3250       if (current_frame_info.r[reg_save_ar_pfs])
3251         {
3252           regno = current_frame_info.r[reg_save_ar_pfs];
3253           reg_emitted (reg_save_ar_pfs);
3254         }
3255       else
3256         regno = next_scratch_gr_reg ();
3257       ar_pfs_save_reg = gen_rtx_REG (DImode, regno);
3258
3259       insn = emit_insn (gen_alloc (ar_pfs_save_reg,
3260                                    GEN_INT (current_frame_info.n_input_regs),
3261                                    GEN_INT (current_frame_info.n_local_regs),
3262                                    GEN_INT (current_frame_info.n_output_regs),
3263                                    GEN_INT (current_frame_info.n_rotate_regs)));
3264       RTX_FRAME_RELATED_P (insn) = (current_frame_info.r[reg_save_ar_pfs] != 0);
3265     }
3266
3267   /* Set up frame pointer, stack pointer, and spill iterators.  */
3268
3269   n_varargs = cfun->machine->n_varargs;
3270   setup_spill_pointers (current_frame_info.n_spilled + n_varargs,
3271                         stack_pointer_rtx, 0);
3272
3273   if (frame_pointer_needed)
3274     {
3275       insn = emit_move_insn (hard_frame_pointer_rtx, stack_pointer_rtx);
3276       RTX_FRAME_RELATED_P (insn) = 1;
3277
3278       /* Force the unwind info to recognize this as defining a new CFA,
3279          rather than some temp register setup.  */
3280       add_reg_note (insn, REG_CFA_ADJUST_CFA, NULL_RTX);
3281     }
3282
3283   if (current_frame_info.total_size != 0)
3284     {
3285       rtx frame_size_rtx = GEN_INT (- current_frame_info.total_size);
3286       rtx offset;
3287
3288       if (satisfies_constraint_I (frame_size_rtx))
3289         offset = frame_size_rtx;
3290       else
3291         {
3292           regno = next_scratch_gr_reg ();
3293           offset = gen_rtx_REG (DImode, regno);
3294           emit_move_insn (offset, frame_size_rtx);
3295         }
3296
3297       insn = emit_insn (gen_adddi3 (stack_pointer_rtx,
3298                                     stack_pointer_rtx, offset));
3299
3300       if (! frame_pointer_needed)
3301         {
3302           RTX_FRAME_RELATED_P (insn) = 1;
3303           add_reg_note (insn, REG_CFA_ADJUST_CFA,
3304                         gen_rtx_SET (VOIDmode,
3305                                      stack_pointer_rtx,
3306                                      gen_rtx_PLUS (DImode,
3307                                                    stack_pointer_rtx,
3308                                                    frame_size_rtx)));
3309         }
3310
3311       /* ??? At this point we must generate a magic insn that appears to
3312          modify the stack pointer, the frame pointer, and all spill
3313          iterators.  This would allow the most scheduling freedom.  For
3314          now, just hard stop.  */
3315       emit_insn (gen_blockage ());
3316     }
3317
3318   /* Must copy out ar.unat before doing any integer spills.  */
3319   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
3320     {
3321       if (current_frame_info.r[reg_save_ar_unat])
3322         {
3323           ar_unat_save_reg
3324             = gen_rtx_REG (DImode, current_frame_info.r[reg_save_ar_unat]);
3325           reg_emitted (reg_save_ar_unat);
3326         }
3327       else
3328         {
3329           alt_regno = next_scratch_gr_reg ();
3330           ar_unat_save_reg = gen_rtx_REG (DImode, alt_regno);
3331           current_frame_info.gr_used_mask |= 1 << alt_regno;
3332         }
3333
3334       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
3335       insn = emit_move_insn (ar_unat_save_reg, reg);
3336       if (current_frame_info.r[reg_save_ar_unat])
3337         {
3338           RTX_FRAME_RELATED_P (insn) = 1;
3339           add_reg_note (insn, REG_CFA_REGISTER, NULL_RTX);
3340         }
3341
3342       /* Even if we're not going to generate an epilogue, we still
3343          need to save the register so that EH works.  */
3344       if (! epilogue_p && current_frame_info.r[reg_save_ar_unat])
3345         emit_insn (gen_prologue_use (ar_unat_save_reg));
3346     }
3347   else
3348     ar_unat_save_reg = NULL_RTX;
3349
3350   /* Spill all varargs registers.  Do this before spilling any GR registers,
3351      since we want the UNAT bits for the GR registers to override the UNAT
3352      bits from varargs, which we don't care about.  */
3353
3354   cfa_off = -16;
3355   for (regno = GR_ARG_FIRST + 7; n_varargs > 0; --n_varargs, --regno)
3356     {
3357       reg = gen_rtx_REG (DImode, regno);
3358       do_spill (gen_gr_spill, reg, cfa_off += 8, NULL_RTX);
3359     }
3360
3361   /* Locate the bottom of the register save area.  */
3362   cfa_off = (current_frame_info.spill_cfa_off
3363              + current_frame_info.spill_size
3364              + current_frame_info.extra_spill_size);
3365
3366   /* Save the predicate register block either in a register or in memory.  */
3367   if (TEST_HARD_REG_BIT (current_frame_info.mask, PR_REG (0)))
3368     {
3369       reg = gen_rtx_REG (DImode, PR_REG (0));
3370       if (current_frame_info.r[reg_save_pr] != 0)
3371         {
3372           alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_pr]);
3373           reg_emitted (reg_save_pr);
3374           insn = emit_move_insn (alt_reg, reg);
3375
3376           /* ??? Denote pr spill/fill by a DImode move that modifies all
3377              64 hard registers.  */
3378           RTX_FRAME_RELATED_P (insn) = 1;
3379           add_reg_note (insn, REG_CFA_REGISTER, NULL_RTX);
3380
3381           /* Even if we're not going to generate an epilogue, we still
3382              need to save the register so that EH works.  */
3383           if (! epilogue_p)
3384             emit_insn (gen_prologue_use (alt_reg));
3385         }
3386       else
3387         {
3388           alt_regno = next_scratch_gr_reg ();
3389           alt_reg = gen_rtx_REG (DImode, alt_regno);
3390           insn = emit_move_insn (alt_reg, reg);
3391           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
3392           cfa_off -= 8;
3393         }
3394     }
3395
3396   /* Handle AR regs in numerical order.  All of them get special handling.  */
3397   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM)
3398       && current_frame_info.r[reg_save_ar_unat] == 0)
3399     {
3400       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
3401       do_spill (gen_movdi_x, ar_unat_save_reg, cfa_off, reg);
3402       cfa_off -= 8;
3403     }
3404
3405   /* The alloc insn already copied ar.pfs into a general register.  The
3406      only thing we have to do now is copy that register to a stack slot
3407      if we'd not allocated a local register for the job.  */
3408   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM)
3409       && current_frame_info.r[reg_save_ar_pfs] == 0)
3410     {
3411       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
3412       do_spill (gen_movdi_x, ar_pfs_save_reg, cfa_off, reg);
3413       cfa_off -= 8;
3414     }
3415
3416   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_LC_REGNUM))
3417     {
3418       reg = gen_rtx_REG (DImode, AR_LC_REGNUM);
3419       if (current_frame_info.r[reg_save_ar_lc] != 0)
3420         {
3421           alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_ar_lc]);
3422           reg_emitted (reg_save_ar_lc);
3423           insn = emit_move_insn (alt_reg, reg);
3424           RTX_FRAME_RELATED_P (insn) = 1;
3425           add_reg_note (insn, REG_CFA_REGISTER, NULL_RTX);
3426
3427           /* Even if we're not going to generate an epilogue, we still
3428              need to save the register so that EH works.  */
3429           if (! epilogue_p)
3430             emit_insn (gen_prologue_use (alt_reg));
3431         }
3432       else
3433         {
3434           alt_regno = next_scratch_gr_reg ();
3435           alt_reg = gen_rtx_REG (DImode, alt_regno);
3436           emit_move_insn (alt_reg, reg);
3437           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
3438           cfa_off -= 8;
3439         }
3440     }
3441
3442   /* Save the return pointer.  */
3443   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
3444     {
3445       reg = gen_rtx_REG (DImode, BR_REG (0));
3446       if (current_frame_info.r[reg_save_b0] != 0)
3447         {
3448           alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_b0]);
3449           reg_emitted (reg_save_b0);
3450           insn = emit_move_insn (alt_reg, reg);
3451           RTX_FRAME_RELATED_P (insn) = 1;
3452           add_reg_note (insn, REG_CFA_REGISTER, NULL_RTX);
3453
3454           /* Even if we're not going to generate an epilogue, we still
3455              need to save the register so that EH works.  */
3456           if (! epilogue_p)
3457             emit_insn (gen_prologue_use (alt_reg));
3458         }
3459       else
3460         {
3461           alt_regno = next_scratch_gr_reg ();
3462           alt_reg = gen_rtx_REG (DImode, alt_regno);
3463           emit_move_insn (alt_reg, reg);
3464           do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
3465           cfa_off -= 8;
3466         }
3467     }
3468
3469   if (current_frame_info.r[reg_save_gp])
3470     {
3471       reg_emitted (reg_save_gp);
3472       insn = emit_move_insn (gen_rtx_REG (DImode,
3473                                           current_frame_info.r[reg_save_gp]),
3474                              pic_offset_table_rtx);
3475     }
3476
3477   /* We should now be at the base of the gr/br/fr spill area.  */
3478   gcc_assert (cfa_off == (current_frame_info.spill_cfa_off
3479                           + current_frame_info.spill_size));
3480
3481   /* Spill all general registers.  */
3482   for (regno = GR_REG (1); regno <= GR_REG (31); ++regno)
3483     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3484       {
3485         reg = gen_rtx_REG (DImode, regno);
3486         do_spill (gen_gr_spill, reg, cfa_off, reg);
3487         cfa_off -= 8;
3488       }
3489
3490   /* Spill the rest of the BR registers.  */
3491   for (regno = BR_REG (1); regno <= BR_REG (7); ++regno)
3492     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3493       {
3494         alt_regno = next_scratch_gr_reg ();
3495         alt_reg = gen_rtx_REG (DImode, alt_regno);
3496         reg = gen_rtx_REG (DImode, regno);
3497         emit_move_insn (alt_reg, reg);
3498         do_spill (gen_movdi_x, alt_reg, cfa_off, reg);
3499         cfa_off -= 8;
3500       }
3501
3502   /* Align the frame and spill all FR registers.  */
3503   for (regno = FR_REG (2); regno <= FR_REG (127); ++regno)
3504     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3505       {
3506         gcc_assert (!(cfa_off & 15));
3507         reg = gen_rtx_REG (XFmode, regno);
3508         do_spill (gen_fr_spill_x, reg, cfa_off, reg);
3509         cfa_off -= 16;
3510       }
3511
3512   gcc_assert (cfa_off == current_frame_info.spill_cfa_off);
3513
3514   finish_spill_pointers ();
3515 }
3516
3517 /* Output the textual info surrounding the prologue.  */
3518
3519 void
3520 ia64_start_function (FILE *file, const char *fnname,
3521                      tree decl ATTRIBUTE_UNUSED)
3522 {
3523 #if VMS_DEBUGGING_INFO
3524   if (vms_debug_main
3525       && strncmp (vms_debug_main, fnname, strlen (vms_debug_main)) == 0)
3526     {
3527       targetm.asm_out.globalize_label (asm_out_file, VMS_DEBUG_MAIN_POINTER);
3528       ASM_OUTPUT_DEF (asm_out_file, VMS_DEBUG_MAIN_POINTER, fnname);
3529       dwarf2out_vms_debug_main_pointer ();
3530       vms_debug_main = 0;
3531     }
3532 #endif
3533
3534   fputs ("\t.proc ", file);
3535   assemble_name (file, fnname);
3536   fputc ('\n', file);
3537   ASM_OUTPUT_LABEL (file, fnname);
3538 }
3539
3540 /* Called after register allocation to add any instructions needed for the
3541    epilogue.  Using an epilogue insn is favored compared to putting all of the
3542    instructions in output_function_prologue(), since it allows the scheduler
3543    to intermix instructions with the saves of the caller saved registers.  In
3544    some cases, it might be necessary to emit a barrier instruction as the last
3545    insn to prevent such scheduling.  */
3546
3547 void
3548 ia64_expand_epilogue (int sibcall_p)
3549 {
3550   rtx insn, reg, alt_reg, ar_unat_save_reg;
3551   int regno, alt_regno, cfa_off;
3552
3553   ia64_compute_frame_size (get_frame_size ());
3554
3555   /* If there is a frame pointer, then we use it instead of the stack
3556      pointer, so that the stack pointer does not need to be valid when
3557      the epilogue starts.  See EXIT_IGNORE_STACK.  */
3558   if (frame_pointer_needed)
3559     setup_spill_pointers (current_frame_info.n_spilled,
3560                           hard_frame_pointer_rtx, 0);
3561   else
3562     setup_spill_pointers (current_frame_info.n_spilled, stack_pointer_rtx,
3563                           current_frame_info.total_size);
3564
3565   if (current_frame_info.total_size != 0)
3566     {
3567       /* ??? At this point we must generate a magic insn that appears to
3568          modify the spill iterators and the frame pointer.  This would
3569          allow the most scheduling freedom.  For now, just hard stop.  */
3570       emit_insn (gen_blockage ());
3571     }
3572
3573   /* Locate the bottom of the register save area.  */
3574   cfa_off = (current_frame_info.spill_cfa_off
3575              + current_frame_info.spill_size
3576              + current_frame_info.extra_spill_size);
3577
3578   /* Restore the predicate registers.  */
3579   if (TEST_HARD_REG_BIT (current_frame_info.mask, PR_REG (0)))
3580     {
3581       if (current_frame_info.r[reg_save_pr] != 0)
3582         {
3583           alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_pr]);
3584           reg_emitted (reg_save_pr);
3585         }
3586       else
3587         {
3588           alt_regno = next_scratch_gr_reg ();
3589           alt_reg = gen_rtx_REG (DImode, alt_regno);
3590           do_restore (gen_movdi_x, alt_reg, cfa_off);
3591           cfa_off -= 8;
3592         }
3593       reg = gen_rtx_REG (DImode, PR_REG (0));
3594       emit_move_insn (reg, alt_reg);
3595     }
3596
3597   /* Restore the application registers.  */
3598
3599   /* Load the saved unat from the stack, but do not restore it until
3600      after the GRs have been restored.  */
3601   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
3602     {
3603       if (current_frame_info.r[reg_save_ar_unat] != 0)
3604         {
3605           ar_unat_save_reg
3606             = gen_rtx_REG (DImode, current_frame_info.r[reg_save_ar_unat]);
3607           reg_emitted (reg_save_ar_unat);
3608         }
3609       else
3610         {
3611           alt_regno = next_scratch_gr_reg ();
3612           ar_unat_save_reg = gen_rtx_REG (DImode, alt_regno);
3613           current_frame_info.gr_used_mask |= 1 << alt_regno;
3614           do_restore (gen_movdi_x, ar_unat_save_reg, cfa_off);
3615           cfa_off -= 8;
3616         }
3617     }
3618   else
3619     ar_unat_save_reg = NULL_RTX;
3620
3621   if (current_frame_info.r[reg_save_ar_pfs] != 0)
3622     {
3623       reg_emitted (reg_save_ar_pfs);
3624       alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_ar_pfs]);
3625       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
3626       emit_move_insn (reg, alt_reg);
3627     }
3628   else if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_PFS_REGNUM))
3629     {
3630       alt_regno = next_scratch_gr_reg ();
3631       alt_reg = gen_rtx_REG (DImode, alt_regno);
3632       do_restore (gen_movdi_x, alt_reg, cfa_off);
3633       cfa_off -= 8;
3634       reg = gen_rtx_REG (DImode, AR_PFS_REGNUM);
3635       emit_move_insn (reg, alt_reg);
3636     }
3637
3638   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_LC_REGNUM))
3639     {
3640       if (current_frame_info.r[reg_save_ar_lc] != 0)
3641         {
3642           alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_ar_lc]);
3643           reg_emitted (reg_save_ar_lc);
3644         }
3645       else
3646         {
3647           alt_regno = next_scratch_gr_reg ();
3648           alt_reg = gen_rtx_REG (DImode, alt_regno);
3649           do_restore (gen_movdi_x, alt_reg, cfa_off);
3650           cfa_off -= 8;
3651         }
3652       reg = gen_rtx_REG (DImode, AR_LC_REGNUM);
3653       emit_move_insn (reg, alt_reg);
3654     }
3655
3656   /* Restore the return pointer.  */
3657   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
3658     {
3659       if (current_frame_info.r[reg_save_b0] != 0)
3660         {
3661          alt_reg = gen_rtx_REG (DImode, current_frame_info.r[reg_save_b0]);
3662          reg_emitted (reg_save_b0);
3663         }
3664       else
3665         {
3666           alt_regno = next_scratch_gr_reg ();
3667           alt_reg = gen_rtx_REG (DImode, alt_regno);
3668           do_restore (gen_movdi_x, alt_reg, cfa_off);
3669           cfa_off -= 8;
3670         }
3671       reg = gen_rtx_REG (DImode, BR_REG (0));
3672       emit_move_insn (reg, alt_reg);
3673     }
3674
3675   /* We should now be at the base of the gr/br/fr spill area.  */
3676   gcc_assert (cfa_off == (current_frame_info.spill_cfa_off
3677                           + current_frame_info.spill_size));
3678
3679   /* The GP may be stored on the stack in the prologue, but it's
3680      never restored in the epilogue.  Skip the stack slot.  */
3681   if (TEST_HARD_REG_BIT (current_frame_info.mask, GR_REG (1)))
3682     cfa_off -= 8;
3683
3684   /* Restore all general registers.  */
3685   for (regno = GR_REG (2); regno <= GR_REG (31); ++regno)
3686     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3687       {
3688         reg = gen_rtx_REG (DImode, regno);
3689         do_restore (gen_gr_restore, reg, cfa_off);
3690         cfa_off -= 8;
3691       }
3692
3693   /* Restore the branch registers.  */
3694   for (regno = BR_REG (1); regno <= BR_REG (7); ++regno)
3695     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3696       {
3697         alt_regno = next_scratch_gr_reg ();
3698         alt_reg = gen_rtx_REG (DImode, alt_regno);
3699         do_restore (gen_movdi_x, alt_reg, cfa_off);
3700         cfa_off -= 8;
3701         reg = gen_rtx_REG (DImode, regno);
3702         emit_move_insn (reg, alt_reg);
3703       }
3704
3705   /* Restore floating point registers.  */
3706   for (regno = FR_REG (2); regno <= FR_REG (127); ++regno)
3707     if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3708       {
3709         gcc_assert (!(cfa_off & 15));
3710         reg = gen_rtx_REG (XFmode, regno);
3711         do_restore (gen_fr_restore_x, reg, cfa_off);
3712         cfa_off -= 16;
3713       }
3714
3715   /* Restore ar.unat for real.  */
3716   if (TEST_HARD_REG_BIT (current_frame_info.mask, AR_UNAT_REGNUM))
3717     {
3718       reg = gen_rtx_REG (DImode, AR_UNAT_REGNUM);
3719       emit_move_insn (reg, ar_unat_save_reg);
3720     }
3721
3722   gcc_assert (cfa_off == current_frame_info.spill_cfa_off);
3723
3724   finish_spill_pointers ();
3725
3726   if (current_frame_info.total_size
3727       || cfun->machine->ia64_eh_epilogue_sp
3728       || frame_pointer_needed)
3729     {
3730       /* ??? At this point we must generate a magic insn that appears to
3731          modify the spill iterators, the stack pointer, and the frame
3732          pointer.  This would allow the most scheduling freedom.  For now,
3733          just hard stop.  */
3734       emit_insn (gen_blockage ());
3735     }
3736
3737   if (cfun->machine->ia64_eh_epilogue_sp)
3738     emit_move_insn (stack_pointer_rtx, cfun->machine->ia64_eh_epilogue_sp);
3739   else if (frame_pointer_needed)
3740     {
3741       insn = emit_move_insn (stack_pointer_rtx, hard_frame_pointer_rtx);
3742       RTX_FRAME_RELATED_P (insn) = 1;
3743       add_reg_note (insn, REG_CFA_ADJUST_CFA, NULL);
3744     }
3745   else if (current_frame_info.total_size)
3746     {
3747       rtx offset, frame_size_rtx;
3748
3749       frame_size_rtx = GEN_INT (current_frame_info.total_size);
3750       if (satisfies_constraint_I (frame_size_rtx))
3751         offset = frame_size_rtx;
3752       else
3753         {
3754           regno = next_scratch_gr_reg ();
3755           offset = gen_rtx_REG (DImode, regno);
3756           emit_move_insn (offset, frame_size_rtx);
3757         }
3758
3759       insn = emit_insn (gen_adddi3 (stack_pointer_rtx, stack_pointer_rtx,
3760                                     offset));
3761
3762       RTX_FRAME_RELATED_P (insn) = 1;
3763       add_reg_note (insn, REG_CFA_ADJUST_CFA,
3764                     gen_rtx_SET (VOIDmode,
3765                                  stack_pointer_rtx,
3766                                  gen_rtx_PLUS (DImode,
3767                                                stack_pointer_rtx,
3768                                                frame_size_rtx)));
3769     }
3770
3771   if (cfun->machine->ia64_eh_epilogue_bsp)
3772     emit_insn (gen_set_bsp (cfun->machine->ia64_eh_epilogue_bsp));
3773
3774   if (! sibcall_p)
3775     emit_jump_insn (gen_return_internal (gen_rtx_REG (DImode, BR_REG (0))));
3776   else
3777     {
3778       int fp = GR_REG (2);
3779       /* We need a throw away register here, r0 and r1 are reserved,
3780          so r2 is the first available call clobbered register.  If
3781          there was a frame_pointer register, we may have swapped the
3782          names of r2 and HARD_FRAME_POINTER_REGNUM, so we have to make
3783          sure we're using the string "r2" when emitting the register
3784          name for the assembler.  */
3785       if (current_frame_info.r[reg_fp] 
3786           && current_frame_info.r[reg_fp] == GR_REG (2))
3787         fp = HARD_FRAME_POINTER_REGNUM;
3788
3789       /* We must emit an alloc to force the input registers to become output
3790          registers.  Otherwise, if the callee tries to pass its parameters
3791          through to another call without an intervening alloc, then these
3792          values get lost.  */
3793       /* ??? We don't need to preserve all input registers.  We only need to
3794          preserve those input registers used as arguments to the sibling call.
3795          It is unclear how to compute that number here.  */
3796       if (current_frame_info.n_input_regs != 0)
3797         {
3798           rtx n_inputs = GEN_INT (current_frame_info.n_input_regs);
3799           insn = emit_insn (gen_alloc (gen_rtx_REG (DImode, fp),
3800                                 const0_rtx, const0_rtx,
3801                                 n_inputs, const0_rtx));
3802           RTX_FRAME_RELATED_P (insn) = 1;
3803         }
3804     }
3805 }
3806
3807 /* Return 1 if br.ret can do all the work required to return from a
3808    function.  */
3809
3810 int
3811 ia64_direct_return (void)
3812 {
3813   if (reload_completed && ! frame_pointer_needed)
3814     {
3815       ia64_compute_frame_size (get_frame_size ());
3816
3817       return (current_frame_info.total_size == 0
3818               && current_frame_info.n_spilled == 0
3819               && current_frame_info.r[reg_save_b0] == 0
3820               && current_frame_info.r[reg_save_pr] == 0
3821               && current_frame_info.r[reg_save_ar_pfs] == 0
3822               && current_frame_info.r[reg_save_ar_unat] == 0
3823               && current_frame_info.r[reg_save_ar_lc] == 0);
3824     }
3825   return 0;
3826 }
3827
3828 /* Return the magic cookie that we use to hold the return address
3829    during early compilation.  */
3830
3831 rtx
3832 ia64_return_addr_rtx (HOST_WIDE_INT count, rtx frame ATTRIBUTE_UNUSED)
3833 {
3834   if (count != 0)
3835     return NULL;
3836   return gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const0_rtx), UNSPEC_RET_ADDR);
3837 }
3838
3839 /* Split this value after reload, now that we know where the return
3840    address is saved.  */
3841
3842 void
3843 ia64_split_return_addr_rtx (rtx dest)
3844 {
3845   rtx src;
3846
3847   if (TEST_HARD_REG_BIT (current_frame_info.mask, BR_REG (0)))
3848     {
3849       if (current_frame_info.r[reg_save_b0] != 0)
3850         {
3851           src = gen_rtx_REG (DImode, current_frame_info.r[reg_save_b0]);
3852           reg_emitted (reg_save_b0);
3853         }
3854       else
3855         {
3856           HOST_WIDE_INT off;
3857           unsigned int regno;
3858           rtx off_r;
3859
3860           /* Compute offset from CFA for BR0.  */
3861           /* ??? Must be kept in sync with ia64_expand_prologue.  */
3862           off = (current_frame_info.spill_cfa_off
3863                  + current_frame_info.spill_size);
3864           for (regno = GR_REG (1); regno <= GR_REG (31); ++regno)
3865             if (TEST_HARD_REG_BIT (current_frame_info.mask, regno))
3866               off -= 8;
3867
3868           /* Convert CFA offset to a register based offset.  */
3869           if (frame_pointer_needed)
3870             src = hard_frame_pointer_rtx;
3871           else
3872             {
3873               src = stack_pointer_rtx;
3874               off += current_frame_info.total_size;
3875             }
3876
3877           /* Load address into scratch register.  */
3878           off_r = GEN_INT (off);
3879           if (satisfies_constraint_I (off_r))
3880             emit_insn (gen_adddi3 (dest, src, off_r));
3881           else
3882             {
3883               emit_move_insn (dest, off_r);
3884               emit_insn (gen_adddi3 (dest, src, dest));
3885             }
3886
3887           src = gen_rtx_MEM (Pmode, dest);
3888         }
3889     }
3890   else
3891     src = gen_rtx_REG (DImode, BR_REG (0));
3892
3893   emit_move_insn (dest, src);
3894 }
3895
3896 int
3897 ia64_hard_regno_rename_ok (int from, int to)
3898 {
3899   /* Don't clobber any of the registers we reserved for the prologue.  */
3900   unsigned int r;
3901
3902   for (r = reg_fp; r <= reg_save_ar_lc; r++)
3903     if (to == current_frame_info.r[r] 
3904         || from == current_frame_info.r[r]
3905         || to == emitted_frame_related_regs[r]
3906         || from == emitted_frame_related_regs[r])
3907       return 0;
3908
3909   /* Don't use output registers outside the register frame.  */
3910   if (OUT_REGNO_P (to) && to >= OUT_REG (current_frame_info.n_output_regs))
3911     return 0;
3912
3913   /* Retain even/oddness on predicate register pairs.  */
3914   if (PR_REGNO_P (from) && PR_REGNO_P (to))
3915     return (from & 1) == (to & 1);
3916
3917   return 1;
3918 }
3919
3920 /* Target hook for assembling integer objects.  Handle word-sized
3921    aligned objects and detect the cases when @fptr is needed.  */
3922
3923 static bool
3924 ia64_assemble_integer (rtx x, unsigned int size, int aligned_p)
3925 {
3926   if (size == POINTER_SIZE / BITS_PER_UNIT
3927       && !(TARGET_NO_PIC || TARGET_AUTO_PIC)
3928       && GET_CODE (x) == SYMBOL_REF
3929       && SYMBOL_REF_FUNCTION_P (x))
3930     {
3931       static const char * const directive[2][2] = {
3932           /* 64-bit pointer */  /* 32-bit pointer */
3933         { "\tdata8.ua\t@fptr(", "\tdata4.ua\t@fptr("},  /* unaligned */
3934         { "\tdata8\t@fptr(",    "\tdata4\t@fptr("}      /* aligned */
3935       };
3936       fputs (directive[(aligned_p != 0)][POINTER_SIZE == 32], asm_out_file);
3937       output_addr_const (asm_out_file, x);
3938       fputs (")\n", asm_out_file);
3939       return true;
3940     }
3941   return default_assemble_integer (x, size, aligned_p);
3942 }
3943
3944 /* Emit the function prologue.  */
3945
3946 static void
3947 ia64_output_function_prologue (FILE *file, HOST_WIDE_INT size ATTRIBUTE_UNUSED)
3948 {
3949   int mask, grsave, grsave_prev;
3950
3951   if (current_frame_info.need_regstk)
3952     fprintf (file, "\t.regstk %d, %d, %d, %d\n",
3953              current_frame_info.n_input_regs,
3954              current_frame_info.n_local_regs,
3955              current_frame_info.n_output_regs,
3956              current_frame_info.n_rotate_regs);
3957
3958   if (ia64_except_unwind_info () != UI_TARGET)
3959     return;
3960
3961   /* Emit the .prologue directive.  */
3962
3963   mask = 0;
3964   grsave = grsave_prev = 0;
3965   if (current_frame_info.r[reg_save_b0] != 0)
3966     {
3967       mask |= 8;
3968       grsave = grsave_prev = current_frame_info.r[reg_save_b0];
3969     }
3970   if (current_frame_info.r[reg_save_ar_pfs] != 0
3971       && (grsave_prev == 0
3972           || current_frame_info.r[reg_save_ar_pfs] == grsave_prev + 1))
3973     {
3974       mask |= 4;
3975       if (grsave_prev == 0)
3976         grsave = current_frame_info.r[reg_save_ar_pfs];
3977       grsave_prev = current_frame_info.r[reg_save_ar_pfs];
3978     }
3979   if (current_frame_info.r[reg_fp] != 0
3980       && (grsave_prev == 0
3981           || current_frame_info.r[reg_fp] == grsave_prev + 1))
3982     {
3983       mask |= 2;
3984       if (grsave_prev == 0)
3985         grsave = HARD_FRAME_POINTER_REGNUM;
3986       grsave_prev = current_frame_info.r[reg_fp];
3987     }
3988   if (current_frame_info.r[reg_save_pr] != 0
3989       && (grsave_prev == 0
3990           || current_frame_info.r[reg_save_pr] == grsave_prev + 1))
3991     {
3992       mask |= 1;
3993       if (grsave_prev == 0)
3994         grsave = current_frame_info.r[reg_save_pr];
3995     }
3996
3997   if (mask && TARGET_GNU_AS)
3998     fprintf (file, "\t.prologue %d, %d\n", mask,
3999              ia64_dbx_register_number (grsave));
4000   else
4001     fputs ("\t.prologue\n", file);
4002
4003   /* Emit a .spill directive, if necessary, to relocate the base of
4004      the register spill area.  */
4005   if (current_frame_info.spill_cfa_off != -16)
4006     fprintf (file, "\t.spill %ld\n",
4007              (long) (current_frame_info.spill_cfa_off
4008                      + current_frame_info.spill_size));
4009 }
4010
4011 /* Emit the .body directive at the scheduled end of the prologue.  */
4012
4013 static void
4014 ia64_output_function_end_prologue (FILE *file)
4015 {
4016   if (ia64_except_unwind_info () != UI_TARGET)
4017     return;
4018
4019   fputs ("\t.body\n", file);
4020 }
4021
4022 /* Emit the function epilogue.  */
4023
4024 static void
4025 ia64_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
4026                                HOST_WIDE_INT size ATTRIBUTE_UNUSED)
4027 {
4028   int i;
4029
4030   if (current_frame_info.r[reg_fp])
4031     {
4032       const char *tmp = reg_names[HARD_FRAME_POINTER_REGNUM];
4033       reg_names[HARD_FRAME_POINTER_REGNUM]
4034         = reg_names[current_frame_info.r[reg_fp]];
4035       reg_names[current_frame_info.r[reg_fp]] = tmp;
4036       reg_emitted (reg_fp);
4037     }
4038   if (! TARGET_REG_NAMES)
4039     {
4040       for (i = 0; i < current_frame_info.n_input_regs; i++)
4041         reg_names[IN_REG (i)] = ia64_input_reg_names[i];
4042       for (i = 0; i < current_frame_info.n_local_regs; i++)
4043         reg_names[LOC_REG (i)] = ia64_local_reg_names[i];
4044       for (i = 0; i < current_frame_info.n_output_regs; i++)
4045         reg_names[OUT_REG (i)] = ia64_output_reg_names[i];
4046     }
4047
4048   current_frame_info.initialized = 0;
4049 }
4050
4051 int
4052 ia64_dbx_register_number (int regno)
4053 {
4054   /* In ia64_expand_prologue we quite literally renamed the frame pointer
4055      from its home at loc79 to something inside the register frame.  We
4056      must perform the same renumbering here for the debug info.  */
4057   if (current_frame_info.r[reg_fp])
4058     {
4059       if (regno == HARD_FRAME_POINTER_REGNUM)
4060         regno = current_frame_info.r[reg_fp];
4061       else if (regno == current_frame_info.r[reg_fp])
4062         regno = HARD_FRAME_POINTER_REGNUM;
4063     }
4064
4065   if (IN_REGNO_P (regno))
4066     return 32 + regno - IN_REG (0);
4067   else if (LOC_REGNO_P (regno))
4068     return 32 + current_frame_info.n_input_regs + regno - LOC_REG (0);
4069   else if (OUT_REGNO_P (regno))
4070     return (32 + current_frame_info.n_input_regs
4071             + current_frame_info.n_local_regs + regno - OUT_REG (0));
4072   else
4073     return regno;
4074 }
4075
4076 /* Implement TARGET_TRAMPOLINE_INIT.
4077
4078    The trampoline should set the static chain pointer to value placed
4079    into the trampoline and should branch to the specified routine.
4080    To make the normal indirect-subroutine calling convention work,
4081    the trampoline must look like a function descriptor; the first
4082    word being the target address and the second being the target's
4083    global pointer.
4084
4085    We abuse the concept of a global pointer by arranging for it
4086    to point to the data we need to load.  The complete trampoline
4087    has the following form:
4088
4089                 +-------------------+ \
4090         TRAMP:  | __ia64_trampoline | |
4091                 +-------------------+  > fake function descriptor
4092                 | TRAMP+16          | |
4093                 +-------------------+ /
4094                 | target descriptor |
4095                 +-------------------+
4096                 | static link       |
4097                 +-------------------+
4098 */
4099
4100 static void
4101 ia64_trampoline_init (rtx m_tramp, tree fndecl, rtx static_chain)
4102 {
4103   rtx fnaddr = XEXP (DECL_RTL (fndecl), 0);
4104   rtx addr, addr_reg, tramp, eight = GEN_INT (8);
4105
4106   /* The Intel assembler requires that the global __ia64_trampoline symbol
4107      be declared explicitly */
4108   if (!TARGET_GNU_AS)
4109     {
4110       static bool declared_ia64_trampoline = false;
4111
4112       if (!declared_ia64_trampoline)
4113         {
4114           declared_ia64_trampoline = true;
4115           (*targetm.asm_out.globalize_label) (asm_out_file,
4116                                               "__ia64_trampoline");
4117         }
4118     }
4119
4120   /* Make sure addresses are Pmode even if we are in ILP32 mode. */
4121   addr = convert_memory_address (Pmode, XEXP (m_tramp, 0));
4122   fnaddr = convert_memory_address (Pmode, fnaddr);
4123   static_chain = convert_memory_address (Pmode, static_chain);
4124
4125   /* Load up our iterator.  */
4126   addr_reg = copy_to_reg (addr);
4127   m_tramp = adjust_automodify_address (m_tramp, Pmode, addr_reg, 0);
4128
4129   /* The first two words are the fake descriptor:
4130      __ia64_trampoline, ADDR+16.  */
4131   tramp = gen_rtx_SYMBOL_REF (Pmode, "__ia64_trampoline");
4132   if (TARGET_ABI_OPEN_VMS)
4133     {
4134       /* HP decided to break the ELF ABI on VMS (to deal with an ambiguity
4135          in the Macro-32 compiler) and changed the semantics of the LTOFF22
4136          relocation against function symbols to make it identical to the
4137          LTOFF_FPTR22 relocation.  Emit the latter directly to stay within
4138          strict ELF and dereference to get the bare code address.  */
4139       rtx reg = gen_reg_rtx (Pmode);
4140       SYMBOL_REF_FLAGS (tramp) |= SYMBOL_FLAG_FUNCTION;
4141       emit_move_insn (reg, tramp);
4142       emit_move_insn (reg, gen_rtx_MEM (Pmode, reg));
4143       tramp = reg;
4144    }
4145   emit_move_insn (m_tramp, tramp);
4146   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
4147   m_tramp = adjust_automodify_address (m_tramp, VOIDmode, NULL, 8);
4148
4149   emit_move_insn (m_tramp, force_reg (Pmode, plus_constant (addr, 16)));
4150   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
4151   m_tramp = adjust_automodify_address (m_tramp, VOIDmode, NULL, 8);
4152
4153   /* The third word is the target descriptor.  */
4154   emit_move_insn (m_tramp, force_reg (Pmode, fnaddr));
4155   emit_insn (gen_adddi3 (addr_reg, addr_reg, eight));
4156   m_tramp = adjust_automodify_address (m_tramp, VOIDmode, NULL, 8);
4157
4158   /* The fourth word is the static chain.  */
4159   emit_move_insn (m_tramp, static_chain);
4160 }
4161 \f
4162 /* Do any needed setup for a variadic function.  CUM has not been updated
4163    for the last named argument which has type TYPE and mode MODE.
4164
4165    We generate the actual spill instructions during prologue generation.  */
4166
4167 static void
4168 ia64_setup_incoming_varargs (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4169                              tree type, int * pretend_size,
4170                              int second_time ATTRIBUTE_UNUSED)
4171 {
4172   CUMULATIVE_ARGS next_cum = *cum;
4173
4174   /* Skip the current argument.  */
4175   ia64_function_arg_advance (&next_cum, mode, type, 1);
4176
4177   if (next_cum.words < MAX_ARGUMENT_SLOTS)
4178     {
4179       int n = MAX_ARGUMENT_SLOTS - next_cum.words;
4180       *pretend_size = n * UNITS_PER_WORD;
4181       cfun->machine->n_varargs = n;
4182     }
4183 }
4184
4185 /* Check whether TYPE is a homogeneous floating point aggregate.  If
4186    it is, return the mode of the floating point type that appears
4187    in all leafs.  If it is not, return VOIDmode.
4188
4189    An aggregate is a homogeneous floating point aggregate is if all
4190    fields/elements in it have the same floating point type (e.g,
4191    SFmode).  128-bit quad-precision floats are excluded.
4192
4193    Variable sized aggregates should never arrive here, since we should
4194    have already decided to pass them by reference.  Top-level zero-sized
4195    aggregates are excluded because our parallels crash the middle-end.  */
4196
4197 static enum machine_mode
4198 hfa_element_mode (const_tree type, bool nested)
4199 {
4200   enum machine_mode element_mode = VOIDmode;
4201   enum machine_mode mode;
4202   enum tree_code code = TREE_CODE (type);
4203   int know_element_mode = 0;
4204   tree t;
4205
4206   if (!nested && (!TYPE_SIZE (type) || integer_zerop (TYPE_SIZE (type))))
4207     return VOIDmode;
4208
4209   switch (code)
4210     {
4211     case VOID_TYPE:     case INTEGER_TYPE:      case ENUMERAL_TYPE:
4212     case BOOLEAN_TYPE:  case POINTER_TYPE:
4213     case OFFSET_TYPE:   case REFERENCE_TYPE:    case METHOD_TYPE:
4214     case LANG_TYPE:             case FUNCTION_TYPE:
4215       return VOIDmode;
4216
4217       /* Fortran complex types are supposed to be HFAs, so we need to handle
4218          gcc's COMPLEX_TYPEs as HFAs.  We need to exclude the integral complex
4219          types though.  */
4220     case COMPLEX_TYPE:
4221       if (GET_MODE_CLASS (TYPE_MODE (type)) == MODE_COMPLEX_FLOAT
4222           && TYPE_MODE (type) != TCmode)
4223         return GET_MODE_INNER (TYPE_MODE (type));
4224       else
4225         return VOIDmode;
4226
4227     case REAL_TYPE:
4228       /* We want to return VOIDmode for raw REAL_TYPEs, but the actual
4229          mode if this is contained within an aggregate.  */
4230       if (nested && TYPE_MODE (type) != TFmode)
4231         return TYPE_MODE (type);
4232       else
4233         return VOIDmode;
4234
4235     case ARRAY_TYPE:
4236       return hfa_element_mode (TREE_TYPE (type), 1);
4237
4238     case RECORD_TYPE:
4239     case UNION_TYPE:
4240     case QUAL_UNION_TYPE:
4241       for (t = TYPE_FIELDS (type); t; t = DECL_CHAIN (t))
4242         {
4243           if (TREE_CODE (t) != FIELD_DECL)
4244             continue;
4245
4246           mode = hfa_element_mode (TREE_TYPE (t), 1);
4247           if (know_element_mode)
4248             {
4249               if (mode != element_mode)
4250                 return VOIDmode;
4251             }
4252           else if (GET_MODE_CLASS (mode) != MODE_FLOAT)
4253             return VOIDmode;
4254           else
4255             {
4256               know_element_mode = 1;
4257               element_mode = mode;
4258             }
4259         }
4260       return element_mode;
4261
4262     default:
4263       /* If we reach here, we probably have some front-end specific type
4264          that the backend doesn't know about.  This can happen via the
4265          aggregate_value_p call in init_function_start.  All we can do is
4266          ignore unknown tree types.  */
4267       return VOIDmode;
4268     }
4269
4270   return VOIDmode;
4271 }
4272
4273 /* Return the number of words required to hold a quantity of TYPE and MODE
4274    when passed as an argument.  */
4275 static int
4276 ia64_function_arg_words (const_tree type, enum machine_mode mode)
4277 {
4278   int words;
4279
4280   if (mode == BLKmode)
4281     words = int_size_in_bytes (type);
4282   else
4283     words = GET_MODE_SIZE (mode);
4284
4285   return (words + UNITS_PER_WORD - 1) / UNITS_PER_WORD;  /* round up */
4286 }
4287
4288 /* Return the number of registers that should be skipped so the current
4289    argument (described by TYPE and WORDS) will be properly aligned.
4290
4291    Integer and float arguments larger than 8 bytes start at the next
4292    even boundary.  Aggregates larger than 8 bytes start at the next
4293    even boundary if the aggregate has 16 byte alignment.  Note that
4294    in the 32-bit ABI, TImode and TFmode have only 8-byte alignment
4295    but are still to be aligned in registers.
4296
4297    ??? The ABI does not specify how to handle aggregates with
4298    alignment from 9 to 15 bytes, or greater than 16.  We handle them
4299    all as if they had 16 byte alignment.  Such aggregates can occur
4300    only if gcc extensions are used.  */
4301 static int
4302 ia64_function_arg_offset (const CUMULATIVE_ARGS *cum,
4303                           const_tree type, int words)
4304 {
4305   /* No registers are skipped on VMS.  */
4306   if (TARGET_ABI_OPEN_VMS || (cum->words & 1) == 0)
4307     return 0;
4308
4309   if (type
4310       && TREE_CODE (type) != INTEGER_TYPE
4311       && TREE_CODE (type) != REAL_TYPE)
4312     return TYPE_ALIGN (type) > 8 * BITS_PER_UNIT;
4313   else
4314     return words > 1;
4315 }
4316
4317 /* Return rtx for register where argument is passed, or zero if it is passed
4318    on the stack.  */
4319 /* ??? 128-bit quad-precision floats are always passed in general
4320    registers.  */
4321
4322 static rtx
4323 ia64_function_arg_1 (const CUMULATIVE_ARGS *cum, enum machine_mode mode,
4324                      const_tree type, bool named, bool incoming)
4325 {
4326   int basereg = (incoming ? GR_ARG_FIRST : AR_ARG_FIRST);
4327   int words = ia64_function_arg_words (type, mode);
4328   int offset = ia64_function_arg_offset (cum, type, words);
4329   enum machine_mode hfa_mode = VOIDmode;
4330
4331   /* For OPEN VMS, emit the instruction setting up the argument register here,
4332      when we know this will be together with the other arguments setup related
4333      insns.  This is not the conceptually best place to do this, but this is
4334      the easiest as we have convenient access to cumulative args info.  */
4335
4336   if (TARGET_ABI_OPEN_VMS && mode == VOIDmode && type == void_type_node
4337       && named == 1)
4338     {
4339       unsigned HOST_WIDE_INT regval = cum->words;
4340       int i;
4341
4342       for (i = 0; i < 8; i++)
4343         regval |= ((int) cum->atypes[i]) << (i * 3 + 8);
4344
4345       emit_move_insn (gen_rtx_REG (DImode, GR_REG (25)),
4346                       GEN_INT (regval));
4347     }
4348
4349   /* If all argument slots are used, then it must go on the stack.  */
4350   if (cum->words + offset >= MAX_ARGUMENT_SLOTS)
4351     return 0;
4352
4353   /* Check for and handle homogeneous FP aggregates.  */
4354   if (type)
4355     hfa_mode = hfa_element_mode (type, 0);
4356
4357   /* Unnamed prototyped hfas are passed as usual.  Named prototyped hfas
4358      and unprototyped hfas are passed specially.  */
4359   if (hfa_mode != VOIDmode && (! cum->prototype || named))
4360     {
4361       rtx loc[16];
4362       int i = 0;
4363       int fp_regs = cum->fp_regs;
4364       int int_regs = cum->words + offset;
4365       int hfa_size = GET_MODE_SIZE (hfa_mode);
4366       int byte_size;
4367       int args_byte_size;
4368
4369       /* If prototyped, pass it in FR regs then GR regs.
4370          If not prototyped, pass it in both FR and GR regs.
4371
4372          If this is an SFmode aggregate, then it is possible to run out of
4373          FR regs while GR regs are still left.  In that case, we pass the
4374          remaining part in the GR regs.  */
4375
4376       /* Fill the FP regs.  We do this always.  We stop if we reach the end
4377          of the argument, the last FP register, or the last argument slot.  */
4378
4379       byte_size = ((mode == BLKmode)
4380                    ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
4381       args_byte_size = int_regs * UNITS_PER_WORD;
4382       offset = 0;
4383       for (; (offset < byte_size && fp_regs < MAX_ARGUMENT_SLOTS
4384               && args_byte_size < (MAX_ARGUMENT_SLOTS * UNITS_PER_WORD)); i++)
4385         {
4386           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4387                                       gen_rtx_REG (hfa_mode, (FR_ARG_FIRST
4388                                                               + fp_regs)),
4389                                       GEN_INT (offset));
4390           offset += hfa_size;
4391           args_byte_size += hfa_size;
4392           fp_regs++;
4393         }
4394
4395       /* If no prototype, then the whole thing must go in GR regs.  */
4396       if (! cum->prototype)
4397         offset = 0;
4398       /* If this is an SFmode aggregate, then we might have some left over
4399          that needs to go in GR regs.  */
4400       else if (byte_size != offset)
4401         int_regs += offset / UNITS_PER_WORD;
4402
4403       /* Fill in the GR regs.  We must use DImode here, not the hfa mode.  */
4404
4405       for (; offset < byte_size && int_regs < MAX_ARGUMENT_SLOTS; i++)
4406         {
4407           enum machine_mode gr_mode = DImode;
4408           unsigned int gr_size;
4409
4410           /* If we have an odd 4 byte hunk because we ran out of FR regs,
4411              then this goes in a GR reg left adjusted/little endian, right
4412              adjusted/big endian.  */
4413           /* ??? Currently this is handled wrong, because 4-byte hunks are
4414              always right adjusted/little endian.  */
4415           if (offset & 0x4)
4416             gr_mode = SImode;
4417           /* If we have an even 4 byte hunk because the aggregate is a
4418              multiple of 4 bytes in size, then this goes in a GR reg right
4419              adjusted/little endian.  */
4420           else if (byte_size - offset == 4)
4421             gr_mode = SImode;
4422
4423           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4424                                       gen_rtx_REG (gr_mode, (basereg
4425                                                              + int_regs)),
4426                                       GEN_INT (offset));
4427
4428           gr_size = GET_MODE_SIZE (gr_mode);
4429           offset += gr_size;
4430           if (gr_size == UNITS_PER_WORD
4431               || (gr_size < UNITS_PER_WORD && offset % UNITS_PER_WORD == 0))
4432             int_regs++;
4433           else if (gr_size > UNITS_PER_WORD)
4434             int_regs += gr_size / UNITS_PER_WORD;
4435         }
4436       return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
4437     }
4438   
4439   /* On OpenVMS variable argument is either in Rn or Fn.  */
4440   else if (TARGET_ABI_OPEN_VMS && named == 0)
4441     {
4442       if (FLOAT_MODE_P (mode))
4443         return gen_rtx_REG (mode, FR_ARG_FIRST + cum->words);
4444       else
4445         return gen_rtx_REG (mode, basereg + cum->words);
4446     }
4447
4448   /* Integral and aggregates go in general registers.  If we have run out of
4449      FR registers, then FP values must also go in general registers.  This can
4450      happen when we have a SFmode HFA.  */
4451   else if (mode == TFmode || mode == TCmode
4452            || (! FLOAT_MODE_P (mode) || cum->fp_regs == MAX_ARGUMENT_SLOTS))
4453     {
4454       int byte_size = ((mode == BLKmode)
4455                        ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
4456       if (BYTES_BIG_ENDIAN
4457         && (mode == BLKmode || (type && AGGREGATE_TYPE_P (type)))
4458         && byte_size < UNITS_PER_WORD
4459         && byte_size > 0)
4460         {
4461           rtx gr_reg = gen_rtx_EXPR_LIST (VOIDmode,
4462                                           gen_rtx_REG (DImode,
4463                                                        (basereg + cum->words
4464                                                         + offset)),
4465                                           const0_rtx);
4466           return gen_rtx_PARALLEL (mode, gen_rtvec (1, gr_reg));
4467         }
4468       else
4469         return gen_rtx_REG (mode, basereg + cum->words + offset);
4470
4471     }
4472
4473   /* If there is a prototype, then FP values go in a FR register when
4474      named, and in a GR register when unnamed.  */
4475   else if (cum->prototype)
4476     {
4477       if (named)
4478         return gen_rtx_REG (mode, FR_ARG_FIRST + cum->fp_regs);
4479       /* In big-endian mode, an anonymous SFmode value must be represented
4480          as (parallel:SF [(expr_list (reg:DI n) (const_int 0))]) to force
4481          the value into the high half of the general register.  */
4482       else if (BYTES_BIG_ENDIAN && mode == SFmode)
4483         return gen_rtx_PARALLEL (mode,
4484                  gen_rtvec (1,
4485                    gen_rtx_EXPR_LIST (VOIDmode,
4486                      gen_rtx_REG (DImode, basereg + cum->words + offset),
4487                                       const0_rtx)));
4488       else
4489         return gen_rtx_REG (mode, basereg + cum->words + offset);
4490     }
4491   /* If there is no prototype, then FP values go in both FR and GR
4492      registers.  */
4493   else
4494     {
4495       /* See comment above.  */
4496       enum machine_mode inner_mode =
4497         (BYTES_BIG_ENDIAN && mode == SFmode) ? DImode : mode;
4498
4499       rtx fp_reg = gen_rtx_EXPR_LIST (VOIDmode,
4500                                       gen_rtx_REG (mode, (FR_ARG_FIRST
4501                                                           + cum->fp_regs)),
4502                                       const0_rtx);
4503       rtx gr_reg = gen_rtx_EXPR_LIST (VOIDmode,
4504                                       gen_rtx_REG (inner_mode,
4505                                                    (basereg + cum->words
4506                                                     + offset)),
4507                                       const0_rtx);
4508
4509       return gen_rtx_PARALLEL (mode, gen_rtvec (2, fp_reg, gr_reg));
4510     }
4511 }
4512
4513 /* Implement TARGET_FUNCION_ARG target hook.  */
4514
4515 static rtx
4516 ia64_function_arg (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4517                    const_tree type, bool named)
4518 {
4519   return ia64_function_arg_1 (cum, mode, type, named, false);
4520 }
4521
4522 /* Implement TARGET_FUNCION_INCOMING_ARG target hook.  */
4523
4524 static rtx
4525 ia64_function_incoming_arg (CUMULATIVE_ARGS *cum,
4526                             enum machine_mode mode,
4527                             const_tree type, bool named)
4528 {
4529   return ia64_function_arg_1 (cum, mode, type, named, true);
4530 }
4531
4532 /* Return number of bytes, at the beginning of the argument, that must be
4533    put in registers.  0 is the argument is entirely in registers or entirely
4534    in memory.  */
4535
4536 static int
4537 ia64_arg_partial_bytes (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4538                         tree type, bool named ATTRIBUTE_UNUSED)
4539 {
4540   int words = ia64_function_arg_words (type, mode);
4541   int offset = ia64_function_arg_offset (cum, type, words);
4542
4543   /* If all argument slots are used, then it must go on the stack.  */
4544   if (cum->words + offset >= MAX_ARGUMENT_SLOTS)
4545     return 0;
4546
4547   /* It doesn't matter whether the argument goes in FR or GR regs.  If
4548      it fits within the 8 argument slots, then it goes entirely in
4549      registers.  If it extends past the last argument slot, then the rest
4550      goes on the stack.  */
4551
4552   if (words + cum->words + offset <= MAX_ARGUMENT_SLOTS)
4553     return 0;
4554
4555   return (MAX_ARGUMENT_SLOTS - cum->words - offset) * UNITS_PER_WORD;
4556 }
4557
4558 /* Return ivms_arg_type based on machine_mode.  */
4559
4560 static enum ivms_arg_type
4561 ia64_arg_type (enum machine_mode mode)
4562 {
4563   switch (mode)
4564     {
4565     case SFmode:
4566       return FS;
4567     case DFmode:
4568       return FT;
4569     default:
4570       return I64;
4571     }
4572 }
4573
4574 /* Update CUM to point after this argument.  This is patterned after
4575    ia64_function_arg.  */
4576
4577 static void
4578 ia64_function_arg_advance (CUMULATIVE_ARGS *cum, enum machine_mode mode,
4579                            const_tree type, bool named)
4580 {
4581   int words = ia64_function_arg_words (type, mode);
4582   int offset = ia64_function_arg_offset (cum, type, words);
4583   enum machine_mode hfa_mode = VOIDmode;
4584
4585   /* If all arg slots are already full, then there is nothing to do.  */
4586   if (cum->words >= MAX_ARGUMENT_SLOTS)
4587     {
4588       cum->words += words + offset;
4589       return;
4590     }
4591
4592   cum->atypes[cum->words] = ia64_arg_type (mode);
4593   cum->words += words + offset;
4594
4595   /* Check for and handle homogeneous FP aggregates.  */
4596   if (type)
4597     hfa_mode = hfa_element_mode (type, 0);
4598
4599   /* Unnamed prototyped hfas are passed as usual.  Named prototyped hfas
4600      and unprototyped hfas are passed specially.  */
4601   if (hfa_mode != VOIDmode && (! cum->prototype || named))
4602     {
4603       int fp_regs = cum->fp_regs;
4604       /* This is the original value of cum->words + offset.  */
4605       int int_regs = cum->words - words;
4606       int hfa_size = GET_MODE_SIZE (hfa_mode);
4607       int byte_size;
4608       int args_byte_size;
4609
4610       /* If prototyped, pass it in FR regs then GR regs.
4611          If not prototyped, pass it in both FR and GR regs.
4612
4613          If this is an SFmode aggregate, then it is possible to run out of
4614          FR regs while GR regs are still left.  In that case, we pass the
4615          remaining part in the GR regs.  */
4616
4617       /* Fill the FP regs.  We do this always.  We stop if we reach the end
4618          of the argument, the last FP register, or the last argument slot.  */
4619
4620       byte_size = ((mode == BLKmode)
4621                    ? int_size_in_bytes (type) : GET_MODE_SIZE (mode));
4622       args_byte_size = int_regs * UNITS_PER_WORD;
4623       offset = 0;
4624       for (; (offset < byte_size && fp_regs < MAX_ARGUMENT_SLOTS
4625               && args_byte_size < (MAX_ARGUMENT_SLOTS * UNITS_PER_WORD));)
4626         {
4627           offset += hfa_size;
4628           args_byte_size += hfa_size;
4629           fp_regs++;
4630         }
4631
4632       cum->fp_regs = fp_regs;
4633     }
4634
4635   /* On OpenVMS variable argument is either in Rn or Fn.  */
4636   else if (TARGET_ABI_OPEN_VMS && named == 0)
4637     {
4638       cum->int_regs = cum->words;
4639       cum->fp_regs = cum->words;
4640     }
4641
4642   /* Integral and aggregates go in general registers.  So do TFmode FP values.
4643      If we have run out of FR registers, then other FP values must also go in
4644      general registers.  This can happen when we have a SFmode HFA.  */
4645   else if (mode == TFmode || mode == TCmode
4646            || (! FLOAT_MODE_P (mode) || cum->fp_regs == MAX_ARGUMENT_SLOTS))
4647     cum->int_regs = cum->words;
4648
4649   /* If there is a prototype, then FP values go in a FR register when
4650      named, and in a GR register when unnamed.  */
4651   else if (cum->prototype)
4652     {
4653       if (! named)
4654         cum->int_regs = cum->words;
4655       else
4656         /* ??? Complex types should not reach here.  */
4657         cum->fp_regs += (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT ? 2 : 1);
4658     }
4659   /* If there is no prototype, then FP values go in both FR and GR
4660      registers.  */
4661   else
4662     {
4663       /* ??? Complex types should not reach here.  */
4664       cum->fp_regs += (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT ? 2 : 1);
4665       cum->int_regs = cum->words;
4666     }
4667 }
4668
4669 /* Arguments with alignment larger than 8 bytes start at the next even
4670    boundary.  On ILP32 HPUX, TFmode arguments start on next even boundary
4671    even though their normal alignment is 8 bytes.  See ia64_function_arg.  */
4672
4673 static unsigned int
4674 ia64_function_arg_boundary (enum machine_mode mode, const_tree type)
4675 {
4676   if (mode == TFmode && TARGET_HPUX && TARGET_ILP32)
4677     return PARM_BOUNDARY * 2;
4678
4679   if (type)
4680     {
4681       if (TYPE_ALIGN (type) > PARM_BOUNDARY)
4682         return PARM_BOUNDARY * 2;
4683       else
4684         return PARM_BOUNDARY;
4685     }
4686
4687   if (GET_MODE_BITSIZE (mode) > PARM_BOUNDARY)
4688     return PARM_BOUNDARY * 2;
4689   else
4690     return PARM_BOUNDARY;
4691 }
4692
4693 /* True if it is OK to do sibling call optimization for the specified
4694    call expression EXP.  DECL will be the called function, or NULL if
4695    this is an indirect call.  */
4696 static bool
4697 ia64_function_ok_for_sibcall (tree decl, tree exp ATTRIBUTE_UNUSED)
4698 {
4699   /* We can't perform a sibcall if the current function has the syscall_linkage
4700      attribute.  */
4701   if (lookup_attribute ("syscall_linkage",
4702                         TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))))
4703     return false;
4704
4705   /* We must always return with our current GP.  This means we can
4706      only sibcall to functions defined in the current module unless
4707      TARGET_CONST_GP is set to true.  */
4708   return (decl && (*targetm.binds_local_p) (decl)) || TARGET_CONST_GP;
4709 }
4710 \f
4711
4712 /* Implement va_arg.  */
4713
4714 static tree
4715 ia64_gimplify_va_arg (tree valist, tree type, gimple_seq *pre_p,
4716                       gimple_seq *post_p)
4717 {
4718   /* Variable sized types are passed by reference.  */
4719   if (pass_by_reference (NULL, TYPE_MODE (type), type, false))
4720     {
4721       tree ptrtype = build_pointer_type (type);
4722       tree addr = std_gimplify_va_arg_expr (valist, ptrtype, pre_p, post_p);
4723       return build_va_arg_indirect_ref (addr);
4724     }
4725
4726   /* Aggregate arguments with alignment larger than 8 bytes start at
4727      the next even boundary.  Integer and floating point arguments
4728      do so if they are larger than 8 bytes, whether or not they are
4729      also aligned larger than 8 bytes.  */
4730   if ((TREE_CODE (type) == REAL_TYPE || TREE_CODE (type) == INTEGER_TYPE)
4731       ? int_size_in_bytes (type) > 8 : TYPE_ALIGN (type) > 8 * BITS_PER_UNIT)
4732     {
4733       tree t = build2 (POINTER_PLUS_EXPR, TREE_TYPE (valist), valist,
4734                        size_int (2 * UNITS_PER_WORD - 1));
4735       t = fold_convert (sizetype, t);
4736       t = build2 (BIT_AND_EXPR, TREE_TYPE (t), t,
4737                   size_int (-2 * UNITS_PER_WORD));
4738       t = fold_convert (TREE_TYPE (valist), t);
4739       gimplify_assign (unshare_expr (valist), t, pre_p);
4740     }
4741
4742   return std_gimplify_va_arg_expr (valist, type, pre_p, post_p);
4743 }
4744 \f
4745 /* Return 1 if function return value returned in memory.  Return 0 if it is
4746    in a register.  */
4747
4748 static bool
4749 ia64_return_in_memory (const_tree valtype, const_tree fntype ATTRIBUTE_UNUSED)
4750 {
4751   enum machine_mode mode;
4752   enum machine_mode hfa_mode;
4753   HOST_WIDE_INT byte_size;
4754
4755   mode = TYPE_MODE (valtype);
4756   byte_size = GET_MODE_SIZE (mode);
4757   if (mode == BLKmode)
4758     {
4759       byte_size = int_size_in_bytes (valtype);
4760       if (byte_size < 0)
4761         return true;
4762     }
4763
4764   /* Hfa's with up to 8 elements are returned in the FP argument registers.  */
4765
4766   hfa_mode = hfa_element_mode (valtype, 0);
4767   if (hfa_mode != VOIDmode)
4768     {
4769       int hfa_size = GET_MODE_SIZE (hfa_mode);
4770
4771       if (byte_size / hfa_size > MAX_ARGUMENT_SLOTS)
4772         return true;
4773       else
4774         return false;
4775     }
4776   else if (byte_size > UNITS_PER_WORD * MAX_INT_RETURN_SLOTS)
4777     return true;
4778   else
4779     return false;
4780 }
4781
4782 /* Return rtx for register that holds the function return value.  */
4783
4784 static rtx
4785 ia64_function_value (const_tree valtype,
4786                      const_tree fn_decl_or_type,
4787                      bool outgoing ATTRIBUTE_UNUSED)
4788 {
4789   enum machine_mode mode;
4790   enum machine_mode hfa_mode;
4791   int unsignedp;
4792   const_tree func = fn_decl_or_type;
4793
4794   if (fn_decl_or_type
4795       && !DECL_P (fn_decl_or_type))
4796     func = NULL;
4797   
4798   mode = TYPE_MODE (valtype);
4799   hfa_mode = hfa_element_mode (valtype, 0);
4800
4801   if (hfa_mode != VOIDmode)
4802     {
4803       rtx loc[8];
4804       int i;
4805       int hfa_size;
4806       int byte_size;
4807       int offset;
4808
4809       hfa_size = GET_MODE_SIZE (hfa_mode);
4810       byte_size = ((mode == BLKmode)
4811                    ? int_size_in_bytes (valtype) : GET_MODE_SIZE (mode));
4812       offset = 0;
4813       for (i = 0; offset < byte_size; i++)
4814         {
4815           loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4816                                       gen_rtx_REG (hfa_mode, FR_ARG_FIRST + i),
4817                                       GEN_INT (offset));
4818           offset += hfa_size;
4819         }
4820       return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
4821     }
4822   else if (FLOAT_TYPE_P (valtype) && mode != TFmode && mode != TCmode)
4823     return gen_rtx_REG (mode, FR_ARG_FIRST);
4824   else
4825     {
4826       bool need_parallel = false;
4827
4828       /* In big-endian mode, we need to manage the layout of aggregates
4829          in the registers so that we get the bits properly aligned in
4830          the highpart of the registers.  */
4831       if (BYTES_BIG_ENDIAN
4832           && (mode == BLKmode || (valtype && AGGREGATE_TYPE_P (valtype))))
4833         need_parallel = true;
4834
4835       /* Something like struct S { long double x; char a[0] } is not an
4836          HFA structure, and therefore doesn't go in fp registers.  But
4837          the middle-end will give it XFmode anyway, and XFmode values
4838          don't normally fit in integer registers.  So we need to smuggle
4839          the value inside a parallel.  */
4840       else if (mode == XFmode || mode == XCmode || mode == RFmode)
4841         need_parallel = true;
4842
4843       if (need_parallel)
4844         {
4845           rtx loc[8];
4846           int offset;
4847           int bytesize;
4848           int i;
4849
4850           offset = 0;
4851           bytesize = int_size_in_bytes (valtype);
4852           /* An empty PARALLEL is invalid here, but the return value
4853              doesn't matter for empty structs.  */
4854           if (bytesize == 0)
4855             return gen_rtx_REG (mode, GR_RET_FIRST);
4856           for (i = 0; offset < bytesize; i++)
4857             {
4858               loc[i] = gen_rtx_EXPR_LIST (VOIDmode,
4859                                           gen_rtx_REG (DImode,
4860                                                        GR_RET_FIRST + i),
4861                                           GEN_INT (offset));
4862               offset += UNITS_PER_WORD;
4863             }
4864           return gen_rtx_PARALLEL (mode, gen_rtvec_v (i, loc));
4865         }
4866
4867       mode = ia64_promote_function_mode (valtype, mode, &unsignedp,
4868                                          func ? TREE_TYPE (func) : NULL_TREE,
4869                                          true);
4870
4871       return gen_rtx_REG (mode, GR_RET_FIRST);
4872     }
4873 }
4874
4875 /* Worker function for TARGET_LIBCALL_VALUE.  */
4876
4877 static rtx
4878 ia64_libcall_value (enum machine_mode mode,
4879                     const_rtx fun ATTRIBUTE_UNUSED)
4880 {
4881   return gen_rtx_REG (mode,
4882                       (((GET_MODE_CLASS (mode) == MODE_FLOAT
4883                          || GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
4884                         && (mode) != TFmode)
4885                        ? FR_RET_FIRST : GR_RET_FIRST));
4886 }
4887
4888 /* Worker function for FUNCTION_VALUE_REGNO_P.  */
4889
4890 static bool
4891 ia64_function_value_regno_p (const unsigned int regno)
4892 {
4893   return ((regno >= GR_RET_FIRST && regno <= GR_RET_LAST)
4894           || (regno >= FR_RET_FIRST && regno <= FR_RET_LAST));
4895 }
4896
4897 /* This is called from dwarf2out.c via TARGET_ASM_OUTPUT_DWARF_DTPREL.
4898    We need to emit DTP-relative relocations.  */
4899
4900 static void
4901 ia64_output_dwarf_dtprel (FILE *file, int size, rtx x)
4902 {
4903   gcc_assert (size == 4 || size == 8);
4904   if (size == 4)
4905     fputs ("\tdata4.ua\t@dtprel(", file);
4906   else
4907     fputs ("\tdata8.ua\t@dtprel(", file);
4908   output_addr_const (file, x);
4909   fputs (")", file);
4910 }
4911
4912 /* Print a memory address as an operand to reference that memory location.  */
4913
4914 /* ??? Do we need this?  It gets used only for 'a' operands.  We could perhaps
4915    also call this from ia64_print_operand for memory addresses.  */
4916
4917 void
4918 ia64_print_operand_address (FILE * stream ATTRIBUTE_UNUSED,
4919                             rtx address ATTRIBUTE_UNUSED)
4920 {
4921 }
4922
4923 /* Print an operand to an assembler instruction.
4924    C    Swap and print a comparison operator.
4925    D    Print an FP comparison operator.
4926    E    Print 32 - constant, for SImode shifts as extract.
4927    e    Print 64 - constant, for DImode rotates.
4928    F    A floating point constant 0.0 emitted as f0, or 1.0 emitted as f1, or
4929         a floating point register emitted normally.
4930    G    A floating point constant.
4931    I    Invert a predicate register by adding 1.
4932    J    Select the proper predicate register for a condition.
4933    j    Select the inverse predicate register for a condition.
4934    O    Append .acq for volatile load.
4935    P    Postincrement of a MEM.
4936    Q    Append .rel for volatile store.
4937    R    Print .s .d or nothing for a single, double or no truncation.
4938    S    Shift amount for shladd instruction.
4939    T    Print an 8-bit sign extended number (K) as a 32-bit unsigned number
4940         for Intel assembler.
4941    U    Print an 8-bit sign extended number (K) as a 64-bit unsigned number
4942         for Intel assembler.
4943    X    A pair of floating point registers.
4944    r    Print register name, or constant 0 as r0.  HP compatibility for
4945         Linux kernel.
4946    v    Print vector constant value as an 8-byte integer value.  */
4947
4948 void
4949 ia64_print_operand (FILE * file, rtx x, int code)
4950 {
4951   const char *str;
4952
4953   switch (code)
4954     {
4955     case 0:
4956       /* Handled below.  */
4957       break;
4958
4959     case 'C':
4960       {
4961         enum rtx_code c = swap_condition (GET_CODE (x));
4962         fputs (GET_RTX_NAME (c), file);
4963         return;
4964       }
4965
4966     case 'D':
4967       switch (GET_CODE (x))
4968         {
4969         case NE:
4970           str = "neq";
4971           break;
4972         case UNORDERED:
4973           str = "unord";
4974           break;
4975         case ORDERED:
4976           str = "ord";
4977           break;
4978         case UNLT:
4979           str = "nge";
4980           break;
4981         case UNLE:
4982           str = "ngt";
4983           break;
4984         case UNGT:
4985           str = "nle";
4986           break;
4987         case UNGE:
4988           str = "nlt";
4989           break;
4990         default:
4991           str = GET_RTX_NAME (GET_CODE (x));
4992           break;
4993         }
4994       fputs (str, file);
4995       return;
4996
4997     case 'E':
4998       fprintf (file, HOST_WIDE_INT_PRINT_DEC, 32 - INTVAL (x));
4999       return;
5000
5001     case 'e':
5002       fprintf (file, HOST_WIDE_INT_PRINT_DEC, 64 - INTVAL (x));
5003       return;
5004
5005     case 'F':
5006       if (x == CONST0_RTX (GET_MODE (x)))
5007         str = reg_names [FR_REG (0)];
5008       else if (x == CONST1_RTX (GET_MODE (x)))
5009         str = reg_names [FR_REG (1)];
5010       else
5011         {
5012           gcc_assert (GET_CODE (x) == REG);
5013           str = reg_names [REGNO (x)];
5014         }
5015       fputs (str, file);
5016       return;
5017
5018     case 'G':
5019       {
5020         long val[4];
5021         REAL_VALUE_TYPE rv;
5022         REAL_VALUE_FROM_CONST_DOUBLE (rv, x);
5023         real_to_target (val, &rv, GET_MODE (x));
5024         if (GET_MODE (x) == SFmode)
5025           fprintf (file, "0x%08lx", val[0] & 0xffffffff);
5026         else if (GET_MODE (x) == DFmode)
5027           fprintf (file, "0x%08lx%08lx", (WORDS_BIG_ENDIAN ? val[0] : val[1])
5028                                           & 0xffffffff,
5029                                          (WORDS_BIG_ENDIAN ? val[1] : val[0])
5030                                           & 0xffffffff);
5031         else
5032           output_operand_lossage ("invalid %%G mode");
5033       }
5034       return;
5035
5036     case 'I':
5037       fputs (reg_names [REGNO (x) + 1], file);
5038       return;
5039
5040     case 'J':
5041     case 'j':
5042       {
5043         unsigned int regno = REGNO (XEXP (x, 0));
5044         if (GET_CODE (x) == EQ)
5045           regno += 1;
5046         if (code == 'j')
5047           regno ^= 1;
5048         fputs (reg_names [regno], file);
5049       }
5050       return;
5051
5052     case 'O':
5053       if (MEM_VOLATILE_P (x))
5054         fputs(".acq", file);
5055       return;
5056
5057     case 'P':
5058       {
5059         HOST_WIDE_INT value;
5060
5061         switch (GET_CODE (XEXP (x, 0)))
5062           {
5063           default:
5064             return;
5065
5066           case POST_MODIFY:
5067             x = XEXP (XEXP (XEXP (x, 0), 1), 1);
5068             if (GET_CODE (x) == CONST_INT)
5069               value = INTVAL (x);
5070             else
5071               {
5072                 gcc_assert (GET_CODE (x) == REG);
5073                 fprintf (file, ", %s", reg_names[REGNO (x)]);
5074                 return;
5075               }
5076             break;
5077
5078           case POST_INC:
5079             value = GET_MODE_SIZE (GET_MODE (x));
5080             break;
5081
5082           case POST_DEC:
5083             value = - (HOST_WIDE_INT) GET_MODE_SIZE (GET_MODE (x));
5084             break;
5085           }
5086
5087         fprintf (file, ", " HOST_WIDE_INT_PRINT_DEC, value);
5088         return;
5089       }
5090
5091     case 'Q':
5092       if (MEM_VOLATILE_P (x))
5093         fputs(".rel", file);
5094       return;
5095
5096     case 'R':
5097       if (x == CONST0_RTX (GET_MODE (x)))
5098         fputs(".s", file);
5099       else if (x == CONST1_RTX (GET_MODE (x)))
5100         fputs(".d", file);
5101       else if (x == CONST2_RTX (GET_MODE (x)))
5102         ;
5103       else
5104         output_operand_lossage ("invalid %%R value");
5105       return;
5106
5107     case 'S':
5108       fprintf (file, "%d", exact_log2 (INTVAL (x)));
5109       return;
5110
5111     case 'T':
5112       if (! TARGET_GNU_AS && GET_CODE (x) == CONST_INT)
5113         {
5114           fprintf (file, "0x%x", (int) INTVAL (x) & 0xffffffff);
5115           return;
5116         }
5117       break;
5118
5119     case 'U':
5120       if (! TARGET_GNU_AS && GET_CODE (x) == CONST_INT)
5121         {
5122           const char *prefix = "0x";
5123           if (INTVAL (x) & 0x80000000)
5124             {
5125               fprintf (file, "0xffffffff");
5126               prefix = "";
5127             }
5128           fprintf (file, "%s%x", prefix, (int) INTVAL (x) & 0xffffffff);
5129           return;
5130         }
5131       break;
5132
5133     case 'X':
5134       {
5135         unsigned int regno = REGNO (x);
5136         fprintf (file, "%s, %s", reg_names [regno], reg_names [regno + 1]);
5137       }
5138       return;
5139
5140     case 'r':
5141       /* If this operand is the constant zero, write it as register zero.
5142          Any register, zero, or CONST_INT value is OK here.  */
5143       if (GET_CODE (x) == REG)
5144         fputs (reg_names[REGNO (x)], file);
5145       else if (x == CONST0_RTX (GET_MODE (x)))
5146         fputs ("r0", file);
5147       else if (GET_CODE (x) == CONST_INT)
5148         output_addr_const (file, x);
5149       else
5150         output_operand_lossage ("invalid %%r value");
5151       return;
5152
5153     case 'v':
5154       gcc_assert (GET_CODE (x) == CONST_VECTOR);
5155       x = simplify_subreg (DImode, x, GET_MODE (x), 0);
5156       break;
5157
5158     case '+':
5159       {
5160         const char *which;
5161
5162         /* For conditional branches, returns or calls, substitute
5163            sptk, dptk, dpnt, or spnt for %s.  */
5164         x = find_reg_note (current_output_insn, REG_BR_PROB, 0);
5165         if (x)
5166           {
5167             int pred_val = INTVAL (XEXP (x, 0));
5168
5169             /* Guess top and bottom 10% statically predicted.  */
5170             if (pred_val < REG_BR_PROB_BASE / 50
5171                 && br_prob_note_reliable_p (x))
5172               which = ".spnt";
5173             else if (pred_val < REG_BR_PROB_BASE / 2)
5174               which = ".dpnt";
5175             else if (pred_val < REG_BR_PROB_BASE / 100 * 98
5176                      || !br_prob_note_reliable_p (x))
5177               which = ".dptk";
5178             else
5179               which = ".sptk";
5180           }
5181         else if (GET_CODE (current_output_insn) == CALL_INSN)
5182           which = ".sptk";
5183         else
5184           which = ".dptk";
5185
5186         fputs (which, file);
5187         return;
5188       }
5189
5190     case ',':
5191       x = current_insn_predicate;
5192       if (x)
5193         {
5194           unsigned int regno = REGNO (XEXP (x, 0));
5195           if (GET_CODE (x) == EQ)
5196             regno += 1;
5197           fprintf (file, "(%s) ", reg_names [regno]);
5198         }
5199       return;
5200
5201     default:
5202       output_operand_lossage ("ia64_print_operand: unknown code");
5203       return;
5204     }
5205
5206   switch (GET_CODE (x))
5207     {
5208       /* This happens for the spill/restore instructions.  */
5209     case POST_INC:
5210     case POST_DEC:
5211     case POST_MODIFY:
5212       x = XEXP (x, 0);
5213       /* ... fall through ...  */
5214
5215     case REG:
5216       fputs (reg_names [REGNO (x)], file);
5217       break;
5218
5219     case MEM:
5220       {
5221         rtx addr = XEXP (x, 0);
5222         if (GET_RTX_CLASS (GET_CODE (addr)) == RTX_AUTOINC)
5223           addr = XEXP (addr, 0);
5224         fprintf (file, "[%s]", reg_names [REGNO (addr)]);
5225         break;
5226       }
5227
5228     default:
5229       output_addr_const (file, x);
5230       break;
5231     }
5232
5233   return;
5234 }
5235 \f
5236 /* Compute a (partial) cost for rtx X.  Return true if the complete
5237    cost has been computed, and false if subexpressions should be
5238    scanned.  In either case, *TOTAL contains the cost result.  */
5239 /* ??? This is incomplete.  */
5240
5241 static bool
5242 ia64_rtx_costs (rtx x, int code, int outer_code, int *total,
5243                 bool speed ATTRIBUTE_UNUSED)
5244 {
5245   switch (code)
5246     {
5247     case CONST_INT:
5248       switch (outer_code)
5249         {
5250         case SET:
5251           *total = satisfies_constraint_J (x) ? 0 : COSTS_N_INSNS (1);
5252           return true;
5253         case PLUS:
5254           if (satisfies_constraint_I (x))
5255             *total = 0;
5256           else if (satisfies_constraint_J (x))
5257             *total = 1;
5258           else
5259             *total = COSTS_N_INSNS (1);
5260           return true;
5261         default:
5262           if (satisfies_constraint_K (x) || satisfies_constraint_L (x))
5263             *total = 0;
5264           else
5265             *total = COSTS_N_INSNS (1);
5266           return true;
5267         }
5268
5269     case CONST_DOUBLE:
5270       *total = COSTS_N_INSNS (1);
5271       return true;
5272
5273     case CONST:
5274     case SYMBOL_REF:
5275     case LABEL_REF:
5276       *total = COSTS_N_INSNS (3);
5277       return true;
5278
5279     case FMA:
5280       *total = COSTS_N_INSNS (4);
5281       return true;
5282
5283     case MULT:
5284       /* For multiplies wider than HImode, we have to go to the FPU,
5285          which normally involves copies.  Plus there's the latency
5286          of the multiply itself, and the latency of the instructions to
5287          transfer integer regs to FP regs.  */
5288       if (FLOAT_MODE_P (GET_MODE (x)))
5289         *total = COSTS_N_INSNS (4);
5290       else if (GET_MODE_SIZE (GET_MODE (x)) > 2)
5291         *total = COSTS_N_INSNS (10);
5292       else
5293         *total = COSTS_N_INSNS (2);
5294       return true;
5295
5296     case PLUS:
5297     case MINUS:
5298       if (FLOAT_MODE_P (GET_MODE (x)))
5299         {
5300           *total = COSTS_N_INSNS (4);
5301           return true;
5302         }
5303       /* FALLTHRU */
5304
5305     case ASHIFT:
5306     case ASHIFTRT:
5307     case LSHIFTRT:
5308       *total = COSTS_N_INSNS (1);
5309       return true;
5310
5311     case DIV:
5312     case UDIV:
5313     case MOD:
5314     case UMOD:
5315       /* We make divide expensive, so that divide-by-constant will be
5316          optimized to a multiply.  */
5317       *total = COSTS_N_INSNS (60);
5318       return true;
5319
5320     default:
5321       return false;
5322     }
5323 }
5324
5325 /* Calculate the cost of moving data from a register in class FROM to
5326    one in class TO, using MODE.  */
5327
5328 static int
5329 ia64_register_move_cost (enum machine_mode mode, reg_class_t from_i,
5330                          reg_class_t to_i)
5331 {
5332   enum reg_class from = (enum reg_class) from_i;
5333   enum reg_class to = (enum reg_class) to_i;
5334
5335   /* ADDL_REGS is the same as GR_REGS for movement purposes.  */
5336   if (to == ADDL_REGS)
5337     to = GR_REGS;
5338   if (from == ADDL_REGS)
5339     from = GR_REGS;
5340
5341   /* All costs are symmetric, so reduce cases by putting the
5342      lower number class as the destination.  */
5343   if (from < to)
5344     {
5345       enum reg_class tmp = to;
5346       to = from, from = tmp;
5347     }
5348
5349   /* Moving from FR<->GR in XFmode must be more expensive than 2,
5350      so that we get secondary memory reloads.  Between FR_REGS,
5351      we have to make this at least as expensive as memory_move_cost
5352      to avoid spectacularly poor register class preferencing.  */
5353   if (mode == XFmode || mode == RFmode)
5354     {
5355       if (to != GR_REGS || from != GR_REGS)
5356         return memory_move_cost (mode, to, false);
5357       else
5358         return 3;
5359     }
5360
5361   switch (to)
5362     {
5363     case PR_REGS:
5364       /* Moving between PR registers takes two insns.  */
5365       if (from == PR_REGS)
5366         return 3;
5367       /* Moving between PR and anything but GR is impossible.  */
5368       if (from != GR_REGS)
5369         return memory_move_cost (mode, to, false);
5370       break;
5371
5372     case BR_REGS:
5373       /* Moving between BR and anything but GR is impossible.  */
5374       if (from != GR_REGS && from != GR_AND_BR_REGS)
5375         return memory_move_cost (mode, to, false);
5376       break;
5377
5378     case AR_I_REGS:
5379     case AR_M_REGS:
5380       /* Moving between AR and anything but GR is impossible.  */
5381       if (from != GR_REGS)
5382         return memory_move_cost (mode, to, false);
5383       break;
5384
5385     case GR_REGS:
5386     case FR_REGS:
5387     case FP_REGS:
5388     case GR_AND_FR_REGS:
5389     case GR_AND_BR_REGS:
5390     case ALL_REGS:
5391       break;
5392
5393     default:
5394       gcc_unreachable ();
5395     }
5396
5397   return 2;
5398 }
5399
5400 /* Calculate the cost of moving data of MODE from a register to or from
5401    memory.  */
5402
5403 static int
5404 ia64_memory_move_cost (enum machine_mode mode ATTRIBUTE_UNUSED,
5405                        reg_class_t rclass,
5406                        bool in ATTRIBUTE_UNUSED)
5407 {
5408   if (rclass == GENERAL_REGS
5409       || rclass == FR_REGS
5410       || rclass == FP_REGS
5411       || rclass == GR_AND_FR_REGS)
5412     return 4;
5413   else
5414     return 10;
5415 }
5416
5417 /* Implement TARGET_PREFERRED_RELOAD_CLASS.  Place additional restrictions
5418    on RCLASS to use when copying X into that class.  */
5419
5420 static reg_class_t
5421 ia64_preferred_reload_class (rtx x, reg_class_t rclass)
5422 {
5423   switch (rclass)
5424     {
5425     case FR_REGS:
5426     case FP_REGS:
5427       /* Don't allow volatile mem reloads into floating point registers.
5428          This is defined to force reload to choose the r/m case instead
5429          of the f/f case when reloading (set (reg fX) (mem/v)).  */
5430       if (MEM_P (x) && MEM_VOLATILE_P (x))
5431         return NO_REGS;
5432       
5433       /* Force all unrecognized constants into the constant pool.  */
5434       if (CONSTANT_P (x))
5435         return NO_REGS;
5436       break;
5437
5438     case AR_M_REGS:
5439     case AR_I_REGS:
5440       if (!OBJECT_P (x))
5441         return NO_REGS;
5442       break;
5443
5444     default:
5445       break;
5446     }
5447
5448   return rclass;
5449 }
5450
5451 /* This function returns the register class required for a secondary
5452    register when copying between one of the registers in RCLASS, and X,
5453    using MODE.  A return value of NO_REGS means that no secondary register
5454    is required.  */
5455
5456 enum reg_class
5457 ia64_secondary_reload_class (enum reg_class rclass,
5458                              enum machine_mode mode ATTRIBUTE_UNUSED, rtx x)
5459 {
5460   int regno = -1;
5461
5462   if (GET_CODE (x) == REG || GET_CODE (x) == SUBREG)
5463     regno = true_regnum (x);
5464
5465   switch (rclass)
5466     {
5467     case BR_REGS:
5468     case AR_M_REGS:
5469     case AR_I_REGS:
5470       /* ??? BR<->BR register copies can happen due to a bad gcse/cse/global
5471          interaction.  We end up with two pseudos with overlapping lifetimes
5472          both of which are equiv to the same constant, and both which need
5473          to be in BR_REGS.  This seems to be a cse bug.  cse_basic_block_end
5474          changes depending on the path length, which means the qty_first_reg
5475          check in make_regs_eqv can give different answers at different times.
5476          At some point I'll probably need a reload_indi pattern to handle
5477          this.
5478
5479          We can also get GR_AND_FR_REGS to BR_REGS/AR_REGS copies, where we
5480          wound up with a FP register from GR_AND_FR_REGS.  Extend that to all
5481          non-general registers for good measure.  */
5482       if (regno >= 0 && ! GENERAL_REGNO_P (regno))
5483         return GR_REGS;
5484
5485       /* This is needed if a pseudo used as a call_operand gets spilled to a
5486          stack slot.  */
5487       if (GET_CODE (x) == MEM)
5488         return GR_REGS;
5489       break;
5490
5491     case FR_REGS:
5492     case FP_REGS:
5493       /* Need to go through general registers to get to other class regs.  */
5494       if (regno >= 0 && ! (FR_REGNO_P (regno) || GENERAL_REGNO_P (regno)))
5495         return GR_REGS;
5496
5497       /* This can happen when a paradoxical subreg is an operand to the
5498          muldi3 pattern.  */
5499       /* ??? This shouldn't be necessary after instruction scheduling is
5500          enabled, because paradoxical subregs are not accepted by
5501          register_operand when INSN_SCHEDULING is defined.  Or alternatively,
5502          stop the paradoxical subreg stupidity in the *_operand functions
5503          in recog.c.  */
5504       if (GET_CODE (x) == MEM
5505           && (GET_MODE (x) == SImode || GET_MODE (x) == HImode
5506               || GET_MODE (x) == QImode))
5507         return GR_REGS;
5508
5509       /* This can happen because of the ior/and/etc patterns that accept FP
5510          registers as operands.  If the third operand is a constant, then it
5511          needs to be reloaded into a FP register.  */
5512       if (GET_CODE (x) == CONST_INT)
5513         return GR_REGS;
5514
5515       /* This can happen because of register elimination in a muldi3 insn.
5516          E.g. `26107 * (unsigned long)&u'.  */
5517       if (GET_CODE (x) == PLUS)
5518         return GR_REGS;
5519       break;
5520
5521     case PR_REGS:
5522       /* ??? This happens if we cse/gcse a BImode value across a call,
5523          and the function has a nonlocal goto.  This is because global
5524          does not allocate call crossing pseudos to hard registers when
5525          crtl->has_nonlocal_goto is true.  This is relatively
5526          common for C++ programs that use exceptions.  To reproduce,
5527          return NO_REGS and compile libstdc++.  */
5528       if (GET_CODE (x) == MEM)
5529         return GR_REGS;
5530
5531       /* This can happen when we take a BImode subreg of a DImode value,
5532          and that DImode value winds up in some non-GR register.  */
5533       if (regno >= 0 && ! GENERAL_REGNO_P (regno) && ! PR_REGNO_P (regno))
5534         return GR_REGS;
5535       break;
5536
5537     default:
5538       break;
5539     }
5540
5541   return NO_REGS;
5542 }
5543
5544 \f
5545 /* Implement targetm.unspec_may_trap_p hook.  */
5546 static int
5547 ia64_unspec_may_trap_p (const_rtx x, unsigned flags)
5548 {
5549   if (GET_CODE (x) == UNSPEC)
5550     {
5551       switch (XINT (x, 1))
5552         {
5553         case UNSPEC_LDA:
5554         case UNSPEC_LDS:
5555         case UNSPEC_LDSA:
5556         case UNSPEC_LDCCLR:
5557         case UNSPEC_CHKACLR:
5558         case UNSPEC_CHKS:
5559           /* These unspecs are just wrappers.  */
5560           return may_trap_p_1 (XVECEXP (x, 0, 0), flags);
5561         }
5562     }
5563
5564   return default_unspec_may_trap_p (x, flags);
5565 }
5566
5567 \f
5568 /* Parse the -mfixed-range= option string.  */
5569
5570 static void
5571 fix_range (const char *const_str)
5572 {
5573   int i, first, last;
5574   char *str, *dash, *comma;
5575
5576   /* str must be of the form REG1'-'REG2{,REG1'-'REG} where REG1 and
5577      REG2 are either register names or register numbers.  The effect
5578      of this option is to mark the registers in the range from REG1 to
5579      REG2 as ``fixed'' so they won't be used by the compiler.  This is
5580      used, e.g., to ensure that kernel mode code doesn't use f32-f127.  */
5581
5582   i = strlen (const_str);
5583   str = (char *) alloca (i + 1);
5584   memcpy (str, const_str, i + 1);
5585
5586   while (1)
5587     {
5588       dash = strchr (str, '-');
5589       if (!dash)
5590         {
5591           warning (0, "value of -mfixed-range must have form REG1-REG2");
5592           return;
5593         }
5594       *dash = '\0';
5595
5596       comma = strchr (dash + 1, ',');
5597       if (comma)
5598         *comma = '\0';
5599
5600       first = decode_reg_name (str);
5601       if (first < 0)
5602         {
5603           warning (0, "unknown register name: %s", str);
5604           return;
5605         }
5606
5607       last = decode_reg_name (dash + 1);
5608       if (last < 0)
5609         {
5610           warning (0, "unknown register name: %s", dash + 1);
5611           return;
5612         }
5613
5614       *dash = '-';
5615
5616       if (first > last)
5617         {
5618           warning (0, "%s-%s is an empty range", str, dash + 1);
5619           return;
5620         }
5621
5622       for (i = first; i <= last; ++i)
5623         fixed_regs[i] = call_used_regs[i] = 1;
5624
5625       if (!comma)
5626         break;
5627
5628       *comma = ',';
5629       str = comma + 1;
5630     }
5631 }
5632
5633 /* Implement TARGET_HANDLE_OPTION.  */
5634
5635 static bool
5636 ia64_handle_option (size_t code, const char *arg, int value)
5637 {
5638   switch (code)
5639     {
5640     case OPT_mfixed_range_:
5641       fix_range (arg);
5642       return true;
5643
5644     case OPT_mtls_size_:
5645       if (value != 14 && value != 22 && value != 64)
5646         error ("bad value %<%s%> for -mtls-size= switch", arg);
5647       return true;
5648
5649     case OPT_mtune_:
5650       {
5651         static struct pta
5652           {
5653             const char *name;           /* processor name or nickname.  */
5654             enum processor_type processor;
5655           }
5656         const processor_alias_table[] =
5657           {
5658             {"itanium2", PROCESSOR_ITANIUM2},
5659             {"mckinley", PROCESSOR_ITANIUM2},
5660           };
5661         int const pta_size = ARRAY_SIZE (processor_alias_table);
5662         int i;
5663
5664         for (i = 0; i < pta_size; i++)
5665           if (!strcmp (arg, processor_alias_table[i].name))
5666             {
5667               ia64_tune = processor_alias_table[i].processor;
5668               break;
5669             }
5670         if (i == pta_size)
5671           error ("bad value %<%s%> for -mtune= switch", arg);
5672         return true;
5673       }
5674
5675     default:
5676       return true;
5677     }
5678 }
5679
5680 /* Implement TARGET_OPTION_OVERRIDE.  */
5681
5682 static void
5683 ia64_option_override (void)
5684 {
5685   if (TARGET_AUTO_PIC)
5686     target_flags |= MASK_CONST_GP;
5687
5688   /* Numerous experiment shows that IRA based loop pressure
5689      calculation works better for RTL loop invariant motion on targets
5690      with enough (>= 32) registers.  It is an expensive optimization.
5691      So it is on only for peak performance.  */
5692   if (optimize >= 3)
5693     flag_ira_loop_pressure = 1;
5694
5695
5696   ia64_section_threshold = (global_options_set.x_g_switch_value
5697                             ? g_switch_value
5698                             : IA64_DEFAULT_GVALUE);
5699
5700   init_machine_status = ia64_init_machine_status;
5701
5702   if (align_functions <= 0)
5703     align_functions = 64;
5704   if (align_loops <= 0)
5705     align_loops = 32;
5706   if (TARGET_ABI_OPEN_VMS)
5707     flag_no_common = 1;
5708
5709   ia64_override_options_after_change();
5710 }
5711
5712 /* Implement targetm.override_options_after_change.  */
5713
5714 static void
5715 ia64_override_options_after_change (void)
5716 {
5717   ia64_flag_schedule_insns2 = flag_schedule_insns_after_reload;
5718   flag_schedule_insns_after_reload = 0;
5719
5720   if (optimize >= 3
5721       && !global_options_set.x_flag_selective_scheduling
5722       && !global_options_set.x_flag_selective_scheduling2)
5723     {
5724       flag_selective_scheduling2 = 1;
5725       flag_sel_sched_pipelining = 1;
5726     }
5727   if (mflag_sched_control_spec == 2)
5728     {
5729       /* Control speculation is on by default for the selective scheduler,
5730          but not for the Haifa scheduler.  */
5731       mflag_sched_control_spec = flag_selective_scheduling2 ? 1 : 0;
5732     }
5733   if (flag_sel_sched_pipelining && flag_auto_inc_dec)
5734     {
5735       /* FIXME: remove this when we'd implement breaking autoinsns as
5736          a transformation.  */
5737       flag_auto_inc_dec = 0;
5738     }
5739 }
5740
5741 /* Initialize the record of emitted frame related registers.  */
5742
5743 void ia64_init_expanders (void)
5744 {
5745   memset (&emitted_frame_related_regs, 0, sizeof (emitted_frame_related_regs));
5746 }
5747
5748 static struct machine_function *
5749 ia64_init_machine_status (void)
5750 {
5751   return ggc_alloc_cleared_machine_function ();
5752 }
5753 \f
5754 static enum attr_itanium_class ia64_safe_itanium_class (rtx);
5755 static enum attr_type ia64_safe_type (rtx);
5756
5757 static enum attr_itanium_class
5758 ia64_safe_itanium_class (rtx insn)
5759 {
5760   if (recog_memoized (insn) >= 0)
5761     return get_attr_itanium_class (insn);
5762   else if (DEBUG_INSN_P (insn))
5763     return ITANIUM_CLASS_IGNORE;
5764   else
5765     return ITANIUM_CLASS_UNKNOWN;
5766 }
5767
5768 static enum attr_type
5769 ia64_safe_type (rtx insn)
5770 {
5771   if (recog_memoized (insn) >= 0)
5772     return get_attr_type (insn);
5773   else
5774     return TYPE_UNKNOWN;
5775 }
5776 \f
5777 /* The following collection of routines emit instruction group stop bits as
5778    necessary to avoid dependencies.  */
5779
5780 /* Need to track some additional registers as far as serialization is
5781    concerned so we can properly handle br.call and br.ret.  We could
5782    make these registers visible to gcc, but since these registers are
5783    never explicitly used in gcc generated code, it seems wasteful to
5784    do so (plus it would make the call and return patterns needlessly
5785    complex).  */
5786 #define REG_RP          (BR_REG (0))
5787 #define REG_AR_CFM      (FIRST_PSEUDO_REGISTER + 1)
5788 /* This is used for volatile asms which may require a stop bit immediately
5789    before and after them.  */
5790 #define REG_VOLATILE    (FIRST_PSEUDO_REGISTER + 2)
5791 #define AR_UNAT_BIT_0   (FIRST_PSEUDO_REGISTER + 3)
5792 #define NUM_REGS        (AR_UNAT_BIT_0 + 64)
5793
5794 /* For each register, we keep track of how it has been written in the
5795    current instruction group.
5796
5797    If a register is written unconditionally (no qualifying predicate),
5798    WRITE_COUNT is set to 2 and FIRST_PRED is ignored.
5799
5800    If a register is written if its qualifying predicate P is true, we
5801    set WRITE_COUNT to 1 and FIRST_PRED to P.  Later on, the same register
5802    may be written again by the complement of P (P^1) and when this happens,
5803    WRITE_COUNT gets set to 2.
5804
5805    The result of this is that whenever an insn attempts to write a register
5806    whose WRITE_COUNT is two, we need to issue an insn group barrier first.
5807
5808    If a predicate register is written by a floating-point insn, we set
5809    WRITTEN_BY_FP to true.
5810
5811    If a predicate register is written by an AND.ORCM we set WRITTEN_BY_AND
5812    to true; if it was written by an OR.ANDCM we set WRITTEN_BY_OR to true.  */
5813
5814 #if GCC_VERSION >= 4000
5815 #define RWS_FIELD_TYPE __extension__ unsigned short
5816 #else
5817 #define RWS_FIELD_TYPE unsigned int
5818 #endif
5819 struct reg_write_state
5820 {
5821   RWS_FIELD_TYPE write_count : 2;
5822   RWS_FIELD_TYPE first_pred : 10;
5823   RWS_FIELD_TYPE written_by_fp : 1;
5824   RWS_FIELD_TYPE written_by_and : 1;
5825   RWS_FIELD_TYPE written_by_or : 1;
5826 };
5827
5828 /* Cumulative info for the current instruction group.  */
5829 struct reg_write_state rws_sum[NUM_REGS];
5830 #ifdef ENABLE_CHECKING
5831 /* Bitmap whether a register has been written in the current insn.  */
5832 HARD_REG_ELT_TYPE rws_insn[(NUM_REGS + HOST_BITS_PER_WIDEST_FAST_INT - 1)
5833                            / HOST_BITS_PER_WIDEST_FAST_INT];
5834
5835 static inline void
5836 rws_insn_set (int regno)
5837 {
5838   gcc_assert (!TEST_HARD_REG_BIT (rws_insn, regno));
5839   SET_HARD_REG_BIT (rws_insn, regno);
5840 }
5841
5842 static inline int
5843 rws_insn_test (int regno)
5844 {
5845   return TEST_HARD_REG_BIT (rws_insn, regno);
5846 }
5847 #else
5848 /* When not checking, track just REG_AR_CFM and REG_VOLATILE.  */
5849 unsigned char rws_insn[2];
5850
5851 static inline void
5852 rws_insn_set (int regno)
5853 {
5854   if (regno == REG_AR_CFM)
5855     rws_insn[0] = 1;
5856   else if (regno == REG_VOLATILE)
5857     rws_insn[1] = 1;
5858 }
5859
5860 static inline int
5861 rws_insn_test (int regno)
5862 {
5863   if (regno == REG_AR_CFM)
5864     return rws_insn[0];
5865   if (regno == REG_VOLATILE)
5866     return rws_insn[1];
5867   return 0;
5868 }
5869 #endif
5870
5871 /* Indicates whether this is the first instruction after a stop bit,
5872    in which case we don't need another stop bit.  Without this,
5873    ia64_variable_issue will die when scheduling an alloc.  */
5874 static int first_instruction;
5875
5876 /* Misc flags needed to compute RAW/WAW dependencies while we are traversing
5877    RTL for one instruction.  */
5878 struct reg_flags
5879 {
5880   unsigned int is_write : 1;    /* Is register being written?  */
5881   unsigned int is_fp : 1;       /* Is register used as part of an fp op?  */
5882   unsigned int is_branch : 1;   /* Is register used as part of a branch?  */
5883   unsigned int is_and : 1;      /* Is register used as part of and.orcm?  */
5884   unsigned int is_or : 1;       /* Is register used as part of or.andcm?  */
5885   unsigned int is_sibcall : 1;  /* Is this a sibling or normal call?  */
5886 };
5887
5888 static void rws_update (int, struct reg_flags, int);
5889 static int rws_access_regno (int, struct reg_flags, int);
5890 static int rws_access_reg (rtx, struct reg_flags, int);
5891 static void update_set_flags (rtx, struct reg_flags *);
5892 static int set_src_needs_barrier (rtx, struct reg_flags, int);
5893 static int rtx_needs_barrier (rtx, struct reg_flags, int);
5894 static void init_insn_group_barriers (void);
5895 static int group_barrier_needed (rtx);
5896 static int safe_group_barrier_needed (rtx);
5897 static int in_safe_group_barrier;
5898
5899 /* Update *RWS for REGNO, which is being written by the current instruction,
5900    with predicate PRED, and associated register flags in FLAGS.  */
5901
5902 static void
5903 rws_update (int regno, struct reg_flags flags, int pred)
5904 {
5905   if (pred)
5906     rws_sum[regno].write_count++;
5907   else
5908     rws_sum[regno].write_count = 2;
5909   rws_sum[regno].written_by_fp |= flags.is_fp;
5910   /* ??? Not tracking and/or across differing predicates.  */
5911   rws_sum[regno].written_by_and = flags.is_and;
5912   rws_sum[regno].written_by_or = flags.is_or;
5913   rws_sum[regno].first_pred = pred;
5914 }
5915
5916 /* Handle an access to register REGNO of type FLAGS using predicate register
5917    PRED.  Update rws_sum array.  Return 1 if this access creates
5918    a dependency with an earlier instruction in the same group.  */
5919
5920 static int
5921 rws_access_regno (int regno, struct reg_flags flags, int pred)
5922 {
5923   int need_barrier = 0;
5924
5925   gcc_assert (regno < NUM_REGS);
5926
5927   if (! PR_REGNO_P (regno))
5928     flags.is_and = flags.is_or = 0;
5929
5930   if (flags.is_write)
5931     {
5932       int write_count;
5933
5934       rws_insn_set (regno);
5935       write_count = rws_sum[regno].write_count;
5936
5937       switch (write_count)
5938         {
5939         case 0:
5940           /* The register has not been written yet.  */
5941           if (!in_safe_group_barrier)
5942             rws_update (regno, flags, pred);
5943           break;
5944
5945         case 1:
5946           /* The register has been written via a predicate.  Treat
5947              it like a unconditional write and do not try to check
5948              for complementary pred reg in earlier write.  */
5949           if (flags.is_and && rws_sum[regno].written_by_and)
5950             ;
5951           else if (flags.is_or && rws_sum[regno].written_by_or)
5952             ;
5953           else
5954             need_barrier = 1;
5955           if (!in_safe_group_barrier)
5956             rws_update (regno, flags, pred);
5957           break;
5958
5959         case 2:
5960           /* The register has been unconditionally written already.  We
5961              need a barrier.  */
5962           if (flags.is_and && rws_sum[regno].written_by_and)
5963             ;
5964           else if (flags.is_or && rws_sum[regno].written_by_or)
5965             ;
5966           else
5967             need_barrier = 1;
5968           if (!in_safe_group_barrier)
5969             {
5970               rws_sum[regno].written_by_and = flags.is_and;
5971               rws_sum[regno].written_by_or = flags.is_or;
5972             }
5973           break;
5974
5975         default:
5976           gcc_unreachable ();
5977         }
5978     }
5979   else
5980     {
5981       if (flags.is_branch)
5982         {
5983           /* Branches have several RAW exceptions that allow to avoid
5984              barriers.  */
5985
5986           if (REGNO_REG_CLASS (regno) == BR_REGS || regno == AR_PFS_REGNUM)
5987             /* RAW dependencies on branch regs are permissible as long
5988                as the writer is a non-branch instruction.  Since we
5989                never generate code that uses a branch register written
5990                by a branch instruction, handling this case is
5991                easy.  */
5992             return 0;
5993
5994           if (REGNO_REG_CLASS (regno) == PR_REGS
5995               && ! rws_sum[regno].written_by_fp)
5996             /* The predicates of a branch are available within the
5997                same insn group as long as the predicate was written by
5998                something other than a floating-point instruction.  */
5999             return 0;
6000         }
6001
6002       if (flags.is_and && rws_sum[regno].written_by_and)
6003         return 0;
6004       if (flags.is_or && rws_sum[regno].written_by_or)
6005         return 0;
6006
6007       switch (rws_sum[regno].write_count)
6008         {
6009         case 0:
6010           /* The register has not been written yet.  */
6011           break;
6012
6013         case 1:
6014           /* The register has been written via a predicate, assume we
6015              need a barrier (don't check for complementary regs).  */
6016           need_barrier = 1;
6017           break;
6018
6019         case 2:
6020           /* The register has been unconditionally written already.  We
6021              need a barrier.  */
6022           need_barrier = 1;
6023           break;
6024
6025         default:
6026           gcc_unreachable ();
6027         }
6028     }
6029
6030   return need_barrier;
6031 }
6032
6033 static int
6034 rws_access_reg (rtx reg, struct reg_flags flags, int pred)
6035 {
6036   int regno = REGNO (reg);
6037   int n = HARD_REGNO_NREGS (REGNO (reg), GET_MODE (reg));
6038
6039   if (n == 1)
6040     return rws_access_regno (regno, flags, pred);
6041   else
6042     {
6043       int need_barrier = 0;
6044       while (--n >= 0)
6045         need_barrier |= rws_access_regno (regno + n, flags, pred);
6046       return need_barrier;
6047     }
6048 }
6049
6050 /* Examine X, which is a SET rtx, and update the flags, the predicate, and
6051    the condition, stored in *PFLAGS, *PPRED and *PCOND.  */
6052
6053 static void
6054 update_set_flags (rtx x, struct reg_flags *pflags)
6055 {
6056   rtx src = SET_SRC (x);
6057
6058   switch (GET_CODE (src))
6059     {
6060     case CALL:
6061       return;
6062
6063     case IF_THEN_ELSE:
6064       /* There are four cases here:
6065          (1) The destination is (pc), in which case this is a branch,
6066          nothing here applies.
6067          (2) The destination is ar.lc, in which case this is a
6068          doloop_end_internal,
6069          (3) The destination is an fp register, in which case this is
6070          an fselect instruction.
6071          (4) The condition has (unspec [(reg)] UNSPEC_LDC), in which case 
6072          this is a check load.
6073          In all cases, nothing we do in this function applies.  */
6074       return;
6075
6076     default:
6077       if (COMPARISON_P (src)
6078           && SCALAR_FLOAT_MODE_P (GET_MODE (XEXP (src, 0))))
6079         /* Set pflags->is_fp to 1 so that we know we're dealing
6080            with a floating point comparison when processing the
6081            destination of the SET.  */
6082         pflags->is_fp = 1;
6083
6084       /* Discover if this is a parallel comparison.  We only handle
6085          and.orcm and or.andcm at present, since we must retain a
6086          strict inverse on the predicate pair.  */
6087       else if (GET_CODE (src) == AND)
6088         pflags->is_and = 1;
6089       else if (GET_CODE (src) == IOR)
6090         pflags->is_or = 1;
6091
6092       break;
6093     }
6094 }
6095
6096 /* Subroutine of rtx_needs_barrier; this function determines whether the
6097    source of a given SET rtx found in X needs a barrier.  FLAGS and PRED
6098    are as in rtx_needs_barrier.  COND is an rtx that holds the condition
6099    for this insn.  */
6100
6101 static int
6102 set_src_needs_barrier (rtx x, struct reg_flags flags, int pred)
6103 {
6104   int need_barrier = 0;
6105   rtx dst;
6106   rtx src = SET_SRC (x);
6107
6108   if (GET_CODE (src) == CALL)
6109     /* We don't need to worry about the result registers that
6110        get written by subroutine call.  */
6111     return rtx_needs_barrier (src, flags, pred);
6112   else if (SET_DEST (x) == pc_rtx)
6113     {
6114       /* X is a conditional branch.  */
6115       /* ??? This seems redundant, as the caller sets this bit for
6116          all JUMP_INSNs.  */
6117       if (!ia64_spec_check_src_p (src))
6118         flags.is_branch = 1;
6119       return rtx_needs_barrier (src, flags, pred);
6120     }
6121
6122   if (ia64_spec_check_src_p (src))
6123     /* Avoid checking one register twice (in condition 
6124        and in 'then' section) for ldc pattern.  */
6125     {
6126       gcc_assert (REG_P (XEXP (src, 2)));
6127       need_barrier = rtx_needs_barrier (XEXP (src, 2), flags, pred);
6128                   
6129       /* We process MEM below.  */
6130       src = XEXP (src, 1);
6131     }
6132
6133   need_barrier |= rtx_needs_barrier (src, flags, pred);
6134
6135   dst = SET_DEST (x);
6136   if (GET_CODE (dst) == ZERO_EXTRACT)
6137     {
6138       need_barrier |= rtx_needs_barrier (XEXP (dst, 1), flags, pred);
6139       need_barrier |= rtx_needs_barrier (XEXP (dst, 2), flags, pred);
6140     }
6141   return need_barrier;
6142 }
6143
6144 /* Handle an access to rtx X of type FLAGS using predicate register
6145    PRED.  Return 1 if this access creates a dependency with an earlier
6146    instruction in the same group.  */
6147
6148 static int
6149 rtx_needs_barrier (rtx x, struct reg_flags flags, int pred)
6150 {
6151   int i, j;
6152   int is_complemented = 0;
6153   int need_barrier = 0;
6154   const char *format_ptr;
6155   struct reg_flags new_flags;
6156   rtx cond;
6157
6158   if (! x)
6159     return 0;
6160
6161   new_flags = flags;
6162
6163   switch (GET_CODE (x))
6164     {
6165     case SET:
6166       update_set_flags (x, &new_flags);
6167       need_barrier = set_src_needs_barrier (x, new_flags, pred);
6168       if (GET_CODE (SET_SRC (x)) != CALL)
6169         {
6170           new_flags.is_write = 1;
6171           need_barrier |= rtx_needs_barrier (SET_DEST (x), new_flags, pred);
6172         }
6173       break;
6174
6175     case CALL:
6176       new_flags.is_write = 0;
6177       need_barrier |= rws_access_regno (AR_EC_REGNUM, new_flags, pred);
6178
6179       /* Avoid multiple register writes, in case this is a pattern with
6180          multiple CALL rtx.  This avoids a failure in rws_access_reg.  */
6181       if (! flags.is_sibcall && ! rws_insn_test (REG_AR_CFM))
6182         {
6183           new_flags.is_write = 1;
6184           need_barrier |= rws_access_regno (REG_RP, new_flags, pred);
6185           need_barrier |= rws_access_regno (AR_PFS_REGNUM, new_flags, pred);
6186           need_barrier |= rws_access_regno (REG_AR_CFM, new_flags, pred);
6187         }
6188       break;
6189
6190     case COND_EXEC:
6191       /* X is a predicated instruction.  */
6192
6193       cond = COND_EXEC_TEST (x);
6194       gcc_assert (!pred);
6195       need_barrier = rtx_needs_barrier (cond, flags, 0);
6196
6197       if (GET_CODE (cond) == EQ)
6198         is_complemented = 1;
6199       cond = XEXP (cond, 0);
6200       gcc_assert (GET_CODE (cond) == REG
6201                   && REGNO_REG_CLASS (REGNO (cond)) == PR_REGS);
6202       pred = REGNO (cond);
6203       if (is_complemented)
6204         ++pred;
6205
6206       need_barrier |= rtx_needs_barrier (COND_EXEC_CODE (x), flags, pred);
6207       return need_barrier;
6208
6209     case CLOBBER:
6210     case USE:
6211       /* Clobber & use are for earlier compiler-phases only.  */
6212       break;
6213
6214     case ASM_OPERANDS:
6215     case ASM_INPUT:
6216       /* We always emit stop bits for traditional asms.  We emit stop bits
6217          for volatile extended asms if TARGET_VOL_ASM_STOP is true.  */
6218       if (GET_CODE (x) != ASM_OPERANDS
6219           || (MEM_VOLATILE_P (x) && TARGET_VOL_ASM_STOP))
6220         {
6221           /* Avoid writing the register multiple times if we have multiple
6222              asm outputs.  This avoids a failure in rws_access_reg.  */
6223           if (! rws_insn_test (REG_VOLATILE))
6224             {
6225               new_flags.is_write = 1;
6226               rws_access_regno (REG_VOLATILE, new_flags, pred);
6227             }
6228           return 1;
6229         }
6230
6231       /* For all ASM_OPERANDS, we must traverse the vector of input operands.
6232          We cannot just fall through here since then we would be confused
6233          by the ASM_INPUT rtx inside ASM_OPERANDS, which do not indicate
6234          traditional asms unlike their normal usage.  */
6235
6236       for (i = ASM_OPERANDS_INPUT_LENGTH (x) - 1; i >= 0; --i)
6237         if (rtx_needs_barrier (ASM_OPERANDS_INPUT (x, i), flags, pred))
6238           need_barrier = 1;
6239       break;
6240
6241     case PARALLEL:
6242       for (i = XVECLEN (x, 0) - 1; i >= 0; --i)
6243         {
6244           rtx pat = XVECEXP (x, 0, i);
6245           switch (GET_CODE (pat))
6246             {
6247             case SET:
6248               update_set_flags (pat, &new_flags);
6249               need_barrier |= set_src_needs_barrier (pat, new_flags, pred);
6250               break;
6251
6252             case USE:
6253             case CALL:
6254             case ASM_OPERANDS:
6255               need_barrier |= rtx_needs_barrier (pat, flags, pred);
6256               break;
6257
6258             case CLOBBER:
6259             case RETURN:
6260               break;
6261
6262             default:
6263               gcc_unreachable ();
6264             }
6265         }
6266       for (i = XVECLEN (x, 0) - 1; i >= 0; --i)
6267         {
6268           rtx pat = XVECEXP (x, 0, i);
6269           if (GET_CODE (pat) == SET)
6270             {
6271               if (GET_CODE (SET_SRC (pat)) != CALL)
6272                 {
6273                   new_flags.is_write = 1;
6274                   need_barrier |= rtx_needs_barrier (SET_DEST (pat), new_flags,
6275                                                      pred);
6276                 }
6277             }
6278           else if (GET_CODE (pat) == CLOBBER || GET_CODE (pat) == RETURN)
6279             need_barrier |= rtx_needs_barrier (pat, flags, pred);
6280         }
6281       break;
6282
6283     case SUBREG:
6284       need_barrier |= rtx_needs_barrier (SUBREG_REG (x), flags, pred);
6285       break;
6286     case REG:
6287       if (REGNO (x) == AR_UNAT_REGNUM)
6288         {
6289           for (i = 0; i < 64; ++i)
6290             need_barrier |= rws_access_regno (AR_UNAT_BIT_0 + i, flags, pred);
6291         }
6292       else
6293         need_barrier = rws_access_reg (x, flags, pred);
6294       break;
6295
6296     case MEM:
6297       /* Find the regs used in memory address computation.  */
6298       new_flags.is_write = 0;
6299       need_barrier = rtx_needs_barrier (XEXP (x, 0), new_flags, pred);
6300       break;
6301
6302     case CONST_INT:   case CONST_DOUBLE:  case CONST_VECTOR:
6303     case SYMBOL_REF:  case LABEL_REF:     case CONST:
6304       break;
6305
6306       /* Operators with side-effects.  */
6307     case POST_INC:    case POST_DEC:
6308       gcc_assert (GET_CODE (XEXP (x, 0)) == REG);
6309
6310       new_flags.is_write = 0;
6311       need_barrier  = rws_access_reg (XEXP (x, 0), new_flags, pred);
6312       new_flags.is_write = 1;
6313       need_barrier |= rws_access_reg (XEXP (x, 0), new_flags, pred);
6314       break;
6315
6316     case POST_MODIFY:
6317       gcc_assert (GET_CODE (XEXP (x, 0)) == REG);
6318
6319       new_flags.is_write = 0;
6320       need_barrier  = rws_access_reg (XEXP (x, 0), new_flags, pred);
6321       need_barrier |= rtx_needs_barrier (XEXP (x, 1), new_flags, pred);
6322       new_flags.is_write = 1;
6323       need_barrier |= rws_access_reg (XEXP (x, 0), new_flags, pred);
6324       break;
6325
6326       /* Handle common unary and binary ops for efficiency.  */
6327     case COMPARE:  case PLUS:    case MINUS:   case MULT:      case DIV:
6328     case MOD:      case UDIV:    case UMOD:    case AND:       case IOR:
6329     case XOR:      case ASHIFT:  case ROTATE:  case ASHIFTRT:  case LSHIFTRT:
6330     case ROTATERT: case SMIN:    case SMAX:    case UMIN:      case UMAX:
6331     case NE:       case EQ:      case GE:      case GT:        case LE:
6332     case LT:       case GEU:     case GTU:     case LEU:       case LTU:
6333       need_barrier = rtx_needs_barrier (XEXP (x, 0), new_flags, pred);
6334       need_barrier |= rtx_needs_barrier (XEXP (x, 1), new_flags, pred);
6335       break;
6336
6337     case NEG:      case NOT:            case SIGN_EXTEND:     case ZERO_EXTEND:
6338     case TRUNCATE: case FLOAT_EXTEND:   case FLOAT_TRUNCATE:  case FLOAT:
6339     case FIX:      case UNSIGNED_FLOAT: case UNSIGNED_FIX:    case ABS:
6340     case SQRT:     case FFS:            case POPCOUNT:
6341       need_barrier = rtx_needs_barrier (XEXP (x, 0), flags, pred);
6342       break;
6343
6344     case VEC_SELECT:
6345       /* VEC_SELECT's second argument is a PARALLEL with integers that
6346          describe the elements selected.  On ia64, those integers are
6347          always constants.  Avoid walking the PARALLEL so that we don't
6348          get confused with "normal" parallels and then die.  */
6349       need_barrier = rtx_needs_barrier (XEXP (x, 0), flags, pred);
6350       break;
6351
6352     case UNSPEC:
6353       switch (XINT (x, 1))
6354         {
6355         case UNSPEC_LTOFF_DTPMOD:
6356         case UNSPEC_LTOFF_DTPREL:
6357         case UNSPEC_DTPREL:
6358         case UNSPEC_LTOFF_TPREL:
6359         case UNSPEC_TPREL:
6360         case UNSPEC_PRED_REL_MUTEX:
6361         case UNSPEC_PIC_CALL:
6362         case UNSPEC_MF:
6363         case UNSPEC_FETCHADD_ACQ:
6364         case UNSPEC_BSP_VALUE:
6365         case UNSPEC_FLUSHRS:
6366         case UNSPEC_BUNDLE_SELECTOR:
6367           break;
6368
6369         case UNSPEC_GR_SPILL:
6370         case UNSPEC_GR_RESTORE:
6371           {
6372             HOST_WIDE_INT offset = INTVAL (XVECEXP (x, 0, 1));
6373             HOST_WIDE_INT bit = (offset >> 3) & 63;
6374
6375             need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
6376             new_flags.is_write = (XINT (x, 1) == UNSPEC_GR_SPILL);
6377             need_barrier |= rws_access_regno (AR_UNAT_BIT_0 + bit,
6378                                               new_flags, pred);
6379             break;
6380           }
6381
6382         case UNSPEC_FR_SPILL:
6383         case UNSPEC_FR_RESTORE:
6384         case UNSPEC_GETF_EXP:
6385         case UNSPEC_SETF_EXP:
6386         case UNSPEC_ADDP4:
6387         case UNSPEC_FR_SQRT_RECIP_APPROX:
6388         case UNSPEC_FR_SQRT_RECIP_APPROX_RES:
6389         case UNSPEC_LDA:
6390         case UNSPEC_LDS:
6391         case UNSPEC_LDS_A:
6392         case UNSPEC_LDSA:
6393         case UNSPEC_CHKACLR:
6394         case UNSPEC_CHKS:
6395           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
6396           break;
6397
6398         case UNSPEC_FR_RECIP_APPROX:
6399         case UNSPEC_SHRP:
6400         case UNSPEC_COPYSIGN:
6401         case UNSPEC_FR_RECIP_APPROX_RES:
6402           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 0), flags, pred);
6403           need_barrier |= rtx_needs_barrier (XVECEXP (x, 0, 1), flags, pred);
6404           break;
6405
6406         case UNSPEC_CMPXCHG_ACQ:
6407           need_barrier = rtx_needs_barrier (XVECEXP (x, 0, 1), flags, pred);
6408           need_barrier |= rtx_needs_barrier (XVECEXP (x, 0, 2), flags, pred);
6409           break;
6410
6411         default:
6412           gcc_unreachable ();
6413         }
6414       break;
6415
6416     case UNSPEC_VOLATILE:
6417       switch (XINT (x, 1))
6418         {
6419         case UNSPECV_ALLOC:
6420           /* Alloc must always be the first instruction of a group.
6421              We force this by always returning true.  */
6422           /* ??? We might get better scheduling if we explicitly check for
6423              input/local/output register dependencies, and modify the
6424              scheduler so that alloc is always reordered to the start of
6425              the current group.  We could then eliminate all of the
6426              first_instruction code.  */
6427           rws_access_regno (AR_PFS_REGNUM, flags, pred);
6428
6429           new_flags.is_write = 1;
6430           rws_access_regno (REG_AR_CFM, new_flags, pred);
6431           return 1;
6432
6433         case UNSPECV_SET_BSP:
6434           need_barrier = 1;
6435           break;
6436
6437         case UNSPECV_BLOCKAGE:
6438         case UNSPECV_INSN_GROUP_BARRIER:
6439         case UNSPECV_BREAK:
6440         case UNSPECV_PSAC_ALL:
6441         case UNSPECV_PSAC_NORMAL:
6442           return 0;
6443
6444         default:
6445           gcc_unreachable ();
6446         }
6447       break;
6448
6449     case RETURN:
6450       new_flags.is_write = 0;
6451       need_barrier  = rws_access_regno (REG_RP, flags, pred);
6452       need_barrier |= rws_access_regno (AR_PFS_REGNUM, flags, pred);
6453
6454       new_flags.is_write = 1;
6455       need_barrier |= rws_access_regno (AR_EC_REGNUM, new_flags, pred);
6456       need_barrier |= rws_access_regno (REG_AR_CFM, new_flags, pred);
6457       break;
6458
6459     default:
6460       format_ptr = GET_RTX_FORMAT (GET_CODE (x));
6461       for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
6462         switch (format_ptr[i])
6463           {
6464           case '0':     /* unused field */
6465           case 'i':     /* integer */
6466           case 'n':     /* note */
6467           case 'w':     /* wide integer */
6468           case 's':     /* pointer to string */
6469           case 'S':     /* optional pointer to string */
6470             break;
6471
6472           case 'e':
6473             if (rtx_needs_barrier (XEXP (x, i), flags, pred))
6474               need_barrier = 1;
6475             break;
6476
6477           case 'E':
6478             for (j = XVECLEN (x, i) - 1; j >= 0; --j)
6479               if (rtx_needs_barrier (XVECEXP (x, i, j), flags, pred))
6480                 need_barrier = 1;
6481             break;
6482
6483           default:
6484             gcc_unreachable ();
6485           }
6486       break;
6487     }
6488   return need_barrier;
6489 }
6490
6491 /* Clear out the state for group_barrier_needed at the start of a
6492    sequence of insns.  */
6493
6494 static void
6495 init_insn_group_barriers (void)
6496 {
6497   memset (rws_sum, 0, sizeof (rws_sum));
6498   first_instruction = 1;
6499 }
6500
6501 /* Given the current state, determine whether a group barrier (a stop bit) is
6502    necessary before INSN.  Return nonzero if so.  This modifies the state to
6503    include the effects of INSN as a side-effect.  */
6504
6505 static int
6506 group_barrier_needed (rtx insn)
6507 {
6508   rtx pat;
6509   int need_barrier = 0;
6510   struct reg_flags flags;
6511
6512   memset (&flags, 0, sizeof (flags));
6513   switch (GET_CODE (insn))
6514     {
6515     case NOTE:
6516     case DEBUG_INSN:
6517       break;
6518
6519     case BARRIER:
6520       /* A barrier doesn't imply an instruction group boundary.  */
6521       break;
6522
6523     case CODE_LABEL:
6524       memset (rws_insn, 0, sizeof (rws_insn));
6525       return 1;
6526
6527     case CALL_INSN:
6528       flags.is_branch = 1;
6529       flags.is_sibcall = SIBLING_CALL_P (insn);
6530       memset (rws_insn, 0, sizeof (rws_insn));
6531
6532       /* Don't bundle a call following another call.  */
6533       if ((pat = prev_active_insn (insn))
6534           && GET_CODE (pat) == CALL_INSN)
6535         {
6536           need_barrier = 1;
6537           break;
6538         }
6539
6540       need_barrier = rtx_needs_barrier (PATTERN (insn), flags, 0);
6541       break;
6542
6543     case JUMP_INSN:
6544       if (!ia64_spec_check_p (insn))
6545         flags.is_branch = 1;
6546
6547       /* Don't bundle a jump following a call.  */
6548       if ((pat = prev_active_insn (insn))
6549           && GET_CODE (pat) == CALL_INSN)
6550         {
6551           need_barrier = 1;
6552           break;
6553         }
6554       /* FALLTHRU */
6555
6556     case INSN:
6557       if (GET_CODE (PATTERN (insn)) == USE
6558           || GET_CODE (PATTERN (insn)) == CLOBBER)
6559         /* Don't care about USE and CLOBBER "insns"---those are used to
6560            indicate to the optimizer that it shouldn't get rid of
6561            certain operations.  */
6562         break;
6563
6564       pat = PATTERN (insn);
6565
6566       /* Ug.  Hack hacks hacked elsewhere.  */
6567       switch (recog_memoized (insn))
6568         {
6569           /* We play dependency tricks with the epilogue in order
6570              to get proper schedules.  Undo this for dv analysis.  */
6571         case CODE_FOR_epilogue_deallocate_stack:
6572         case CODE_FOR_prologue_allocate_stack:
6573           pat = XVECEXP (pat, 0, 0);
6574           break;
6575
6576           /* The pattern we use for br.cloop confuses the code above.
6577              The second element of the vector is representative.  */
6578         case CODE_FOR_doloop_end_internal:
6579           pat = XVECEXP (pat, 0, 1);
6580           break;
6581
6582           /* Doesn't generate code.  */
6583         case CODE_FOR_pred_rel_mutex:
6584         case CODE_FOR_prologue_use:
6585           return 0;
6586
6587         default:
6588           break;
6589         }
6590
6591       memset (rws_insn, 0, sizeof (rws_insn));
6592       need_barrier = rtx_needs_barrier (pat, flags, 0);
6593
6594       /* Check to see if the previous instruction was a volatile
6595          asm.  */
6596       if (! need_barrier)
6597         need_barrier = rws_access_regno (REG_VOLATILE, flags, 0);
6598
6599       break;
6600
6601     default:
6602       gcc_unreachable ();
6603     }
6604
6605   if (first_instruction && INSN_P (insn)
6606       && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
6607       && GET_CODE (PATTERN (insn)) != USE
6608       && GET_CODE (PATTERN (insn)) != CLOBBER)
6609     {
6610       need_barrier = 0;
6611       first_instruction = 0;
6612     }
6613
6614   return need_barrier;
6615 }
6616
6617 /* Like group_barrier_needed, but do not clobber the current state.  */
6618
6619 static int
6620 safe_group_barrier_needed (rtx insn)
6621 {
6622   int saved_first_instruction;
6623   int t;
6624
6625   saved_first_instruction = first_instruction;
6626   in_safe_group_barrier = 1;
6627
6628   t = group_barrier_needed (insn);
6629
6630   first_instruction = saved_first_instruction;
6631   in_safe_group_barrier = 0;
6632
6633   return t;
6634 }
6635
6636 /* Scan the current function and insert stop bits as necessary to
6637    eliminate dependencies.  This function assumes that a final
6638    instruction scheduling pass has been run which has already
6639    inserted most of the necessary stop bits.  This function only
6640    inserts new ones at basic block boundaries, since these are
6641    invisible to the scheduler.  */
6642
6643 static void
6644 emit_insn_group_barriers (FILE *dump)
6645 {
6646   rtx insn;
6647   rtx last_label = 0;
6648   int insns_since_last_label = 0;
6649
6650   init_insn_group_barriers ();
6651
6652   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
6653     {
6654       if (GET_CODE (insn) == CODE_LABEL)
6655         {
6656           if (insns_since_last_label)
6657             last_label = insn;
6658           insns_since_last_label = 0;
6659         }
6660       else if (GET_CODE (insn) == NOTE
6661                && NOTE_KIND (insn) == NOTE_INSN_BASIC_BLOCK)
6662         {
6663           if (insns_since_last_label)
6664             last_label = insn;
6665           insns_since_last_label = 0;
6666         }
6667       else if (GET_CODE (insn) == INSN
6668                && GET_CODE (PATTERN (insn)) == UNSPEC_VOLATILE
6669                && XINT (PATTERN (insn), 1) == UNSPECV_INSN_GROUP_BARRIER)
6670         {
6671           init_insn_group_barriers ();
6672           last_label = 0;
6673         }
6674       else if (NONDEBUG_INSN_P (insn))
6675         {
6676           insns_since_last_label = 1;
6677
6678           if (group_barrier_needed (insn))
6679             {
6680               if (last_label)
6681                 {
6682                   if (dump)
6683                     fprintf (dump, "Emitting stop before label %d\n",
6684                              INSN_UID (last_label));
6685                   emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), last_label);
6686                   insn = last_label;
6687
6688                   init_insn_group_barriers ();
6689                   last_label = 0;
6690                 }
6691             }
6692         }
6693     }
6694 }
6695
6696 /* Like emit_insn_group_barriers, but run if no final scheduling pass was run.
6697    This function has to emit all necessary group barriers.  */
6698
6699 static void
6700 emit_all_insn_group_barriers (FILE *dump ATTRIBUTE_UNUSED)
6701 {
6702   rtx insn;
6703
6704   init_insn_group_barriers ();
6705
6706   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
6707     {
6708       if (GET_CODE (insn) == BARRIER)
6709         {
6710           rtx last = prev_active_insn (insn);
6711
6712           if (! last)
6713             continue;
6714           if (GET_CODE (last) == JUMP_INSN
6715               && GET_CODE (PATTERN (last)) == ADDR_DIFF_VEC)
6716             last = prev_active_insn (last);
6717           if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
6718             emit_insn_after (gen_insn_group_barrier (GEN_INT (3)), last);
6719
6720           init_insn_group_barriers ();
6721         }
6722       else if (NONDEBUG_INSN_P (insn))
6723         {
6724           if (recog_memoized (insn) == CODE_FOR_insn_group_barrier)
6725             init_insn_group_barriers ();
6726           else if (group_barrier_needed (insn))
6727             {
6728               emit_insn_before (gen_insn_group_barrier (GEN_INT (3)), insn);
6729               init_insn_group_barriers ();
6730               group_barrier_needed (insn);
6731             }
6732         }
6733     }
6734 }
6735
6736 \f
6737
6738 /* Instruction scheduling support.  */
6739
6740 #define NR_BUNDLES 10
6741
6742 /* A list of names of all available bundles.  */
6743
6744 static const char *bundle_name [NR_BUNDLES] =
6745 {
6746   ".mii",
6747   ".mmi",
6748   ".mfi",
6749   ".mmf",
6750 #if NR_BUNDLES == 10
6751   ".bbb",
6752   ".mbb",
6753 #endif
6754   ".mib",
6755   ".mmb",
6756   ".mfb",
6757   ".mlx"
6758 };
6759
6760 /* Nonzero if we should insert stop bits into the schedule.  */
6761
6762 int ia64_final_schedule = 0;
6763
6764 /* Codes of the corresponding queried units: */
6765
6766 static int _0mii_, _0mmi_, _0mfi_, _0mmf_;
6767 static int _0bbb_, _0mbb_, _0mib_, _0mmb_, _0mfb_, _0mlx_;
6768
6769 static int _1mii_, _1mmi_, _1mfi_, _1mmf_;
6770 static int _1bbb_, _1mbb_, _1mib_, _1mmb_, _1mfb_, _1mlx_;
6771
6772 static int pos_1, pos_2, pos_3, pos_4, pos_5, pos_6;
6773
6774 /* The following variable value is an insn group barrier.  */
6775
6776 static rtx dfa_stop_insn;
6777
6778 /* The following variable value is the last issued insn.  */
6779
6780 static rtx last_scheduled_insn;
6781
6782 /* The following variable value is pointer to a DFA state used as
6783    temporary variable.  */
6784
6785 static state_t temp_dfa_state = NULL;
6786
6787 /* The following variable value is DFA state after issuing the last
6788    insn.  */
6789
6790 static state_t prev_cycle_state = NULL;
6791
6792 /* The following array element values are TRUE if the corresponding
6793    insn requires to add stop bits before it.  */
6794
6795 static char *stops_p = NULL;
6796
6797 /* The following variable is used to set up the mentioned above array.  */
6798
6799 static int stop_before_p = 0;
6800
6801 /* The following variable value is length of the arrays `clocks' and
6802    `add_cycles'. */
6803
6804 static int clocks_length;
6805
6806 /* The following variable value is number of data speculations in progress.  */
6807 static int pending_data_specs = 0;
6808
6809 /* Number of memory references on current and three future processor cycles.  */
6810 static char mem_ops_in_group[4];
6811
6812 /* Number of current processor cycle (from scheduler's point of view).  */
6813 static int current_cycle;
6814
6815 static rtx ia64_single_set (rtx);
6816 static void ia64_emit_insn_before (rtx, rtx);
6817
6818 /* Map a bundle number to its pseudo-op.  */
6819
6820 const char *
6821 get_bundle_name (int b)
6822 {
6823   return bundle_name[b];
6824 }
6825
6826
6827 /* Return the maximum number of instructions a cpu can issue.  */
6828
6829 static int
6830 ia64_issue_rate (void)
6831 {
6832   return 6;
6833 }
6834
6835 /* Helper function - like single_set, but look inside COND_EXEC.  */
6836
6837 static rtx
6838 ia64_single_set (rtx insn)
6839 {
6840   rtx x = PATTERN (insn), ret;
6841   if (GET_CODE (x) == COND_EXEC)
6842     x = COND_EXEC_CODE (x);
6843   if (GET_CODE (x) == SET)
6844     return x;
6845
6846   /* Special case here prologue_allocate_stack and epilogue_deallocate_stack.
6847      Although they are not classical single set, the second set is there just
6848      to protect it from moving past FP-relative stack accesses.  */
6849   switch (recog_memoized (insn))
6850     {
6851     case CODE_FOR_prologue_allocate_stack:
6852     case CODE_FOR_epilogue_deallocate_stack:
6853       ret = XVECEXP (x, 0, 0);
6854       break;
6855
6856     default:
6857       ret = single_set_2 (insn, x);
6858       break;
6859     }
6860
6861   return ret;
6862 }
6863
6864 /* Adjust the cost of a scheduling dependency.
6865    Return the new cost of a dependency of type DEP_TYPE or INSN on DEP_INSN.
6866    COST is the current cost, DW is dependency weakness.  */
6867 static int
6868 ia64_adjust_cost_2 (rtx insn, int dep_type1, rtx dep_insn, int cost, dw_t dw)
6869 {
6870   enum reg_note dep_type = (enum reg_note) dep_type1;
6871   enum attr_itanium_class dep_class;
6872   enum attr_itanium_class insn_class;
6873
6874   insn_class = ia64_safe_itanium_class (insn);
6875   dep_class = ia64_safe_itanium_class (dep_insn);
6876
6877   /* Treat true memory dependencies separately.  Ignore apparent true
6878      dependence between store and call (call has a MEM inside a SYMBOL_REF).  */
6879   if (dep_type == REG_DEP_TRUE
6880       && (dep_class == ITANIUM_CLASS_ST || dep_class == ITANIUM_CLASS_STF)
6881       && (insn_class == ITANIUM_CLASS_BR || insn_class == ITANIUM_CLASS_SCALL))
6882     return 0;
6883
6884   if (dw == MIN_DEP_WEAK)
6885     /* Store and load are likely to alias, use higher cost to avoid stall.  */
6886     return PARAM_VALUE (PARAM_SCHED_MEM_TRUE_DEP_COST);
6887   else if (dw > MIN_DEP_WEAK)
6888     {
6889       /* Store and load are less likely to alias.  */
6890       if (mflag_sched_fp_mem_deps_zero_cost && dep_class == ITANIUM_CLASS_STF)
6891         /* Assume there will be no cache conflict for floating-point data.
6892            For integer data, L1 conflict penalty is huge (17 cycles), so we
6893            never assume it will not cause a conflict.  */
6894         return 0;
6895       else
6896         return cost;
6897     }
6898
6899   if (dep_type != REG_DEP_OUTPUT)
6900     return cost;
6901
6902   if (dep_class == ITANIUM_CLASS_ST || dep_class == ITANIUM_CLASS_STF
6903       || insn_class == ITANIUM_CLASS_ST || insn_class == ITANIUM_CLASS_STF)
6904     return 0;
6905
6906   return cost;
6907 }
6908
6909 /* Like emit_insn_before, but skip cycle_display notes.
6910    ??? When cycle display notes are implemented, update this.  */
6911
6912 static void
6913 ia64_emit_insn_before (rtx insn, rtx before)
6914 {
6915   emit_insn_before (insn, before);
6916 }
6917
6918 /* The following function marks insns who produce addresses for load
6919    and store insns.  Such insns will be placed into M slots because it
6920    decrease latency time for Itanium1 (see function
6921    `ia64_produce_address_p' and the DFA descriptions).  */
6922
6923 static void
6924 ia64_dependencies_evaluation_hook (rtx head, rtx tail)
6925 {
6926   rtx insn, next, next_tail;
6927
6928   /* Before reload, which_alternative is not set, which means that
6929      ia64_safe_itanium_class will produce wrong results for (at least)
6930      move instructions.  */
6931   if (!reload_completed)
6932     return;
6933
6934   next_tail = NEXT_INSN (tail);
6935   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6936     if (INSN_P (insn))
6937       insn->call = 0;
6938   for (insn = head; insn != next_tail; insn = NEXT_INSN (insn))
6939     if (INSN_P (insn)
6940         && ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IALU)
6941       {
6942         sd_iterator_def sd_it;
6943         dep_t dep;
6944         bool has_mem_op_consumer_p = false;
6945
6946         FOR_EACH_DEP (insn, SD_LIST_FORW, sd_it, dep)
6947           {
6948             enum attr_itanium_class c;
6949
6950             if (DEP_TYPE (dep) != REG_DEP_TRUE)
6951               continue;
6952
6953             next = DEP_CON (dep);
6954             c = ia64_safe_itanium_class (next);
6955             if ((c == ITANIUM_CLASS_ST
6956                  || c == ITANIUM_CLASS_STF)
6957                 && ia64_st_address_bypass_p (insn, next))
6958               {
6959                 has_mem_op_consumer_p = true;
6960                 break;
6961               }
6962             else if ((c == ITANIUM_CLASS_LD
6963                       || c == ITANIUM_CLASS_FLD
6964                       || c == ITANIUM_CLASS_FLDP)
6965                      && ia64_ld_address_bypass_p (insn, next))
6966               {
6967                 has_mem_op_consumer_p = true;
6968                 break;
6969               }
6970           }
6971
6972         insn->call = has_mem_op_consumer_p;
6973       }
6974 }
6975
6976 /* We're beginning a new block.  Initialize data structures as necessary.  */
6977
6978 static void
6979 ia64_sched_init (FILE *dump ATTRIBUTE_UNUSED,
6980                  int sched_verbose ATTRIBUTE_UNUSED,
6981                  int max_ready ATTRIBUTE_UNUSED)
6982 {
6983 #ifdef ENABLE_CHECKING
6984   rtx insn;
6985
6986   if (!sel_sched_p () && reload_completed)
6987     for (insn = NEXT_INSN (current_sched_info->prev_head);
6988          insn != current_sched_info->next_tail;
6989          insn = NEXT_INSN (insn))
6990       gcc_assert (!SCHED_GROUP_P (insn));
6991 #endif
6992   last_scheduled_insn = NULL_RTX;
6993   init_insn_group_barriers ();
6994
6995   current_cycle = 0;
6996   memset (mem_ops_in_group, 0, sizeof (mem_ops_in_group));
6997 }
6998
6999 /* We're beginning a scheduling pass.  Check assertion.  */
7000
7001 static void
7002 ia64_sched_init_global (FILE *dump ATTRIBUTE_UNUSED,
7003                         int sched_verbose ATTRIBUTE_UNUSED,
7004                         int max_ready ATTRIBUTE_UNUSED)
7005 {  
7006   gcc_assert (pending_data_specs == 0);
7007 }
7008
7009 /* Scheduling pass is now finished.  Free/reset static variable.  */
7010 static void
7011 ia64_sched_finish_global (FILE *dump ATTRIBUTE_UNUSED,
7012                           int sched_verbose ATTRIBUTE_UNUSED)
7013 {
7014   gcc_assert (pending_data_specs == 0);
7015 }
7016
7017 /* Return TRUE if INSN is a load (either normal or speculative, but not a
7018    speculation check), FALSE otherwise.  */
7019 static bool
7020 is_load_p (rtx insn)
7021 {
7022   enum attr_itanium_class insn_class = ia64_safe_itanium_class (insn);
7023
7024   return
7025    ((insn_class == ITANIUM_CLASS_LD || insn_class == ITANIUM_CLASS_FLD)
7026     && get_attr_check_load (insn) == CHECK_LOAD_NO);
7027 }
7028
7029 /* If INSN is a memory reference, memoize it in MEM_OPS_IN_GROUP global array
7030    (taking account for 3-cycle cache reference postponing for stores: Intel
7031    Itanium 2 Reference Manual for Software Development and Optimization,
7032    6.7.3.1).  */
7033 static void
7034 record_memory_reference (rtx insn)
7035 {
7036   enum attr_itanium_class insn_class = ia64_safe_itanium_class (insn);
7037
7038   switch (insn_class) {
7039     case ITANIUM_CLASS_FLD:
7040     case ITANIUM_CLASS_LD:
7041       mem_ops_in_group[current_cycle % 4]++;
7042       break;
7043     case ITANIUM_CLASS_STF:
7044     case ITANIUM_CLASS_ST:
7045       mem_ops_in_group[(current_cycle + 3) % 4]++;
7046       break;
7047     default:;
7048   }
7049 }
7050
7051 /* We are about to being issuing insns for this clock cycle.
7052    Override the default sort algorithm to better slot instructions.  */
7053
7054 static int
7055 ia64_dfa_sched_reorder (FILE *dump, int sched_verbose, rtx *ready,
7056                         int *pn_ready, int clock_var,
7057                         int reorder_type)
7058 {
7059   int n_asms;
7060   int n_ready = *pn_ready;
7061   rtx *e_ready = ready + n_ready;
7062   rtx *insnp;
7063
7064   if (sched_verbose)
7065     fprintf (dump, "// ia64_dfa_sched_reorder (type %d):\n", reorder_type);
7066
7067   if (reorder_type == 0)
7068     {
7069       /* First, move all USEs, CLOBBERs and other crud out of the way.  */
7070       n_asms = 0;
7071       for (insnp = ready; insnp < e_ready; insnp++)
7072         if (insnp < e_ready)
7073           {
7074             rtx insn = *insnp;
7075             enum attr_type t = ia64_safe_type (insn);
7076             if (t == TYPE_UNKNOWN)
7077               {
7078                 if (GET_CODE (PATTERN (insn)) == ASM_INPUT
7079                     || asm_noperands (PATTERN (insn)) >= 0)
7080                   {
7081                     rtx lowest = ready[n_asms];
7082                     ready[n_asms] = insn;
7083                     *insnp = lowest;
7084                     n_asms++;
7085                   }
7086                 else
7087                   {
7088                     rtx highest = ready[n_ready - 1];
7089                     ready[n_ready - 1] = insn;
7090                     *insnp = highest;
7091                     return 1;
7092                   }
7093               }
7094           }
7095
7096       if (n_asms < n_ready)
7097         {
7098           /* Some normal insns to process.  Skip the asms.  */
7099           ready += n_asms;
7100           n_ready -= n_asms;
7101         }
7102       else if (n_ready > 0)
7103         return 1;
7104     }
7105
7106   if (ia64_final_schedule)
7107     {
7108       int deleted = 0;
7109       int nr_need_stop = 0;
7110
7111       for (insnp = ready; insnp < e_ready; insnp++)
7112         if (safe_group_barrier_needed (*insnp))
7113           nr_need_stop++;
7114
7115       if (reorder_type == 1 && n_ready == nr_need_stop)
7116         return 0;
7117       if (reorder_type == 0)
7118         return 1;
7119       insnp = e_ready;
7120       /* Move down everything that needs a stop bit, preserving
7121          relative order.  */
7122       while (insnp-- > ready + deleted)
7123         while (insnp >= ready + deleted)
7124           {
7125             rtx insn = *insnp;
7126             if (! safe_group_barrier_needed (insn))
7127               break;
7128             memmove (ready + 1, ready, (insnp - ready) * sizeof (rtx));
7129             *ready = insn;
7130             deleted++;
7131           }
7132       n_ready -= deleted;
7133       ready += deleted;
7134     }
7135
7136   current_cycle = clock_var;
7137   if (reload_completed && mem_ops_in_group[clock_var % 4] >= ia64_max_memory_insns)
7138     {
7139       int moved = 0;
7140
7141       insnp = e_ready;
7142       /* Move down loads/stores, preserving relative order.  */
7143       while (insnp-- > ready + moved)
7144         while (insnp >= ready + moved)
7145           {
7146             rtx insn = *insnp;
7147             if (! is_load_p (insn))
7148               break;
7149             memmove (ready + 1, ready, (insnp - ready) * sizeof (rtx));
7150             *ready = insn;
7151             moved++;
7152           }
7153       n_ready -= moved;
7154       ready += moved;
7155     }
7156
7157   return 1;
7158 }
7159
7160 /* We are about to being issuing insns for this clock cycle.  Override
7161    the default sort algorithm to better slot instructions.  */
7162
7163 static int
7164 ia64_sched_reorder (FILE *dump, int sched_verbose, rtx *ready, int *pn_ready,
7165                     int clock_var)
7166 {
7167   return ia64_dfa_sched_reorder (dump, sched_verbose, ready,
7168                                  pn_ready, clock_var, 0);
7169 }
7170
7171 /* Like ia64_sched_reorder, but called after issuing each insn.
7172    Override the default sort algorithm to better slot instructions.  */
7173
7174 static int
7175 ia64_sched_reorder2 (FILE *dump ATTRIBUTE_UNUSED,
7176                      int sched_verbose ATTRIBUTE_UNUSED, rtx *ready,
7177                      int *pn_ready, int clock_var)
7178 {
7179   return ia64_dfa_sched_reorder (dump, sched_verbose, ready, pn_ready,
7180                                  clock_var, 1);
7181 }
7182
7183 /* We are about to issue INSN.  Return the number of insns left on the
7184    ready queue that can be issued this cycle.  */
7185
7186 static int
7187 ia64_variable_issue (FILE *dump ATTRIBUTE_UNUSED,
7188                      int sched_verbose ATTRIBUTE_UNUSED,
7189                      rtx insn ATTRIBUTE_UNUSED,
7190                      int can_issue_more ATTRIBUTE_UNUSED)
7191 {
7192   if (sched_deps_info->generate_spec_deps && !sel_sched_p ())
7193     /* Modulo scheduling does not extend h_i_d when emitting
7194        new instructions.  Don't use h_i_d, if we don't have to.  */
7195     {
7196       if (DONE_SPEC (insn) & BEGIN_DATA)
7197         pending_data_specs++;
7198       if (CHECK_SPEC (insn) & BEGIN_DATA)
7199         pending_data_specs--;
7200     }
7201
7202   if (DEBUG_INSN_P (insn))
7203     return 1;
7204
7205   last_scheduled_insn = insn;
7206   memcpy (prev_cycle_state, curr_state, dfa_state_size);
7207   if (reload_completed)
7208     {
7209       int needed = group_barrier_needed (insn);
7210       
7211       gcc_assert (!needed);
7212       if (GET_CODE (insn) == CALL_INSN)
7213         init_insn_group_barriers ();
7214       stops_p [INSN_UID (insn)] = stop_before_p;
7215       stop_before_p = 0;
7216
7217       record_memory_reference (insn);
7218     }
7219   return 1;
7220 }
7221
7222 /* We are choosing insn from the ready queue.  Return nonzero if INSN
7223    can be chosen.  */
7224
7225 static int
7226 ia64_first_cycle_multipass_dfa_lookahead_guard (rtx insn)
7227 {
7228   gcc_assert (insn && INSN_P (insn));
7229   return ((!reload_completed
7230            || !safe_group_barrier_needed (insn))
7231           && ia64_first_cycle_multipass_dfa_lookahead_guard_spec (insn)
7232           && (!mflag_sched_mem_insns_hard_limit
7233               || !is_load_p (insn)
7234               || mem_ops_in_group[current_cycle % 4] < ia64_max_memory_insns));
7235 }
7236
7237 /* We are choosing insn from the ready queue.  Return nonzero if INSN
7238    can be chosen.  */
7239
7240 static bool
7241 ia64_first_cycle_multipass_dfa_lookahead_guard_spec (const_rtx insn)
7242 {
7243   gcc_assert (insn  && INSN_P (insn));
7244   /* Size of ALAT is 32.  As far as we perform conservative data speculation,
7245      we keep ALAT half-empty.  */
7246   return (pending_data_specs < 16
7247           || !(TODO_SPEC (insn) & BEGIN_DATA));
7248 }
7249
7250 /* The following variable value is pseudo-insn used by the DFA insn
7251    scheduler to change the DFA state when the simulated clock is
7252    increased.  */
7253
7254 static rtx dfa_pre_cycle_insn;
7255
7256 /* Returns 1 when a meaningful insn was scheduled between the last group
7257    barrier and LAST.  */
7258 static int
7259 scheduled_good_insn (rtx last)
7260 {
7261   if (last && recog_memoized (last) >= 0)
7262     return 1;
7263
7264   for ( ;
7265        last != NULL && !NOTE_INSN_BASIC_BLOCK_P (last)
7266        && !stops_p[INSN_UID (last)];
7267        last = PREV_INSN (last))
7268     /* We could hit a NOTE_INSN_DELETED here which is actually outside
7269        the ebb we're scheduling.  */
7270     if (INSN_P (last) && recog_memoized (last) >= 0)
7271       return 1;
7272
7273   return 0;
7274 }
7275
7276 /* We are about to being issuing INSN.  Return nonzero if we cannot
7277    issue it on given cycle CLOCK and return zero if we should not sort
7278    the ready queue on the next clock start.  */
7279
7280 static int
7281 ia64_dfa_new_cycle (FILE *dump, int verbose, rtx insn, int last_clock,
7282                     int clock, int *sort_p)
7283 {
7284   gcc_assert (insn && INSN_P (insn));
7285
7286   if (DEBUG_INSN_P (insn))
7287     return 0;
7288
7289   /* When a group barrier is needed for insn, last_scheduled_insn
7290      should be set.  */
7291   gcc_assert (!(reload_completed && safe_group_barrier_needed (insn))
7292               || last_scheduled_insn);
7293
7294   if ((reload_completed
7295        && (safe_group_barrier_needed (insn)
7296            || (mflag_sched_stop_bits_after_every_cycle
7297                && last_clock != clock
7298                && last_scheduled_insn
7299                && scheduled_good_insn (last_scheduled_insn))))
7300       || (last_scheduled_insn
7301           && (GET_CODE (last_scheduled_insn) == CALL_INSN
7302               || GET_CODE (PATTERN (last_scheduled_insn)) == ASM_INPUT
7303               || asm_noperands (PATTERN (last_scheduled_insn)) >= 0)))
7304     {
7305       init_insn_group_barriers ();
7306
7307       if (verbose && dump)
7308         fprintf (dump, "//    Stop should be before %d%s\n", INSN_UID (insn),
7309                  last_clock == clock ? " + cycle advance" : "");
7310
7311       stop_before_p = 1;
7312       current_cycle = clock;
7313       mem_ops_in_group[current_cycle % 4] = 0;
7314
7315       if (last_clock == clock)
7316         {
7317           state_transition (curr_state, dfa_stop_insn);
7318           if (TARGET_EARLY_STOP_BITS)
7319             *sort_p = (last_scheduled_insn == NULL_RTX
7320                        || GET_CODE (last_scheduled_insn) != CALL_INSN);
7321           else
7322             *sort_p = 0;
7323           return 1;
7324         }
7325
7326       if (last_scheduled_insn)
7327         {
7328           if (GET_CODE (PATTERN (last_scheduled_insn)) == ASM_INPUT
7329               || asm_noperands (PATTERN (last_scheduled_insn)) >= 0)
7330             state_reset (curr_state);
7331           else
7332             {
7333               memcpy (curr_state, prev_cycle_state, dfa_state_size);
7334               state_transition (curr_state, dfa_stop_insn);
7335               state_transition (curr_state, dfa_pre_cycle_insn);
7336               state_transition (curr_state, NULL);
7337             }
7338         }
7339     }
7340   return 0;
7341 }
7342
7343 /* Implement targetm.sched.h_i_d_extended hook.
7344    Extend internal data structures.  */
7345 static void
7346 ia64_h_i_d_extended (void)
7347 {
7348   if (stops_p != NULL) 
7349     {
7350       int new_clocks_length = get_max_uid () * 3 / 2;
7351       stops_p = (char *) xrecalloc (stops_p, new_clocks_length, clocks_length, 1);
7352       clocks_length = new_clocks_length;
7353     }
7354 }
7355 \f
7356
7357 /* This structure describes the data used by the backend to guide scheduling.
7358    When the current scheduling point is switched, this data should be saved
7359    and restored later, if the scheduler returns to this point.  */
7360 struct _ia64_sched_context
7361 {
7362   state_t prev_cycle_state;
7363   rtx last_scheduled_insn;
7364   struct reg_write_state rws_sum[NUM_REGS];
7365   struct reg_write_state rws_insn[NUM_REGS];
7366   int first_instruction;
7367   int pending_data_specs;
7368   int current_cycle;
7369   char mem_ops_in_group[4];
7370 };
7371 typedef struct _ia64_sched_context *ia64_sched_context_t;
7372
7373 /* Allocates a scheduling context.  */
7374 static void *
7375 ia64_alloc_sched_context (void)
7376 {
7377   return xmalloc (sizeof (struct _ia64_sched_context));
7378 }
7379
7380 /* Initializes the _SC context with clean data, if CLEAN_P, and from
7381    the global context otherwise.  */
7382 static void
7383 ia64_init_sched_context (void *_sc, bool clean_p)
7384 {
7385   ia64_sched_context_t sc = (ia64_sched_context_t) _sc;
7386
7387   sc->prev_cycle_state = xmalloc (dfa_state_size);
7388   if (clean_p)
7389     {
7390       state_reset (sc->prev_cycle_state);
7391       sc->last_scheduled_insn = NULL_RTX;
7392       memset (sc->rws_sum, 0, sizeof (rws_sum));
7393       memset (sc->rws_insn, 0, sizeof (rws_insn));
7394       sc->first_instruction = 1;
7395       sc->pending_data_specs = 0;
7396       sc->current_cycle = 0;
7397       memset (sc->mem_ops_in_group, 0, sizeof (mem_ops_in_group));
7398     }
7399   else
7400     {
7401       memcpy (sc->prev_cycle_state, prev_cycle_state, dfa_state_size);
7402       sc->last_scheduled_insn = last_scheduled_insn;
7403       memcpy (sc->rws_sum, rws_sum, sizeof (rws_sum));
7404       memcpy (sc->rws_insn, rws_insn, sizeof (rws_insn));
7405       sc->first_instruction = first_instruction;
7406       sc->pending_data_specs = pending_data_specs;
7407       sc->current_cycle = current_cycle;
7408       memcpy (sc->mem_ops_in_group, mem_ops_in_group, sizeof (mem_ops_in_group));
7409     }
7410 }
7411
7412 /* Sets the global scheduling context to the one pointed to by _SC.  */
7413 static void
7414 ia64_set_sched_context (void *_sc)
7415 {
7416   ia64_sched_context_t sc = (ia64_sched_context_t) _sc;
7417
7418   gcc_assert (sc != NULL);
7419
7420   memcpy (prev_cycle_state, sc->prev_cycle_state, dfa_state_size);
7421   last_scheduled_insn = sc->last_scheduled_insn;
7422   memcpy (rws_sum, sc->rws_sum, sizeof (rws_sum));
7423   memcpy (rws_insn, sc->rws_insn, sizeof (rws_insn));
7424   first_instruction = sc->first_instruction;
7425   pending_data_specs = sc->pending_data_specs;
7426   current_cycle = sc->current_cycle;
7427   memcpy (mem_ops_in_group, sc->mem_ops_in_group, sizeof (mem_ops_in_group));
7428 }
7429
7430 /* Clears the data in the _SC scheduling context.  */
7431 static void
7432 ia64_clear_sched_context (void *_sc)
7433 {
7434   ia64_sched_context_t sc = (ia64_sched_context_t) _sc;
7435   
7436   free (sc->prev_cycle_state);
7437   sc->prev_cycle_state = NULL;
7438 }
7439
7440 /* Frees the _SC scheduling context.  */
7441 static void
7442 ia64_free_sched_context (void *_sc)
7443 {
7444   gcc_assert (_sc != NULL);
7445
7446   free (_sc);
7447 }
7448
7449 typedef rtx (* gen_func_t) (rtx, rtx);
7450
7451 /* Return a function that will generate a load of mode MODE_NO
7452    with speculation types TS.  */
7453 static gen_func_t
7454 get_spec_load_gen_function (ds_t ts, int mode_no)
7455 {
7456   static gen_func_t gen_ld_[] = {
7457     gen_movbi,
7458     gen_movqi_internal,
7459     gen_movhi_internal,
7460     gen_movsi_internal,
7461     gen_movdi_internal,
7462     gen_movsf_internal,
7463     gen_movdf_internal,
7464     gen_movxf_internal,
7465     gen_movti_internal,
7466     gen_zero_extendqidi2,
7467     gen_zero_extendhidi2,
7468     gen_zero_extendsidi2,
7469   };
7470
7471   static gen_func_t gen_ld_a[] = {
7472     gen_movbi_advanced,
7473     gen_movqi_advanced,
7474     gen_movhi_advanced,
7475     gen_movsi_advanced,
7476     gen_movdi_advanced,
7477     gen_movsf_advanced,
7478     gen_movdf_advanced,
7479     gen_movxf_advanced,
7480     gen_movti_advanced,
7481     gen_zero_extendqidi2_advanced,
7482     gen_zero_extendhidi2_advanced,
7483     gen_zero_extendsidi2_advanced,
7484   };
7485   static gen_func_t gen_ld_s[] = {
7486     gen_movbi_speculative,
7487     gen_movqi_speculative,
7488     gen_movhi_speculative,
7489     gen_movsi_speculative,
7490     gen_movdi_speculative,
7491     gen_movsf_speculative,
7492     gen_movdf_speculative,
7493     gen_movxf_speculative,
7494     gen_movti_speculative,
7495     gen_zero_extendqidi2_speculative,
7496     gen_zero_extendhidi2_speculative,
7497     gen_zero_extendsidi2_speculative,
7498   };
7499   static gen_func_t gen_ld_sa[] = {
7500     gen_movbi_speculative_advanced,
7501     gen_movqi_speculative_advanced,
7502     gen_movhi_speculative_advanced,
7503     gen_movsi_speculative_advanced,
7504     gen_movdi_speculative_advanced,
7505     gen_movsf_speculative_advanced,
7506     gen_movdf_speculative_advanced,
7507     gen_movxf_speculative_advanced,
7508     gen_movti_speculative_advanced,
7509     gen_zero_extendqidi2_speculative_advanced,
7510     gen_zero_extendhidi2_speculative_advanced,
7511     gen_zero_extendsidi2_speculative_advanced,
7512   };
7513   static gen_func_t gen_ld_s_a[] = {
7514     gen_movbi_speculative_a,
7515     gen_movqi_speculative_a,
7516     gen_movhi_speculative_a,
7517     gen_movsi_speculative_a,
7518     gen_movdi_speculative_a,
7519     gen_movsf_speculative_a,
7520     gen_movdf_speculative_a,
7521     gen_movxf_speculative_a,
7522     gen_movti_speculative_a,
7523     gen_zero_extendqidi2_speculative_a,
7524     gen_zero_extendhidi2_speculative_a,
7525     gen_zero_extendsidi2_speculative_a,
7526   };
7527
7528   gen_func_t *gen_ld;
7529
7530   if (ts & BEGIN_DATA)
7531     {
7532       if (ts & BEGIN_CONTROL)
7533         gen_ld = gen_ld_sa;
7534       else
7535         gen_ld = gen_ld_a;
7536     }
7537   else if (ts & BEGIN_CONTROL)
7538     {
7539       if ((spec_info->flags & SEL_SCHED_SPEC_DONT_CHECK_CONTROL)
7540           || ia64_needs_block_p (ts))
7541         gen_ld = gen_ld_s;
7542       else
7543         gen_ld = gen_ld_s_a;
7544     }
7545   else if (ts == 0)
7546     gen_ld = gen_ld_;
7547   else
7548     gcc_unreachable ();
7549
7550   return gen_ld[mode_no];
7551 }
7552
7553 /* Constants that help mapping 'enum machine_mode' to int.  */
7554 enum SPEC_MODES
7555   {
7556     SPEC_MODE_INVALID = -1,
7557     SPEC_MODE_FIRST = 0,
7558     SPEC_MODE_FOR_EXTEND_FIRST = 1,
7559     SPEC_MODE_FOR_EXTEND_LAST = 3,
7560     SPEC_MODE_LAST = 8
7561   };
7562
7563 enum
7564   {
7565     /* Offset to reach ZERO_EXTEND patterns.  */
7566     SPEC_GEN_EXTEND_OFFSET = SPEC_MODE_LAST - SPEC_MODE_FOR_EXTEND_FIRST + 1
7567   };
7568
7569 /* Return index of the MODE.  */
7570 static int
7571 ia64_mode_to_int (enum machine_mode mode)
7572 {
7573   switch (mode)
7574     {
7575     case BImode: return 0; /* SPEC_MODE_FIRST  */
7576     case QImode: return 1; /* SPEC_MODE_FOR_EXTEND_FIRST  */
7577     case HImode: return 2;
7578     case SImode: return 3; /* SPEC_MODE_FOR_EXTEND_LAST  */
7579     case DImode: return 4;
7580     case SFmode: return 5;
7581     case DFmode: return 6;
7582     case XFmode: return 7;
7583     case TImode:
7584       /* ??? This mode needs testing.  Bypasses for ldfp8 instruction are not
7585          mentioned in itanium[12].md.  Predicate fp_register_operand also
7586          needs to be defined.  Bottom line: better disable for now.  */
7587       return SPEC_MODE_INVALID;
7588     default:     return SPEC_MODE_INVALID;
7589     }
7590 }
7591
7592 /* Provide information about speculation capabilities.  */
7593 static void
7594 ia64_set_sched_flags (spec_info_t spec_info)
7595 {
7596   unsigned int *flags = &(current_sched_info->flags);
7597
7598   if (*flags & SCHED_RGN
7599       || *flags & SCHED_EBB
7600       || *flags & SEL_SCHED)
7601     {
7602       int mask = 0;
7603
7604       if ((mflag_sched_br_data_spec && !reload_completed && optimize > 0)
7605           || (mflag_sched_ar_data_spec && reload_completed))
7606         {
7607           mask |= BEGIN_DATA;
7608
7609           if (!sel_sched_p ()
7610               && ((mflag_sched_br_in_data_spec && !reload_completed)
7611                   || (mflag_sched_ar_in_data_spec && reload_completed)))
7612             mask |= BE_IN_DATA;
7613         }
7614       
7615       if (mflag_sched_control_spec
7616           && (!sel_sched_p ()
7617               || reload_completed))
7618         {
7619           mask |= BEGIN_CONTROL;
7620           
7621           if (!sel_sched_p () && mflag_sched_in_control_spec)
7622             mask |= BE_IN_CONTROL;
7623         }
7624
7625       spec_info->mask = mask;
7626
7627       if (mask)
7628         {
7629           *flags |= USE_DEPS_LIST | DO_SPECULATION;
7630
7631           if (mask & BE_IN_SPEC)
7632             *flags |= NEW_BBS;
7633           
7634           spec_info->flags = 0;
7635       
7636           if ((mask & DATA_SPEC) && mflag_sched_prefer_non_data_spec_insns)
7637             spec_info->flags |= PREFER_NON_DATA_SPEC;
7638
7639           if (mask & CONTROL_SPEC)
7640             {
7641               if (mflag_sched_prefer_non_control_spec_insns)
7642                 spec_info->flags |= PREFER_NON_CONTROL_SPEC;
7643
7644               if (sel_sched_p () && mflag_sel_sched_dont_check_control_spec)
7645                 spec_info->flags |= SEL_SCHED_SPEC_DONT_CHECK_CONTROL;
7646             }
7647
7648           if (sched_verbose >= 1)
7649             spec_info->dump = sched_dump;
7650           else
7651             spec_info->dump = 0;
7652           
7653           if (mflag_sched_count_spec_in_critical_path)
7654             spec_info->flags |= COUNT_SPEC_IN_CRITICAL_PATH;
7655         }
7656     }
7657   else
7658     spec_info->mask = 0;
7659 }
7660
7661 /* If INSN is an appropriate load return its mode.
7662    Return -1 otherwise.  */
7663 static int
7664 get_mode_no_for_insn (rtx insn)
7665 {
7666   rtx reg, mem, mode_rtx;
7667   int mode_no;
7668   bool extend_p;
7669
7670   extract_insn_cached (insn);
7671
7672   /* We use WHICH_ALTERNATIVE only after reload.  This will
7673      guarantee that reload won't touch a speculative insn.  */
7674
7675   if (recog_data.n_operands != 2)
7676     return -1;
7677
7678   reg = recog_data.operand[0];
7679   mem = recog_data.operand[1];
7680
7681   /* We should use MEM's mode since REG's mode in presence of
7682      ZERO_EXTEND will always be DImode.  */
7683   if (get_attr_speculable1 (insn) == SPECULABLE1_YES)
7684     /* Process non-speculative ld.  */
7685     {
7686       if (!reload_completed)
7687         {
7688           /* Do not speculate into regs like ar.lc.  */
7689           if (!REG_P (reg) || AR_REGNO_P (REGNO (reg)))
7690             return -1;
7691
7692           if (!MEM_P (mem))
7693             return -1;
7694
7695           {
7696             rtx mem_reg = XEXP (mem, 0);
7697
7698             if (!REG_P (mem_reg))
7699               return -1;
7700           }
7701
7702           mode_rtx = mem;
7703         }
7704       else if (get_attr_speculable2 (insn) == SPECULABLE2_YES)
7705         {
7706           gcc_assert (REG_P (reg) && MEM_P (mem));
7707           mode_rtx = mem;
7708         }
7709       else
7710         return -1;
7711     }
7712   else if (get_attr_data_speculative (insn) == DATA_SPECULATIVE_YES
7713            || get_attr_control_speculative (insn) == CONTROL_SPECULATIVE_YES
7714            || get_attr_check_load (insn) == CHECK_LOAD_YES)
7715     /* Process speculative ld or ld.c.  */
7716     {
7717       gcc_assert (REG_P (reg) && MEM_P (mem));
7718       mode_rtx = mem;
7719     }
7720   else
7721     {
7722       enum attr_itanium_class attr_class = get_attr_itanium_class (insn);
7723
7724       if (attr_class == ITANIUM_CLASS_CHK_A
7725           || attr_class == ITANIUM_CLASS_CHK_S_I
7726           || attr_class == ITANIUM_CLASS_CHK_S_F)
7727         /* Process chk.  */
7728         mode_rtx = reg;
7729       else
7730         return -1;
7731     }
7732
7733   mode_no = ia64_mode_to_int (GET_MODE (mode_rtx));
7734
7735   if (mode_no == SPEC_MODE_INVALID)
7736     return -1;
7737
7738   extend_p = (GET_MODE (reg) != GET_MODE (mode_rtx));
7739
7740   if (extend_p)
7741     {
7742       if (!(SPEC_MODE_FOR_EXTEND_FIRST <= mode_no
7743             && mode_no <= SPEC_MODE_FOR_EXTEND_LAST))
7744         return -1;
7745
7746       mode_no += SPEC_GEN_EXTEND_OFFSET;
7747     }
7748
7749   return mode_no;
7750 }
7751
7752 /* If X is an unspec part of a speculative load, return its code.
7753    Return -1 otherwise.  */
7754 static int
7755 get_spec_unspec_code (const_rtx x)
7756 {
7757   if (GET_CODE (x) != UNSPEC)
7758     return -1;
7759
7760   {
7761     int code;
7762
7763     code = XINT (x, 1);
7764
7765     switch (code)
7766       {
7767       case UNSPEC_LDA:
7768       case UNSPEC_LDS:
7769       case UNSPEC_LDS_A:
7770       case UNSPEC_LDSA:
7771         return code;
7772
7773       default:
7774         return -1;
7775       }
7776   }
7777 }
7778
7779 /* Implement skip_rtx_p hook.  */
7780 static bool
7781 ia64_skip_rtx_p (const_rtx x)
7782 {
7783   return get_spec_unspec_code (x) != -1;
7784 }
7785
7786 /* If INSN is a speculative load, return its UNSPEC code.
7787    Return -1 otherwise.  */
7788 static int
7789 get_insn_spec_code (const_rtx insn)
7790 {
7791   rtx pat, reg, mem;
7792
7793   pat = PATTERN (insn);
7794
7795   if (GET_CODE (pat) == COND_EXEC)
7796     pat = COND_EXEC_CODE (pat);
7797
7798   if (GET_CODE (pat) != SET)
7799     return -1;
7800
7801   reg = SET_DEST (pat);
7802   if (!REG_P (reg))
7803     return -1;
7804
7805   mem = SET_SRC (pat);
7806   if (GET_CODE (mem) == ZERO_EXTEND)
7807     mem = XEXP (mem, 0);
7808
7809   return get_spec_unspec_code (mem);
7810 }
7811
7812 /* If INSN is a speculative load, return a ds with the speculation types.
7813    Otherwise [if INSN is a normal instruction] return 0.  */
7814 static ds_t
7815 ia64_get_insn_spec_ds (rtx insn)
7816 {
7817   int code = get_insn_spec_code (insn);
7818
7819   switch (code)
7820     {
7821     case UNSPEC_LDA:
7822       return BEGIN_DATA;
7823
7824     case UNSPEC_LDS:
7825     case UNSPEC_LDS_A:
7826       return BEGIN_CONTROL;
7827
7828     case UNSPEC_LDSA:
7829       return BEGIN_DATA | BEGIN_CONTROL;
7830
7831     default:
7832       return 0;
7833     }
7834 }
7835
7836 /* If INSN is a speculative load return a ds with the speculation types that
7837    will be checked.
7838    Otherwise [if INSN is a normal instruction] return 0.  */
7839 static ds_t
7840 ia64_get_insn_checked_ds (rtx insn)
7841 {
7842   int code = get_insn_spec_code (insn);
7843
7844   switch (code)
7845     {
7846     case UNSPEC_LDA:
7847       return BEGIN_DATA | BEGIN_CONTROL;
7848
7849     case UNSPEC_LDS:
7850       return BEGIN_CONTROL;
7851
7852     case UNSPEC_LDS_A:
7853     case UNSPEC_LDSA:
7854       return BEGIN_DATA | BEGIN_CONTROL;
7855
7856     default:
7857       return 0;
7858     }
7859 }
7860
7861 /* If GEN_P is true, calculate the index of needed speculation check and return
7862    speculative pattern for INSN with speculative mode TS, machine mode
7863    MODE_NO and with ZERO_EXTEND (if EXTEND_P is true).
7864    If GEN_P is false, just calculate the index of needed speculation check.  */
7865 static rtx
7866 ia64_gen_spec_load (rtx insn, ds_t ts, int mode_no)
7867 {
7868   rtx pat, new_pat;
7869   gen_func_t gen_load;
7870
7871   gen_load = get_spec_load_gen_function (ts, mode_no);
7872
7873   new_pat = gen_load (copy_rtx (recog_data.operand[0]),
7874                       copy_rtx (recog_data.operand[1]));
7875
7876   pat = PATTERN (insn);
7877   if (GET_CODE (pat) == COND_EXEC)
7878     new_pat = gen_rtx_COND_EXEC (VOIDmode, copy_rtx (COND_EXEC_TEST (pat)),
7879                                  new_pat);
7880
7881   return new_pat;
7882 }
7883
7884 static bool
7885 insn_can_be_in_speculative_p (rtx insn ATTRIBUTE_UNUSED,
7886                               ds_t ds ATTRIBUTE_UNUSED)
7887 {
7888   return false;
7889 }
7890
7891 /* Implement targetm.sched.speculate_insn hook.
7892    Check if the INSN can be TS speculative.
7893    If 'no' - return -1.
7894    If 'yes' - generate speculative pattern in the NEW_PAT and return 1.
7895    If current pattern of the INSN already provides TS speculation,
7896    return 0.  */
7897 static int
7898 ia64_speculate_insn (rtx insn, ds_t ts, rtx *new_pat)
7899 {  
7900   int mode_no;
7901   int res;
7902   
7903   gcc_assert (!(ts & ~SPECULATIVE));
7904
7905   if (ia64_spec_check_p (insn))
7906     return -1;
7907
7908   if ((ts & BE_IN_SPEC)
7909       && !insn_can_be_in_speculative_p (insn, ts))
7910     return -1;
7911
7912   mode_no = get_mode_no_for_insn (insn);
7913
7914   if (mode_no != SPEC_MODE_INVALID)
7915     {
7916       if (ia64_get_insn_spec_ds (insn) == ds_get_speculation_types (ts))
7917         res = 0;
7918       else
7919         {
7920           res = 1;
7921           *new_pat = ia64_gen_spec_load (insn, ts, mode_no);
7922         }
7923     }
7924   else
7925     res = -1;
7926
7927   return res;
7928 }
7929
7930 /* Return a function that will generate a check for speculation TS with mode
7931    MODE_NO.
7932    If simple check is needed, pass true for SIMPLE_CHECK_P.
7933    If clearing check is needed, pass true for CLEARING_CHECK_P.  */
7934 static gen_func_t
7935 get_spec_check_gen_function (ds_t ts, int mode_no,
7936                              bool simple_check_p, bool clearing_check_p)
7937 {
7938   static gen_func_t gen_ld_c_clr[] = {
7939     gen_movbi_clr,
7940     gen_movqi_clr,
7941     gen_movhi_clr,
7942     gen_movsi_clr,
7943     gen_movdi_clr,
7944     gen_movsf_clr,
7945     gen_movdf_clr,
7946     gen_movxf_clr,
7947     gen_movti_clr,
7948     gen_zero_extendqidi2_clr,
7949     gen_zero_extendhidi2_clr,
7950     gen_zero_extendsidi2_clr,
7951   };
7952   static gen_func_t gen_ld_c_nc[] = {
7953     gen_movbi_nc,
7954     gen_movqi_nc,
7955     gen_movhi_nc,
7956     gen_movsi_nc,
7957     gen_movdi_nc,
7958     gen_movsf_nc,
7959     gen_movdf_nc,
7960     gen_movxf_nc,
7961     gen_movti_nc,
7962     gen_zero_extendqidi2_nc,
7963     gen_zero_extendhidi2_nc,
7964     gen_zero_extendsidi2_nc,
7965   };
7966   static gen_func_t gen_chk_a_clr[] = {
7967     gen_advanced_load_check_clr_bi,
7968     gen_advanced_load_check_clr_qi,
7969     gen_advanced_load_check_clr_hi,
7970     gen_advanced_load_check_clr_si,
7971     gen_advanced_load_check_clr_di,
7972     gen_advanced_load_check_clr_sf,
7973     gen_advanced_load_check_clr_df,
7974     gen_advanced_load_check_clr_xf,
7975     gen_advanced_load_check_clr_ti,
7976     gen_advanced_load_check_clr_di,
7977     gen_advanced_load_check_clr_di,
7978     gen_advanced_load_check_clr_di,
7979   };
7980   static gen_func_t gen_chk_a_nc[] = {
7981     gen_advanced_load_check_nc_bi,
7982     gen_advanced_load_check_nc_qi,
7983     gen_advanced_load_check_nc_hi,
7984     gen_advanced_load_check_nc_si,
7985     gen_advanced_load_check_nc_di,
7986     gen_advanced_load_check_nc_sf,
7987     gen_advanced_load_check_nc_df,
7988     gen_advanced_load_check_nc_xf,
7989     gen_advanced_load_check_nc_ti,
7990     gen_advanced_load_check_nc_di,
7991     gen_advanced_load_check_nc_di,
7992     gen_advanced_load_check_nc_di,
7993   };
7994   static gen_func_t gen_chk_s[] = {
7995     gen_speculation_check_bi,
7996     gen_speculation_check_qi,
7997     gen_speculation_check_hi,
7998     gen_speculation_check_si,
7999     gen_speculation_check_di,
8000     gen_speculation_check_sf,
8001     gen_speculation_check_df,
8002     gen_speculation_check_xf,
8003     gen_speculation_check_ti,
8004     gen_speculation_check_di,
8005     gen_speculation_check_di,
8006     gen_speculation_check_di,
8007   };
8008
8009   gen_func_t *gen_check;
8010
8011   if (ts & BEGIN_DATA)
8012     {
8013       /* We don't need recovery because even if this is ld.sa
8014          ALAT entry will be allocated only if NAT bit is set to zero.
8015          So it is enough to use ld.c here.  */
8016
8017       if (simple_check_p)
8018         {
8019           gcc_assert (mflag_sched_spec_ldc);
8020
8021           if (clearing_check_p)
8022             gen_check = gen_ld_c_clr;
8023           else
8024             gen_check = gen_ld_c_nc;
8025         }
8026       else
8027         {
8028           if (clearing_check_p)
8029             gen_check = gen_chk_a_clr;
8030           else
8031             gen_check = gen_chk_a_nc;
8032         }
8033     }
8034   else if (ts & BEGIN_CONTROL)
8035     {
8036       if (simple_check_p)
8037         /* We might want to use ld.sa -> ld.c instead of
8038            ld.s -> chk.s.  */
8039         {
8040           gcc_assert (!ia64_needs_block_p (ts));
8041
8042           if (clearing_check_p)
8043             gen_check = gen_ld_c_clr;
8044           else
8045             gen_check = gen_ld_c_nc;
8046         }
8047       else
8048         {
8049           gen_check = gen_chk_s;
8050         }
8051     }
8052   else
8053     gcc_unreachable ();
8054
8055   gcc_assert (mode_no >= 0);
8056   return gen_check[mode_no];
8057 }
8058
8059 /* Return nonzero, if INSN needs branchy recovery check.  */
8060 static bool
8061 ia64_needs_block_p (ds_t ts)
8062 {
8063   if (ts & BEGIN_DATA)
8064     return !mflag_sched_spec_ldc;
8065
8066   gcc_assert ((ts & BEGIN_CONTROL) != 0);
8067
8068   return !(mflag_sched_spec_control_ldc && mflag_sched_spec_ldc);
8069 }
8070
8071 /* Generate (or regenerate, if (MUTATE_P)) recovery check for INSN.
8072    If (LABEL != 0 || MUTATE_P), generate branchy recovery check.
8073    Otherwise, generate a simple check.  */
8074 static rtx
8075 ia64_gen_spec_check (rtx insn, rtx label, ds_t ds)
8076 {
8077   rtx op1, pat, check_pat;
8078   gen_func_t gen_check;
8079   int mode_no;
8080
8081   mode_no = get_mode_no_for_insn (insn);
8082   gcc_assert (mode_no >= 0);
8083
8084   if (label)
8085     op1 = label;
8086   else
8087     {
8088       gcc_assert (!ia64_needs_block_p (ds));
8089       op1 = copy_rtx (recog_data.operand[1]);
8090     }
8091       
8092   gen_check = get_spec_check_gen_function (ds, mode_no, label == NULL_RTX,
8093                                            true);
8094
8095   check_pat = gen_check (copy_rtx (recog_data.operand[0]), op1);
8096     
8097   pat = PATTERN (insn);
8098   if (GET_CODE (pat) == COND_EXEC)
8099     check_pat = gen_rtx_COND_EXEC (VOIDmode, copy_rtx (COND_EXEC_TEST (pat)),
8100                                    check_pat);
8101
8102   return check_pat;
8103 }
8104
8105 /* Return nonzero, if X is branchy recovery check.  */
8106 static int
8107 ia64_spec_check_p (rtx x)
8108 {
8109   x = PATTERN (x);
8110   if (GET_CODE (x) == COND_EXEC)
8111     x = COND_EXEC_CODE (x);
8112   if (GET_CODE (x) == SET)
8113     return ia64_spec_check_src_p (SET_SRC (x));
8114   return 0;
8115 }
8116
8117 /* Return nonzero, if SRC belongs to recovery check.  */
8118 static int
8119 ia64_spec_check_src_p (rtx src)
8120 {
8121   if (GET_CODE (src) == IF_THEN_ELSE)
8122     {
8123       rtx t;
8124
8125       t = XEXP (src, 0);
8126       if (GET_CODE (t) == NE)
8127         {
8128           t = XEXP (t, 0);          
8129
8130           if (GET_CODE (t) == UNSPEC)
8131             {
8132               int code;
8133               
8134               code = XINT (t, 1);
8135              
8136               if (code == UNSPEC_LDCCLR
8137                   || code == UNSPEC_LDCNC
8138                   || code == UNSPEC_CHKACLR
8139                   || code == UNSPEC_CHKANC
8140                   || code == UNSPEC_CHKS)
8141                 {
8142                   gcc_assert (code != 0);
8143                   return code;
8144                 }
8145             }
8146         }
8147     }
8148   return 0;
8149 }
8150 \f
8151
8152 /* The following page contains abstract data `bundle states' which are
8153    used for bundling insns (inserting nops and template generation).  */
8154
8155 /* The following describes state of insn bundling.  */
8156
8157 struct bundle_state
8158 {
8159   /* Unique bundle state number to identify them in the debugging
8160      output  */
8161   int unique_num;
8162   rtx insn;     /* corresponding insn, NULL for the 1st and the last state  */
8163   /* number nops before and after the insn  */
8164   short before_nops_num, after_nops_num;
8165   int insn_num; /* insn number (0 - for initial state, 1 - for the 1st
8166                    insn */
8167   int cost;     /* cost of the state in cycles */
8168   int accumulated_insns_num; /* number of all previous insns including
8169                                 nops.  L is considered as 2 insns */
8170   int branch_deviation; /* deviation of previous branches from 3rd slots  */
8171   int middle_bundle_stops; /* number of stop bits in the middle of bundles */
8172   struct bundle_state *next;  /* next state with the same insn_num  */
8173   struct bundle_state *originator; /* originator (previous insn state)  */
8174   /* All bundle states are in the following chain.  */
8175   struct bundle_state *allocated_states_chain;
8176   /* The DFA State after issuing the insn and the nops.  */
8177   state_t dfa_state;
8178 };
8179
8180 /* The following is map insn number to the corresponding bundle state.  */
8181
8182 static struct bundle_state **index_to_bundle_states;
8183
8184 /* The unique number of next bundle state.  */
8185
8186 static int bundle_states_num;
8187
8188 /* All allocated bundle states are in the following chain.  */
8189
8190 static struct bundle_state *allocated_bundle_states_chain;
8191
8192 /* All allocated but not used bundle states are in the following
8193    chain.  */
8194
8195 static struct bundle_state *free_bundle_state_chain;
8196
8197
8198 /* The following function returns a free bundle state.  */
8199
8200 static struct bundle_state *
8201 get_free_bundle_state (void)
8202 {
8203   struct bundle_state *result;
8204
8205   if (free_bundle_state_chain != NULL)
8206     {
8207       result = free_bundle_state_chain;
8208       free_bundle_state_chain = result->next;
8209     }
8210   else
8211     {
8212       result = XNEW (struct bundle_state);
8213       result->dfa_state = xmalloc (dfa_state_size);
8214       result->allocated_states_chain = allocated_bundle_states_chain;
8215       allocated_bundle_states_chain = result;
8216     }
8217   result->unique_num = bundle_states_num++;
8218   return result;
8219
8220 }
8221
8222 /* The following function frees given bundle state.  */
8223
8224 static void
8225 free_bundle_state (struct bundle_state *state)
8226 {
8227   state->next = free_bundle_state_chain;
8228   free_bundle_state_chain = state;
8229 }
8230
8231 /* Start work with abstract data `bundle states'.  */
8232
8233 static void
8234 initiate_bundle_states (void)
8235 {
8236   bundle_states_num = 0;
8237   free_bundle_state_chain = NULL;
8238   allocated_bundle_states_chain = NULL;
8239 }
8240
8241 /* Finish work with abstract data `bundle states'.  */
8242
8243 static void
8244 finish_bundle_states (void)
8245 {
8246   struct bundle_state *curr_state, *next_state;
8247
8248   for (curr_state = allocated_bundle_states_chain;
8249        curr_state != NULL;
8250        curr_state = next_state)
8251     {
8252       next_state = curr_state->allocated_states_chain;
8253       free (curr_state->dfa_state);
8254       free (curr_state);
8255     }
8256 }
8257
8258 /* Hash table of the bundle states.  The key is dfa_state and insn_num
8259    of the bundle states.  */
8260
8261 static htab_t bundle_state_table;
8262
8263 /* The function returns hash of BUNDLE_STATE.  */
8264
8265 static unsigned
8266 bundle_state_hash (const void *bundle_state)
8267 {
8268   const struct bundle_state *const state
8269     = (const struct bundle_state *) bundle_state;
8270   unsigned result, i;
8271
8272   for (result = i = 0; i < dfa_state_size; i++)
8273     result += (((unsigned char *) state->dfa_state) [i]
8274                << ((i % CHAR_BIT) * 3 + CHAR_BIT));
8275   return result + state->insn_num;
8276 }
8277
8278 /* The function returns nonzero if the bundle state keys are equal.  */
8279
8280 static int
8281 bundle_state_eq_p (const void *bundle_state_1, const void *bundle_state_2)
8282 {
8283   const struct bundle_state *const state1
8284     = (const struct bundle_state *) bundle_state_1;
8285   const struct bundle_state *const state2
8286     = (const struct bundle_state *) bundle_state_2;
8287
8288   return (state1->insn_num == state2->insn_num
8289           && memcmp (state1->dfa_state, state2->dfa_state,
8290                      dfa_state_size) == 0);
8291 }
8292
8293 /* The function inserts the BUNDLE_STATE into the hash table.  The
8294    function returns nonzero if the bundle has been inserted into the
8295    table.  The table contains the best bundle state with given key.  */
8296
8297 static int
8298 insert_bundle_state (struct bundle_state *bundle_state)
8299 {
8300   void **entry_ptr;
8301
8302   entry_ptr = htab_find_slot (bundle_state_table, bundle_state, INSERT);
8303   if (*entry_ptr == NULL)
8304     {
8305       bundle_state->next = index_to_bundle_states [bundle_state->insn_num];
8306       index_to_bundle_states [bundle_state->insn_num] = bundle_state;
8307       *entry_ptr = (void *) bundle_state;
8308       return TRUE;
8309     }
8310   else if (bundle_state->cost < ((struct bundle_state *) *entry_ptr)->cost
8311            || (bundle_state->cost == ((struct bundle_state *) *entry_ptr)->cost
8312                && (((struct bundle_state *)*entry_ptr)->accumulated_insns_num
8313                    > bundle_state->accumulated_insns_num
8314                    || (((struct bundle_state *)
8315                         *entry_ptr)->accumulated_insns_num
8316                        == bundle_state->accumulated_insns_num
8317                        && (((struct bundle_state *)
8318                             *entry_ptr)->branch_deviation
8319                            > bundle_state->branch_deviation
8320                            || (((struct bundle_state *)
8321                                 *entry_ptr)->branch_deviation
8322                                == bundle_state->branch_deviation
8323                                && ((struct bundle_state *)
8324                                    *entry_ptr)->middle_bundle_stops
8325                                > bundle_state->middle_bundle_stops))))))
8326
8327     {
8328       struct bundle_state temp;
8329
8330       temp = *(struct bundle_state *) *entry_ptr;
8331       *(struct bundle_state *) *entry_ptr = *bundle_state;
8332       ((struct bundle_state *) *entry_ptr)->next = temp.next;
8333       *bundle_state = temp;
8334     }
8335   return FALSE;
8336 }
8337
8338 /* Start work with the hash table.  */
8339
8340 static void
8341 initiate_bundle_state_table (void)
8342 {
8343   bundle_state_table = htab_create (50, bundle_state_hash, bundle_state_eq_p,
8344                                     (htab_del) 0);
8345 }
8346
8347 /* Finish work with the hash table.  */
8348
8349 static void
8350 finish_bundle_state_table (void)
8351 {
8352   htab_delete (bundle_state_table);
8353 }
8354
8355 \f
8356
8357 /* The following variable is a insn `nop' used to check bundle states
8358    with different number of inserted nops.  */
8359
8360 static rtx ia64_nop;
8361
8362 /* The following function tries to issue NOPS_NUM nops for the current
8363    state without advancing processor cycle.  If it failed, the
8364    function returns FALSE and frees the current state.  */
8365
8366 static int
8367 try_issue_nops (struct bundle_state *curr_state, int nops_num)
8368 {
8369   int i;
8370
8371   for (i = 0; i < nops_num; i++)
8372     if (state_transition (curr_state->dfa_state, ia64_nop) >= 0)
8373       {
8374         free_bundle_state (curr_state);
8375         return FALSE;
8376       }
8377   return TRUE;
8378 }
8379
8380 /* The following function tries to issue INSN for the current
8381    state without advancing processor cycle.  If it failed, the
8382    function returns FALSE and frees the current state.  */
8383
8384 static int
8385 try_issue_insn (struct bundle_state *curr_state, rtx insn)
8386 {
8387   if (insn && state_transition (curr_state->dfa_state, insn) >= 0)
8388     {
8389       free_bundle_state (curr_state);
8390       return FALSE;
8391     }
8392   return TRUE;
8393 }
8394
8395 /* The following function tries to issue BEFORE_NOPS_NUM nops and INSN
8396    starting with ORIGINATOR without advancing processor cycle.  If
8397    TRY_BUNDLE_END_P is TRUE, the function also/only (if
8398    ONLY_BUNDLE_END_P is TRUE) tries to issue nops to fill all bundle.
8399    If it was successful, the function creates new bundle state and
8400    insert into the hash table and into `index_to_bundle_states'.  */
8401
8402 static void
8403 issue_nops_and_insn (struct bundle_state *originator, int before_nops_num,
8404                      rtx insn, int try_bundle_end_p, int only_bundle_end_p)
8405 {
8406   struct bundle_state *curr_state;
8407
8408   curr_state = get_free_bundle_state ();
8409   memcpy (curr_state->dfa_state, originator->dfa_state, dfa_state_size);
8410   curr_state->insn = insn;
8411   curr_state->insn_num = originator->insn_num + 1;
8412   curr_state->cost = originator->cost;
8413   curr_state->originator = originator;
8414   curr_state->before_nops_num = before_nops_num;
8415   curr_state->after_nops_num = 0;
8416   curr_state->accumulated_insns_num
8417     = originator->accumulated_insns_num + before_nops_num;
8418   curr_state->branch_deviation = originator->branch_deviation;
8419   curr_state->middle_bundle_stops = originator->middle_bundle_stops;
8420   gcc_assert (insn);
8421   if (INSN_CODE (insn) == CODE_FOR_insn_group_barrier)
8422     {
8423       gcc_assert (GET_MODE (insn) != TImode);
8424       if (!try_issue_nops (curr_state, before_nops_num))
8425         return;
8426       if (!try_issue_insn (curr_state, insn))
8427         return;
8428       memcpy (temp_dfa_state, curr_state->dfa_state, dfa_state_size);
8429       if (curr_state->accumulated_insns_num % 3 != 0)
8430         curr_state->middle_bundle_stops++;
8431       if (state_transition (temp_dfa_state, dfa_pre_cycle_insn) >= 0
8432           && curr_state->accumulated_insns_num % 3 != 0)
8433         {
8434           free_bundle_state (curr_state);
8435           return;
8436         }
8437     }
8438   else if (GET_MODE (insn) != TImode)
8439     {
8440       if (!try_issue_nops (curr_state, before_nops_num))
8441         return;
8442       if (!try_issue_insn (curr_state, insn))
8443         return;
8444       curr_state->accumulated_insns_num++;
8445       gcc_assert (GET_CODE (PATTERN (insn)) != ASM_INPUT
8446                   && asm_noperands (PATTERN (insn)) < 0);
8447
8448       if (ia64_safe_type (insn) == TYPE_L)
8449         curr_state->accumulated_insns_num++;
8450     }
8451   else
8452     {
8453       /* If this is an insn that must be first in a group, then don't allow
8454          nops to be emitted before it.  Currently, alloc is the only such
8455          supported instruction.  */
8456       /* ??? The bundling automatons should handle this for us, but they do
8457          not yet have support for the first_insn attribute.  */
8458       if (before_nops_num > 0 && get_attr_first_insn (insn) == FIRST_INSN_YES)
8459         {
8460           free_bundle_state (curr_state);
8461           return;
8462         }
8463
8464       state_transition (curr_state->dfa_state, dfa_pre_cycle_insn);
8465       state_transition (curr_state->dfa_state, NULL);
8466       curr_state->cost++;
8467       if (!try_issue_nops (curr_state, before_nops_num))
8468         return;
8469       if (!try_issue_insn (curr_state, insn))
8470         return;
8471       curr_state->accumulated_insns_num++;
8472       if (GET_CODE (PATTERN (insn)) == ASM_INPUT
8473           || asm_noperands (PATTERN (insn)) >= 0)
8474         {
8475           /* Finish bundle containing asm insn.  */
8476           curr_state->after_nops_num
8477             = 3 - curr_state->accumulated_insns_num % 3;
8478           curr_state->accumulated_insns_num
8479             += 3 - curr_state->accumulated_insns_num % 3;
8480         }
8481       else if (ia64_safe_type (insn) == TYPE_L)
8482         curr_state->accumulated_insns_num++;
8483     }
8484   if (ia64_safe_type (insn) == TYPE_B)
8485     curr_state->branch_deviation
8486       += 2 - (curr_state->accumulated_insns_num - 1) % 3;
8487   if (try_bundle_end_p && curr_state->accumulated_insns_num % 3 != 0)
8488     {
8489       if (!only_bundle_end_p && insert_bundle_state (curr_state))
8490         {
8491           state_t dfa_state;
8492           struct bundle_state *curr_state1;
8493           struct bundle_state *allocated_states_chain;
8494
8495           curr_state1 = get_free_bundle_state ();
8496           dfa_state = curr_state1->dfa_state;
8497           allocated_states_chain = curr_state1->allocated_states_chain;
8498           *curr_state1 = *curr_state;
8499           curr_state1->dfa_state = dfa_state;
8500           curr_state1->allocated_states_chain = allocated_states_chain;
8501           memcpy (curr_state1->dfa_state, curr_state->dfa_state,
8502                   dfa_state_size);
8503           curr_state = curr_state1;
8504         }
8505       if (!try_issue_nops (curr_state,
8506                            3 - curr_state->accumulated_insns_num % 3))
8507         return;
8508       curr_state->after_nops_num
8509         = 3 - curr_state->accumulated_insns_num % 3;
8510       curr_state->accumulated_insns_num
8511         += 3 - curr_state->accumulated_insns_num % 3;
8512     }
8513   if (!insert_bundle_state (curr_state))
8514     free_bundle_state (curr_state);
8515   return;
8516 }
8517
8518 /* The following function returns position in the two window bundle
8519    for given STATE.  */
8520
8521 static int
8522 get_max_pos (state_t state)
8523 {
8524   if (cpu_unit_reservation_p (state, pos_6))
8525     return 6;
8526   else if (cpu_unit_reservation_p (state, pos_5))
8527     return 5;
8528   else if (cpu_unit_reservation_p (state, pos_4))
8529     return 4;
8530   else if (cpu_unit_reservation_p (state, pos_3))
8531     return 3;
8532   else if (cpu_unit_reservation_p (state, pos_2))
8533     return 2;
8534   else if (cpu_unit_reservation_p (state, pos_1))
8535     return 1;
8536   else
8537     return 0;
8538 }
8539
8540 /* The function returns code of a possible template for given position
8541    and state.  The function should be called only with 2 values of
8542    position equal to 3 or 6.  We avoid generating F NOPs by putting
8543    templates containing F insns at the end of the template search
8544    because undocumented anomaly in McKinley derived cores which can
8545    cause stalls if an F-unit insn (including a NOP) is issued within a
8546    six-cycle window after reading certain application registers (such
8547    as ar.bsp).  Furthermore, power-considerations also argue against
8548    the use of F-unit instructions unless they're really needed.  */
8549
8550 static int
8551 get_template (state_t state, int pos)
8552 {
8553   switch (pos)
8554     {
8555     case 3:
8556       if (cpu_unit_reservation_p (state, _0mmi_))
8557         return 1;
8558       else if (cpu_unit_reservation_p (state, _0mii_))
8559         return 0;
8560       else if (cpu_unit_reservation_p (state, _0mmb_))
8561         return 7;
8562       else if (cpu_unit_reservation_p (state, _0mib_))
8563         return 6;
8564       else if (cpu_unit_reservation_p (state, _0mbb_))
8565         return 5;
8566       else if (cpu_unit_reservation_p (state, _0bbb_))
8567         return 4;
8568       else if (cpu_unit_reservation_p (state, _0mmf_))
8569         return 3;
8570       else if (cpu_unit_reservation_p (state, _0mfi_))
8571         return 2;
8572       else if (cpu_unit_reservation_p (state, _0mfb_))
8573         return 8;
8574       else if (cpu_unit_reservation_p (state, _0mlx_))
8575         return 9;
8576       else
8577         gcc_unreachable ();
8578     case 6:
8579       if (cpu_unit_reservation_p (state, _1mmi_))
8580         return 1;
8581       else if (cpu_unit_reservation_p (state, _1mii_))
8582         return 0;
8583       else if (cpu_unit_reservation_p (state, _1mmb_))
8584         return 7;
8585       else if (cpu_unit_reservation_p (state, _1mib_))
8586         return 6;
8587       else if (cpu_unit_reservation_p (state, _1mbb_))
8588         return 5;
8589       else if (cpu_unit_reservation_p (state, _1bbb_))
8590         return 4;
8591       else if (_1mmf_ >= 0 && cpu_unit_reservation_p (state, _1mmf_))
8592         return 3;
8593       else if (cpu_unit_reservation_p (state, _1mfi_))
8594         return 2;
8595       else if (cpu_unit_reservation_p (state, _1mfb_))
8596         return 8;
8597       else if (cpu_unit_reservation_p (state, _1mlx_))
8598         return 9;
8599       else
8600         gcc_unreachable ();
8601     default:
8602       gcc_unreachable ();
8603     }
8604 }
8605
8606 /* True when INSN is important for bundling.  */
8607 static bool
8608 important_for_bundling_p (rtx insn)
8609 {
8610   return (INSN_P (insn)
8611           && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
8612           && GET_CODE (PATTERN (insn)) != USE
8613           && GET_CODE (PATTERN (insn)) != CLOBBER);
8614 }
8615
8616 /* The following function returns an insn important for insn bundling
8617    followed by INSN and before TAIL.  */
8618
8619 static rtx
8620 get_next_important_insn (rtx insn, rtx tail)
8621 {
8622   for (; insn && insn != tail; insn = NEXT_INSN (insn))
8623     if (important_for_bundling_p (insn))
8624       return insn;
8625   return NULL_RTX;
8626 }
8627
8628 /* Add a bundle selector TEMPLATE0 before INSN.  */
8629
8630 static void
8631 ia64_add_bundle_selector_before (int template0, rtx insn)
8632 {
8633   rtx b = gen_bundle_selector (GEN_INT (template0));
8634
8635   ia64_emit_insn_before (b, insn);
8636 #if NR_BUNDLES == 10
8637   if ((template0 == 4 || template0 == 5)
8638       && ia64_except_unwind_info () == UI_TARGET)
8639     {
8640       int i;
8641       rtx note = NULL_RTX;
8642
8643       /* In .mbb and .bbb bundles, check if CALL_INSN isn't in the
8644          first or second slot.  If it is and has REG_EH_NOTE set, copy it
8645          to following nops, as br.call sets rp to the address of following
8646          bundle and therefore an EH region end must be on a bundle
8647          boundary.  */
8648       insn = PREV_INSN (insn);
8649       for (i = 0; i < 3; i++)
8650         {
8651           do
8652             insn = next_active_insn (insn);
8653           while (GET_CODE (insn) == INSN
8654                  && get_attr_empty (insn) == EMPTY_YES);
8655           if (GET_CODE (insn) == CALL_INSN)
8656             note = find_reg_note (insn, REG_EH_REGION, NULL_RTX);
8657           else if (note)
8658             {
8659               int code;
8660
8661               gcc_assert ((code = recog_memoized (insn)) == CODE_FOR_nop
8662                           || code == CODE_FOR_nop_b);
8663               if (find_reg_note (insn, REG_EH_REGION, NULL_RTX))
8664                 note = NULL_RTX;
8665               else
8666                 add_reg_note (insn, REG_EH_REGION, XEXP (note, 0));
8667             }
8668         }
8669     }
8670 #endif
8671 }
8672
8673 /* The following function does insn bundling.  Bundling means
8674    inserting templates and nop insns to fit insn groups into permitted
8675    templates.  Instruction scheduling uses NDFA (non-deterministic
8676    finite automata) encoding informations about the templates and the
8677    inserted nops.  Nondeterminism of the automata permits follows
8678    all possible insn sequences very fast.
8679
8680    Unfortunately it is not possible to get information about inserting
8681    nop insns and used templates from the automata states.  The
8682    automata only says that we can issue an insn possibly inserting
8683    some nops before it and using some template.  Therefore insn
8684    bundling in this function is implemented by using DFA
8685    (deterministic finite automata).  We follow all possible insn
8686    sequences by inserting 0-2 nops (that is what the NDFA describe for
8687    insn scheduling) before/after each insn being bundled.  We know the
8688    start of simulated processor cycle from insn scheduling (insn
8689    starting a new cycle has TImode).
8690
8691    Simple implementation of insn bundling would create enormous
8692    number of possible insn sequences satisfying information about new
8693    cycle ticks taken from the insn scheduling.  To make the algorithm
8694    practical we use dynamic programming.  Each decision (about
8695    inserting nops and implicitly about previous decisions) is described
8696    by structure bundle_state (see above).  If we generate the same
8697    bundle state (key is automaton state after issuing the insns and
8698    nops for it), we reuse already generated one.  As consequence we
8699    reject some decisions which cannot improve the solution and
8700    reduce memory for the algorithm.
8701
8702    When we reach the end of EBB (extended basic block), we choose the
8703    best sequence and then, moving back in EBB, insert templates for
8704    the best alternative.  The templates are taken from querying
8705    automaton state for each insn in chosen bundle states.
8706
8707    So the algorithm makes two (forward and backward) passes through
8708    EBB.  */
8709
8710 static void
8711 bundling (FILE *dump, int verbose, rtx prev_head_insn, rtx tail)
8712 {
8713   struct bundle_state *curr_state, *next_state, *best_state;
8714   rtx insn, next_insn;
8715   int insn_num;
8716   int i, bundle_end_p, only_bundle_end_p, asm_p;
8717   int pos = 0, max_pos, template0, template1;
8718   rtx b;
8719   rtx nop;
8720   enum attr_type type;
8721
8722   insn_num = 0;
8723   /* Count insns in the EBB.  */
8724   for (insn = NEXT_INSN (prev_head_insn);
8725        insn && insn != tail;
8726        insn = NEXT_INSN (insn))
8727     if (INSN_P (insn))
8728       insn_num++;
8729   if (insn_num == 0)
8730     return;
8731   bundling_p = 1;
8732   dfa_clean_insn_cache ();
8733   initiate_bundle_state_table ();
8734   index_to_bundle_states = XNEWVEC (struct bundle_state *, insn_num + 2);
8735   /* First (forward) pass -- generation of bundle states.  */
8736   curr_state = get_free_bundle_state ();
8737   curr_state->insn = NULL;
8738   curr_state->before_nops_num = 0;
8739   curr_state->after_nops_num = 0;
8740   curr_state->insn_num = 0;
8741   curr_state->cost = 0;
8742   curr_state->accumulated_insns_num = 0;
8743   curr_state->branch_deviation = 0;
8744   curr_state->middle_bundle_stops = 0;
8745   curr_state->next = NULL;
8746   curr_state->originator = NULL;
8747   state_reset (curr_state->dfa_state);
8748   index_to_bundle_states [0] = curr_state;
8749   insn_num = 0;
8750   /* Shift cycle mark if it is put on insn which could be ignored.  */
8751   for (insn = NEXT_INSN (prev_head_insn);
8752        insn != tail;
8753        insn = NEXT_INSN (insn))
8754     if (INSN_P (insn)
8755         && (ia64_safe_itanium_class (insn) == ITANIUM_CLASS_IGNORE
8756             || GET_CODE (PATTERN (insn)) == USE
8757             || GET_CODE (PATTERN (insn)) == CLOBBER)
8758         && GET_MODE (insn) == TImode)
8759       {
8760         PUT_MODE (insn, VOIDmode);
8761         for (next_insn = NEXT_INSN (insn);
8762              next_insn != tail;
8763              next_insn = NEXT_INSN (next_insn))
8764           if (INSN_P (next_insn)
8765               && ia64_safe_itanium_class (next_insn) != ITANIUM_CLASS_IGNORE
8766               && GET_CODE (PATTERN (next_insn)) != USE
8767               && GET_CODE (PATTERN (next_insn)) != CLOBBER
8768               && INSN_CODE (next_insn) != CODE_FOR_insn_group_barrier)
8769             {
8770               PUT_MODE (next_insn, TImode);
8771               break;
8772             }
8773       }
8774   /* Forward pass: generation of bundle states.  */
8775   for (insn = get_next_important_insn (NEXT_INSN (prev_head_insn), tail);
8776        insn != NULL_RTX;
8777        insn = next_insn)
8778     {
8779       gcc_assert (INSN_P (insn)
8780                   && ia64_safe_itanium_class (insn) != ITANIUM_CLASS_IGNORE
8781                   && GET_CODE (PATTERN (insn)) != USE
8782                   && GET_CODE (PATTERN (insn)) != CLOBBER);
8783       type = ia64_safe_type (insn);
8784       next_insn = get_next_important_insn (NEXT_INSN (insn), tail);
8785       insn_num++;
8786       index_to_bundle_states [insn_num] = NULL;
8787       for (curr_state = index_to_bundle_states [insn_num - 1];
8788            curr_state != NULL;
8789            curr_state = next_state)
8790         {
8791           pos = curr_state->accumulated_insns_num % 3;
8792           next_state = curr_state->next;
8793           /* We must fill up the current bundle in order to start a
8794              subsequent asm insn in a new bundle.  Asm insn is always
8795              placed in a separate bundle.  */
8796           only_bundle_end_p
8797             = (next_insn != NULL_RTX
8798                && INSN_CODE (insn) == CODE_FOR_insn_group_barrier
8799                && ia64_safe_type (next_insn) == TYPE_UNKNOWN);
8800           /* We may fill up the current bundle if it is the cycle end
8801              without a group barrier.  */
8802           bundle_end_p
8803             = (only_bundle_end_p || next_insn == NULL_RTX
8804                || (GET_MODE (next_insn) == TImode
8805                    && INSN_CODE (insn) != CODE_FOR_insn_group_barrier));
8806           if (type == TYPE_F || type == TYPE_B || type == TYPE_L
8807               || type == TYPE_S)
8808             issue_nops_and_insn (curr_state, 2, insn, bundle_end_p,
8809                                  only_bundle_end_p);
8810           issue_nops_and_insn (curr_state, 1, insn, bundle_end_p,
8811                                only_bundle_end_p);
8812           issue_nops_and_insn (curr_state, 0, insn, bundle_end_p,
8813                                only_bundle_end_p);
8814         }
8815       gcc_assert (index_to_bundle_states [insn_num]);
8816       for (curr_state = index_to_bundle_states [insn_num];
8817            curr_state != NULL;
8818            curr_state = curr_state->next)
8819         if (verbose >= 2 && dump)
8820           {
8821             /* This structure is taken from generated code of the
8822                pipeline hazard recognizer (see file insn-attrtab.c).
8823                Please don't forget to change the structure if a new
8824                automaton is added to .md file.  */
8825             struct DFA_chip
8826             {
8827               unsigned short one_automaton_state;
8828               unsigned short oneb_automaton_state;
8829               unsigned short two_automaton_state;
8830               unsigned short twob_automaton_state;
8831             };
8832
8833             fprintf
8834               (dump,
8835                "//    Bundle state %d (orig %d, cost %d, nops %d/%d, insns %d, branch %d, mid.stops %d state %d) for %d\n",
8836                curr_state->unique_num,
8837                (curr_state->originator == NULL
8838                 ? -1 : curr_state->originator->unique_num),
8839                curr_state->cost,
8840                curr_state->before_nops_num, curr_state->after_nops_num,
8841                curr_state->accumulated_insns_num, curr_state->branch_deviation,
8842                curr_state->middle_bundle_stops,
8843                ((struct DFA_chip *) curr_state->dfa_state)->twob_automaton_state,
8844                INSN_UID (insn));
8845           }
8846     }
8847   
8848   /* We should find a solution because the 2nd insn scheduling has
8849      found one.  */
8850   gcc_assert (index_to_bundle_states [insn_num]);
8851   /* Find a state corresponding to the best insn sequence.  */
8852   best_state = NULL;
8853   for (curr_state = index_to_bundle_states [insn_num];
8854        curr_state != NULL;
8855        curr_state = curr_state->next)
8856     /* We are just looking at the states with fully filled up last
8857        bundle.  The first we prefer insn sequences with minimal cost
8858        then with minimal inserted nops and finally with branch insns
8859        placed in the 3rd slots.  */
8860     if (curr_state->accumulated_insns_num % 3 == 0
8861         && (best_state == NULL || best_state->cost > curr_state->cost
8862             || (best_state->cost == curr_state->cost
8863                 && (curr_state->accumulated_insns_num
8864                     < best_state->accumulated_insns_num
8865                     || (curr_state->accumulated_insns_num
8866                         == best_state->accumulated_insns_num
8867                         && (curr_state->branch_deviation
8868                             < best_state->branch_deviation
8869                             || (curr_state->branch_deviation
8870                                 == best_state->branch_deviation
8871                                 && curr_state->middle_bundle_stops
8872                                 < best_state->middle_bundle_stops)))))))
8873       best_state = curr_state;
8874   /* Second (backward) pass: adding nops and templates.  */
8875   gcc_assert (best_state);
8876   insn_num = best_state->before_nops_num;
8877   template0 = template1 = -1;
8878   for (curr_state = best_state;
8879        curr_state->originator != NULL;
8880        curr_state = curr_state->originator)
8881     {
8882       insn = curr_state->insn;
8883       asm_p = (GET_CODE (PATTERN (insn)) == ASM_INPUT
8884                || asm_noperands (PATTERN (insn)) >= 0);
8885       insn_num++;
8886       if (verbose >= 2 && dump)
8887         {
8888           struct DFA_chip
8889           {
8890             unsigned short one_automaton_state;
8891             unsigned short oneb_automaton_state;
8892             unsigned short two_automaton_state;
8893             unsigned short twob_automaton_state;
8894           };
8895
8896           fprintf
8897             (dump,
8898              "//    Best %d (orig %d, cost %d, nops %d/%d, insns %d, branch %d, mid.stops %d, state %d) for %d\n",
8899              curr_state->unique_num,
8900              (curr_state->originator == NULL
8901               ? -1 : curr_state->originator->unique_num),
8902              curr_state->cost,
8903              curr_state->before_nops_num, curr_state->after_nops_num,
8904              curr_state->accumulated_insns_num, curr_state->branch_deviation,
8905              curr_state->middle_bundle_stops,
8906              ((struct DFA_chip *) curr_state->dfa_state)->twob_automaton_state,
8907              INSN_UID (insn));
8908         }
8909       /* Find the position in the current bundle window.  The window can
8910          contain at most two bundles.  Two bundle window means that
8911          the processor will make two bundle rotation.  */
8912       max_pos = get_max_pos (curr_state->dfa_state);
8913       if (max_pos == 6
8914           /* The following (negative template number) means that the
8915              processor did one bundle rotation.  */
8916           || (max_pos == 3 && template0 < 0))
8917         {
8918           /* We are at the end of the window -- find template(s) for
8919              its bundle(s).  */
8920           pos = max_pos;
8921           if (max_pos == 3)
8922             template0 = get_template (curr_state->dfa_state, 3);
8923           else
8924             {
8925               template1 = get_template (curr_state->dfa_state, 3);
8926               template0 = get_template (curr_state->dfa_state, 6);
8927             }
8928         }
8929       if (max_pos > 3 && template1 < 0)
8930         /* It may happen when we have the stop inside a bundle.  */
8931         {
8932           gcc_assert (pos <= 3);
8933           template1 = get_template (curr_state->dfa_state, 3);
8934           pos += 3;
8935         }
8936       if (!asm_p)
8937         /* Emit nops after the current insn.  */
8938         for (i = 0; i < curr_state->after_nops_num; i++)
8939           {
8940             nop = gen_nop ();
8941             emit_insn_after (nop, insn);
8942             pos--;
8943             gcc_assert (pos >= 0);
8944             if (pos % 3 == 0)
8945               {
8946                 /* We are at the start of a bundle: emit the template
8947                    (it should be defined).  */
8948                 gcc_assert (template0 >= 0);
8949                 ia64_add_bundle_selector_before (template0, nop);
8950                 /* If we have two bundle window, we make one bundle
8951                    rotation.  Otherwise template0 will be undefined
8952                    (negative value).  */
8953                 template0 = template1;
8954                 template1 = -1;
8955               }
8956           }
8957       /* Move the position backward in the window.  Group barrier has
8958          no slot.  Asm insn takes all bundle.  */
8959       if (INSN_CODE (insn) != CODE_FOR_insn_group_barrier
8960           && GET_CODE (PATTERN (insn)) != ASM_INPUT
8961           && asm_noperands (PATTERN (insn)) < 0)
8962         pos--;
8963       /* Long insn takes 2 slots.  */
8964       if (ia64_safe_type (insn) == TYPE_L)
8965         pos--;
8966       gcc_assert (pos >= 0);
8967       if (pos % 3 == 0
8968           && INSN_CODE (insn) != CODE_FOR_insn_group_barrier
8969           && GET_CODE (PATTERN (insn)) != ASM_INPUT
8970           && asm_noperands (PATTERN (insn)) < 0)
8971         {
8972           /* The current insn is at the bundle start: emit the
8973              template.  */
8974           gcc_assert (template0 >= 0);
8975           ia64_add_bundle_selector_before (template0, insn);
8976           b = PREV_INSN (insn);
8977           insn = b;
8978           /* See comment above in analogous place for emitting nops
8979              after the insn.  */
8980           template0 = template1;
8981           template1 = -1;
8982         }
8983       /* Emit nops after the current insn.  */
8984       for (i = 0; i < curr_state->before_nops_num; i++)
8985         {
8986           nop = gen_nop ();
8987           ia64_emit_insn_before (nop, insn);
8988           nop = PREV_INSN (insn);
8989           insn = nop;
8990           pos--;
8991           gcc_assert (pos >= 0);
8992           if (pos % 3 == 0)
8993             {
8994               /* See comment above in analogous place for emitting nops
8995                  after the insn.  */
8996               gcc_assert (template0 >= 0);
8997               ia64_add_bundle_selector_before (template0, insn);
8998               b = PREV_INSN (insn);
8999               insn = b;
9000               template0 = template1;
9001               template1 = -1;
9002             }
9003         }
9004     }
9005
9006 #ifdef ENABLE_CHECKING
9007   {
9008     /* Assert right calculation of middle_bundle_stops.  */
9009     int num = best_state->middle_bundle_stops;
9010     bool start_bundle = true, end_bundle = false;
9011
9012     for (insn = NEXT_INSN (prev_head_insn);
9013          insn && insn != tail;
9014          insn = NEXT_INSN (insn))
9015       {
9016         if (!INSN_P (insn))
9017           continue;
9018         if (recog_memoized (insn) == CODE_FOR_bundle_selector)
9019           start_bundle = true;
9020         else
9021           {
9022             rtx next_insn;
9023
9024             for (next_insn = NEXT_INSN (insn);
9025                  next_insn && next_insn != tail;
9026                  next_insn = NEXT_INSN (next_insn))
9027               if (INSN_P (next_insn)
9028                   && (ia64_safe_itanium_class (next_insn)
9029                       != ITANIUM_CLASS_IGNORE
9030                       || recog_memoized (next_insn)
9031                       == CODE_FOR_bundle_selector)
9032                   && GET_CODE (PATTERN (next_insn)) != USE
9033                   && GET_CODE (PATTERN (next_insn)) != CLOBBER)
9034                 break;
9035
9036             end_bundle = next_insn == NULL_RTX
9037              || next_insn == tail
9038              || (INSN_P (next_insn)
9039                  && recog_memoized (next_insn)
9040                  == CODE_FOR_bundle_selector);
9041             if (recog_memoized (insn) == CODE_FOR_insn_group_barrier
9042                 && !start_bundle && !end_bundle
9043                 && next_insn
9044                 && GET_CODE (PATTERN (next_insn)) != ASM_INPUT
9045                 && asm_noperands (PATTERN (next_insn)) < 0)
9046               num--;
9047
9048             start_bundle = false;
9049           }
9050       }
9051
9052     gcc_assert (num == 0);
9053   }
9054 #endif
9055
9056   free (index_to_bundle_states);
9057   finish_bundle_state_table ();
9058   bundling_p = 0;
9059   dfa_clean_insn_cache ();
9060 }
9061
9062 /* The following function is called at the end of scheduling BB or
9063    EBB.  After reload, it inserts stop bits and does insn bundling.  */
9064
9065 static void
9066 ia64_sched_finish (FILE *dump, int sched_verbose)
9067 {
9068   if (sched_verbose)
9069     fprintf (dump, "// Finishing schedule.\n");
9070   if (!reload_completed)
9071     return;
9072   if (reload_completed)
9073     {
9074       final_emit_insn_group_barriers (dump);
9075       bundling (dump, sched_verbose, current_sched_info->prev_head,
9076                 current_sched_info->next_tail);
9077       if (sched_verbose && dump)
9078         fprintf (dump, "//    finishing %d-%d\n",
9079                  INSN_UID (NEXT_INSN (current_sched_info->prev_head)),
9080                  INSN_UID (PREV_INSN (current_sched_info->next_tail)));
9081
9082       return;
9083     }
9084 }
9085
9086 /* The following function inserts stop bits in scheduled BB or EBB.  */
9087
9088 static void
9089 final_emit_insn_group_barriers (FILE *dump ATTRIBUTE_UNUSED)
9090 {
9091   rtx insn;
9092   int need_barrier_p = 0;
9093   int seen_good_insn = 0;
9094
9095   init_insn_group_barriers ();
9096
9097   for (insn = NEXT_INSN (current_sched_info->prev_head);
9098        insn != current_sched_info->next_tail;
9099        insn = NEXT_INSN (insn))
9100     {
9101       if (GET_CODE (insn) == BARRIER)
9102         {
9103           rtx last = prev_active_insn (insn);
9104
9105           if (! last)
9106             continue;
9107           if (GET_CODE (last) == JUMP_INSN
9108               && GET_CODE (PATTERN (last)) == ADDR_DIFF_VEC)
9109             last = prev_active_insn (last);
9110           if (recog_memoized (last) != CODE_FOR_insn_group_barrier)
9111             emit_insn_after (gen_insn_group_barrier (GEN_INT (3)), last);
9112
9113           init_insn_group_barriers ();
9114           seen_good_insn = 0;
9115           need_barrier_p = 0;
9116         }
9117       else if (NONDEBUG_INSN_P (insn))
9118         {
9119           if (recog_memoized (insn) == CODE_FOR_insn_group_barrier)
9120             {
9121               init_insn_group_barriers ();
9122               seen_good_insn = 0;
9123               need_barrier_p = 0;
9124             }
9125           else if (need_barrier_p || group_barrier_needed (insn)
9126                    || (mflag_sched_stop_bits_after_every_cycle
9127                        && GET_MODE (insn) == TImode
9128                        && seen_good_insn))
9129             {
9130               if (TARGET_EARLY_STOP_BITS)
9131                 {
9132                   rtx last;
9133
9134                   for (last = insn;
9135                        last != current_sched_info->prev_head;
9136                        last = PREV_INSN (last))
9137                     if (INSN_P (last) && GET_MODE (last) == TImode
9138                         && stops_p [INSN_UID (last)])
9139                       break;
9140                   if (last == current_sched_info->prev_head)
9141                     last = insn;
9142                   last = prev_active_insn (last);
9143                   if (last
9144                       && recog_memoized (last) != CODE_FOR_insn_group_barrier)
9145                     emit_insn_after (gen_insn_group_barrier (GEN_INT (3)),
9146                                      last);
9147                   init_insn_group_barriers ();
9148                   for (last = NEXT_INSN (last);
9149                        last != insn;
9150                        last = NEXT_INSN (last))
9151                     if (INSN_P (last))
9152                       {
9153                         group_barrier_needed (last);
9154                         if (recog_memoized (last) >= 0
9155                             && important_for_bundling_p (last))
9156                           seen_good_insn = 1;
9157                       }
9158                 }
9159               else
9160                 {
9161                   emit_insn_before (gen_insn_group_barrier (GEN_INT (3)),
9162                                     insn);
9163                   init_insn_group_barriers ();
9164                   seen_good_insn = 0;
9165                 }
9166               group_barrier_needed (insn);
9167               if (recog_memoized (insn) >= 0
9168                   && important_for_bundling_p (insn))
9169                 seen_good_insn = 1;
9170             }
9171           else if (recog_memoized (insn) >= 0
9172                    && important_for_bundling_p (insn))
9173             seen_good_insn = 1;
9174           need_barrier_p = (GET_CODE (insn) == CALL_INSN
9175                             || GET_CODE (PATTERN (insn)) == ASM_INPUT
9176                             || asm_noperands (PATTERN (insn)) >= 0);
9177         }
9178     }
9179 }
9180
9181 \f
9182
9183 /* If the following function returns TRUE, we will use the DFA
9184    insn scheduler.  */
9185
9186 static int
9187 ia64_first_cycle_multipass_dfa_lookahead (void)
9188 {
9189   return (reload_completed ? 6 : 4);
9190 }
9191
9192 /* The following function initiates variable `dfa_pre_cycle_insn'.  */
9193
9194 static void
9195 ia64_init_dfa_pre_cycle_insn (void)
9196 {
9197   if (temp_dfa_state == NULL)
9198     {
9199       dfa_state_size = state_size ();
9200       temp_dfa_state = xmalloc (dfa_state_size);
9201       prev_cycle_state = xmalloc (dfa_state_size);
9202     }
9203   dfa_pre_cycle_insn = make_insn_raw (gen_pre_cycle ());
9204   PREV_INSN (dfa_pre_cycle_insn) = NEXT_INSN (dfa_pre_cycle_insn) = NULL_RTX;
9205   recog_memoized (dfa_pre_cycle_insn);
9206   dfa_stop_insn = make_insn_raw (gen_insn_group_barrier (GEN_INT (3)));
9207   PREV_INSN (dfa_stop_insn) = NEXT_INSN (dfa_stop_insn) = NULL_RTX;
9208   recog_memoized (dfa_stop_insn);
9209 }
9210
9211 /* The following function returns the pseudo insn DFA_PRE_CYCLE_INSN
9212    used by the DFA insn scheduler.  */
9213
9214 static rtx
9215 ia64_dfa_pre_cycle_insn (void)
9216 {
9217   return dfa_pre_cycle_insn;
9218 }
9219
9220 /* The following function returns TRUE if PRODUCER (of type ilog or
9221    ld) produces address for CONSUMER (of type st or stf). */
9222
9223 int
9224 ia64_st_address_bypass_p (rtx producer, rtx consumer)
9225 {
9226   rtx dest, reg, mem;
9227
9228   gcc_assert (producer && consumer);
9229   dest = ia64_single_set (producer);
9230   gcc_assert (dest);
9231   reg = SET_DEST (dest);
9232   gcc_assert (reg);
9233   if (GET_CODE (reg) == SUBREG)
9234     reg = SUBREG_REG (reg);
9235   gcc_assert (GET_CODE (reg) == REG);
9236   
9237   dest = ia64_single_set (consumer);
9238   gcc_assert (dest);
9239   mem = SET_DEST (dest);
9240   gcc_assert (mem && GET_CODE (mem) == MEM);
9241   return reg_mentioned_p (reg, mem);
9242 }
9243
9244 /* The following function returns TRUE if PRODUCER (of type ilog or
9245    ld) produces address for CONSUMER (of type ld or fld). */
9246
9247 int
9248 ia64_ld_address_bypass_p (rtx producer, rtx consumer)
9249 {
9250   rtx dest, src, reg, mem;
9251
9252   gcc_assert (producer && consumer);
9253   dest = ia64_single_set (producer);
9254   gcc_assert (dest);
9255   reg = SET_DEST (dest);
9256   gcc_assert (reg);
9257   if (GET_CODE (reg) == SUBREG)
9258     reg = SUBREG_REG (reg);
9259   gcc_assert (GET_CODE (reg) == REG);
9260   
9261   src = ia64_single_set (consumer);
9262   gcc_assert (src);
9263   mem = SET_SRC (src);
9264   gcc_assert (mem);
9265  
9266   if (GET_CODE (mem) == UNSPEC && XVECLEN (mem, 0) > 0)
9267     mem = XVECEXP (mem, 0, 0);
9268   else if (GET_CODE (mem) == IF_THEN_ELSE)
9269     /* ??? Is this bypass necessary for ld.c?  */
9270     {
9271       gcc_assert (XINT (XEXP (XEXP (mem, 0), 0), 1) == UNSPEC_LDCCLR);
9272       mem = XEXP (mem, 1);
9273     }
9274      
9275   while (GET_CODE (mem) == SUBREG || GET_CODE (mem) == ZERO_EXTEND)
9276     mem = XEXP (mem, 0);
9277
9278   if (GET_CODE (mem) == UNSPEC)
9279     {
9280       int c = XINT (mem, 1);
9281
9282       gcc_assert (c == UNSPEC_LDA || c == UNSPEC_LDS || c == UNSPEC_LDS_A
9283                   || c == UNSPEC_LDSA);
9284       mem = XVECEXP (mem, 0, 0);
9285     }
9286
9287   /* Note that LO_SUM is used for GOT loads.  */
9288   gcc_assert (GET_CODE (mem) == LO_SUM || GET_CODE (mem) == MEM);
9289
9290   return reg_mentioned_p (reg, mem);
9291 }
9292
9293 /* The following function returns TRUE if INSN produces address for a
9294    load/store insn.  We will place such insns into M slot because it
9295    decreases its latency time.  */
9296
9297 int
9298 ia64_produce_address_p (rtx insn)
9299 {
9300   return insn->call;
9301 }
9302
9303 \f
9304 /* Emit pseudo-ops for the assembler to describe predicate relations.
9305    At present this assumes that we only consider predicate pairs to
9306    be mutex, and that the assembler can deduce proper values from
9307    straight-line code.  */
9308
9309 static void
9310 emit_predicate_relation_info (void)
9311 {
9312   basic_block bb;
9313
9314   FOR_EACH_BB_REVERSE (bb)
9315     {
9316       int r;
9317       rtx head = BB_HEAD (bb);
9318
9319       /* We only need such notes at code labels.  */
9320       if (GET_CODE (head) != CODE_LABEL)
9321         continue;
9322       if (NOTE_INSN_BASIC_BLOCK_P (NEXT_INSN (head)))
9323         head = NEXT_INSN (head);
9324
9325       /* Skip p0, which may be thought to be live due to (reg:DI p0)
9326          grabbing the entire block of predicate registers.  */
9327       for (r = PR_REG (2); r < PR_REG (64); r += 2)
9328         if (REGNO_REG_SET_P (df_get_live_in (bb), r))
9329           {
9330             rtx p = gen_rtx_REG (BImode, r);
9331             rtx n = emit_insn_after (gen_pred_rel_mutex (p), head);
9332             if (head == BB_END (bb))
9333               BB_END (bb) = n;
9334             head = n;
9335           }
9336     }
9337
9338   /* Look for conditional calls that do not return, and protect predicate
9339      relations around them.  Otherwise the assembler will assume the call
9340      returns, and complain about uses of call-clobbered predicates after
9341      the call.  */
9342   FOR_EACH_BB_REVERSE (bb)
9343     {
9344       rtx insn = BB_HEAD (bb);
9345
9346       while (1)
9347         {
9348           if (GET_CODE (insn) == CALL_INSN
9349               && GET_CODE (PATTERN (insn)) == COND_EXEC
9350               && find_reg_note (insn, REG_NORETURN, NULL_RTX))
9351             {
9352               rtx b = emit_insn_before (gen_safe_across_calls_all (), insn);
9353               rtx a = emit_insn_after (gen_safe_across_calls_normal (), insn);
9354               if (BB_HEAD (bb) == insn)
9355                 BB_HEAD (bb) = b;
9356               if (BB_END (bb) == insn)
9357                 BB_END (bb) = a;
9358             }
9359
9360           if (insn == BB_END (bb))
9361             break;
9362           insn = NEXT_INSN (insn);
9363         }
9364     }
9365 }
9366
9367 /* Perform machine dependent operations on the rtl chain INSNS.  */
9368
9369 static void
9370 ia64_reorg (void)
9371 {
9372   /* We are freeing block_for_insn in the toplev to keep compatibility
9373      with old MDEP_REORGS that are not CFG based.  Recompute it now.  */
9374   compute_bb_for_insn ();
9375
9376   /* If optimizing, we'll have split before scheduling.  */
9377   if (optimize == 0)
9378     split_all_insns ();
9379
9380   if (optimize && ia64_flag_schedule_insns2
9381       && dbg_cnt (ia64_sched2))
9382     {
9383       timevar_push (TV_SCHED2);
9384       ia64_final_schedule = 1;
9385
9386       initiate_bundle_states ();
9387       ia64_nop = make_insn_raw (gen_nop ());
9388       PREV_INSN (ia64_nop) = NEXT_INSN (ia64_nop) = NULL_RTX;
9389       recog_memoized (ia64_nop);
9390       clocks_length = get_max_uid () + 1;
9391       stops_p = XCNEWVEC (char, clocks_length);
9392
9393       if (ia64_tune == PROCESSOR_ITANIUM2)
9394         {
9395           pos_1 = get_cpu_unit_code ("2_1");
9396           pos_2 = get_cpu_unit_code ("2_2");
9397           pos_3 = get_cpu_unit_code ("2_3");
9398           pos_4 = get_cpu_unit_code ("2_4");
9399           pos_5 = get_cpu_unit_code ("2_5");
9400           pos_6 = get_cpu_unit_code ("2_6");
9401           _0mii_ = get_cpu_unit_code ("2b_0mii.");
9402           _0mmi_ = get_cpu_unit_code ("2b_0mmi.");
9403           _0mfi_ = get_cpu_unit_code ("2b_0mfi.");
9404           _0mmf_ = get_cpu_unit_code ("2b_0mmf.");
9405           _0bbb_ = get_cpu_unit_code ("2b_0bbb.");
9406           _0mbb_ = get_cpu_unit_code ("2b_0mbb.");
9407           _0mib_ = get_cpu_unit_code ("2b_0mib.");
9408           _0mmb_ = get_cpu_unit_code ("2b_0mmb.");
9409           _0mfb_ = get_cpu_unit_code ("2b_0mfb.");
9410           _0mlx_ = get_cpu_unit_code ("2b_0mlx.");
9411           _1mii_ = get_cpu_unit_code ("2b_1mii.");
9412           _1mmi_ = get_cpu_unit_code ("2b_1mmi.");
9413           _1mfi_ = get_cpu_unit_code ("2b_1mfi.");
9414           _1mmf_ = get_cpu_unit_code ("2b_1mmf.");
9415           _1bbb_ = get_cpu_unit_code ("2b_1bbb.");
9416           _1mbb_ = get_cpu_unit_code ("2b_1mbb.");
9417           _1mib_ = get_cpu_unit_code ("2b_1mib.");
9418           _1mmb_ = get_cpu_unit_code ("2b_1mmb.");
9419           _1mfb_ = get_cpu_unit_code ("2b_1mfb.");
9420           _1mlx_ = get_cpu_unit_code ("2b_1mlx.");
9421         }
9422       else
9423         {
9424           pos_1 = get_cpu_unit_code ("1_1");
9425           pos_2 = get_cpu_unit_code ("1_2");
9426           pos_3 = get_cpu_unit_code ("1_3");
9427           pos_4 = get_cpu_unit_code ("1_4");
9428           pos_5 = get_cpu_unit_code ("1_5");
9429           pos_6 = get_cpu_unit_code ("1_6");
9430           _0mii_ = get_cpu_unit_code ("1b_0mii.");
9431           _0mmi_ = get_cpu_unit_code ("1b_0mmi.");
9432           _0mfi_ = get_cpu_unit_code ("1b_0mfi.");
9433           _0mmf_ = get_cpu_unit_code ("1b_0mmf.");
9434           _0bbb_ = get_cpu_unit_code ("1b_0bbb.");
9435           _0mbb_ = get_cpu_unit_code ("1b_0mbb.");
9436           _0mib_ = get_cpu_unit_code ("1b_0mib.");
9437           _0mmb_ = get_cpu_unit_code ("1b_0mmb.");
9438           _0mfb_ = get_cpu_unit_code ("1b_0mfb.");
9439           _0mlx_ = get_cpu_unit_code ("1b_0mlx.");
9440           _1mii_ = get_cpu_unit_code ("1b_1mii.");
9441           _1mmi_ = get_cpu_unit_code ("1b_1mmi.");
9442           _1mfi_ = get_cpu_unit_code ("1b_1mfi.");
9443           _1mmf_ = get_cpu_unit_code ("1b_1mmf.");
9444           _1bbb_ = get_cpu_unit_code ("1b_1bbb.");
9445           _1mbb_ = get_cpu_unit_code ("1b_1mbb.");
9446           _1mib_ = get_cpu_unit_code ("1b_1mib.");
9447           _1mmb_ = get_cpu_unit_code ("1b_1mmb.");
9448           _1mfb_ = get_cpu_unit_code ("1b_1mfb.");
9449           _1mlx_ = get_cpu_unit_code ("1b_1mlx.");
9450         }
9451
9452       if (flag_selective_scheduling2
9453           && !maybe_skip_selective_scheduling ())
9454         run_selective_scheduling ();
9455       else
9456         schedule_ebbs ();
9457
9458       /* Redo alignment computation, as it might gone wrong.  */
9459       compute_alignments ();
9460
9461       /* We cannot reuse this one because it has been corrupted by the
9462          evil glat.  */
9463       finish_bundle_states ();
9464       free (stops_p);
9465       stops_p = NULL;
9466       emit_insn_group_barriers (dump_file);
9467
9468       ia64_final_schedule = 0;
9469       timevar_pop (TV_SCHED2);
9470     }
9471   else
9472     emit_all_insn_group_barriers (dump_file);
9473
9474   df_analyze ();
9475  
9476   /* A call must not be the last instruction in a function, so that the
9477      return address is still within the function, so that unwinding works
9478      properly.  Note that IA-64 differs from dwarf2 on this point.  */
9479   if (ia64_except_unwind_info () == UI_TARGET)
9480     {
9481       rtx insn;
9482       int saw_stop = 0;
9483
9484       insn = get_last_insn ();
9485       if (! INSN_P (insn))
9486         insn = prev_active_insn (insn);
9487       if (insn)
9488         {
9489           /* Skip over insns that expand to nothing.  */
9490           while (GET_CODE (insn) == INSN
9491                  && get_attr_empty (insn) == EMPTY_YES)
9492             {
9493               if (GET_CODE (PATTERN (insn)) == UNSPEC_VOLATILE
9494                   && XINT (PATTERN (insn), 1) == UNSPECV_INSN_GROUP_BARRIER)
9495                 saw_stop = 1;
9496               insn = prev_active_insn (insn);
9497             }
9498           if (GET_CODE (insn) == CALL_INSN)
9499             {
9500               if (! saw_stop)
9501                 emit_insn (gen_insn_group_barrier (GEN_INT (3)));
9502               emit_insn (gen_break_f ());
9503               emit_insn (gen_insn_group_barrier (GEN_INT (3)));
9504             }
9505         }
9506     }
9507
9508   emit_predicate_relation_info ();
9509
9510   if (ia64_flag_var_tracking)
9511     {
9512       timevar_push (TV_VAR_TRACKING);
9513       variable_tracking_main ();
9514       timevar_pop (TV_VAR_TRACKING);
9515     }
9516   df_finish_pass (false);
9517 }
9518 \f
9519 /* Return true if REGNO is used by the epilogue.  */
9520
9521 int
9522 ia64_epilogue_uses (int regno)
9523 {
9524   switch (regno)
9525     {
9526     case R_GR (1):
9527       /* With a call to a function in another module, we will write a new
9528          value to "gp".  After returning from such a call, we need to make
9529          sure the function restores the original gp-value, even if the
9530          function itself does not use the gp anymore.  */
9531       return !(TARGET_AUTO_PIC || TARGET_NO_PIC);
9532
9533     case IN_REG (0): case IN_REG (1): case IN_REG (2): case IN_REG (3):
9534     case IN_REG (4): case IN_REG (5): case IN_REG (6): case IN_REG (7):
9535       /* For functions defined with the syscall_linkage attribute, all
9536          input registers are marked as live at all function exits.  This
9537          prevents the register allocator from using the input registers,
9538          which in turn makes it possible to restart a system call after
9539          an interrupt without having to save/restore the input registers.
9540          This also prevents kernel data from leaking to application code.  */
9541       return lookup_attribute ("syscall_linkage",
9542            TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl))) != NULL;
9543
9544     case R_BR (0):
9545       /* Conditional return patterns can't represent the use of `b0' as
9546          the return address, so we force the value live this way.  */
9547       return 1;
9548
9549     case AR_PFS_REGNUM:
9550       /* Likewise for ar.pfs, which is used by br.ret.  */
9551       return 1;
9552
9553     default:
9554       return 0;
9555     }
9556 }
9557
9558 /* Return true if REGNO is used by the frame unwinder.  */
9559
9560 int
9561 ia64_eh_uses (int regno)
9562 {
9563   unsigned int r;
9564
9565   if (! reload_completed)
9566     return 0;
9567
9568   if (regno == 0)
9569     return 0;
9570
9571   for (r = reg_save_b0; r <= reg_save_ar_lc; r++)
9572     if (regno == current_frame_info.r[r]
9573        || regno == emitted_frame_related_regs[r])
9574       return 1;
9575
9576   return 0;
9577 }
9578 \f
9579 /* Return true if this goes in small data/bss.  */
9580
9581 /* ??? We could also support own long data here.  Generating movl/add/ld8
9582    instead of addl,ld8/ld8.  This makes the code bigger, but should make the
9583    code faster because there is one less load.  This also includes incomplete
9584    types which can't go in sdata/sbss.  */
9585
9586 static bool
9587 ia64_in_small_data_p (const_tree exp)
9588 {
9589   if (TARGET_NO_SDATA)
9590     return false;
9591
9592   /* We want to merge strings, so we never consider them small data.  */
9593   if (TREE_CODE (exp) == STRING_CST)
9594     return false;
9595
9596   /* Functions are never small data.  */
9597   if (TREE_CODE (exp) == FUNCTION_DECL)
9598     return false;
9599
9600   if (TREE_CODE (exp) == VAR_DECL && DECL_SECTION_NAME (exp))
9601     {
9602       const char *section = TREE_STRING_POINTER (DECL_SECTION_NAME (exp));
9603
9604       if (strcmp (section, ".sdata") == 0
9605           || strncmp (section, ".sdata.", 7) == 0
9606           || strncmp (section, ".gnu.linkonce.s.", 16) == 0
9607           || strcmp (section, ".sbss") == 0
9608           || strncmp (section, ".sbss.", 6) == 0
9609           || strncmp (section, ".gnu.linkonce.sb.", 17) == 0)
9610         return true;
9611     }
9612   else
9613     {
9614       HOST_WIDE_INT size = int_size_in_bytes (TREE_TYPE (exp));
9615
9616       /* If this is an incomplete type with size 0, then we can't put it
9617          in sdata because it might be too big when completed.  */
9618       if (size > 0 && size <= ia64_section_threshold)
9619         return true;
9620     }
9621
9622   return false;
9623 }
9624 \f
9625 /* Output assembly directives for prologue regions.  */
9626
9627 /* The current basic block number.  */
9628
9629 static bool last_block;
9630
9631 /* True if we need a copy_state command at the start of the next block.  */
9632
9633 static bool need_copy_state;
9634
9635 #ifndef MAX_ARTIFICIAL_LABEL_BYTES
9636 # define MAX_ARTIFICIAL_LABEL_BYTES 30
9637 #endif
9638
9639 /* Emit a debugging label after a call-frame-related insn.  We'd
9640    rather output the label right away, but we'd have to output it
9641    after, not before, the instruction, and the instruction has not
9642    been output yet.  So we emit the label after the insn, delete it to
9643    avoid introducing basic blocks, and mark it as preserved, such that
9644    it is still output, given that it is referenced in debug info.  */
9645
9646 static const char *
9647 ia64_emit_deleted_label_after_insn (rtx insn)
9648 {
9649   char label[MAX_ARTIFICIAL_LABEL_BYTES];
9650   rtx lb = gen_label_rtx ();
9651   rtx label_insn = emit_label_after (lb, insn);
9652
9653   LABEL_PRESERVE_P (lb) = 1;
9654
9655   delete_insn (label_insn);
9656
9657   ASM_GENERATE_INTERNAL_LABEL (label, "L", CODE_LABEL_NUMBER (label_insn));
9658
9659   return xstrdup (label);
9660 }
9661
9662 /* Define the CFA after INSN with the steady-state definition.  */
9663
9664 static void
9665 ia64_dwarf2out_def_steady_cfa (rtx insn, bool frame)
9666 {
9667   rtx fp = frame_pointer_needed
9668     ? hard_frame_pointer_rtx
9669     : stack_pointer_rtx;
9670   const char *label = ia64_emit_deleted_label_after_insn (insn);
9671
9672   if (!frame)
9673     return;
9674
9675   dwarf2out_def_cfa
9676     (label, REGNO (fp),
9677      ia64_initial_elimination_offset
9678      (REGNO (arg_pointer_rtx), REGNO (fp))
9679      + ARG_POINTER_CFA_OFFSET (current_function_decl));
9680 }
9681
9682 /* All we need to do here is avoid a crash in the generic dwarf2
9683    processing.  The real CFA definition is set up above.  */
9684
9685 static void
9686 ia64_dwarf_handle_frame_unspec (const char * ARG_UNUSED (label),
9687                                 rtx ARG_UNUSED (pattern),
9688                                 int index)
9689 {
9690   gcc_assert (index == UNSPECV_ALLOC);
9691 }
9692
9693 /* The generic dwarf2 frame debug info generator does not define a
9694    separate region for the very end of the epilogue, so refrain from
9695    doing so in the IA64-specific code as well.  */
9696
9697 #define IA64_CHANGE_CFA_IN_EPILOGUE 0
9698
9699 /* The function emits unwind directives for the start of an epilogue.  */
9700
9701 static void
9702 process_epilogue (FILE *asm_out_file, rtx insn, bool unwind, bool frame)
9703 {
9704   /* If this isn't the last block of the function, then we need to label the
9705      current state, and copy it back in at the start of the next block.  */
9706
9707   if (!last_block)
9708     {
9709       if (unwind)
9710         fprintf (asm_out_file, "\t.label_state %d\n",
9711                  ++cfun->machine->state_num);
9712       need_copy_state = true;
9713     }
9714
9715   if (unwind)
9716     fprintf (asm_out_file, "\t.restore sp\n");
9717   if (IA64_CHANGE_CFA_IN_EPILOGUE && frame)
9718     dwarf2out_def_cfa (ia64_emit_deleted_label_after_insn (insn),
9719                        STACK_POINTER_REGNUM, INCOMING_FRAME_SP_OFFSET);
9720 }
9721
9722 /* This function processes a SET pattern for REG_CFA_ADJUST_CFA.  */
9723
9724 static void
9725 process_cfa_adjust_cfa (FILE *asm_out_file, rtx pat, rtx insn,
9726                         bool unwind, bool frame)
9727 {
9728   rtx dest = SET_DEST (pat);
9729   rtx src = SET_SRC (pat);
9730
9731   if (dest == stack_pointer_rtx)
9732     {
9733       if (GET_CODE (src) == PLUS)
9734         {
9735           rtx op0 = XEXP (src, 0);
9736           rtx op1 = XEXP (src, 1);
9737           
9738           gcc_assert (op0 == dest && GET_CODE (op1) == CONST_INT);
9739           
9740           if (INTVAL (op1) < 0)
9741             {
9742               gcc_assert (!frame_pointer_needed);
9743               if (unwind)
9744                 fprintf (asm_out_file,
9745                          "\t.fframe "HOST_WIDE_INT_PRINT_DEC"\n",
9746                          -INTVAL (op1));
9747               ia64_dwarf2out_def_steady_cfa (insn, frame);
9748             }
9749           else
9750             process_epilogue (asm_out_file, insn, unwind, frame);
9751         }
9752       else
9753         {
9754           gcc_assert (src == hard_frame_pointer_rtx);
9755           process_epilogue (asm_out_file, insn, unwind, frame);
9756         }
9757     }
9758   else if (dest == hard_frame_pointer_rtx)
9759     {
9760       gcc_assert (src == stack_pointer_rtx);
9761       gcc_assert (frame_pointer_needed);
9762
9763       if (unwind)
9764         fprintf (asm_out_file, "\t.vframe r%d\n",
9765                  ia64_dbx_register_number (REGNO (dest)));
9766       ia64_dwarf2out_def_steady_cfa (insn, frame);
9767     }
9768   else
9769     gcc_unreachable ();
9770 }
9771
9772 /* This function processes a SET pattern for REG_CFA_REGISTER.  */
9773
9774 static void
9775 process_cfa_register (FILE *asm_out_file, rtx pat, bool unwind)
9776 {
9777   rtx dest = SET_DEST (pat);
9778   rtx src = SET_SRC (pat);
9779
9780   int dest_regno = REGNO (dest);
9781   int src_regno = REGNO (src);
9782
9783   switch (src_regno)
9784     {
9785     case BR_REG (0):
9786       /* Saving return address pointer.  */
9787       gcc_assert (dest_regno == current_frame_info.r[reg_save_b0]);
9788       if (unwind)
9789         fprintf (asm_out_file, "\t.save rp, r%d\n",
9790                  ia64_dbx_register_number (dest_regno));
9791       break;
9792
9793     case PR_REG (0):
9794       gcc_assert (dest_regno == current_frame_info.r[reg_save_pr]);
9795       if (unwind)
9796         fprintf (asm_out_file, "\t.save pr, r%d\n",
9797                  ia64_dbx_register_number (dest_regno));
9798       break;
9799
9800     case AR_UNAT_REGNUM:
9801       gcc_assert (dest_regno == current_frame_info.r[reg_save_ar_unat]);
9802       if (unwind)
9803         fprintf (asm_out_file, "\t.save ar.unat, r%d\n",
9804                  ia64_dbx_register_number (dest_regno));
9805       break;
9806
9807     case AR_LC_REGNUM:
9808       gcc_assert (dest_regno == current_frame_info.r[reg_save_ar_lc]);
9809       if (unwind)
9810         fprintf (asm_out_file, "\t.save ar.lc, r%d\n",
9811                  ia64_dbx_register_number (dest_regno));
9812       break;
9813
9814     default:
9815       /* Everything else should indicate being stored to memory.  */
9816       gcc_unreachable ();
9817     }
9818 }
9819
9820 /* This function processes a SET pattern for REG_CFA_OFFSET.  */
9821
9822 static void
9823 process_cfa_offset (FILE *asm_out_file, rtx pat, bool unwind)
9824 {
9825   rtx dest = SET_DEST (pat);
9826   rtx src = SET_SRC (pat);
9827   int src_regno = REGNO (src);
9828   const char *saveop;
9829   HOST_WIDE_INT off;
9830   rtx base;
9831
9832   gcc_assert (MEM_P (dest));
9833   if (GET_CODE (XEXP (dest, 0)) == REG)
9834     {
9835       base = XEXP (dest, 0);
9836       off = 0;
9837     }
9838   else
9839     {
9840       gcc_assert (GET_CODE (XEXP (dest, 0)) == PLUS
9841                   && GET_CODE (XEXP (XEXP (dest, 0), 1)) == CONST_INT);
9842       base = XEXP (XEXP (dest, 0), 0);
9843       off = INTVAL (XEXP (XEXP (dest, 0), 1));
9844     }
9845
9846   if (base == hard_frame_pointer_rtx)
9847     {
9848       saveop = ".savepsp";
9849       off = - off;
9850     }
9851   else
9852     {
9853       gcc_assert (base == stack_pointer_rtx);
9854       saveop = ".savesp";
9855     }
9856
9857   src_regno = REGNO (src);
9858   switch (src_regno)
9859     {
9860     case BR_REG (0):
9861       gcc_assert (!current_frame_info.r[reg_save_b0]);
9862       if (unwind)
9863         fprintf (asm_out_file, "\t%s rp, " HOST_WIDE_INT_PRINT_DEC "\n",
9864                  saveop, off);
9865       break;
9866
9867     case PR_REG (0):
9868       gcc_assert (!current_frame_info.r[reg_save_pr]);
9869       if (unwind)
9870         fprintf (asm_out_file, "\t%s pr, " HOST_WIDE_INT_PRINT_DEC "\n",
9871                  saveop, off);
9872       break;
9873
9874     case AR_LC_REGNUM:
9875       gcc_assert (!current_frame_info.r[reg_save_ar_lc]);
9876       if (unwind)
9877         fprintf (asm_out_file, "\t%s ar.lc, " HOST_WIDE_INT_PRINT_DEC "\n",
9878                  saveop, off);
9879       break;
9880
9881     case AR_PFS_REGNUM:
9882       gcc_assert (!current_frame_info.r[reg_save_ar_pfs]);
9883       if (unwind)
9884         fprintf (asm_out_file, "\t%s ar.pfs, " HOST_WIDE_INT_PRINT_DEC "\n",
9885                  saveop, off);
9886       break;
9887
9888     case AR_UNAT_REGNUM:
9889       gcc_assert (!current_frame_info.r[reg_save_ar_unat]);
9890       if (unwind)
9891         fprintf (asm_out_file, "\t%s ar.unat, " HOST_WIDE_INT_PRINT_DEC "\n",
9892                  saveop, off);
9893       break;
9894
9895     case GR_REG (4):
9896     case GR_REG (5):
9897     case GR_REG (6):
9898     case GR_REG (7):
9899       if (unwind)
9900         fprintf (asm_out_file, "\t.save.g 0x%x\n",
9901                  1 << (src_regno - GR_REG (4)));
9902       break;
9903
9904     case BR_REG (1):
9905     case BR_REG (2):
9906     case BR_REG (3):
9907     case BR_REG (4):
9908     case BR_REG (5):
9909       if (unwind)
9910         fprintf (asm_out_file, "\t.save.b 0x%x\n",
9911                  1 << (src_regno - BR_REG (1)));
9912       break;
9913
9914     case FR_REG (2):
9915     case FR_REG (3):
9916     case FR_REG (4):
9917     case FR_REG (5):
9918       if (unwind)
9919         fprintf (asm_out_file, "\t.save.f 0x%x\n",
9920                  1 << (src_regno - FR_REG (2)));
9921       break;
9922
9923     case FR_REG (16): case FR_REG (17): case FR_REG (18): case FR_REG (19):
9924     case FR_REG (20): case FR_REG (21): case FR_REG (22): case FR_REG (23):
9925     case FR_REG (24): case FR_REG (25): case FR_REG (26): case FR_REG (27):
9926     case FR_REG (28): case FR_REG (29): case FR_REG (30): case FR_REG (31):
9927       if (unwind)
9928         fprintf (asm_out_file, "\t.save.gf 0x0, 0x%x\n",
9929                  1 << (src_regno - FR_REG (12)));
9930       break;
9931
9932     default:
9933       /* ??? For some reason we mark other general registers, even those
9934          we can't represent in the unwind info.  Ignore them.  */
9935       break;
9936     }
9937 }
9938
9939 /* This function looks at a single insn and emits any directives
9940    required to unwind this insn.  */
9941
9942 static void
9943 ia64_asm_unwind_emit (FILE *asm_out_file, rtx insn)
9944 {
9945   bool unwind = ia64_except_unwind_info () == UI_TARGET;
9946   bool frame = dwarf2out_do_frame ();
9947   rtx note, pat;
9948   bool handled_one;
9949
9950   if (!unwind && !frame)
9951     return;
9952
9953   if (NOTE_INSN_BASIC_BLOCK_P (insn))
9954     {
9955       last_block = NOTE_BASIC_BLOCK (insn)->next_bb == EXIT_BLOCK_PTR;
9956
9957       /* Restore unwind state from immediately before the epilogue.  */
9958       if (need_copy_state)
9959         {
9960           if (unwind)
9961             {
9962               fprintf (asm_out_file, "\t.body\n");
9963               fprintf (asm_out_file, "\t.copy_state %d\n",
9964                        cfun->machine->state_num);
9965             }
9966           if (IA64_CHANGE_CFA_IN_EPILOGUE)
9967             ia64_dwarf2out_def_steady_cfa (insn, frame);
9968           need_copy_state = false;
9969         }
9970     }
9971
9972   if (GET_CODE (insn) == NOTE || ! RTX_FRAME_RELATED_P (insn))
9973     return;
9974
9975   /* Look for the ALLOC insn.  */
9976   if (INSN_CODE (insn) == CODE_FOR_alloc)
9977     {
9978       rtx dest = SET_DEST (XVECEXP (PATTERN (insn), 0, 0));
9979       int dest_regno = REGNO (dest);
9980
9981       /* If this is the final destination for ar.pfs, then this must
9982          be the alloc in the prologue.  */
9983       if (dest_regno == current_frame_info.r[reg_save_ar_pfs])
9984         {
9985           if (unwind)
9986             fprintf (asm_out_file, "\t.save ar.pfs, r%d\n",
9987                      ia64_dbx_register_number (dest_regno));
9988         }
9989       else
9990         {
9991           /* This must be an alloc before a sibcall.  We must drop the
9992              old frame info.  The easiest way to drop the old frame
9993              info is to ensure we had a ".restore sp" directive
9994              followed by a new prologue.  If the procedure doesn't
9995              have a memory-stack frame, we'll issue a dummy ".restore
9996              sp" now.  */
9997           if (current_frame_info.total_size == 0 && !frame_pointer_needed)
9998             /* if haven't done process_epilogue() yet, do it now */
9999             process_epilogue (asm_out_file, insn, unwind, frame);
10000           if (unwind)
10001             fprintf (asm_out_file, "\t.prologue\n");
10002         }
10003       return;
10004     }
10005
10006   handled_one = false;
10007   for (note = REG_NOTES (insn); note; note = XEXP (note, 1))
10008     switch (REG_NOTE_KIND (note))
10009       {
10010       case REG_CFA_ADJUST_CFA:
10011         pat = XEXP (note, 0);
10012         if (pat == NULL)
10013           pat = PATTERN (insn);
10014         process_cfa_adjust_cfa (asm_out_file, pat, insn, unwind, frame);
10015         handled_one = true;
10016         break;
10017
10018       case REG_CFA_OFFSET:
10019         pat = XEXP (note, 0);
10020         if (pat == NULL)
10021           pat = PATTERN (insn);
10022         process_cfa_offset (asm_out_file, pat, unwind);
10023         handled_one = true;
10024         break;
10025
10026       case REG_CFA_REGISTER:
10027         pat = XEXP (note, 0);
10028         if (pat == NULL)
10029           pat = PATTERN (insn);
10030         process_cfa_register (asm_out_file, pat, unwind);
10031         handled_one = true;
10032         break;
10033
10034       case REG_FRAME_RELATED_EXPR:
10035       case REG_CFA_DEF_CFA:
10036       case REG_CFA_EXPRESSION:
10037       case REG_CFA_RESTORE:
10038       case REG_CFA_SET_VDRAP:
10039         /* Not used in the ia64 port.  */
10040         gcc_unreachable ();
10041
10042       default:
10043         /* Not a frame-related note.  */
10044         break;
10045       }
10046
10047   /* All REG_FRAME_RELATED_P insns, besides ALLOC, are marked with the
10048      explicit action to take.  No guessing required.  */
10049   gcc_assert (handled_one);
10050 }
10051
10052 /* Implement TARGET_ASM_EMIT_EXCEPT_PERSONALITY.  */
10053
10054 static void
10055 ia64_asm_emit_except_personality (rtx personality)
10056 {
10057   fputs ("\t.personality\t", asm_out_file);
10058   output_addr_const (asm_out_file, personality);
10059   fputc ('\n', asm_out_file);
10060 }
10061
10062 /* Implement TARGET_ASM_INITIALIZE_SECTIONS.  */
10063
10064 static void
10065 ia64_asm_init_sections (void)
10066 {
10067   exception_section = get_unnamed_section (0, output_section_asm_op,
10068                                            "\t.handlerdata");
10069 }
10070
10071 /* Implement TARGET_DEBUG_UNWIND_INFO.  */
10072
10073 static enum unwind_info_type
10074 ia64_debug_unwind_info (void)
10075 {
10076   return UI_TARGET;
10077 }
10078
10079 /* Implement TARGET_EXCEPT_UNWIND_INFO.  */
10080
10081 static enum unwind_info_type
10082 ia64_except_unwind_info (void)
10083 {
10084   /* Honor the --enable-sjlj-exceptions configure switch.  */
10085 #ifdef CONFIG_UNWIND_EXCEPTIONS
10086   if (CONFIG_UNWIND_EXCEPTIONS)
10087     return UI_SJLJ;
10088 #endif
10089
10090   /* For simplicity elsewhere in this file, indicate that all unwind
10091      info is disabled if we're not emitting unwind tables.  */
10092   if (!flag_exceptions && !flag_unwind_tables)
10093     return UI_NONE;
10094
10095   return UI_TARGET;
10096 }
10097 \f
10098 enum ia64_builtins
10099 {
10100   IA64_BUILTIN_BSP,
10101   IA64_BUILTIN_COPYSIGNQ,
10102   IA64_BUILTIN_FABSQ,
10103   IA64_BUILTIN_FLUSHRS,
10104   IA64_BUILTIN_INFQ,
10105   IA64_BUILTIN_HUGE_VALQ,
10106   IA64_BUILTIN_max
10107 };
10108
10109 static GTY(()) tree ia64_builtins[(int) IA64_BUILTIN_max];
10110
10111 void
10112 ia64_init_builtins (void)
10113 {
10114   tree fpreg_type;
10115   tree float80_type;
10116   tree decl;
10117
10118   /* The __fpreg type.  */
10119   fpreg_type = make_node (REAL_TYPE);
10120   TYPE_PRECISION (fpreg_type) = 82;
10121   layout_type (fpreg_type);
10122   (*lang_hooks.types.register_builtin_type) (fpreg_type, "__fpreg");
10123
10124   /* The __float80 type.  */
10125   float80_type = make_node (REAL_TYPE);
10126   TYPE_PRECISION (float80_type) = 80;
10127   layout_type (float80_type);
10128   (*lang_hooks.types.register_builtin_type) (float80_type, "__float80");
10129
10130   /* The __float128 type.  */
10131   if (!TARGET_HPUX)
10132     {
10133       tree ftype;
10134       tree float128_type = make_node (REAL_TYPE);
10135
10136       TYPE_PRECISION (float128_type) = 128;
10137       layout_type (float128_type);
10138       (*lang_hooks.types.register_builtin_type) (float128_type, "__float128");
10139
10140       /* TFmode support builtins.  */
10141       ftype = build_function_type (float128_type, void_list_node);
10142       decl = add_builtin_function ("__builtin_infq", ftype,
10143                                    IA64_BUILTIN_INFQ, BUILT_IN_MD,
10144                                    NULL, NULL_TREE);
10145       ia64_builtins[IA64_BUILTIN_INFQ] = decl;
10146
10147       decl = add_builtin_function ("__builtin_huge_valq", ftype,
10148                                    IA64_BUILTIN_HUGE_VALQ, BUILT_IN_MD,
10149                                    NULL, NULL_TREE);
10150       ia64_builtins[IA64_BUILTIN_HUGE_VALQ] = decl;
10151
10152       ftype = build_function_type_list (float128_type,
10153                                         float128_type,
10154                                         NULL_TREE);
10155       decl = add_builtin_function ("__builtin_fabsq", ftype,
10156                                    IA64_BUILTIN_FABSQ, BUILT_IN_MD,
10157                                    "__fabstf2", NULL_TREE);
10158       TREE_READONLY (decl) = 1;
10159       ia64_builtins[IA64_BUILTIN_FABSQ] = decl;
10160
10161       ftype = build_function_type_list (float128_type,
10162                                         float128_type,
10163                                         float128_type,
10164                                         NULL_TREE);
10165       decl = add_builtin_function ("__builtin_copysignq", ftype,
10166                                    IA64_BUILTIN_COPYSIGNQ, BUILT_IN_MD,
10167                                    "__copysigntf3", NULL_TREE);
10168       TREE_READONLY (decl) = 1;
10169       ia64_builtins[IA64_BUILTIN_COPYSIGNQ] = decl;
10170     }
10171   else
10172     /* Under HPUX, this is a synonym for "long double".  */
10173     (*lang_hooks.types.register_builtin_type) (long_double_type_node,
10174                                                "__float128");
10175
10176   /* Fwrite on VMS is non-standard.  */
10177   if (TARGET_ABI_OPEN_VMS)
10178     {
10179       implicit_built_in_decls[(int) BUILT_IN_FWRITE] = NULL_TREE;
10180       implicit_built_in_decls[(int) BUILT_IN_FWRITE_UNLOCKED] = NULL_TREE;
10181     }
10182
10183 #define def_builtin(name, type, code)                                   \
10184   add_builtin_function ((name), (type), (code), BUILT_IN_MD,    \
10185                        NULL, NULL_TREE)
10186
10187   decl = def_builtin ("__builtin_ia64_bsp",
10188                build_function_type (ptr_type_node, void_list_node),
10189                IA64_BUILTIN_BSP);
10190   ia64_builtins[IA64_BUILTIN_BSP] = decl;
10191
10192   decl = def_builtin ("__builtin_ia64_flushrs",
10193                build_function_type (void_type_node, void_list_node),
10194                IA64_BUILTIN_FLUSHRS);
10195   ia64_builtins[IA64_BUILTIN_FLUSHRS] = decl;
10196
10197 #undef def_builtin
10198
10199   if (TARGET_HPUX)
10200     {
10201       if (built_in_decls [BUILT_IN_FINITE])
10202         set_user_assembler_name (built_in_decls [BUILT_IN_FINITE],
10203           "_Isfinite");
10204       if (built_in_decls [BUILT_IN_FINITEF])
10205         set_user_assembler_name (built_in_decls [BUILT_IN_FINITEF],
10206           "_Isfinitef");
10207       if (built_in_decls [BUILT_IN_FINITEL])
10208         set_user_assembler_name (built_in_decls [BUILT_IN_FINITEL],
10209           "_Isfinitef128");
10210     }
10211 }
10212
10213 rtx
10214 ia64_expand_builtin (tree exp, rtx target, rtx subtarget ATTRIBUTE_UNUSED,
10215                      enum machine_mode mode ATTRIBUTE_UNUSED,
10216                      int ignore ATTRIBUTE_UNUSED)
10217 {
10218   tree fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
10219   unsigned int fcode = DECL_FUNCTION_CODE (fndecl);
10220
10221   switch (fcode)
10222     {
10223     case IA64_BUILTIN_BSP:
10224       if (! target || ! register_operand (target, DImode))
10225         target = gen_reg_rtx (DImode);
10226       emit_insn (gen_bsp_value (target));
10227 #ifdef POINTERS_EXTEND_UNSIGNED
10228       target = convert_memory_address (ptr_mode, target);
10229 #endif
10230       return target;
10231
10232     case IA64_BUILTIN_FLUSHRS:
10233       emit_insn (gen_flushrs ());
10234       return const0_rtx;
10235
10236     case IA64_BUILTIN_INFQ:
10237     case IA64_BUILTIN_HUGE_VALQ:
10238       {
10239         enum machine_mode target_mode = TYPE_MODE (TREE_TYPE (exp));
10240         REAL_VALUE_TYPE inf;
10241         rtx tmp;
10242
10243         real_inf (&inf);
10244         tmp = CONST_DOUBLE_FROM_REAL_VALUE (inf, target_mode);
10245
10246         tmp = validize_mem (force_const_mem (target_mode, tmp));
10247
10248         if (target == 0)
10249           target = gen_reg_rtx (target_mode);
10250
10251         emit_move_insn (target, tmp);
10252         return target;
10253       }
10254
10255     case IA64_BUILTIN_FABSQ:
10256     case IA64_BUILTIN_COPYSIGNQ:
10257       return expand_call (exp, target, ignore);
10258
10259     default:
10260       gcc_unreachable ();
10261     }
10262
10263   return NULL_RTX;
10264 }
10265
10266 /* Return the ia64 builtin for CODE.  */
10267
10268 static tree
10269 ia64_builtin_decl (unsigned code, bool initialize_p ATTRIBUTE_UNUSED)
10270 {
10271   if (code >= IA64_BUILTIN_max)
10272     return error_mark_node;
10273
10274   return ia64_builtins[code];
10275 }
10276
10277 /* For the HP-UX IA64 aggregate parameters are passed stored in the
10278    most significant bits of the stack slot.  */
10279
10280 enum direction
10281 ia64_hpux_function_arg_padding (enum machine_mode mode, const_tree type)
10282 {
10283    /* Exception to normal case for structures/unions/etc.  */
10284
10285    if (type && AGGREGATE_TYPE_P (type)
10286        && int_size_in_bytes (type) < UNITS_PER_WORD)
10287      return upward;
10288
10289    /* Fall back to the default.  */
10290    return DEFAULT_FUNCTION_ARG_PADDING (mode, type);
10291 }
10292
10293 /* Emit text to declare externally defined variables and functions, because
10294    the Intel assembler does not support undefined externals.  */
10295
10296 void
10297 ia64_asm_output_external (FILE *file, tree decl, const char *name)
10298 {
10299   /* We output the name if and only if TREE_SYMBOL_REFERENCED is
10300      set in order to avoid putting out names that are never really
10301      used. */
10302   if (TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (decl)))
10303     {
10304       /* maybe_assemble_visibility will return 1 if the assembler
10305          visibility directive is output.  */
10306       int need_visibility = ((*targetm.binds_local_p) (decl)
10307                              && maybe_assemble_visibility (decl));
10308
10309 #ifdef DO_CRTL_NAMES
10310       DO_CRTL_NAMES;
10311 #endif
10312
10313       /* GNU as does not need anything here, but the HP linker does
10314          need something for external functions.  */
10315       if ((TARGET_HPUX_LD || !TARGET_GNU_AS)
10316           && TREE_CODE (decl) == FUNCTION_DECL)
10317           (*targetm.asm_out.globalize_decl_name) (file, decl);
10318       else if (need_visibility && !TARGET_GNU_AS)
10319         (*targetm.asm_out.globalize_label) (file, name);
10320     }
10321 }
10322
10323 /* Set SImode div/mod functions, init_integral_libfuncs only initializes
10324    modes of word_mode and larger.  Rename the TFmode libfuncs using the
10325    HPUX conventions. __divtf3 is used for XFmode. We need to keep it for
10326    backward compatibility. */
10327
10328 static void
10329 ia64_init_libfuncs (void)
10330 {
10331   set_optab_libfunc (sdiv_optab, SImode, "__divsi3");
10332   set_optab_libfunc (udiv_optab, SImode, "__udivsi3");
10333   set_optab_libfunc (smod_optab, SImode, "__modsi3");
10334   set_optab_libfunc (umod_optab, SImode, "__umodsi3");
10335
10336   set_optab_libfunc (add_optab, TFmode, "_U_Qfadd");
10337   set_optab_libfunc (sub_optab, TFmode, "_U_Qfsub");
10338   set_optab_libfunc (smul_optab, TFmode, "_U_Qfmpy");
10339   set_optab_libfunc (sdiv_optab, TFmode, "_U_Qfdiv");
10340   set_optab_libfunc (neg_optab, TFmode, "_U_Qfneg");
10341
10342   set_conv_libfunc (sext_optab, TFmode, SFmode, "_U_Qfcnvff_sgl_to_quad");
10343   set_conv_libfunc (sext_optab, TFmode, DFmode, "_U_Qfcnvff_dbl_to_quad");
10344   set_conv_libfunc (sext_optab, TFmode, XFmode, "_U_Qfcnvff_f80_to_quad");
10345   set_conv_libfunc (trunc_optab, SFmode, TFmode, "_U_Qfcnvff_quad_to_sgl");
10346   set_conv_libfunc (trunc_optab, DFmode, TFmode, "_U_Qfcnvff_quad_to_dbl");
10347   set_conv_libfunc (trunc_optab, XFmode, TFmode, "_U_Qfcnvff_quad_to_f80");
10348
10349   set_conv_libfunc (sfix_optab, SImode, TFmode, "_U_Qfcnvfxt_quad_to_sgl");
10350   set_conv_libfunc (sfix_optab, DImode, TFmode, "_U_Qfcnvfxt_quad_to_dbl");
10351   set_conv_libfunc (sfix_optab, TImode, TFmode, "_U_Qfcnvfxt_quad_to_quad");
10352   set_conv_libfunc (ufix_optab, SImode, TFmode, "_U_Qfcnvfxut_quad_to_sgl");
10353   set_conv_libfunc (ufix_optab, DImode, TFmode, "_U_Qfcnvfxut_quad_to_dbl");
10354
10355   set_conv_libfunc (sfloat_optab, TFmode, SImode, "_U_Qfcnvxf_sgl_to_quad");
10356   set_conv_libfunc (sfloat_optab, TFmode, DImode, "_U_Qfcnvxf_dbl_to_quad");
10357   set_conv_libfunc (sfloat_optab, TFmode, TImode, "_U_Qfcnvxf_quad_to_quad");
10358   /* HP-UX 11.23 libc does not have a function for unsigned
10359      SImode-to-TFmode conversion.  */
10360   set_conv_libfunc (ufloat_optab, TFmode, DImode, "_U_Qfcnvxuf_dbl_to_quad");
10361 }
10362
10363 /* Rename all the TFmode libfuncs using the HPUX conventions.  */
10364
10365 static void
10366 ia64_hpux_init_libfuncs (void)
10367 {
10368   ia64_init_libfuncs ();
10369
10370   /* The HP SI millicode division and mod functions expect DI arguments.
10371      By turning them off completely we avoid using both libgcc and the
10372      non-standard millicode routines and use the HP DI millicode routines
10373      instead.  */
10374
10375   set_optab_libfunc (sdiv_optab, SImode, 0);
10376   set_optab_libfunc (udiv_optab, SImode, 0);
10377   set_optab_libfunc (smod_optab, SImode, 0);
10378   set_optab_libfunc (umod_optab, SImode, 0);
10379
10380   set_optab_libfunc (sdiv_optab, DImode, "__milli_divI");
10381   set_optab_libfunc (udiv_optab, DImode, "__milli_divU");
10382   set_optab_libfunc (smod_optab, DImode, "__milli_remI");
10383   set_optab_libfunc (umod_optab, DImode, "__milli_remU");
10384
10385   /* HP-UX libc has TF min/max/abs routines in it.  */
10386   set_optab_libfunc (smin_optab, TFmode, "_U_Qfmin");
10387   set_optab_libfunc (smax_optab, TFmode, "_U_Qfmax");
10388   set_optab_libfunc (abs_optab, TFmode, "_U_Qfabs");
10389
10390   /* ia64_expand_compare uses this.  */
10391   cmptf_libfunc = init_one_libfunc ("_U_Qfcmp");
10392
10393   /* These should never be used.  */
10394   set_optab_libfunc (eq_optab, TFmode, 0);
10395   set_optab_libfunc (ne_optab, TFmode, 0);
10396   set_optab_libfunc (gt_optab, TFmode, 0);
10397   set_optab_libfunc (ge_optab, TFmode, 0);
10398   set_optab_libfunc (lt_optab, TFmode, 0);
10399   set_optab_libfunc (le_optab, TFmode, 0);
10400 }
10401
10402 /* Rename the division and modulus functions in VMS.  */
10403
10404 static void
10405 ia64_vms_init_libfuncs (void)
10406 {
10407   set_optab_libfunc (sdiv_optab, SImode, "OTS$DIV_I");
10408   set_optab_libfunc (sdiv_optab, DImode, "OTS$DIV_L");
10409   set_optab_libfunc (udiv_optab, SImode, "OTS$DIV_UI");
10410   set_optab_libfunc (udiv_optab, DImode, "OTS$DIV_UL");
10411   set_optab_libfunc (smod_optab, SImode, "OTS$REM_I");
10412   set_optab_libfunc (smod_optab, DImode, "OTS$REM_L");
10413   set_optab_libfunc (umod_optab, SImode, "OTS$REM_UI");
10414   set_optab_libfunc (umod_optab, DImode, "OTS$REM_UL");
10415   abort_libfunc = init_one_libfunc ("decc$abort");
10416   memcmp_libfunc = init_one_libfunc ("decc$memcmp");
10417 #ifdef MEM_LIBFUNCS_INIT
10418   MEM_LIBFUNCS_INIT;
10419 #endif
10420 }
10421
10422 /* Rename the TFmode libfuncs available from soft-fp in glibc using
10423    the HPUX conventions.  */
10424
10425 static void
10426 ia64_sysv4_init_libfuncs (void)
10427 {
10428   ia64_init_libfuncs ();
10429
10430   /* These functions are not part of the HPUX TFmode interface.  We
10431      use them instead of _U_Qfcmp, which doesn't work the way we
10432      expect.  */
10433   set_optab_libfunc (eq_optab, TFmode, "_U_Qfeq");
10434   set_optab_libfunc (ne_optab, TFmode, "_U_Qfne");
10435   set_optab_libfunc (gt_optab, TFmode, "_U_Qfgt");
10436   set_optab_libfunc (ge_optab, TFmode, "_U_Qfge");
10437   set_optab_libfunc (lt_optab, TFmode, "_U_Qflt");
10438   set_optab_libfunc (le_optab, TFmode, "_U_Qfle");
10439
10440   /* We leave out _U_Qfmin, _U_Qfmax and _U_Qfabs since soft-fp in
10441      glibc doesn't have them.  */
10442 }
10443
10444 /* Use soft-fp.  */
10445
10446 static void
10447 ia64_soft_fp_init_libfuncs (void)
10448 {
10449 }
10450
10451 static bool
10452 ia64_vms_valid_pointer_mode (enum machine_mode mode)
10453 {
10454   return (mode == SImode || mode == DImode);
10455 }
10456 \f
10457 /* For HPUX, it is illegal to have relocations in shared segments.  */
10458
10459 static int
10460 ia64_hpux_reloc_rw_mask (void)
10461 {
10462   return 3;
10463 }
10464
10465 /* For others, relax this so that relocations to local data goes in
10466    read-only segments, but we still cannot allow global relocations
10467    in read-only segments.  */
10468
10469 static int
10470 ia64_reloc_rw_mask (void)
10471 {
10472   return flag_pic ? 3 : 2;
10473 }
10474
10475 /* Return the section to use for X.  The only special thing we do here
10476    is to honor small data.  */
10477
10478 static section *
10479 ia64_select_rtx_section (enum machine_mode mode, rtx x,
10480                          unsigned HOST_WIDE_INT align)
10481 {
10482   if (GET_MODE_SIZE (mode) > 0
10483       && GET_MODE_SIZE (mode) <= ia64_section_threshold
10484       && !TARGET_NO_SDATA)
10485     return sdata_section;
10486   else
10487     return default_elf_select_rtx_section (mode, x, align);
10488 }
10489
10490 static unsigned int
10491 ia64_section_type_flags (tree decl, const char *name, int reloc)
10492 {
10493   unsigned int flags = 0;
10494
10495   if (strcmp (name, ".sdata") == 0
10496       || strncmp (name, ".sdata.", 7) == 0
10497       || strncmp (name, ".gnu.linkonce.s.", 16) == 0
10498       || strncmp (name, ".sdata2.", 8) == 0
10499       || strncmp (name, ".gnu.linkonce.s2.", 17) == 0
10500       || strcmp (name, ".sbss") == 0
10501       || strncmp (name, ".sbss.", 6) == 0
10502       || strncmp (name, ".gnu.linkonce.sb.", 17) == 0)
10503     flags = SECTION_SMALL;
10504
10505 #if TARGET_ABI_OPEN_VMS
10506   if (decl && DECL_ATTRIBUTES (decl)
10507       && lookup_attribute ("common_object", DECL_ATTRIBUTES (decl)))
10508     flags |= SECTION_VMS_OVERLAY;
10509 #endif
10510
10511   flags |= default_section_type_flags (decl, name, reloc);
10512   return flags;
10513 }
10514
10515 /* Returns true if FNTYPE (a FUNCTION_TYPE or a METHOD_TYPE) returns a
10516    structure type and that the address of that type should be passed
10517    in out0, rather than in r8.  */
10518
10519 static bool
10520 ia64_struct_retval_addr_is_first_parm_p (tree fntype)
10521 {
10522   tree ret_type = TREE_TYPE (fntype);
10523
10524   /* The Itanium C++ ABI requires that out0, rather than r8, be used
10525      as the structure return address parameter, if the return value
10526      type has a non-trivial copy constructor or destructor.  It is not
10527      clear if this same convention should be used for other
10528      programming languages.  Until G++ 3.4, we incorrectly used r8 for
10529      these return values.  */
10530   return (abi_version_at_least (2)
10531           && ret_type
10532           && TYPE_MODE (ret_type) == BLKmode 
10533           && TREE_ADDRESSABLE (ret_type)
10534           && strcmp (lang_hooks.name, "GNU C++") == 0);
10535 }
10536
10537 /* Output the assembler code for a thunk function.  THUNK_DECL is the
10538    declaration for the thunk function itself, FUNCTION is the decl for
10539    the target function.  DELTA is an immediate constant offset to be
10540    added to THIS.  If VCALL_OFFSET is nonzero, the word at
10541    *(*this + vcall_offset) should be added to THIS.  */
10542
10543 static void
10544 ia64_output_mi_thunk (FILE *file, tree thunk ATTRIBUTE_UNUSED,
10545                       HOST_WIDE_INT delta, HOST_WIDE_INT vcall_offset,
10546                       tree function)
10547 {
10548   rtx this_rtx, insn, funexp;
10549   unsigned int this_parmno;
10550   unsigned int this_regno;
10551   rtx delta_rtx;
10552
10553   reload_completed = 1;
10554   epilogue_completed = 1;
10555
10556   /* Set things up as ia64_expand_prologue might.  */
10557   last_scratch_gr_reg = 15;
10558
10559   memset (&current_frame_info, 0, sizeof (current_frame_info));
10560   current_frame_info.spill_cfa_off = -16;
10561   current_frame_info.n_input_regs = 1;
10562   current_frame_info.need_regstk = (TARGET_REG_NAMES != 0);
10563
10564   /* Mark the end of the (empty) prologue.  */
10565   emit_note (NOTE_INSN_PROLOGUE_END);
10566
10567   /* Figure out whether "this" will be the first parameter (the
10568      typical case) or the second parameter (as happens when the
10569      virtual function returns certain class objects).  */
10570   this_parmno
10571     = (ia64_struct_retval_addr_is_first_parm_p (TREE_TYPE (thunk))
10572        ? 1 : 0);
10573   this_regno = IN_REG (this_parmno);
10574   if (!TARGET_REG_NAMES)
10575     reg_names[this_regno] = ia64_reg_numbers[this_parmno];
10576
10577   this_rtx = gen_rtx_REG (Pmode, this_regno);
10578
10579   /* Apply the constant offset, if required.  */
10580   delta_rtx = GEN_INT (delta);
10581   if (TARGET_ILP32)
10582     {
10583       rtx tmp = gen_rtx_REG (ptr_mode, this_regno);
10584       REG_POINTER (tmp) = 1;
10585       if (delta && satisfies_constraint_I (delta_rtx))
10586         {
10587           emit_insn (gen_ptr_extend_plus_imm (this_rtx, tmp, delta_rtx));
10588           delta = 0;
10589         }
10590       else
10591         emit_insn (gen_ptr_extend (this_rtx, tmp));
10592     }
10593   if (delta)
10594     {
10595       if (!satisfies_constraint_I (delta_rtx))
10596         {
10597           rtx tmp = gen_rtx_REG (Pmode, 2);
10598           emit_move_insn (tmp, delta_rtx);
10599           delta_rtx = tmp;
10600         }
10601       emit_insn (gen_adddi3 (this_rtx, this_rtx, delta_rtx));
10602     }
10603
10604   /* Apply the offset from the vtable, if required.  */
10605   if (vcall_offset)
10606     {
10607       rtx vcall_offset_rtx = GEN_INT (vcall_offset);
10608       rtx tmp = gen_rtx_REG (Pmode, 2);
10609
10610       if (TARGET_ILP32)
10611         {
10612           rtx t = gen_rtx_REG (ptr_mode, 2);
10613           REG_POINTER (t) = 1;
10614           emit_move_insn (t, gen_rtx_MEM (ptr_mode, this_rtx));
10615           if (satisfies_constraint_I (vcall_offset_rtx))
10616             {
10617               emit_insn (gen_ptr_extend_plus_imm (tmp, t, vcall_offset_rtx));
10618               vcall_offset = 0;
10619             }
10620           else
10621             emit_insn (gen_ptr_extend (tmp, t));
10622         }
10623       else
10624         emit_move_insn (tmp, gen_rtx_MEM (Pmode, this_rtx));
10625
10626       if (vcall_offset)
10627         {
10628           if (!satisfies_constraint_J (vcall_offset_rtx))
10629             {
10630               rtx tmp2 = gen_rtx_REG (Pmode, next_scratch_gr_reg ());
10631               emit_move_insn (tmp2, vcall_offset_rtx);
10632               vcall_offset_rtx = tmp2;
10633             }
10634           emit_insn (gen_adddi3 (tmp, tmp, vcall_offset_rtx));
10635         }
10636
10637       if (TARGET_ILP32)
10638         emit_insn (gen_zero_extendsidi2 (tmp, gen_rtx_MEM (ptr_mode, tmp)));
10639       else
10640         emit_move_insn (tmp, gen_rtx_MEM (Pmode, tmp));
10641
10642       emit_insn (gen_adddi3 (this_rtx, this_rtx, tmp));
10643     }
10644
10645   /* Generate a tail call to the target function.  */
10646   if (! TREE_USED (function))
10647     {
10648       assemble_external (function);
10649       TREE_USED (function) = 1;
10650     }
10651   funexp = XEXP (DECL_RTL (function), 0);
10652   funexp = gen_rtx_MEM (FUNCTION_MODE, funexp);
10653   ia64_expand_call (NULL_RTX, funexp, NULL_RTX, 1);
10654   insn = get_last_insn ();
10655   SIBLING_CALL_P (insn) = 1;
10656
10657   /* Code generation for calls relies on splitting.  */
10658   reload_completed = 1;
10659   epilogue_completed = 1;
10660   try_split (PATTERN (insn), insn, 0);
10661
10662   emit_barrier ();
10663
10664   /* Run just enough of rest_of_compilation to get the insns emitted.
10665      There's not really enough bulk here to make other passes such as
10666      instruction scheduling worth while.  Note that use_thunk calls
10667      assemble_start_function and assemble_end_function.  */
10668
10669   insn_locators_alloc ();
10670   emit_all_insn_group_barriers (NULL);
10671   insn = get_insns ();
10672   shorten_branches (insn);
10673   final_start_function (insn, file, 1);
10674   final (insn, file, 1);
10675   final_end_function ();
10676
10677   reload_completed = 0;
10678   epilogue_completed = 0;
10679 }
10680
10681 /* Worker function for TARGET_STRUCT_VALUE_RTX.  */
10682
10683 static rtx
10684 ia64_struct_value_rtx (tree fntype,
10685                        int incoming ATTRIBUTE_UNUSED)
10686 {
10687   if (TARGET_ABI_OPEN_VMS ||
10688       (fntype && ia64_struct_retval_addr_is_first_parm_p (fntype)))
10689     return NULL_RTX;
10690   return gen_rtx_REG (Pmode, GR_REG (8));
10691 }
10692
10693 static bool
10694 ia64_scalar_mode_supported_p (enum machine_mode mode)
10695 {
10696   switch (mode)
10697     {
10698     case QImode:
10699     case HImode:
10700     case SImode:
10701     case DImode:
10702     case TImode:
10703       return true;
10704
10705     case SFmode:
10706     case DFmode:
10707     case XFmode:
10708     case RFmode:
10709       return true;
10710
10711     case TFmode:
10712       return true;
10713
10714     default:
10715       return false;
10716     }
10717 }
10718
10719 static bool
10720 ia64_vector_mode_supported_p (enum machine_mode mode)
10721 {
10722   switch (mode)
10723     {
10724     case V8QImode:
10725     case V4HImode:
10726     case V2SImode:
10727       return true;
10728
10729     case V2SFmode:
10730       return true;
10731
10732     default:
10733       return false;
10734     }
10735 }
10736
10737 /* Implement the FUNCTION_PROFILER macro.  */
10738
10739 void
10740 ia64_output_function_profiler (FILE *file, int labelno)
10741 {
10742   bool indirect_call;
10743
10744   /* If the function needs a static chain and the static chain
10745      register is r15, we use an indirect call so as to bypass
10746      the PLT stub in case the executable is dynamically linked,
10747      because the stub clobbers r15 as per 5.3.6 of the psABI.
10748      We don't need to do that in non canonical PIC mode.  */
10749
10750   if (cfun->static_chain_decl && !TARGET_NO_PIC && !TARGET_AUTO_PIC)
10751     {
10752       gcc_assert (STATIC_CHAIN_REGNUM == 15);
10753       indirect_call = true;
10754     }
10755   else
10756     indirect_call = false;
10757
10758   if (TARGET_GNU_AS)
10759     fputs ("\t.prologue 4, r40\n", file);
10760   else
10761     fputs ("\t.prologue\n\t.save ar.pfs, r40\n", file);
10762   fputs ("\talloc out0 = ar.pfs, 8, 0, 4, 0\n", file);
10763
10764   if (NO_PROFILE_COUNTERS)
10765     fputs ("\tmov out3 = r0\n", file);
10766   else
10767     {
10768       char buf[20];
10769       ASM_GENERATE_INTERNAL_LABEL (buf, "LP", labelno);
10770
10771       if (TARGET_AUTO_PIC)
10772         fputs ("\tmovl out3 = @gprel(", file);
10773       else
10774         fputs ("\taddl out3 = @ltoff(", file);
10775       assemble_name (file, buf);
10776       if (TARGET_AUTO_PIC)
10777         fputs (")\n", file);
10778       else
10779         fputs ("), r1\n", file);
10780     }
10781
10782   if (indirect_call)
10783     fputs ("\taddl r14 = @ltoff(@fptr(_mcount)), r1\n", file);
10784   fputs ("\t;;\n", file);
10785
10786   fputs ("\t.save rp, r42\n", file);
10787   fputs ("\tmov out2 = b0\n", file);
10788   if (indirect_call)
10789     fputs ("\tld8 r14 = [r14]\n\t;;\n", file);
10790   fputs ("\t.body\n", file);
10791   fputs ("\tmov out1 = r1\n", file);
10792   if (indirect_call)
10793     {
10794       fputs ("\tld8 r16 = [r14], 8\n\t;;\n", file);
10795       fputs ("\tmov b6 = r16\n", file);
10796       fputs ("\tld8 r1 = [r14]\n", file);
10797       fputs ("\tbr.call.sptk.many b0 = b6\n\t;;\n", file);
10798     }
10799   else
10800     fputs ("\tbr.call.sptk.many b0 = _mcount\n\t;;\n", file);
10801 }
10802
10803 static GTY(()) rtx mcount_func_rtx;
10804 static rtx
10805 gen_mcount_func_rtx (void)
10806 {
10807   if (!mcount_func_rtx)
10808     mcount_func_rtx = init_one_libfunc ("_mcount");
10809   return mcount_func_rtx;
10810 }
10811
10812 void
10813 ia64_profile_hook (int labelno)
10814 {
10815   rtx label, ip;
10816
10817   if (NO_PROFILE_COUNTERS)
10818     label = const0_rtx;
10819   else
10820     {
10821       char buf[30];
10822       const char *label_name;
10823       ASM_GENERATE_INTERNAL_LABEL (buf, "LP", labelno);
10824       label_name = (*targetm.strip_name_encoding) (ggc_strdup (buf));
10825       label = gen_rtx_SYMBOL_REF (Pmode, label_name);
10826       SYMBOL_REF_FLAGS (label) = SYMBOL_FLAG_LOCAL;
10827     }
10828   ip = gen_reg_rtx (Pmode);
10829   emit_insn (gen_ip_value (ip));
10830   emit_library_call (gen_mcount_func_rtx (), LCT_NORMAL,
10831                      VOIDmode, 3,
10832                      gen_rtx_REG (Pmode, BR_REG (0)), Pmode,
10833                      ip, Pmode,
10834                      label, Pmode);
10835 }
10836
10837 /* Return the mangling of TYPE if it is an extended fundamental type.  */
10838
10839 static const char *
10840 ia64_mangle_type (const_tree type)
10841 {
10842   type = TYPE_MAIN_VARIANT (type);
10843
10844   if (TREE_CODE (type) != VOID_TYPE && TREE_CODE (type) != BOOLEAN_TYPE
10845       && TREE_CODE (type) != INTEGER_TYPE && TREE_CODE (type) != REAL_TYPE)
10846     return NULL;
10847
10848   /* On HP-UX, "long double" is mangled as "e" so __float128 is
10849      mangled as "e".  */
10850   if (!TARGET_HPUX && TYPE_MODE (type) == TFmode)
10851     return "g";
10852   /* On HP-UX, "e" is not available as a mangling of __float80 so use
10853      an extended mangling.  Elsewhere, "e" is available since long
10854      double is 80 bits.  */
10855   if (TYPE_MODE (type) == XFmode)
10856     return TARGET_HPUX ? "u9__float80" : "e";
10857   if (TYPE_MODE (type) == RFmode)
10858     return "u7__fpreg";
10859   return NULL;
10860 }
10861
10862 /* Return the diagnostic message string if conversion from FROMTYPE to
10863    TOTYPE is not allowed, NULL otherwise.  */
10864 static const char *
10865 ia64_invalid_conversion (const_tree fromtype, const_tree totype)
10866 {
10867   /* Reject nontrivial conversion to or from __fpreg.  */
10868   if (TYPE_MODE (fromtype) == RFmode
10869       && TYPE_MODE (totype) != RFmode
10870       && TYPE_MODE (totype) != VOIDmode)
10871     return N_("invalid conversion from %<__fpreg%>");
10872   if (TYPE_MODE (totype) == RFmode
10873       && TYPE_MODE (fromtype) != RFmode)
10874     return N_("invalid conversion to %<__fpreg%>");
10875   return NULL;
10876 }
10877
10878 /* Return the diagnostic message string if the unary operation OP is
10879    not permitted on TYPE, NULL otherwise.  */
10880 static const char *
10881 ia64_invalid_unary_op (int op, const_tree type)
10882 {
10883   /* Reject operations on __fpreg other than unary + or &.  */
10884   if (TYPE_MODE (type) == RFmode
10885       && op != CONVERT_EXPR
10886       && op != ADDR_EXPR)
10887     return N_("invalid operation on %<__fpreg%>");
10888   return NULL;
10889 }
10890
10891 /* Return the diagnostic message string if the binary operation OP is
10892    not permitted on TYPE1 and TYPE2, NULL otherwise.  */
10893 static const char *
10894 ia64_invalid_binary_op (int op ATTRIBUTE_UNUSED, const_tree type1, const_tree type2)
10895 {
10896   /* Reject operations on __fpreg.  */
10897   if (TYPE_MODE (type1) == RFmode || TYPE_MODE (type2) == RFmode)
10898     return N_("invalid operation on %<__fpreg%>");
10899   return NULL;
10900 }
10901
10902 /* Implement TARGET_OPTION_DEFAULT_PARAMS.  */
10903 static void
10904 ia64_option_default_params (void)
10905 {
10906   /* Let the scheduler form additional regions.  */
10907   set_default_param_value (PARAM_MAX_SCHED_EXTEND_REGIONS_ITERS, 2);
10908
10909   /* Set the default values for cache-related parameters.  */
10910   set_default_param_value (PARAM_SIMULTANEOUS_PREFETCHES, 6);
10911   set_default_param_value (PARAM_L1_CACHE_LINE_SIZE, 32);
10912
10913   set_default_param_value (PARAM_SCHED_MEM_TRUE_DEP_COST, 4);
10914 }
10915
10916 /* HP-UX version_id attribute.
10917    For object foo, if the version_id is set to 1234 put out an alias
10918    of '.alias foo "foo{1234}"  We can't use "foo{1234}" in anything
10919    other than an alias statement because it is an illegal symbol name.  */
10920
10921 static tree
10922 ia64_handle_version_id_attribute (tree *node ATTRIBUTE_UNUSED,
10923                                  tree name ATTRIBUTE_UNUSED,
10924                                  tree args,
10925                                  int flags ATTRIBUTE_UNUSED,
10926                                  bool *no_add_attrs)
10927 {
10928   tree arg = TREE_VALUE (args);
10929
10930   if (TREE_CODE (arg) != STRING_CST)
10931     {
10932       error("version attribute is not a string");
10933       *no_add_attrs = true;
10934       return NULL_TREE;
10935     }
10936   return NULL_TREE;
10937 }
10938
10939 /* Target hook for c_mode_for_suffix.  */
10940
10941 static enum machine_mode
10942 ia64_c_mode_for_suffix (char suffix)
10943 {
10944   if (suffix == 'q')
10945     return TFmode;
10946   if (suffix == 'w')
10947     return XFmode;
10948
10949   return VOIDmode;
10950 }
10951
10952 static enum machine_mode
10953 ia64_promote_function_mode (const_tree type,
10954                             enum machine_mode mode,
10955                             int *punsignedp,
10956                             const_tree funtype,
10957                             int for_return)
10958 {
10959   /* Special processing required for OpenVMS ...  */
10960
10961   if (!TARGET_ABI_OPEN_VMS)
10962     return default_promote_function_mode(type, mode, punsignedp, funtype,
10963                                          for_return);
10964
10965   /* HP OpenVMS Calling Standard dated June, 2004, that describes
10966      HP OpenVMS I64 Version 8.2EFT,
10967      chapter 4 "OpenVMS I64 Conventions"
10968      section 4.7 "Procedure Linkage"
10969      subsection 4.7.5.2, "Normal Register Parameters"
10970
10971      "Unsigned integral (except unsigned 32-bit), set, and VAX floating-point
10972      values passed in registers are zero-filled; signed integral values as
10973      well as unsigned 32-bit integral values are sign-extended to 64 bits.
10974      For all other types passed in the general registers, unused bits are
10975      undefined."  */
10976
10977   if (!AGGREGATE_TYPE_P (type)
10978       && GET_MODE_CLASS (mode) == MODE_INT
10979       && GET_MODE_SIZE (mode) < UNITS_PER_WORD)
10980     {
10981       if (mode == SImode)
10982         *punsignedp = 0;
10983       return DImode;
10984     }
10985   else
10986     return promote_mode (type, mode, punsignedp);
10987 }
10988    
10989 static GTY(()) rtx ia64_dconst_0_5_rtx;
10990
10991 rtx
10992 ia64_dconst_0_5 (void)
10993 {
10994   if (! ia64_dconst_0_5_rtx)
10995     {
10996       REAL_VALUE_TYPE rv;
10997       real_from_string (&rv, "0.5");
10998       ia64_dconst_0_5_rtx = const_double_from_real_value (rv, DFmode);
10999     }
11000   return ia64_dconst_0_5_rtx;
11001 }
11002
11003 static GTY(()) rtx ia64_dconst_0_375_rtx;
11004
11005 rtx
11006 ia64_dconst_0_375 (void)
11007 {
11008   if (! ia64_dconst_0_375_rtx)
11009     {
11010       REAL_VALUE_TYPE rv;
11011       real_from_string (&rv, "0.375");
11012       ia64_dconst_0_375_rtx = const_double_from_real_value (rv, DFmode);
11013     }
11014   return ia64_dconst_0_375_rtx;
11015 }
11016
11017 static enum machine_mode
11018 ia64_get_reg_raw_mode (int regno)
11019 {
11020   if (FR_REGNO_P (regno))
11021     return XFmode;
11022   return default_get_reg_raw_mode(regno);
11023 }
11024
11025 #include "gt-ia64.h"