OSDN Git Service

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