OSDN Git Service

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