OSDN Git Service

arm: Convert to atomic optabs.
[pf3gnuchains/gcc-fork.git] / gcc / config / arm / arm.c
1 /* Output routines for GCC for ARM.
2    Copyright (C) 1991, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
3    2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012
4    Free Software Foundation, Inc.
5    Contributed by Pieter `Tiggr' Schoenmakers (rcpieter@win.tue.nl)
6    and Martin Simmons (@harleqn.co.uk).
7    More major hacks by Richard Earnshaw (rearnsha@arm.com).
8
9    This file is part of GCC.
10
11    GCC is free software; you can redistribute it and/or modify it
12    under the terms of the GNU General Public License as published
13    by the Free Software Foundation; either version 3, or (at your
14    option) any later version.
15
16    GCC is distributed in the hope that it will be useful, but WITHOUT
17    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
19    License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with GCC; see the file COPYING3.  If not see
23    <http://www.gnu.org/licenses/>.  */
24
25 #include "config.h"
26 #include "system.h"
27 #include "coretypes.h"
28 #include "tm.h"
29 #include "rtl.h"
30 #include "tree.h"
31 #include "obstack.h"
32 #include "regs.h"
33 #include "hard-reg-set.h"
34 #include "insn-config.h"
35 #include "conditions.h"
36 #include "output.h"
37 #include "insn-attr.h"
38 #include "flags.h"
39 #include "reload.h"
40 #include "function.h"
41 #include "expr.h"
42 #include "optabs.h"
43 #include "diagnostic-core.h"
44 #include "recog.h"
45 #include "cgraph.h"
46 #include "ggc.h"
47 #include "except.h"
48 #include "c-family/c-pragma.h"  /* ??? */
49 #include "integrate.h"
50 #include "tm_p.h"
51 #include "target.h"
52 #include "target-def.h"
53 #include "debug.h"
54 #include "langhooks.h"
55 #include "df.h"
56 #include "intl.h"
57 #include "libfuncs.h"
58 #include "params.h"
59 #include "opts.h"
60
61 /* Forward definitions of types.  */
62 typedef struct minipool_node    Mnode;
63 typedef struct minipool_fixup   Mfix;
64
65 void (*arm_lang_output_object_attributes_hook)(void);
66
67 struct four_ints
68 {
69   int i[4];
70 };
71
72 /* Forward function declarations.  */
73 static bool arm_needs_doubleword_align (enum machine_mode, const_tree);
74 static int arm_compute_static_chain_stack_bytes (void);
75 static arm_stack_offsets *arm_get_frame_offsets (void);
76 static void arm_add_gc_roots (void);
77 static int arm_gen_constant (enum rtx_code, enum machine_mode, rtx,
78                              HOST_WIDE_INT, rtx, rtx, int, int);
79 static unsigned bit_count (unsigned long);
80 static int arm_address_register_rtx_p (rtx, int);
81 static int arm_legitimate_index_p (enum machine_mode, rtx, RTX_CODE, int);
82 static int thumb2_legitimate_index_p (enum machine_mode, rtx, int);
83 static int thumb1_base_register_rtx_p (rtx, enum machine_mode, int);
84 static rtx arm_legitimize_address (rtx, rtx, enum machine_mode);
85 static rtx thumb_legitimize_address (rtx, rtx, enum machine_mode);
86 inline static int thumb1_index_register_rtx_p (rtx, int);
87 static bool arm_legitimate_address_p (enum machine_mode, rtx, bool);
88 static int thumb_far_jump_used_p (void);
89 static bool thumb_force_lr_save (void);
90 static rtx emit_sfm (int, int);
91 static unsigned arm_size_return_regs (void);
92 static bool arm_assemble_integer (rtx, unsigned int, int);
93 static void arm_print_operand (FILE *, rtx, int);
94 static void arm_print_operand_address (FILE *, rtx);
95 static bool arm_print_operand_punct_valid_p (unsigned char code);
96 static const char *fp_const_from_val (REAL_VALUE_TYPE *);
97 static arm_cc get_arm_condition_code (rtx);
98 static HOST_WIDE_INT int_log2 (HOST_WIDE_INT);
99 static rtx is_jump_table (rtx);
100 static const char *output_multi_immediate (rtx *, const char *, const char *,
101                                            int, HOST_WIDE_INT);
102 static const char *shift_op (rtx, HOST_WIDE_INT *);
103 static struct machine_function *arm_init_machine_status (void);
104 static void thumb_exit (FILE *, int);
105 static rtx is_jump_table (rtx);
106 static HOST_WIDE_INT get_jump_table_size (rtx);
107 static Mnode *move_minipool_fix_forward_ref (Mnode *, Mnode *, HOST_WIDE_INT);
108 static Mnode *add_minipool_forward_ref (Mfix *);
109 static Mnode *move_minipool_fix_backward_ref (Mnode *, Mnode *, HOST_WIDE_INT);
110 static Mnode *add_minipool_backward_ref (Mfix *);
111 static void assign_minipool_offsets (Mfix *);
112 static void arm_print_value (FILE *, rtx);
113 static void dump_minipool (rtx);
114 static int arm_barrier_cost (rtx);
115 static Mfix *create_fix_barrier (Mfix *, HOST_WIDE_INT);
116 static void push_minipool_barrier (rtx, HOST_WIDE_INT);
117 static void push_minipool_fix (rtx, HOST_WIDE_INT, rtx *, enum machine_mode,
118                                rtx);
119 static void arm_reorg (void);
120 static bool note_invalid_constants (rtx, HOST_WIDE_INT, int);
121 static unsigned long arm_compute_save_reg0_reg12_mask (void);
122 static unsigned long arm_compute_save_reg_mask (void);
123 static unsigned long arm_isr_value (tree);
124 static unsigned long arm_compute_func_type (void);
125 static tree arm_handle_fndecl_attribute (tree *, tree, tree, int, bool *);
126 static tree arm_handle_pcs_attribute (tree *, tree, tree, int, bool *);
127 static tree arm_handle_isr_attribute (tree *, tree, tree, int, bool *);
128 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
129 static tree arm_handle_notshared_attribute (tree *, tree, tree, int, bool *);
130 #endif
131 static void arm_output_function_epilogue (FILE *, HOST_WIDE_INT);
132 static void arm_output_function_prologue (FILE *, HOST_WIDE_INT);
133 static int arm_comp_type_attributes (const_tree, const_tree);
134 static void arm_set_default_type_attributes (tree);
135 static int arm_adjust_cost (rtx, rtx, rtx, int);
136 static int optimal_immediate_sequence (enum rtx_code code,
137                                        unsigned HOST_WIDE_INT val,
138                                        struct four_ints *return_sequence);
139 static int optimal_immediate_sequence_1 (enum rtx_code code,
140                                          unsigned HOST_WIDE_INT val,
141                                          struct four_ints *return_sequence,
142                                          int i);
143 static int arm_get_strip_length (int);
144 static bool arm_function_ok_for_sibcall (tree, tree);
145 static enum machine_mode arm_promote_function_mode (const_tree,
146                                                     enum machine_mode, int *,
147                                                     const_tree, int);
148 static bool arm_return_in_memory (const_tree, const_tree);
149 static rtx arm_function_value (const_tree, const_tree, bool);
150 static rtx arm_libcall_value_1 (enum machine_mode);
151 static rtx arm_libcall_value (enum machine_mode, const_rtx);
152 static bool arm_function_value_regno_p (const unsigned int);
153 static void arm_internal_label (FILE *, const char *, unsigned long);
154 static void arm_output_mi_thunk (FILE *, tree, HOST_WIDE_INT, HOST_WIDE_INT,
155                                  tree);
156 static bool arm_have_conditional_execution (void);
157 static bool arm_cannot_force_const_mem (enum machine_mode, rtx);
158 static bool arm_legitimate_constant_p (enum machine_mode, rtx);
159 static bool arm_rtx_costs_1 (rtx, enum rtx_code, int*, bool);
160 static bool arm_size_rtx_costs (rtx, enum rtx_code, enum rtx_code, int *);
161 static bool arm_slowmul_rtx_costs (rtx, enum rtx_code, enum rtx_code, int *, bool);
162 static bool arm_fastmul_rtx_costs (rtx, enum rtx_code, enum rtx_code, int *, bool);
163 static bool arm_xscale_rtx_costs (rtx, enum rtx_code, enum rtx_code, int *, bool);
164 static bool arm_9e_rtx_costs (rtx, enum rtx_code, enum rtx_code, int *, bool);
165 static bool arm_rtx_costs (rtx, int, int, int, int *, bool);
166 static int arm_address_cost (rtx, bool);
167 static int arm_register_move_cost (enum machine_mode, reg_class_t, reg_class_t);
168 static int arm_memory_move_cost (enum machine_mode, reg_class_t, bool);
169 static bool arm_memory_load_p (rtx);
170 static bool arm_cirrus_insn_p (rtx);
171 static void cirrus_reorg (rtx);
172 static void arm_init_builtins (void);
173 static void arm_init_iwmmxt_builtins (void);
174 static rtx safe_vector_operand (rtx, enum machine_mode);
175 static rtx arm_expand_binop_builtin (enum insn_code, tree, rtx);
176 static rtx arm_expand_unop_builtin (enum insn_code, tree, rtx, int);
177 static rtx arm_expand_builtin (tree, rtx, rtx, enum machine_mode, int);
178 static tree arm_builtin_decl (unsigned, bool);
179 static void emit_constant_insn (rtx cond, rtx pattern);
180 static rtx emit_set_insn (rtx, rtx);
181 static int arm_arg_partial_bytes (cumulative_args_t, enum machine_mode,
182                                   tree, bool);
183 static rtx arm_function_arg (cumulative_args_t, enum machine_mode,
184                              const_tree, bool);
185 static void arm_function_arg_advance (cumulative_args_t, enum machine_mode,
186                                       const_tree, bool);
187 static unsigned int arm_function_arg_boundary (enum machine_mode, const_tree);
188 static rtx aapcs_allocate_return_reg (enum machine_mode, const_tree,
189                                       const_tree);
190 static rtx aapcs_libcall_value (enum machine_mode);
191 static int aapcs_select_return_coproc (const_tree, const_tree);
192
193 #ifdef OBJECT_FORMAT_ELF
194 static void arm_elf_asm_constructor (rtx, int) ATTRIBUTE_UNUSED;
195 static void arm_elf_asm_destructor (rtx, int) ATTRIBUTE_UNUSED;
196 #endif
197 #ifndef ARM_PE
198 static void arm_encode_section_info (tree, rtx, int);
199 #endif
200
201 static void arm_file_end (void);
202 static void arm_file_start (void);
203
204 static void arm_setup_incoming_varargs (cumulative_args_t, enum machine_mode,
205                                         tree, int *, int);
206 static bool arm_pass_by_reference (cumulative_args_t,
207                                    enum machine_mode, const_tree, bool);
208 static bool arm_promote_prototypes (const_tree);
209 static bool arm_default_short_enums (void);
210 static bool arm_align_anon_bitfield (void);
211 static bool arm_return_in_msb (const_tree);
212 static bool arm_must_pass_in_stack (enum machine_mode, const_tree);
213 static bool arm_return_in_memory (const_tree, const_tree);
214 #if ARM_UNWIND_INFO
215 static void arm_unwind_emit (FILE *, rtx);
216 static bool arm_output_ttype (rtx);
217 static void arm_asm_emit_except_personality (rtx);
218 static void arm_asm_init_sections (void);
219 #endif
220 static rtx arm_dwarf_register_span (rtx);
221
222 static tree arm_cxx_guard_type (void);
223 static bool arm_cxx_guard_mask_bit (void);
224 static tree arm_get_cookie_size (tree);
225 static bool arm_cookie_has_size (void);
226 static bool arm_cxx_cdtor_returns_this (void);
227 static bool arm_cxx_key_method_may_be_inline (void);
228 static void arm_cxx_determine_class_data_visibility (tree);
229 static bool arm_cxx_class_data_always_comdat (void);
230 static bool arm_cxx_use_aeabi_atexit (void);
231 static void arm_init_libfuncs (void);
232 static tree arm_build_builtin_va_list (void);
233 static void arm_expand_builtin_va_start (tree, rtx);
234 static tree arm_gimplify_va_arg_expr (tree, tree, gimple_seq *, gimple_seq *);
235 static void arm_option_override (void);
236 static unsigned HOST_WIDE_INT arm_shift_truncation_mask (enum machine_mode);
237 static bool arm_cannot_copy_insn_p (rtx);
238 static bool arm_tls_symbol_p (rtx x);
239 static int arm_issue_rate (void);
240 static void arm_output_dwarf_dtprel (FILE *, int, rtx) ATTRIBUTE_UNUSED;
241 static bool arm_output_addr_const_extra (FILE *, rtx);
242 static bool arm_allocate_stack_slots_for_args (void);
243 static const char *arm_invalid_parameter_type (const_tree t);
244 static const char *arm_invalid_return_type (const_tree t);
245 static tree arm_promoted_type (const_tree t);
246 static tree arm_convert_to_type (tree type, tree expr);
247 static bool arm_scalar_mode_supported_p (enum machine_mode);
248 static bool arm_frame_pointer_required (void);
249 static bool arm_can_eliminate (const int, const int);
250 static void arm_asm_trampoline_template (FILE *);
251 static void arm_trampoline_init (rtx, tree, rtx);
252 static rtx arm_trampoline_adjust_address (rtx);
253 static rtx arm_pic_static_addr (rtx orig, rtx reg);
254 static bool cortex_a9_sched_adjust_cost (rtx, rtx, rtx, int *);
255 static bool xscale_sched_adjust_cost (rtx, rtx, rtx, int *);
256 static bool fa726te_sched_adjust_cost (rtx, rtx, rtx, int *);
257 static bool arm_array_mode_supported_p (enum machine_mode,
258                                         unsigned HOST_WIDE_INT);
259 static enum machine_mode arm_preferred_simd_mode (enum machine_mode);
260 static bool arm_class_likely_spilled_p (reg_class_t);
261 static bool arm_vector_alignment_reachable (const_tree type, bool is_packed);
262 static bool arm_builtin_support_vector_misalignment (enum machine_mode mode,
263                                                      const_tree type,
264                                                      int misalignment,
265                                                      bool is_packed);
266 static void arm_conditional_register_usage (void);
267 static reg_class_t arm_preferred_rename_class (reg_class_t rclass);
268 static unsigned int arm_autovectorize_vector_sizes (void);
269 static int arm_default_branch_cost (bool, bool);
270 static int arm_cortex_a5_branch_cost (bool, bool);
271
272 \f
273 /* Table of machine attributes.  */
274 static const struct attribute_spec arm_attribute_table[] =
275 {
276   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler,
277        affects_type_identity } */
278   /* Function calls made to this symbol must be done indirectly, because
279      it may lie outside of the 26 bit addressing range of a normal function
280      call.  */
281   { "long_call",    0, 0, false, true,  true,  NULL, false },
282   /* Whereas these functions are always known to reside within the 26 bit
283      addressing range.  */
284   { "short_call",   0, 0, false, true,  true,  NULL, false },
285   /* Specify the procedure call conventions for a function.  */
286   { "pcs",          1, 1, false, true,  true,  arm_handle_pcs_attribute,
287     false },
288   /* Interrupt Service Routines have special prologue and epilogue requirements.  */
289   { "isr",          0, 1, false, false, false, arm_handle_isr_attribute,
290     false },
291   { "interrupt",    0, 1, false, false, false, arm_handle_isr_attribute,
292     false },
293   { "naked",        0, 0, true,  false, false, arm_handle_fndecl_attribute,
294     false },
295 #ifdef ARM_PE
296   /* ARM/PE has three new attributes:
297      interfacearm - ?
298      dllexport - for exporting a function/variable that will live in a dll
299      dllimport - for importing a function/variable from a dll
300
301      Microsoft allows multiple declspecs in one __declspec, separating
302      them with spaces.  We do NOT support this.  Instead, use __declspec
303      multiple times.
304   */
305   { "dllimport",    0, 0, true,  false, false, NULL, false },
306   { "dllexport",    0, 0, true,  false, false, NULL, false },
307   { "interfacearm", 0, 0, true,  false, false, arm_handle_fndecl_attribute,
308     false },
309 #elif TARGET_DLLIMPORT_DECL_ATTRIBUTES
310   { "dllimport",    0, 0, false, false, false, handle_dll_attribute, false },
311   { "dllexport",    0, 0, false, false, false, handle_dll_attribute, false },
312   { "notshared",    0, 0, false, true, false, arm_handle_notshared_attribute,
313     false },
314 #endif
315   { NULL,           0, 0, false, false, false, NULL, false }
316 };
317 \f
318 /* Initialize the GCC target structure.  */
319 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
320 #undef  TARGET_MERGE_DECL_ATTRIBUTES
321 #define TARGET_MERGE_DECL_ATTRIBUTES merge_dllimport_decl_attributes
322 #endif
323
324 #undef TARGET_LEGITIMIZE_ADDRESS
325 #define TARGET_LEGITIMIZE_ADDRESS arm_legitimize_address
326
327 #undef  TARGET_ATTRIBUTE_TABLE
328 #define TARGET_ATTRIBUTE_TABLE arm_attribute_table
329
330 #undef TARGET_ASM_FILE_START
331 #define TARGET_ASM_FILE_START arm_file_start
332 #undef TARGET_ASM_FILE_END
333 #define TARGET_ASM_FILE_END arm_file_end
334
335 #undef  TARGET_ASM_ALIGNED_SI_OP
336 #define TARGET_ASM_ALIGNED_SI_OP NULL
337 #undef  TARGET_ASM_INTEGER
338 #define TARGET_ASM_INTEGER arm_assemble_integer
339
340 #undef TARGET_PRINT_OPERAND
341 #define TARGET_PRINT_OPERAND arm_print_operand
342 #undef TARGET_PRINT_OPERAND_ADDRESS
343 #define TARGET_PRINT_OPERAND_ADDRESS arm_print_operand_address
344 #undef TARGET_PRINT_OPERAND_PUNCT_VALID_P
345 #define TARGET_PRINT_OPERAND_PUNCT_VALID_P arm_print_operand_punct_valid_p
346
347 #undef TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA
348 #define TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA arm_output_addr_const_extra
349
350 #undef  TARGET_ASM_FUNCTION_PROLOGUE
351 #define TARGET_ASM_FUNCTION_PROLOGUE arm_output_function_prologue
352
353 #undef  TARGET_ASM_FUNCTION_EPILOGUE
354 #define TARGET_ASM_FUNCTION_EPILOGUE arm_output_function_epilogue
355
356 #undef  TARGET_OPTION_OVERRIDE
357 #define TARGET_OPTION_OVERRIDE arm_option_override
358
359 #undef  TARGET_COMP_TYPE_ATTRIBUTES
360 #define TARGET_COMP_TYPE_ATTRIBUTES arm_comp_type_attributes
361
362 #undef  TARGET_SET_DEFAULT_TYPE_ATTRIBUTES
363 #define TARGET_SET_DEFAULT_TYPE_ATTRIBUTES arm_set_default_type_attributes
364
365 #undef  TARGET_SCHED_ADJUST_COST
366 #define TARGET_SCHED_ADJUST_COST arm_adjust_cost
367
368 #undef TARGET_REGISTER_MOVE_COST
369 #define TARGET_REGISTER_MOVE_COST arm_register_move_cost
370
371 #undef TARGET_MEMORY_MOVE_COST
372 #define TARGET_MEMORY_MOVE_COST arm_memory_move_cost
373
374 #undef TARGET_ENCODE_SECTION_INFO
375 #ifdef ARM_PE
376 #define TARGET_ENCODE_SECTION_INFO  arm_pe_encode_section_info
377 #else
378 #define TARGET_ENCODE_SECTION_INFO  arm_encode_section_info
379 #endif
380
381 #undef  TARGET_STRIP_NAME_ENCODING
382 #define TARGET_STRIP_NAME_ENCODING arm_strip_name_encoding
383
384 #undef  TARGET_ASM_INTERNAL_LABEL
385 #define TARGET_ASM_INTERNAL_LABEL arm_internal_label
386
387 #undef  TARGET_FUNCTION_OK_FOR_SIBCALL
388 #define TARGET_FUNCTION_OK_FOR_SIBCALL arm_function_ok_for_sibcall
389
390 #undef  TARGET_FUNCTION_VALUE
391 #define TARGET_FUNCTION_VALUE arm_function_value
392
393 #undef  TARGET_LIBCALL_VALUE
394 #define TARGET_LIBCALL_VALUE arm_libcall_value
395
396 #undef TARGET_FUNCTION_VALUE_REGNO_P
397 #define TARGET_FUNCTION_VALUE_REGNO_P arm_function_value_regno_p
398
399 #undef  TARGET_ASM_OUTPUT_MI_THUNK
400 #define TARGET_ASM_OUTPUT_MI_THUNK arm_output_mi_thunk
401 #undef  TARGET_ASM_CAN_OUTPUT_MI_THUNK
402 #define TARGET_ASM_CAN_OUTPUT_MI_THUNK default_can_output_mi_thunk_no_vcall
403
404 #undef  TARGET_RTX_COSTS
405 #define TARGET_RTX_COSTS arm_rtx_costs
406 #undef  TARGET_ADDRESS_COST
407 #define TARGET_ADDRESS_COST arm_address_cost
408
409 #undef TARGET_SHIFT_TRUNCATION_MASK
410 #define TARGET_SHIFT_TRUNCATION_MASK arm_shift_truncation_mask
411 #undef TARGET_VECTOR_MODE_SUPPORTED_P
412 #define TARGET_VECTOR_MODE_SUPPORTED_P arm_vector_mode_supported_p
413 #undef TARGET_ARRAY_MODE_SUPPORTED_P
414 #define TARGET_ARRAY_MODE_SUPPORTED_P arm_array_mode_supported_p
415 #undef TARGET_VECTORIZE_PREFERRED_SIMD_MODE
416 #define TARGET_VECTORIZE_PREFERRED_SIMD_MODE arm_preferred_simd_mode
417 #undef TARGET_VECTORIZE_AUTOVECTORIZE_VECTOR_SIZES
418 #define TARGET_VECTORIZE_AUTOVECTORIZE_VECTOR_SIZES \
419   arm_autovectorize_vector_sizes
420
421 #undef  TARGET_MACHINE_DEPENDENT_REORG
422 #define TARGET_MACHINE_DEPENDENT_REORG arm_reorg
423
424 #undef  TARGET_INIT_BUILTINS
425 #define TARGET_INIT_BUILTINS  arm_init_builtins
426 #undef  TARGET_EXPAND_BUILTIN
427 #define TARGET_EXPAND_BUILTIN arm_expand_builtin
428 #undef  TARGET_BUILTIN_DECL
429 #define TARGET_BUILTIN_DECL arm_builtin_decl
430
431 #undef TARGET_INIT_LIBFUNCS
432 #define TARGET_INIT_LIBFUNCS arm_init_libfuncs
433
434 #undef TARGET_PROMOTE_FUNCTION_MODE
435 #define TARGET_PROMOTE_FUNCTION_MODE arm_promote_function_mode
436 #undef TARGET_PROMOTE_PROTOTYPES
437 #define TARGET_PROMOTE_PROTOTYPES arm_promote_prototypes
438 #undef TARGET_PASS_BY_REFERENCE
439 #define TARGET_PASS_BY_REFERENCE arm_pass_by_reference
440 #undef TARGET_ARG_PARTIAL_BYTES
441 #define TARGET_ARG_PARTIAL_BYTES arm_arg_partial_bytes
442 #undef TARGET_FUNCTION_ARG
443 #define TARGET_FUNCTION_ARG arm_function_arg
444 #undef TARGET_FUNCTION_ARG_ADVANCE
445 #define TARGET_FUNCTION_ARG_ADVANCE arm_function_arg_advance
446 #undef TARGET_FUNCTION_ARG_BOUNDARY
447 #define TARGET_FUNCTION_ARG_BOUNDARY arm_function_arg_boundary
448
449 #undef  TARGET_SETUP_INCOMING_VARARGS
450 #define TARGET_SETUP_INCOMING_VARARGS arm_setup_incoming_varargs
451
452 #undef TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS
453 #define TARGET_ALLOCATE_STACK_SLOTS_FOR_ARGS arm_allocate_stack_slots_for_args
454
455 #undef TARGET_ASM_TRAMPOLINE_TEMPLATE
456 #define TARGET_ASM_TRAMPOLINE_TEMPLATE arm_asm_trampoline_template
457 #undef TARGET_TRAMPOLINE_INIT
458 #define TARGET_TRAMPOLINE_INIT arm_trampoline_init
459 #undef TARGET_TRAMPOLINE_ADJUST_ADDRESS
460 #define TARGET_TRAMPOLINE_ADJUST_ADDRESS arm_trampoline_adjust_address
461
462 #undef TARGET_DEFAULT_SHORT_ENUMS
463 #define TARGET_DEFAULT_SHORT_ENUMS arm_default_short_enums
464
465 #undef TARGET_ALIGN_ANON_BITFIELD
466 #define TARGET_ALIGN_ANON_BITFIELD arm_align_anon_bitfield
467
468 #undef TARGET_NARROW_VOLATILE_BITFIELD
469 #define TARGET_NARROW_VOLATILE_BITFIELD hook_bool_void_false
470
471 #undef TARGET_CXX_GUARD_TYPE
472 #define TARGET_CXX_GUARD_TYPE arm_cxx_guard_type
473
474 #undef TARGET_CXX_GUARD_MASK_BIT
475 #define TARGET_CXX_GUARD_MASK_BIT arm_cxx_guard_mask_bit
476
477 #undef TARGET_CXX_GET_COOKIE_SIZE
478 #define TARGET_CXX_GET_COOKIE_SIZE arm_get_cookie_size
479
480 #undef TARGET_CXX_COOKIE_HAS_SIZE
481 #define TARGET_CXX_COOKIE_HAS_SIZE arm_cookie_has_size
482
483 #undef TARGET_CXX_CDTOR_RETURNS_THIS
484 #define TARGET_CXX_CDTOR_RETURNS_THIS arm_cxx_cdtor_returns_this
485
486 #undef TARGET_CXX_KEY_METHOD_MAY_BE_INLINE
487 #define TARGET_CXX_KEY_METHOD_MAY_BE_INLINE arm_cxx_key_method_may_be_inline
488
489 #undef TARGET_CXX_USE_AEABI_ATEXIT
490 #define TARGET_CXX_USE_AEABI_ATEXIT arm_cxx_use_aeabi_atexit
491
492 #undef TARGET_CXX_DETERMINE_CLASS_DATA_VISIBILITY
493 #define TARGET_CXX_DETERMINE_CLASS_DATA_VISIBILITY \
494   arm_cxx_determine_class_data_visibility
495
496 #undef TARGET_CXX_CLASS_DATA_ALWAYS_COMDAT
497 #define TARGET_CXX_CLASS_DATA_ALWAYS_COMDAT arm_cxx_class_data_always_comdat
498
499 #undef TARGET_RETURN_IN_MSB
500 #define TARGET_RETURN_IN_MSB arm_return_in_msb
501
502 #undef TARGET_RETURN_IN_MEMORY
503 #define TARGET_RETURN_IN_MEMORY arm_return_in_memory
504
505 #undef TARGET_MUST_PASS_IN_STACK
506 #define TARGET_MUST_PASS_IN_STACK arm_must_pass_in_stack
507
508 #if ARM_UNWIND_INFO
509 #undef TARGET_ASM_UNWIND_EMIT
510 #define TARGET_ASM_UNWIND_EMIT arm_unwind_emit
511
512 /* EABI unwinding tables use a different format for the typeinfo tables.  */
513 #undef TARGET_ASM_TTYPE
514 #define TARGET_ASM_TTYPE arm_output_ttype
515
516 #undef TARGET_ARM_EABI_UNWINDER
517 #define TARGET_ARM_EABI_UNWINDER true
518
519 #undef TARGET_ASM_EMIT_EXCEPT_PERSONALITY
520 #define TARGET_ASM_EMIT_EXCEPT_PERSONALITY arm_asm_emit_except_personality
521
522 #undef TARGET_ASM_INIT_SECTIONS
523 #define TARGET_ASM_INIT_SECTIONS arm_asm_init_sections
524 #endif /* ARM_UNWIND_INFO */
525
526 #undef TARGET_DWARF_REGISTER_SPAN
527 #define TARGET_DWARF_REGISTER_SPAN arm_dwarf_register_span
528
529 #undef  TARGET_CANNOT_COPY_INSN_P
530 #define TARGET_CANNOT_COPY_INSN_P arm_cannot_copy_insn_p
531
532 #ifdef HAVE_AS_TLS
533 #undef TARGET_HAVE_TLS
534 #define TARGET_HAVE_TLS true
535 #endif
536
537 #undef TARGET_HAVE_CONDITIONAL_EXECUTION
538 #define TARGET_HAVE_CONDITIONAL_EXECUTION arm_have_conditional_execution
539
540 #undef TARGET_LEGITIMATE_CONSTANT_P
541 #define TARGET_LEGITIMATE_CONSTANT_P arm_legitimate_constant_p
542
543 #undef TARGET_CANNOT_FORCE_CONST_MEM
544 #define TARGET_CANNOT_FORCE_CONST_MEM arm_cannot_force_const_mem
545
546 #undef TARGET_MAX_ANCHOR_OFFSET
547 #define TARGET_MAX_ANCHOR_OFFSET 4095
548
549 /* The minimum is set such that the total size of the block
550    for a particular anchor is -4088 + 1 + 4095 bytes, which is
551    divisible by eight, ensuring natural spacing of anchors.  */
552 #undef TARGET_MIN_ANCHOR_OFFSET
553 #define TARGET_MIN_ANCHOR_OFFSET -4088
554
555 #undef TARGET_SCHED_ISSUE_RATE
556 #define TARGET_SCHED_ISSUE_RATE arm_issue_rate
557
558 #undef TARGET_MANGLE_TYPE
559 #define TARGET_MANGLE_TYPE arm_mangle_type
560
561 #undef TARGET_BUILD_BUILTIN_VA_LIST
562 #define TARGET_BUILD_BUILTIN_VA_LIST arm_build_builtin_va_list
563 #undef TARGET_EXPAND_BUILTIN_VA_START
564 #define TARGET_EXPAND_BUILTIN_VA_START arm_expand_builtin_va_start
565 #undef TARGET_GIMPLIFY_VA_ARG_EXPR
566 #define TARGET_GIMPLIFY_VA_ARG_EXPR arm_gimplify_va_arg_expr
567
568 #ifdef HAVE_AS_TLS
569 #undef TARGET_ASM_OUTPUT_DWARF_DTPREL
570 #define TARGET_ASM_OUTPUT_DWARF_DTPREL arm_output_dwarf_dtprel
571 #endif
572
573 #undef TARGET_LEGITIMATE_ADDRESS_P
574 #define TARGET_LEGITIMATE_ADDRESS_P     arm_legitimate_address_p
575
576 #undef TARGET_INVALID_PARAMETER_TYPE
577 #define TARGET_INVALID_PARAMETER_TYPE arm_invalid_parameter_type
578
579 #undef TARGET_INVALID_RETURN_TYPE
580 #define TARGET_INVALID_RETURN_TYPE arm_invalid_return_type
581
582 #undef TARGET_PROMOTED_TYPE
583 #define TARGET_PROMOTED_TYPE arm_promoted_type
584
585 #undef TARGET_CONVERT_TO_TYPE
586 #define TARGET_CONVERT_TO_TYPE arm_convert_to_type
587
588 #undef TARGET_SCALAR_MODE_SUPPORTED_P
589 #define TARGET_SCALAR_MODE_SUPPORTED_P arm_scalar_mode_supported_p
590
591 #undef TARGET_FRAME_POINTER_REQUIRED
592 #define TARGET_FRAME_POINTER_REQUIRED arm_frame_pointer_required
593
594 #undef TARGET_CAN_ELIMINATE
595 #define TARGET_CAN_ELIMINATE arm_can_eliminate
596
597 #undef TARGET_CONDITIONAL_REGISTER_USAGE
598 #define TARGET_CONDITIONAL_REGISTER_USAGE arm_conditional_register_usage
599
600 #undef TARGET_CLASS_LIKELY_SPILLED_P
601 #define TARGET_CLASS_LIKELY_SPILLED_P arm_class_likely_spilled_p
602
603 #undef TARGET_VECTORIZE_VECTOR_ALIGNMENT_REACHABLE
604 #define TARGET_VECTORIZE_VECTOR_ALIGNMENT_REACHABLE \
605   arm_vector_alignment_reachable
606
607 #undef TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT
608 #define TARGET_VECTORIZE_SUPPORT_VECTOR_MISALIGNMENT \
609   arm_builtin_support_vector_misalignment
610
611 #undef TARGET_PREFERRED_RENAME_CLASS
612 #define TARGET_PREFERRED_RENAME_CLASS \
613   arm_preferred_rename_class
614
615 struct gcc_target targetm = TARGET_INITIALIZER;
616 \f
617 /* Obstack for minipool constant handling.  */
618 static struct obstack minipool_obstack;
619 static char *         minipool_startobj;
620
621 /* The maximum number of insns skipped which
622    will be conditionalised if possible.  */
623 static int max_insns_skipped = 5;
624
625 extern FILE * asm_out_file;
626
627 /* True if we are currently building a constant table.  */
628 int making_const_table;
629
630 /* The processor for which instructions should be scheduled.  */
631 enum processor_type arm_tune = arm_none;
632
633 /* The current tuning set.  */
634 const struct tune_params *current_tune;
635
636 /* Which floating point hardware to schedule for.  */
637 int arm_fpu_attr;
638
639 /* Which floating popint hardware to use.  */
640 const struct arm_fpu_desc *arm_fpu_desc;
641
642 /* Used for Thumb call_via trampolines.  */
643 rtx thumb_call_via_label[14];
644 static int thumb_call_reg_needed;
645
646 /* Bit values used to identify processor capabilities.  */
647 #define FL_CO_PROC    (1 << 0)        /* Has external co-processor bus */
648 #define FL_ARCH3M     (1 << 1)        /* Extended multiply */
649 #define FL_MODE26     (1 << 2)        /* 26-bit mode support */
650 #define FL_MODE32     (1 << 3)        /* 32-bit mode support */
651 #define FL_ARCH4      (1 << 4)        /* Architecture rel 4 */
652 #define FL_ARCH5      (1 << 5)        /* Architecture rel 5 */
653 #define FL_THUMB      (1 << 6)        /* Thumb aware */
654 #define FL_LDSCHED    (1 << 7)        /* Load scheduling necessary */
655 #define FL_STRONG     (1 << 8)        /* StrongARM */
656 #define FL_ARCH5E     (1 << 9)        /* DSP extensions to v5 */
657 #define FL_XSCALE     (1 << 10)       /* XScale */
658 #define FL_CIRRUS     (1 << 11)       /* Cirrus/DSP.  */
659 #define FL_ARCH6      (1 << 12)       /* Architecture rel 6.  Adds
660                                          media instructions.  */
661 #define FL_VFPV2      (1 << 13)       /* Vector Floating Point V2.  */
662 #define FL_WBUF       (1 << 14)       /* Schedule for write buffer ops.
663                                          Note: ARM6 & 7 derivatives only.  */
664 #define FL_ARCH6K     (1 << 15)       /* Architecture rel 6 K extensions.  */
665 #define FL_THUMB2     (1 << 16)       /* Thumb-2.  */
666 #define FL_NOTM       (1 << 17)       /* Instructions not present in the 'M'
667                                          profile.  */
668 #define FL_THUMB_DIV  (1 << 18)       /* Hardware divide (Thumb mode).  */
669 #define FL_VFPV3      (1 << 19)       /* Vector Floating Point V3.  */
670 #define FL_NEON       (1 << 20)       /* Neon instructions.  */
671 #define FL_ARCH7EM    (1 << 21)       /* Instructions present in the ARMv7E-M
672                                          architecture.  */
673 #define FL_ARCH7      (1 << 22)       /* Architecture 7.  */
674 #define FL_ARM_DIV    (1 << 23)       /* Hardware divide (ARM mode).  */
675
676 #define FL_IWMMXT     (1 << 29)       /* XScale v2 or "Intel Wireless MMX technology".  */
677
678 /* Flags that only effect tuning, not available instructions.  */
679 #define FL_TUNE         (FL_WBUF | FL_VFPV2 | FL_STRONG | FL_LDSCHED \
680                          | FL_CO_PROC)
681
682 #define FL_FOR_ARCH2    FL_NOTM
683 #define FL_FOR_ARCH3    (FL_FOR_ARCH2 | FL_MODE32)
684 #define FL_FOR_ARCH3M   (FL_FOR_ARCH3 | FL_ARCH3M)
685 #define FL_FOR_ARCH4    (FL_FOR_ARCH3M | FL_ARCH4)
686 #define FL_FOR_ARCH4T   (FL_FOR_ARCH4 | FL_THUMB)
687 #define FL_FOR_ARCH5    (FL_FOR_ARCH4 | FL_ARCH5)
688 #define FL_FOR_ARCH5T   (FL_FOR_ARCH5 | FL_THUMB)
689 #define FL_FOR_ARCH5E   (FL_FOR_ARCH5 | FL_ARCH5E)
690 #define FL_FOR_ARCH5TE  (FL_FOR_ARCH5E | FL_THUMB)
691 #define FL_FOR_ARCH5TEJ FL_FOR_ARCH5TE
692 #define FL_FOR_ARCH6    (FL_FOR_ARCH5TE | FL_ARCH6)
693 #define FL_FOR_ARCH6J   FL_FOR_ARCH6
694 #define FL_FOR_ARCH6K   (FL_FOR_ARCH6 | FL_ARCH6K)
695 #define FL_FOR_ARCH6Z   FL_FOR_ARCH6
696 #define FL_FOR_ARCH6ZK  FL_FOR_ARCH6K
697 #define FL_FOR_ARCH6T2  (FL_FOR_ARCH6 | FL_THUMB2)
698 #define FL_FOR_ARCH6M   (FL_FOR_ARCH6 & ~FL_NOTM)
699 #define FL_FOR_ARCH7    ((FL_FOR_ARCH6T2 & ~FL_NOTM) | FL_ARCH7)
700 #define FL_FOR_ARCH7A   (FL_FOR_ARCH7 | FL_NOTM | FL_ARCH6K)
701 #define FL_FOR_ARCH7R   (FL_FOR_ARCH7A | FL_THUMB_DIV)
702 #define FL_FOR_ARCH7M   (FL_FOR_ARCH7 | FL_THUMB_DIV)
703 #define FL_FOR_ARCH7EM  (FL_FOR_ARCH7M | FL_ARCH7EM)
704
705 /* The bits in this mask specify which
706    instructions we are allowed to generate.  */
707 static unsigned long insn_flags = 0;
708
709 /* The bits in this mask specify which instruction scheduling options should
710    be used.  */
711 static unsigned long tune_flags = 0;
712
713 /* The following are used in the arm.md file as equivalents to bits
714    in the above two flag variables.  */
715
716 /* Nonzero if this chip supports the ARM Architecture 3M extensions.  */
717 int arm_arch3m = 0;
718
719 /* Nonzero if this chip supports the ARM Architecture 4 extensions.  */
720 int arm_arch4 = 0;
721
722 /* Nonzero if this chip supports the ARM Architecture 4t extensions.  */
723 int arm_arch4t = 0;
724
725 /* Nonzero if this chip supports the ARM Architecture 5 extensions.  */
726 int arm_arch5 = 0;
727
728 /* Nonzero if this chip supports the ARM Architecture 5E extensions.  */
729 int arm_arch5e = 0;
730
731 /* Nonzero if this chip supports the ARM Architecture 6 extensions.  */
732 int arm_arch6 = 0;
733
734 /* Nonzero if this chip supports the ARM 6K extensions.  */
735 int arm_arch6k = 0;
736
737 /* Nonzero if this chip supports the ARM 7 extensions.  */
738 int arm_arch7 = 0;
739
740 /* Nonzero if instructions not present in the 'M' profile can be used.  */
741 int arm_arch_notm = 0;
742
743 /* Nonzero if instructions present in ARMv7E-M can be used.  */
744 int arm_arch7em = 0;
745
746 /* Nonzero if this chip can benefit from load scheduling.  */
747 int arm_ld_sched = 0;
748
749 /* Nonzero if this chip is a StrongARM.  */
750 int arm_tune_strongarm = 0;
751
752 /* Nonzero if this chip is a Cirrus variant.  */
753 int arm_arch_cirrus = 0;
754
755 /* Nonzero if this chip supports Intel Wireless MMX technology.  */
756 int arm_arch_iwmmxt = 0;
757
758 /* Nonzero if this chip is an XScale.  */
759 int arm_arch_xscale = 0;
760
761 /* Nonzero if tuning for XScale  */
762 int arm_tune_xscale = 0;
763
764 /* Nonzero if we want to tune for stores that access the write-buffer.
765    This typically means an ARM6 or ARM7 with MMU or MPU.  */
766 int arm_tune_wbuf = 0;
767
768 /* Nonzero if tuning for Cortex-A9.  */
769 int arm_tune_cortex_a9 = 0;
770
771 /* Nonzero if generating Thumb instructions.  */
772 int thumb_code = 0;
773
774 /* Nonzero if generating Thumb-1 instructions.  */
775 int thumb1_code = 0;
776
777 /* Nonzero if we should define __THUMB_INTERWORK__ in the
778    preprocessor.
779    XXX This is a bit of a hack, it's intended to help work around
780    problems in GLD which doesn't understand that armv5t code is
781    interworking clean.  */
782 int arm_cpp_interwork = 0;
783
784 /* Nonzero if chip supports Thumb 2.  */
785 int arm_arch_thumb2;
786
787 /* Nonzero if chip supports integer division instruction.  */
788 int arm_arch_arm_hwdiv;
789 int arm_arch_thumb_hwdiv;
790
791 /* In case of a PRE_INC, POST_INC, PRE_DEC, POST_DEC memory reference,
792    we must report the mode of the memory reference from
793    TARGET_PRINT_OPERAND to TARGET_PRINT_OPERAND_ADDRESS.  */
794 enum machine_mode output_memory_reference_mode;
795
796 /* The register number to be used for the PIC offset register.  */
797 unsigned arm_pic_register = INVALID_REGNUM;
798
799 /* Set to 1 after arm_reorg has started.  Reset to start at the start of
800    the next function.  */
801 static int after_arm_reorg = 0;
802
803 enum arm_pcs arm_pcs_default;
804
805 /* For an explanation of these variables, see final_prescan_insn below.  */
806 int arm_ccfsm_state;
807 /* arm_current_cc is also used for Thumb-2 cond_exec blocks.  */
808 enum arm_cond_code arm_current_cc;
809
810 rtx arm_target_insn;
811 int arm_target_label;
812 /* The number of conditionally executed insns, including the current insn.  */
813 int arm_condexec_count = 0;
814 /* A bitmask specifying the patterns for the IT block.
815    Zero means do not output an IT block before this insn. */
816 int arm_condexec_mask = 0;
817 /* The number of bits used in arm_condexec_mask.  */
818 int arm_condexec_masklen = 0;
819
820 /* The condition codes of the ARM, and the inverse function.  */
821 static const char * const arm_condition_codes[] =
822 {
823   "eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc",
824   "hi", "ls", "ge", "lt", "gt", "le", "al", "nv"
825 };
826
827 /* The register numbers in sequence, for passing to arm_gen_load_multiple.  */
828 int arm_regs_in_sequence[] =
829 {
830   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
831 };
832
833 #define ARM_LSL_NAME (TARGET_UNIFIED_ASM ? "lsl" : "asl")
834 #define streq(string1, string2) (strcmp (string1, string2) == 0)
835
836 #define THUMB2_WORK_REGS (0xff & ~(  (1 << THUMB_HARD_FRAME_POINTER_REGNUM) \
837                                    | (1 << SP_REGNUM) | (1 << PC_REGNUM) \
838                                    | (1 << PIC_OFFSET_TABLE_REGNUM)))
839 \f
840 /* Initialization code.  */
841
842 struct processors
843 {
844   const char *const name;
845   enum processor_type core;
846   const char *arch;
847   const unsigned long flags;
848   const struct tune_params *const tune;
849 };
850
851
852 #define ARM_PREFETCH_NOT_BENEFICIAL 0, -1, -1
853 #define ARM_PREFETCH_BENEFICIAL(prefetch_slots,l1_size,l1_line_size) \
854   prefetch_slots, \
855   l1_size, \
856   l1_line_size
857
858 const struct tune_params arm_slowmul_tune =
859 {
860   arm_slowmul_rtx_costs,
861   NULL,
862   3,                                            /* Constant limit.  */
863   5,                                            /* Max cond insns.  */
864   ARM_PREFETCH_NOT_BENEFICIAL,
865   true,                                         /* Prefer constant pool.  */
866   arm_default_branch_cost
867 };
868
869 const struct tune_params arm_fastmul_tune =
870 {
871   arm_fastmul_rtx_costs,
872   NULL,
873   1,                                            /* Constant limit.  */
874   5,                                            /* Max cond insns.  */
875   ARM_PREFETCH_NOT_BENEFICIAL,
876   true,                                         /* Prefer constant pool.  */
877   arm_default_branch_cost
878 };
879
880 /* StrongARM has early execution of branches, so a sequence that is worth
881    skipping is shorter.  Set max_insns_skipped to a lower value.  */
882
883 const struct tune_params arm_strongarm_tune =
884 {
885   arm_fastmul_rtx_costs,
886   NULL,
887   1,                                            /* Constant limit.  */
888   3,                                            /* Max cond insns.  */
889   ARM_PREFETCH_NOT_BENEFICIAL,
890   true,                                         /* Prefer constant pool.  */
891   arm_default_branch_cost
892 };
893
894 const struct tune_params arm_xscale_tune =
895 {
896   arm_xscale_rtx_costs,
897   xscale_sched_adjust_cost,
898   2,                                            /* Constant limit.  */
899   3,                                            /* Max cond insns.  */
900   ARM_PREFETCH_NOT_BENEFICIAL,
901   true,                                         /* Prefer constant pool.  */
902   arm_default_branch_cost
903 };
904
905 const struct tune_params arm_9e_tune =
906 {
907   arm_9e_rtx_costs,
908   NULL,
909   1,                                            /* Constant limit.  */
910   5,                                            /* Max cond insns.  */
911   ARM_PREFETCH_NOT_BENEFICIAL,
912   true,                                         /* Prefer constant pool.  */
913   arm_default_branch_cost
914 };
915
916 const struct tune_params arm_v6t2_tune =
917 {
918   arm_9e_rtx_costs,
919   NULL,
920   1,                                            /* Constant limit.  */
921   5,                                            /* Max cond insns.  */
922   ARM_PREFETCH_NOT_BENEFICIAL,
923   false,                                        /* Prefer constant pool.  */
924   arm_default_branch_cost
925 };
926
927 /* Generic Cortex tuning.  Use more specific tunings if appropriate.  */
928 const struct tune_params arm_cortex_tune =
929 {
930   arm_9e_rtx_costs,
931   NULL,
932   1,                                            /* Constant limit.  */
933   5,                                            /* Max cond insns.  */
934   ARM_PREFETCH_NOT_BENEFICIAL,
935   false,                                        /* Prefer constant pool.  */
936   arm_default_branch_cost
937 };
938
939 /* Branches can be dual-issued on Cortex-A5, so conditional execution is
940    less appealing.  Set max_insns_skipped to a low value.  */
941
942 const struct tune_params arm_cortex_a5_tune =
943 {
944   arm_9e_rtx_costs,
945   NULL,
946   1,                                            /* Constant limit.  */
947   1,                                            /* Max cond insns.  */
948   ARM_PREFETCH_NOT_BENEFICIAL,
949   false,                                        /* Prefer constant pool.  */
950   arm_cortex_a5_branch_cost
951 };
952
953 const struct tune_params arm_cortex_a9_tune =
954 {
955   arm_9e_rtx_costs,
956   cortex_a9_sched_adjust_cost,
957   1,                                            /* Constant limit.  */
958   5,                                            /* Max cond insns.  */
959   ARM_PREFETCH_BENEFICIAL(4,32,32),
960   false,                                        /* Prefer constant pool.  */
961   arm_default_branch_cost
962 };
963
964 const struct tune_params arm_cortex_a15_tune =
965 {
966   arm_9e_rtx_costs,
967   NULL,
968   1,                                            /* Constant limit.  */
969   1,                                            /* Max cond insns.  */
970   ARM_PREFETCH_NOT_BENEFICIAL,                  /* TODO: Calculate correct values.  */
971   false,                                        /* Prefer constant pool.  */
972   arm_cortex_a5_branch_cost
973 };
974
975 const struct tune_params arm_fa726te_tune =
976 {
977   arm_9e_rtx_costs,
978   fa726te_sched_adjust_cost,
979   1,                                            /* Constant limit.  */
980   5,                                            /* Max cond insns.  */
981   ARM_PREFETCH_NOT_BENEFICIAL,
982   true,                                         /* Prefer constant pool.  */
983   arm_default_branch_cost
984 };
985
986
987 /* Not all of these give usefully different compilation alternatives,
988    but there is no simple way of generalizing them.  */
989 static const struct processors all_cores[] =
990 {
991   /* ARM Cores */
992 #define ARM_CORE(NAME, IDENT, ARCH, FLAGS, COSTS) \
993   {NAME, IDENT, #ARCH, FLAGS | FL_FOR_ARCH##ARCH, &arm_##COSTS##_tune},
994 #include "arm-cores.def"
995 #undef ARM_CORE
996   {NULL, arm_none, NULL, 0, NULL}
997 };
998
999 static const struct processors all_architectures[] =
1000 {
1001   /* ARM Architectures */
1002   /* We don't specify tuning costs here as it will be figured out
1003      from the core.  */
1004
1005 #define ARM_ARCH(NAME, CORE, ARCH, FLAGS) \
1006   {NAME, CORE, #ARCH, FLAGS, NULL},
1007 #include "arm-arches.def"
1008 #undef ARM_ARCH
1009   {NULL, arm_none, NULL, 0 , NULL}
1010 };
1011
1012
1013 /* These are populated as commandline arguments are processed, or NULL
1014    if not specified.  */
1015 static const struct processors *arm_selected_arch;
1016 static const struct processors *arm_selected_cpu;
1017 static const struct processors *arm_selected_tune;
1018
1019 /* The name of the preprocessor macro to define for this architecture.  */
1020
1021 char arm_arch_name[] = "__ARM_ARCH_0UNK__";
1022
1023 /* Available values for -mfpu=.  */
1024
1025 static const struct arm_fpu_desc all_fpus[] =
1026 {
1027 #define ARM_FPU(NAME, MODEL, REV, VFP_REGS, NEON, FP16) \
1028   { NAME, MODEL, REV, VFP_REGS, NEON, FP16 },
1029 #include "arm-fpus.def"
1030 #undef ARM_FPU
1031 };
1032
1033
1034 /* Supported TLS relocations.  */
1035
1036 enum tls_reloc {
1037   TLS_GD32,
1038   TLS_LDM32,
1039   TLS_LDO32,
1040   TLS_IE32,
1041   TLS_LE32,
1042   TLS_DESCSEQ   /* GNU scheme */
1043 };
1044
1045 /* The maximum number of insns to be used when loading a constant.  */
1046 inline static int
1047 arm_constant_limit (bool size_p)
1048 {
1049   return size_p ? 1 : current_tune->constant_limit;
1050 }
1051
1052 /* Emit an insn that's a simple single-set.  Both the operands must be known
1053    to be valid.  */
1054 inline static rtx
1055 emit_set_insn (rtx x, rtx y)
1056 {
1057   return emit_insn (gen_rtx_SET (VOIDmode, x, y));
1058 }
1059
1060 /* Return the number of bits set in VALUE.  */
1061 static unsigned
1062 bit_count (unsigned long value)
1063 {
1064   unsigned long count = 0;
1065
1066   while (value)
1067     {
1068       count++;
1069       value &= value - 1;  /* Clear the least-significant set bit.  */
1070     }
1071
1072   return count;
1073 }
1074
1075 typedef struct
1076 {
1077   enum machine_mode mode;
1078   const char *name;
1079 } arm_fixed_mode_set;
1080
1081 /* A small helper for setting fixed-point library libfuncs.  */
1082
1083 static void
1084 arm_set_fixed_optab_libfunc (optab optable, enum machine_mode mode,
1085                              const char *funcname, const char *modename,
1086                              int num_suffix)
1087 {
1088   char buffer[50];
1089
1090   if (num_suffix == 0)
1091     sprintf (buffer, "__gnu_%s%s", funcname, modename);
1092   else
1093     sprintf (buffer, "__gnu_%s%s%d", funcname, modename, num_suffix);
1094
1095   set_optab_libfunc (optable, mode, buffer);
1096 }
1097
1098 static void
1099 arm_set_fixed_conv_libfunc (convert_optab optable, enum machine_mode to,
1100                             enum machine_mode from, const char *funcname,
1101                             const char *toname, const char *fromname)
1102 {
1103   char buffer[50];
1104   const char *maybe_suffix_2 = "";
1105
1106   /* Follow the logic for selecting a "2" suffix in fixed-bit.h.  */
1107   if (ALL_FIXED_POINT_MODE_P (from) && ALL_FIXED_POINT_MODE_P (to)
1108       && UNSIGNED_FIXED_POINT_MODE_P (from) == UNSIGNED_FIXED_POINT_MODE_P (to)
1109       && ALL_FRACT_MODE_P (from) == ALL_FRACT_MODE_P (to))
1110     maybe_suffix_2 = "2";
1111
1112   sprintf (buffer, "__gnu_%s%s%s%s", funcname, fromname, toname,
1113            maybe_suffix_2);
1114
1115   set_conv_libfunc (optable, to, from, buffer);
1116 }
1117
1118 /* Set up library functions unique to ARM.  */
1119
1120 static void
1121 arm_init_libfuncs (void)
1122 {
1123   /* For Linux, we have access to kernel support for atomic operations.  */
1124   if (arm_abi == ARM_ABI_AAPCS_LINUX)
1125     init_sync_libfuncs (2 * UNITS_PER_WORD);
1126
1127   /* There are no special library functions unless we are using the
1128      ARM BPABI.  */
1129   if (!TARGET_BPABI)
1130     return;
1131
1132   /* The functions below are described in Section 4 of the "Run-Time
1133      ABI for the ARM architecture", Version 1.0.  */
1134
1135   /* Double-precision floating-point arithmetic.  Table 2.  */
1136   set_optab_libfunc (add_optab, DFmode, "__aeabi_dadd");
1137   set_optab_libfunc (sdiv_optab, DFmode, "__aeabi_ddiv");
1138   set_optab_libfunc (smul_optab, DFmode, "__aeabi_dmul");
1139   set_optab_libfunc (neg_optab, DFmode, "__aeabi_dneg");
1140   set_optab_libfunc (sub_optab, DFmode, "__aeabi_dsub");
1141
1142   /* Double-precision comparisons.  Table 3.  */
1143   set_optab_libfunc (eq_optab, DFmode, "__aeabi_dcmpeq");
1144   set_optab_libfunc (ne_optab, DFmode, NULL);
1145   set_optab_libfunc (lt_optab, DFmode, "__aeabi_dcmplt");
1146   set_optab_libfunc (le_optab, DFmode, "__aeabi_dcmple");
1147   set_optab_libfunc (ge_optab, DFmode, "__aeabi_dcmpge");
1148   set_optab_libfunc (gt_optab, DFmode, "__aeabi_dcmpgt");
1149   set_optab_libfunc (unord_optab, DFmode, "__aeabi_dcmpun");
1150
1151   /* Single-precision floating-point arithmetic.  Table 4.  */
1152   set_optab_libfunc (add_optab, SFmode, "__aeabi_fadd");
1153   set_optab_libfunc (sdiv_optab, SFmode, "__aeabi_fdiv");
1154   set_optab_libfunc (smul_optab, SFmode, "__aeabi_fmul");
1155   set_optab_libfunc (neg_optab, SFmode, "__aeabi_fneg");
1156   set_optab_libfunc (sub_optab, SFmode, "__aeabi_fsub");
1157
1158   /* Single-precision comparisons.  Table 5.  */
1159   set_optab_libfunc (eq_optab, SFmode, "__aeabi_fcmpeq");
1160   set_optab_libfunc (ne_optab, SFmode, NULL);
1161   set_optab_libfunc (lt_optab, SFmode, "__aeabi_fcmplt");
1162   set_optab_libfunc (le_optab, SFmode, "__aeabi_fcmple");
1163   set_optab_libfunc (ge_optab, SFmode, "__aeabi_fcmpge");
1164   set_optab_libfunc (gt_optab, SFmode, "__aeabi_fcmpgt");
1165   set_optab_libfunc (unord_optab, SFmode, "__aeabi_fcmpun");
1166
1167   /* Floating-point to integer conversions.  Table 6.  */
1168   set_conv_libfunc (sfix_optab, SImode, DFmode, "__aeabi_d2iz");
1169   set_conv_libfunc (ufix_optab, SImode, DFmode, "__aeabi_d2uiz");
1170   set_conv_libfunc (sfix_optab, DImode, DFmode, "__aeabi_d2lz");
1171   set_conv_libfunc (ufix_optab, DImode, DFmode, "__aeabi_d2ulz");
1172   set_conv_libfunc (sfix_optab, SImode, SFmode, "__aeabi_f2iz");
1173   set_conv_libfunc (ufix_optab, SImode, SFmode, "__aeabi_f2uiz");
1174   set_conv_libfunc (sfix_optab, DImode, SFmode, "__aeabi_f2lz");
1175   set_conv_libfunc (ufix_optab, DImode, SFmode, "__aeabi_f2ulz");
1176
1177   /* Conversions between floating types.  Table 7.  */
1178   set_conv_libfunc (trunc_optab, SFmode, DFmode, "__aeabi_d2f");
1179   set_conv_libfunc (sext_optab, DFmode, SFmode, "__aeabi_f2d");
1180
1181   /* Integer to floating-point conversions.  Table 8.  */
1182   set_conv_libfunc (sfloat_optab, DFmode, SImode, "__aeabi_i2d");
1183   set_conv_libfunc (ufloat_optab, DFmode, SImode, "__aeabi_ui2d");
1184   set_conv_libfunc (sfloat_optab, DFmode, DImode, "__aeabi_l2d");
1185   set_conv_libfunc (ufloat_optab, DFmode, DImode, "__aeabi_ul2d");
1186   set_conv_libfunc (sfloat_optab, SFmode, SImode, "__aeabi_i2f");
1187   set_conv_libfunc (ufloat_optab, SFmode, SImode, "__aeabi_ui2f");
1188   set_conv_libfunc (sfloat_optab, SFmode, DImode, "__aeabi_l2f");
1189   set_conv_libfunc (ufloat_optab, SFmode, DImode, "__aeabi_ul2f");
1190
1191   /* Long long.  Table 9.  */
1192   set_optab_libfunc (smul_optab, DImode, "__aeabi_lmul");
1193   set_optab_libfunc (sdivmod_optab, DImode, "__aeabi_ldivmod");
1194   set_optab_libfunc (udivmod_optab, DImode, "__aeabi_uldivmod");
1195   set_optab_libfunc (ashl_optab, DImode, "__aeabi_llsl");
1196   set_optab_libfunc (lshr_optab, DImode, "__aeabi_llsr");
1197   set_optab_libfunc (ashr_optab, DImode, "__aeabi_lasr");
1198   set_optab_libfunc (cmp_optab, DImode, "__aeabi_lcmp");
1199   set_optab_libfunc (ucmp_optab, DImode, "__aeabi_ulcmp");
1200
1201   /* Integer (32/32->32) division.  \S 4.3.1.  */
1202   set_optab_libfunc (sdivmod_optab, SImode, "__aeabi_idivmod");
1203   set_optab_libfunc (udivmod_optab, SImode, "__aeabi_uidivmod");
1204
1205   /* The divmod functions are designed so that they can be used for
1206      plain division, even though they return both the quotient and the
1207      remainder.  The quotient is returned in the usual location (i.e.,
1208      r0 for SImode, {r0, r1} for DImode), just as would be expected
1209      for an ordinary division routine.  Because the AAPCS calling
1210      conventions specify that all of { r0, r1, r2, r3 } are
1211      callee-saved registers, there is no need to tell the compiler
1212      explicitly that those registers are clobbered by these
1213      routines.  */
1214   set_optab_libfunc (sdiv_optab, DImode, "__aeabi_ldivmod");
1215   set_optab_libfunc (udiv_optab, DImode, "__aeabi_uldivmod");
1216
1217   /* For SImode division the ABI provides div-without-mod routines,
1218      which are faster.  */
1219   set_optab_libfunc (sdiv_optab, SImode, "__aeabi_idiv");
1220   set_optab_libfunc (udiv_optab, SImode, "__aeabi_uidiv");
1221
1222   /* We don't have mod libcalls.  Fortunately gcc knows how to use the
1223      divmod libcalls instead.  */
1224   set_optab_libfunc (smod_optab, DImode, NULL);
1225   set_optab_libfunc (umod_optab, DImode, NULL);
1226   set_optab_libfunc (smod_optab, SImode, NULL);
1227   set_optab_libfunc (umod_optab, SImode, NULL);
1228
1229   /* Half-precision float operations.  The compiler handles all operations
1230      with NULL libfuncs by converting the SFmode.  */
1231   switch (arm_fp16_format)
1232     {
1233     case ARM_FP16_FORMAT_IEEE:
1234     case ARM_FP16_FORMAT_ALTERNATIVE:
1235
1236       /* Conversions.  */
1237       set_conv_libfunc (trunc_optab, HFmode, SFmode,
1238                         (arm_fp16_format == ARM_FP16_FORMAT_IEEE
1239                          ? "__gnu_f2h_ieee"
1240                          : "__gnu_f2h_alternative"));
1241       set_conv_libfunc (sext_optab, SFmode, HFmode,
1242                         (arm_fp16_format == ARM_FP16_FORMAT_IEEE
1243                          ? "__gnu_h2f_ieee"
1244                          : "__gnu_h2f_alternative"));
1245
1246       /* Arithmetic.  */
1247       set_optab_libfunc (add_optab, HFmode, NULL);
1248       set_optab_libfunc (sdiv_optab, HFmode, NULL);
1249       set_optab_libfunc (smul_optab, HFmode, NULL);
1250       set_optab_libfunc (neg_optab, HFmode, NULL);
1251       set_optab_libfunc (sub_optab, HFmode, NULL);
1252
1253       /* Comparisons.  */
1254       set_optab_libfunc (eq_optab, HFmode, NULL);
1255       set_optab_libfunc (ne_optab, HFmode, NULL);
1256       set_optab_libfunc (lt_optab, HFmode, NULL);
1257       set_optab_libfunc (le_optab, HFmode, NULL);
1258       set_optab_libfunc (ge_optab, HFmode, NULL);
1259       set_optab_libfunc (gt_optab, HFmode, NULL);
1260       set_optab_libfunc (unord_optab, HFmode, NULL);
1261       break;
1262
1263     default:
1264       break;
1265     }
1266
1267   /* Use names prefixed with __gnu_ for fixed-point helper functions.  */
1268   {
1269     const arm_fixed_mode_set fixed_arith_modes[] =
1270       {
1271         { QQmode, "qq" },
1272         { UQQmode, "uqq" },
1273         { HQmode, "hq" },
1274         { UHQmode, "uhq" },
1275         { SQmode, "sq" },
1276         { USQmode, "usq" },
1277         { DQmode, "dq" },
1278         { UDQmode, "udq" },
1279         { TQmode, "tq" },
1280         { UTQmode, "utq" },
1281         { HAmode, "ha" },
1282         { UHAmode, "uha" },
1283         { SAmode, "sa" },
1284         { USAmode, "usa" },
1285         { DAmode, "da" },
1286         { UDAmode, "uda" },
1287         { TAmode, "ta" },
1288         { UTAmode, "uta" }
1289       };
1290     const arm_fixed_mode_set fixed_conv_modes[] =
1291       {
1292         { QQmode, "qq" },
1293         { UQQmode, "uqq" },
1294         { HQmode, "hq" },
1295         { UHQmode, "uhq" },
1296         { SQmode, "sq" },
1297         { USQmode, "usq" },
1298         { DQmode, "dq" },
1299         { UDQmode, "udq" },
1300         { TQmode, "tq" },
1301         { UTQmode, "utq" },
1302         { HAmode, "ha" },
1303         { UHAmode, "uha" },
1304         { SAmode, "sa" },
1305         { USAmode, "usa" },
1306         { DAmode, "da" },
1307         { UDAmode, "uda" },
1308         { TAmode, "ta" },
1309         { UTAmode, "uta" },
1310         { QImode, "qi" },
1311         { HImode, "hi" },
1312         { SImode, "si" },
1313         { DImode, "di" },
1314         { TImode, "ti" },
1315         { SFmode, "sf" },
1316         { DFmode, "df" }
1317       };
1318     unsigned int i, j;
1319
1320     for (i = 0; i < ARRAY_SIZE (fixed_arith_modes); i++)
1321       {
1322         arm_set_fixed_optab_libfunc (add_optab, fixed_arith_modes[i].mode,
1323                                      "add", fixed_arith_modes[i].name, 3);
1324         arm_set_fixed_optab_libfunc (ssadd_optab, fixed_arith_modes[i].mode,
1325                                      "ssadd", fixed_arith_modes[i].name, 3);
1326         arm_set_fixed_optab_libfunc (usadd_optab, fixed_arith_modes[i].mode,
1327                                      "usadd", fixed_arith_modes[i].name, 3);
1328         arm_set_fixed_optab_libfunc (sub_optab, fixed_arith_modes[i].mode,
1329                                      "sub", fixed_arith_modes[i].name, 3);
1330         arm_set_fixed_optab_libfunc (sssub_optab, fixed_arith_modes[i].mode,
1331                                      "sssub", fixed_arith_modes[i].name, 3);
1332         arm_set_fixed_optab_libfunc (ussub_optab, fixed_arith_modes[i].mode,
1333                                      "ussub", fixed_arith_modes[i].name, 3);
1334         arm_set_fixed_optab_libfunc (smul_optab, fixed_arith_modes[i].mode,
1335                                      "mul", fixed_arith_modes[i].name, 3);
1336         arm_set_fixed_optab_libfunc (ssmul_optab, fixed_arith_modes[i].mode,
1337                                      "ssmul", fixed_arith_modes[i].name, 3);
1338         arm_set_fixed_optab_libfunc (usmul_optab, fixed_arith_modes[i].mode,
1339                                      "usmul", fixed_arith_modes[i].name, 3);
1340         arm_set_fixed_optab_libfunc (sdiv_optab, fixed_arith_modes[i].mode,
1341                                      "div", fixed_arith_modes[i].name, 3);
1342         arm_set_fixed_optab_libfunc (udiv_optab, fixed_arith_modes[i].mode,
1343                                      "udiv", fixed_arith_modes[i].name, 3);
1344         arm_set_fixed_optab_libfunc (ssdiv_optab, fixed_arith_modes[i].mode,
1345                                      "ssdiv", fixed_arith_modes[i].name, 3);
1346         arm_set_fixed_optab_libfunc (usdiv_optab, fixed_arith_modes[i].mode,
1347                                      "usdiv", fixed_arith_modes[i].name, 3);
1348         arm_set_fixed_optab_libfunc (neg_optab, fixed_arith_modes[i].mode,
1349                                      "neg", fixed_arith_modes[i].name, 2);
1350         arm_set_fixed_optab_libfunc (ssneg_optab, fixed_arith_modes[i].mode,
1351                                      "ssneg", fixed_arith_modes[i].name, 2);
1352         arm_set_fixed_optab_libfunc (usneg_optab, fixed_arith_modes[i].mode,
1353                                      "usneg", fixed_arith_modes[i].name, 2);
1354         arm_set_fixed_optab_libfunc (ashl_optab, fixed_arith_modes[i].mode,
1355                                      "ashl", fixed_arith_modes[i].name, 3);
1356         arm_set_fixed_optab_libfunc (ashr_optab, fixed_arith_modes[i].mode,
1357                                      "ashr", fixed_arith_modes[i].name, 3);
1358         arm_set_fixed_optab_libfunc (lshr_optab, fixed_arith_modes[i].mode,
1359                                      "lshr", fixed_arith_modes[i].name, 3);
1360         arm_set_fixed_optab_libfunc (ssashl_optab, fixed_arith_modes[i].mode,
1361                                      "ssashl", fixed_arith_modes[i].name, 3);
1362         arm_set_fixed_optab_libfunc (usashl_optab, fixed_arith_modes[i].mode,
1363                                      "usashl", fixed_arith_modes[i].name, 3);
1364         arm_set_fixed_optab_libfunc (cmp_optab, fixed_arith_modes[i].mode,
1365                                      "cmp", fixed_arith_modes[i].name, 2);
1366       }
1367
1368     for (i = 0; i < ARRAY_SIZE (fixed_conv_modes); i++)
1369       for (j = 0; j < ARRAY_SIZE (fixed_conv_modes); j++)
1370         {
1371           if (i == j
1372               || (!ALL_FIXED_POINT_MODE_P (fixed_conv_modes[i].mode)
1373                   && !ALL_FIXED_POINT_MODE_P (fixed_conv_modes[j].mode)))
1374             continue;
1375
1376           arm_set_fixed_conv_libfunc (fract_optab, fixed_conv_modes[i].mode,
1377                                       fixed_conv_modes[j].mode, "fract",
1378                                       fixed_conv_modes[i].name,
1379                                       fixed_conv_modes[j].name);
1380           arm_set_fixed_conv_libfunc (satfract_optab,
1381                                       fixed_conv_modes[i].mode,
1382                                       fixed_conv_modes[j].mode, "satfract",
1383                                       fixed_conv_modes[i].name,
1384                                       fixed_conv_modes[j].name);
1385           arm_set_fixed_conv_libfunc (fractuns_optab,
1386                                       fixed_conv_modes[i].mode,
1387                                       fixed_conv_modes[j].mode, "fractuns",
1388                                       fixed_conv_modes[i].name,
1389                                       fixed_conv_modes[j].name);
1390           arm_set_fixed_conv_libfunc (satfractuns_optab,
1391                                       fixed_conv_modes[i].mode,
1392                                       fixed_conv_modes[j].mode, "satfractuns",
1393                                       fixed_conv_modes[i].name,
1394                                       fixed_conv_modes[j].name);
1395         }
1396   }
1397
1398   if (TARGET_AAPCS_BASED)
1399     synchronize_libfunc = init_one_libfunc ("__sync_synchronize");
1400 }
1401
1402 /* On AAPCS systems, this is the "struct __va_list".  */
1403 static GTY(()) tree va_list_type;
1404
1405 /* Return the type to use as __builtin_va_list.  */
1406 static tree
1407 arm_build_builtin_va_list (void)
1408 {
1409   tree va_list_name;
1410   tree ap_field;
1411
1412   if (!TARGET_AAPCS_BASED)
1413     return std_build_builtin_va_list ();
1414
1415   /* AAPCS \S 7.1.4 requires that va_list be a typedef for a type
1416      defined as:
1417
1418        struct __va_list
1419        {
1420          void *__ap;
1421        };
1422
1423      The C Library ABI further reinforces this definition in \S
1424      4.1.
1425
1426      We must follow this definition exactly.  The structure tag
1427      name is visible in C++ mangled names, and thus forms a part
1428      of the ABI.  The field name may be used by people who
1429      #include <stdarg.h>.  */
1430   /* Create the type.  */
1431   va_list_type = lang_hooks.types.make_type (RECORD_TYPE);
1432   /* Give it the required name.  */
1433   va_list_name = build_decl (BUILTINS_LOCATION,
1434                              TYPE_DECL,
1435                              get_identifier ("__va_list"),
1436                              va_list_type);
1437   DECL_ARTIFICIAL (va_list_name) = 1;
1438   TYPE_NAME (va_list_type) = va_list_name;
1439   TYPE_STUB_DECL (va_list_type) = va_list_name;
1440   /* Create the __ap field.  */
1441   ap_field = build_decl (BUILTINS_LOCATION,
1442                          FIELD_DECL,
1443                          get_identifier ("__ap"),
1444                          ptr_type_node);
1445   DECL_ARTIFICIAL (ap_field) = 1;
1446   DECL_FIELD_CONTEXT (ap_field) = va_list_type;
1447   TYPE_FIELDS (va_list_type) = ap_field;
1448   /* Compute its layout.  */
1449   layout_type (va_list_type);
1450
1451   return va_list_type;
1452 }
1453
1454 /* Return an expression of type "void *" pointing to the next
1455    available argument in a variable-argument list.  VALIST is the
1456    user-level va_list object, of type __builtin_va_list.  */
1457 static tree
1458 arm_extract_valist_ptr (tree valist)
1459 {
1460   if (TREE_TYPE (valist) == error_mark_node)
1461     return error_mark_node;
1462
1463   /* On an AAPCS target, the pointer is stored within "struct
1464      va_list".  */
1465   if (TARGET_AAPCS_BASED)
1466     {
1467       tree ap_field = TYPE_FIELDS (TREE_TYPE (valist));
1468       valist = build3 (COMPONENT_REF, TREE_TYPE (ap_field),
1469                        valist, ap_field, NULL_TREE);
1470     }
1471
1472   return valist;
1473 }
1474
1475 /* Implement TARGET_EXPAND_BUILTIN_VA_START.  */
1476 static void
1477 arm_expand_builtin_va_start (tree valist, rtx nextarg)
1478 {
1479   valist = arm_extract_valist_ptr (valist);
1480   std_expand_builtin_va_start (valist, nextarg);
1481 }
1482
1483 /* Implement TARGET_GIMPLIFY_VA_ARG_EXPR.  */
1484 static tree
1485 arm_gimplify_va_arg_expr (tree valist, tree type, gimple_seq *pre_p,
1486                           gimple_seq *post_p)
1487 {
1488   valist = arm_extract_valist_ptr (valist);
1489   return std_gimplify_va_arg_expr (valist, type, pre_p, post_p);
1490 }
1491
1492 /* Fix up any incompatible options that the user has specified.  */
1493 static void
1494 arm_option_override (void)
1495 {
1496   if (global_options_set.x_arm_arch_option)
1497     arm_selected_arch = &all_architectures[arm_arch_option];
1498
1499   if (global_options_set.x_arm_cpu_option)
1500     arm_selected_cpu = &all_cores[(int) arm_cpu_option];
1501
1502   if (global_options_set.x_arm_tune_option)
1503     arm_selected_tune = &all_cores[(int) arm_tune_option];
1504
1505 #ifdef SUBTARGET_OVERRIDE_OPTIONS
1506   SUBTARGET_OVERRIDE_OPTIONS;
1507 #endif
1508
1509   if (arm_selected_arch)
1510     {
1511       if (arm_selected_cpu)
1512         {
1513           /* Check for conflict between mcpu and march.  */
1514           if ((arm_selected_cpu->flags ^ arm_selected_arch->flags) & ~FL_TUNE)
1515             {
1516               warning (0, "switch -mcpu=%s conflicts with -march=%s switch",
1517                        arm_selected_cpu->name, arm_selected_arch->name);
1518               /* -march wins for code generation.
1519                  -mcpu wins for default tuning.  */
1520               if (!arm_selected_tune)
1521                 arm_selected_tune = arm_selected_cpu;
1522
1523               arm_selected_cpu = arm_selected_arch;
1524             }
1525           else
1526             /* -mcpu wins.  */
1527             arm_selected_arch = NULL;
1528         }
1529       else
1530         /* Pick a CPU based on the architecture.  */
1531         arm_selected_cpu = arm_selected_arch;
1532     }
1533
1534   /* If the user did not specify a processor, choose one for them.  */
1535   if (!arm_selected_cpu)
1536     {
1537       const struct processors * sel;
1538       unsigned int        sought;
1539
1540       arm_selected_cpu = &all_cores[TARGET_CPU_DEFAULT];
1541       if (!arm_selected_cpu->name)
1542         {
1543 #ifdef SUBTARGET_CPU_DEFAULT
1544           /* Use the subtarget default CPU if none was specified by
1545              configure.  */
1546           arm_selected_cpu = &all_cores[SUBTARGET_CPU_DEFAULT];
1547 #endif
1548           /* Default to ARM6.  */
1549           if (!arm_selected_cpu->name)
1550             arm_selected_cpu = &all_cores[arm6];
1551         }
1552
1553       sel = arm_selected_cpu;
1554       insn_flags = sel->flags;
1555
1556       /* Now check to see if the user has specified some command line
1557          switch that require certain abilities from the cpu.  */
1558       sought = 0;
1559
1560       if (TARGET_INTERWORK || TARGET_THUMB)
1561         {
1562           sought |= (FL_THUMB | FL_MODE32);
1563
1564           /* There are no ARM processors that support both APCS-26 and
1565              interworking.  Therefore we force FL_MODE26 to be removed
1566              from insn_flags here (if it was set), so that the search
1567              below will always be able to find a compatible processor.  */
1568           insn_flags &= ~FL_MODE26;
1569         }
1570
1571       if (sought != 0 && ((sought & insn_flags) != sought))
1572         {
1573           /* Try to locate a CPU type that supports all of the abilities
1574              of the default CPU, plus the extra abilities requested by
1575              the user.  */
1576           for (sel = all_cores; sel->name != NULL; sel++)
1577             if ((sel->flags & sought) == (sought | insn_flags))
1578               break;
1579
1580           if (sel->name == NULL)
1581             {
1582               unsigned current_bit_count = 0;
1583               const struct processors * best_fit = NULL;
1584
1585               /* Ideally we would like to issue an error message here
1586                  saying that it was not possible to find a CPU compatible
1587                  with the default CPU, but which also supports the command
1588                  line options specified by the programmer, and so they
1589                  ought to use the -mcpu=<name> command line option to
1590                  override the default CPU type.
1591
1592                  If we cannot find a cpu that has both the
1593                  characteristics of the default cpu and the given
1594                  command line options we scan the array again looking
1595                  for a best match.  */
1596               for (sel = all_cores; sel->name != NULL; sel++)
1597                 if ((sel->flags & sought) == sought)
1598                   {
1599                     unsigned count;
1600
1601                     count = bit_count (sel->flags & insn_flags);
1602
1603                     if (count >= current_bit_count)
1604                       {
1605                         best_fit = sel;
1606                         current_bit_count = count;
1607                       }
1608                   }
1609
1610               gcc_assert (best_fit);
1611               sel = best_fit;
1612             }
1613
1614           arm_selected_cpu = sel;
1615         }
1616     }
1617
1618   gcc_assert (arm_selected_cpu);
1619   /* The selected cpu may be an architecture, so lookup tuning by core ID.  */
1620   if (!arm_selected_tune)
1621     arm_selected_tune = &all_cores[arm_selected_cpu->core];
1622
1623   sprintf (arm_arch_name, "__ARM_ARCH_%s__", arm_selected_cpu->arch);
1624   insn_flags = arm_selected_cpu->flags;
1625
1626   arm_tune = arm_selected_tune->core;
1627   tune_flags = arm_selected_tune->flags;
1628   current_tune = arm_selected_tune->tune;
1629
1630   /* Make sure that the processor choice does not conflict with any of the
1631      other command line choices.  */
1632   if (TARGET_ARM && !(insn_flags & FL_NOTM))
1633     error ("target CPU does not support ARM mode");
1634
1635   /* BPABI targets use linker tricks to allow interworking on cores
1636      without thumb support.  */
1637   if (TARGET_INTERWORK && !((insn_flags & FL_THUMB) || TARGET_BPABI))
1638     {
1639       warning (0, "target CPU does not support interworking" );
1640       target_flags &= ~MASK_INTERWORK;
1641     }
1642
1643   if (TARGET_THUMB && !(insn_flags & FL_THUMB))
1644     {
1645       warning (0, "target CPU does not support THUMB instructions");
1646       target_flags &= ~MASK_THUMB;
1647     }
1648
1649   if (TARGET_APCS_FRAME && TARGET_THUMB)
1650     {
1651       /* warning (0, "ignoring -mapcs-frame because -mthumb was used"); */
1652       target_flags &= ~MASK_APCS_FRAME;
1653     }
1654
1655   /* Callee super interworking implies thumb interworking.  Adding
1656      this to the flags here simplifies the logic elsewhere.  */
1657   if (TARGET_THUMB && TARGET_CALLEE_INTERWORKING)
1658     target_flags |= MASK_INTERWORK;
1659
1660   /* TARGET_BACKTRACE calls leaf_function_p, which causes a crash if done
1661      from here where no function is being compiled currently.  */
1662   if ((TARGET_TPCS_FRAME || TARGET_TPCS_LEAF_FRAME) && TARGET_ARM)
1663     warning (0, "enabling backtrace support is only meaningful when compiling for the Thumb");
1664
1665   if (TARGET_ARM && TARGET_CALLEE_INTERWORKING)
1666     warning (0, "enabling callee interworking support is only meaningful when compiling for the Thumb");
1667
1668   if (TARGET_APCS_STACK && !TARGET_APCS_FRAME)
1669     {
1670       warning (0, "-mapcs-stack-check incompatible with -mno-apcs-frame");
1671       target_flags |= MASK_APCS_FRAME;
1672     }
1673
1674   if (TARGET_POKE_FUNCTION_NAME)
1675     target_flags |= MASK_APCS_FRAME;
1676
1677   if (TARGET_APCS_REENT && flag_pic)
1678     error ("-fpic and -mapcs-reent are incompatible");
1679
1680   if (TARGET_APCS_REENT)
1681     warning (0, "APCS reentrant code not supported.  Ignored");
1682
1683   /* If this target is normally configured to use APCS frames, warn if they
1684      are turned off and debugging is turned on.  */
1685   if (TARGET_ARM
1686       && write_symbols != NO_DEBUG
1687       && !TARGET_APCS_FRAME
1688       && (TARGET_DEFAULT & MASK_APCS_FRAME))
1689     warning (0, "-g with -mno-apcs-frame may not give sensible debugging");
1690
1691   if (TARGET_APCS_FLOAT)
1692     warning (0, "passing floating point arguments in fp regs not yet supported");
1693
1694   if (TARGET_LITTLE_WORDS)
1695     warning (OPT_Wdeprecated, "%<mwords-little-endian%> is deprecated and "
1696              "will be removed in a future release");
1697
1698   /* Initialize boolean versions of the flags, for use in the arm.md file.  */
1699   arm_arch3m = (insn_flags & FL_ARCH3M) != 0;
1700   arm_arch4 = (insn_flags & FL_ARCH4) != 0;
1701   arm_arch4t = arm_arch4 & ((insn_flags & FL_THUMB) != 0);
1702   arm_arch5 = (insn_flags & FL_ARCH5) != 0;
1703   arm_arch5e = (insn_flags & FL_ARCH5E) != 0;
1704   arm_arch6 = (insn_flags & FL_ARCH6) != 0;
1705   arm_arch6k = (insn_flags & FL_ARCH6K) != 0;
1706   arm_arch_notm = (insn_flags & FL_NOTM) != 0;
1707   arm_arch7 = (insn_flags & FL_ARCH7) != 0;
1708   arm_arch7em = (insn_flags & FL_ARCH7EM) != 0;
1709   arm_arch_thumb2 = (insn_flags & FL_THUMB2) != 0;
1710   arm_arch_xscale = (insn_flags & FL_XSCALE) != 0;
1711   arm_arch_cirrus = (insn_flags & FL_CIRRUS) != 0;
1712
1713   arm_ld_sched = (tune_flags & FL_LDSCHED) != 0;
1714   arm_tune_strongarm = (tune_flags & FL_STRONG) != 0;
1715   thumb_code = TARGET_ARM == 0;
1716   thumb1_code = TARGET_THUMB1 != 0;
1717   arm_tune_wbuf = (tune_flags & FL_WBUF) != 0;
1718   arm_tune_xscale = (tune_flags & FL_XSCALE) != 0;
1719   arm_arch_iwmmxt = (insn_flags & FL_IWMMXT) != 0;
1720   arm_arch_thumb_hwdiv = (insn_flags & FL_THUMB_DIV) != 0;
1721   arm_arch_arm_hwdiv = (insn_flags & FL_ARM_DIV) != 0;
1722   arm_tune_cortex_a9 = (arm_tune == cortexa9) != 0;
1723
1724   /* If we are not using the default (ARM mode) section anchor offset
1725      ranges, then set the correct ranges now.  */
1726   if (TARGET_THUMB1)
1727     {
1728       /* Thumb-1 LDR instructions cannot have negative offsets.
1729          Permissible positive offset ranges are 5-bit (for byte loads),
1730          6-bit (for halfword loads), or 7-bit (for word loads).
1731          Empirical results suggest a 7-bit anchor range gives the best
1732          overall code size.  */
1733       targetm.min_anchor_offset = 0;
1734       targetm.max_anchor_offset = 127;
1735     }
1736   else if (TARGET_THUMB2)
1737     {
1738       /* The minimum is set such that the total size of the block
1739          for a particular anchor is 248 + 1 + 4095 bytes, which is
1740          divisible by eight, ensuring natural spacing of anchors.  */
1741       targetm.min_anchor_offset = -248;
1742       targetm.max_anchor_offset = 4095;
1743     }
1744
1745   /* V5 code we generate is completely interworking capable, so we turn off
1746      TARGET_INTERWORK here to avoid many tests later on.  */
1747
1748   /* XXX However, we must pass the right pre-processor defines to CPP
1749      or GLD can get confused.  This is a hack.  */
1750   if (TARGET_INTERWORK)
1751     arm_cpp_interwork = 1;
1752
1753   if (arm_arch5)
1754     target_flags &= ~MASK_INTERWORK;
1755
1756   if (TARGET_IWMMXT && !ARM_DOUBLEWORD_ALIGN)
1757     error ("iwmmxt requires an AAPCS compatible ABI for proper operation");
1758
1759   if (TARGET_IWMMXT_ABI && !TARGET_IWMMXT)
1760     error ("iwmmxt abi requires an iwmmxt capable cpu");
1761
1762   if (!global_options_set.x_arm_fpu_index)
1763     {
1764       const char *target_fpu_name;
1765       bool ok;
1766
1767 #ifdef FPUTYPE_DEFAULT
1768       target_fpu_name = FPUTYPE_DEFAULT;
1769 #else
1770       if (arm_arch_cirrus)
1771         target_fpu_name = "maverick";
1772       else
1773         target_fpu_name = "fpe2";
1774 #endif
1775
1776       ok = opt_enum_arg_to_value (OPT_mfpu_, target_fpu_name, &arm_fpu_index,
1777                                   CL_TARGET);
1778       gcc_assert (ok);
1779     }
1780
1781   arm_fpu_desc = &all_fpus[arm_fpu_index];
1782
1783   switch (arm_fpu_desc->model)
1784     {
1785     case ARM_FP_MODEL_FPA:
1786       if (arm_fpu_desc->rev == 2)
1787         arm_fpu_attr = FPU_FPE2;
1788       else if (arm_fpu_desc->rev == 3)
1789         arm_fpu_attr = FPU_FPE3;
1790       else
1791         arm_fpu_attr = FPU_FPA;
1792       break;
1793
1794     case ARM_FP_MODEL_MAVERICK:
1795       arm_fpu_attr = FPU_MAVERICK;
1796       break;
1797
1798     case ARM_FP_MODEL_VFP:
1799       arm_fpu_attr = FPU_VFP;
1800       break;
1801
1802     default:
1803       gcc_unreachable();
1804     }
1805
1806   if (TARGET_AAPCS_BASED
1807       && (arm_fpu_desc->model == ARM_FP_MODEL_FPA))
1808     error ("FPA is unsupported in the AAPCS");
1809
1810   if (TARGET_AAPCS_BASED)
1811     {
1812       if (TARGET_CALLER_INTERWORKING)
1813         error ("AAPCS does not support -mcaller-super-interworking");
1814       else
1815         if (TARGET_CALLEE_INTERWORKING)
1816           error ("AAPCS does not support -mcallee-super-interworking");
1817     }
1818
1819   /* FPA and iWMMXt are incompatible because the insn encodings overlap.
1820      VFP and iWMMXt can theoretically coexist, but it's unlikely such silicon
1821      will ever exist.  GCC makes no attempt to support this combination.  */
1822   if (TARGET_IWMMXT && !TARGET_SOFT_FLOAT)
1823     sorry ("iWMMXt and hardware floating point");
1824
1825   /* ??? iWMMXt insn patterns need auditing for Thumb-2.  */
1826   if (TARGET_THUMB2 && TARGET_IWMMXT)
1827     sorry ("Thumb-2 iWMMXt");
1828
1829   /* __fp16 support currently assumes the core has ldrh.  */
1830   if (!arm_arch4 && arm_fp16_format != ARM_FP16_FORMAT_NONE)
1831     sorry ("__fp16 and no ldrh");
1832
1833   /* If soft-float is specified then don't use FPU.  */
1834   if (TARGET_SOFT_FLOAT)
1835     arm_fpu_attr = FPU_NONE;
1836
1837   if (TARGET_AAPCS_BASED)
1838     {
1839       if (arm_abi == ARM_ABI_IWMMXT)
1840         arm_pcs_default = ARM_PCS_AAPCS_IWMMXT;
1841       else if (arm_float_abi == ARM_FLOAT_ABI_HARD
1842                && TARGET_HARD_FLOAT
1843                && TARGET_VFP)
1844         arm_pcs_default = ARM_PCS_AAPCS_VFP;
1845       else
1846         arm_pcs_default = ARM_PCS_AAPCS;
1847     }
1848   else
1849     {
1850       if (arm_float_abi == ARM_FLOAT_ABI_HARD && TARGET_VFP)
1851         sorry ("-mfloat-abi=hard and VFP");
1852
1853       if (arm_abi == ARM_ABI_APCS)
1854         arm_pcs_default = ARM_PCS_APCS;
1855       else
1856         arm_pcs_default = ARM_PCS_ATPCS;
1857     }
1858
1859   /* For arm2/3 there is no need to do any scheduling if there is only
1860      a floating point emulator, or we are doing software floating-point.  */
1861   if ((TARGET_SOFT_FLOAT
1862        || (TARGET_FPA && arm_fpu_desc->rev))
1863       && (tune_flags & FL_MODE32) == 0)
1864     flag_schedule_insns = flag_schedule_insns_after_reload = 0;
1865
1866   /* Use the cp15 method if it is available.  */
1867   if (target_thread_pointer == TP_AUTO)
1868     {
1869       if (arm_arch6k && !TARGET_THUMB1)
1870         target_thread_pointer = TP_CP15;
1871       else
1872         target_thread_pointer = TP_SOFT;
1873     }
1874
1875   if (TARGET_HARD_TP && TARGET_THUMB1)
1876     error ("can not use -mtp=cp15 with 16-bit Thumb");
1877
1878   /* Override the default structure alignment for AAPCS ABI.  */
1879   if (!global_options_set.x_arm_structure_size_boundary)
1880     {
1881       if (TARGET_AAPCS_BASED)
1882         arm_structure_size_boundary = 8;
1883     }
1884   else
1885     {
1886       if (arm_structure_size_boundary != 8
1887           && arm_structure_size_boundary != 32
1888           && !(ARM_DOUBLEWORD_ALIGN && arm_structure_size_boundary == 64))
1889         {
1890           if (ARM_DOUBLEWORD_ALIGN)
1891             warning (0,
1892                      "structure size boundary can only be set to 8, 32 or 64");
1893           else
1894             warning (0, "structure size boundary can only be set to 8 or 32");
1895           arm_structure_size_boundary
1896             = (TARGET_AAPCS_BASED ? 8 : DEFAULT_STRUCTURE_SIZE_BOUNDARY);
1897         }
1898     }
1899
1900   if (!TARGET_ARM && TARGET_VXWORKS_RTP && flag_pic)
1901     {
1902       error ("RTP PIC is incompatible with Thumb");
1903       flag_pic = 0;
1904     }
1905
1906   /* If stack checking is disabled, we can use r10 as the PIC register,
1907      which keeps r9 available.  The EABI specifies r9 as the PIC register.  */
1908   if (flag_pic && TARGET_SINGLE_PIC_BASE)
1909     {
1910       if (TARGET_VXWORKS_RTP)
1911         warning (0, "RTP PIC is incompatible with -msingle-pic-base");
1912       arm_pic_register = (TARGET_APCS_STACK || TARGET_AAPCS_BASED) ? 9 : 10;
1913     }
1914
1915   if (flag_pic && TARGET_VXWORKS_RTP)
1916     arm_pic_register = 9;
1917
1918   if (arm_pic_register_string != NULL)
1919     {
1920       int pic_register = decode_reg_name (arm_pic_register_string);
1921
1922       if (!flag_pic)
1923         warning (0, "-mpic-register= is useless without -fpic");
1924
1925       /* Prevent the user from choosing an obviously stupid PIC register.  */
1926       else if (pic_register < 0 || call_used_regs[pic_register]
1927                || pic_register == HARD_FRAME_POINTER_REGNUM
1928                || pic_register == STACK_POINTER_REGNUM
1929                || pic_register >= PC_REGNUM
1930                || (TARGET_VXWORKS_RTP
1931                    && (unsigned int) pic_register != arm_pic_register))
1932         error ("unable to use '%s' for PIC register", arm_pic_register_string);
1933       else
1934         arm_pic_register = pic_register;
1935     }
1936
1937   /* Enable -mfix-cortex-m3-ldrd by default for Cortex-M3 cores.  */
1938   if (fix_cm3_ldrd == 2)
1939     {
1940       if (arm_selected_cpu->core == cortexm3)
1941         fix_cm3_ldrd = 1;
1942       else
1943         fix_cm3_ldrd = 0;
1944     }
1945
1946   /* Enable -munaligned-access by default for
1947      - all ARMv6 architecture-based processors
1948      - ARMv7-A, ARMv7-R, and ARMv7-M architecture-based processors.
1949
1950      Disable -munaligned-access by default for
1951      - all pre-ARMv6 architecture-based processors
1952      - ARMv6-M architecture-based processors.  */
1953
1954   if (unaligned_access == 2)
1955     {
1956       if (arm_arch6 && (arm_arch_notm || arm_arch7))
1957         unaligned_access = 1;
1958       else
1959         unaligned_access = 0;
1960     }
1961   else if (unaligned_access == 1
1962            && !(arm_arch6 && (arm_arch_notm || arm_arch7)))
1963     {
1964       warning (0, "target CPU does not support unaligned accesses");
1965       unaligned_access = 0;
1966     }
1967
1968   if (TARGET_THUMB1 && flag_schedule_insns)
1969     {
1970       /* Don't warn since it's on by default in -O2.  */
1971       flag_schedule_insns = 0;
1972     }
1973
1974   if (optimize_size)
1975     {
1976       /* If optimizing for size, bump the number of instructions that we
1977          are prepared to conditionally execute (even on a StrongARM).  */
1978       max_insns_skipped = 6;
1979     }
1980   else
1981     max_insns_skipped = current_tune->max_insns_skipped;
1982
1983   /* Hot/Cold partitioning is not currently supported, since we can't
1984      handle literal pool placement in that case.  */
1985   if (flag_reorder_blocks_and_partition)
1986     {
1987       inform (input_location,
1988               "-freorder-blocks-and-partition not supported on this architecture");
1989       flag_reorder_blocks_and_partition = 0;
1990       flag_reorder_blocks = 1;
1991     }
1992
1993   if (flag_pic)
1994     /* Hoisting PIC address calculations more aggressively provides a small,
1995        but measurable, size reduction for PIC code.  Therefore, we decrease
1996        the bar for unrestricted expression hoisting to the cost of PIC address
1997        calculation, which is 2 instructions.  */
1998     maybe_set_param_value (PARAM_GCSE_UNRESTRICTED_COST, 2,
1999                            global_options.x_param_values,
2000                            global_options_set.x_param_values);
2001
2002   /* ARM EABI defaults to strict volatile bitfields.  */
2003   if (TARGET_AAPCS_BASED && flag_strict_volatile_bitfields < 0
2004       && abi_version_at_least(2))
2005     flag_strict_volatile_bitfields = 1;
2006
2007   /* Enable sw prefetching at -O3 for CPUS that have prefetch, and we have deemed
2008      it beneficial (signified by setting num_prefetch_slots to 1 or more.)  */
2009   if (flag_prefetch_loop_arrays < 0
2010       && HAVE_prefetch
2011       && optimize >= 3
2012       && current_tune->num_prefetch_slots > 0)
2013     flag_prefetch_loop_arrays = 1;
2014
2015   /* Set up parameters to be used in prefetching algorithm.  Do not override the
2016      defaults unless we are tuning for a core we have researched values for.  */
2017   if (current_tune->num_prefetch_slots > 0)
2018     maybe_set_param_value (PARAM_SIMULTANEOUS_PREFETCHES,
2019                            current_tune->num_prefetch_slots,
2020                            global_options.x_param_values,
2021                            global_options_set.x_param_values);
2022   if (current_tune->l1_cache_line_size >= 0)
2023     maybe_set_param_value (PARAM_L1_CACHE_LINE_SIZE,
2024                            current_tune->l1_cache_line_size,
2025                            global_options.x_param_values,
2026                            global_options_set.x_param_values);
2027   if (current_tune->l1_cache_size >= 0)
2028     maybe_set_param_value (PARAM_L1_CACHE_SIZE,
2029                            current_tune->l1_cache_size,
2030                            global_options.x_param_values,
2031                            global_options_set.x_param_values);
2032
2033   /* Register global variables with the garbage collector.  */
2034   arm_add_gc_roots ();
2035 }
2036
2037 static void
2038 arm_add_gc_roots (void)
2039 {
2040   gcc_obstack_init(&minipool_obstack);
2041   minipool_startobj = (char *) obstack_alloc (&minipool_obstack, 0);
2042 }
2043 \f
2044 /* A table of known ARM exception types.
2045    For use with the interrupt function attribute.  */
2046
2047 typedef struct
2048 {
2049   const char *const arg;
2050   const unsigned long return_value;
2051 }
2052 isr_attribute_arg;
2053
2054 static const isr_attribute_arg isr_attribute_args [] =
2055 {
2056   { "IRQ",   ARM_FT_ISR },
2057   { "irq",   ARM_FT_ISR },
2058   { "FIQ",   ARM_FT_FIQ },
2059   { "fiq",   ARM_FT_FIQ },
2060   { "ABORT", ARM_FT_ISR },
2061   { "abort", ARM_FT_ISR },
2062   { "ABORT", ARM_FT_ISR },
2063   { "abort", ARM_FT_ISR },
2064   { "UNDEF", ARM_FT_EXCEPTION },
2065   { "undef", ARM_FT_EXCEPTION },
2066   { "SWI",   ARM_FT_EXCEPTION },
2067   { "swi",   ARM_FT_EXCEPTION },
2068   { NULL,    ARM_FT_NORMAL }
2069 };
2070
2071 /* Returns the (interrupt) function type of the current
2072    function, or ARM_FT_UNKNOWN if the type cannot be determined.  */
2073
2074 static unsigned long
2075 arm_isr_value (tree argument)
2076 {
2077   const isr_attribute_arg * ptr;
2078   const char *              arg;
2079
2080   if (!arm_arch_notm)
2081     return ARM_FT_NORMAL | ARM_FT_STACKALIGN;
2082
2083   /* No argument - default to IRQ.  */
2084   if (argument == NULL_TREE)
2085     return ARM_FT_ISR;
2086
2087   /* Get the value of the argument.  */
2088   if (TREE_VALUE (argument) == NULL_TREE
2089       || TREE_CODE (TREE_VALUE (argument)) != STRING_CST)
2090     return ARM_FT_UNKNOWN;
2091
2092   arg = TREE_STRING_POINTER (TREE_VALUE (argument));
2093
2094   /* Check it against the list of known arguments.  */
2095   for (ptr = isr_attribute_args; ptr->arg != NULL; ptr++)
2096     if (streq (arg, ptr->arg))
2097       return ptr->return_value;
2098
2099   /* An unrecognized interrupt type.  */
2100   return ARM_FT_UNKNOWN;
2101 }
2102
2103 /* Computes the type of the current function.  */
2104
2105 static unsigned long
2106 arm_compute_func_type (void)
2107 {
2108   unsigned long type = ARM_FT_UNKNOWN;
2109   tree a;
2110   tree attr;
2111
2112   gcc_assert (TREE_CODE (current_function_decl) == FUNCTION_DECL);
2113
2114   /* Decide if the current function is volatile.  Such functions
2115      never return, and many memory cycles can be saved by not storing
2116      register values that will never be needed again.  This optimization
2117      was added to speed up context switching in a kernel application.  */
2118   if (optimize > 0
2119       && (TREE_NOTHROW (current_function_decl)
2120           || !(flag_unwind_tables
2121                || (flag_exceptions
2122                    && arm_except_unwind_info (&global_options) != UI_SJLJ)))
2123       && TREE_THIS_VOLATILE (current_function_decl))
2124     type |= ARM_FT_VOLATILE;
2125
2126   if (cfun->static_chain_decl != NULL)
2127     type |= ARM_FT_NESTED;
2128
2129   attr = DECL_ATTRIBUTES (current_function_decl);
2130
2131   a = lookup_attribute ("naked", attr);
2132   if (a != NULL_TREE)
2133     type |= ARM_FT_NAKED;
2134
2135   a = lookup_attribute ("isr", attr);
2136   if (a == NULL_TREE)
2137     a = lookup_attribute ("interrupt", attr);
2138
2139   if (a == NULL_TREE)
2140     type |= TARGET_INTERWORK ? ARM_FT_INTERWORKED : ARM_FT_NORMAL;
2141   else
2142     type |= arm_isr_value (TREE_VALUE (a));
2143
2144   return type;
2145 }
2146
2147 /* Returns the type of the current function.  */
2148
2149 unsigned long
2150 arm_current_func_type (void)
2151 {
2152   if (ARM_FUNC_TYPE (cfun->machine->func_type) == ARM_FT_UNKNOWN)
2153     cfun->machine->func_type = arm_compute_func_type ();
2154
2155   return cfun->machine->func_type;
2156 }
2157
2158 bool
2159 arm_allocate_stack_slots_for_args (void)
2160 {
2161   /* Naked functions should not allocate stack slots for arguments.  */
2162   return !IS_NAKED (arm_current_func_type ());
2163 }
2164
2165 \f
2166 /* Output assembler code for a block containing the constant parts
2167    of a trampoline, leaving space for the variable parts.
2168
2169    On the ARM, (if r8 is the static chain regnum, and remembering that
2170    referencing pc adds an offset of 8) the trampoline looks like:
2171            ldr          r8, [pc, #0]
2172            ldr          pc, [pc]
2173            .word        static chain value
2174            .word        function's address
2175    XXX FIXME: When the trampoline returns, r8 will be clobbered.  */
2176
2177 static void
2178 arm_asm_trampoline_template (FILE *f)
2179 {
2180   if (TARGET_ARM)
2181     {
2182       asm_fprintf (f, "\tldr\t%r, [%r, #0]\n", STATIC_CHAIN_REGNUM, PC_REGNUM);
2183       asm_fprintf (f, "\tldr\t%r, [%r, #0]\n", PC_REGNUM, PC_REGNUM);
2184     }
2185   else if (TARGET_THUMB2)
2186     {
2187       /* The Thumb-2 trampoline is similar to the arm implementation.
2188          Unlike 16-bit Thumb, we enter the stub in thumb mode.  */
2189       asm_fprintf (f, "\tldr.w\t%r, [%r, #4]\n",
2190                    STATIC_CHAIN_REGNUM, PC_REGNUM);
2191       asm_fprintf (f, "\tldr.w\t%r, [%r, #4]\n", PC_REGNUM, PC_REGNUM);
2192     }
2193   else
2194     {
2195       ASM_OUTPUT_ALIGN (f, 2);
2196       fprintf (f, "\t.code\t16\n");
2197       fprintf (f, ".Ltrampoline_start:\n");
2198       asm_fprintf (f, "\tpush\t{r0, r1}\n");
2199       asm_fprintf (f, "\tldr\tr0, [%r, #8]\n", PC_REGNUM);
2200       asm_fprintf (f, "\tmov\t%r, r0\n", STATIC_CHAIN_REGNUM);
2201       asm_fprintf (f, "\tldr\tr0, [%r, #8]\n", PC_REGNUM);
2202       asm_fprintf (f, "\tstr\tr0, [%r, #4]\n", SP_REGNUM);
2203       asm_fprintf (f, "\tpop\t{r0, %r}\n", PC_REGNUM);
2204     }
2205   assemble_aligned_integer (UNITS_PER_WORD, const0_rtx);
2206   assemble_aligned_integer (UNITS_PER_WORD, const0_rtx);
2207 }
2208
2209 /* Emit RTL insns to initialize the variable parts of a trampoline.  */
2210
2211 static void
2212 arm_trampoline_init (rtx m_tramp, tree fndecl, rtx chain_value)
2213 {
2214   rtx fnaddr, mem, a_tramp;
2215
2216   emit_block_move (m_tramp, assemble_trampoline_template (),
2217                    GEN_INT (TRAMPOLINE_SIZE), BLOCK_OP_NORMAL);
2218
2219   mem = adjust_address (m_tramp, SImode, TARGET_32BIT ? 8 : 12);
2220   emit_move_insn (mem, chain_value);
2221
2222   mem = adjust_address (m_tramp, SImode, TARGET_32BIT ? 12 : 16);
2223   fnaddr = XEXP (DECL_RTL (fndecl), 0);
2224   emit_move_insn (mem, fnaddr);
2225
2226   a_tramp = XEXP (m_tramp, 0);
2227   emit_library_call (gen_rtx_SYMBOL_REF (Pmode, "__clear_cache"),
2228                      LCT_NORMAL, VOIDmode, 2, a_tramp, Pmode,
2229                      plus_constant (a_tramp, TRAMPOLINE_SIZE), Pmode);
2230 }
2231
2232 /* Thumb trampolines should be entered in thumb mode, so set
2233    the bottom bit of the address.  */
2234
2235 static rtx
2236 arm_trampoline_adjust_address (rtx addr)
2237 {
2238   if (TARGET_THUMB)
2239     addr = expand_simple_binop (Pmode, IOR, addr, const1_rtx,
2240                                 NULL, 0, OPTAB_LIB_WIDEN);
2241   return addr;
2242 }
2243 \f
2244 /* Return 1 if it is possible to return using a single instruction.
2245    If SIBLING is non-null, this is a test for a return before a sibling
2246    call.  SIBLING is the call insn, so we can examine its register usage.  */
2247
2248 int
2249 use_return_insn (int iscond, rtx sibling)
2250 {
2251   int regno;
2252   unsigned int func_type;
2253   unsigned long saved_int_regs;
2254   unsigned HOST_WIDE_INT stack_adjust;
2255   arm_stack_offsets *offsets;
2256
2257   /* Never use a return instruction before reload has run.  */
2258   if (!reload_completed)
2259     return 0;
2260
2261   func_type = arm_current_func_type ();
2262
2263   /* Naked, volatile and stack alignment functions need special
2264      consideration.  */
2265   if (func_type & (ARM_FT_VOLATILE | ARM_FT_NAKED | ARM_FT_STACKALIGN))
2266     return 0;
2267
2268   /* So do interrupt functions that use the frame pointer and Thumb
2269      interrupt functions.  */
2270   if (IS_INTERRUPT (func_type) && (frame_pointer_needed || TARGET_THUMB))
2271     return 0;
2272
2273   offsets = arm_get_frame_offsets ();
2274   stack_adjust = offsets->outgoing_args - offsets->saved_regs;
2275
2276   /* As do variadic functions.  */
2277   if (crtl->args.pretend_args_size
2278       || cfun->machine->uses_anonymous_args
2279       /* Or if the function calls __builtin_eh_return () */
2280       || crtl->calls_eh_return
2281       /* Or if the function calls alloca */
2282       || cfun->calls_alloca
2283       /* Or if there is a stack adjustment.  However, if the stack pointer
2284          is saved on the stack, we can use a pre-incrementing stack load.  */
2285       || !(stack_adjust == 0 || (TARGET_APCS_FRAME && frame_pointer_needed
2286                                  && stack_adjust == 4)))
2287     return 0;
2288
2289   saved_int_regs = offsets->saved_regs_mask;
2290
2291   /* Unfortunately, the insn
2292
2293        ldmib sp, {..., sp, ...}
2294
2295      triggers a bug on most SA-110 based devices, such that the stack
2296      pointer won't be correctly restored if the instruction takes a
2297      page fault.  We work around this problem by popping r3 along with
2298      the other registers, since that is never slower than executing
2299      another instruction.
2300
2301      We test for !arm_arch5 here, because code for any architecture
2302      less than this could potentially be run on one of the buggy
2303      chips.  */
2304   if (stack_adjust == 4 && !arm_arch5 && TARGET_ARM)
2305     {
2306       /* Validate that r3 is a call-clobbered register (always true in
2307          the default abi) ...  */
2308       if (!call_used_regs[3])
2309         return 0;
2310
2311       /* ... that it isn't being used for a return value ... */
2312       if (arm_size_return_regs () >= (4 * UNITS_PER_WORD))
2313         return 0;
2314
2315       /* ... or for a tail-call argument ...  */
2316       if (sibling)
2317         {
2318           gcc_assert (GET_CODE (sibling) == CALL_INSN);
2319
2320           if (find_regno_fusage (sibling, USE, 3))
2321             return 0;
2322         }
2323
2324       /* ... and that there are no call-saved registers in r0-r2
2325          (always true in the default ABI).  */
2326       if (saved_int_regs & 0x7)
2327         return 0;
2328     }
2329
2330   /* Can't be done if interworking with Thumb, and any registers have been
2331      stacked.  */
2332   if (TARGET_INTERWORK && saved_int_regs != 0 && !IS_INTERRUPT(func_type))
2333     return 0;
2334
2335   /* On StrongARM, conditional returns are expensive if they aren't
2336      taken and multiple registers have been stacked.  */
2337   if (iscond && arm_tune_strongarm)
2338     {
2339       /* Conditional return when just the LR is stored is a simple
2340          conditional-load instruction, that's not expensive.  */
2341       if (saved_int_regs != 0 && saved_int_regs != (1 << LR_REGNUM))
2342         return 0;
2343
2344       if (flag_pic
2345           && arm_pic_register != INVALID_REGNUM
2346           && df_regs_ever_live_p (PIC_OFFSET_TABLE_REGNUM))
2347         return 0;
2348     }
2349
2350   /* If there are saved registers but the LR isn't saved, then we need
2351      two instructions for the return.  */
2352   if (saved_int_regs && !(saved_int_regs & (1 << LR_REGNUM)))
2353     return 0;
2354
2355   /* Can't be done if any of the FPA regs are pushed,
2356      since this also requires an insn.  */
2357   if (TARGET_HARD_FLOAT && TARGET_FPA)
2358     for (regno = FIRST_FPA_REGNUM; regno <= LAST_FPA_REGNUM; regno++)
2359       if (df_regs_ever_live_p (regno) && !call_used_regs[regno])
2360         return 0;
2361
2362   /* Likewise VFP regs.  */
2363   if (TARGET_HARD_FLOAT && TARGET_VFP)
2364     for (regno = FIRST_VFP_REGNUM; regno <= LAST_VFP_REGNUM; regno++)
2365       if (df_regs_ever_live_p (regno) && !call_used_regs[regno])
2366         return 0;
2367
2368   if (TARGET_REALLY_IWMMXT)
2369     for (regno = FIRST_IWMMXT_REGNUM; regno <= LAST_IWMMXT_REGNUM; regno++)
2370       if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
2371         return 0;
2372
2373   return 1;
2374 }
2375
2376 /* Return TRUE if int I is a valid immediate ARM constant.  */
2377
2378 int
2379 const_ok_for_arm (HOST_WIDE_INT i)
2380 {
2381   int lowbit;
2382
2383   /* For machines with >32 bit HOST_WIDE_INT, the bits above bit 31 must
2384      be all zero, or all one.  */
2385   if ((i & ~(unsigned HOST_WIDE_INT) 0xffffffff) != 0
2386       && ((i & ~(unsigned HOST_WIDE_INT) 0xffffffff)
2387           != ((~(unsigned HOST_WIDE_INT) 0)
2388               & ~(unsigned HOST_WIDE_INT) 0xffffffff)))
2389     return FALSE;
2390
2391   i &= (unsigned HOST_WIDE_INT) 0xffffffff;
2392
2393   /* Fast return for 0 and small values.  We must do this for zero, since
2394      the code below can't handle that one case.  */
2395   if ((i & ~(unsigned HOST_WIDE_INT) 0xff) == 0)
2396     return TRUE;
2397
2398   /* Get the number of trailing zeros.  */
2399   lowbit = ffs((int) i) - 1;
2400
2401   /* Only even shifts are allowed in ARM mode so round down to the
2402      nearest even number.  */
2403   if (TARGET_ARM)
2404     lowbit &= ~1;
2405
2406   if ((i & ~(((unsigned HOST_WIDE_INT) 0xff) << lowbit)) == 0)
2407     return TRUE;
2408
2409   if (TARGET_ARM)
2410     {
2411       /* Allow rotated constants in ARM mode.  */
2412       if (lowbit <= 4
2413            && ((i & ~0xc000003f) == 0
2414                || (i & ~0xf000000f) == 0
2415                || (i & ~0xfc000003) == 0))
2416         return TRUE;
2417     }
2418   else
2419     {
2420       HOST_WIDE_INT v;
2421
2422       /* Allow repeated patterns 0x00XY00XY or 0xXYXYXYXY.  */
2423       v = i & 0xff;
2424       v |= v << 16;
2425       if (i == v || i == (v | (v << 8)))
2426         return TRUE;
2427
2428       /* Allow repeated pattern 0xXY00XY00.  */
2429       v = i & 0xff00;
2430       v |= v << 16;
2431       if (i == v)
2432         return TRUE;
2433     }
2434
2435   return FALSE;
2436 }
2437
2438 /* Return true if I is a valid constant for the operation CODE.  */
2439 int
2440 const_ok_for_op (HOST_WIDE_INT i, enum rtx_code code)
2441 {
2442   if (const_ok_for_arm (i))
2443     return 1;
2444
2445   switch (code)
2446     {
2447     case SET:
2448       /* See if we can use movw.  */
2449       if (arm_arch_thumb2 && (i & 0xffff0000) == 0)
2450         return 1;
2451       else
2452         /* Otherwise, try mvn.  */
2453         return const_ok_for_arm (ARM_SIGN_EXTEND (~i));
2454
2455     case PLUS:
2456       /* See if we can use addw or subw.  */
2457       if (TARGET_THUMB2
2458           && ((i & 0xfffff000) == 0
2459               || ((-i) & 0xfffff000) == 0))
2460         return 1;
2461       /* else fall through.  */
2462
2463     case COMPARE:
2464     case EQ:
2465     case NE:
2466     case GT:
2467     case LE:
2468     case LT:
2469     case GE:
2470     case GEU:
2471     case LTU:
2472     case GTU:
2473     case LEU:
2474     case UNORDERED:
2475     case ORDERED:
2476     case UNEQ:
2477     case UNGE:
2478     case UNLT:
2479     case UNGT:
2480     case UNLE:
2481       return const_ok_for_arm (ARM_SIGN_EXTEND (-i));
2482
2483     case MINUS:         /* Should only occur with (MINUS I reg) => rsb */
2484     case XOR:
2485       return 0;
2486
2487     case IOR:
2488       if (TARGET_THUMB2)
2489         return const_ok_for_arm (ARM_SIGN_EXTEND (~i));
2490       return 0;
2491
2492     case AND:
2493       return const_ok_for_arm (ARM_SIGN_EXTEND (~i));
2494
2495     default:
2496       gcc_unreachable ();
2497     }
2498 }
2499
2500 /* Emit a sequence of insns to handle a large constant.
2501    CODE is the code of the operation required, it can be any of SET, PLUS,
2502    IOR, AND, XOR, MINUS;
2503    MODE is the mode in which the operation is being performed;
2504    VAL is the integer to operate on;
2505    SOURCE is the other operand (a register, or a null-pointer for SET);
2506    SUBTARGETS means it is safe to create scratch registers if that will
2507    either produce a simpler sequence, or we will want to cse the values.
2508    Return value is the number of insns emitted.  */
2509
2510 /* ??? Tweak this for thumb2.  */
2511 int
2512 arm_split_constant (enum rtx_code code, enum machine_mode mode, rtx insn,
2513                     HOST_WIDE_INT val, rtx target, rtx source, int subtargets)
2514 {
2515   rtx cond;
2516
2517   if (insn && GET_CODE (PATTERN (insn)) == COND_EXEC)
2518     cond = COND_EXEC_TEST (PATTERN (insn));
2519   else
2520     cond = NULL_RTX;
2521
2522   if (subtargets || code == SET
2523       || (GET_CODE (target) == REG && GET_CODE (source) == REG
2524           && REGNO (target) != REGNO (source)))
2525     {
2526       /* After arm_reorg has been called, we can't fix up expensive
2527          constants by pushing them into memory so we must synthesize
2528          them in-line, regardless of the cost.  This is only likely to
2529          be more costly on chips that have load delay slots and we are
2530          compiling without running the scheduler (so no splitting
2531          occurred before the final instruction emission).
2532
2533          Ref: gcc -O1 -mcpu=strongarm gcc.c-torture/compile/980506-2.c
2534       */
2535       if (!after_arm_reorg
2536           && !cond
2537           && (arm_gen_constant (code, mode, NULL_RTX, val, target, source,
2538                                 1, 0)
2539               > (arm_constant_limit (optimize_function_for_size_p (cfun))
2540                  + (code != SET))))
2541         {
2542           if (code == SET)
2543             {
2544               /* Currently SET is the only monadic value for CODE, all
2545                  the rest are diadic.  */
2546               if (TARGET_USE_MOVT)
2547                 arm_emit_movpair (target, GEN_INT (val));
2548               else
2549                 emit_set_insn (target, GEN_INT (val));
2550
2551               return 1;
2552             }
2553           else
2554             {
2555               rtx temp = subtargets ? gen_reg_rtx (mode) : target;
2556
2557               if (TARGET_USE_MOVT)
2558                 arm_emit_movpair (temp, GEN_INT (val));
2559               else
2560                 emit_set_insn (temp, GEN_INT (val));
2561
2562               /* For MINUS, the value is subtracted from, since we never
2563                  have subtraction of a constant.  */
2564               if (code == MINUS)
2565                 emit_set_insn (target, gen_rtx_MINUS (mode, temp, source));
2566               else
2567                 emit_set_insn (target,
2568                                gen_rtx_fmt_ee (code, mode, source, temp));
2569               return 2;
2570             }
2571         }
2572     }
2573
2574   return arm_gen_constant (code, mode, cond, val, target, source, subtargets,
2575                            1);
2576 }
2577
2578 /* Return a sequence of integers, in RETURN_SEQUENCE that fit into
2579    ARM/THUMB2 immediates, and add up to VAL.
2580    Thr function return value gives the number of insns required.  */
2581 static int
2582 optimal_immediate_sequence (enum rtx_code code, unsigned HOST_WIDE_INT val,
2583                             struct four_ints *return_sequence)
2584 {
2585   int best_consecutive_zeros = 0;
2586   int i;
2587   int best_start = 0;
2588   int insns1, insns2;
2589   struct four_ints tmp_sequence;
2590
2591   /* If we aren't targetting ARM, the best place to start is always at
2592      the bottom, otherwise look more closely.  */
2593   if (TARGET_ARM)
2594     {
2595       for (i = 0; i < 32; i += 2)
2596         {
2597           int consecutive_zeros = 0;
2598
2599           if (!(val & (3 << i)))
2600             {
2601               while ((i < 32) && !(val & (3 << i)))
2602                 {
2603                   consecutive_zeros += 2;
2604                   i += 2;
2605                 }
2606               if (consecutive_zeros > best_consecutive_zeros)
2607                 {
2608                   best_consecutive_zeros = consecutive_zeros;
2609                   best_start = i - consecutive_zeros;
2610                 }
2611               i -= 2;
2612             }
2613         }
2614     }
2615
2616   /* So long as it won't require any more insns to do so, it's
2617      desirable to emit a small constant (in bits 0...9) in the last
2618      insn.  This way there is more chance that it can be combined with
2619      a later addressing insn to form a pre-indexed load or store
2620      operation.  Consider:
2621
2622            *((volatile int *)0xe0000100) = 1;
2623            *((volatile int *)0xe0000110) = 2;
2624
2625      We want this to wind up as:
2626
2627             mov rA, #0xe0000000
2628             mov rB, #1
2629             str rB, [rA, #0x100]
2630             mov rB, #2
2631             str rB, [rA, #0x110]
2632
2633      rather than having to synthesize both large constants from scratch.
2634
2635      Therefore, we calculate how many insns would be required to emit
2636      the constant starting from `best_start', and also starting from
2637      zero (i.e. with bit 31 first to be output).  If `best_start' doesn't
2638      yield a shorter sequence, we may as well use zero.  */
2639   insns1 = optimal_immediate_sequence_1 (code, val, return_sequence, best_start);
2640   if (best_start != 0
2641       && ((((unsigned HOST_WIDE_INT) 1) << best_start) < val))
2642     {
2643       insns2 = optimal_immediate_sequence_1 (code, val, &tmp_sequence, 0);
2644       if (insns2 <= insns1)
2645         {
2646           *return_sequence = tmp_sequence;
2647           insns1 = insns2;
2648         }
2649     }
2650
2651   return insns1;
2652 }
2653
2654 /* As for optimal_immediate_sequence, but starting at bit-position I.  */
2655 static int
2656 optimal_immediate_sequence_1 (enum rtx_code code, unsigned HOST_WIDE_INT val,
2657                              struct four_ints *return_sequence, int i)
2658 {
2659   int remainder = val & 0xffffffff;
2660   int insns = 0;
2661
2662   /* Try and find a way of doing the job in either two or three
2663      instructions.
2664
2665      In ARM mode we can use 8-bit constants, rotated to any 2-bit aligned
2666      location.  We start at position I.  This may be the MSB, or
2667      optimial_immediate_sequence may have positioned it at the largest block
2668      of zeros that are aligned on a 2-bit boundary. We then fill up the temps,
2669      wrapping around to the top of the word when we drop off the bottom.
2670      In the worst case this code should produce no more than four insns.
2671
2672      In Thumb2 mode, we can use 32/16-bit replicated constants, and 8-bit
2673      constants, shifted to any arbitrary location.  We should always start
2674      at the MSB.  */
2675   do
2676     {
2677       int end;
2678       unsigned int b1, b2, b3, b4;
2679       unsigned HOST_WIDE_INT result;
2680       int loc;
2681
2682       gcc_assert (insns < 4);
2683
2684       if (i <= 0)
2685         i += 32;
2686
2687       /* First, find the next normal 12/8-bit shifted/rotated immediate.  */
2688       if (remainder & ((TARGET_ARM ? (3 << (i - 2)) : (1 << (i - 1)))))
2689         {
2690           loc = i;
2691           if (i <= 12 && TARGET_THUMB2 && code == PLUS)
2692             /* We can use addw/subw for the last 12 bits.  */
2693             result = remainder;
2694           else
2695             {
2696               /* Use an 8-bit shifted/rotated immediate.  */
2697               end = i - 8;
2698               if (end < 0)
2699                 end += 32;
2700               result = remainder & ((0x0ff << end)
2701                                    | ((i < end) ? (0xff >> (32 - end))
2702                                                 : 0));
2703               i -= 8;
2704             }
2705         }
2706       else
2707         {
2708           /* Arm allows rotates by a multiple of two. Thumb-2 allows
2709              arbitrary shifts.  */
2710           i -= TARGET_ARM ? 2 : 1;
2711           continue;
2712         }
2713
2714       /* Next, see if we can do a better job with a thumb2 replicated
2715          constant.
2716
2717          We do it this way around to catch the cases like 0x01F001E0 where
2718          two 8-bit immediates would work, but a replicated constant would
2719          make it worse.
2720
2721          TODO: 16-bit constants that don't clear all the bits, but still win.
2722          TODO: Arithmetic splitting for set/add/sub, rather than bitwise.  */
2723       if (TARGET_THUMB2)
2724         {
2725           b1 = (remainder & 0xff000000) >> 24;
2726           b2 = (remainder & 0x00ff0000) >> 16;
2727           b3 = (remainder & 0x0000ff00) >> 8;
2728           b4 = remainder & 0xff;
2729
2730           if (loc > 24)
2731             {
2732               /* The 8-bit immediate already found clears b1 (and maybe b2),
2733                  but must leave b3 and b4 alone.  */
2734
2735               /* First try to find a 32-bit replicated constant that clears
2736                  almost everything.  We can assume that we can't do it in one,
2737                  or else we wouldn't be here.  */
2738               unsigned int tmp = b1 & b2 & b3 & b4;
2739               unsigned int tmp2 = tmp + (tmp << 8) + (tmp << 16)
2740                                   + (tmp << 24);
2741               unsigned int matching_bytes = (tmp == b1) + (tmp == b2)
2742                                             + (tmp == b3) + (tmp == b4);
2743               if (tmp
2744                   && (matching_bytes >= 3
2745                       || (matching_bytes == 2
2746                           && const_ok_for_op (remainder & ~tmp2, code))))
2747                 {
2748                   /* At least 3 of the bytes match, and the fourth has at
2749                      least as many bits set, or two of the bytes match
2750                      and it will only require one more insn to finish.  */
2751                   result = tmp2;
2752                   i = tmp != b1 ? 32
2753                       : tmp != b2 ? 24
2754                       : tmp != b3 ? 16
2755                       : 8;
2756                 }
2757
2758               /* Second, try to find a 16-bit replicated constant that can
2759                  leave three of the bytes clear.  If b2 or b4 is already
2760                  zero, then we can.  If the 8-bit from above would not
2761                  clear b2 anyway, then we still win.  */
2762               else if (b1 == b3 && (!b2 || !b4
2763                                || (remainder & 0x00ff0000 & ~result)))
2764                 {
2765                   result = remainder & 0xff00ff00;
2766                   i = 24;
2767                 }
2768             }
2769           else if (loc > 16)
2770             {
2771               /* The 8-bit immediate already found clears b2 (and maybe b3)
2772                  and we don't get here unless b1 is alredy clear, but it will
2773                  leave b4 unchanged.  */
2774
2775               /* If we can clear b2 and b4 at once, then we win, since the
2776                  8-bits couldn't possibly reach that far.  */
2777               if (b2 == b4)
2778                 {
2779                   result = remainder & 0x00ff00ff;
2780                   i = 16;
2781                 }
2782             }
2783         }
2784
2785       return_sequence->i[insns++] = result;
2786       remainder &= ~result;
2787
2788       if (code == SET || code == MINUS)
2789         code = PLUS;
2790     }
2791   while (remainder);
2792
2793   return insns;
2794 }
2795
2796 /* Emit an instruction with the indicated PATTERN.  If COND is
2797    non-NULL, conditionalize the execution of the instruction on COND
2798    being true.  */
2799
2800 static void
2801 emit_constant_insn (rtx cond, rtx pattern)
2802 {
2803   if (cond)
2804     pattern = gen_rtx_COND_EXEC (VOIDmode, copy_rtx (cond), pattern);
2805   emit_insn (pattern);
2806 }
2807
2808 /* As above, but extra parameter GENERATE which, if clear, suppresses
2809    RTL generation.  */
2810
2811 static int
2812 arm_gen_constant (enum rtx_code code, enum machine_mode mode, rtx cond,
2813                   HOST_WIDE_INT val, rtx target, rtx source, int subtargets,
2814                   int generate)
2815 {
2816   int can_invert = 0;
2817   int can_negate = 0;
2818   int final_invert = 0;
2819   int i;
2820   int set_sign_bit_copies = 0;
2821   int clear_sign_bit_copies = 0;
2822   int clear_zero_bit_copies = 0;
2823   int set_zero_bit_copies = 0;
2824   int insns = 0, neg_insns, inv_insns;
2825   unsigned HOST_WIDE_INT temp1, temp2;
2826   unsigned HOST_WIDE_INT remainder = val & 0xffffffff;
2827   struct four_ints *immediates;
2828   struct four_ints pos_immediates, neg_immediates, inv_immediates;
2829
2830   /* Find out which operations are safe for a given CODE.  Also do a quick
2831      check for degenerate cases; these can occur when DImode operations
2832      are split.  */
2833   switch (code)
2834     {
2835     case SET:
2836       can_invert = 1;
2837       break;
2838
2839     case PLUS:
2840       can_negate = 1;
2841       break;
2842
2843     case IOR:
2844       if (remainder == 0xffffffff)
2845         {
2846           if (generate)
2847             emit_constant_insn (cond,
2848                                 gen_rtx_SET (VOIDmode, target,
2849                                              GEN_INT (ARM_SIGN_EXTEND (val))));
2850           return 1;
2851         }
2852
2853       if (remainder == 0)
2854         {
2855           if (reload_completed && rtx_equal_p (target, source))
2856             return 0;
2857
2858           if (generate)
2859             emit_constant_insn (cond,
2860                                 gen_rtx_SET (VOIDmode, target, source));
2861           return 1;
2862         }
2863       break;
2864
2865     case AND:
2866       if (remainder == 0)
2867         {
2868           if (generate)
2869             emit_constant_insn (cond,
2870                                 gen_rtx_SET (VOIDmode, target, const0_rtx));
2871           return 1;
2872         }
2873       if (remainder == 0xffffffff)
2874         {
2875           if (reload_completed && rtx_equal_p (target, source))
2876             return 0;
2877           if (generate)
2878             emit_constant_insn (cond,
2879                                 gen_rtx_SET (VOIDmode, target, source));
2880           return 1;
2881         }
2882       can_invert = 1;
2883       break;
2884
2885     case XOR:
2886       if (remainder == 0)
2887         {
2888           if (reload_completed && rtx_equal_p (target, source))
2889             return 0;
2890           if (generate)
2891             emit_constant_insn (cond,
2892                                 gen_rtx_SET (VOIDmode, target, source));
2893           return 1;
2894         }
2895
2896       if (remainder == 0xffffffff)
2897         {
2898           if (generate)
2899             emit_constant_insn (cond,
2900                                 gen_rtx_SET (VOIDmode, target,
2901                                              gen_rtx_NOT (mode, source)));
2902           return 1;
2903         }
2904       final_invert = 1;
2905       break;
2906
2907     case MINUS:
2908       /* We treat MINUS as (val - source), since (source - val) is always
2909          passed as (source + (-val)).  */
2910       if (remainder == 0)
2911         {
2912           if (generate)
2913             emit_constant_insn (cond,
2914                                 gen_rtx_SET (VOIDmode, target,
2915                                              gen_rtx_NEG (mode, source)));
2916           return 1;
2917         }
2918       if (const_ok_for_arm (val))
2919         {
2920           if (generate)
2921             emit_constant_insn (cond,
2922                                 gen_rtx_SET (VOIDmode, target,
2923                                              gen_rtx_MINUS (mode, GEN_INT (val),
2924                                                             source)));
2925           return 1;
2926         }
2927
2928       break;
2929
2930     default:
2931       gcc_unreachable ();
2932     }
2933
2934   /* If we can do it in one insn get out quickly.  */
2935   if (const_ok_for_op (val, code))
2936     {
2937       if (generate)
2938         emit_constant_insn (cond,
2939                             gen_rtx_SET (VOIDmode, target,
2940                                          (source
2941                                           ? gen_rtx_fmt_ee (code, mode, source,
2942                                                             GEN_INT (val))
2943                                           : GEN_INT (val))));
2944       return 1;
2945     }
2946
2947   /* Calculate a few attributes that may be useful for specific
2948      optimizations.  */
2949   /* Count number of leading zeros.  */
2950   for (i = 31; i >= 0; i--)
2951     {
2952       if ((remainder & (1 << i)) == 0)
2953         clear_sign_bit_copies++;
2954       else
2955         break;
2956     }
2957
2958   /* Count number of leading 1's.  */
2959   for (i = 31; i >= 0; i--)
2960     {
2961       if ((remainder & (1 << i)) != 0)
2962         set_sign_bit_copies++;
2963       else
2964         break;
2965     }
2966
2967   /* Count number of trailing zero's.  */
2968   for (i = 0; i <= 31; i++)
2969     {
2970       if ((remainder & (1 << i)) == 0)
2971         clear_zero_bit_copies++;
2972       else
2973         break;
2974     }
2975
2976   /* Count number of trailing 1's.  */
2977   for (i = 0; i <= 31; i++)
2978     {
2979       if ((remainder & (1 << i)) != 0)
2980         set_zero_bit_copies++;
2981       else
2982         break;
2983     }
2984
2985   switch (code)
2986     {
2987     case SET:
2988       /* See if we can do this by sign_extending a constant that is known
2989          to be negative.  This is a good, way of doing it, since the shift
2990          may well merge into a subsequent insn.  */
2991       if (set_sign_bit_copies > 1)
2992         {
2993           if (const_ok_for_arm
2994               (temp1 = ARM_SIGN_EXTEND (remainder
2995                                         << (set_sign_bit_copies - 1))))
2996             {
2997               if (generate)
2998                 {
2999                   rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
3000                   emit_constant_insn (cond,
3001                                       gen_rtx_SET (VOIDmode, new_src,
3002                                                    GEN_INT (temp1)));
3003                   emit_constant_insn (cond,
3004                                       gen_ashrsi3 (target, new_src,
3005                                                    GEN_INT (set_sign_bit_copies - 1)));
3006                 }
3007               return 2;
3008             }
3009           /* For an inverted constant, we will need to set the low bits,
3010              these will be shifted out of harm's way.  */
3011           temp1 |= (1 << (set_sign_bit_copies - 1)) - 1;
3012           if (const_ok_for_arm (~temp1))
3013             {
3014               if (generate)
3015                 {
3016                   rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
3017                   emit_constant_insn (cond,
3018                                       gen_rtx_SET (VOIDmode, new_src,
3019                                                    GEN_INT (temp1)));
3020                   emit_constant_insn (cond,
3021                                       gen_ashrsi3 (target, new_src,
3022                                                    GEN_INT (set_sign_bit_copies - 1)));
3023                 }
3024               return 2;
3025             }
3026         }
3027
3028       /* See if we can calculate the value as the difference between two
3029          valid immediates.  */
3030       if (clear_sign_bit_copies + clear_zero_bit_copies <= 16)
3031         {
3032           int topshift = clear_sign_bit_copies & ~1;
3033
3034           temp1 = ARM_SIGN_EXTEND ((remainder + (0x00800000 >> topshift))
3035                                    & (0xff000000 >> topshift));
3036
3037           /* If temp1 is zero, then that means the 9 most significant
3038              bits of remainder were 1 and we've caused it to overflow.
3039              When topshift is 0 we don't need to do anything since we
3040              can borrow from 'bit 32'.  */
3041           if (temp1 == 0 && topshift != 0)
3042             temp1 = 0x80000000 >> (topshift - 1);
3043
3044           temp2 = ARM_SIGN_EXTEND (temp1 - remainder);
3045
3046           if (const_ok_for_arm (temp2))
3047             {
3048               if (generate)
3049                 {
3050                   rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
3051                   emit_constant_insn (cond,
3052                                       gen_rtx_SET (VOIDmode, new_src,
3053                                                    GEN_INT (temp1)));
3054                   emit_constant_insn (cond,
3055                                       gen_addsi3 (target, new_src,
3056                                                   GEN_INT (-temp2)));
3057                 }
3058
3059               return 2;
3060             }
3061         }
3062
3063       /* See if we can generate this by setting the bottom (or the top)
3064          16 bits, and then shifting these into the other half of the
3065          word.  We only look for the simplest cases, to do more would cost
3066          too much.  Be careful, however, not to generate this when the
3067          alternative would take fewer insns.  */
3068       if (val & 0xffff0000)
3069         {
3070           temp1 = remainder & 0xffff0000;
3071           temp2 = remainder & 0x0000ffff;
3072
3073           /* Overlaps outside this range are best done using other methods.  */
3074           for (i = 9; i < 24; i++)
3075             {
3076               if ((((temp2 | (temp2 << i)) & 0xffffffff) == remainder)
3077                   && !const_ok_for_arm (temp2))
3078                 {
3079                   rtx new_src = (subtargets
3080                                  ? (generate ? gen_reg_rtx (mode) : NULL_RTX)
3081                                  : target);
3082                   insns = arm_gen_constant (code, mode, cond, temp2, new_src,
3083                                             source, subtargets, generate);
3084                   source = new_src;
3085                   if (generate)
3086                     emit_constant_insn
3087                       (cond,
3088                        gen_rtx_SET
3089                        (VOIDmode, target,
3090                         gen_rtx_IOR (mode,
3091                                      gen_rtx_ASHIFT (mode, source,
3092                                                      GEN_INT (i)),
3093                                      source)));
3094                   return insns + 1;
3095                 }
3096             }
3097
3098           /* Don't duplicate cases already considered.  */
3099           for (i = 17; i < 24; i++)
3100             {
3101               if (((temp1 | (temp1 >> i)) == remainder)
3102                   && !const_ok_for_arm (temp1))
3103                 {
3104                   rtx new_src = (subtargets
3105                                  ? (generate ? gen_reg_rtx (mode) : NULL_RTX)
3106                                  : target);
3107                   insns = arm_gen_constant (code, mode, cond, temp1, new_src,
3108                                             source, subtargets, generate);
3109                   source = new_src;
3110                   if (generate)
3111                     emit_constant_insn
3112                       (cond,
3113                        gen_rtx_SET (VOIDmode, target,
3114                                     gen_rtx_IOR
3115                                     (mode,
3116                                      gen_rtx_LSHIFTRT (mode, source,
3117                                                        GEN_INT (i)),
3118                                      source)));
3119                   return insns + 1;
3120                 }
3121             }
3122         }
3123       break;
3124
3125     case IOR:
3126     case XOR:
3127       /* If we have IOR or XOR, and the constant can be loaded in a
3128          single instruction, and we can find a temporary to put it in,
3129          then this can be done in two instructions instead of 3-4.  */
3130       if (subtargets
3131           /* TARGET can't be NULL if SUBTARGETS is 0 */
3132           || (reload_completed && !reg_mentioned_p (target, source)))
3133         {
3134           if (const_ok_for_arm (ARM_SIGN_EXTEND (~val)))
3135             {
3136               if (generate)
3137                 {
3138                   rtx sub = subtargets ? gen_reg_rtx (mode) : target;
3139
3140                   emit_constant_insn (cond,
3141                                       gen_rtx_SET (VOIDmode, sub,
3142                                                    GEN_INT (val)));
3143                   emit_constant_insn (cond,
3144                                       gen_rtx_SET (VOIDmode, target,
3145                                                    gen_rtx_fmt_ee (code, mode,
3146                                                                    source, sub)));
3147                 }
3148               return 2;
3149             }
3150         }
3151
3152       if (code == XOR)
3153         break;
3154
3155       /*  Convert.
3156           x = y | constant ( which is composed of set_sign_bit_copies of leading 1s
3157                              and the remainder 0s for e.g. 0xfff00000)
3158           x = ~(~(y ashift set_sign_bit_copies) lshiftrt set_sign_bit_copies)
3159
3160           This can be done in 2 instructions by using shifts with mov or mvn.
3161           e.g. for
3162           x = x | 0xfff00000;
3163           we generate.
3164           mvn   r0, r0, asl #12
3165           mvn   r0, r0, lsr #12  */
3166       if (set_sign_bit_copies > 8
3167           && (val & (-1 << (32 - set_sign_bit_copies))) == val)
3168         {
3169           if (generate)
3170             {
3171               rtx sub = subtargets ? gen_reg_rtx (mode) : target;
3172               rtx shift = GEN_INT (set_sign_bit_copies);
3173
3174               emit_constant_insn
3175                 (cond,
3176                  gen_rtx_SET (VOIDmode, sub,
3177                               gen_rtx_NOT (mode,
3178                                            gen_rtx_ASHIFT (mode,
3179                                                            source,
3180                                                            shift))));
3181               emit_constant_insn
3182                 (cond,
3183                  gen_rtx_SET (VOIDmode, target,
3184                               gen_rtx_NOT (mode,
3185                                            gen_rtx_LSHIFTRT (mode, sub,
3186                                                              shift))));
3187             }
3188           return 2;
3189         }
3190
3191       /* Convert
3192           x = y | constant (which has set_zero_bit_copies number of trailing ones).
3193            to
3194           x = ~((~y lshiftrt set_zero_bit_copies) ashift set_zero_bit_copies).
3195
3196           For eg. r0 = r0 | 0xfff
3197                mvn      r0, r0, lsr #12
3198                mvn      r0, r0, asl #12
3199
3200       */
3201       if (set_zero_bit_copies > 8
3202           && (remainder & ((1 << set_zero_bit_copies) - 1)) == remainder)
3203         {
3204           if (generate)
3205             {
3206               rtx sub = subtargets ? gen_reg_rtx (mode) : target;
3207               rtx shift = GEN_INT (set_zero_bit_copies);
3208
3209               emit_constant_insn
3210                 (cond,
3211                  gen_rtx_SET (VOIDmode, sub,
3212                               gen_rtx_NOT (mode,
3213                                            gen_rtx_LSHIFTRT (mode,
3214                                                              source,
3215                                                              shift))));
3216               emit_constant_insn
3217                 (cond,
3218                  gen_rtx_SET (VOIDmode, target,
3219                               gen_rtx_NOT (mode,
3220                                            gen_rtx_ASHIFT (mode, sub,
3221                                                            shift))));
3222             }
3223           return 2;
3224         }
3225
3226       /* This will never be reached for Thumb2 because orn is a valid
3227          instruction. This is for Thumb1 and the ARM 32 bit cases.
3228
3229          x = y | constant (such that ~constant is a valid constant)
3230          Transform this to
3231          x = ~(~y & ~constant).
3232       */
3233       if (const_ok_for_arm (temp1 = ARM_SIGN_EXTEND (~val)))
3234         {
3235           if (generate)
3236             {
3237               rtx sub = subtargets ? gen_reg_rtx (mode) : target;
3238               emit_constant_insn (cond,
3239                                   gen_rtx_SET (VOIDmode, sub,
3240                                                gen_rtx_NOT (mode, source)));
3241               source = sub;
3242               if (subtargets)
3243                 sub = gen_reg_rtx (mode);
3244               emit_constant_insn (cond,
3245                                   gen_rtx_SET (VOIDmode, sub,
3246                                                gen_rtx_AND (mode, source,
3247                                                             GEN_INT (temp1))));
3248               emit_constant_insn (cond,
3249                                   gen_rtx_SET (VOIDmode, target,
3250                                                gen_rtx_NOT (mode, sub)));
3251             }
3252           return 3;
3253         }
3254       break;
3255
3256     case AND:
3257       /* See if two shifts will do 2 or more insn's worth of work.  */
3258       if (clear_sign_bit_copies >= 16 && clear_sign_bit_copies < 24)
3259         {
3260           HOST_WIDE_INT shift_mask = ((0xffffffff
3261                                        << (32 - clear_sign_bit_copies))
3262                                       & 0xffffffff);
3263
3264           if ((remainder | shift_mask) != 0xffffffff)
3265             {
3266               if (generate)
3267                 {
3268                   rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
3269                   insns = arm_gen_constant (AND, mode, cond,
3270                                             remainder | shift_mask,
3271                                             new_src, source, subtargets, 1);
3272                   source = new_src;
3273                 }
3274               else
3275                 {
3276                   rtx targ = subtargets ? NULL_RTX : target;
3277                   insns = arm_gen_constant (AND, mode, cond,
3278                                             remainder | shift_mask,
3279                                             targ, source, subtargets, 0);
3280                 }
3281             }
3282
3283           if (generate)
3284             {
3285               rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
3286               rtx shift = GEN_INT (clear_sign_bit_copies);
3287
3288               emit_insn (gen_ashlsi3 (new_src, source, shift));
3289               emit_insn (gen_lshrsi3 (target, new_src, shift));
3290             }
3291
3292           return insns + 2;
3293         }
3294
3295       if (clear_zero_bit_copies >= 16 && clear_zero_bit_copies < 24)
3296         {
3297           HOST_WIDE_INT shift_mask = (1 << clear_zero_bit_copies) - 1;
3298
3299           if ((remainder | shift_mask) != 0xffffffff)
3300             {
3301               if (generate)
3302                 {
3303                   rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
3304
3305                   insns = arm_gen_constant (AND, mode, cond,
3306                                             remainder | shift_mask,
3307                                             new_src, source, subtargets, 1);
3308                   source = new_src;
3309                 }
3310               else
3311                 {
3312                   rtx targ = subtargets ? NULL_RTX : target;
3313
3314                   insns = arm_gen_constant (AND, mode, cond,
3315                                             remainder | shift_mask,
3316                                             targ, source, subtargets, 0);
3317                 }
3318             }
3319
3320           if (generate)
3321             {
3322               rtx new_src = subtargets ? gen_reg_rtx (mode) : target;
3323               rtx shift = GEN_INT (clear_zero_bit_copies);
3324
3325               emit_insn (gen_lshrsi3 (new_src, source, shift));
3326               emit_insn (gen_ashlsi3 (target, new_src, shift));
3327             }
3328
3329           return insns + 2;
3330         }
3331
3332       break;
3333
3334     default:
3335       break;
3336     }
3337
3338   /* Calculate what the instruction sequences would be if we generated it
3339      normally, negated, or inverted.  */
3340   if (code == AND)
3341     /* AND cannot be split into multiple insns, so invert and use BIC.  */
3342     insns = 99;
3343   else
3344     insns = optimal_immediate_sequence (code, remainder, &pos_immediates);
3345
3346   if (can_negate)
3347     neg_insns = optimal_immediate_sequence (code, (-remainder) & 0xffffffff,
3348                                             &neg_immediates);
3349   else
3350     neg_insns = 99;
3351
3352   if (can_invert || final_invert)
3353     inv_insns = optimal_immediate_sequence (code, remainder ^ 0xffffffff,
3354                                             &inv_immediates);
3355   else
3356     inv_insns = 99;
3357
3358   immediates = &pos_immediates;
3359
3360   /* Is the negated immediate sequence more efficient?  */
3361   if (neg_insns < insns && neg_insns <= inv_insns)
3362     {
3363       insns = neg_insns;
3364       immediates = &neg_immediates;
3365     }
3366   else
3367     can_negate = 0;
3368
3369   /* Is the inverted immediate sequence more efficient?
3370      We must allow for an extra NOT instruction for XOR operations, although
3371      there is some chance that the final 'mvn' will get optimized later.  */
3372   if ((inv_insns + 1) < insns || (!final_invert && inv_insns < insns))
3373     {
3374       insns = inv_insns;
3375       immediates = &inv_immediates;
3376     }
3377   else
3378     {
3379       can_invert = 0;
3380       final_invert = 0;
3381     }
3382
3383   /* Now output the chosen sequence as instructions.  */
3384   if (generate)
3385     {
3386       for (i = 0; i < insns; i++)
3387         {
3388           rtx new_src, temp1_rtx;
3389
3390           temp1 = immediates->i[i];
3391
3392           if (code == SET || code == MINUS)
3393             new_src = (subtargets ? gen_reg_rtx (mode) : target);
3394           else if ((final_invert || i < (insns - 1)) && subtargets)
3395             new_src = gen_reg_rtx (mode);
3396           else
3397             new_src = target;
3398
3399           if (can_invert)
3400             temp1 = ~temp1;
3401           else if (can_negate)
3402             temp1 = -temp1;
3403
3404           temp1 = trunc_int_for_mode (temp1, mode);
3405           temp1_rtx = GEN_INT (temp1);
3406
3407           if (code == SET)
3408             ;
3409           else if (code == MINUS)
3410             temp1_rtx = gen_rtx_MINUS (mode, temp1_rtx, source);
3411           else
3412             temp1_rtx = gen_rtx_fmt_ee (code, mode, source, temp1_rtx);
3413
3414           emit_constant_insn (cond,
3415                               gen_rtx_SET (VOIDmode, new_src,
3416                                            temp1_rtx));
3417           source = new_src;
3418
3419           if (code == SET)
3420             {
3421               can_negate = can_invert;
3422               can_invert = 0;
3423               code = PLUS;
3424             }
3425           else if (code == MINUS)
3426             code = PLUS;
3427         }
3428     }
3429
3430   if (final_invert)
3431     {
3432       if (generate)
3433         emit_constant_insn (cond, gen_rtx_SET (VOIDmode, target,
3434                                                gen_rtx_NOT (mode, source)));
3435       insns++;
3436     }
3437
3438   return insns;
3439 }
3440
3441 /* Canonicalize a comparison so that we are more likely to recognize it.
3442    This can be done for a few constant compares, where we can make the
3443    immediate value easier to load.  */
3444
3445 enum rtx_code
3446 arm_canonicalize_comparison (enum rtx_code code, rtx *op0, rtx *op1)
3447 {
3448   enum machine_mode mode;
3449   unsigned HOST_WIDE_INT i, maxval;
3450
3451   mode = GET_MODE (*op0);
3452   if (mode == VOIDmode)
3453     mode = GET_MODE (*op1);
3454
3455   maxval = (((unsigned HOST_WIDE_INT) 1) << (GET_MODE_BITSIZE(mode) - 1)) - 1;
3456
3457   /* For DImode, we have GE/LT/GEU/LTU comparisons.  In ARM mode
3458      we can also use cmp/cmpeq for GTU/LEU.  GT/LE must be either
3459      reversed or (for constant OP1) adjusted to GE/LT.  Similarly
3460      for GTU/LEU in Thumb mode.  */
3461   if (mode == DImode)
3462     {
3463       rtx tem;
3464
3465       /* To keep things simple, always use the Cirrus cfcmp64 if it is
3466          available.  */
3467       if (TARGET_ARM && TARGET_HARD_FLOAT && TARGET_MAVERICK)
3468         return code;
3469
3470       if (code == GT || code == LE
3471           || (!TARGET_ARM && (code == GTU || code == LEU)))
3472         {
3473           /* Missing comparison.  First try to use an available
3474              comparison.  */
3475           if (GET_CODE (*op1) == CONST_INT)
3476             {
3477               i = INTVAL (*op1);
3478               switch (code)
3479                 {
3480                 case GT:
3481                 case LE:
3482                   if (i != maxval
3483                       && arm_const_double_by_immediates (GEN_INT (i + 1)))
3484                     {
3485                       *op1 = GEN_INT (i + 1);
3486                       return code == GT ? GE : LT;
3487                     }
3488                   break;
3489                 case GTU:
3490                 case LEU:
3491                   if (i != ~((unsigned HOST_WIDE_INT) 0)
3492                       && arm_const_double_by_immediates (GEN_INT (i + 1)))
3493                     {
3494                       *op1 = GEN_INT (i + 1);
3495                       return code == GTU ? GEU : LTU;
3496                     }
3497                   break;
3498                 default:
3499                   gcc_unreachable ();
3500                 }
3501             }
3502
3503           /* If that did not work, reverse the condition.  */
3504           tem = *op0;
3505           *op0 = *op1;
3506           *op1 = tem;
3507           return swap_condition (code);
3508         }
3509
3510       return code;
3511     }
3512
3513   /* If *op0 is (zero_extend:SI (subreg:QI (reg:SI) 0)) and comparing
3514      with const0_rtx, change it to (and:SI (reg:SI) (const_int 255)),
3515      to facilitate possible combining with a cmp into 'ands'.  */
3516   if (mode == SImode
3517       && GET_CODE (*op0) == ZERO_EXTEND
3518       && GET_CODE (XEXP (*op0, 0)) == SUBREG
3519       && GET_MODE (XEXP (*op0, 0)) == QImode
3520       && GET_MODE (SUBREG_REG (XEXP (*op0, 0))) == SImode
3521       && subreg_lowpart_p (XEXP (*op0, 0))
3522       && *op1 == const0_rtx)
3523     *op0 = gen_rtx_AND (SImode, SUBREG_REG (XEXP (*op0, 0)),
3524                         GEN_INT (255));
3525
3526   /* Comparisons smaller than DImode.  Only adjust comparisons against
3527      an out-of-range constant.  */
3528   if (GET_CODE (*op1) != CONST_INT
3529       || const_ok_for_arm (INTVAL (*op1))
3530       || const_ok_for_arm (- INTVAL (*op1)))
3531     return code;
3532
3533   i = INTVAL (*op1);
3534
3535   switch (code)
3536     {
3537     case EQ:
3538     case NE:
3539       return code;
3540
3541     case GT:
3542     case LE:
3543       if (i != maxval
3544           && (const_ok_for_arm (i + 1) || const_ok_for_arm (-(i + 1))))
3545         {
3546           *op1 = GEN_INT (i + 1);
3547           return code == GT ? GE : LT;
3548         }
3549       break;
3550
3551     case GE:
3552     case LT:
3553       if (i != ~maxval
3554           && (const_ok_for_arm (i - 1) || const_ok_for_arm (-(i - 1))))
3555         {
3556           *op1 = GEN_INT (i - 1);
3557           return code == GE ? GT : LE;
3558         }
3559       break;
3560
3561     case GTU:
3562     case LEU:
3563       if (i != ~((unsigned HOST_WIDE_INT) 0)
3564           && (const_ok_for_arm (i + 1) || const_ok_for_arm (-(i + 1))))
3565         {
3566           *op1 = GEN_INT (i + 1);
3567           return code == GTU ? GEU : LTU;
3568         }
3569       break;
3570
3571     case GEU:
3572     case LTU:
3573       if (i != 0
3574           && (const_ok_for_arm (i - 1) || const_ok_for_arm (-(i - 1))))
3575         {
3576           *op1 = GEN_INT (i - 1);
3577           return code == GEU ? GTU : LEU;
3578         }
3579       break;
3580
3581     default:
3582       gcc_unreachable ();
3583     }
3584
3585   return code;
3586 }
3587
3588
3589 /* Define how to find the value returned by a function.  */
3590
3591 static rtx
3592 arm_function_value(const_tree type, const_tree func,
3593                    bool outgoing ATTRIBUTE_UNUSED)
3594 {
3595   enum machine_mode mode;
3596   int unsignedp ATTRIBUTE_UNUSED;
3597   rtx r ATTRIBUTE_UNUSED;
3598
3599   mode = TYPE_MODE (type);
3600
3601   if (TARGET_AAPCS_BASED)
3602     return aapcs_allocate_return_reg (mode, type, func);
3603
3604   /* Promote integer types.  */
3605   if (INTEGRAL_TYPE_P (type))
3606     mode = arm_promote_function_mode (type, mode, &unsignedp, func, 1);
3607
3608   /* Promotes small structs returned in a register to full-word size
3609      for big-endian AAPCS.  */
3610   if (arm_return_in_msb (type))
3611     {
3612       HOST_WIDE_INT size = int_size_in_bytes (type);
3613       if (size % UNITS_PER_WORD != 0)
3614         {
3615           size += UNITS_PER_WORD - size % UNITS_PER_WORD;
3616           mode = mode_for_size (size * BITS_PER_UNIT, MODE_INT, 0);
3617         }
3618     }
3619
3620   return arm_libcall_value_1 (mode);
3621 }
3622
3623 static int
3624 libcall_eq (const void *p1, const void *p2)
3625 {
3626   return rtx_equal_p ((const_rtx) p1, (const_rtx) p2);
3627 }
3628
3629 static hashval_t
3630 libcall_hash (const void *p1)
3631 {
3632   return hash_rtx ((const_rtx) p1, VOIDmode, NULL, NULL, FALSE);
3633 }
3634
3635 static void
3636 add_libcall (htab_t htab, rtx libcall)
3637 {
3638   *htab_find_slot (htab, libcall, INSERT) = libcall;
3639 }
3640
3641 static bool
3642 arm_libcall_uses_aapcs_base (const_rtx libcall)
3643 {
3644   static bool init_done = false;
3645   static htab_t libcall_htab;
3646
3647   if (!init_done)
3648     {
3649       init_done = true;
3650
3651       libcall_htab = htab_create (31, libcall_hash, libcall_eq,
3652                                   NULL);
3653       add_libcall (libcall_htab,
3654                    convert_optab_libfunc (sfloat_optab, SFmode, SImode));
3655       add_libcall (libcall_htab,
3656                    convert_optab_libfunc (sfloat_optab, DFmode, SImode));
3657       add_libcall (libcall_htab,
3658                    convert_optab_libfunc (sfloat_optab, SFmode, DImode));
3659       add_libcall (libcall_htab,
3660                    convert_optab_libfunc (sfloat_optab, DFmode, DImode));
3661
3662       add_libcall (libcall_htab,
3663                    convert_optab_libfunc (ufloat_optab, SFmode, SImode));
3664       add_libcall (libcall_htab,
3665                    convert_optab_libfunc (ufloat_optab, DFmode, SImode));
3666       add_libcall (libcall_htab,
3667                    convert_optab_libfunc (ufloat_optab, SFmode, DImode));
3668       add_libcall (libcall_htab,
3669                    convert_optab_libfunc (ufloat_optab, DFmode, DImode));
3670
3671       add_libcall (libcall_htab,
3672                    convert_optab_libfunc (sext_optab, SFmode, HFmode));
3673       add_libcall (libcall_htab,
3674                    convert_optab_libfunc (trunc_optab, HFmode, SFmode));
3675       add_libcall (libcall_htab,
3676                    convert_optab_libfunc (sfix_optab, DImode, DFmode));
3677       add_libcall (libcall_htab,
3678                    convert_optab_libfunc (ufix_optab, DImode, DFmode));
3679       add_libcall (libcall_htab,
3680                    convert_optab_libfunc (sfix_optab, DImode, SFmode));
3681       add_libcall (libcall_htab,
3682                    convert_optab_libfunc (ufix_optab, DImode, SFmode));
3683
3684       /* Values from double-precision helper functions are returned in core
3685          registers if the selected core only supports single-precision
3686          arithmetic, even if we are using the hard-float ABI.  The same is
3687          true for single-precision helpers, but we will never be using the
3688          hard-float ABI on a CPU which doesn't support single-precision
3689          operations in hardware.  */
3690       add_libcall (libcall_htab, optab_libfunc (add_optab, DFmode));
3691       add_libcall (libcall_htab, optab_libfunc (sdiv_optab, DFmode));
3692       add_libcall (libcall_htab, optab_libfunc (smul_optab, DFmode));
3693       add_libcall (libcall_htab, optab_libfunc (neg_optab, DFmode));
3694       add_libcall (libcall_htab, optab_libfunc (sub_optab, DFmode));
3695       add_libcall (libcall_htab, optab_libfunc (eq_optab, DFmode));
3696       add_libcall (libcall_htab, optab_libfunc (lt_optab, DFmode));
3697       add_libcall (libcall_htab, optab_libfunc (le_optab, DFmode));
3698       add_libcall (libcall_htab, optab_libfunc (ge_optab, DFmode));
3699       add_libcall (libcall_htab, optab_libfunc (gt_optab, DFmode));
3700       add_libcall (libcall_htab, optab_libfunc (unord_optab, DFmode));
3701       add_libcall (libcall_htab, convert_optab_libfunc (sext_optab, DFmode,
3702                                                         SFmode));
3703       add_libcall (libcall_htab, convert_optab_libfunc (trunc_optab, SFmode,
3704                                                         DFmode));
3705     }
3706
3707   return libcall && htab_find (libcall_htab, libcall) != NULL;
3708 }
3709
3710 static rtx
3711 arm_libcall_value_1 (enum machine_mode mode)
3712 {
3713   if (TARGET_AAPCS_BASED)
3714     return aapcs_libcall_value (mode);
3715   else if (TARGET_32BIT
3716            && TARGET_HARD_FLOAT_ABI
3717            && TARGET_FPA
3718            && GET_MODE_CLASS (mode) == MODE_FLOAT)
3719     return gen_rtx_REG (mode, FIRST_FPA_REGNUM);
3720   else if (TARGET_32BIT
3721            && TARGET_HARD_FLOAT_ABI
3722            && TARGET_MAVERICK
3723            && GET_MODE_CLASS (mode) == MODE_FLOAT)
3724     return gen_rtx_REG (mode, FIRST_CIRRUS_FP_REGNUM);
3725   else if (TARGET_IWMMXT_ABI
3726            && arm_vector_mode_supported_p (mode))
3727     return gen_rtx_REG (mode, FIRST_IWMMXT_REGNUM);
3728   else
3729     return gen_rtx_REG (mode, ARG_REGISTER (1));
3730 }
3731
3732 /* Define how to find the value returned by a library function
3733    assuming the value has mode MODE.  */
3734
3735 static rtx
3736 arm_libcall_value (enum machine_mode mode, const_rtx libcall)
3737 {
3738   if (TARGET_AAPCS_BASED && arm_pcs_default != ARM_PCS_AAPCS
3739       && GET_MODE_CLASS (mode) == MODE_FLOAT)
3740     {
3741       /* The following libcalls return their result in integer registers,
3742          even though they return a floating point value.  */
3743       if (arm_libcall_uses_aapcs_base (libcall))
3744         return gen_rtx_REG (mode, ARG_REGISTER(1));
3745
3746     }
3747
3748   return arm_libcall_value_1 (mode);
3749 }
3750
3751 /* Implement TARGET_FUNCTION_VALUE_REGNO_P.  */
3752
3753 static bool
3754 arm_function_value_regno_p (const unsigned int regno)
3755 {
3756   if (regno == ARG_REGISTER (1)
3757       || (TARGET_32BIT
3758           && TARGET_AAPCS_BASED
3759           && TARGET_VFP
3760           && TARGET_HARD_FLOAT
3761           && regno == FIRST_VFP_REGNUM)
3762       || (TARGET_32BIT
3763           && TARGET_HARD_FLOAT_ABI
3764           && TARGET_MAVERICK
3765           && regno == FIRST_CIRRUS_FP_REGNUM)
3766       || (TARGET_IWMMXT_ABI
3767           && regno == FIRST_IWMMXT_REGNUM)
3768       || (TARGET_32BIT
3769           && TARGET_HARD_FLOAT_ABI
3770           && TARGET_FPA
3771           && regno == FIRST_FPA_REGNUM))
3772     return true;
3773
3774   return false;
3775 }
3776
3777 /* Determine the amount of memory needed to store the possible return
3778    registers of an untyped call.  */
3779 int
3780 arm_apply_result_size (void)
3781 {
3782   int size = 16;
3783
3784   if (TARGET_32BIT)
3785     {
3786       if (TARGET_HARD_FLOAT_ABI)
3787         {
3788           if (TARGET_VFP)
3789             size += 32;
3790           if (TARGET_FPA)
3791             size += 12;
3792           if (TARGET_MAVERICK)
3793             size += 8;
3794         }
3795       if (TARGET_IWMMXT_ABI)
3796         size += 8;
3797     }
3798
3799   return size;
3800 }
3801
3802 /* Decide whether TYPE should be returned in memory (true)
3803    or in a register (false).  FNTYPE is the type of the function making
3804    the call.  */
3805 static bool
3806 arm_return_in_memory (const_tree type, const_tree fntype)
3807 {
3808   HOST_WIDE_INT size;
3809
3810   size = int_size_in_bytes (type);  /* Negative if not fixed size.  */
3811
3812   if (TARGET_AAPCS_BASED)
3813     {
3814       /* Simple, non-aggregate types (ie not including vectors and
3815          complex) are always returned in a register (or registers).
3816          We don't care about which register here, so we can short-cut
3817          some of the detail.  */
3818       if (!AGGREGATE_TYPE_P (type)
3819           && TREE_CODE (type) != VECTOR_TYPE
3820           && TREE_CODE (type) != COMPLEX_TYPE)
3821         return false;
3822
3823       /* Any return value that is no larger than one word can be
3824          returned in r0.  */
3825       if (((unsigned HOST_WIDE_INT) size) <= UNITS_PER_WORD)
3826         return false;
3827
3828       /* Check any available co-processors to see if they accept the
3829          type as a register candidate (VFP, for example, can return
3830          some aggregates in consecutive registers).  These aren't
3831          available if the call is variadic.  */
3832       if (aapcs_select_return_coproc (type, fntype) >= 0)
3833         return false;
3834
3835       /* Vector values should be returned using ARM registers, not
3836          memory (unless they're over 16 bytes, which will break since
3837          we only have four call-clobbered registers to play with).  */
3838       if (TREE_CODE (type) == VECTOR_TYPE)
3839         return (size < 0 || size > (4 * UNITS_PER_WORD));
3840
3841       /* The rest go in memory.  */
3842       return true;
3843     }
3844
3845   if (TREE_CODE (type) == VECTOR_TYPE)
3846     return (size < 0 || size > (4 * UNITS_PER_WORD));
3847
3848   if (!AGGREGATE_TYPE_P (type) &&
3849       (TREE_CODE (type) != VECTOR_TYPE))
3850     /* All simple types are returned in registers.  */
3851     return false;
3852
3853   if (arm_abi != ARM_ABI_APCS)
3854     {
3855       /* ATPCS and later return aggregate types in memory only if they are
3856          larger than a word (or are variable size).  */
3857       return (size < 0 || size > UNITS_PER_WORD);
3858     }
3859
3860   /* For the arm-wince targets we choose to be compatible with Microsoft's
3861      ARM and Thumb compilers, which always return aggregates in memory.  */
3862 #ifndef ARM_WINCE
3863   /* All structures/unions bigger than one word are returned in memory.
3864      Also catch the case where int_size_in_bytes returns -1.  In this case
3865      the aggregate is either huge or of variable size, and in either case
3866      we will want to return it via memory and not in a register.  */
3867   if (size < 0 || size > UNITS_PER_WORD)
3868     return true;
3869
3870   if (TREE_CODE (type) == RECORD_TYPE)
3871     {
3872       tree field;
3873
3874       /* For a struct the APCS says that we only return in a register
3875          if the type is 'integer like' and every addressable element
3876          has an offset of zero.  For practical purposes this means
3877          that the structure can have at most one non bit-field element
3878          and that this element must be the first one in the structure.  */
3879
3880       /* Find the first field, ignoring non FIELD_DECL things which will
3881          have been created by C++.  */
3882       for (field = TYPE_FIELDS (type);
3883            field && TREE_CODE (field) != FIELD_DECL;
3884            field = DECL_CHAIN (field))
3885         continue;
3886
3887       if (field == NULL)
3888         return false; /* An empty structure.  Allowed by an extension to ANSI C.  */
3889
3890       /* Check that the first field is valid for returning in a register.  */
3891
3892       /* ... Floats are not allowed */
3893       if (FLOAT_TYPE_P (TREE_TYPE (field)))
3894         return true;
3895
3896       /* ... Aggregates that are not themselves valid for returning in
3897          a register are not allowed.  */
3898       if (arm_return_in_memory (TREE_TYPE (field), NULL_TREE))
3899         return true;
3900
3901       /* Now check the remaining fields, if any.  Only bitfields are allowed,
3902          since they are not addressable.  */
3903       for (field = DECL_CHAIN (field);
3904            field;
3905            field = DECL_CHAIN (field))
3906         {
3907           if (TREE_CODE (field) != FIELD_DECL)
3908             continue;
3909
3910           if (!DECL_BIT_FIELD_TYPE (field))
3911             return true;
3912         }
3913
3914       return false;
3915     }
3916
3917   if (TREE_CODE (type) == UNION_TYPE)
3918     {
3919       tree field;
3920
3921       /* Unions can be returned in registers if every element is
3922          integral, or can be returned in an integer register.  */
3923       for (field = TYPE_FIELDS (type);
3924            field;
3925            field = DECL_CHAIN (field))
3926         {
3927           if (TREE_CODE (field) != FIELD_DECL)
3928             continue;
3929
3930           if (FLOAT_TYPE_P (TREE_TYPE (field)))
3931             return true;
3932
3933           if (arm_return_in_memory (TREE_TYPE (field), NULL_TREE))
3934             return true;
3935         }
3936
3937       return false;
3938     }
3939 #endif /* not ARM_WINCE */
3940
3941   /* Return all other types in memory.  */
3942   return true;
3943 }
3944
3945 /* Indicate whether or not words of a double are in big-endian order.  */
3946
3947 int
3948 arm_float_words_big_endian (void)
3949 {
3950   if (TARGET_MAVERICK)
3951     return 0;
3952
3953   /* For FPA, float words are always big-endian.  For VFP, floats words
3954      follow the memory system mode.  */
3955
3956   if (TARGET_FPA)
3957     {
3958       return 1;
3959     }
3960
3961   if (TARGET_VFP)
3962     return (TARGET_BIG_END ? 1 : 0);
3963
3964   return 1;
3965 }
3966
3967 const struct pcs_attribute_arg
3968 {
3969   const char *arg;
3970   enum arm_pcs value;
3971 } pcs_attribute_args[] =
3972   {
3973     {"aapcs", ARM_PCS_AAPCS},
3974     {"aapcs-vfp", ARM_PCS_AAPCS_VFP},
3975 #if 0
3976     /* We could recognize these, but changes would be needed elsewhere
3977      * to implement them.  */
3978     {"aapcs-iwmmxt", ARM_PCS_AAPCS_IWMMXT},
3979     {"atpcs", ARM_PCS_ATPCS},
3980     {"apcs", ARM_PCS_APCS},
3981 #endif
3982     {NULL, ARM_PCS_UNKNOWN}
3983   };
3984
3985 static enum arm_pcs
3986 arm_pcs_from_attribute (tree attr)
3987 {
3988   const struct pcs_attribute_arg *ptr;
3989   const char *arg;
3990
3991   /* Get the value of the argument.  */
3992   if (TREE_VALUE (attr) == NULL_TREE
3993       || TREE_CODE (TREE_VALUE (attr)) != STRING_CST)
3994     return ARM_PCS_UNKNOWN;
3995
3996   arg = TREE_STRING_POINTER (TREE_VALUE (attr));
3997
3998   /* Check it against the list of known arguments.  */
3999   for (ptr = pcs_attribute_args; ptr->arg != NULL; ptr++)
4000     if (streq (arg, ptr->arg))
4001       return ptr->value;
4002
4003   /* An unrecognized interrupt type.  */
4004   return ARM_PCS_UNKNOWN;
4005 }
4006
4007 /* Get the PCS variant to use for this call.  TYPE is the function's type
4008    specification, DECL is the specific declartion.  DECL may be null if
4009    the call could be indirect or if this is a library call.  */
4010 static enum arm_pcs
4011 arm_get_pcs_model (const_tree type, const_tree decl)
4012 {
4013   bool user_convention = false;
4014   enum arm_pcs user_pcs = arm_pcs_default;
4015   tree attr;
4016
4017   gcc_assert (type);
4018
4019   attr = lookup_attribute ("pcs", TYPE_ATTRIBUTES (type));
4020   if (attr)
4021     {
4022       user_pcs = arm_pcs_from_attribute (TREE_VALUE (attr));
4023       user_convention = true;
4024     }
4025
4026   if (TARGET_AAPCS_BASED)
4027     {
4028       /* Detect varargs functions.  These always use the base rules
4029          (no argument is ever a candidate for a co-processor
4030          register).  */
4031       bool base_rules = stdarg_p (type);
4032
4033       if (user_convention)
4034         {
4035           if (user_pcs > ARM_PCS_AAPCS_LOCAL)
4036             sorry ("non-AAPCS derived PCS variant");
4037           else if (base_rules && user_pcs != ARM_PCS_AAPCS)
4038             error ("variadic functions must use the base AAPCS variant");
4039         }
4040
4041       if (base_rules)
4042         return ARM_PCS_AAPCS;
4043       else if (user_convention)
4044         return user_pcs;
4045       else if (decl && flag_unit_at_a_time)
4046         {
4047           /* Local functions never leak outside this compilation unit,
4048              so we are free to use whatever conventions are
4049              appropriate.  */
4050           /* FIXME: remove CONST_CAST_TREE when cgraph is constified.  */
4051           struct cgraph_local_info *i = cgraph_local_info (CONST_CAST_TREE(decl));
4052           if (i && i->local)
4053             return ARM_PCS_AAPCS_LOCAL;
4054         }
4055     }
4056   else if (user_convention && user_pcs != arm_pcs_default)
4057     sorry ("PCS variant");
4058
4059   /* For everything else we use the target's default.  */
4060   return arm_pcs_default;
4061 }
4062
4063
4064 static void
4065 aapcs_vfp_cum_init (CUMULATIVE_ARGS *pcum  ATTRIBUTE_UNUSED,
4066                     const_tree fntype ATTRIBUTE_UNUSED,
4067                     rtx libcall ATTRIBUTE_UNUSED,
4068                     const_tree fndecl ATTRIBUTE_UNUSED)
4069 {
4070   /* Record the unallocated VFP registers.  */
4071   pcum->aapcs_vfp_regs_free = (1 << NUM_VFP_ARG_REGS) - 1;
4072   pcum->aapcs_vfp_reg_alloc = 0;
4073 }
4074
4075 /* Walk down the type tree of TYPE counting consecutive base elements.
4076    If *MODEP is VOIDmode, then set it to the first valid floating point
4077    type.  If a non-floating point type is found, or if a floating point
4078    type that doesn't match a non-VOIDmode *MODEP is found, then return -1,
4079    otherwise return the count in the sub-tree.  */
4080 static int
4081 aapcs_vfp_sub_candidate (const_tree type, enum machine_mode *modep)
4082 {
4083   enum machine_mode mode;
4084   HOST_WIDE_INT size;
4085
4086   switch (TREE_CODE (type))
4087     {
4088     case REAL_TYPE:
4089       mode = TYPE_MODE (type);
4090       if (mode != DFmode && mode != SFmode)
4091         return -1;
4092
4093       if (*modep == VOIDmode)
4094         *modep = mode;
4095
4096       if (*modep == mode)
4097         return 1;
4098
4099       break;
4100
4101     case COMPLEX_TYPE:
4102       mode = TYPE_MODE (TREE_TYPE (type));
4103       if (mode != DFmode && mode != SFmode)
4104         return -1;
4105
4106       if (*modep == VOIDmode)
4107         *modep = mode;
4108
4109       if (*modep == mode)
4110         return 2;
4111
4112       break;
4113
4114     case VECTOR_TYPE:
4115       /* Use V2SImode and V4SImode as representatives of all 64-bit
4116          and 128-bit vector types, whether or not those modes are
4117          supported with the present options.  */
4118       size = int_size_in_bytes (type);
4119       switch (size)
4120         {
4121         case 8:
4122           mode = V2SImode;
4123           break;
4124         case 16:
4125           mode = V4SImode;
4126           break;
4127         default:
4128           return -1;
4129         }
4130
4131       if (*modep == VOIDmode)
4132         *modep = mode;
4133
4134       /* Vector modes are considered to be opaque: two vectors are
4135          equivalent for the purposes of being homogeneous aggregates
4136          if they are the same size.  */
4137       if (*modep == mode)
4138         return 1;
4139
4140       break;
4141
4142     case ARRAY_TYPE:
4143       {
4144         int count;
4145         tree index = TYPE_DOMAIN (type);
4146
4147         /* Can't handle incomplete types.  */
4148         if (!COMPLETE_TYPE_P(type))
4149           return -1;
4150
4151         count = aapcs_vfp_sub_candidate (TREE_TYPE (type), modep);
4152         if (count == -1
4153             || !index
4154             || !TYPE_MAX_VALUE (index)
4155             || !host_integerp (TYPE_MAX_VALUE (index), 1)
4156             || !TYPE_MIN_VALUE (index)
4157             || !host_integerp (TYPE_MIN_VALUE (index), 1)
4158             || count < 0)
4159           return -1;
4160
4161         count *= (1 + tree_low_cst (TYPE_MAX_VALUE (index), 1)
4162                       - tree_low_cst (TYPE_MIN_VALUE (index), 1));
4163
4164         /* There must be no padding.  */
4165         if (!host_integerp (TYPE_SIZE (type), 1)
4166             || (tree_low_cst (TYPE_SIZE (type), 1)
4167                 != count * GET_MODE_BITSIZE (*modep)))
4168           return -1;
4169
4170         return count;
4171       }
4172
4173     case RECORD_TYPE:
4174       {
4175         int count = 0;
4176         int sub_count;
4177         tree field;
4178
4179         /* Can't handle incomplete types.  */
4180         if (!COMPLETE_TYPE_P(type))
4181           return -1;
4182
4183         for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4184           {
4185             if (TREE_CODE (field) != FIELD_DECL)
4186               continue;
4187
4188             sub_count = aapcs_vfp_sub_candidate (TREE_TYPE (field), modep);
4189             if (sub_count < 0)
4190               return -1;
4191             count += sub_count;
4192           }
4193
4194         /* There must be no padding.  */
4195         if (!host_integerp (TYPE_SIZE (type), 1)
4196             || (tree_low_cst (TYPE_SIZE (type), 1)
4197                 != count * GET_MODE_BITSIZE (*modep)))
4198           return -1;
4199
4200         return count;
4201       }
4202
4203     case UNION_TYPE:
4204     case QUAL_UNION_TYPE:
4205       {
4206         /* These aren't very interesting except in a degenerate case.  */
4207         int count = 0;
4208         int sub_count;
4209         tree field;
4210
4211         /* Can't handle incomplete types.  */
4212         if (!COMPLETE_TYPE_P(type))
4213           return -1;
4214
4215         for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
4216           {
4217             if (TREE_CODE (field) != FIELD_DECL)
4218               continue;
4219
4220             sub_count = aapcs_vfp_sub_candidate (TREE_TYPE (field), modep);
4221             if (sub_count < 0)
4222               return -1;
4223             count = count > sub_count ? count : sub_count;
4224           }
4225
4226         /* There must be no padding.  */
4227         if (!host_integerp (TYPE_SIZE (type), 1)
4228             || (tree_low_cst (TYPE_SIZE (type), 1)
4229                 != count * GET_MODE_BITSIZE (*modep)))
4230           return -1;
4231
4232         return count;
4233       }
4234
4235     default:
4236       break;
4237     }
4238
4239   return -1;
4240 }
4241
4242 /* Return true if PCS_VARIANT should use VFP registers.  */
4243 static bool
4244 use_vfp_abi (enum arm_pcs pcs_variant, bool is_double)
4245 {
4246   if (pcs_variant == ARM_PCS_AAPCS_VFP)
4247     {
4248       static bool seen_thumb1_vfp = false;
4249
4250       if (TARGET_THUMB1 && !seen_thumb1_vfp)
4251         {
4252           sorry ("Thumb-1 hard-float VFP ABI");
4253           /* sorry() is not immediately fatal, so only display this once.  */
4254           seen_thumb1_vfp = true;
4255         }
4256
4257       return true;
4258     }
4259
4260   if (pcs_variant != ARM_PCS_AAPCS_LOCAL)
4261     return false;
4262
4263   return (TARGET_32BIT && TARGET_VFP && TARGET_HARD_FLOAT &&
4264           (TARGET_VFP_DOUBLE || !is_double));
4265 }
4266
4267 static bool
4268 aapcs_vfp_is_call_or_return_candidate (enum arm_pcs pcs_variant,
4269                                        enum machine_mode mode, const_tree type,
4270                                        enum machine_mode *base_mode, int *count)
4271 {
4272   enum machine_mode new_mode = VOIDmode;
4273
4274   if (GET_MODE_CLASS (mode) == MODE_FLOAT
4275       || GET_MODE_CLASS (mode) == MODE_VECTOR_INT
4276       || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
4277     {
4278       *count = 1;
4279       new_mode = mode;
4280     }
4281   else if (GET_MODE_CLASS (mode) == MODE_COMPLEX_FLOAT)
4282     {
4283       *count = 2;
4284       new_mode = (mode == DCmode ? DFmode : SFmode);
4285     }
4286   else if (type && (mode == BLKmode || TREE_CODE (type) == VECTOR_TYPE))
4287     {
4288       int ag_count = aapcs_vfp_sub_candidate (type, &new_mode);
4289
4290       if (ag_count > 0 && ag_count <= 4)
4291         *count = ag_count;
4292       else
4293         return false;
4294     }
4295   else
4296     return false;
4297
4298
4299   if (!use_vfp_abi (pcs_variant, ARM_NUM_REGS (new_mode) > 1))
4300     return false;
4301
4302   *base_mode = new_mode;
4303   return true;
4304 }
4305
4306 static bool
4307 aapcs_vfp_is_return_candidate (enum arm_pcs pcs_variant,
4308                                enum machine_mode mode, const_tree type)
4309 {
4310   int count ATTRIBUTE_UNUSED;
4311   enum machine_mode ag_mode ATTRIBUTE_UNUSED;
4312
4313   if (!use_vfp_abi (pcs_variant, false))
4314     return false;
4315   return aapcs_vfp_is_call_or_return_candidate (pcs_variant, mode, type,
4316                                                 &ag_mode, &count);
4317 }
4318
4319 static bool
4320 aapcs_vfp_is_call_candidate (CUMULATIVE_ARGS *pcum, enum machine_mode mode,
4321                              const_tree type)
4322 {
4323   if (!use_vfp_abi (pcum->pcs_variant, false))
4324     return false;
4325
4326   return aapcs_vfp_is_call_or_return_candidate (pcum->pcs_variant, mode, type,
4327                                                 &pcum->aapcs_vfp_rmode,
4328                                                 &pcum->aapcs_vfp_rcount);
4329 }
4330
4331 static bool
4332 aapcs_vfp_allocate (CUMULATIVE_ARGS *pcum, enum machine_mode mode,
4333                     const_tree type  ATTRIBUTE_UNUSED)
4334 {
4335   int shift = GET_MODE_SIZE (pcum->aapcs_vfp_rmode) / GET_MODE_SIZE (SFmode);
4336   unsigned mask = (1 << (shift * pcum->aapcs_vfp_rcount)) - 1;
4337   int regno;
4338
4339   for (regno = 0; regno < NUM_VFP_ARG_REGS; regno += shift)
4340     if (((pcum->aapcs_vfp_regs_free >> regno) & mask) == mask)
4341       {
4342         pcum->aapcs_vfp_reg_alloc = mask << regno;
4343         if (mode == BLKmode || (mode == TImode && !TARGET_NEON))
4344           {
4345             int i;
4346             int rcount = pcum->aapcs_vfp_rcount;
4347             int rshift = shift;
4348             enum machine_mode rmode = pcum->aapcs_vfp_rmode;
4349             rtx par;
4350             if (!TARGET_NEON)
4351               {
4352                 /* Avoid using unsupported vector modes.  */
4353                 if (rmode == V2SImode)
4354                   rmode = DImode;
4355                 else if (rmode == V4SImode)
4356                   {
4357                     rmode = DImode;
4358                     rcount *= 2;
4359                     rshift /= 2;
4360                   }
4361               }
4362             par = gen_rtx_PARALLEL (mode, rtvec_alloc (rcount));
4363             for (i = 0; i < rcount; i++)
4364               {
4365                 rtx tmp = gen_rtx_REG (rmode,
4366                                        FIRST_VFP_REGNUM + regno + i * rshift);
4367                 tmp = gen_rtx_EXPR_LIST
4368                   (VOIDmode, tmp,
4369                    GEN_INT (i * GET_MODE_SIZE (rmode)));
4370                 XVECEXP (par, 0, i) = tmp;
4371               }
4372
4373             pcum->aapcs_reg = par;
4374           }
4375         else
4376           pcum->aapcs_reg = gen_rtx_REG (mode, FIRST_VFP_REGNUM + regno);
4377         return true;
4378       }
4379   return false;
4380 }
4381
4382 static rtx
4383 aapcs_vfp_allocate_return_reg (enum arm_pcs pcs_variant ATTRIBUTE_UNUSED,
4384                                enum machine_mode mode,
4385                                const_tree type ATTRIBUTE_UNUSED)
4386 {
4387   if (!use_vfp_abi (pcs_variant, false))
4388     return NULL;
4389
4390   if (mode == BLKmode || (mode == TImode && !TARGET_NEON))
4391     {
4392       int count;
4393       enum machine_mode ag_mode;
4394       int i;
4395       rtx par;
4396       int shift;
4397
4398       aapcs_vfp_is_call_or_return_candidate (pcs_variant, mode, type,
4399                                              &ag_mode, &count);
4400
4401       if (!TARGET_NEON)
4402         {
4403           if (ag_mode == V2SImode)
4404             ag_mode = DImode;
4405           else if (ag_mode == V4SImode)
4406             {
4407               ag_mode = DImode;
4408               count *= 2;
4409             }
4410         }
4411       shift = GET_MODE_SIZE(ag_mode) / GET_MODE_SIZE(SFmode);
4412       par = gen_rtx_PARALLEL (mode, rtvec_alloc (count));
4413       for (i = 0; i < count; i++)
4414         {
4415           rtx tmp = gen_rtx_REG (ag_mode, FIRST_VFP_REGNUM + i * shift);
4416           tmp = gen_rtx_EXPR_LIST (VOIDmode, tmp,
4417                                    GEN_INT (i * GET_MODE_SIZE (ag_mode)));
4418           XVECEXP (par, 0, i) = tmp;
4419         }
4420
4421       return par;
4422     }
4423
4424   return gen_rtx_REG (mode, FIRST_VFP_REGNUM);
4425 }
4426
4427 static void
4428 aapcs_vfp_advance (CUMULATIVE_ARGS *pcum  ATTRIBUTE_UNUSED,
4429                    enum machine_mode mode  ATTRIBUTE_UNUSED,
4430                    const_tree type  ATTRIBUTE_UNUSED)
4431 {
4432   pcum->aapcs_vfp_regs_free &= ~pcum->aapcs_vfp_reg_alloc;
4433   pcum->aapcs_vfp_reg_alloc = 0;
4434   return;
4435 }
4436
4437 #define AAPCS_CP(X)                             \
4438   {                                             \
4439     aapcs_ ## X ## _cum_init,                   \
4440     aapcs_ ## X ## _is_call_candidate,          \
4441     aapcs_ ## X ## _allocate,                   \
4442     aapcs_ ## X ## _is_return_candidate,        \
4443     aapcs_ ## X ## _allocate_return_reg,        \
4444     aapcs_ ## X ## _advance                     \
4445   }
4446
4447 /* Table of co-processors that can be used to pass arguments in
4448    registers.  Idealy no arugment should be a candidate for more than
4449    one co-processor table entry, but the table is processed in order
4450    and stops after the first match.  If that entry then fails to put
4451    the argument into a co-processor register, the argument will go on
4452    the stack.  */
4453 static struct
4454 {
4455   /* Initialize co-processor related state in CUMULATIVE_ARGS structure.  */
4456   void (*cum_init) (CUMULATIVE_ARGS *, const_tree, rtx, const_tree);
4457
4458   /* Return true if an argument of mode MODE (or type TYPE if MODE is
4459      BLKmode) is a candidate for this co-processor's registers; this
4460      function should ignore any position-dependent state in
4461      CUMULATIVE_ARGS and only use call-type dependent information.  */
4462   bool (*is_call_candidate) (CUMULATIVE_ARGS *, enum machine_mode, const_tree);
4463
4464   /* Return true if the argument does get a co-processor register; it
4465      should set aapcs_reg to an RTX of the register allocated as is
4466      required for a return from FUNCTION_ARG.  */
4467   bool (*allocate) (CUMULATIVE_ARGS *, enum machine_mode, const_tree);
4468
4469   /* Return true if a result of mode MODE (or type TYPE if MODE is
4470      BLKmode) is can be returned in this co-processor's registers.  */
4471   bool (*is_return_candidate) (enum arm_pcs, enum machine_mode, const_tree);
4472
4473   /* Allocate and return an RTX element to hold the return type of a
4474      call, this routine must not fail and will only be called if
4475      is_return_candidate returned true with the same parameters.  */
4476   rtx (*allocate_return_reg) (enum arm_pcs, enum machine_mode, const_tree);
4477
4478   /* Finish processing this argument and prepare to start processing
4479      the next one.  */
4480   void (*advance) (CUMULATIVE_ARGS *, enum machine_mode, const_tree);
4481 } aapcs_cp_arg_layout[ARM_NUM_COPROC_SLOTS] =
4482   {
4483     AAPCS_CP(vfp)
4484   };
4485
4486 #undef AAPCS_CP
4487
4488 static int
4489 aapcs_select_call_coproc (CUMULATIVE_ARGS *pcum, enum machine_mode mode,
4490                           const_tree type)
4491 {
4492   int i;
4493
4494   for (i = 0; i < ARM_NUM_COPROC_SLOTS; i++)
4495     if (aapcs_cp_arg_layout[i].is_call_candidate (pcum, mode, type))
4496       return i;
4497
4498   return -1;
4499 }
4500
4501 static int
4502 aapcs_select_return_coproc (const_tree type, const_tree fntype)
4503 {
4504   /* We aren't passed a decl, so we can't check that a call is local.
4505      However, it isn't clear that that would be a win anyway, since it
4506      might limit some tail-calling opportunities.  */
4507   enum arm_pcs pcs_variant;
4508
4509   if (fntype)
4510     {
4511       const_tree fndecl = NULL_TREE;
4512
4513       if (TREE_CODE (fntype) == FUNCTION_DECL)
4514         {
4515           fndecl = fntype;
4516           fntype = TREE_TYPE (fntype);
4517         }
4518
4519       pcs_variant = arm_get_pcs_model (fntype, fndecl);
4520     }
4521   else
4522     pcs_variant = arm_pcs_default;
4523
4524   if (pcs_variant != ARM_PCS_AAPCS)
4525     {
4526       int i;
4527
4528       for (i = 0; i < ARM_NUM_COPROC_SLOTS; i++)
4529         if (aapcs_cp_arg_layout[i].is_return_candidate (pcs_variant,
4530                                                         TYPE_MODE (type),
4531                                                         type))
4532           return i;
4533     }
4534   return -1;
4535 }
4536
4537 static rtx
4538 aapcs_allocate_return_reg (enum machine_mode mode, const_tree type,
4539                            const_tree fntype)
4540 {
4541   /* We aren't passed a decl, so we can't check that a call is local.
4542      However, it isn't clear that that would be a win anyway, since it
4543      might limit some tail-calling opportunities.  */
4544   enum arm_pcs pcs_variant;
4545   int unsignedp ATTRIBUTE_UNUSED;
4546
4547   if (fntype)
4548     {
4549       const_tree fndecl = NULL_TREE;
4550
4551       if (TREE_CODE (fntype) == FUNCTION_DECL)
4552         {
4553           fndecl = fntype;
4554           fntype = TREE_TYPE (fntype);
4555         }
4556
4557       pcs_variant = arm_get_pcs_model (fntype, fndecl);
4558     }
4559   else
4560     pcs_variant = arm_pcs_default;
4561
4562   /* Promote integer types.  */
4563   if (type && INTEGRAL_TYPE_P (type))
4564     mode = arm_promote_function_mode (type, mode, &unsignedp, fntype, 1);
4565
4566   if (pcs_variant != ARM_PCS_AAPCS)
4567     {
4568       int i;
4569
4570       for (i = 0; i < ARM_NUM_COPROC_SLOTS; i++)
4571         if (aapcs_cp_arg_layout[i].is_return_candidate (pcs_variant, mode,
4572                                                         type))
4573           return aapcs_cp_arg_layout[i].allocate_return_reg (pcs_variant,
4574                                                              mode, type);
4575     }
4576
4577   /* Promotes small structs returned in a register to full-word size
4578      for big-endian AAPCS.  */
4579   if (type && arm_return_in_msb (type))
4580     {
4581       HOST_WIDE_INT size = int_size_in_bytes (type);
4582       if (size % UNITS_PER_WORD != 0)
4583         {
4584           size += UNITS_PER_WORD - size % UNITS_PER_WORD;
4585           mode = mode_for_size (size * BITS_PER_UNIT, MODE_INT, 0);
4586         }
4587     }
4588
4589   return gen_rtx_REG (mode, R0_REGNUM);
4590 }
4591
4592 static rtx
4593 aapcs_libcall_value (enum machine_mode mode)
4594 {
4595   if (BYTES_BIG_ENDIAN && ALL_FIXED_POINT_MODE_P (mode)
4596       && GET_MODE_SIZE (mode) <= 4)
4597     mode = SImode;
4598
4599   return aapcs_allocate_return_reg (mode, NULL_TREE, NULL_TREE);
4600 }
4601
4602 /* Lay out a function argument using the AAPCS rules.  The rule
4603    numbers referred to here are those in the AAPCS.  */
4604 static void
4605 aapcs_layout_arg (CUMULATIVE_ARGS *pcum, enum machine_mode mode,
4606                   const_tree type, bool named)
4607 {
4608   int nregs, nregs2;
4609   int ncrn;
4610
4611   /* We only need to do this once per argument.  */
4612   if (pcum->aapcs_arg_processed)
4613     return;
4614
4615   pcum->aapcs_arg_processed = true;
4616
4617   /* Special case: if named is false then we are handling an incoming
4618      anonymous argument which is on the stack.  */
4619   if (!named)
4620     return;
4621
4622   /* Is this a potential co-processor register candidate?  */
4623   if (pcum->pcs_variant != ARM_PCS_AAPCS)
4624     {
4625       int slot = aapcs_select_call_coproc (pcum, mode, type);
4626       pcum->aapcs_cprc_slot = slot;
4627
4628       /* We don't have to apply any of the rules from part B of the
4629          preparation phase, these are handled elsewhere in the
4630          compiler.  */
4631
4632       if (slot >= 0)
4633         {
4634           /* A Co-processor register candidate goes either in its own
4635              class of registers or on the stack.  */
4636           if (!pcum->aapcs_cprc_failed[slot])
4637             {
4638               /* C1.cp - Try to allocate the argument to co-processor
4639                  registers.  */
4640               if (aapcs_cp_arg_layout[slot].allocate (pcum, mode, type))
4641                 return;
4642
4643               /* C2.cp - Put the argument on the stack and note that we
4644                  can't assign any more candidates in this slot.  We also
4645                  need to note that we have allocated stack space, so that
4646                  we won't later try to split a non-cprc candidate between
4647                  core registers and the stack.  */
4648               pcum->aapcs_cprc_failed[slot] = true;
4649               pcum->can_split = false;
4650             }
4651
4652           /* We didn't get a register, so this argument goes on the
4653              stack.  */
4654           gcc_assert (pcum->can_split == false);
4655           return;
4656         }
4657     }
4658
4659   /* C3 - For double-word aligned arguments, round the NCRN up to the
4660      next even number.  */
4661   ncrn = pcum->aapcs_ncrn;
4662   if ((ncrn & 1) && arm_needs_doubleword_align (mode, type))
4663     ncrn++;
4664
4665   nregs = ARM_NUM_REGS2(mode, type);
4666
4667   /* Sigh, this test should really assert that nregs > 0, but a GCC
4668      extension allows empty structs and then gives them empty size; it
4669      then allows such a structure to be passed by value.  For some of
4670      the code below we have to pretend that such an argument has
4671      non-zero size so that we 'locate' it correctly either in
4672      registers or on the stack.  */
4673   gcc_assert (nregs >= 0);
4674
4675   nregs2 = nregs ? nregs : 1;
4676
4677   /* C4 - Argument fits entirely in core registers.  */
4678   if (ncrn + nregs2 <= NUM_ARG_REGS)
4679     {
4680       pcum->aapcs_reg = gen_rtx_REG (mode, ncrn);
4681       pcum->aapcs_next_ncrn = ncrn + nregs;
4682       return;
4683     }
4684
4685   /* C5 - Some core registers left and there are no arguments already
4686      on the stack: split this argument between the remaining core
4687      registers and the stack.  */
4688   if (ncrn < NUM_ARG_REGS && pcum->can_split)
4689     {
4690       pcum->aapcs_reg = gen_rtx_REG (mode, ncrn);
4691       pcum->aapcs_next_ncrn = NUM_ARG_REGS;
4692       pcum->aapcs_partial = (NUM_ARG_REGS - ncrn) * UNITS_PER_WORD;
4693       return;
4694     }
4695
4696   /* C6 - NCRN is set to 4.  */
4697   pcum->aapcs_next_ncrn = NUM_ARG_REGS;
4698
4699   /* C7,C8 - arugment goes on the stack.  We have nothing to do here.  */
4700   return;
4701 }
4702
4703 /* Initialize a variable CUM of type CUMULATIVE_ARGS
4704    for a call to a function whose data type is FNTYPE.
4705    For a library call, FNTYPE is NULL.  */
4706 void
4707 arm_init_cumulative_args (CUMULATIVE_ARGS *pcum, tree fntype,
4708                           rtx libname,
4709                           tree fndecl ATTRIBUTE_UNUSED)
4710 {
4711   /* Long call handling.  */
4712   if (fntype)
4713     pcum->pcs_variant = arm_get_pcs_model (fntype, fndecl);
4714   else
4715     pcum->pcs_variant = arm_pcs_default;
4716
4717   if (pcum->pcs_variant <= ARM_PCS_AAPCS_LOCAL)
4718     {
4719       if (arm_libcall_uses_aapcs_base (libname))
4720         pcum->pcs_variant = ARM_PCS_AAPCS;
4721
4722       pcum->aapcs_ncrn = pcum->aapcs_next_ncrn = 0;
4723       pcum->aapcs_reg = NULL_RTX;
4724       pcum->aapcs_partial = 0;
4725       pcum->aapcs_arg_processed = false;
4726       pcum->aapcs_cprc_slot = -1;
4727       pcum->can_split = true;
4728
4729       if (pcum->pcs_variant != ARM_PCS_AAPCS)
4730         {
4731           int i;
4732
4733           for (i = 0; i < ARM_NUM_COPROC_SLOTS; i++)
4734             {
4735               pcum->aapcs_cprc_failed[i] = false;
4736               aapcs_cp_arg_layout[i].cum_init (pcum, fntype, libname, fndecl);
4737             }
4738         }
4739       return;
4740     }
4741
4742   /* Legacy ABIs */
4743
4744   /* On the ARM, the offset starts at 0.  */
4745   pcum->nregs = 0;
4746   pcum->iwmmxt_nregs = 0;
4747   pcum->can_split = true;
4748
4749   /* Varargs vectors are treated the same as long long.
4750      named_count avoids having to change the way arm handles 'named' */
4751   pcum->named_count = 0;
4752   pcum->nargs = 0;
4753
4754   if (TARGET_REALLY_IWMMXT && fntype)
4755     {
4756       tree fn_arg;
4757
4758       for (fn_arg = TYPE_ARG_TYPES (fntype);
4759            fn_arg;
4760            fn_arg = TREE_CHAIN (fn_arg))
4761         pcum->named_count += 1;
4762
4763       if (! pcum->named_count)
4764         pcum->named_count = INT_MAX;
4765     }
4766 }
4767
4768
4769 /* Return true if mode/type need doubleword alignment.  */
4770 static bool
4771 arm_needs_doubleword_align (enum machine_mode mode, const_tree type)
4772 {
4773   return (GET_MODE_ALIGNMENT (mode) > PARM_BOUNDARY
4774           || (type && TYPE_ALIGN (type) > PARM_BOUNDARY));
4775 }
4776
4777
4778 /* Determine where to put an argument to a function.
4779    Value is zero to push the argument on the stack,
4780    or a hard register in which to store the argument.
4781
4782    MODE is the argument's machine mode.
4783    TYPE is the data type of the argument (as a tree).
4784     This is null for libcalls where that information may
4785     not be available.
4786    CUM is a variable of type CUMULATIVE_ARGS which gives info about
4787     the preceding args and about the function being called.
4788    NAMED is nonzero if this argument is a named parameter
4789     (otherwise it is an extra parameter matching an ellipsis).
4790
4791    On the ARM, normally the first 16 bytes are passed in registers r0-r3; all
4792    other arguments are passed on the stack.  If (NAMED == 0) (which happens
4793    only in assign_parms, since TARGET_SETUP_INCOMING_VARARGS is
4794    defined), say it is passed in the stack (function_prologue will
4795    indeed make it pass in the stack if necessary).  */
4796
4797 static rtx
4798 arm_function_arg (cumulative_args_t pcum_v, enum machine_mode mode,
4799                   const_tree type, bool named)
4800 {
4801   CUMULATIVE_ARGS *pcum = get_cumulative_args (pcum_v);
4802   int nregs;
4803
4804   /* Handle the special case quickly.  Pick an arbitrary value for op2 of
4805      a call insn (op3 of a call_value insn).  */
4806   if (mode == VOIDmode)
4807     return const0_rtx;
4808
4809   if (pcum->pcs_variant <= ARM_PCS_AAPCS_LOCAL)
4810     {
4811       aapcs_layout_arg (pcum, mode, type, named);
4812       return pcum->aapcs_reg;
4813     }
4814
4815   /* Varargs vectors are treated the same as long long.
4816      named_count avoids having to change the way arm handles 'named' */
4817   if (TARGET_IWMMXT_ABI
4818       && arm_vector_mode_supported_p (mode)
4819       && pcum->named_count > pcum->nargs + 1)
4820     {
4821       if (pcum->iwmmxt_nregs <= 9)
4822         return gen_rtx_REG (mode, pcum->iwmmxt_nregs + FIRST_IWMMXT_REGNUM);
4823       else
4824         {
4825           pcum->can_split = false;
4826           return NULL_RTX;
4827         }
4828     }
4829
4830   /* Put doubleword aligned quantities in even register pairs.  */
4831   if (pcum->nregs & 1
4832       && ARM_DOUBLEWORD_ALIGN
4833       && arm_needs_doubleword_align (mode, type))
4834     pcum->nregs++;
4835
4836   /* Only allow splitting an arg between regs and memory if all preceding
4837      args were allocated to regs.  For args passed by reference we only count
4838      the reference pointer.  */
4839   if (pcum->can_split)
4840     nregs = 1;
4841   else
4842     nregs = ARM_NUM_REGS2 (mode, type);
4843
4844   if (!named || pcum->nregs + nregs > NUM_ARG_REGS)
4845     return NULL_RTX;
4846
4847   return gen_rtx_REG (mode, pcum->nregs);
4848 }
4849
4850 static unsigned int
4851 arm_function_arg_boundary (enum machine_mode mode, const_tree type)
4852 {
4853   return (ARM_DOUBLEWORD_ALIGN && arm_needs_doubleword_align (mode, type)
4854           ? DOUBLEWORD_ALIGNMENT
4855           : PARM_BOUNDARY);
4856 }
4857
4858 static int
4859 arm_arg_partial_bytes (cumulative_args_t pcum_v, enum machine_mode mode,
4860                        tree type, bool named)
4861 {
4862   CUMULATIVE_ARGS *pcum = get_cumulative_args (pcum_v);
4863   int nregs = pcum->nregs;
4864
4865   if (pcum->pcs_variant <= ARM_PCS_AAPCS_LOCAL)
4866     {
4867       aapcs_layout_arg (pcum, mode, type, named);
4868       return pcum->aapcs_partial;
4869     }
4870
4871   if (TARGET_IWMMXT_ABI && arm_vector_mode_supported_p (mode))
4872     return 0;
4873
4874   if (NUM_ARG_REGS > nregs
4875       && (NUM_ARG_REGS < nregs + ARM_NUM_REGS2 (mode, type))
4876       && pcum->can_split)
4877     return (NUM_ARG_REGS - nregs) * UNITS_PER_WORD;
4878
4879   return 0;
4880 }
4881
4882 /* Update the data in PCUM to advance over an argument
4883    of mode MODE and data type TYPE.
4884    (TYPE is null for libcalls where that information may not be available.)  */
4885
4886 static void
4887 arm_function_arg_advance (cumulative_args_t pcum_v, enum machine_mode mode,
4888                           const_tree type, bool named)
4889 {
4890   CUMULATIVE_ARGS *pcum = get_cumulative_args (pcum_v);
4891
4892   if (pcum->pcs_variant <= ARM_PCS_AAPCS_LOCAL)
4893     {
4894       aapcs_layout_arg (pcum, mode, type, named);
4895
4896       if (pcum->aapcs_cprc_slot >= 0)
4897         {
4898           aapcs_cp_arg_layout[pcum->aapcs_cprc_slot].advance (pcum, mode,
4899                                                               type);
4900           pcum->aapcs_cprc_slot = -1;
4901         }
4902
4903       /* Generic stuff.  */
4904       pcum->aapcs_arg_processed = false;
4905       pcum->aapcs_ncrn = pcum->aapcs_next_ncrn;
4906       pcum->aapcs_reg = NULL_RTX;
4907       pcum->aapcs_partial = 0;
4908     }
4909   else
4910     {
4911       pcum->nargs += 1;
4912       if (arm_vector_mode_supported_p (mode)
4913           && pcum->named_count > pcum->nargs
4914           && TARGET_IWMMXT_ABI)
4915         pcum->iwmmxt_nregs += 1;
4916       else
4917         pcum->nregs += ARM_NUM_REGS2 (mode, type);
4918     }
4919 }
4920
4921 /* Variable sized types are passed by reference.  This is a GCC
4922    extension to the ARM ABI.  */
4923
4924 static bool
4925 arm_pass_by_reference (cumulative_args_t cum ATTRIBUTE_UNUSED,
4926                        enum machine_mode mode ATTRIBUTE_UNUSED,
4927                        const_tree type, bool named ATTRIBUTE_UNUSED)
4928 {
4929   return type && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST;
4930 }
4931 \f
4932 /* Encode the current state of the #pragma [no_]long_calls.  */
4933 typedef enum
4934 {
4935   OFF,          /* No #pragma [no_]long_calls is in effect.  */
4936   LONG,         /* #pragma long_calls is in effect.  */
4937   SHORT         /* #pragma no_long_calls is in effect.  */
4938 } arm_pragma_enum;
4939
4940 static arm_pragma_enum arm_pragma_long_calls = OFF;
4941
4942 void
4943 arm_pr_long_calls (struct cpp_reader * pfile ATTRIBUTE_UNUSED)
4944 {
4945   arm_pragma_long_calls = LONG;
4946 }
4947
4948 void
4949 arm_pr_no_long_calls (struct cpp_reader * pfile ATTRIBUTE_UNUSED)
4950 {
4951   arm_pragma_long_calls = SHORT;
4952 }
4953
4954 void
4955 arm_pr_long_calls_off (struct cpp_reader * pfile ATTRIBUTE_UNUSED)
4956 {
4957   arm_pragma_long_calls = OFF;
4958 }
4959 \f
4960 /* Handle an attribute requiring a FUNCTION_DECL;
4961    arguments as in struct attribute_spec.handler.  */
4962 static tree
4963 arm_handle_fndecl_attribute (tree *node, tree name, tree args ATTRIBUTE_UNUSED,
4964                              int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
4965 {
4966   if (TREE_CODE (*node) != FUNCTION_DECL)
4967     {
4968       warning (OPT_Wattributes, "%qE attribute only applies to functions",
4969                name);
4970       *no_add_attrs = true;
4971     }
4972
4973   return NULL_TREE;
4974 }
4975
4976 /* Handle an "interrupt" or "isr" attribute;
4977    arguments as in struct attribute_spec.handler.  */
4978 static tree
4979 arm_handle_isr_attribute (tree *node, tree name, tree args, int flags,
4980                           bool *no_add_attrs)
4981 {
4982   if (DECL_P (*node))
4983     {
4984       if (TREE_CODE (*node) != FUNCTION_DECL)
4985         {
4986           warning (OPT_Wattributes, "%qE attribute only applies to functions",
4987                    name);
4988           *no_add_attrs = true;
4989         }
4990       /* FIXME: the argument if any is checked for type attributes;
4991          should it be checked for decl ones?  */
4992     }
4993   else
4994     {
4995       if (TREE_CODE (*node) == FUNCTION_TYPE
4996           || TREE_CODE (*node) == METHOD_TYPE)
4997         {
4998           if (arm_isr_value (args) == ARM_FT_UNKNOWN)
4999             {
5000               warning (OPT_Wattributes, "%qE attribute ignored",
5001                        name);
5002               *no_add_attrs = true;
5003             }
5004         }
5005       else if (TREE_CODE (*node) == POINTER_TYPE
5006                && (TREE_CODE (TREE_TYPE (*node)) == FUNCTION_TYPE
5007                    || TREE_CODE (TREE_TYPE (*node)) == METHOD_TYPE)
5008                && arm_isr_value (args) != ARM_FT_UNKNOWN)
5009         {
5010           *node = build_variant_type_copy (*node);
5011           TREE_TYPE (*node) = build_type_attribute_variant
5012             (TREE_TYPE (*node),
5013              tree_cons (name, args, TYPE_ATTRIBUTES (TREE_TYPE (*node))));
5014           *no_add_attrs = true;
5015         }
5016       else
5017         {
5018           /* Possibly pass this attribute on from the type to a decl.  */
5019           if (flags & ((int) ATTR_FLAG_DECL_NEXT
5020                        | (int) ATTR_FLAG_FUNCTION_NEXT
5021                        | (int) ATTR_FLAG_ARRAY_NEXT))
5022             {
5023               *no_add_attrs = true;
5024               return tree_cons (name, args, NULL_TREE);
5025             }
5026           else
5027             {
5028               warning (OPT_Wattributes, "%qE attribute ignored",
5029                        name);
5030             }
5031         }
5032     }
5033
5034   return NULL_TREE;
5035 }
5036
5037 /* Handle a "pcs" attribute; arguments as in struct
5038    attribute_spec.handler.  */
5039 static tree
5040 arm_handle_pcs_attribute (tree *node ATTRIBUTE_UNUSED, tree name, tree args,
5041                           int flags ATTRIBUTE_UNUSED, bool *no_add_attrs)
5042 {
5043   if (arm_pcs_from_attribute (args) == ARM_PCS_UNKNOWN)
5044     {
5045       warning (OPT_Wattributes, "%qE attribute ignored", name);
5046       *no_add_attrs = true;
5047     }
5048   return NULL_TREE;
5049 }
5050
5051 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
5052 /* Handle the "notshared" attribute.  This attribute is another way of
5053    requesting hidden visibility.  ARM's compiler supports
5054    "__declspec(notshared)"; we support the same thing via an
5055    attribute.  */
5056
5057 static tree
5058 arm_handle_notshared_attribute (tree *node,
5059                                 tree name ATTRIBUTE_UNUSED,
5060                                 tree args ATTRIBUTE_UNUSED,
5061                                 int flags ATTRIBUTE_UNUSED,
5062                                 bool *no_add_attrs)
5063 {
5064   tree decl = TYPE_NAME (*node);
5065
5066   if (decl)
5067     {
5068       DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
5069       DECL_VISIBILITY_SPECIFIED (decl) = 1;
5070       *no_add_attrs = false;
5071     }
5072   return NULL_TREE;
5073 }
5074 #endif
5075
5076 /* Return 0 if the attributes for two types are incompatible, 1 if they
5077    are compatible, and 2 if they are nearly compatible (which causes a
5078    warning to be generated).  */
5079 static int
5080 arm_comp_type_attributes (const_tree type1, const_tree type2)
5081 {
5082   int l1, l2, s1, s2;
5083
5084   /* Check for mismatch of non-default calling convention.  */
5085   if (TREE_CODE (type1) != FUNCTION_TYPE)
5086     return 1;
5087
5088   /* Check for mismatched call attributes.  */
5089   l1 = lookup_attribute ("long_call", TYPE_ATTRIBUTES (type1)) != NULL;
5090   l2 = lookup_attribute ("long_call", TYPE_ATTRIBUTES (type2)) != NULL;
5091   s1 = lookup_attribute ("short_call", TYPE_ATTRIBUTES (type1)) != NULL;
5092   s2 = lookup_attribute ("short_call", TYPE_ATTRIBUTES (type2)) != NULL;
5093
5094   /* Only bother to check if an attribute is defined.  */
5095   if (l1 | l2 | s1 | s2)
5096     {
5097       /* If one type has an attribute, the other must have the same attribute.  */
5098       if ((l1 != l2) || (s1 != s2))
5099         return 0;
5100
5101       /* Disallow mixed attributes.  */
5102       if ((l1 & s2) || (l2 & s1))
5103         return 0;
5104     }
5105
5106   /* Check for mismatched ISR attribute.  */
5107   l1 = lookup_attribute ("isr", TYPE_ATTRIBUTES (type1)) != NULL;
5108   if (! l1)
5109     l1 = lookup_attribute ("interrupt", TYPE_ATTRIBUTES (type1)) != NULL;
5110   l2 = lookup_attribute ("isr", TYPE_ATTRIBUTES (type2)) != NULL;
5111   if (! l2)
5112     l1 = lookup_attribute ("interrupt", TYPE_ATTRIBUTES (type2)) != NULL;
5113   if (l1 != l2)
5114     return 0;
5115
5116   return 1;
5117 }
5118
5119 /*  Assigns default attributes to newly defined type.  This is used to
5120     set short_call/long_call attributes for function types of
5121     functions defined inside corresponding #pragma scopes.  */
5122 static void
5123 arm_set_default_type_attributes (tree type)
5124 {
5125   /* Add __attribute__ ((long_call)) to all functions, when
5126      inside #pragma long_calls or __attribute__ ((short_call)),
5127      when inside #pragma no_long_calls.  */
5128   if (TREE_CODE (type) == FUNCTION_TYPE || TREE_CODE (type) == METHOD_TYPE)
5129     {
5130       tree type_attr_list, attr_name;
5131       type_attr_list = TYPE_ATTRIBUTES (type);
5132
5133       if (arm_pragma_long_calls == LONG)
5134         attr_name = get_identifier ("long_call");
5135       else if (arm_pragma_long_calls == SHORT)
5136         attr_name = get_identifier ("short_call");
5137       else
5138         return;
5139
5140       type_attr_list = tree_cons (attr_name, NULL_TREE, type_attr_list);
5141       TYPE_ATTRIBUTES (type) = type_attr_list;
5142     }
5143 }
5144 \f
5145 /* Return true if DECL is known to be linked into section SECTION.  */
5146
5147 static bool
5148 arm_function_in_section_p (tree decl, section *section)
5149 {
5150   /* We can only be certain about functions defined in the same
5151      compilation unit.  */
5152   if (!TREE_STATIC (decl))
5153     return false;
5154
5155   /* Make sure that SYMBOL always binds to the definition in this
5156      compilation unit.  */
5157   if (!targetm.binds_local_p (decl))
5158     return false;
5159
5160   /* If DECL_SECTION_NAME is set, assume it is trustworthy.  */
5161   if (!DECL_SECTION_NAME (decl))
5162     {
5163       /* Make sure that we will not create a unique section for DECL.  */
5164       if (flag_function_sections || DECL_ONE_ONLY (decl))
5165         return false;
5166     }
5167
5168   return function_section (decl) == section;
5169 }
5170
5171 /* Return nonzero if a 32-bit "long_call" should be generated for
5172    a call from the current function to DECL.  We generate a long_call
5173    if the function:
5174
5175         a.  has an __attribute__((long call))
5176      or b.  is within the scope of a #pragma long_calls
5177      or c.  the -mlong-calls command line switch has been specified
5178
5179    However we do not generate a long call if the function:
5180
5181         d.  has an __attribute__ ((short_call))
5182      or e.  is inside the scope of a #pragma no_long_calls
5183      or f.  is defined in the same section as the current function.  */
5184
5185 bool
5186 arm_is_long_call_p (tree decl)
5187 {
5188   tree attrs;
5189
5190   if (!decl)
5191     return TARGET_LONG_CALLS;
5192
5193   attrs = TYPE_ATTRIBUTES (TREE_TYPE (decl));
5194   if (lookup_attribute ("short_call", attrs))
5195     return false;
5196
5197   /* For "f", be conservative, and only cater for cases in which the
5198      whole of the current function is placed in the same section.  */
5199   if (!flag_reorder_blocks_and_partition
5200       && TREE_CODE (decl) == FUNCTION_DECL
5201       && arm_function_in_section_p (decl, current_function_section ()))
5202     return false;
5203
5204   if (lookup_attribute ("long_call", attrs))
5205     return true;
5206
5207   return TARGET_LONG_CALLS;
5208 }
5209
5210 /* Return nonzero if it is ok to make a tail-call to DECL.  */
5211 static bool
5212 arm_function_ok_for_sibcall (tree decl, tree exp)
5213 {
5214   unsigned long func_type;
5215
5216   if (cfun->machine->sibcall_blocked)
5217     return false;
5218
5219   /* Never tailcall something for which we have no decl, or if we
5220      are generating code for Thumb-1.  */
5221   if (decl == NULL || TARGET_THUMB1)
5222     return false;
5223
5224   /* The PIC register is live on entry to VxWorks PLT entries, so we
5225      must make the call before restoring the PIC register.  */
5226   if (TARGET_VXWORKS_RTP && flag_pic && !targetm.binds_local_p (decl))
5227     return false;
5228
5229   /* Cannot tail-call to long calls, since these are out of range of
5230      a branch instruction.  */
5231   if (arm_is_long_call_p (decl))
5232     return false;
5233
5234   /* If we are interworking and the function is not declared static
5235      then we can't tail-call it unless we know that it exists in this
5236      compilation unit (since it might be a Thumb routine).  */
5237   if (TARGET_INTERWORK && TREE_PUBLIC (decl) && !TREE_ASM_WRITTEN (decl))
5238     return false;
5239
5240   func_type = arm_current_func_type ();
5241   /* Never tailcall from an ISR routine - it needs a special exit sequence.  */
5242   if (IS_INTERRUPT (func_type))
5243     return false;
5244
5245   if (!VOID_TYPE_P (TREE_TYPE (DECL_RESULT (cfun->decl))))
5246     {
5247       /* Check that the return value locations are the same.  For
5248          example that we aren't returning a value from the sibling in
5249          a VFP register but then need to transfer it to a core
5250          register.  */
5251       rtx a, b;
5252
5253       a = arm_function_value (TREE_TYPE (exp), decl, false);
5254       b = arm_function_value (TREE_TYPE (DECL_RESULT (cfun->decl)),
5255                               cfun->decl, false);
5256       if (!rtx_equal_p (a, b))
5257         return false;
5258     }
5259
5260   /* Never tailcall if function may be called with a misaligned SP.  */
5261   if (IS_STACKALIGN (func_type))
5262     return false;
5263
5264   /* The AAPCS says that, on bare-metal, calls to unresolved weak
5265      references should become a NOP.  Don't convert such calls into
5266      sibling calls.  */
5267   if (TARGET_AAPCS_BASED
5268       && arm_abi == ARM_ABI_AAPCS
5269       && DECL_WEAK (decl))
5270     return false;
5271
5272   /* Everything else is ok.  */
5273   return true;
5274 }
5275
5276 \f
5277 /* Addressing mode support functions.  */
5278
5279 /* Return nonzero if X is a legitimate immediate operand when compiling
5280    for PIC.  We know that X satisfies CONSTANT_P and flag_pic is true.  */
5281 int
5282 legitimate_pic_operand_p (rtx x)
5283 {
5284   if (GET_CODE (x) == SYMBOL_REF
5285       || (GET_CODE (x) == CONST
5286           && GET_CODE (XEXP (x, 0)) == PLUS
5287           && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF))
5288     return 0;
5289
5290   return 1;
5291 }
5292
5293 /* Record that the current function needs a PIC register.  Initialize
5294    cfun->machine->pic_reg if we have not already done so.  */
5295
5296 static void
5297 require_pic_register (void)
5298 {
5299   /* A lot of the logic here is made obscure by the fact that this
5300      routine gets called as part of the rtx cost estimation process.
5301      We don't want those calls to affect any assumptions about the real
5302      function; and further, we can't call entry_of_function() until we
5303      start the real expansion process.  */
5304   if (!crtl->uses_pic_offset_table)
5305     {
5306       gcc_assert (can_create_pseudo_p ());
5307       if (arm_pic_register != INVALID_REGNUM)
5308         {
5309           if (!cfun->machine->pic_reg)
5310             cfun->machine->pic_reg = gen_rtx_REG (Pmode, arm_pic_register);
5311
5312           /* Play games to avoid marking the function as needing pic
5313              if we are being called as part of the cost-estimation
5314              process.  */
5315           if (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl)
5316             crtl->uses_pic_offset_table = 1;
5317         }
5318       else
5319         {
5320           rtx seq, insn;
5321
5322           if (!cfun->machine->pic_reg)
5323             cfun->machine->pic_reg = gen_reg_rtx (Pmode);
5324
5325           /* Play games to avoid marking the function as needing pic
5326              if we are being called as part of the cost-estimation
5327              process.  */
5328           if (current_ir_type () != IR_GIMPLE || currently_expanding_to_rtl)
5329             {
5330               crtl->uses_pic_offset_table = 1;
5331               start_sequence ();
5332
5333               arm_load_pic_register (0UL);
5334
5335               seq = get_insns ();
5336               end_sequence ();
5337
5338               for (insn = seq; insn; insn = NEXT_INSN (insn))
5339                 if (INSN_P (insn))
5340                   INSN_LOCATOR (insn) = prologue_locator;
5341
5342               /* We can be called during expansion of PHI nodes, where
5343                  we can't yet emit instructions directly in the final
5344                  insn stream.  Queue the insns on the entry edge, they will
5345                  be committed after everything else is expanded.  */
5346               insert_insn_on_edge (seq, single_succ_edge (ENTRY_BLOCK_PTR));
5347             }
5348         }
5349     }
5350 }
5351
5352 rtx
5353 legitimize_pic_address (rtx orig, enum machine_mode mode, rtx reg)
5354 {
5355   if (GET_CODE (orig) == SYMBOL_REF
5356       || GET_CODE (orig) == LABEL_REF)
5357     {
5358       rtx insn;
5359
5360       if (reg == 0)
5361         {
5362           gcc_assert (can_create_pseudo_p ());
5363           reg = gen_reg_rtx (Pmode);
5364         }
5365
5366       /* VxWorks does not impose a fixed gap between segments; the run-time
5367          gap can be different from the object-file gap.  We therefore can't
5368          use GOTOFF unless we are absolutely sure that the symbol is in the
5369          same segment as the GOT.  Unfortunately, the flexibility of linker
5370          scripts means that we can't be sure of that in general, so assume
5371          that GOTOFF is never valid on VxWorks.  */
5372       if ((GET_CODE (orig) == LABEL_REF
5373            || (GET_CODE (orig) == SYMBOL_REF &&
5374                SYMBOL_REF_LOCAL_P (orig)))
5375           && NEED_GOT_RELOC
5376           && !TARGET_VXWORKS_RTP)
5377         insn = arm_pic_static_addr (orig, reg);
5378       else
5379         {
5380           rtx pat;
5381           rtx mem;
5382
5383           /* If this function doesn't have a pic register, create one now.  */
5384           require_pic_register ();
5385
5386           pat = gen_calculate_pic_address (reg, cfun->machine->pic_reg, orig);
5387
5388           /* Make the MEM as close to a constant as possible.  */
5389           mem = SET_SRC (pat);
5390           gcc_assert (MEM_P (mem) && !MEM_VOLATILE_P (mem));
5391           MEM_READONLY_P (mem) = 1;
5392           MEM_NOTRAP_P (mem) = 1;
5393
5394           insn = emit_insn (pat);
5395         }
5396
5397       /* Put a REG_EQUAL note on this insn, so that it can be optimized
5398          by loop.  */
5399       set_unique_reg_note (insn, REG_EQUAL, orig);
5400
5401       return reg;
5402     }
5403   else if (GET_CODE (orig) == CONST)
5404     {
5405       rtx base, offset;
5406
5407       if (GET_CODE (XEXP (orig, 0)) == PLUS
5408           && XEXP (XEXP (orig, 0), 0) == cfun->machine->pic_reg)
5409         return orig;
5410
5411       /* Handle the case where we have: const (UNSPEC_TLS).  */
5412       if (GET_CODE (XEXP (orig, 0)) == UNSPEC
5413           && XINT (XEXP (orig, 0), 1) == UNSPEC_TLS)
5414         return orig;
5415
5416       /* Handle the case where we have:
5417          const (plus (UNSPEC_TLS) (ADDEND)).  The ADDEND must be a
5418          CONST_INT.  */
5419       if (GET_CODE (XEXP (orig, 0)) == PLUS
5420           && GET_CODE (XEXP (XEXP (orig, 0), 0)) == UNSPEC
5421           && XINT (XEXP (XEXP (orig, 0), 0), 1) == UNSPEC_TLS)
5422         {
5423           gcc_assert (GET_CODE (XEXP (XEXP (orig, 0), 1)) == CONST_INT);
5424           return orig;
5425         }
5426
5427       if (reg == 0)
5428         {
5429           gcc_assert (can_create_pseudo_p ());
5430           reg = gen_reg_rtx (Pmode);
5431         }
5432
5433       gcc_assert (GET_CODE (XEXP (orig, 0)) == PLUS);
5434
5435       base = legitimize_pic_address (XEXP (XEXP (orig, 0), 0), Pmode, reg);
5436       offset = legitimize_pic_address (XEXP (XEXP (orig, 0), 1), Pmode,
5437                                        base == reg ? 0 : reg);
5438
5439       if (GET_CODE (offset) == CONST_INT)
5440         {
5441           /* The base register doesn't really matter, we only want to
5442              test the index for the appropriate mode.  */
5443           if (!arm_legitimate_index_p (mode, offset, SET, 0))
5444             {
5445               gcc_assert (can_create_pseudo_p ());
5446               offset = force_reg (Pmode, offset);
5447             }
5448
5449           if (GET_CODE (offset) == CONST_INT)
5450             return plus_constant (base, INTVAL (offset));
5451         }
5452
5453       if (GET_MODE_SIZE (mode) > 4
5454           && (GET_MODE_CLASS (mode) == MODE_INT
5455               || TARGET_SOFT_FLOAT))
5456         {
5457           emit_insn (gen_addsi3 (reg, base, offset));
5458           return reg;
5459         }
5460
5461       return gen_rtx_PLUS (Pmode, base, offset);
5462     }
5463
5464   return orig;
5465 }
5466
5467
5468 /* Find a spare register to use during the prolog of a function.  */
5469
5470 static int
5471 thumb_find_work_register (unsigned long pushed_regs_mask)
5472 {
5473   int reg;
5474
5475   /* Check the argument registers first as these are call-used.  The
5476      register allocation order means that sometimes r3 might be used
5477      but earlier argument registers might not, so check them all.  */
5478   for (reg = LAST_ARG_REGNUM; reg >= 0; reg --)
5479     if (!df_regs_ever_live_p (reg))
5480       return reg;
5481
5482   /* Before going on to check the call-saved registers we can try a couple
5483      more ways of deducing that r3 is available.  The first is when we are
5484      pushing anonymous arguments onto the stack and we have less than 4
5485      registers worth of fixed arguments(*).  In this case r3 will be part of
5486      the variable argument list and so we can be sure that it will be
5487      pushed right at the start of the function.  Hence it will be available
5488      for the rest of the prologue.
5489      (*): ie crtl->args.pretend_args_size is greater than 0.  */
5490   if (cfun->machine->uses_anonymous_args
5491       && crtl->args.pretend_args_size > 0)
5492     return LAST_ARG_REGNUM;
5493
5494   /* The other case is when we have fixed arguments but less than 4 registers
5495      worth.  In this case r3 might be used in the body of the function, but
5496      it is not being used to convey an argument into the function.  In theory
5497      we could just check crtl->args.size to see how many bytes are
5498      being passed in argument registers, but it seems that it is unreliable.
5499      Sometimes it will have the value 0 when in fact arguments are being
5500      passed.  (See testcase execute/20021111-1.c for an example).  So we also
5501      check the args_info.nregs field as well.  The problem with this field is
5502      that it makes no allowances for arguments that are passed to the
5503      function but which are not used.  Hence we could miss an opportunity
5504      when a function has an unused argument in r3.  But it is better to be
5505      safe than to be sorry.  */
5506   if (! cfun->machine->uses_anonymous_args
5507       && crtl->args.size >= 0
5508       && crtl->args.size <= (LAST_ARG_REGNUM * UNITS_PER_WORD)
5509       && crtl->args.info.nregs < 4)
5510     return LAST_ARG_REGNUM;
5511
5512   /* Otherwise look for a call-saved register that is going to be pushed.  */
5513   for (reg = LAST_LO_REGNUM; reg > LAST_ARG_REGNUM; reg --)
5514     if (pushed_regs_mask & (1 << reg))
5515       return reg;
5516
5517   if (TARGET_THUMB2)
5518     {
5519       /* Thumb-2 can use high regs.  */
5520       for (reg = FIRST_HI_REGNUM; reg < 15; reg ++)
5521         if (pushed_regs_mask & (1 << reg))
5522           return reg;
5523     }
5524   /* Something went wrong - thumb_compute_save_reg_mask()
5525      should have arranged for a suitable register to be pushed.  */
5526   gcc_unreachable ();
5527 }
5528
5529 static GTY(()) int pic_labelno;
5530
5531 /* Generate code to load the PIC register.  In thumb mode SCRATCH is a
5532    low register.  */
5533
5534 void
5535 arm_load_pic_register (unsigned long saved_regs ATTRIBUTE_UNUSED)
5536 {
5537   rtx l1, labelno, pic_tmp, pic_rtx, pic_reg;
5538
5539   if (crtl->uses_pic_offset_table == 0 || TARGET_SINGLE_PIC_BASE)
5540     return;
5541
5542   gcc_assert (flag_pic);
5543
5544   pic_reg = cfun->machine->pic_reg;
5545   if (TARGET_VXWORKS_RTP)
5546     {
5547       pic_rtx = gen_rtx_SYMBOL_REF (Pmode, VXWORKS_GOTT_BASE);
5548       pic_rtx = gen_rtx_CONST (Pmode, pic_rtx);
5549       emit_insn (gen_pic_load_addr_32bit (pic_reg, pic_rtx));
5550
5551       emit_insn (gen_rtx_SET (Pmode, pic_reg, gen_rtx_MEM (Pmode, pic_reg)));
5552
5553       pic_tmp = gen_rtx_SYMBOL_REF (Pmode, VXWORKS_GOTT_INDEX);
5554       emit_insn (gen_pic_offset_arm (pic_reg, pic_reg, pic_tmp));
5555     }
5556   else
5557     {
5558       /* We use an UNSPEC rather than a LABEL_REF because this label
5559          never appears in the code stream.  */
5560
5561       labelno = GEN_INT (pic_labelno++);
5562       l1 = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, labelno), UNSPEC_PIC_LABEL);
5563       l1 = gen_rtx_CONST (VOIDmode, l1);
5564
5565       /* On the ARM the PC register contains 'dot + 8' at the time of the
5566          addition, on the Thumb it is 'dot + 4'.  */
5567       pic_rtx = plus_constant (l1, TARGET_ARM ? 8 : 4);
5568       pic_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, pic_rtx),
5569                                 UNSPEC_GOTSYM_OFF);
5570       pic_rtx = gen_rtx_CONST (Pmode, pic_rtx);
5571
5572       if (TARGET_32BIT)
5573         {
5574           emit_insn (gen_pic_load_addr_32bit (pic_reg, pic_rtx));
5575           if (TARGET_ARM)
5576             emit_insn (gen_pic_add_dot_plus_eight (pic_reg, pic_reg, labelno));
5577           else
5578             emit_insn (gen_pic_add_dot_plus_four (pic_reg, pic_reg, labelno));
5579         }
5580       else /* TARGET_THUMB1 */
5581         {
5582           if (arm_pic_register != INVALID_REGNUM
5583               && REGNO (pic_reg) > LAST_LO_REGNUM)
5584             {
5585               /* We will have pushed the pic register, so we should always be
5586                  able to find a work register.  */
5587               pic_tmp = gen_rtx_REG (SImode,
5588                                      thumb_find_work_register (saved_regs));
5589               emit_insn (gen_pic_load_addr_thumb1 (pic_tmp, pic_rtx));
5590               emit_insn (gen_movsi (pic_offset_table_rtx, pic_tmp));
5591             }
5592           else
5593             emit_insn (gen_pic_load_addr_thumb1 (pic_reg, pic_rtx));
5594           emit_insn (gen_pic_add_dot_plus_four (pic_reg, pic_reg, labelno));
5595         }
5596     }
5597
5598   /* Need to emit this whether or not we obey regdecls,
5599      since setjmp/longjmp can cause life info to screw up.  */
5600   emit_use (pic_reg);
5601 }
5602
5603 /* Generate code to load the address of a static var when flag_pic is set.  */
5604 static rtx
5605 arm_pic_static_addr (rtx orig, rtx reg)
5606 {
5607   rtx l1, labelno, offset_rtx, insn;
5608
5609   gcc_assert (flag_pic);
5610
5611   /* We use an UNSPEC rather than a LABEL_REF because this label
5612      never appears in the code stream.  */
5613   labelno = GEN_INT (pic_labelno++);
5614   l1 = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, labelno), UNSPEC_PIC_LABEL);
5615   l1 = gen_rtx_CONST (VOIDmode, l1);
5616
5617   /* On the ARM the PC register contains 'dot + 8' at the time of the
5618      addition, on the Thumb it is 'dot + 4'.  */
5619   offset_rtx = plus_constant (l1, TARGET_ARM ? 8 : 4);
5620   offset_rtx = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, orig, offset_rtx),
5621                                UNSPEC_SYMBOL_OFFSET);
5622   offset_rtx = gen_rtx_CONST (Pmode, offset_rtx);
5623
5624   if (TARGET_32BIT)
5625     {
5626       emit_insn (gen_pic_load_addr_32bit (reg, offset_rtx));
5627       if (TARGET_ARM)
5628         insn = emit_insn (gen_pic_add_dot_plus_eight (reg, reg, labelno));
5629       else
5630         insn = emit_insn (gen_pic_add_dot_plus_four (reg, reg, labelno));
5631     }
5632   else /* TARGET_THUMB1 */
5633     {
5634       emit_insn (gen_pic_load_addr_thumb1 (reg, offset_rtx));
5635       insn = emit_insn (gen_pic_add_dot_plus_four (reg, reg, labelno));
5636     }
5637
5638   return insn;
5639 }
5640
5641 /* Return nonzero if X is valid as an ARM state addressing register.  */
5642 static int
5643 arm_address_register_rtx_p (rtx x, int strict_p)
5644 {
5645   int regno;
5646
5647   if (GET_CODE (x) != REG)
5648     return 0;
5649
5650   regno = REGNO (x);
5651
5652   if (strict_p)
5653     return ARM_REGNO_OK_FOR_BASE_P (regno);
5654
5655   return (regno <= LAST_ARM_REGNUM
5656           || regno >= FIRST_PSEUDO_REGISTER
5657           || regno == FRAME_POINTER_REGNUM
5658           || regno == ARG_POINTER_REGNUM);
5659 }
5660
5661 /* Return TRUE if this rtx is the difference of a symbol and a label,
5662    and will reduce to a PC-relative relocation in the object file.
5663    Expressions like this can be left alone when generating PIC, rather
5664    than forced through the GOT.  */
5665 static int
5666 pcrel_constant_p (rtx x)
5667 {
5668   if (GET_CODE (x) == MINUS)
5669     return symbol_mentioned_p (XEXP (x, 0)) && label_mentioned_p (XEXP (x, 1));
5670
5671   return FALSE;
5672 }
5673
5674 /* Return true if X will surely end up in an index register after next
5675    splitting pass.  */
5676 static bool
5677 will_be_in_index_register (const_rtx x)
5678 {
5679   /* arm.md: calculate_pic_address will split this into a register.  */
5680   return GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_PIC_SYM;
5681 }
5682
5683 /* Return nonzero if X is a valid ARM state address operand.  */
5684 int
5685 arm_legitimate_address_outer_p (enum machine_mode mode, rtx x, RTX_CODE outer,
5686                                 int strict_p)
5687 {
5688   bool use_ldrd;
5689   enum rtx_code code = GET_CODE (x);
5690
5691   if (arm_address_register_rtx_p (x, strict_p))
5692     return 1;
5693
5694   use_ldrd = (TARGET_LDRD
5695               && (mode == DImode
5696                   || (mode == DFmode && (TARGET_SOFT_FLOAT || TARGET_VFP))));
5697
5698   if (code == POST_INC || code == PRE_DEC
5699       || ((code == PRE_INC || code == POST_DEC)
5700           && (use_ldrd || GET_MODE_SIZE (mode) <= 4)))
5701     return arm_address_register_rtx_p (XEXP (x, 0), strict_p);
5702
5703   else if ((code == POST_MODIFY || code == PRE_MODIFY)
5704            && arm_address_register_rtx_p (XEXP (x, 0), strict_p)
5705            && GET_CODE (XEXP (x, 1)) == PLUS
5706            && rtx_equal_p (XEXP (XEXP (x, 1), 0), XEXP (x, 0)))
5707     {
5708       rtx addend = XEXP (XEXP (x, 1), 1);
5709
5710       /* Don't allow ldrd post increment by register because it's hard
5711          to fixup invalid register choices.  */
5712       if (use_ldrd
5713           && GET_CODE (x) == POST_MODIFY
5714           && GET_CODE (addend) == REG)
5715         return 0;
5716
5717       return ((use_ldrd || GET_MODE_SIZE (mode) <= 4)
5718               && arm_legitimate_index_p (mode, addend, outer, strict_p));
5719     }
5720
5721   /* After reload constants split into minipools will have addresses
5722      from a LABEL_REF.  */
5723   else if (reload_completed
5724            && (code == LABEL_REF
5725                || (code == CONST
5726                    && GET_CODE (XEXP (x, 0)) == PLUS
5727                    && GET_CODE (XEXP (XEXP (x, 0), 0)) == LABEL_REF
5728                    && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)))
5729     return 1;
5730
5731   else if (mode == TImode || (TARGET_NEON && VALID_NEON_STRUCT_MODE (mode)))
5732     return 0;
5733
5734   else if (code == PLUS)
5735     {
5736       rtx xop0 = XEXP (x, 0);
5737       rtx xop1 = XEXP (x, 1);
5738
5739       return ((arm_address_register_rtx_p (xop0, strict_p)
5740                && ((GET_CODE(xop1) == CONST_INT
5741                     && arm_legitimate_index_p (mode, xop1, outer, strict_p))
5742                    || (!strict_p && will_be_in_index_register (xop1))))
5743               || (arm_address_register_rtx_p (xop1, strict_p)
5744                   && arm_legitimate_index_p (mode, xop0, outer, strict_p)));
5745     }
5746
5747 #if 0
5748   /* Reload currently can't handle MINUS, so disable this for now */
5749   else if (GET_CODE (x) == MINUS)
5750     {
5751       rtx xop0 = XEXP (x, 0);
5752       rtx xop1 = XEXP (x, 1);
5753
5754       return (arm_address_register_rtx_p (xop0, strict_p)
5755               && arm_legitimate_index_p (mode, xop1, outer, strict_p));
5756     }
5757 #endif
5758
5759   else if (GET_MODE_CLASS (mode) != MODE_FLOAT
5760            && code == SYMBOL_REF
5761            && CONSTANT_POOL_ADDRESS_P (x)
5762            && ! (flag_pic
5763                  && symbol_mentioned_p (get_pool_constant (x))
5764                  && ! pcrel_constant_p (get_pool_constant (x))))
5765     return 1;
5766
5767   return 0;
5768 }
5769
5770 /* Return nonzero if X is a valid Thumb-2 address operand.  */
5771 static int
5772 thumb2_legitimate_address_p (enum machine_mode mode, rtx x, int strict_p)
5773 {
5774   bool use_ldrd;
5775   enum rtx_code code = GET_CODE (x);
5776
5777   if (arm_address_register_rtx_p (x, strict_p))
5778     return 1;
5779
5780   use_ldrd = (TARGET_LDRD
5781               && (mode == DImode
5782                   || (mode == DFmode && (TARGET_SOFT_FLOAT || TARGET_VFP))));
5783
5784   if (code == POST_INC || code == PRE_DEC
5785       || ((code == PRE_INC || code == POST_DEC)
5786           && (use_ldrd || GET_MODE_SIZE (mode) <= 4)))
5787     return arm_address_register_rtx_p (XEXP (x, 0), strict_p);
5788
5789   else if ((code == POST_MODIFY || code == PRE_MODIFY)
5790            && arm_address_register_rtx_p (XEXP (x, 0), strict_p)
5791            && GET_CODE (XEXP (x, 1)) == PLUS
5792            && rtx_equal_p (XEXP (XEXP (x, 1), 0), XEXP (x, 0)))
5793     {
5794       /* Thumb-2 only has autoincrement by constant.  */
5795       rtx addend = XEXP (XEXP (x, 1), 1);
5796       HOST_WIDE_INT offset;
5797
5798       if (GET_CODE (addend) != CONST_INT)
5799         return 0;
5800
5801       offset = INTVAL(addend);
5802       if (GET_MODE_SIZE (mode) <= 4)
5803         return (offset > -256 && offset < 256);
5804
5805       return (use_ldrd && offset > -1024 && offset < 1024
5806               && (offset & 3) == 0);
5807     }
5808
5809   /* After reload constants split into minipools will have addresses
5810      from a LABEL_REF.  */
5811   else if (reload_completed
5812            && (code == LABEL_REF
5813                || (code == CONST
5814                    && GET_CODE (XEXP (x, 0)) == PLUS
5815                    && GET_CODE (XEXP (XEXP (x, 0), 0)) == LABEL_REF
5816                    && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)))
5817     return 1;
5818
5819   else if (mode == TImode || (TARGET_NEON && VALID_NEON_STRUCT_MODE (mode)))
5820     return 0;
5821
5822   else if (code == PLUS)
5823     {
5824       rtx xop0 = XEXP (x, 0);
5825       rtx xop1 = XEXP (x, 1);
5826
5827       return ((arm_address_register_rtx_p (xop0, strict_p)
5828                && (thumb2_legitimate_index_p (mode, xop1, strict_p)
5829                    || (!strict_p && will_be_in_index_register (xop1))))
5830               || (arm_address_register_rtx_p (xop1, strict_p)
5831                   && thumb2_legitimate_index_p (mode, xop0, strict_p)));
5832     }
5833
5834   else if (GET_MODE_CLASS (mode) != MODE_FLOAT
5835            && code == SYMBOL_REF
5836            && CONSTANT_POOL_ADDRESS_P (x)
5837            && ! (flag_pic
5838                  && symbol_mentioned_p (get_pool_constant (x))
5839                  && ! pcrel_constant_p (get_pool_constant (x))))
5840     return 1;
5841
5842   return 0;
5843 }
5844
5845 /* Return nonzero if INDEX is valid for an address index operand in
5846    ARM state.  */
5847 static int
5848 arm_legitimate_index_p (enum machine_mode mode, rtx index, RTX_CODE outer,
5849                         int strict_p)
5850 {
5851   HOST_WIDE_INT range;
5852   enum rtx_code code = GET_CODE (index);
5853
5854   /* Standard coprocessor addressing modes.  */
5855   if (TARGET_HARD_FLOAT
5856       && (TARGET_VFP || TARGET_FPA || TARGET_MAVERICK)
5857       && (mode == SFmode || mode == DFmode
5858           || (TARGET_MAVERICK && mode == DImode)))
5859     return (code == CONST_INT && INTVAL (index) < 1024
5860             && INTVAL (index) > -1024
5861             && (INTVAL (index) & 3) == 0);
5862
5863   /* For quad modes, we restrict the constant offset to be slightly less
5864      than what the instruction format permits.  We do this because for
5865      quad mode moves, we will actually decompose them into two separate
5866      double-mode reads or writes.  INDEX must therefore be a valid
5867      (double-mode) offset and so should INDEX+8.  */
5868   if (TARGET_NEON && VALID_NEON_QREG_MODE (mode))
5869     return (code == CONST_INT
5870             && INTVAL (index) < 1016
5871             && INTVAL (index) > -1024
5872             && (INTVAL (index) & 3) == 0);
5873
5874   /* We have no such constraint on double mode offsets, so we permit the
5875      full range of the instruction format.  */
5876   if (TARGET_NEON && VALID_NEON_DREG_MODE (mode))
5877     return (code == CONST_INT
5878             && INTVAL (index) < 1024
5879             && INTVAL (index) > -1024
5880             && (INTVAL (index) & 3) == 0);
5881
5882   if (TARGET_REALLY_IWMMXT && VALID_IWMMXT_REG_MODE (mode))
5883     return (code == CONST_INT
5884             && INTVAL (index) < 1024
5885             && INTVAL (index) > -1024
5886             && (INTVAL (index) & 3) == 0);
5887
5888   if (arm_address_register_rtx_p (index, strict_p)
5889       && (GET_MODE_SIZE (mode) <= 4))
5890     return 1;
5891
5892   if (mode == DImode || mode == DFmode)
5893     {
5894       if (code == CONST_INT)
5895         {
5896           HOST_WIDE_INT val = INTVAL (index);
5897
5898           if (TARGET_LDRD)
5899             return val > -256 && val < 256;
5900           else
5901             return val > -4096 && val < 4092;
5902         }
5903
5904       return TARGET_LDRD && arm_address_register_rtx_p (index, strict_p);
5905     }
5906
5907   if (GET_MODE_SIZE (mode) <= 4
5908       && ! (arm_arch4
5909             && (mode == HImode
5910                 || mode == HFmode
5911                 || (mode == QImode && outer == SIGN_EXTEND))))
5912     {
5913       if (code == MULT)
5914         {
5915           rtx xiop0 = XEXP (index, 0);
5916           rtx xiop1 = XEXP (index, 1);
5917
5918           return ((arm_address_register_rtx_p (xiop0, strict_p)
5919                    && power_of_two_operand (xiop1, SImode))
5920                   || (arm_address_register_rtx_p (xiop1, strict_p)
5921                       && power_of_two_operand (xiop0, SImode)));
5922         }
5923       else if (code == LSHIFTRT || code == ASHIFTRT
5924                || code == ASHIFT || code == ROTATERT)
5925         {
5926           rtx op = XEXP (index, 1);
5927
5928           return (arm_address_register_rtx_p (XEXP (index, 0), strict_p)
5929                   && GET_CODE (op) == CONST_INT
5930                   && INTVAL (op) > 0
5931                   && INTVAL (op) <= 31);
5932         }
5933     }
5934
5935   /* For ARM v4 we may be doing a sign-extend operation during the
5936      load.  */
5937   if (arm_arch4)
5938     {
5939       if (mode == HImode
5940           || mode == HFmode
5941           || (outer == SIGN_EXTEND && mode == QImode))
5942         range = 256;
5943       else
5944         range = 4096;
5945     }
5946   else
5947     range = (mode == HImode || mode == HFmode) ? 4095 : 4096;
5948
5949   return (code == CONST_INT
5950           && INTVAL (index) < range
5951           && INTVAL (index) > -range);
5952 }
5953
5954 /* Return true if OP is a valid index scaling factor for Thumb-2 address
5955    index operand.  i.e. 1, 2, 4 or 8.  */
5956 static bool
5957 thumb2_index_mul_operand (rtx op)
5958 {
5959   HOST_WIDE_INT val;
5960
5961   if (GET_CODE(op) != CONST_INT)
5962     return false;
5963
5964   val = INTVAL(op);
5965   return (val == 1 || val == 2 || val == 4 || val == 8);
5966 }
5967
5968 /* Return nonzero if INDEX is a valid Thumb-2 address index operand.  */
5969 static int
5970 thumb2_legitimate_index_p (enum machine_mode mode, rtx index, int strict_p)
5971 {
5972   enum rtx_code code = GET_CODE (index);
5973
5974   /* ??? Combine arm and thumb2 coprocessor addressing modes.  */
5975   /* Standard coprocessor addressing modes.  */
5976   if (TARGET_HARD_FLOAT
5977       && (TARGET_VFP || TARGET_FPA || TARGET_MAVERICK)
5978       && (mode == SFmode || mode == DFmode
5979           || (TARGET_MAVERICK && mode == DImode)))
5980     return (code == CONST_INT && INTVAL (index) < 1024
5981             /* Thumb-2 allows only > -256 index range for it's core register
5982                load/stores. Since we allow SF/DF in core registers, we have
5983                to use the intersection between -256~4096 (core) and -1024~1024
5984                (coprocessor).  */
5985             && INTVAL (index) > -256
5986             && (INTVAL (index) & 3) == 0);
5987
5988   if (TARGET_REALLY_IWMMXT && VALID_IWMMXT_REG_MODE (mode))
5989     {
5990       /* For DImode assume values will usually live in core regs
5991          and only allow LDRD addressing modes.  */
5992       if (!TARGET_LDRD || mode != DImode)
5993         return (code == CONST_INT
5994                 && INTVAL (index) < 1024
5995                 && INTVAL (index) > -1024
5996                 && (INTVAL (index) & 3) == 0);
5997     }
5998
5999   /* For quad modes, we restrict the constant offset to be slightly less
6000      than what the instruction format permits.  We do this because for
6001      quad mode moves, we will actually decompose them into two separate
6002      double-mode reads or writes.  INDEX must therefore be a valid
6003      (double-mode) offset and so should INDEX+8.  */
6004   if (TARGET_NEON && VALID_NEON_QREG_MODE (mode))
6005     return (code == CONST_INT
6006             && INTVAL (index) < 1016
6007             && INTVAL (index) > -1024
6008             && (INTVAL (index) & 3) == 0);
6009
6010   /* We have no such constraint on double mode offsets, so we permit the
6011      full range of the instruction format.  */
6012   if (TARGET_NEON && VALID_NEON_DREG_MODE (mode))
6013     return (code == CONST_INT
6014             && INTVAL (index) < 1024
6015             && INTVAL (index) > -1024
6016             && (INTVAL (index) & 3) == 0);
6017
6018   if (arm_address_register_rtx_p (index, strict_p)
6019       && (GET_MODE_SIZE (mode) <= 4))
6020     return 1;
6021
6022   if (mode == DImode || mode == DFmode)
6023     {
6024       if (code == CONST_INT)
6025         {
6026           HOST_WIDE_INT val = INTVAL (index);
6027           /* ??? Can we assume ldrd for thumb2?  */
6028           /* Thumb-2 ldrd only has reg+const addressing modes.  */
6029           /* ldrd supports offsets of +-1020.
6030              However the ldr fallback does not.  */
6031           return val > -256 && val < 256 && (val & 3) == 0;
6032         }
6033       else
6034         return 0;
6035     }
6036
6037   if (code == MULT)
6038     {
6039       rtx xiop0 = XEXP (index, 0);
6040       rtx xiop1 = XEXP (index, 1);
6041
6042       return ((arm_address_register_rtx_p (xiop0, strict_p)
6043                && thumb2_index_mul_operand (xiop1))
6044               || (arm_address_register_rtx_p (xiop1, strict_p)
6045                   && thumb2_index_mul_operand (xiop0)));
6046     }
6047   else if (code == ASHIFT)
6048     {
6049       rtx op = XEXP (index, 1);
6050
6051       return (arm_address_register_rtx_p (XEXP (index, 0), strict_p)
6052               && GET_CODE (op) == CONST_INT
6053               && INTVAL (op) > 0
6054               && INTVAL (op) <= 3);
6055     }
6056
6057   return (code == CONST_INT
6058           && INTVAL (index) < 4096
6059           && INTVAL (index) > -256);
6060 }
6061
6062 /* Return nonzero if X is valid as a 16-bit Thumb state base register.  */
6063 static int
6064 thumb1_base_register_rtx_p (rtx x, enum machine_mode mode, int strict_p)
6065 {
6066   int regno;
6067
6068   if (GET_CODE (x) != REG)
6069     return 0;
6070
6071   regno = REGNO (x);
6072
6073   if (strict_p)
6074     return THUMB1_REGNO_MODE_OK_FOR_BASE_P (regno, mode);
6075
6076   return (regno <= LAST_LO_REGNUM
6077           || regno > LAST_VIRTUAL_REGISTER
6078           || regno == FRAME_POINTER_REGNUM
6079           || (GET_MODE_SIZE (mode) >= 4
6080               && (regno == STACK_POINTER_REGNUM
6081                   || regno >= FIRST_PSEUDO_REGISTER
6082                   || x == hard_frame_pointer_rtx
6083                   || x == arg_pointer_rtx)));
6084 }
6085
6086 /* Return nonzero if x is a legitimate index register.  This is the case
6087    for any base register that can access a QImode object.  */
6088 inline static int
6089 thumb1_index_register_rtx_p (rtx x, int strict_p)
6090 {
6091   return thumb1_base_register_rtx_p (x, QImode, strict_p);
6092 }
6093
6094 /* Return nonzero if x is a legitimate 16-bit Thumb-state address.
6095
6096    The AP may be eliminated to either the SP or the FP, so we use the
6097    least common denominator, e.g. SImode, and offsets from 0 to 64.
6098
6099    ??? Verify whether the above is the right approach.
6100
6101    ??? Also, the FP may be eliminated to the SP, so perhaps that
6102    needs special handling also.
6103
6104    ??? Look at how the mips16 port solves this problem.  It probably uses
6105    better ways to solve some of these problems.
6106
6107    Although it is not incorrect, we don't accept QImode and HImode
6108    addresses based on the frame pointer or arg pointer until the
6109    reload pass starts.  This is so that eliminating such addresses
6110    into stack based ones won't produce impossible code.  */
6111 int
6112 thumb1_legitimate_address_p (enum machine_mode mode, rtx x, int strict_p)
6113 {
6114   /* ??? Not clear if this is right.  Experiment.  */
6115   if (GET_MODE_SIZE (mode) < 4
6116       && !(reload_in_progress || reload_completed)
6117       && (reg_mentioned_p (frame_pointer_rtx, x)
6118           || reg_mentioned_p (arg_pointer_rtx, x)
6119           || reg_mentioned_p (virtual_incoming_args_rtx, x)
6120           || reg_mentioned_p (virtual_outgoing_args_rtx, x)
6121           || reg_mentioned_p (virtual_stack_dynamic_rtx, x)
6122           || reg_mentioned_p (virtual_stack_vars_rtx, x)))
6123     return 0;
6124
6125   /* Accept any base register.  SP only in SImode or larger.  */
6126   else if (thumb1_base_register_rtx_p (x, mode, strict_p))
6127     return 1;
6128
6129   /* This is PC relative data before arm_reorg runs.  */
6130   else if (GET_MODE_SIZE (mode) >= 4 && CONSTANT_P (x)
6131            && GET_CODE (x) == SYMBOL_REF
6132            && CONSTANT_POOL_ADDRESS_P (x) && !flag_pic)
6133     return 1;
6134
6135   /* This is PC relative data after arm_reorg runs.  */
6136   else if ((GET_MODE_SIZE (mode) >= 4 || mode == HFmode)
6137            && reload_completed
6138            && (GET_CODE (x) == LABEL_REF
6139                || (GET_CODE (x) == CONST
6140                    && GET_CODE (XEXP (x, 0)) == PLUS
6141                    && GET_CODE (XEXP (XEXP (x, 0), 0)) == LABEL_REF
6142                    && GET_CODE (XEXP (XEXP (x, 0), 1)) == CONST_INT)))
6143     return 1;
6144
6145   /* Post-inc indexing only supported for SImode and larger.  */
6146   else if (GET_CODE (x) == POST_INC && GET_MODE_SIZE (mode) >= 4
6147            && thumb1_index_register_rtx_p (XEXP (x, 0), strict_p))
6148     return 1;
6149
6150   else if (GET_CODE (x) == PLUS)
6151     {
6152       /* REG+REG address can be any two index registers.  */
6153       /* We disallow FRAME+REG addressing since we know that FRAME
6154          will be replaced with STACK, and SP relative addressing only
6155          permits SP+OFFSET.  */
6156       if (GET_MODE_SIZE (mode) <= 4
6157           && XEXP (x, 0) != frame_pointer_rtx
6158           && XEXP (x, 1) != frame_pointer_rtx
6159           && thumb1_index_register_rtx_p (XEXP (x, 0), strict_p)
6160           && (thumb1_index_register_rtx_p (XEXP (x, 1), strict_p)
6161               || (!strict_p && will_be_in_index_register (XEXP (x, 1)))))
6162         return 1;
6163
6164       /* REG+const has 5-7 bit offset for non-SP registers.  */
6165       else if ((thumb1_index_register_rtx_p (XEXP (x, 0), strict_p)
6166                 || XEXP (x, 0) == arg_pointer_rtx)
6167                && GET_CODE (XEXP (x, 1)) == CONST_INT
6168                && thumb_legitimate_offset_p (mode, INTVAL (XEXP (x, 1))))
6169         return 1;
6170
6171       /* REG+const has 10-bit offset for SP, but only SImode and
6172          larger is supported.  */
6173       /* ??? Should probably check for DI/DFmode overflow here
6174          just like GO_IF_LEGITIMATE_OFFSET does.  */
6175       else if (GET_CODE (XEXP (x, 0)) == REG
6176                && REGNO (XEXP (x, 0)) == STACK_POINTER_REGNUM
6177                && GET_MODE_SIZE (mode) >= 4
6178                && GET_CODE (XEXP (x, 1)) == CONST_INT
6179                && INTVAL (XEXP (x, 1)) >= 0
6180                && INTVAL (XEXP (x, 1)) + GET_MODE_SIZE (mode) <= 1024
6181                && (INTVAL (XEXP (x, 1)) & 3) == 0)
6182         return 1;
6183
6184       else if (GET_CODE (XEXP (x, 0)) == REG
6185                && (REGNO (XEXP (x, 0)) == FRAME_POINTER_REGNUM
6186                    || REGNO (XEXP (x, 0)) == ARG_POINTER_REGNUM
6187                    || (REGNO (XEXP (x, 0)) >= FIRST_VIRTUAL_REGISTER
6188                        && REGNO (XEXP (x, 0))
6189                           <= LAST_VIRTUAL_POINTER_REGISTER))
6190                && GET_MODE_SIZE (mode) >= 4
6191                && GET_CODE (XEXP (x, 1)) == CONST_INT
6192                && (INTVAL (XEXP (x, 1)) & 3) == 0)
6193         return 1;
6194     }
6195
6196   else if (GET_MODE_CLASS (mode) != MODE_FLOAT
6197            && GET_MODE_SIZE (mode) == 4
6198            && GET_CODE (x) == SYMBOL_REF
6199            && CONSTANT_POOL_ADDRESS_P (x)
6200            && ! (flag_pic
6201                  && symbol_mentioned_p (get_pool_constant (x))
6202                  && ! pcrel_constant_p (get_pool_constant (x))))
6203     return 1;
6204
6205   return 0;
6206 }
6207
6208 /* Return nonzero if VAL can be used as an offset in a Thumb-state address
6209    instruction of mode MODE.  */
6210 int
6211 thumb_legitimate_offset_p (enum machine_mode mode, HOST_WIDE_INT val)
6212 {
6213   switch (GET_MODE_SIZE (mode))
6214     {
6215     case 1:
6216       return val >= 0 && val < 32;
6217
6218     case 2:
6219       return val >= 0 && val < 64 && (val & 1) == 0;
6220
6221     default:
6222       return (val >= 0
6223               && (val + GET_MODE_SIZE (mode)) <= 128
6224               && (val & 3) == 0);
6225     }
6226 }
6227
6228 bool
6229 arm_legitimate_address_p (enum machine_mode mode, rtx x, bool strict_p)
6230 {
6231   if (TARGET_ARM)
6232     return arm_legitimate_address_outer_p (mode, x, SET, strict_p);
6233   else if (TARGET_THUMB2)
6234     return thumb2_legitimate_address_p (mode, x, strict_p);
6235   else /* if (TARGET_THUMB1) */
6236     return thumb1_legitimate_address_p (mode, x, strict_p);
6237 }
6238
6239 /* Build the SYMBOL_REF for __tls_get_addr.  */
6240
6241 static GTY(()) rtx tls_get_addr_libfunc;
6242
6243 static rtx
6244 get_tls_get_addr (void)
6245 {
6246   if (!tls_get_addr_libfunc)
6247     tls_get_addr_libfunc = init_one_libfunc ("__tls_get_addr");
6248   return tls_get_addr_libfunc;
6249 }
6250
6251 static rtx
6252 arm_load_tp (rtx target)
6253 {
6254   if (!target)
6255     target = gen_reg_rtx (SImode);
6256
6257   if (TARGET_HARD_TP)
6258     {
6259       /* Can return in any reg.  */
6260       emit_insn (gen_load_tp_hard (target));
6261     }
6262   else
6263     {
6264       /* Always returned in r0.  Immediately copy the result into a pseudo,
6265          otherwise other uses of r0 (e.g. setting up function arguments) may
6266          clobber the value.  */
6267
6268       rtx tmp;
6269
6270       emit_insn (gen_load_tp_soft ());
6271
6272       tmp = gen_rtx_REG (SImode, 0);
6273       emit_move_insn (target, tmp);
6274     }
6275   return target;
6276 }
6277
6278 static rtx
6279 load_tls_operand (rtx x, rtx reg)
6280 {
6281   rtx tmp;
6282
6283   if (reg == NULL_RTX)
6284     reg = gen_reg_rtx (SImode);
6285
6286   tmp = gen_rtx_CONST (SImode, x);
6287
6288   emit_move_insn (reg, tmp);
6289
6290   return reg;
6291 }
6292
6293 static rtx
6294 arm_call_tls_get_addr (rtx x, rtx reg, rtx *valuep, int reloc)
6295 {
6296   rtx insns, label, labelno, sum;
6297
6298   gcc_assert (reloc != TLS_DESCSEQ);
6299   start_sequence ();
6300
6301   labelno = GEN_INT (pic_labelno++);
6302   label = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, labelno), UNSPEC_PIC_LABEL);
6303   label = gen_rtx_CONST (VOIDmode, label);
6304
6305   sum = gen_rtx_UNSPEC (Pmode,
6306                         gen_rtvec (4, x, GEN_INT (reloc), label,
6307                                    GEN_INT (TARGET_ARM ? 8 : 4)),
6308                         UNSPEC_TLS);
6309   reg = load_tls_operand (sum, reg);
6310
6311   if (TARGET_ARM)
6312     emit_insn (gen_pic_add_dot_plus_eight (reg, reg, labelno));
6313   else
6314     emit_insn (gen_pic_add_dot_plus_four (reg, reg, labelno));
6315
6316   *valuep = emit_library_call_value (get_tls_get_addr (), NULL_RTX,
6317                                      LCT_PURE, /* LCT_CONST?  */
6318                                      Pmode, 1, reg, Pmode);
6319
6320   insns = get_insns ();
6321   end_sequence ();
6322
6323   return insns;
6324 }
6325
6326 static rtx
6327 arm_tls_descseq_addr (rtx x, rtx reg)
6328 {
6329   rtx labelno = GEN_INT (pic_labelno++);
6330   rtx label = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, labelno), UNSPEC_PIC_LABEL);
6331   rtx sum = gen_rtx_UNSPEC (Pmode,
6332                             gen_rtvec (4, x, GEN_INT (TLS_DESCSEQ),
6333                                        gen_rtx_CONST (VOIDmode, label),
6334                                        GEN_INT (!TARGET_ARM)),
6335                             UNSPEC_TLS);
6336   rtx reg0 = load_tls_operand (sum, gen_rtx_REG (SImode, 0));
6337
6338   emit_insn (gen_tlscall (x, labelno));
6339   if (!reg)
6340     reg = gen_reg_rtx (SImode);
6341   else
6342     gcc_assert (REGNO (reg) != 0);
6343
6344   emit_move_insn (reg, reg0);
6345
6346   return reg;
6347 }
6348
6349 rtx
6350 legitimize_tls_address (rtx x, rtx reg)
6351 {
6352   rtx dest, tp, label, labelno, sum, insns, ret, eqv, addend;
6353   unsigned int model = SYMBOL_REF_TLS_MODEL (x);
6354
6355   switch (model)
6356     {
6357     case TLS_MODEL_GLOBAL_DYNAMIC:
6358       if (TARGET_GNU2_TLS)
6359         {
6360           reg = arm_tls_descseq_addr (x, reg);
6361
6362           tp = arm_load_tp (NULL_RTX);
6363
6364           dest = gen_rtx_PLUS (Pmode, tp, reg);
6365         }
6366       else
6367         {
6368           /* Original scheme */
6369           insns = arm_call_tls_get_addr (x, reg, &ret, TLS_GD32);
6370           dest = gen_reg_rtx (Pmode);
6371           emit_libcall_block (insns, dest, ret, x);
6372         }
6373       return dest;
6374
6375     case TLS_MODEL_LOCAL_DYNAMIC:
6376       if (TARGET_GNU2_TLS)
6377         {
6378           reg = arm_tls_descseq_addr (x, reg);
6379
6380           tp = arm_load_tp (NULL_RTX);
6381
6382           dest = gen_rtx_PLUS (Pmode, tp, reg);
6383         }
6384       else
6385         {
6386           insns = arm_call_tls_get_addr (x, reg, &ret, TLS_LDM32);
6387
6388           /* Attach a unique REG_EQUIV, to allow the RTL optimizers to
6389              share the LDM result with other LD model accesses.  */
6390           eqv = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, const1_rtx),
6391                                 UNSPEC_TLS);
6392           dest = gen_reg_rtx (Pmode);
6393           emit_libcall_block (insns, dest, ret, eqv);
6394
6395           /* Load the addend.  */
6396           addend = gen_rtx_UNSPEC (Pmode, gen_rtvec (2, x,
6397                                                      GEN_INT (TLS_LDO32)),
6398                                    UNSPEC_TLS);
6399           addend = force_reg (SImode, gen_rtx_CONST (SImode, addend));
6400           dest = gen_rtx_PLUS (Pmode, dest, addend);
6401         }
6402       return dest;
6403
6404     case TLS_MODEL_INITIAL_EXEC:
6405       labelno = GEN_INT (pic_labelno++);
6406       label = gen_rtx_UNSPEC (Pmode, gen_rtvec (1, labelno), UNSPEC_PIC_LABEL);
6407       label = gen_rtx_CONST (VOIDmode, label);
6408       sum = gen_rtx_UNSPEC (Pmode,
6409                             gen_rtvec (4, x, GEN_INT (TLS_IE32), label,
6410                                        GEN_INT (TARGET_ARM ? 8 : 4)),
6411                             UNSPEC_TLS);
6412       reg = load_tls_operand (sum, reg);
6413
6414       if (TARGET_ARM)
6415         emit_insn (gen_tls_load_dot_plus_eight (reg, reg, labelno));
6416       else if (TARGET_THUMB2)
6417         emit_insn (gen_tls_load_dot_plus_four (reg, NULL, reg, labelno));
6418       else
6419         {
6420           emit_insn (gen_pic_add_dot_plus_four (reg, reg, labelno));
6421           emit_move_insn (reg, gen_const_mem (SImode, reg));
6422         }
6423
6424       tp = arm_load_tp (NULL_RTX);
6425
6426       return gen_rtx_PLUS (Pmode, tp, reg);
6427
6428     case TLS_MODEL_LOCAL_EXEC:
6429       tp = arm_load_tp (NULL_RTX);
6430
6431       reg = gen_rtx_UNSPEC (Pmode,
6432                             gen_rtvec (2, x, GEN_INT (TLS_LE32)),
6433                             UNSPEC_TLS);
6434       reg = force_reg (SImode, gen_rtx_CONST (SImode, reg));
6435
6436       return gen_rtx_PLUS (Pmode, tp, reg);
6437
6438     default:
6439       abort ();
6440     }
6441 }
6442
6443 /* Try machine-dependent ways of modifying an illegitimate address
6444    to be legitimate.  If we find one, return the new, valid address.  */
6445 rtx
6446 arm_legitimize_address (rtx x, rtx orig_x, enum machine_mode mode)
6447 {
6448   if (!TARGET_ARM)
6449     {
6450       /* TODO: legitimize_address for Thumb2.  */
6451       if (TARGET_THUMB2)
6452         return x;
6453       return thumb_legitimize_address (x, orig_x, mode);
6454     }
6455
6456   if (arm_tls_symbol_p (x))
6457     return legitimize_tls_address (x, NULL_RTX);
6458
6459   if (GET_CODE (x) == PLUS)
6460     {
6461       rtx xop0 = XEXP (x, 0);
6462       rtx xop1 = XEXP (x, 1);
6463
6464       if (CONSTANT_P (xop0) && !symbol_mentioned_p (xop0))
6465         xop0 = force_reg (SImode, xop0);
6466
6467       if (CONSTANT_P (xop1) && !symbol_mentioned_p (xop1))
6468         xop1 = force_reg (SImode, xop1);
6469
6470       if (ARM_BASE_REGISTER_RTX_P (xop0)
6471           && GET_CODE (xop1) == CONST_INT)
6472         {
6473           HOST_WIDE_INT n, low_n;
6474           rtx base_reg, val;
6475           n = INTVAL (xop1);
6476
6477           /* VFP addressing modes actually allow greater offsets, but for
6478              now we just stick with the lowest common denominator.  */
6479           if (mode == DImode
6480               || ((TARGET_SOFT_FLOAT || TARGET_VFP) && mode == DFmode))
6481             {
6482               low_n = n & 0x0f;
6483               n &= ~0x0f;
6484               if (low_n > 4)
6485                 {
6486                   n += 16;
6487                   low_n -= 16;
6488                 }
6489             }
6490           else
6491             {
6492               low_n = ((mode) == TImode ? 0
6493                        : n >= 0 ? (n & 0xfff) : -((-n) & 0xfff));
6494               n -= low_n;
6495             }
6496
6497           base_reg = gen_reg_rtx (SImode);
6498           val = force_operand (plus_constant (xop0, n), NULL_RTX);
6499           emit_move_insn (base_reg, val);
6500           x = plus_constant (base_reg, low_n);
6501         }
6502       else if (xop0 != XEXP (x, 0) || xop1 != XEXP (x, 1))
6503         x = gen_rtx_PLUS (SImode, xop0, xop1);
6504     }
6505
6506   /* XXX We don't allow MINUS any more -- see comment in
6507      arm_legitimate_address_outer_p ().  */
6508   else if (GET_CODE (x) == MINUS)
6509     {
6510       rtx xop0 = XEXP (x, 0);
6511       rtx xop1 = XEXP (x, 1);
6512
6513       if (CONSTANT_P (xop0))
6514         xop0 = force_reg (SImode, xop0);
6515
6516       if (CONSTANT_P (xop1) && ! symbol_mentioned_p (xop1))
6517         xop1 = force_reg (SImode, xop1);
6518
6519       if (xop0 != XEXP (x, 0) || xop1 != XEXP (x, 1))
6520         x = gen_rtx_MINUS (SImode, xop0, xop1);
6521     }
6522
6523   /* Make sure to take full advantage of the pre-indexed addressing mode
6524      with absolute addresses which often allows for the base register to
6525      be factorized for multiple adjacent memory references, and it might
6526      even allows for the mini pool to be avoided entirely. */
6527   else if (GET_CODE (x) == CONST_INT && optimize > 0)
6528     {
6529       unsigned int bits;
6530       HOST_WIDE_INT mask, base, index;
6531       rtx base_reg;
6532
6533       /* ldr and ldrb can use a 12-bit index, ldrsb and the rest can only
6534          use a 8-bit index. So let's use a 12-bit index for SImode only and
6535          hope that arm_gen_constant will enable ldrb to use more bits. */
6536       bits = (mode == SImode) ? 12 : 8;
6537       mask = (1 << bits) - 1;
6538       base = INTVAL (x) & ~mask;
6539       index = INTVAL (x) & mask;
6540       if (bit_count (base & 0xffffffff) > (32 - bits)/2)
6541         {
6542           /* It'll most probably be more efficient to generate the base
6543              with more bits set and use a negative index instead. */
6544           base |= mask;
6545           index -= mask;
6546         }
6547       base_reg = force_reg (SImode, GEN_INT (base));
6548       x = plus_constant (base_reg, index);
6549     }
6550
6551   if (flag_pic)
6552     {
6553       /* We need to find and carefully transform any SYMBOL and LABEL
6554          references; so go back to the original address expression.  */
6555       rtx new_x = legitimize_pic_address (orig_x, mode, NULL_RTX);
6556
6557       if (new_x != orig_x)
6558         x = new_x;
6559     }
6560
6561   return x;
6562 }
6563
6564
6565 /* Try machine-dependent ways of modifying an illegitimate Thumb address
6566    to be legitimate.  If we find one, return the new, valid address.  */
6567 rtx
6568 thumb_legitimize_address (rtx x, rtx orig_x, enum machine_mode mode)
6569 {
6570   if (arm_tls_symbol_p (x))
6571     return legitimize_tls_address (x, NULL_RTX);
6572
6573   if (GET_CODE (x) == PLUS
6574       && GET_CODE (XEXP (x, 1)) == CONST_INT
6575       && (INTVAL (XEXP (x, 1)) >= 32 * GET_MODE_SIZE (mode)
6576           || INTVAL (XEXP (x, 1)) < 0))
6577     {
6578       rtx xop0 = XEXP (x, 0);
6579       rtx xop1 = XEXP (x, 1);
6580       HOST_WIDE_INT offset = INTVAL (xop1);
6581
6582       /* Try and fold the offset into a biasing of the base register and
6583          then offsetting that.  Don't do this when optimizing for space
6584          since it can cause too many CSEs.  */
6585       if (optimize_size && offset >= 0
6586           && offset < 256 + 31 * GET_MODE_SIZE (mode))
6587         {
6588           HOST_WIDE_INT delta;
6589
6590           if (offset >= 256)
6591             delta = offset - (256 - GET_MODE_SIZE (mode));
6592           else if (offset < 32 * GET_MODE_SIZE (mode) + 8)
6593             delta = 31 * GET_MODE_SIZE (mode);
6594           else
6595             delta = offset & (~31 * GET_MODE_SIZE (mode));
6596
6597           xop0 = force_operand (plus_constant (xop0, offset - delta),
6598                                 NULL_RTX);
6599           x = plus_constant (xop0, delta);
6600         }
6601       else if (offset < 0 && offset > -256)
6602         /* Small negative offsets are best done with a subtract before the
6603            dereference, forcing these into a register normally takes two
6604            instructions.  */
6605         x = force_operand (x, NULL_RTX);
6606       else
6607         {
6608           /* For the remaining cases, force the constant into a register.  */
6609           xop1 = force_reg (SImode, xop1);
6610           x = gen_rtx_PLUS (SImode, xop0, xop1);
6611         }
6612     }
6613   else if (GET_CODE (x) == PLUS
6614            && s_register_operand (XEXP (x, 1), SImode)
6615            && !s_register_operand (XEXP (x, 0), SImode))
6616     {
6617       rtx xop0 = force_operand (XEXP (x, 0), NULL_RTX);
6618
6619       x = gen_rtx_PLUS (SImode, xop0, XEXP (x, 1));
6620     }
6621
6622   if (flag_pic)
6623     {
6624       /* We need to find and carefully transform any SYMBOL and LABEL
6625          references; so go back to the original address expression.  */
6626       rtx new_x = legitimize_pic_address (orig_x, mode, NULL_RTX);
6627
6628       if (new_x != orig_x)
6629         x = new_x;
6630     }
6631
6632   return x;
6633 }
6634
6635 bool
6636 arm_legitimize_reload_address (rtx *p,
6637                                enum machine_mode mode,
6638                                int opnum, int type,
6639                                int ind_levels ATTRIBUTE_UNUSED)
6640 {
6641   /* We must recognize output that we have already generated ourselves.  */
6642   if (GET_CODE (*p) == PLUS
6643       && GET_CODE (XEXP (*p, 0)) == PLUS
6644       && GET_CODE (XEXP (XEXP (*p, 0), 0)) == REG
6645       && GET_CODE (XEXP (XEXP (*p, 0), 1)) == CONST_INT
6646       && GET_CODE (XEXP (*p, 1)) == CONST_INT)
6647     {
6648       push_reload (XEXP (*p, 0), NULL_RTX, &XEXP (*p, 0), NULL,
6649                    MODE_BASE_REG_CLASS (mode), GET_MODE (*p),
6650                    VOIDmode, 0, 0, opnum, (enum reload_type) type);
6651       return true;
6652     }
6653
6654   if (GET_CODE (*p) == PLUS
6655       && GET_CODE (XEXP (*p, 0)) == REG
6656       && ARM_REGNO_OK_FOR_BASE_P (REGNO (XEXP (*p, 0)))
6657       /* If the base register is equivalent to a constant, let the generic
6658          code handle it.  Otherwise we will run into problems if a future
6659          reload pass decides to rematerialize the constant.  */
6660       && !reg_equiv_constant (ORIGINAL_REGNO (XEXP (*p, 0)))
6661       && GET_CODE (XEXP (*p, 1)) == CONST_INT)
6662     {
6663       HOST_WIDE_INT val = INTVAL (XEXP (*p, 1));
6664       HOST_WIDE_INT low, high;
6665
6666       /* Detect coprocessor load/stores.  */
6667       bool coproc_p = ((TARGET_HARD_FLOAT
6668                         && (TARGET_VFP || TARGET_FPA || TARGET_MAVERICK)
6669                         && (mode == SFmode || mode == DFmode
6670                             || (mode == DImode && TARGET_MAVERICK)))
6671                        || (TARGET_REALLY_IWMMXT
6672                            && VALID_IWMMXT_REG_MODE (mode))
6673                        || (TARGET_NEON
6674                            && (VALID_NEON_DREG_MODE (mode)
6675                                || VALID_NEON_QREG_MODE (mode))));
6676
6677       /* For some conditions, bail out when lower two bits are unaligned.  */
6678       if ((val & 0x3) != 0
6679           /* Coprocessor load/store indexes are 8-bits + '00' appended.  */
6680           && (coproc_p
6681               /* For DI, and DF under soft-float: */
6682               || ((mode == DImode || mode == DFmode)
6683                   /* Without ldrd, we use stm/ldm, which does not
6684                      fair well with unaligned bits.  */
6685                   && (! TARGET_LDRD
6686                       /* Thumb-2 ldrd/strd is [-1020,+1020] in steps of 4.  */
6687                       || TARGET_THUMB2))))
6688         return false;
6689
6690       /* When breaking down a [reg+index] reload address into [(reg+high)+low],
6691          of which the (reg+high) gets turned into a reload add insn,
6692          we try to decompose the index into high/low values that can often
6693          also lead to better reload CSE.
6694          For example:
6695                  ldr r0, [r2, #4100]  // Offset too large
6696                  ldr r1, [r2, #4104]  // Offset too large
6697
6698          is best reloaded as:
6699                  add t1, r2, #4096
6700                  ldr r0, [t1, #4]
6701                  add t2, r2, #4096
6702                  ldr r1, [t2, #8]
6703
6704          which post-reload CSE can simplify in most cases to eliminate the
6705          second add instruction:
6706                  add t1, r2, #4096
6707                  ldr r0, [t1, #4]
6708                  ldr r1, [t1, #8]
6709
6710          The idea here is that we want to split out the bits of the constant
6711          as a mask, rather than as subtracting the maximum offset that the
6712          respective type of load/store used can handle.
6713
6714          When encountering negative offsets, we can still utilize it even if
6715          the overall offset is positive; sometimes this may lead to an immediate
6716          that can be constructed with fewer instructions.
6717          For example:
6718                  ldr r0, [r2, #0x3FFFFC]
6719
6720          This is best reloaded as:
6721                  add t1, r2, #0x400000
6722                  ldr r0, [t1, #-4]
6723
6724          The trick for spotting this for a load insn with N bits of offset
6725          (i.e. bits N-1:0) is to look at bit N; if it is set, then chose a
6726          negative offset that is going to make bit N and all the bits below
6727          it become zero in the remainder part.
6728
6729          The SIGN_MAG_LOW_ADDR_BITS macro below implements this, with respect
6730          to sign-magnitude addressing (i.e. separate +- bit, or 1's complement),
6731          used in most cases of ARM load/store instructions.  */
6732
6733 #define SIGN_MAG_LOW_ADDR_BITS(VAL, N)                                  \
6734       (((VAL) & ((1 << (N)) - 1))                                       \
6735        ? (((VAL) & ((1 << ((N) + 1)) - 1)) ^ (1 << (N))) - (1 << (N))   \
6736        : 0)
6737
6738       if (coproc_p)
6739         {
6740           low = SIGN_MAG_LOW_ADDR_BITS (val, 10);
6741
6742           /* NEON quad-word load/stores are made of two double-word accesses,
6743              so the valid index range is reduced by 8. Treat as 9-bit range if
6744              we go over it.  */
6745           if (TARGET_NEON && VALID_NEON_QREG_MODE (mode) && low >= 1016)
6746             low = SIGN_MAG_LOW_ADDR_BITS (val, 9);
6747         }
6748       else if (GET_MODE_SIZE (mode) == 8)
6749         {
6750           if (TARGET_LDRD)
6751             low = (TARGET_THUMB2
6752                    ? SIGN_MAG_LOW_ADDR_BITS (val, 10)
6753                    : SIGN_MAG_LOW_ADDR_BITS (val, 8));
6754           else
6755             /* For pre-ARMv5TE (without ldrd), we use ldm/stm(db/da/ib)
6756                to access doublewords. The supported load/store offsets are
6757                -8, -4, and 4, which we try to produce here.  */
6758             low = ((val & 0xf) ^ 0x8) - 0x8;
6759         }
6760       else if (GET_MODE_SIZE (mode) < 8)
6761         {
6762           /* NEON element load/stores do not have an offset.  */
6763           if (TARGET_NEON_FP16 && mode == HFmode)
6764             return false;
6765
6766           if (TARGET_THUMB2)
6767             {
6768               /* Thumb-2 has an asymmetrical index range of (-256,4096).
6769                  Try the wider 12-bit range first, and re-try if the result
6770                  is out of range.  */
6771               low = SIGN_MAG_LOW_ADDR_BITS (val, 12);
6772               if (low < -255)
6773                 low = SIGN_MAG_LOW_ADDR_BITS (val, 8);
6774             }
6775           else
6776             {
6777               if (mode == HImode || mode == HFmode)
6778                 {
6779                   if (arm_arch4)
6780                     low = SIGN_MAG_LOW_ADDR_BITS (val, 8);
6781                   else
6782                     {
6783                       /* The storehi/movhi_bytes fallbacks can use only
6784                          [-4094,+4094] of the full ldrb/strb index range.  */
6785                       low = SIGN_MAG_LOW_ADDR_BITS (val, 12);
6786                       if (low == 4095 || low == -4095)
6787                         return false;
6788                     }
6789                 }
6790               else
6791                 low = SIGN_MAG_LOW_ADDR_BITS (val, 12);
6792             }
6793         }
6794       else
6795         return false;
6796
6797       high = ((((val - low) & (unsigned HOST_WIDE_INT) 0xffffffff)
6798                ^ (unsigned HOST_WIDE_INT) 0x80000000)
6799               - (unsigned HOST_WIDE_INT) 0x80000000);
6800       /* Check for overflow or zero */
6801       if (low == 0 || high == 0 || (high + low != val))
6802         return false;
6803
6804       /* Reload the high part into a base reg; leave the low part
6805          in the mem.  */
6806       *p = gen_rtx_PLUS (GET_MODE (*p),
6807                          gen_rtx_PLUS (GET_MODE (*p), XEXP (*p, 0),
6808                                        GEN_INT (high)),
6809                          GEN_INT (low));
6810       push_reload (XEXP (*p, 0), NULL_RTX, &XEXP (*p, 0), NULL,
6811                    MODE_BASE_REG_CLASS (mode), GET_MODE (*p),
6812                    VOIDmode, 0, 0, opnum, (enum reload_type) type);
6813       return true;
6814     }
6815
6816   return false;
6817 }
6818
6819 rtx
6820 thumb_legitimize_reload_address (rtx *x_p,
6821                                  enum machine_mode mode,
6822                                  int opnum, int type,
6823                                  int ind_levels ATTRIBUTE_UNUSED)
6824 {
6825   rtx x = *x_p;
6826
6827   if (GET_CODE (x) == PLUS
6828       && GET_MODE_SIZE (mode) < 4
6829       && REG_P (XEXP (x, 0))
6830       && XEXP (x, 0) == stack_pointer_rtx
6831       && GET_CODE (XEXP (x, 1)) == CONST_INT
6832       && !thumb_legitimate_offset_p (mode, INTVAL (XEXP (x, 1))))
6833     {
6834       rtx orig_x = x;
6835
6836       x = copy_rtx (x);
6837       push_reload (orig_x, NULL_RTX, x_p, NULL, MODE_BASE_REG_CLASS (mode),
6838                    Pmode, VOIDmode, 0, 0, opnum, (enum reload_type) type);
6839       return x;
6840     }
6841
6842   /* If both registers are hi-regs, then it's better to reload the
6843      entire expression rather than each register individually.  That
6844      only requires one reload register rather than two.  */
6845   if (GET_CODE (x) == PLUS
6846       && REG_P (XEXP (x, 0))
6847       && REG_P (XEXP (x, 1))
6848       && !REG_MODE_OK_FOR_REG_BASE_P (XEXP (x, 0), mode)
6849       && !REG_MODE_OK_FOR_REG_BASE_P (XEXP (x, 1), mode))
6850     {
6851       rtx orig_x = x;
6852
6853       x = copy_rtx (x);
6854       push_reload (orig_x, NULL_RTX, x_p, NULL, MODE_BASE_REG_CLASS (mode),
6855                    Pmode, VOIDmode, 0, 0, opnum, (enum reload_type) type);
6856       return x;
6857     }
6858
6859   return NULL;
6860 }
6861
6862 /* Test for various thread-local symbols.  */
6863
6864 /* Return TRUE if X is a thread-local symbol.  */
6865
6866 static bool
6867 arm_tls_symbol_p (rtx x)
6868 {
6869   if (! TARGET_HAVE_TLS)
6870     return false;
6871
6872   if (GET_CODE (x) != SYMBOL_REF)
6873     return false;
6874
6875   return SYMBOL_REF_TLS_MODEL (x) != 0;
6876 }
6877
6878 /* Helper for arm_tls_referenced_p.  */
6879
6880 static int
6881 arm_tls_operand_p_1 (rtx *x, void *data ATTRIBUTE_UNUSED)
6882 {
6883   if (GET_CODE (*x) == SYMBOL_REF)
6884     return SYMBOL_REF_TLS_MODEL (*x) != 0;
6885
6886   /* Don't recurse into UNSPEC_TLS looking for TLS symbols; these are
6887      TLS offsets, not real symbol references.  */
6888   if (GET_CODE (*x) == UNSPEC
6889       && XINT (*x, 1) == UNSPEC_TLS)
6890     return -1;
6891
6892   return 0;
6893 }
6894
6895 /* Return TRUE if X contains any TLS symbol references.  */
6896
6897 bool
6898 arm_tls_referenced_p (rtx x)
6899 {
6900   if (! TARGET_HAVE_TLS)
6901     return false;
6902
6903   return for_each_rtx (&x, arm_tls_operand_p_1, NULL);
6904 }
6905
6906 /* Implement TARGET_LEGITIMATE_CONSTANT_P.
6907
6908    On the ARM, allow any integer (invalid ones are removed later by insn
6909    patterns), nice doubles and symbol_refs which refer to the function's
6910    constant pool XXX.
6911
6912    When generating pic allow anything.  */
6913
6914 static bool
6915 arm_legitimate_constant_p_1 (enum machine_mode mode, rtx x)
6916 {
6917   /* At present, we have no support for Neon structure constants, so forbid
6918      them here.  It might be possible to handle simple cases like 0 and -1
6919      in future.  */
6920   if (TARGET_NEON && VALID_NEON_STRUCT_MODE (mode))
6921     return false;
6922
6923   return flag_pic || !label_mentioned_p (x);
6924 }
6925
6926 static bool
6927 thumb_legitimate_constant_p (enum machine_mode mode ATTRIBUTE_UNUSED, rtx x)
6928 {
6929   return (GET_CODE (x) == CONST_INT
6930           || GET_CODE (x) == CONST_DOUBLE
6931           || CONSTANT_ADDRESS_P (x)
6932           || flag_pic);
6933 }
6934
6935 static bool
6936 arm_legitimate_constant_p (enum machine_mode mode, rtx x)
6937 {
6938   return (!arm_cannot_force_const_mem (mode, x)
6939           && (TARGET_32BIT
6940               ? arm_legitimate_constant_p_1 (mode, x)
6941               : thumb_legitimate_constant_p (mode, x)));
6942 }
6943
6944 /* Implement TARGET_CANNOT_FORCE_CONST_MEM.  */
6945
6946 static bool
6947 arm_cannot_force_const_mem (enum machine_mode mode ATTRIBUTE_UNUSED, rtx x)
6948 {
6949   rtx base, offset;
6950
6951   if (ARM_OFFSETS_MUST_BE_WITHIN_SECTIONS_P)
6952     {
6953       split_const (x, &base, &offset);
6954       if (GET_CODE (base) == SYMBOL_REF
6955           && !offset_within_block_p (base, INTVAL (offset)))
6956         return true;
6957     }
6958   return arm_tls_referenced_p (x);
6959 }
6960 \f
6961 #define REG_OR_SUBREG_REG(X)                                            \
6962   (GET_CODE (X) == REG                                                  \
6963    || (GET_CODE (X) == SUBREG && GET_CODE (SUBREG_REG (X)) == REG))
6964
6965 #define REG_OR_SUBREG_RTX(X)                    \
6966    (GET_CODE (X) == REG ? (X) : SUBREG_REG (X))
6967
6968 static inline int
6969 thumb1_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer)
6970 {
6971   enum machine_mode mode = GET_MODE (x);
6972   int total;
6973
6974   switch (code)
6975     {
6976     case ASHIFT:
6977     case ASHIFTRT:
6978     case LSHIFTRT:
6979     case ROTATERT:
6980     case PLUS:
6981     case MINUS:
6982     case COMPARE:
6983     case NEG:
6984     case NOT:
6985       return COSTS_N_INSNS (1);
6986
6987     case MULT:
6988       if (GET_CODE (XEXP (x, 1)) == CONST_INT)
6989         {
6990           int cycles = 0;
6991           unsigned HOST_WIDE_INT i = INTVAL (XEXP (x, 1));
6992
6993           while (i)
6994             {
6995               i >>= 2;
6996               cycles++;
6997             }
6998           return COSTS_N_INSNS (2) + cycles;
6999         }
7000       return COSTS_N_INSNS (1) + 16;
7001
7002     case SET:
7003       return (COSTS_N_INSNS (1)
7004               + 4 * ((GET_CODE (SET_SRC (x)) == MEM)
7005                      + GET_CODE (SET_DEST (x)) == MEM));
7006
7007     case CONST_INT:
7008       if (outer == SET)
7009         {
7010           if ((unsigned HOST_WIDE_INT) INTVAL (x) < 256)
7011             return 0;
7012           if (thumb_shiftable_const (INTVAL (x)))
7013             return COSTS_N_INSNS (2);
7014           return COSTS_N_INSNS (3);
7015         }
7016       else if ((outer == PLUS || outer == COMPARE)
7017                && INTVAL (x) < 256 && INTVAL (x) > -256)
7018         return 0;
7019       else if ((outer == IOR || outer == XOR || outer == AND)
7020                && INTVAL (x) < 256 && INTVAL (x) >= -256)
7021         return COSTS_N_INSNS (1);
7022       else if (outer == AND)
7023         {
7024           int i;
7025           /* This duplicates the tests in the andsi3 expander.  */
7026           for (i = 9; i <= 31; i++)
7027             if ((((HOST_WIDE_INT) 1) << i) - 1 == INTVAL (x)
7028                 || (((HOST_WIDE_INT) 1) << i) - 1 == ~INTVAL (x))
7029               return COSTS_N_INSNS (2);
7030         }
7031       else if (outer == ASHIFT || outer == ASHIFTRT
7032                || outer == LSHIFTRT)
7033         return 0;
7034       return COSTS_N_INSNS (2);
7035
7036     case CONST:
7037     case CONST_DOUBLE:
7038     case LABEL_REF:
7039     case SYMBOL_REF:
7040       return COSTS_N_INSNS (3);
7041
7042     case UDIV:
7043     case UMOD:
7044     case DIV:
7045     case MOD:
7046       return 100;
7047
7048     case TRUNCATE:
7049       return 99;
7050
7051     case AND:
7052     case XOR:
7053     case IOR:
7054       /* XXX guess.  */
7055       return 8;
7056
7057     case MEM:
7058       /* XXX another guess.  */
7059       /* Memory costs quite a lot for the first word, but subsequent words
7060          load at the equivalent of a single insn each.  */
7061       return (10 + 4 * ((GET_MODE_SIZE (mode) - 1) / UNITS_PER_WORD)
7062               + ((GET_CODE (x) == SYMBOL_REF && CONSTANT_POOL_ADDRESS_P (x))
7063                  ? 4 : 0));
7064
7065     case IF_THEN_ELSE:
7066       /* XXX a guess.  */
7067       if (GET_CODE (XEXP (x, 1)) == PC || GET_CODE (XEXP (x, 2)) == PC)
7068         return 14;
7069       return 2;
7070
7071     case SIGN_EXTEND:
7072     case ZERO_EXTEND:
7073       total = mode == DImode ? COSTS_N_INSNS (1) : 0;
7074       total += thumb1_rtx_costs (XEXP (x, 0), GET_CODE (XEXP (x, 0)), code);
7075
7076       if (mode == SImode)
7077         return total;
7078
7079       if (arm_arch6)
7080         return total + COSTS_N_INSNS (1);
7081
7082       /* Assume a two-shift sequence.  Increase the cost slightly so
7083          we prefer actual shifts over an extend operation.  */
7084       return total + 1 + COSTS_N_INSNS (2);
7085
7086     default:
7087       return 99;
7088     }
7089 }
7090
7091 static inline bool
7092 arm_rtx_costs_1 (rtx x, enum rtx_code outer, int* total, bool speed)
7093 {
7094   enum machine_mode mode = GET_MODE (x);
7095   enum rtx_code subcode;
7096   rtx operand;
7097   enum rtx_code code = GET_CODE (x);
7098   *total = 0;
7099
7100   switch (code)
7101     {
7102     case MEM:
7103       /* Memory costs quite a lot for the first word, but subsequent words
7104          load at the equivalent of a single insn each.  */
7105       *total = COSTS_N_INSNS (2 + ARM_NUM_REGS (mode));
7106       return true;
7107
7108     case DIV:
7109     case MOD:
7110     case UDIV:
7111     case UMOD:
7112       if (TARGET_HARD_FLOAT && mode == SFmode)
7113         *total = COSTS_N_INSNS (2);
7114       else if (TARGET_HARD_FLOAT && mode == DFmode && !TARGET_VFP_SINGLE)
7115         *total = COSTS_N_INSNS (4);
7116       else
7117         *total = COSTS_N_INSNS (20);
7118       return false;
7119
7120     case ROTATE:
7121       if (GET_CODE (XEXP (x, 1)) == REG)
7122         *total = COSTS_N_INSNS (1); /* Need to subtract from 32 */
7123       else if (GET_CODE (XEXP (x, 1)) != CONST_INT)
7124         *total = rtx_cost (XEXP (x, 1), code, 1, speed);
7125
7126       /* Fall through */
7127     case ROTATERT:
7128       if (mode != SImode)
7129         {
7130           *total += COSTS_N_INSNS (4);
7131           return true;
7132         }
7133
7134       /* Fall through */
7135     case ASHIFT: case LSHIFTRT: case ASHIFTRT:
7136       *total += rtx_cost (XEXP (x, 0), code, 0, speed);
7137       if (mode == DImode)
7138         {
7139           *total += COSTS_N_INSNS (3);
7140           return true;
7141         }
7142
7143       *total += COSTS_N_INSNS (1);
7144       /* Increase the cost of complex shifts because they aren't any faster,
7145          and reduce dual issue opportunities.  */
7146       if (arm_tune_cortex_a9
7147           && outer != SET && GET_CODE (XEXP (x, 1)) != CONST_INT)
7148         ++*total;
7149
7150       return true;
7151
7152     case MINUS:
7153       if (mode == DImode)
7154         {
7155           *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
7156           if (GET_CODE (XEXP (x, 0)) == CONST_INT
7157               && const_ok_for_arm (INTVAL (XEXP (x, 0))))
7158             {
7159               *total += rtx_cost (XEXP (x, 1), code, 1, speed);
7160               return true;
7161             }
7162
7163           if (GET_CODE (XEXP (x, 1)) == CONST_INT
7164               && const_ok_for_arm (INTVAL (XEXP (x, 1))))
7165             {
7166               *total += rtx_cost (XEXP (x, 0), code, 0, speed);
7167               return true;
7168             }
7169
7170           return false;
7171         }
7172
7173       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
7174         {
7175           if (TARGET_HARD_FLOAT
7176               && (mode == SFmode
7177                   || (mode == DFmode && !TARGET_VFP_SINGLE)))
7178             {
7179               *total = COSTS_N_INSNS (1);
7180               if (GET_CODE (XEXP (x, 0)) == CONST_DOUBLE
7181                   && arm_const_double_rtx (XEXP (x, 0)))
7182                 {
7183                   *total += rtx_cost (XEXP (x, 1), code, 1, speed);
7184                   return true;
7185                 }
7186
7187               if (GET_CODE (XEXP (x, 1)) == CONST_DOUBLE
7188                   && arm_const_double_rtx (XEXP (x, 1)))
7189                 {
7190                   *total += rtx_cost (XEXP (x, 0), code, 0, speed);
7191                   return true;
7192                 }
7193
7194               return false;
7195             }
7196           *total = COSTS_N_INSNS (20);
7197           return false;
7198         }
7199
7200       *total = COSTS_N_INSNS (1);
7201       if (GET_CODE (XEXP (x, 0)) == CONST_INT
7202           && const_ok_for_arm (INTVAL (XEXP (x, 0))))
7203         {
7204           *total += rtx_cost (XEXP (x, 1), code, 1, speed);
7205           return true;
7206         }
7207
7208       subcode = GET_CODE (XEXP (x, 1));
7209       if (subcode == ASHIFT || subcode == ASHIFTRT
7210           || subcode == LSHIFTRT
7211           || subcode == ROTATE || subcode == ROTATERT)
7212         {
7213           *total += rtx_cost (XEXP (x, 0), code, 0, speed);
7214           *total += rtx_cost (XEXP (XEXP (x, 1), 0), subcode, 0, speed);
7215           return true;
7216         }
7217
7218       /* A shift as a part of RSB costs no more than RSB itself.  */
7219       if (GET_CODE (XEXP (x, 0)) == MULT
7220           && power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode))
7221         {
7222           *total += rtx_cost (XEXP (XEXP (x, 0), 0), code, 0, speed);
7223           *total += rtx_cost (XEXP (x, 1), code, 1, speed);
7224           return true;
7225         }
7226
7227       if (subcode == MULT
7228           && power_of_two_operand (XEXP (XEXP (x, 1), 1), SImode))
7229         {
7230           *total += rtx_cost (XEXP (x, 0), code, 0, speed);
7231           *total += rtx_cost (XEXP (XEXP (x, 1), 0), subcode, 0, speed);
7232           return true;
7233         }
7234
7235       if (GET_RTX_CLASS (GET_CODE (XEXP (x, 1))) == RTX_COMPARE
7236           || GET_RTX_CLASS (GET_CODE (XEXP (x, 1))) == RTX_COMM_COMPARE)
7237         {
7238           *total = COSTS_N_INSNS (1) + rtx_cost (XEXP (x, 0), code, 0, speed);
7239           if (GET_CODE (XEXP (XEXP (x, 1), 0)) == REG
7240               && REGNO (XEXP (XEXP (x, 1), 0)) != CC_REGNUM)
7241             *total += COSTS_N_INSNS (1);
7242
7243           return true;
7244         }
7245
7246       /* Fall through */
7247
7248     case PLUS:
7249       if (code == PLUS && arm_arch6 && mode == SImode
7250           && (GET_CODE (XEXP (x, 0)) == ZERO_EXTEND
7251               || GET_CODE (XEXP (x, 0)) == SIGN_EXTEND))
7252         {
7253           *total = COSTS_N_INSNS (1);
7254           *total += rtx_cost (XEXP (XEXP (x, 0), 0), GET_CODE (XEXP (x, 0)),
7255                               0, speed);
7256           *total += rtx_cost (XEXP (x, 1), code, 1, speed);
7257           return true;
7258         }
7259
7260       /* MLA: All arguments must be registers.  We filter out
7261          multiplication by a power of two, so that we fall down into
7262          the code below.  */
7263       if (GET_CODE (XEXP (x, 0)) == MULT
7264           && !power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode))
7265         {
7266           /* The cost comes from the cost of the multiply.  */
7267           return false;
7268         }
7269
7270       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
7271         {
7272           if (TARGET_HARD_FLOAT
7273               && (mode == SFmode
7274                   || (mode == DFmode && !TARGET_VFP_SINGLE)))
7275             {
7276               *total = COSTS_N_INSNS (1);
7277               if (GET_CODE (XEXP (x, 1)) == CONST_DOUBLE
7278                   && arm_const_double_rtx (XEXP (x, 1)))
7279                 {
7280                   *total += rtx_cost (XEXP (x, 0), code, 0, speed);
7281                   return true;
7282                 }
7283
7284               return false;
7285             }
7286
7287           *total = COSTS_N_INSNS (20);
7288           return false;
7289         }
7290
7291       if (GET_RTX_CLASS (GET_CODE (XEXP (x, 0))) == RTX_COMPARE
7292           || GET_RTX_CLASS (GET_CODE (XEXP (x, 0))) == RTX_COMM_COMPARE)
7293         {
7294           *total = COSTS_N_INSNS (1) + rtx_cost (XEXP (x, 1), code, 1, speed);
7295           if (GET_CODE (XEXP (XEXP (x, 0), 0)) == REG
7296               && REGNO (XEXP (XEXP (x, 0), 0)) != CC_REGNUM)
7297             *total += COSTS_N_INSNS (1);
7298           return true;
7299         }
7300
7301       /* Fall through */
7302
7303     case AND: case XOR: case IOR:
7304
7305       /* Normally the frame registers will be spilt into reg+const during
7306          reload, so it is a bad idea to combine them with other instructions,
7307          since then they might not be moved outside of loops.  As a compromise
7308          we allow integration with ops that have a constant as their second
7309          operand.  */
7310       if (REG_OR_SUBREG_REG (XEXP (x, 0))
7311           && ARM_FRAME_RTX (REG_OR_SUBREG_RTX (XEXP (x, 0)))
7312           && GET_CODE (XEXP (x, 1)) != CONST_INT)
7313         *total = COSTS_N_INSNS (1);
7314
7315       if (mode == DImode)
7316         {
7317           *total += COSTS_N_INSNS (2);
7318           if (GET_CODE (XEXP (x, 1)) == CONST_INT
7319               && const_ok_for_op (INTVAL (XEXP (x, 1)), code))
7320             {
7321               *total += rtx_cost (XEXP (x, 0), code, 0, speed);
7322               return true;
7323             }
7324
7325           return false;
7326         }
7327
7328       *total += COSTS_N_INSNS (1);
7329       if (GET_CODE (XEXP (x, 1)) == CONST_INT
7330           && const_ok_for_op (INTVAL (XEXP (x, 1)), code))
7331         {
7332           *total += rtx_cost (XEXP (x, 0), code, 0, speed);
7333           return true;
7334         }
7335       subcode = GET_CODE (XEXP (x, 0));
7336       if (subcode == ASHIFT || subcode == ASHIFTRT
7337           || subcode == LSHIFTRT
7338           || subcode == ROTATE || subcode == ROTATERT)
7339         {
7340           *total += rtx_cost (XEXP (x, 1), code, 1, speed);
7341           *total += rtx_cost (XEXP (XEXP (x, 0), 0), subcode, 0, speed);
7342           return true;
7343         }
7344
7345       if (subcode == MULT
7346           && power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode))
7347         {
7348           *total += rtx_cost (XEXP (x, 1), code, 1, speed);
7349           *total += rtx_cost (XEXP (XEXP (x, 0), 0), subcode, 0, speed);
7350           return true;
7351         }
7352
7353       if (subcode == UMIN || subcode == UMAX
7354           || subcode == SMIN || subcode == SMAX)
7355         {
7356           *total = COSTS_N_INSNS (3);
7357           return true;
7358         }
7359
7360       return false;
7361
7362     case MULT:
7363       /* This should have been handled by the CPU specific routines.  */
7364       gcc_unreachable ();
7365
7366     case TRUNCATE:
7367       if (arm_arch3m && mode == SImode
7368           && GET_CODE (XEXP (x, 0)) == LSHIFTRT
7369           && GET_CODE (XEXP (XEXP (x, 0), 0)) == MULT
7370           && (GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 0))
7371               == GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 1)))
7372           && (GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 0)) == ZERO_EXTEND
7373               || GET_CODE (XEXP (XEXP (XEXP (x, 0), 0), 0)) == SIGN_EXTEND))
7374         {
7375           *total = rtx_cost (XEXP (XEXP (x, 0), 0), LSHIFTRT, 0, speed);
7376           return true;
7377         }
7378       *total = COSTS_N_INSNS (2); /* Plus the cost of the MULT */
7379       return false;
7380
7381     case NEG:
7382       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
7383         {
7384           if (TARGET_HARD_FLOAT
7385               && (mode == SFmode
7386                   || (mode == DFmode && !TARGET_VFP_SINGLE)))
7387             {
7388               *total = COSTS_N_INSNS (1);
7389               return false;
7390             }
7391           *total = COSTS_N_INSNS (2);
7392           return false;
7393         }
7394
7395       /* Fall through */
7396     case NOT:
7397       *total = COSTS_N_INSNS (ARM_NUM_REGS(mode));
7398       if (mode == SImode && code == NOT)
7399         {
7400           subcode = GET_CODE (XEXP (x, 0));
7401           if (subcode == ASHIFT || subcode == ASHIFTRT
7402               || subcode == LSHIFTRT
7403               || subcode == ROTATE || subcode == ROTATERT
7404               || (subcode == MULT
7405                   && power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode)))
7406             {
7407               *total += rtx_cost (XEXP (XEXP (x, 0), 0), subcode, 0, speed);
7408               /* Register shifts cost an extra cycle.  */
7409               if (GET_CODE (XEXP (XEXP (x, 0), 1)) != CONST_INT)
7410                 *total += COSTS_N_INSNS (1) + rtx_cost (XEXP (XEXP (x, 0), 1),
7411                                                         subcode, 1, speed);
7412               return true;
7413             }
7414         }
7415
7416       return false;
7417
7418     case IF_THEN_ELSE:
7419       if (GET_CODE (XEXP (x, 1)) == PC || GET_CODE (XEXP (x, 2)) == PC)
7420         {
7421           *total = COSTS_N_INSNS (4);
7422           return true;
7423         }
7424
7425       operand = XEXP (x, 0);
7426
7427       if (!((GET_RTX_CLASS (GET_CODE (operand)) == RTX_COMPARE
7428              || GET_RTX_CLASS (GET_CODE (operand)) == RTX_COMM_COMPARE)
7429             && GET_CODE (XEXP (operand, 0)) == REG
7430             && REGNO (XEXP (operand, 0)) == CC_REGNUM))
7431         *total += COSTS_N_INSNS (1);
7432       *total += (rtx_cost (XEXP (x, 1), code, 1, speed)
7433                  + rtx_cost (XEXP (x, 2), code, 2, speed));
7434       return true;
7435
7436     case NE:
7437       if (mode == SImode && XEXP (x, 1) == const0_rtx)
7438         {
7439           *total = COSTS_N_INSNS (2) + rtx_cost (XEXP (x, 0), code, 0, speed);
7440           return true;
7441         }
7442       goto scc_insn;
7443
7444     case GE:
7445       if ((GET_CODE (XEXP (x, 0)) != REG || REGNO (XEXP (x, 0)) != CC_REGNUM)
7446           && mode == SImode && XEXP (x, 1) == const0_rtx)
7447         {
7448           *total = COSTS_N_INSNS (2) + rtx_cost (XEXP (x, 0), code, 0, speed);
7449           return true;
7450         }
7451       goto scc_insn;
7452
7453     case LT:
7454       if ((GET_CODE (XEXP (x, 0)) != REG || REGNO (XEXP (x, 0)) != CC_REGNUM)
7455           && mode == SImode && XEXP (x, 1) == const0_rtx)
7456         {
7457           *total = COSTS_N_INSNS (1) + rtx_cost (XEXP (x, 0), code, 0, speed);
7458           return true;
7459         }
7460       goto scc_insn;
7461
7462     case EQ:
7463     case GT:
7464     case LE:
7465     case GEU:
7466     case LTU:
7467     case GTU:
7468     case LEU:
7469     case UNORDERED:
7470     case ORDERED:
7471     case UNEQ:
7472     case UNGE:
7473     case UNLT:
7474     case UNGT:
7475     case UNLE:
7476     scc_insn:
7477       /* SCC insns.  In the case where the comparison has already been
7478          performed, then they cost 2 instructions.  Otherwise they need
7479          an additional comparison before them.  */
7480       *total = COSTS_N_INSNS (2);
7481       if (GET_CODE (XEXP (x, 0)) == REG && REGNO (XEXP (x, 0)) == CC_REGNUM)
7482         {
7483           return true;
7484         }
7485
7486       /* Fall through */
7487     case COMPARE:
7488       if (GET_CODE (XEXP (x, 0)) == REG && REGNO (XEXP (x, 0)) == CC_REGNUM)
7489         {
7490           *total = 0;
7491           return true;
7492         }
7493
7494       *total += COSTS_N_INSNS (1);
7495       if (GET_CODE (XEXP (x, 1)) == CONST_INT
7496           && const_ok_for_op (INTVAL (XEXP (x, 1)), code))
7497         {
7498           *total += rtx_cost (XEXP (x, 0), code, 0, speed);
7499           return true;
7500         }
7501
7502       subcode = GET_CODE (XEXP (x, 0));
7503       if (subcode == ASHIFT || subcode == ASHIFTRT
7504           || subcode == LSHIFTRT
7505           || subcode == ROTATE || subcode == ROTATERT)
7506         {
7507           *total += rtx_cost (XEXP (x, 1), code, 1, speed);
7508           *total += rtx_cost (XEXP (XEXP (x, 0), 0), subcode, 0, speed);
7509           return true;
7510         }
7511
7512       if (subcode == MULT
7513           && power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode))
7514         {
7515           *total += rtx_cost (XEXP (x, 1), code, 1, speed);
7516           *total += rtx_cost (XEXP (XEXP (x, 0), 0), subcode, 0, speed);
7517           return true;
7518         }
7519
7520       return false;
7521
7522     case UMIN:
7523     case UMAX:
7524     case SMIN:
7525     case SMAX:
7526       *total = COSTS_N_INSNS (2) + rtx_cost (XEXP (x, 0), code, 0, speed);
7527       if (GET_CODE (XEXP (x, 1)) != CONST_INT
7528           || !const_ok_for_arm (INTVAL (XEXP (x, 1))))
7529         *total += rtx_cost (XEXP (x, 1), code, 1, speed);
7530       return true;
7531
7532     case ABS:
7533       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
7534         {
7535           if (TARGET_HARD_FLOAT
7536               && (mode == SFmode
7537                   || (mode == DFmode && !TARGET_VFP_SINGLE)))
7538             {
7539               *total = COSTS_N_INSNS (1);
7540               return false;
7541             }
7542           *total = COSTS_N_INSNS (20);
7543           return false;
7544         }
7545       *total = COSTS_N_INSNS (1);
7546       if (mode == DImode)
7547         *total += COSTS_N_INSNS (3);
7548       return false;
7549
7550     case SIGN_EXTEND:
7551     case ZERO_EXTEND:
7552       *total = 0;
7553       if (GET_MODE_CLASS (mode) == MODE_INT)
7554         {
7555           rtx op = XEXP (x, 0);
7556           enum machine_mode opmode = GET_MODE (op);
7557
7558           if (mode == DImode)
7559             *total += COSTS_N_INSNS (1);
7560
7561           if (opmode != SImode)
7562             {
7563               if (MEM_P (op))
7564                 {
7565                   /* If !arm_arch4, we use one of the extendhisi2_mem
7566                      or movhi_bytes patterns for HImode.  For a QImode
7567                      sign extension, we first zero-extend from memory
7568                      and then perform a shift sequence.  */
7569                   if (!arm_arch4 && (opmode != QImode || code == SIGN_EXTEND))
7570                     *total += COSTS_N_INSNS (2);
7571                 }
7572               else if (arm_arch6)
7573                 *total += COSTS_N_INSNS (1);
7574
7575               /* We don't have the necessary insn, so we need to perform some
7576                  other operation.  */
7577               else if (TARGET_ARM && code == ZERO_EXTEND && mode == QImode)
7578                 /* An and with constant 255.  */
7579                 *total += COSTS_N_INSNS (1);
7580               else
7581                 /* A shift sequence.  Increase costs slightly to avoid
7582                    combining two shifts into an extend operation.  */
7583                 *total += COSTS_N_INSNS (2) + 1;
7584             }
7585
7586           return false;
7587         }
7588
7589       switch (GET_MODE (XEXP (x, 0)))
7590         {
7591         case V8QImode:
7592         case V4HImode:
7593         case V2SImode:
7594         case V4QImode:
7595         case V2HImode:
7596           *total = COSTS_N_INSNS (1);
7597           return false;
7598
7599         default:
7600           gcc_unreachable ();
7601         }
7602       gcc_unreachable ();
7603
7604     case ZERO_EXTRACT:
7605     case SIGN_EXTRACT:
7606       *total = COSTS_N_INSNS (1) + rtx_cost (XEXP (x, 0), code, 0, speed);
7607       return true;
7608
7609     case CONST_INT:
7610       if (const_ok_for_arm (INTVAL (x))
7611           || const_ok_for_arm (~INTVAL (x)))
7612         *total = COSTS_N_INSNS (1);
7613       else
7614         *total = COSTS_N_INSNS (arm_gen_constant (SET, mode, NULL_RTX,
7615                                                   INTVAL (x), NULL_RTX,
7616                                                   NULL_RTX, 0, 0));
7617       return true;
7618
7619     case CONST:
7620     case LABEL_REF:
7621     case SYMBOL_REF:
7622       *total = COSTS_N_INSNS (3);
7623       return true;
7624
7625     case HIGH:
7626       *total = COSTS_N_INSNS (1);
7627       return true;
7628
7629     case LO_SUM:
7630       *total = COSTS_N_INSNS (1);
7631       *total += rtx_cost (XEXP (x, 0), code, 0, speed);
7632       return true;
7633
7634     case CONST_DOUBLE:
7635       if (TARGET_HARD_FLOAT && vfp3_const_double_rtx (x)
7636           && (mode == SFmode || !TARGET_VFP_SINGLE))
7637         *total = COSTS_N_INSNS (1);
7638       else
7639         *total = COSTS_N_INSNS (4);
7640       return true;
7641
7642     case SET:
7643       return false;
7644
7645     default:
7646       *total = COSTS_N_INSNS (4);
7647       return false;
7648     }
7649 }
7650
7651 /* Estimates the size cost of thumb1 instructions.
7652    For now most of the code is copied from thumb1_rtx_costs. We need more
7653    fine grain tuning when we have more related test cases.  */
7654 static inline int
7655 thumb1_size_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer)
7656 {
7657   enum machine_mode mode = GET_MODE (x);
7658
7659   switch (code)
7660     {
7661     case ASHIFT:
7662     case ASHIFTRT:
7663     case LSHIFTRT:
7664     case ROTATERT:
7665     case PLUS:
7666     case MINUS:
7667     case COMPARE:
7668     case NEG:
7669     case NOT:
7670       return COSTS_N_INSNS (1);
7671
7672     case MULT:
7673       if (GET_CODE (XEXP (x, 1)) == CONST_INT)
7674         {
7675           /* Thumb1 mul instruction can't operate on const. We must Load it
7676              into a register first.  */
7677           int const_size = thumb1_size_rtx_costs (XEXP (x, 1), CONST_INT, SET);
7678           return COSTS_N_INSNS (1) + const_size;
7679         }
7680       return COSTS_N_INSNS (1);
7681
7682     case SET:
7683       return (COSTS_N_INSNS (1)
7684               + 4 * ((GET_CODE (SET_SRC (x)) == MEM)
7685                      + GET_CODE (SET_DEST (x)) == MEM));
7686
7687     case CONST_INT:
7688       if (outer == SET)
7689         {
7690           if ((unsigned HOST_WIDE_INT) INTVAL (x) < 256)
7691             return COSTS_N_INSNS (1);
7692           /* See split "TARGET_THUMB1 && satisfies_constraint_J".  */
7693           if (INTVAL (x) >= -255 && INTVAL (x) <= -1)
7694             return COSTS_N_INSNS (2);
7695           /* See split "TARGET_THUMB1 && satisfies_constraint_K".  */
7696           if (thumb_shiftable_const (INTVAL (x)))
7697             return COSTS_N_INSNS (2);
7698           return COSTS_N_INSNS (3);
7699         }
7700       else if ((outer == PLUS || outer == COMPARE)
7701                && INTVAL (x) < 256 && INTVAL (x) > -256)
7702         return 0;
7703       else if ((outer == IOR || outer == XOR || outer == AND)
7704                && INTVAL (x) < 256 && INTVAL (x) >= -256)
7705         return COSTS_N_INSNS (1);
7706       else if (outer == AND)
7707         {
7708           int i;
7709           /* This duplicates the tests in the andsi3 expander.  */
7710           for (i = 9; i <= 31; i++)
7711             if ((((HOST_WIDE_INT) 1) << i) - 1 == INTVAL (x)
7712                 || (((HOST_WIDE_INT) 1) << i) - 1 == ~INTVAL (x))
7713               return COSTS_N_INSNS (2);
7714         }
7715       else if (outer == ASHIFT || outer == ASHIFTRT
7716                || outer == LSHIFTRT)
7717         return 0;
7718       return COSTS_N_INSNS (2);
7719
7720     case CONST:
7721     case CONST_DOUBLE:
7722     case LABEL_REF:
7723     case SYMBOL_REF:
7724       return COSTS_N_INSNS (3);
7725
7726     case UDIV:
7727     case UMOD:
7728     case DIV:
7729     case MOD:
7730       return 100;
7731
7732     case TRUNCATE:
7733       return 99;
7734
7735     case AND:
7736     case XOR:
7737     case IOR:
7738       /* XXX guess.  */
7739       return 8;
7740
7741     case MEM:
7742       /* XXX another guess.  */
7743       /* Memory costs quite a lot for the first word, but subsequent words
7744          load at the equivalent of a single insn each.  */
7745       return (10 + 4 * ((GET_MODE_SIZE (mode) - 1) / UNITS_PER_WORD)
7746               + ((GET_CODE (x) == SYMBOL_REF && CONSTANT_POOL_ADDRESS_P (x))
7747                  ? 4 : 0));
7748
7749     case IF_THEN_ELSE:
7750       /* XXX a guess.  */
7751       if (GET_CODE (XEXP (x, 1)) == PC || GET_CODE (XEXP (x, 2)) == PC)
7752         return 14;
7753       return 2;
7754
7755     case ZERO_EXTEND:
7756       /* XXX still guessing.  */
7757       switch (GET_MODE (XEXP (x, 0)))
7758         {
7759           case QImode:
7760             return (1 + (mode == DImode ? 4 : 0)
7761                     + (GET_CODE (XEXP (x, 0)) == MEM ? 10 : 0));
7762
7763           case HImode:
7764             return (4 + (mode == DImode ? 4 : 0)
7765                     + (GET_CODE (XEXP (x, 0)) == MEM ? 10 : 0));
7766
7767           case SImode:
7768             return (1 + (GET_CODE (XEXP (x, 0)) == MEM ? 10 : 0));
7769
7770           default:
7771             return 99;
7772         }
7773
7774     default:
7775       return 99;
7776     }
7777 }
7778
7779 /* RTX costs when optimizing for size.  */
7780 static bool
7781 arm_size_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer_code,
7782                     int *total)
7783 {
7784   enum machine_mode mode = GET_MODE (x);
7785   if (TARGET_THUMB1)
7786     {
7787       *total = thumb1_size_rtx_costs (x, code, outer_code);
7788       return true;
7789     }
7790
7791   /* FIXME: This makes no attempt to prefer narrow Thumb-2 instructions.  */
7792   switch (code)
7793     {
7794     case MEM:
7795       /* A memory access costs 1 insn if the mode is small, or the address is
7796          a single register, otherwise it costs one insn per word.  */
7797       if (REG_P (XEXP (x, 0)))
7798         *total = COSTS_N_INSNS (1);
7799       else if (flag_pic
7800                && GET_CODE (XEXP (x, 0)) == PLUS
7801                && will_be_in_index_register (XEXP (XEXP (x, 0), 1)))
7802         /* This will be split into two instructions.
7803            See arm.md:calculate_pic_address.  */
7804         *total = COSTS_N_INSNS (2);
7805       else
7806         *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
7807       return true;
7808
7809     case DIV:
7810     case MOD:
7811     case UDIV:
7812     case UMOD:
7813       /* Needs a libcall, so it costs about this.  */
7814       *total = COSTS_N_INSNS (2);
7815       return false;
7816
7817     case ROTATE:
7818       if (mode == SImode && GET_CODE (XEXP (x, 1)) == REG)
7819         {
7820           *total = COSTS_N_INSNS (2) + rtx_cost (XEXP (x, 0), code, 0, false);
7821           return true;
7822         }
7823       /* Fall through */
7824     case ROTATERT:
7825     case ASHIFT:
7826     case LSHIFTRT:
7827     case ASHIFTRT:
7828       if (mode == DImode && GET_CODE (XEXP (x, 1)) == CONST_INT)
7829         {
7830           *total = COSTS_N_INSNS (3) + rtx_cost (XEXP (x, 0), code, 0, false);
7831           return true;
7832         }
7833       else if (mode == SImode)
7834         {
7835           *total = COSTS_N_INSNS (1) + rtx_cost (XEXP (x, 0), code, 0, false);
7836           /* Slightly disparage register shifts, but not by much.  */
7837           if (GET_CODE (XEXP (x, 1)) != CONST_INT)
7838             *total += 1 + rtx_cost (XEXP (x, 1), code, 1, false);
7839           return true;
7840         }
7841
7842       /* Needs a libcall.  */
7843       *total = COSTS_N_INSNS (2);
7844       return false;
7845
7846     case MINUS:
7847       if (TARGET_HARD_FLOAT && GET_MODE_CLASS (mode) == MODE_FLOAT
7848           && (mode == SFmode || !TARGET_VFP_SINGLE))
7849         {
7850           *total = COSTS_N_INSNS (1);
7851           return false;
7852         }
7853
7854       if (mode == SImode)
7855         {
7856           enum rtx_code subcode0 = GET_CODE (XEXP (x, 0));
7857           enum rtx_code subcode1 = GET_CODE (XEXP (x, 1));
7858
7859           if (subcode0 == ROTATE || subcode0 == ROTATERT || subcode0 == ASHIFT
7860               || subcode0 == LSHIFTRT || subcode0 == ASHIFTRT
7861               || subcode1 == ROTATE || subcode1 == ROTATERT
7862               || subcode1 == ASHIFT || subcode1 == LSHIFTRT
7863               || subcode1 == ASHIFTRT)
7864             {
7865               /* It's just the cost of the two operands.  */
7866               *total = 0;
7867               return false;
7868             }
7869
7870           *total = COSTS_N_INSNS (1);
7871           return false;
7872         }
7873
7874       *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
7875       return false;
7876
7877     case PLUS:
7878       if (TARGET_HARD_FLOAT && GET_MODE_CLASS (mode) == MODE_FLOAT
7879           && (mode == SFmode || !TARGET_VFP_SINGLE))
7880         {
7881           *total = COSTS_N_INSNS (1);
7882           return false;
7883         }
7884
7885       /* A shift as a part of ADD costs nothing.  */
7886       if (GET_CODE (XEXP (x, 0)) == MULT
7887           && power_of_two_operand (XEXP (XEXP (x, 0), 1), SImode))
7888         {
7889           *total = COSTS_N_INSNS (TARGET_THUMB2 ? 2 : 1);
7890           *total += rtx_cost (XEXP (XEXP (x, 0), 0), code, 0, false);
7891           *total += rtx_cost (XEXP (x, 1), code, 1, false);
7892           return true;
7893         }
7894
7895       /* Fall through */
7896     case AND: case XOR: case IOR:
7897       if (mode == SImode)
7898         {
7899           enum rtx_code subcode = GET_CODE (XEXP (x, 0));
7900
7901           if (subcode == ROTATE || subcode == ROTATERT || subcode == ASHIFT
7902               || subcode == LSHIFTRT || subcode == ASHIFTRT
7903               || (code == AND && subcode == NOT))
7904             {
7905               /* It's just the cost of the two operands.  */
7906               *total = 0;
7907               return false;
7908             }
7909         }
7910
7911       *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
7912       return false;
7913
7914     case MULT:
7915       *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
7916       return false;
7917
7918     case NEG:
7919       if (TARGET_HARD_FLOAT && GET_MODE_CLASS (mode) == MODE_FLOAT
7920           && (mode == SFmode || !TARGET_VFP_SINGLE))
7921         {
7922           *total = COSTS_N_INSNS (1);
7923           return false;
7924         }
7925
7926       /* Fall through */
7927     case NOT:
7928       *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
7929
7930       return false;
7931
7932     case IF_THEN_ELSE:
7933       *total = 0;
7934       return false;
7935
7936     case COMPARE:
7937       if (cc_register (XEXP (x, 0), VOIDmode))
7938         * total = 0;
7939       else
7940         *total = COSTS_N_INSNS (1);
7941       return false;
7942
7943     case ABS:
7944       if (TARGET_HARD_FLOAT && GET_MODE_CLASS (mode) == MODE_FLOAT
7945           && (mode == SFmode || !TARGET_VFP_SINGLE))
7946         *total = COSTS_N_INSNS (1);
7947       else
7948         *total = COSTS_N_INSNS (1 + ARM_NUM_REGS (mode));
7949       return false;
7950
7951     case SIGN_EXTEND:
7952     case ZERO_EXTEND:
7953       return arm_rtx_costs_1 (x, outer_code, total, 0);
7954
7955     case CONST_INT:
7956       if (const_ok_for_arm (INTVAL (x)))
7957         /* A multiplication by a constant requires another instruction
7958            to load the constant to a register.  */
7959         *total = COSTS_N_INSNS ((outer_code == SET || outer_code == MULT)
7960                                 ? 1 : 0);
7961       else if (const_ok_for_arm (~INTVAL (x)))
7962         *total = COSTS_N_INSNS (outer_code == AND ? 0 : 1);
7963       else if (const_ok_for_arm (-INTVAL (x)))
7964         {
7965           if (outer_code == COMPARE || outer_code == PLUS
7966               || outer_code == MINUS)
7967             *total = 0;
7968           else
7969             *total = COSTS_N_INSNS (1);
7970         }
7971       else
7972         *total = COSTS_N_INSNS (2);
7973       return true;
7974
7975     case CONST:
7976     case LABEL_REF:
7977     case SYMBOL_REF:
7978       *total = COSTS_N_INSNS (2);
7979       return true;
7980
7981     case CONST_DOUBLE:
7982       *total = COSTS_N_INSNS (4);
7983       return true;
7984
7985     case HIGH:
7986     case LO_SUM:
7987       /* We prefer constant pool entries to MOVW/MOVT pairs, so bump the
7988          cost of these slightly.  */
7989       *total = COSTS_N_INSNS (1) + 1;
7990       return true;
7991
7992     case SET:
7993       return false;
7994
7995     default:
7996       if (mode != VOIDmode)
7997         *total = COSTS_N_INSNS (ARM_NUM_REGS (mode));
7998       else
7999         *total = COSTS_N_INSNS (4); /* How knows?  */
8000       return false;
8001     }
8002 }
8003
8004 /* RTX costs when optimizing for size.  */
8005 static bool
8006 arm_rtx_costs (rtx x, int code, int outer_code, int opno ATTRIBUTE_UNUSED,
8007                int *total, bool speed)
8008 {
8009   if (!speed)
8010     return arm_size_rtx_costs (x, (enum rtx_code) code,
8011                                (enum rtx_code) outer_code, total);
8012   else
8013     return current_tune->rtx_costs (x, (enum rtx_code) code,
8014                                     (enum rtx_code) outer_code,
8015                                     total, speed);
8016 }
8017
8018 /* RTX costs for cores with a slow MUL implementation.  Thumb-2 is not
8019    supported on any "slowmul" cores, so it can be ignored.  */
8020
8021 static bool
8022 arm_slowmul_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer_code,
8023                        int *total, bool speed)
8024 {
8025   enum machine_mode mode = GET_MODE (x);
8026
8027   if (TARGET_THUMB)
8028     {
8029       *total = thumb1_rtx_costs (x, code, outer_code);
8030       return true;
8031     }
8032
8033   switch (code)
8034     {
8035     case MULT:
8036       if (GET_MODE_CLASS (mode) == MODE_FLOAT
8037           || mode == DImode)
8038         {
8039           *total = COSTS_N_INSNS (20);
8040           return false;
8041         }
8042
8043       if (GET_CODE (XEXP (x, 1)) == CONST_INT)
8044         {
8045           unsigned HOST_WIDE_INT i = (INTVAL (XEXP (x, 1))
8046                                       & (unsigned HOST_WIDE_INT) 0xffffffff);
8047           int cost, const_ok = const_ok_for_arm (i);
8048           int j, booth_unit_size;
8049
8050           /* Tune as appropriate.  */
8051           cost = const_ok ? 4 : 8;
8052           booth_unit_size = 2;
8053           for (j = 0; i && j < 32; j += booth_unit_size)
8054             {
8055               i >>= booth_unit_size;
8056               cost++;
8057             }
8058
8059           *total = COSTS_N_INSNS (cost);
8060           *total += rtx_cost (XEXP (x, 0), code, 0, speed);
8061           return true;
8062         }
8063
8064       *total = COSTS_N_INSNS (20);
8065       return false;
8066
8067     default:
8068       return arm_rtx_costs_1 (x, outer_code, total, speed);;
8069     }
8070 }
8071
8072
8073 /* RTX cost for cores with a fast multiply unit (M variants).  */
8074
8075 static bool
8076 arm_fastmul_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer_code,
8077                        int *total, bool speed)
8078 {
8079   enum machine_mode mode = GET_MODE (x);
8080
8081   if (TARGET_THUMB1)
8082     {
8083       *total = thumb1_rtx_costs (x, code, outer_code);
8084       return true;
8085     }
8086
8087   /* ??? should thumb2 use different costs?  */
8088   switch (code)
8089     {
8090     case MULT:
8091       /* There is no point basing this on the tuning, since it is always the
8092          fast variant if it exists at all.  */
8093       if (mode == DImode
8094           && (GET_CODE (XEXP (x, 0)) == GET_CODE (XEXP (x, 1)))
8095           && (GET_CODE (XEXP (x, 0)) == ZERO_EXTEND
8096               || GET_CODE (XEXP (x, 0)) == SIGN_EXTEND))
8097         {
8098           *total = COSTS_N_INSNS(2);
8099           return false;
8100         }
8101
8102
8103       if (mode == DImode)
8104         {
8105           *total = COSTS_N_INSNS (5);
8106           return false;
8107         }
8108
8109       if (GET_CODE (XEXP (x, 1)) == CONST_INT)
8110         {
8111           unsigned HOST_WIDE_INT i = (INTVAL (XEXP (x, 1))
8112                                       & (unsigned HOST_WIDE_INT) 0xffffffff);
8113           int cost, const_ok = const_ok_for_arm (i);
8114           int j, booth_unit_size;
8115
8116           /* Tune as appropriate.  */
8117           cost = const_ok ? 4 : 8;
8118           booth_unit_size = 8;
8119           for (j = 0; i && j < 32; j += booth_unit_size)
8120             {
8121               i >>= booth_unit_size;
8122               cost++;
8123             }
8124
8125           *total = COSTS_N_INSNS(cost);
8126           return false;
8127         }
8128
8129       if (mode == SImode)
8130         {
8131           *total = COSTS_N_INSNS (4);
8132           return false;
8133         }
8134
8135       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
8136         {
8137           if (TARGET_HARD_FLOAT
8138               && (mode == SFmode
8139                   || (mode == DFmode && !TARGET_VFP_SINGLE)))
8140             {
8141               *total = COSTS_N_INSNS (1);
8142               return false;
8143             }
8144         }
8145
8146       /* Requires a lib call */
8147       *total = COSTS_N_INSNS (20);
8148       return false;
8149
8150     default:
8151       return arm_rtx_costs_1 (x, outer_code, total, speed);
8152     }
8153 }
8154
8155
8156 /* RTX cost for XScale CPUs.  Thumb-2 is not supported on any xscale cores,
8157    so it can be ignored.  */
8158
8159 static bool
8160 arm_xscale_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer_code,
8161                       int *total, bool speed)
8162 {
8163   enum machine_mode mode = GET_MODE (x);
8164
8165   if (TARGET_THUMB)
8166     {
8167       *total = thumb1_rtx_costs (x, code, outer_code);
8168       return true;
8169     }
8170
8171   switch (code)
8172     {
8173     case COMPARE:
8174       if (GET_CODE (XEXP (x, 0)) != MULT)
8175         return arm_rtx_costs_1 (x, outer_code, total, speed);
8176
8177       /* A COMPARE of a MULT is slow on XScale; the muls instruction
8178          will stall until the multiplication is complete.  */
8179       *total = COSTS_N_INSNS (3);
8180       return false;
8181
8182     case MULT:
8183       /* There is no point basing this on the tuning, since it is always the
8184          fast variant if it exists at all.  */
8185       if (mode == DImode
8186           && (GET_CODE (XEXP (x, 0)) == GET_CODE (XEXP (x, 1)))
8187           && (GET_CODE (XEXP (x, 0)) == ZERO_EXTEND
8188               || GET_CODE (XEXP (x, 0)) == SIGN_EXTEND))
8189         {
8190           *total = COSTS_N_INSNS (2);
8191           return false;
8192         }
8193
8194
8195       if (mode == DImode)
8196         {
8197           *total = COSTS_N_INSNS (5);
8198           return false;
8199         }
8200
8201       if (GET_CODE (XEXP (x, 1)) == CONST_INT)
8202         {
8203           /* If operand 1 is a constant we can more accurately
8204              calculate the cost of the multiply.  The multiplier can
8205              retire 15 bits on the first cycle and a further 12 on the
8206              second.  We do, of course, have to load the constant into
8207              a register first.  */
8208           unsigned HOST_WIDE_INT i = INTVAL (XEXP (x, 1));
8209           /* There's a general overhead of one cycle.  */
8210           int cost = 1;
8211           unsigned HOST_WIDE_INT masked_const;
8212
8213           if (i & 0x80000000)
8214             i = ~i;
8215
8216           i &= (unsigned HOST_WIDE_INT) 0xffffffff;
8217
8218           masked_const = i & 0xffff8000;
8219           if (masked_const != 0)
8220             {
8221               cost++;
8222               masked_const = i & 0xf8000000;
8223               if (masked_const != 0)
8224                 cost++;
8225             }
8226           *total = COSTS_N_INSNS (cost);
8227           return false;
8228         }
8229
8230       if (mode == SImode)
8231         {
8232           *total = COSTS_N_INSNS (3);
8233           return false;
8234         }
8235
8236       /* Requires a lib call */
8237       *total = COSTS_N_INSNS (20);
8238       return false;
8239
8240     default:
8241       return arm_rtx_costs_1 (x, outer_code, total, speed);
8242     }
8243 }
8244
8245
8246 /* RTX costs for 9e (and later) cores.  */
8247
8248 static bool
8249 arm_9e_rtx_costs (rtx x, enum rtx_code code, enum rtx_code outer_code,
8250                   int *total, bool speed)
8251 {
8252   enum machine_mode mode = GET_MODE (x);
8253
8254   if (TARGET_THUMB1)
8255     {
8256       switch (code)
8257         {
8258         case MULT:
8259           *total = COSTS_N_INSNS (3);
8260           return true;
8261
8262         default:
8263           *total = thumb1_rtx_costs (x, code, outer_code);
8264           return true;
8265         }
8266     }
8267
8268   switch (code)
8269     {
8270     case MULT:
8271       /* There is no point basing this on the tuning, since it is always the
8272          fast variant if it exists at all.  */
8273       if (mode == DImode
8274           && (GET_CODE (XEXP (x, 0)) == GET_CODE (XEXP (x, 1)))
8275           && (GET_CODE (XEXP (x, 0)) == ZERO_EXTEND
8276               || GET_CODE (XEXP (x, 0)) == SIGN_EXTEND))
8277         {
8278           *total = COSTS_N_INSNS (2);
8279           return false;
8280         }
8281
8282
8283       if (mode == DImode)
8284         {
8285           *total = COSTS_N_INSNS (5);
8286           return false;
8287         }
8288
8289       if (mode == SImode)
8290         {
8291           *total = COSTS_N_INSNS (2);
8292           return false;
8293         }
8294
8295       if (GET_MODE_CLASS (mode) == MODE_FLOAT)
8296         {
8297           if (TARGET_HARD_FLOAT
8298               && (mode == SFmode
8299                   || (mode == DFmode && !TARGET_VFP_SINGLE)))
8300             {
8301               *total = COSTS_N_INSNS (1);
8302               return false;
8303             }
8304         }
8305
8306       *total = COSTS_N_INSNS (20);
8307       return false;
8308
8309     default:
8310       return arm_rtx_costs_1 (x, outer_code, total, speed);
8311     }
8312 }
8313 /* All address computations that can be done are free, but rtx cost returns
8314    the same for practically all of them.  So we weight the different types
8315    of address here in the order (most pref first):
8316    PRE/POST_INC/DEC, SHIFT or NON-INT sum, INT sum, REG, MEM or LABEL.  */
8317 static inline int
8318 arm_arm_address_cost (rtx x)
8319 {
8320   enum rtx_code c  = GET_CODE (x);
8321
8322   if (c == PRE_INC || c == PRE_DEC || c == POST_INC || c == POST_DEC)
8323     return 0;
8324   if (c == MEM || c == LABEL_REF || c == SYMBOL_REF)
8325     return 10;
8326
8327   if (c == PLUS)
8328     {
8329       if (GET_CODE (XEXP (x, 1)) == CONST_INT)
8330         return 2;
8331
8332       if (ARITHMETIC_P (XEXP (x, 0)) || ARITHMETIC_P (XEXP (x, 1)))
8333         return 3;
8334
8335       return 4;
8336     }
8337
8338   return 6;
8339 }
8340
8341 static inline int
8342 arm_thumb_address_cost (rtx x)
8343 {
8344   enum rtx_code c  = GET_CODE (x);
8345
8346   if (c == REG)
8347     return 1;
8348   if (c == PLUS
8349       && GET_CODE (XEXP (x, 0)) == REG
8350       && GET_CODE (XEXP (x, 1)) == CONST_INT)
8351     return 1;
8352
8353   return 2;
8354 }
8355
8356 static int
8357 arm_address_cost (rtx x, bool speed ATTRIBUTE_UNUSED)
8358 {
8359   return TARGET_32BIT ? arm_arm_address_cost (x) : arm_thumb_address_cost (x);
8360 }
8361
8362 /* Adjust cost hook for XScale.  */
8363 static bool
8364 xscale_sched_adjust_cost (rtx insn, rtx link, rtx dep, int * cost)
8365 {
8366   /* Some true dependencies can have a higher cost depending
8367      on precisely how certain input operands are used.  */
8368   if (REG_NOTE_KIND(link) == 0
8369       && recog_memoized (insn) >= 0
8370       && recog_memoized (dep) >= 0)
8371     {
8372       int shift_opnum = get_attr_shift (insn);
8373       enum attr_type attr_type = get_attr_type (dep);
8374
8375       /* If nonzero, SHIFT_OPNUM contains the operand number of a shifted
8376          operand for INSN.  If we have a shifted input operand and the
8377          instruction we depend on is another ALU instruction, then we may
8378          have to account for an additional stall.  */
8379       if (shift_opnum != 0
8380           && (attr_type == TYPE_ALU_SHIFT || attr_type == TYPE_ALU_SHIFT_REG))
8381         {
8382           rtx shifted_operand;
8383           int opno;
8384
8385           /* Get the shifted operand.  */
8386           extract_insn (insn);
8387           shifted_operand = recog_data.operand[shift_opnum];
8388
8389           /* Iterate over all the operands in DEP.  If we write an operand
8390              that overlaps with SHIFTED_OPERAND, then we have increase the
8391              cost of this dependency.  */
8392           extract_insn (dep);
8393           preprocess_constraints ();
8394           for (opno = 0; opno < recog_data.n_operands; opno++)
8395             {
8396               /* We can ignore strict inputs.  */
8397               if (recog_data.operand_type[opno] == OP_IN)
8398                 continue;
8399
8400               if (reg_overlap_mentioned_p (recog_data.operand[opno],
8401                                            shifted_operand))
8402                 {
8403                   *cost = 2;
8404                   return false;
8405                 }
8406             }
8407         }
8408     }
8409   return true;
8410 }
8411
8412 /* Adjust cost hook for Cortex A9.  */
8413 static bool
8414 cortex_a9_sched_adjust_cost (rtx insn, rtx link, rtx dep, int * cost)
8415 {
8416   switch (REG_NOTE_KIND (link))
8417     {
8418     case REG_DEP_ANTI:
8419       *cost = 0;
8420       return false;
8421
8422     case REG_DEP_TRUE:
8423     case REG_DEP_OUTPUT:
8424         if (recog_memoized (insn) >= 0
8425             && recog_memoized (dep) >= 0)
8426           {
8427             if (GET_CODE (PATTERN (insn)) == SET)
8428               {
8429                 if (GET_MODE_CLASS
8430                     (GET_MODE (SET_DEST (PATTERN (insn)))) == MODE_FLOAT
8431                   || GET_MODE_CLASS
8432                     (GET_MODE (SET_SRC (PATTERN (insn)))) == MODE_FLOAT)
8433                   {
8434                     enum attr_type attr_type_insn = get_attr_type (insn);
8435                     enum attr_type attr_type_dep = get_attr_type (dep);
8436
8437                     /* By default all dependencies of the form
8438                        s0 = s0 <op> s1
8439                        s0 = s0 <op> s2
8440                        have an extra latency of 1 cycle because
8441                        of the input and output dependency in this
8442                        case. However this gets modeled as an true
8443                        dependency and hence all these checks.  */
8444                     if (REG_P (SET_DEST (PATTERN (insn)))
8445                         && REG_P (SET_DEST (PATTERN (dep)))
8446                         && reg_overlap_mentioned_p (SET_DEST (PATTERN (insn)),
8447                                                     SET_DEST (PATTERN (dep))))
8448                       {
8449                         /* FMACS is a special case where the dependant
8450                            instruction can be issued 3 cycles before
8451                            the normal latency in case of an output
8452                            dependency.  */
8453                         if ((attr_type_insn == TYPE_FMACS
8454                              || attr_type_insn == TYPE_FMACD)
8455                             && (attr_type_dep == TYPE_FMACS
8456                                 || attr_type_dep == TYPE_FMACD))
8457                           {
8458                             if (REG_NOTE_KIND (link) == REG_DEP_OUTPUT)
8459                               *cost = insn_default_latency (dep) - 3;
8460                             else
8461                               *cost = insn_default_latency (dep);
8462                             return false;
8463                           }
8464                         else
8465                           {
8466                             if (REG_NOTE_KIND (link) == REG_DEP_OUTPUT)
8467                               *cost = insn_default_latency (dep) + 1;
8468                             else
8469                               *cost = insn_default_latency (dep);
8470                           }
8471                         return false;
8472                       }
8473                   }
8474               }
8475           }
8476         break;
8477
8478     default:
8479       gcc_unreachable ();
8480     }
8481
8482   return true;
8483 }
8484
8485 /* Adjust cost hook for FA726TE.  */
8486 static bool
8487 fa726te_sched_adjust_cost (rtx insn, rtx link, rtx dep, int * cost)
8488 {
8489   /* For FA726TE, true dependency on CPSR (i.e. set cond followed by predicated)
8490      have penalty of 3.  */
8491   if (REG_NOTE_KIND (link) == REG_DEP_TRUE
8492       && recog_memoized (insn) >= 0
8493       && recog_memoized (dep) >= 0
8494       && get_attr_conds (dep) == CONDS_SET)
8495     {
8496       /* Use of carry (e.g. 64-bit arithmetic) in ALU: 3-cycle latency.  */
8497       if (get_attr_conds (insn) == CONDS_USE
8498           && get_attr_type (insn) != TYPE_BRANCH)
8499         {
8500           *cost = 3;
8501           return false;
8502         }
8503
8504       if (GET_CODE (PATTERN (insn)) == COND_EXEC
8505           || get_attr_conds (insn) == CONDS_USE)
8506         {
8507           *cost = 0;
8508           return false;
8509         }
8510     }
8511
8512   return true;
8513 }
8514
8515 /* Implement TARGET_REGISTER_MOVE_COST.
8516
8517    Moves between FPA_REGS and GENERAL_REGS are two memory insns.
8518    Moves between VFP_REGS and GENERAL_REGS are a single insn, but
8519    it is typically more expensive than a single memory access.  We set
8520    the cost to less than two memory accesses so that floating
8521    point to integer conversion does not go through memory.  */
8522
8523 int
8524 arm_register_move_cost (enum machine_mode mode ATTRIBUTE_UNUSED,
8525                         reg_class_t from, reg_class_t to)
8526 {
8527   if (TARGET_32BIT)
8528     {
8529       if ((from == FPA_REGS && to != FPA_REGS)
8530           || (from != FPA_REGS && to == FPA_REGS))
8531         return 20;
8532       else if ((IS_VFP_CLASS (from) && !IS_VFP_CLASS (to))
8533                || (!IS_VFP_CLASS (from) && IS_VFP_CLASS (to)))
8534         return 15;
8535       else if ((from == IWMMXT_REGS && to != IWMMXT_REGS)
8536                || (from != IWMMXT_REGS && to == IWMMXT_REGS))
8537         return 4;
8538       else if (from == IWMMXT_GR_REGS || to == IWMMXT_GR_REGS)
8539         return 20;
8540       else if ((from == CIRRUS_REGS && to != CIRRUS_REGS)
8541                || (from != CIRRUS_REGS && to == CIRRUS_REGS))
8542         return 20;
8543       else
8544         return 2;
8545     }
8546   else
8547     {
8548       if (from == HI_REGS || to == HI_REGS)
8549         return 4;
8550       else
8551         return 2;
8552     }
8553 }
8554
8555 /* Implement TARGET_MEMORY_MOVE_COST.  */
8556
8557 int
8558 arm_memory_move_cost (enum machine_mode mode, reg_class_t rclass,
8559                       bool in ATTRIBUTE_UNUSED)
8560 {
8561   if (TARGET_32BIT)
8562     return 10;
8563   else
8564     {
8565       if (GET_MODE_SIZE (mode) < 4)
8566         return 8;
8567       else
8568         return ((2 * GET_MODE_SIZE (mode)) * (rclass == LO_REGS ? 1 : 2));
8569     }
8570 }
8571
8572 /* This function implements the target macro TARGET_SCHED_ADJUST_COST.
8573    It corrects the value of COST based on the relationship between
8574    INSN and DEP through the dependence LINK.  It returns the new
8575    value. There is a per-core adjust_cost hook to adjust scheduler costs
8576    and the per-core hook can choose to completely override the generic
8577    adjust_cost function. Only put bits of code into arm_adjust_cost that
8578    are common across all cores.  */
8579 static int
8580 arm_adjust_cost (rtx insn, rtx link, rtx dep, int cost)
8581 {
8582   rtx i_pat, d_pat;
8583
8584  /* When generating Thumb-1 code, we want to place flag-setting operations
8585     close to a conditional branch which depends on them, so that we can
8586     omit the comparison. */
8587   if (TARGET_THUMB1
8588       && REG_NOTE_KIND (link) == 0
8589       && recog_memoized (insn) == CODE_FOR_cbranchsi4_insn
8590       && recog_memoized (dep) >= 0
8591       && get_attr_conds (dep) == CONDS_SET)
8592     return 0;
8593
8594   if (current_tune->sched_adjust_cost != NULL)
8595     {
8596       if (!current_tune->sched_adjust_cost (insn, link, dep, &cost))
8597         return cost;
8598     }
8599
8600   /* XXX This is not strictly true for the FPA.  */
8601   if (REG_NOTE_KIND (link) == REG_DEP_ANTI
8602       || REG_NOTE_KIND (link) == REG_DEP_OUTPUT)
8603     return 0;
8604
8605   /* Call insns don't incur a stall, even if they follow a load.  */
8606   if (REG_NOTE_KIND (link) == 0
8607       && GET_CODE (insn) == CALL_INSN)
8608     return 1;
8609
8610   if ((i_pat = single_set (insn)) != NULL
8611       && GET_CODE (SET_SRC (i_pat)) == MEM
8612       && (d_pat = single_set (dep)) != NULL
8613       && GET_CODE (SET_DEST (d_pat)) == MEM)
8614     {
8615       rtx src_mem = XEXP (SET_SRC (i_pat), 0);
8616       /* This is a load after a store, there is no conflict if the load reads
8617          from a cached area.  Assume that loads from the stack, and from the
8618          constant pool are cached, and that others will miss.  This is a
8619          hack.  */
8620
8621       if ((GET_CODE (src_mem) == SYMBOL_REF
8622            && CONSTANT_POOL_ADDRESS_P (src_mem))
8623           || reg_mentioned_p (stack_pointer_rtx, src_mem)
8624           || reg_mentioned_p (frame_pointer_rtx, src_mem)
8625           || reg_mentioned_p (hard_frame_pointer_rtx, src_mem))
8626         return 1;
8627     }
8628
8629   return cost;
8630 }
8631
8632 static int
8633 arm_default_branch_cost (bool speed_p, bool predictable_p ATTRIBUTE_UNUSED)
8634 {
8635   if (TARGET_32BIT)
8636     return (TARGET_THUMB2 && !speed_p) ? 1 : 4;
8637   else
8638     return (optimize > 0) ? 2 : 0;
8639 }
8640
8641 static int
8642 arm_cortex_a5_branch_cost (bool speed_p, bool predictable_p)
8643 {
8644   return speed_p ? 0 : arm_default_branch_cost (speed_p, predictable_p);
8645 }
8646
8647 static int fp_consts_inited = 0;
8648
8649 /* Only zero is valid for VFP.  Other values are also valid for FPA.  */
8650 static const char * const strings_fp[8] =
8651 {
8652   "0",   "1",   "2",   "3",
8653   "4",   "5",   "0.5", "10"
8654 };
8655
8656 static REAL_VALUE_TYPE values_fp[8];
8657
8658 static void
8659 init_fp_table (void)
8660 {
8661   int i;
8662   REAL_VALUE_TYPE r;
8663
8664   if (TARGET_VFP)
8665     fp_consts_inited = 1;
8666   else
8667     fp_consts_inited = 8;
8668
8669   for (i = 0; i < fp_consts_inited; i++)
8670     {
8671       r = REAL_VALUE_ATOF (strings_fp[i], DFmode);
8672       values_fp[i] = r;
8673     }
8674 }
8675
8676 /* Return TRUE if rtx X is a valid immediate FP constant.  */
8677 int
8678 arm_const_double_rtx (rtx x)
8679 {
8680   REAL_VALUE_TYPE r;
8681   int i;
8682
8683   if (!fp_consts_inited)
8684     init_fp_table ();
8685
8686   REAL_VALUE_FROM_CONST_DOUBLE (r, x);
8687   if (REAL_VALUE_MINUS_ZERO (r))
8688     return 0;
8689
8690   for (i = 0; i < fp_consts_inited; i++)
8691     if (REAL_VALUES_EQUAL (r, values_fp[i]))
8692       return 1;
8693
8694   return 0;
8695 }
8696
8697 /* Return TRUE if rtx X is a valid immediate FPA constant.  */
8698 int
8699 neg_const_double_rtx_ok_for_fpa (rtx x)
8700 {
8701   REAL_VALUE_TYPE r;
8702   int i;
8703
8704   if (!fp_consts_inited)
8705     init_fp_table ();
8706
8707   REAL_VALUE_FROM_CONST_DOUBLE (r, x);
8708   r = real_value_negate (&r);
8709   if (REAL_VALUE_MINUS_ZERO (r))
8710     return 0;
8711
8712   for (i = 0; i < 8; i++)
8713     if (REAL_VALUES_EQUAL (r, values_fp[i]))
8714       return 1;
8715
8716   return 0;
8717 }
8718
8719
8720 /* VFPv3 has a fairly wide range of representable immediates, formed from
8721    "quarter-precision" floating-point values. These can be evaluated using this
8722    formula (with ^ for exponentiation):
8723
8724      -1^s * n * 2^-r
8725
8726    Where 's' is a sign bit (0/1), 'n' and 'r' are integers such that
8727    16 <= n <= 31 and 0 <= r <= 7.
8728
8729    These values are mapped onto an 8-bit integer ABCDEFGH s.t.
8730
8731      - A (most-significant) is the sign bit.
8732      - BCD are the exponent (encoded as r XOR 3).
8733      - EFGH are the mantissa (encoded as n - 16).
8734 */
8735
8736 /* Return an integer index for a VFPv3 immediate operand X suitable for the
8737    fconst[sd] instruction, or -1 if X isn't suitable.  */
8738 static int
8739 vfp3_const_double_index (rtx x)
8740 {
8741   REAL_VALUE_TYPE r, m;
8742   int sign, exponent;
8743   unsigned HOST_WIDE_INT mantissa, mant_hi;
8744   unsigned HOST_WIDE_INT mask;
8745   HOST_WIDE_INT m1, m2;
8746   int point_pos = 2 * HOST_BITS_PER_WIDE_INT - 1;
8747
8748   if (!TARGET_VFP3 || GET_CODE (x) != CONST_DOUBLE)
8749     return -1;
8750
8751   REAL_VALUE_FROM_CONST_DOUBLE (r, x);
8752
8753   /* We can't represent these things, so detect them first.  */
8754   if (REAL_VALUE_ISINF (r) || REAL_VALUE_ISNAN (r) || REAL_VALUE_MINUS_ZERO (r))
8755     return -1;
8756
8757   /* Extract sign, exponent and mantissa.  */
8758   sign = REAL_VALUE_NEGATIVE (r) ? 1 : 0;
8759   r = real_value_abs (&r);
8760   exponent = REAL_EXP (&r);
8761   /* For the mantissa, we expand into two HOST_WIDE_INTS, apart from the
8762      highest (sign) bit, with a fixed binary point at bit point_pos.
8763      WARNING: If there's ever a VFP version which uses more than 2 * H_W_I - 1
8764      bits for the mantissa, this may fail (low bits would be lost).  */
8765   real_ldexp (&m, &r, point_pos - exponent);
8766   REAL_VALUE_TO_INT (&m1, &m2, m);
8767   mantissa = m1;
8768   mant_hi = m2;
8769
8770   /* If there are bits set in the low part of the mantissa, we can't
8771      represent this value.  */
8772   if (mantissa != 0)
8773     return -1;
8774
8775   /* Now make it so that mantissa contains the most-significant bits, and move
8776      the point_pos to indicate that the least-significant bits have been
8777      discarded.  */
8778   point_pos -= HOST_BITS_PER_WIDE_INT;
8779   mantissa = mant_hi;
8780
8781   /* We can permit four significant bits of mantissa only, plus a high bit
8782      which is always 1.  */
8783   mask = ((unsigned HOST_WIDE_INT)1 << (point_pos - 5)) - 1;
8784   if ((mantissa & mask) != 0)
8785     return -1;
8786
8787   /* Now we know the mantissa is in range, chop off the unneeded bits.  */
8788   mantissa >>= point_pos - 5;
8789
8790   /* The mantissa may be zero. Disallow that case. (It's possible to load the
8791      floating-point immediate zero with Neon using an integer-zero load, but
8792      that case is handled elsewhere.)  */
8793   if (mantissa == 0)
8794     return -1;
8795
8796   gcc_assert (mantissa >= 16 && mantissa <= 31);
8797
8798   /* The value of 5 here would be 4 if GCC used IEEE754-like encoding (where
8799      normalized significands are in the range [1, 2). (Our mantissa is shifted
8800      left 4 places at this point relative to normalized IEEE754 values).  GCC
8801      internally uses [0.5, 1) (see real.c), so the exponent returned from
8802      REAL_EXP must be altered.  */
8803   exponent = 5 - exponent;
8804
8805   if (exponent < 0 || exponent > 7)
8806     return -1;
8807
8808   /* Sign, mantissa and exponent are now in the correct form to plug into the
8809      formula described in the comment above.  */
8810   return (sign << 7) | ((exponent ^ 3) << 4) | (mantissa - 16);
8811 }
8812
8813 /* Return TRUE if rtx X is a valid immediate VFPv3 constant.  */
8814 int
8815 vfp3_const_double_rtx (rtx x)
8816 {
8817   if (!TARGET_VFP3)
8818     return 0;
8819
8820   return vfp3_const_double_index (x) != -1;
8821 }
8822
8823 /* Recognize immediates which can be used in various Neon instructions. Legal
8824    immediates are described by the following table (for VMVN variants, the
8825    bitwise inverse of the constant shown is recognized. In either case, VMOV
8826    is output and the correct instruction to use for a given constant is chosen
8827    by the assembler). The constant shown is replicated across all elements of
8828    the destination vector.
8829
8830    insn elems variant constant (binary)
8831    ---- ----- ------- -----------------
8832    vmov  i32     0    00000000 00000000 00000000 abcdefgh
8833    vmov  i32     1    00000000 00000000 abcdefgh 00000000
8834    vmov  i32     2    00000000 abcdefgh 00000000 00000000
8835    vmov  i32     3    abcdefgh 00000000 00000000 00000000
8836    vmov  i16     4    00000000 abcdefgh
8837    vmov  i16     5    abcdefgh 00000000
8838    vmvn  i32     6    00000000 00000000 00000000 abcdefgh
8839    vmvn  i32     7    00000000 00000000 abcdefgh 00000000
8840    vmvn  i32     8    00000000 abcdefgh 00000000 00000000
8841    vmvn  i32     9    abcdefgh 00000000 00000000 00000000
8842    vmvn  i16    10    00000000 abcdefgh
8843    vmvn  i16    11    abcdefgh 00000000
8844    vmov  i32    12    00000000 00000000 abcdefgh 11111111
8845    vmvn  i32    13    00000000 00000000 abcdefgh 11111111
8846    vmov  i32    14    00000000 abcdefgh 11111111 11111111
8847    vmvn  i32    15    00000000 abcdefgh 11111111 11111111
8848    vmov   i8    16    abcdefgh
8849    vmov  i64    17    aaaaaaaa bbbbbbbb cccccccc dddddddd
8850                       eeeeeeee ffffffff gggggggg hhhhhhhh
8851    vmov  f32    18    aBbbbbbc defgh000 00000000 00000000
8852
8853    For case 18, B = !b. Representable values are exactly those accepted by
8854    vfp3_const_double_index, but are output as floating-point numbers rather
8855    than indices.
8856
8857    Variants 0-5 (inclusive) may also be used as immediates for the second
8858    operand of VORR/VBIC instructions.
8859
8860    The INVERSE argument causes the bitwise inverse of the given operand to be
8861    recognized instead (used for recognizing legal immediates for the VAND/VORN
8862    pseudo-instructions). If INVERSE is true, the value placed in *MODCONST is
8863    *not* inverted (i.e. the pseudo-instruction forms vand/vorn should still be
8864    output, rather than the real insns vbic/vorr).
8865
8866    INVERSE makes no difference to the recognition of float vectors.
8867
8868    The return value is the variant of immediate as shown in the above table, or
8869    -1 if the given value doesn't match any of the listed patterns.
8870 */
8871 static int
8872 neon_valid_immediate (rtx op, enum machine_mode mode, int inverse,
8873                       rtx *modconst, int *elementwidth)
8874 {
8875 #define CHECK(STRIDE, ELSIZE, CLASS, TEST)      \
8876   matches = 1;                                  \
8877   for (i = 0; i < idx; i += (STRIDE))           \
8878     if (!(TEST))                                \
8879       matches = 0;                              \
8880   if (matches)                                  \
8881     {                                           \
8882       immtype = (CLASS);                        \
8883       elsize = (ELSIZE);                        \
8884       break;                                    \
8885     }
8886
8887   unsigned int i, elsize = 0, idx = 0, n_elts = CONST_VECTOR_NUNITS (op);
8888   unsigned int innersize = GET_MODE_SIZE (GET_MODE_INNER (mode));
8889   unsigned char bytes[16];
8890   int immtype = -1, matches;
8891   unsigned int invmask = inverse ? 0xff : 0;
8892
8893   /* Vectors of float constants.  */
8894   if (GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT)
8895     {
8896       rtx el0 = CONST_VECTOR_ELT (op, 0);
8897       REAL_VALUE_TYPE r0;
8898
8899       if (!vfp3_const_double_rtx (el0))
8900         return -1;
8901
8902       REAL_VALUE_FROM_CONST_DOUBLE (r0, el0);
8903
8904       for (i = 1; i < n_elts; i++)
8905         {
8906           rtx elt = CONST_VECTOR_ELT (op, i);
8907           REAL_VALUE_TYPE re;
8908
8909           REAL_VALUE_FROM_CONST_DOUBLE (re, elt);
8910
8911           if (!REAL_VALUES_EQUAL (r0, re))
8912             return -1;
8913         }
8914
8915       if (modconst)
8916         *modconst = CONST_VECTOR_ELT (op, 0);
8917
8918       if (elementwidth)
8919         *elementwidth = 0;
8920
8921       return 18;
8922     }
8923
8924   /* Splat vector constant out into a byte vector.  */
8925   for (i = 0; i < n_elts; i++)
8926     {
8927       rtx el = CONST_VECTOR_ELT (op, i);
8928       unsigned HOST_WIDE_INT elpart;
8929       unsigned int part, parts;
8930
8931       if (GET_CODE (el) == CONST_INT)
8932         {
8933           elpart = INTVAL (el);
8934           parts = 1;
8935         }
8936       else if (GET_CODE (el) == CONST_DOUBLE)
8937         {
8938           elpart = CONST_DOUBLE_LOW (el);
8939           parts = 2;
8940         }
8941       else
8942         gcc_unreachable ();
8943
8944       for (part = 0; part < parts; part++)
8945         {
8946           unsigned int byte;
8947           for (byte = 0; byte < innersize; byte++)
8948             {
8949               bytes[idx++] = (elpart & 0xff) ^ invmask;
8950               elpart >>= BITS_PER_UNIT;
8951             }
8952           if (GET_CODE (el) == CONST_DOUBLE)
8953             elpart = CONST_DOUBLE_HIGH (el);
8954         }
8955     }
8956
8957   /* Sanity check.  */
8958   gcc_assert (idx == GET_MODE_SIZE (mode));
8959
8960   do
8961     {
8962       CHECK (4, 32, 0, bytes[i] == bytes[0] && bytes[i + 1] == 0
8963                        && bytes[i + 2] == 0 && bytes[i + 3] == 0);
8964
8965       CHECK (4, 32, 1, bytes[i] == 0 && bytes[i + 1] == bytes[1]
8966                        && bytes[i + 2] == 0 && bytes[i + 3] == 0);
8967
8968       CHECK (4, 32, 2, bytes[i] == 0 && bytes[i + 1] == 0
8969                        && bytes[i + 2] == bytes[2] && bytes[i + 3] == 0);
8970
8971       CHECK (4, 32, 3, bytes[i] == 0 && bytes[i + 1] == 0
8972                        && bytes[i + 2] == 0 && bytes[i + 3] == bytes[3]);
8973
8974       CHECK (2, 16, 4, bytes[i] == bytes[0] && bytes[i + 1] == 0);
8975
8976       CHECK (2, 16, 5, bytes[i] == 0 && bytes[i + 1] == bytes[1]);
8977
8978       CHECK (4, 32, 6, bytes[i] == bytes[0] && bytes[i + 1] == 0xff
8979                        && bytes[i + 2] == 0xff && bytes[i + 3] == 0xff);
8980
8981       CHECK (4, 32, 7, bytes[i] == 0xff && bytes[i + 1] == bytes[1]
8982                        && bytes[i + 2] == 0xff && bytes[i + 3] == 0xff);
8983
8984       CHECK (4, 32, 8, bytes[i] == 0xff && bytes[i + 1] == 0xff
8985                        && bytes[i + 2] == bytes[2] && bytes[i + 3] == 0xff);
8986
8987       CHECK (4, 32, 9, bytes[i] == 0xff && bytes[i + 1] == 0xff
8988                        && bytes[i + 2] == 0xff && bytes[i + 3] == bytes[3]);
8989
8990       CHECK (2, 16, 10, bytes[i] == bytes[0] && bytes[i + 1] == 0xff);
8991
8992       CHECK (2, 16, 11, bytes[i] == 0xff && bytes[i + 1] == bytes[1]);
8993
8994       CHECK (4, 32, 12, bytes[i] == 0xff && bytes[i + 1] == bytes[1]
8995                         && bytes[i + 2] == 0 && bytes[i + 3] == 0);
8996
8997       CHECK (4, 32, 13, bytes[i] == 0 && bytes[i + 1] == bytes[1]
8998                         && bytes[i + 2] == 0xff && bytes[i + 3] == 0xff);
8999
9000       CHECK (4, 32, 14, bytes[i] == 0xff && bytes[i + 1] == 0xff
9001                         && bytes[i + 2] == bytes[2] && bytes[i + 3] == 0);
9002
9003       CHECK (4, 32, 15, bytes[i] == 0 && bytes[i + 1] == 0
9004                         && bytes[i + 2] == bytes[2] && bytes[i + 3] == 0xff);
9005
9006       CHECK (1, 8, 16, bytes[i] == bytes[0]);
9007
9008       CHECK (1, 64, 17, (bytes[i] == 0 || bytes[i] == 0xff)
9009                         && bytes[i] == bytes[(i + 8) % idx]);
9010     }
9011   while (0);
9012
9013   if (immtype == -1)
9014     return -1;
9015
9016   if (elementwidth)
9017     *elementwidth = elsize;
9018
9019   if (modconst)
9020     {
9021       unsigned HOST_WIDE_INT imm = 0;
9022
9023       /* Un-invert bytes of recognized vector, if necessary.  */
9024       if (invmask != 0)
9025         for (i = 0; i < idx; i++)
9026           bytes[i] ^= invmask;
9027
9028       if (immtype == 17)
9029         {
9030           /* FIXME: Broken on 32-bit H_W_I hosts.  */
9031           gcc_assert (sizeof (HOST_WIDE_INT) == 8);
9032
9033           for (i = 0; i < 8; i++)
9034             imm |= (unsigned HOST_WIDE_INT) (bytes[i] ? 0xff : 0)
9035                    << (i * BITS_PER_UNIT);
9036
9037           *modconst = GEN_INT (imm);
9038         }
9039       else
9040         {
9041           unsigned HOST_WIDE_INT imm = 0;
9042
9043           for (i = 0; i < elsize / BITS_PER_UNIT; i++)
9044             imm |= (unsigned HOST_WIDE_INT) bytes[i] << (i * BITS_PER_UNIT);
9045
9046           *modconst = GEN_INT (imm);
9047         }
9048     }
9049
9050   return immtype;
9051 #undef CHECK
9052 }
9053
9054 /* Return TRUE if rtx X is legal for use as either a Neon VMOV (or, implicitly,
9055    VMVN) immediate. Write back width per element to *ELEMENTWIDTH (or zero for
9056    float elements), and a modified constant (whatever should be output for a
9057    VMOV) in *MODCONST.  */
9058
9059 int
9060 neon_immediate_valid_for_move (rtx op, enum machine_mode mode,
9061                                rtx *modconst, int *elementwidth)
9062 {
9063   rtx tmpconst;
9064   int tmpwidth;
9065   int retval = neon_valid_immediate (op, mode, 0, &tmpconst, &tmpwidth);
9066
9067   if (retval == -1)
9068     return 0;
9069
9070   if (modconst)
9071     *modconst = tmpconst;
9072
9073   if (elementwidth)
9074     *elementwidth = tmpwidth;
9075
9076   return 1;
9077 }
9078
9079 /* Return TRUE if rtx X is legal for use in a VORR or VBIC instruction.  If
9080    the immediate is valid, write a constant suitable for using as an operand
9081    to VORR/VBIC/VAND/VORN to *MODCONST and the corresponding element width to
9082    *ELEMENTWIDTH. See neon_valid_immediate for description of INVERSE.  */
9083
9084 int
9085 neon_immediate_valid_for_logic (rtx op, enum machine_mode mode, int inverse,
9086                                 rtx *modconst, int *elementwidth)
9087 {
9088   rtx tmpconst;
9089   int tmpwidth;
9090   int retval = neon_valid_immediate (op, mode, inverse, &tmpconst, &tmpwidth);
9091
9092   if (retval < 0 || retval > 5)
9093     return 0;
9094
9095   if (modconst)
9096     *modconst = tmpconst;
9097
9098   if (elementwidth)
9099     *elementwidth = tmpwidth;
9100
9101   return 1;
9102 }
9103
9104 /* Return TRUE if rtx OP is legal for use in a VSHR or VSHL instruction.  If
9105    the immediate is valid, write a constant suitable for using as an operand
9106    to VSHR/VSHL to *MODCONST and the corresponding element width to
9107    *ELEMENTWIDTH. ISLEFTSHIFT is for determine left or right shift,
9108    because they have different limitations.  */
9109
9110 int
9111 neon_immediate_valid_for_shift (rtx op, enum machine_mode mode,
9112                                 rtx *modconst, int *elementwidth,
9113                                 bool isleftshift)
9114 {
9115   unsigned int innersize = GET_MODE_SIZE (GET_MODE_INNER (mode));
9116   unsigned int n_elts = CONST_VECTOR_NUNITS (op), i;
9117   unsigned HOST_WIDE_INT last_elt = 0;
9118   unsigned HOST_WIDE_INT maxshift;
9119
9120   /* Split vector constant out into a byte vector.  */
9121   for (i = 0; i < n_elts; i++)
9122     {
9123       rtx el = CONST_VECTOR_ELT (op, i);
9124       unsigned HOST_WIDE_INT elpart;
9125
9126       if (GET_CODE (el) == CONST_INT)
9127         elpart = INTVAL (el);
9128       else if (GET_CODE (el) == CONST_DOUBLE)
9129         return 0;
9130       else
9131         gcc_unreachable ();
9132
9133       if (i != 0 && elpart != last_elt)
9134         return 0;
9135
9136       last_elt = elpart;
9137     }
9138
9139   /* Shift less than element size.  */
9140   maxshift = innersize * 8;
9141
9142   if (isleftshift)
9143     {
9144       /* Left shift immediate value can be from 0 to <size>-1.  */
9145       if (last_elt >= maxshift)
9146         return 0;
9147     }
9148   else
9149     {
9150       /* Right shift immediate value can be from 1 to <size>.  */
9151       if (last_elt == 0 || last_elt > maxshift)
9152         return 0;
9153     }
9154
9155   if (elementwidth)
9156     *elementwidth = innersize * 8;
9157
9158   if (modconst)
9159     *modconst = CONST_VECTOR_ELT (op, 0);
9160
9161   return 1;
9162 }
9163
9164 /* Return a string suitable for output of Neon immediate logic operation
9165    MNEM.  */
9166
9167 char *
9168 neon_output_logic_immediate (const char *mnem, rtx *op2, enum machine_mode mode,
9169                              int inverse, int quad)
9170 {
9171   int width, is_valid;
9172   static char templ[40];
9173
9174   is_valid = neon_immediate_valid_for_logic (*op2, mode, inverse, op2, &width);
9175
9176   gcc_assert (is_valid != 0);
9177
9178   if (quad)
9179     sprintf (templ, "%s.i%d\t%%q0, %%2", mnem, width);
9180   else
9181     sprintf (templ, "%s.i%d\t%%P0, %%2", mnem, width);
9182
9183   return templ;
9184 }
9185
9186 /* Return a string suitable for output of Neon immediate shift operation
9187    (VSHR or VSHL) MNEM.  */
9188
9189 char *
9190 neon_output_shift_immediate (const char *mnem, char sign, rtx *op2,
9191                              enum machine_mode mode, int quad,
9192                              bool isleftshift)
9193 {
9194   int width, is_valid;
9195   static char templ[40];
9196
9197   is_valid = neon_immediate_valid_for_shift (*op2, mode, op2, &width, isleftshift);
9198   gcc_assert (is_valid != 0);
9199
9200   if (quad)
9201     sprintf (templ, "%s.%c%d\t%%q0, %%q1, %%2", mnem, sign, width);
9202   else
9203     sprintf (templ, "%s.%c%d\t%%P0, %%P1, %%2", mnem, sign, width);
9204
9205   return templ;
9206 }
9207
9208 /* Output a sequence of pairwise operations to implement a reduction.
9209    NOTE: We do "too much work" here, because pairwise operations work on two
9210    registers-worth of operands in one go. Unfortunately we can't exploit those
9211    extra calculations to do the full operation in fewer steps, I don't think.
9212    Although all vector elements of the result but the first are ignored, we
9213    actually calculate the same result in each of the elements. An alternative
9214    such as initially loading a vector with zero to use as each of the second
9215    operands would use up an additional register and take an extra instruction,
9216    for no particular gain.  */
9217
9218 void
9219 neon_pairwise_reduce (rtx op0, rtx op1, enum machine_mode mode,
9220                       rtx (*reduc) (rtx, rtx, rtx))
9221 {
9222   enum machine_mode inner = GET_MODE_INNER (mode);
9223   unsigned int i, parts = GET_MODE_SIZE (mode) / GET_MODE_SIZE (inner);
9224   rtx tmpsum = op1;
9225
9226   for (i = parts / 2; i >= 1; i /= 2)
9227     {
9228       rtx dest = (i == 1) ? op0 : gen_reg_rtx (mode);
9229       emit_insn (reduc (dest, tmpsum, tmpsum));
9230       tmpsum = dest;
9231     }
9232 }
9233
9234 /* If VALS is a vector constant that can be loaded into a register
9235    using VDUP, generate instructions to do so and return an RTX to
9236    assign to the register.  Otherwise return NULL_RTX.  */
9237
9238 static rtx
9239 neon_vdup_constant (rtx vals)
9240 {
9241   enum machine_mode mode = GET_MODE (vals);
9242   enum machine_mode inner_mode = GET_MODE_INNER (mode);
9243   int n_elts = GET_MODE_NUNITS (mode);
9244   bool all_same = true;
9245   rtx x;
9246   int i;
9247
9248   if (GET_CODE (vals) != CONST_VECTOR || GET_MODE_SIZE (inner_mode) > 4)
9249     return NULL_RTX;
9250
9251   for (i = 0; i < n_elts; ++i)
9252     {
9253       x = XVECEXP (vals, 0, i);
9254       if (i > 0 && !rtx_equal_p (x, XVECEXP (vals, 0, 0)))
9255         all_same = false;
9256     }
9257
9258   if (!all_same)
9259     /* The elements are not all the same.  We could handle repeating
9260        patterns of a mode larger than INNER_MODE here (e.g. int8x8_t
9261        {0, C, 0, C, 0, C, 0, C} which can be loaded using
9262        vdup.i16).  */
9263     return NULL_RTX;
9264
9265   /* We can load this constant by using VDUP and a constant in a
9266      single ARM register.  This will be cheaper than a vector
9267      load.  */
9268
9269   x = copy_to_mode_reg (inner_mode, XVECEXP (vals, 0, 0));
9270   return gen_rtx_VEC_DUPLICATE (mode, x);
9271 }
9272
9273 /* Generate code to load VALS, which is a PARALLEL containing only
9274    constants (for vec_init) or CONST_VECTOR, efficiently into a
9275    register.  Returns an RTX to copy into the register, or NULL_RTX
9276    for a PARALLEL that can not be converted into a CONST_VECTOR.  */
9277
9278 rtx
9279 neon_make_constant (rtx vals)
9280 {
9281   enum machine_mode mode = GET_MODE (vals);
9282   rtx target;
9283   rtx const_vec = NULL_RTX;
9284   int n_elts = GET_MODE_NUNITS (mode);
9285   int n_const = 0;
9286   int i;
9287
9288   if (GET_CODE (vals) == CONST_VECTOR)
9289     const_vec = vals;
9290   else if (GET_CODE (vals) == PARALLEL)
9291     {
9292       /* A CONST_VECTOR must contain only CONST_INTs and
9293          CONST_DOUBLEs, but CONSTANT_P allows more (e.g. SYMBOL_REF).
9294          Only store valid constants in a CONST_VECTOR.  */
9295       for (i = 0; i < n_elts; ++i)
9296         {
9297           rtx x = XVECEXP (vals, 0, i);
9298           if (GET_CODE (x) == CONST_INT || GET_CODE (x) == CONST_DOUBLE)
9299             n_const++;
9300         }
9301       if (n_const == n_elts)
9302         const_vec = gen_rtx_CONST_VECTOR (mode, XVEC (vals, 0));
9303     }
9304   else
9305     gcc_unreachable ();
9306
9307   if (const_vec != NULL
9308       && neon_immediate_valid_for_move (const_vec, mode, NULL, NULL))
9309     /* Load using VMOV.  On Cortex-A8 this takes one cycle.  */
9310     return const_vec;
9311   else if ((target = neon_vdup_constant (vals)) != NULL_RTX)
9312     /* Loaded using VDUP.  On Cortex-A8 the VDUP takes one NEON
9313        pipeline cycle; creating the constant takes one or two ARM
9314        pipeline cycles.  */
9315     return target;
9316   else if (const_vec != NULL_RTX)
9317     /* Load from constant pool.  On Cortex-A8 this takes two cycles
9318        (for either double or quad vectors).  We can not take advantage
9319        of single-cycle VLD1 because we need a PC-relative addressing
9320        mode.  */
9321     return const_vec;
9322   else
9323     /* A PARALLEL containing something not valid inside CONST_VECTOR.
9324        We can not construct an initializer.  */
9325     return NULL_RTX;
9326 }
9327
9328 /* Initialize vector TARGET to VALS.  */
9329
9330 void
9331 neon_expand_vector_init (rtx target, rtx vals)
9332 {
9333   enum machine_mode mode = GET_MODE (target);
9334   enum machine_mode inner_mode = GET_MODE_INNER (mode);
9335   int n_elts = GET_MODE_NUNITS (mode);
9336   int n_var = 0, one_var = -1;
9337   bool all_same = true;
9338   rtx x, mem;
9339   int i;
9340
9341   for (i = 0; i < n_elts; ++i)
9342     {
9343       x = XVECEXP (vals, 0, i);
9344       if (!CONSTANT_P (x))
9345         ++n_var, one_var = i;
9346
9347       if (i > 0 && !rtx_equal_p (x, XVECEXP (vals, 0, 0)))
9348         all_same = false;
9349     }
9350
9351   if (n_var == 0)
9352     {
9353       rtx constant = neon_make_constant (vals);
9354       if (constant != NULL_RTX)
9355         {
9356           emit_move_insn (target, constant);
9357           return;
9358         }
9359     }
9360
9361   /* Splat a single non-constant element if we can.  */
9362   if (all_same && GET_MODE_SIZE (inner_mode) <= 4)
9363     {
9364       x = copy_to_mode_reg (inner_mode, XVECEXP (vals, 0, 0));
9365       emit_insn (gen_rtx_SET (VOIDmode, target,
9366                               gen_rtx_VEC_DUPLICATE (mode, x)));
9367       return;
9368     }
9369
9370   /* One field is non-constant.  Load constant then overwrite varying
9371      field.  This is more efficient than using the stack.  */
9372   if (n_var == 1)
9373     {
9374       rtx copy = copy_rtx (vals);
9375       rtx index = GEN_INT (one_var);
9376
9377       /* Load constant part of vector, substitute neighboring value for
9378          varying element.  */
9379       XVECEXP (copy, 0, one_var) = XVECEXP (vals, 0, (one_var + 1) % n_elts);
9380       neon_expand_vector_init (target, copy);
9381
9382       /* Insert variable.  */
9383       x = copy_to_mode_reg (inner_mode, XVECEXP (vals, 0, one_var));
9384       switch (mode)
9385         {
9386         case V8QImode:
9387           emit_insn (gen_neon_vset_lanev8qi (target, x, target, index));
9388           break;
9389         case V16QImode:
9390           emit_insn (gen_neon_vset_lanev16qi (target, x, target, index));
9391           break;
9392         case V4HImode:
9393           emit_insn (gen_neon_vset_lanev4hi (target, x, target, index));
9394           break;
9395         case V8HImode:
9396           emit_insn (gen_neon_vset_lanev8hi (target, x, target, index));
9397           break;
9398         case V2SImode:
9399           emit_insn (gen_neon_vset_lanev2si (target, x, target, index));
9400           break;
9401         case V4SImode:
9402           emit_insn (gen_neon_vset_lanev4si (target, x, target, index));
9403           break;
9404         case V2SFmode:
9405           emit_insn (gen_neon_vset_lanev2sf (target, x, target, index));
9406           break;
9407         case V4SFmode:
9408           emit_insn (gen_neon_vset_lanev4sf (target, x, target, index));
9409           break;
9410         case V2DImode:
9411           emit_insn (gen_neon_vset_lanev2di (target, x, target, index));
9412           break;
9413         default:
9414           gcc_unreachable ();
9415         }
9416       return;
9417     }
9418
9419   /* Construct the vector in memory one field at a time
9420      and load the whole vector.  */
9421   mem = assign_stack_temp (mode, GET_MODE_SIZE (mode), 0);
9422   for (i = 0; i < n_elts; i++)
9423     emit_move_insn (adjust_address_nv (mem, inner_mode,
9424                                     i * GET_MODE_SIZE (inner_mode)),
9425                     XVECEXP (vals, 0, i));
9426   emit_move_insn (target, mem);
9427 }
9428
9429 /* Ensure OPERAND lies between LOW (inclusive) and HIGH (exclusive).  Raise
9430    ERR if it doesn't.  FIXME: NEON bounds checks occur late in compilation, so
9431    reported source locations are bogus.  */
9432
9433 static void
9434 bounds_check (rtx operand, HOST_WIDE_INT low, HOST_WIDE_INT high,
9435               const char *err)
9436 {
9437   HOST_WIDE_INT lane;
9438
9439   gcc_assert (GET_CODE (operand) == CONST_INT);
9440
9441   lane = INTVAL (operand);
9442
9443   if (lane < low || lane >= high)
9444     error (err);
9445 }
9446
9447 /* Bounds-check lanes.  */
9448
9449 void
9450 neon_lane_bounds (rtx operand, HOST_WIDE_INT low, HOST_WIDE_INT high)
9451 {
9452   bounds_check (operand, low, high, "lane out of range");
9453 }
9454
9455 /* Bounds-check constants.  */
9456
9457 void
9458 neon_const_bounds (rtx operand, HOST_WIDE_INT low, HOST_WIDE_INT high)
9459 {
9460   bounds_check (operand, low, high, "constant out of range");
9461 }
9462
9463 HOST_WIDE_INT
9464 neon_element_bits (enum machine_mode mode)
9465 {
9466   if (mode == DImode)
9467     return GET_MODE_BITSIZE (mode);
9468   else
9469     return GET_MODE_BITSIZE (GET_MODE_INNER (mode));
9470 }
9471
9472 \f
9473 /* Predicates for `match_operand' and `match_operator'.  */
9474
9475 /* Return nonzero if OP is a valid Cirrus memory address pattern.  */
9476 int
9477 cirrus_memory_offset (rtx op)
9478 {
9479   /* Reject eliminable registers.  */
9480   if (! (reload_in_progress || reload_completed)
9481       && (   reg_mentioned_p (frame_pointer_rtx, op)
9482           || reg_mentioned_p (arg_pointer_rtx, op)
9483           || reg_mentioned_p (virtual_incoming_args_rtx, op)
9484           || reg_mentioned_p (virtual_outgoing_args_rtx, op)
9485           || reg_mentioned_p (virtual_stack_dynamic_rtx, op)
9486           || reg_mentioned_p (virtual_stack_vars_rtx, op)))
9487     return 0;
9488
9489   if (GET_CODE (op) == MEM)
9490     {
9491       rtx ind;
9492
9493       ind = XEXP (op, 0);
9494
9495       /* Match: (mem (reg)).  */
9496       if (GET_CODE (ind) == REG)
9497         return 1;
9498
9499       /* Match:
9500          (mem (plus (reg)
9501                     (const))).  */
9502       if (GET_CODE (ind) == PLUS
9503           && GET_CODE (XEXP (ind, 0)) == REG
9504           && REG_MODE_OK_FOR_BASE_P (XEXP (ind, 0), VOIDmode)
9505           && GET_CODE (XEXP (ind, 1)) == CONST_INT)
9506         return 1;
9507     }
9508
9509   return 0;
9510 }
9511
9512 /* Return TRUE if OP is a valid coprocessor memory address pattern.
9513    WB is true if full writeback address modes are allowed and is false
9514    if limited writeback address modes (POST_INC and PRE_DEC) are
9515    allowed.  */
9516
9517 int
9518 arm_coproc_mem_operand (rtx op, bool wb)
9519 {
9520   rtx ind;
9521
9522   /* Reject eliminable registers.  */
9523   if (! (reload_in_progress || reload_completed)
9524       && (   reg_mentioned_p (frame_pointer_rtx, op)
9525           || reg_mentioned_p (arg_pointer_rtx, op)
9526           || reg_mentioned_p (virtual_incoming_args_rtx, op)
9527           || reg_mentioned_p (virtual_outgoing_args_rtx, op)
9528           || reg_mentioned_p (virtual_stack_dynamic_rtx, op)
9529           || reg_mentioned_p (virtual_stack_vars_rtx, op)))
9530     return FALSE;
9531
9532   /* Constants are converted into offsets from labels.  */
9533   if (GET_CODE (op) != MEM)
9534     return FALSE;
9535
9536   ind = XEXP (op, 0);
9537
9538   if (reload_completed
9539       && (GET_CODE (ind) == LABEL_REF
9540           || (GET_CODE (ind) == CONST
9541               && GET_CODE (XEXP (ind, 0)) == PLUS
9542               && GET_CODE (XEXP (XEXP (ind, 0), 0)) == LABEL_REF
9543               && GET_CODE (XEXP (XEXP (ind, 0), 1)) == CONST_INT)))
9544     return TRUE;
9545
9546   /* Match: (mem (reg)).  */
9547   if (GET_CODE (ind) == REG)
9548     return arm_address_register_rtx_p (ind, 0);
9549
9550   /* Autoincremment addressing modes.  POST_INC and PRE_DEC are
9551      acceptable in any case (subject to verification by
9552      arm_address_register_rtx_p).  We need WB to be true to accept
9553      PRE_INC and POST_DEC.  */
9554   if (GET_CODE (ind) == POST_INC
9555       || GET_CODE (ind) == PRE_DEC
9556       || (wb
9557           && (GET_CODE (ind) == PRE_INC
9558               || GET_CODE (ind) == POST_DEC)))
9559     return arm_address_register_rtx_p (XEXP (ind, 0), 0);
9560
9561   if (wb
9562       && (GET_CODE (ind) == POST_MODIFY || GET_CODE (ind) == PRE_MODIFY)
9563       && arm_address_register_rtx_p (XEXP (ind, 0), 0)
9564       && GET_CODE (XEXP (ind, 1)) == PLUS
9565       && rtx_equal_p (XEXP (XEXP (ind, 1), 0), XEXP (ind, 0)))
9566     ind = XEXP (ind, 1);
9567
9568   /* Match:
9569      (plus (reg)
9570            (const)).  */
9571   if (GET_CODE (ind) == PLUS
9572       && GET_CODE (XEXP (ind, 0)) == REG
9573       && REG_MODE_OK_FOR_BASE_P (XEXP (ind, 0), VOIDmode)
9574       && GET_CODE (XEXP (ind, 1)) == CONST_INT
9575       && INTVAL (XEXP (ind, 1)) > -1024
9576       && INTVAL (XEXP (ind, 1)) <  1024
9577       && (INTVAL (XEXP (ind, 1)) & 3) == 0)
9578     return TRUE;
9579
9580   return FALSE;
9581 }
9582
9583 /* Return TRUE if OP is a memory operand which we can load or store a vector
9584    to/from. TYPE is one of the following values:
9585     0 - Vector load/stor (vldr)
9586     1 - Core registers (ldm)
9587     2 - Element/structure loads (vld1)
9588  */
9589 int
9590 neon_vector_mem_operand (rtx op, int type)
9591 {
9592   rtx ind;
9593
9594   /* Reject eliminable registers.  */
9595   if (! (reload_in_progress || reload_completed)
9596       && (   reg_mentioned_p (frame_pointer_rtx, op)
9597           || reg_mentioned_p (arg_pointer_rtx, op)
9598           || reg_mentioned_p (virtual_incoming_args_rtx, op)
9599           || reg_mentioned_p (virtual_outgoing_args_rtx, op)
9600           || reg_mentioned_p (virtual_stack_dynamic_rtx, op)
9601           || reg_mentioned_p (virtual_stack_vars_rtx, op)))
9602     return FALSE;
9603
9604   /* Constants are converted into offsets from labels.  */
9605   if (GET_CODE (op) != MEM)
9606     return FALSE;
9607
9608   ind = XEXP (op, 0);
9609
9610   if (reload_completed
9611       && (GET_CODE (ind) == LABEL_REF
9612           || (GET_CODE (ind) == CONST
9613               && GET_CODE (XEXP (ind, 0)) == PLUS
9614               && GET_CODE (XEXP (XEXP (ind, 0), 0)) == LABEL_REF
9615               && GET_CODE (XEXP (XEXP (ind, 0), 1)) == CONST_INT)))
9616     return TRUE;
9617
9618   /* Match: (mem (reg)).  */
9619   if (GET_CODE (ind) == REG)
9620     return arm_address_register_rtx_p (ind, 0);
9621
9622   /* Allow post-increment with Neon registers.  */
9623   if ((type != 1 && GET_CODE (ind) == POST_INC)
9624       || (type == 0 && GET_CODE (ind) == PRE_DEC))
9625     return arm_address_register_rtx_p (XEXP (ind, 0), 0);
9626
9627   /* FIXME: vld1 allows register post-modify.  */
9628
9629   /* Match:
9630      (plus (reg)
9631           (const)).  */
9632   if (type == 0
9633       && GET_CODE (ind) == PLUS
9634       && GET_CODE (XEXP (ind, 0)) == REG
9635       && REG_MODE_OK_FOR_BASE_P (XEXP (ind, 0), VOIDmode)
9636       && GET_CODE (XEXP (ind, 1)) == CONST_INT
9637       && INTVAL (XEXP (ind, 1)) > -1024
9638       && INTVAL (XEXP (ind, 1)) < 1016
9639       && (INTVAL (XEXP (ind, 1)) & 3) == 0)
9640     return TRUE;
9641
9642   return FALSE;
9643 }
9644
9645 /* Return TRUE if OP is a mem suitable for loading/storing a Neon struct
9646    type.  */
9647 int
9648 neon_struct_mem_operand (rtx op)
9649 {
9650   rtx ind;
9651
9652   /* Reject eliminable registers.  */
9653   if (! (reload_in_progress || reload_completed)
9654       && (   reg_mentioned_p (frame_pointer_rtx, op)
9655           || reg_mentioned_p (arg_pointer_rtx, op)
9656           || reg_mentioned_p (virtual_incoming_args_rtx, op)
9657           || reg_mentioned_p (virtual_outgoing_args_rtx, op)
9658           || reg_mentioned_p (virtual_stack_dynamic_rtx, op)
9659           || reg_mentioned_p (virtual_stack_vars_rtx, op)))
9660     return FALSE;
9661
9662   /* Constants are converted into offsets from labels.  */
9663   if (GET_CODE (op) != MEM)
9664     return FALSE;
9665
9666   ind = XEXP (op, 0);
9667
9668   if (reload_completed
9669       && (GET_CODE (ind) == LABEL_REF
9670           || (GET_CODE (ind) == CONST
9671               && GET_CODE (XEXP (ind, 0)) == PLUS
9672               && GET_CODE (XEXP (XEXP (ind, 0), 0)) == LABEL_REF
9673               && GET_CODE (XEXP (XEXP (ind, 0), 1)) == CONST_INT)))
9674     return TRUE;
9675
9676   /* Match: (mem (reg)).  */
9677   if (GET_CODE (ind) == REG)
9678     return arm_address_register_rtx_p (ind, 0);
9679
9680   /* vldm/vstm allows POST_INC (ia) and PRE_DEC (db).  */
9681   if (GET_CODE (ind) == POST_INC
9682       || GET_CODE (ind) == PRE_DEC)
9683     return arm_address_register_rtx_p (XEXP (ind, 0), 0);
9684
9685   return FALSE;
9686 }
9687
9688 /* Return true if X is a register that will be eliminated later on.  */
9689 int
9690 arm_eliminable_register (rtx x)
9691 {
9692   return REG_P (x) && (REGNO (x) == FRAME_POINTER_REGNUM
9693                        || REGNO (x) == ARG_POINTER_REGNUM
9694                        || (REGNO (x) >= FIRST_VIRTUAL_REGISTER
9695                            && REGNO (x) <= LAST_VIRTUAL_REGISTER));
9696 }
9697
9698 /* Return GENERAL_REGS if a scratch register required to reload x to/from
9699    coprocessor registers.  Otherwise return NO_REGS.  */
9700
9701 enum reg_class
9702 coproc_secondary_reload_class (enum machine_mode mode, rtx x, bool wb)
9703 {
9704   if (mode == HFmode)
9705     {
9706       if (!TARGET_NEON_FP16)
9707         return GENERAL_REGS;
9708       if (s_register_operand (x, mode) || neon_vector_mem_operand (x, 2))
9709         return NO_REGS;
9710       return GENERAL_REGS;
9711     }
9712
9713   /* The neon move patterns handle all legitimate vector and struct
9714      addresses.  */
9715   if (TARGET_NEON
9716       && (MEM_P (x) || GET_CODE (x) == CONST_VECTOR)
9717       && (GET_MODE_CLASS (mode) == MODE_VECTOR_INT
9718           || GET_MODE_CLASS (mode) == MODE_VECTOR_FLOAT
9719           || VALID_NEON_STRUCT_MODE (mode)))
9720     return NO_REGS;
9721
9722   if (arm_coproc_mem_operand (x, wb) || s_register_operand (x, mode))
9723     return NO_REGS;
9724
9725   return GENERAL_REGS;
9726 }
9727
9728 /* Values which must be returned in the most-significant end of the return
9729    register.  */
9730
9731 static bool
9732 arm_return_in_msb (const_tree valtype)
9733 {
9734   return (TARGET_AAPCS_BASED
9735           && BYTES_BIG_ENDIAN
9736           && (AGGREGATE_TYPE_P (valtype)
9737               || TREE_CODE (valtype) == COMPLEX_TYPE
9738               || FIXED_POINT_TYPE_P (valtype)));
9739 }
9740
9741 /* Returns TRUE if INSN is an "LDR REG, ADDR" instruction.
9742    Use by the Cirrus Maverick code which has to workaround
9743    a hardware bug triggered by such instructions.  */
9744 static bool
9745 arm_memory_load_p (rtx insn)
9746 {
9747   rtx body, lhs, rhs;;
9748
9749   if (insn == NULL_RTX || GET_CODE (insn) != INSN)
9750     return false;
9751
9752   body = PATTERN (insn);
9753
9754   if (GET_CODE (body) != SET)
9755     return false;
9756
9757   lhs = XEXP (body, 0);
9758   rhs = XEXP (body, 1);
9759
9760   lhs = REG_OR_SUBREG_RTX (lhs);
9761
9762   /* If the destination is not a general purpose
9763      register we do not have to worry.  */
9764   if (GET_CODE (lhs) != REG
9765       || REGNO_REG_CLASS (REGNO (lhs)) != GENERAL_REGS)
9766     return false;
9767
9768   /* As well as loads from memory we also have to react
9769      to loads of invalid constants which will be turned
9770      into loads from the minipool.  */
9771   return (GET_CODE (rhs) == MEM
9772           || GET_CODE (rhs) == SYMBOL_REF
9773           || note_invalid_constants (insn, -1, false));
9774 }
9775
9776 /* Return TRUE if INSN is a Cirrus instruction.  */
9777 static bool
9778 arm_cirrus_insn_p (rtx insn)
9779 {
9780   enum attr_cirrus attr;
9781
9782   /* get_attr cannot accept USE or CLOBBER.  */
9783   if (!insn
9784       || GET_CODE (insn) != INSN
9785       || GET_CODE (PATTERN (insn)) == USE
9786       || GET_CODE (PATTERN (insn)) == CLOBBER)
9787     return 0;
9788
9789   attr = get_attr_cirrus (insn);
9790
9791   return attr != CIRRUS_NOT;
9792 }
9793
9794 /* Cirrus reorg for invalid instruction combinations.  */
9795 static void
9796 cirrus_reorg (rtx first)
9797 {
9798   enum attr_cirrus attr;
9799   rtx body = PATTERN (first);
9800   rtx t;
9801   int nops;
9802
9803   /* Any branch must be followed by 2 non Cirrus instructions.  */
9804   if (GET_CODE (first) == JUMP_INSN && GET_CODE (body) != RETURN)
9805     {
9806       nops = 0;
9807       t = next_nonnote_insn (first);
9808
9809       if (arm_cirrus_insn_p (t))
9810         ++ nops;
9811
9812       if (arm_cirrus_insn_p (next_nonnote_insn (t)))
9813         ++ nops;
9814
9815       while (nops --)
9816         emit_insn_after (gen_nop (), first);
9817
9818       return;
9819     }
9820
9821   /* (float (blah)) is in parallel with a clobber.  */
9822   if (GET_CODE (body) == PARALLEL && XVECLEN (body, 0) > 0)
9823     body = XVECEXP (body, 0, 0);
9824
9825   if (GET_CODE (body) == SET)
9826     {
9827       rtx lhs = XEXP (body, 0), rhs = XEXP (body, 1);
9828
9829       /* cfldrd, cfldr64, cfstrd, cfstr64 must
9830          be followed by a non Cirrus insn.  */
9831       if (get_attr_cirrus (first) == CIRRUS_DOUBLE)
9832         {
9833           if (arm_cirrus_insn_p (next_nonnote_insn (first)))
9834             emit_insn_after (gen_nop (), first);
9835
9836           return;
9837         }
9838       else if (arm_memory_load_p (first))
9839         {
9840           unsigned int arm_regno;
9841
9842           /* Any ldr/cfmvdlr, ldr/cfmvdhr, ldr/cfmvsr, ldr/cfmv64lr,
9843              ldr/cfmv64hr combination where the Rd field is the same
9844              in both instructions must be split with a non Cirrus
9845              insn.  Example:
9846
9847              ldr r0, blah
9848              nop
9849              cfmvsr mvf0, r0.  */
9850
9851           /* Get Arm register number for ldr insn.  */
9852           if (GET_CODE (lhs) == REG)
9853             arm_regno = REGNO (lhs);
9854           else
9855             {
9856               gcc_assert (GET_CODE (rhs) == REG);
9857               arm_regno = REGNO (rhs);
9858             }
9859
9860           /* Next insn.  */
9861           first = next_nonnote_insn (first);
9862
9863           if (! arm_cirrus_insn_p (first))
9864             return;
9865
9866           body = PATTERN (first);
9867
9868           /* (float (blah)) is in parallel with a clobber.  */
9869           if (GET_CODE (body) == PARALLEL && XVECLEN (body, 0))
9870             body = XVECEXP (body, 0, 0);
9871
9872           if (GET_CODE (body) == FLOAT)
9873             body = XEXP (body, 0);
9874
9875           if (get_attr_cirrus (first) == CIRRUS_MOVE
9876               && GET_CODE (XEXP (body, 1)) == REG
9877               && arm_regno == REGNO (XEXP (body, 1)))
9878             emit_insn_after (gen_nop (), first);
9879
9880           return;
9881         }
9882     }
9883
9884   /* get_attr cannot accept USE or CLOBBER.  */
9885   if (!first
9886       || GET_CODE (first) != INSN
9887       || GET_CODE (PATTERN (first)) == USE
9888       || GET_CODE (PATTERN (first)) == CLOBBER)
9889     return;
9890
9891   attr = get_attr_cirrus (first);
9892
9893   /* Any coprocessor compare instruction (cfcmps, cfcmpd, ...)
9894      must be followed by a non-coprocessor instruction.  */
9895   if (attr == CIRRUS_COMPARE)
9896     {
9897       nops = 0;
9898
9899       t = next_nonnote_insn (first);
9900
9901       if (arm_cirrus_insn_p (t))
9902         ++ nops;
9903
9904       if (arm_cirrus_insn_p (next_nonnote_insn (t)))
9905         ++ nops;
9906
9907       while (nops --)
9908         emit_insn_after (gen_nop (), first);
9909
9910       return;
9911     }
9912 }
9913
9914 /* Return TRUE if X references a SYMBOL_REF.  */
9915 int
9916 symbol_mentioned_p (rtx x)
9917 {
9918   const char * fmt;
9919   int i;
9920
9921   if (GET_CODE (x) == SYMBOL_REF)
9922     return 1;
9923
9924   /* UNSPEC_TLS entries for a symbol include the SYMBOL_REF, but they
9925      are constant offsets, not symbols.  */
9926   if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_TLS)
9927     return 0;
9928
9929   fmt = GET_RTX_FORMAT (GET_CODE (x));
9930
9931   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
9932     {
9933       if (fmt[i] == 'E')
9934         {
9935           int j;
9936
9937           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
9938             if (symbol_mentioned_p (XVECEXP (x, i, j)))
9939               return 1;
9940         }
9941       else if (fmt[i] == 'e' && symbol_mentioned_p (XEXP (x, i)))
9942         return 1;
9943     }
9944
9945   return 0;
9946 }
9947
9948 /* Return TRUE if X references a LABEL_REF.  */
9949 int
9950 label_mentioned_p (rtx x)
9951 {
9952   const char * fmt;
9953   int i;
9954
9955   if (GET_CODE (x) == LABEL_REF)
9956     return 1;
9957
9958   /* UNSPEC_TLS entries for a symbol include a LABEL_REF for the referencing
9959      instruction, but they are constant offsets, not symbols.  */
9960   if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_TLS)
9961     return 0;
9962
9963   fmt = GET_RTX_FORMAT (GET_CODE (x));
9964   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
9965     {
9966       if (fmt[i] == 'E')
9967         {
9968           int j;
9969
9970           for (j = XVECLEN (x, i) - 1; j >= 0; j--)
9971             if (label_mentioned_p (XVECEXP (x, i, j)))
9972               return 1;
9973         }
9974       else if (fmt[i] == 'e' && label_mentioned_p (XEXP (x, i)))
9975         return 1;
9976     }
9977
9978   return 0;
9979 }
9980
9981 int
9982 tls_mentioned_p (rtx x)
9983 {
9984   switch (GET_CODE (x))
9985     {
9986     case CONST:
9987       return tls_mentioned_p (XEXP (x, 0));
9988
9989     case UNSPEC:
9990       if (XINT (x, 1) == UNSPEC_TLS)
9991         return 1;
9992
9993     default:
9994       return 0;
9995     }
9996 }
9997
9998 /* Must not copy any rtx that uses a pc-relative address.  */
9999
10000 static int
10001 arm_note_pic_base (rtx *x, void *date ATTRIBUTE_UNUSED)
10002 {
10003   if (GET_CODE (*x) == UNSPEC
10004       && XINT (*x, 1) == UNSPEC_PIC_BASE)
10005     return 1;
10006   return 0;
10007 }
10008
10009 static bool
10010 arm_cannot_copy_insn_p (rtx insn)
10011 {
10012   /* The tls call insn cannot be copied, as it is paired with a data
10013      word.  */
10014   if (recog_memoized (insn) == CODE_FOR_tlscall)
10015     return true;
10016
10017   return for_each_rtx (&PATTERN (insn), arm_note_pic_base, NULL);
10018 }
10019
10020 enum rtx_code
10021 minmax_code (rtx x)
10022 {
10023   enum rtx_code code = GET_CODE (x);
10024
10025   switch (code)
10026     {
10027     case SMAX:
10028       return GE;
10029     case SMIN:
10030       return LE;
10031     case UMIN:
10032       return LEU;
10033     case UMAX:
10034       return GEU;
10035     default:
10036       gcc_unreachable ();
10037     }
10038 }
10039
10040 /* Return 1 if memory locations are adjacent.  */
10041 int
10042 adjacent_mem_locations (rtx a, rtx b)
10043 {
10044   /* We don't guarantee to preserve the order of these memory refs.  */
10045   if (volatile_refs_p (a) || volatile_refs_p (b))
10046     return 0;
10047
10048   if ((GET_CODE (XEXP (a, 0)) == REG
10049        || (GET_CODE (XEXP (a, 0)) == PLUS
10050            && GET_CODE (XEXP (XEXP (a, 0), 1)) == CONST_INT))
10051       && (GET_CODE (XEXP (b, 0)) == REG
10052           || (GET_CODE (XEXP (b, 0)) == PLUS
10053               && GET_CODE (XEXP (XEXP (b, 0), 1)) == CONST_INT)))
10054     {
10055       HOST_WIDE_INT val0 = 0, val1 = 0;
10056       rtx reg0, reg1;
10057       int val_diff;
10058
10059       if (GET_CODE (XEXP (a, 0)) == PLUS)
10060         {
10061           reg0 = XEXP (XEXP (a, 0), 0);
10062           val0 = INTVAL (XEXP (XEXP (a, 0), 1));
10063         }
10064       else
10065         reg0 = XEXP (a, 0);
10066
10067       if (GET_CODE (XEXP (b, 0)) == PLUS)
10068         {
10069           reg1 = XEXP (XEXP (b, 0), 0);
10070           val1 = INTVAL (XEXP (XEXP (b, 0), 1));
10071         }
10072       else
10073         reg1 = XEXP (b, 0);
10074
10075       /* Don't accept any offset that will require multiple
10076          instructions to handle, since this would cause the
10077          arith_adjacentmem pattern to output an overlong sequence.  */
10078       if (!const_ok_for_op (val0, PLUS) || !const_ok_for_op (val1, PLUS))
10079         return 0;
10080
10081       /* Don't allow an eliminable register: register elimination can make
10082          the offset too large.  */
10083       if (arm_eliminable_register (reg0))
10084         return 0;
10085
10086       val_diff = val1 - val0;
10087
10088       if (arm_ld_sched)
10089         {
10090           /* If the target has load delay slots, then there's no benefit
10091              to using an ldm instruction unless the offset is zero and
10092              we are optimizing for size.  */
10093           return (optimize_size && (REGNO (reg0) == REGNO (reg1))
10094                   && (val0 == 0 || val1 == 0 || val0 == 4 || val1 == 4)
10095                   && (val_diff == 4 || val_diff == -4));
10096         }
10097
10098       return ((REGNO (reg0) == REGNO (reg1))
10099               && (val_diff == 4 || val_diff == -4));
10100     }
10101
10102   return 0;
10103 }
10104
10105 /* Return true iff it would be profitable to turn a sequence of NOPS loads
10106    or stores (depending on IS_STORE) into a load-multiple or store-multiple
10107    instruction.  ADD_OFFSET is nonzero if the base address register needs
10108    to be modified with an add instruction before we can use it.  */
10109
10110 static bool
10111 multiple_operation_profitable_p (bool is_store ATTRIBUTE_UNUSED,
10112                                  int nops, HOST_WIDE_INT add_offset)
10113  {
10114   /* For ARM8,9 & StrongARM, 2 ldr instructions are faster than an ldm
10115      if the offset isn't small enough.  The reason 2 ldrs are faster
10116      is because these ARMs are able to do more than one cache access
10117      in a single cycle.  The ARM9 and StrongARM have Harvard caches,
10118      whilst the ARM8 has a double bandwidth cache.  This means that
10119      these cores can do both an instruction fetch and a data fetch in
10120      a single cycle, so the trick of calculating the address into a
10121      scratch register (one of the result regs) and then doing a load
10122      multiple actually becomes slower (and no smaller in code size).
10123      That is the transformation
10124
10125         ldr     rd1, [rbase + offset]
10126         ldr     rd2, [rbase + offset + 4]
10127
10128      to
10129
10130         add     rd1, rbase, offset
10131         ldmia   rd1, {rd1, rd2}
10132
10133      produces worse code -- '3 cycles + any stalls on rd2' instead of
10134      '2 cycles + any stalls on rd2'.  On ARMs with only one cache
10135      access per cycle, the first sequence could never complete in less
10136      than 6 cycles, whereas the ldm sequence would only take 5 and
10137      would make better use of sequential accesses if not hitting the
10138      cache.
10139
10140      We cheat here and test 'arm_ld_sched' which we currently know to
10141      only be true for the ARM8, ARM9 and StrongARM.  If this ever
10142      changes, then the test below needs to be reworked.  */
10143   if (nops == 2 && arm_ld_sched && add_offset != 0)
10144     return false;
10145
10146   /* XScale has load-store double instructions, but they have stricter
10147      alignment requirements than load-store multiple, so we cannot
10148      use them.
10149
10150      For XScale ldm requires 2 + NREGS cycles to complete and blocks
10151      the pipeline until completion.
10152
10153         NREGS           CYCLES
10154           1               3
10155           2               4
10156           3               5
10157           4               6
10158
10159      An ldr instruction takes 1-3 cycles, but does not block the
10160      pipeline.
10161
10162         NREGS           CYCLES
10163           1              1-3
10164           2              2-6
10165           3              3-9
10166           4              4-12
10167
10168      Best case ldr will always win.  However, the more ldr instructions
10169      we issue, the less likely we are to be able to schedule them well.
10170      Using ldr instructions also increases code size.
10171
10172      As a compromise, we use ldr for counts of 1 or 2 regs, and ldm
10173      for counts of 3 or 4 regs.  */
10174   if (nops <= 2 && arm_tune_xscale && !optimize_size)
10175     return false;
10176   return true;
10177 }
10178
10179 /* Subroutine of load_multiple_sequence and store_multiple_sequence.
10180    Given an array of UNSORTED_OFFSETS, of which there are NOPS, compute
10181    an array ORDER which describes the sequence to use when accessing the
10182    offsets that produces an ascending order.  In this sequence, each
10183    offset must be larger by exactly 4 than the previous one.  ORDER[0]
10184    must have been filled in with the lowest offset by the caller.
10185    If UNSORTED_REGS is nonnull, it is an array of register numbers that
10186    we use to verify that ORDER produces an ascending order of registers.
10187    Return true if it was possible to construct such an order, false if
10188    not.  */
10189
10190 static bool
10191 compute_offset_order (int nops, HOST_WIDE_INT *unsorted_offsets, int *order,
10192                       int *unsorted_regs)
10193 {
10194   int i;
10195   for (i = 1; i < nops; i++)
10196     {
10197       int j;
10198
10199       order[i] = order[i - 1];
10200       for (j = 0; j < nops; j++)
10201         if (unsorted_offsets[j] == unsorted_offsets[order[i - 1]] + 4)
10202           {
10203             /* We must find exactly one offset that is higher than the
10204                previous one by 4.  */
10205             if (order[i] != order[i - 1])
10206               return false;
10207             order[i] = j;
10208           }
10209       if (order[i] == order[i - 1])
10210         return false;
10211       /* The register numbers must be ascending.  */
10212       if (unsorted_regs != NULL
10213           && unsorted_regs[order[i]] <= unsorted_regs[order[i - 1]])
10214         return false;
10215     }
10216   return true;
10217 }
10218
10219 /* Used to determine in a peephole whether a sequence of load
10220    instructions can be changed into a load-multiple instruction.
10221    NOPS is the number of separate load instructions we are examining.  The
10222    first NOPS entries in OPERANDS are the destination registers, the
10223    next NOPS entries are memory operands.  If this function is
10224    successful, *BASE is set to the common base register of the memory
10225    accesses; *LOAD_OFFSET is set to the first memory location's offset
10226    from that base register.
10227    REGS is an array filled in with the destination register numbers.
10228    SAVED_ORDER (if nonnull), is an array filled in with an order that maps
10229    insn numbers to an ascending order of stores.  If CHECK_REGS is true,
10230    the sequence of registers in REGS matches the loads from ascending memory
10231    locations, and the function verifies that the register numbers are
10232    themselves ascending.  If CHECK_REGS is false, the register numbers
10233    are stored in the order they are found in the operands.  */
10234 static int
10235 load_multiple_sequence (rtx *operands, int nops, int *regs, int *saved_order,
10236                         int *base, HOST_WIDE_INT *load_offset, bool check_regs)
10237 {
10238   int unsorted_regs[MAX_LDM_STM_OPS];
10239   HOST_WIDE_INT unsorted_offsets[MAX_LDM_STM_OPS];
10240   int order[MAX_LDM_STM_OPS];
10241   rtx base_reg_rtx = NULL;
10242   int base_reg = -1;
10243   int i, ldm_case;
10244
10245   /* Can only handle up to MAX_LDM_STM_OPS insns at present, though could be
10246      easily extended if required.  */
10247   gcc_assert (nops >= 2 && nops <= MAX_LDM_STM_OPS);
10248
10249   memset (order, 0, MAX_LDM_STM_OPS * sizeof (int));
10250
10251   /* Loop over the operands and check that the memory references are
10252      suitable (i.e. immediate offsets from the same base register).  At
10253      the same time, extract the target register, and the memory
10254      offsets.  */
10255   for (i = 0; i < nops; i++)
10256     {
10257       rtx reg;
10258       rtx offset;
10259
10260       /* Convert a subreg of a mem into the mem itself.  */
10261       if (GET_CODE (operands[nops + i]) == SUBREG)
10262         operands[nops + i] = alter_subreg (operands + (nops + i));
10263
10264       gcc_assert (GET_CODE (operands[nops + i]) == MEM);
10265
10266       /* Don't reorder volatile memory references; it doesn't seem worth
10267          looking for the case where the order is ok anyway.  */
10268       if (MEM_VOLATILE_P (operands[nops + i]))
10269         return 0;
10270
10271       offset = const0_rtx;
10272
10273       if ((GET_CODE (reg = XEXP (operands[nops + i], 0)) == REG
10274            || (GET_CODE (reg) == SUBREG
10275                && GET_CODE (reg = SUBREG_REG (reg)) == REG))
10276           || (GET_CODE (XEXP (operands[nops + i], 0)) == PLUS
10277               && ((GET_CODE (reg = XEXP (XEXP (operands[nops + i], 0), 0))
10278                    == REG)
10279                   || (GET_CODE (reg) == SUBREG
10280                       && GET_CODE (reg = SUBREG_REG (reg)) == REG))
10281               && (GET_CODE (offset = XEXP (XEXP (operands[nops + i], 0), 1))
10282                   == CONST_INT)))
10283         {
10284           if (i == 0)
10285             {
10286               base_reg = REGNO (reg);
10287               base_reg_rtx = reg;
10288               if (TARGET_THUMB1 && base_reg > LAST_LO_REGNUM)
10289                 return 0;
10290             }
10291           else if (base_reg != (int) REGNO (reg))
10292             /* Not addressed from the same base register.  */
10293             return 0;
10294
10295           unsorted_regs[i] = (GET_CODE (operands[i]) == REG
10296                               ? REGNO (operands[i])
10297                               : REGNO (SUBREG_REG (operands[i])));
10298
10299           /* If it isn't an integer register, or if it overwrites the
10300              base register but isn't the last insn in the list, then
10301              we can't do this.  */
10302           if (unsorted_regs[i] < 0
10303               || (TARGET_THUMB1 && unsorted_regs[i] > LAST_LO_REGNUM)
10304               || unsorted_regs[i] > 14
10305               || (i != nops - 1 && unsorted_regs[i] == base_reg))
10306             return 0;
10307
10308           unsorted_offsets[i] = INTVAL (offset);
10309           if (i == 0 || unsorted_offsets[i] < unsorted_offsets[order[0]])
10310             order[0] = i;
10311         }
10312       else
10313         /* Not a suitable memory address.  */
10314         return 0;
10315     }
10316
10317   /* All the useful information has now been extracted from the
10318      operands into unsorted_regs and unsorted_offsets; additionally,
10319      order[0] has been set to the lowest offset in the list.  Sort
10320      the offsets into order, verifying that they are adjacent, and
10321      check that the register numbers are ascending.  */
10322   if (!compute_offset_order (nops, unsorted_offsets, order,
10323                              check_regs ? unsorted_regs : NULL))
10324     return 0;
10325
10326   if (saved_order)
10327     memcpy (saved_order, order, sizeof order);
10328
10329   if (base)
10330     {
10331       *base = base_reg;
10332
10333       for (i = 0; i < nops; i++)
10334         regs[i] = unsorted_regs[check_regs ? order[i] : i];
10335
10336       *load_offset = unsorted_offsets[order[0]];
10337     }
10338
10339   if (TARGET_THUMB1
10340       && !peep2_reg_dead_p (nops, base_reg_rtx))
10341     return 0;
10342
10343   if (unsorted_offsets[order[0]] == 0)
10344     ldm_case = 1; /* ldmia */
10345   else if (TARGET_ARM && unsorted_offsets[order[0]] == 4)
10346     ldm_case = 2; /* ldmib */
10347   else if (TARGET_ARM && unsorted_offsets[order[nops - 1]] == 0)
10348     ldm_case = 3; /* ldmda */
10349   else if (TARGET_32BIT && unsorted_offsets[order[nops - 1]] == -4)
10350     ldm_case = 4; /* ldmdb */
10351   else if (const_ok_for_arm (unsorted_offsets[order[0]])
10352            || const_ok_for_arm (-unsorted_offsets[order[0]]))
10353     ldm_case = 5;
10354   else
10355     return 0;
10356
10357   if (!multiple_operation_profitable_p (false, nops,
10358                                         ldm_case == 5
10359                                         ? unsorted_offsets[order[0]] : 0))
10360     return 0;
10361
10362   return ldm_case;
10363 }
10364
10365 /* Used to determine in a peephole whether a sequence of store instructions can
10366    be changed into a store-multiple instruction.
10367    NOPS is the number of separate store instructions we are examining.
10368    NOPS_TOTAL is the total number of instructions recognized by the peephole
10369    pattern.
10370    The first NOPS entries in OPERANDS are the source registers, the next
10371    NOPS entries are memory operands.  If this function is successful, *BASE is
10372    set to the common base register of the memory accesses; *LOAD_OFFSET is set
10373    to the first memory location's offset from that base register.  REGS is an
10374    array filled in with the source register numbers, REG_RTXS (if nonnull) is
10375    likewise filled with the corresponding rtx's.
10376    SAVED_ORDER (if nonnull), is an array filled in with an order that maps insn
10377    numbers to an ascending order of stores.
10378    If CHECK_REGS is true, the sequence of registers in *REGS matches the stores
10379    from ascending memory locations, and the function verifies that the register
10380    numbers are themselves ascending.  If CHECK_REGS is false, the register
10381    numbers are stored in the order they are found in the operands.  */
10382 static int
10383 store_multiple_sequence (rtx *operands, int nops, int nops_total,
10384                          int *regs, rtx *reg_rtxs, int *saved_order, int *base,
10385                          HOST_WIDE_INT *load_offset, bool check_regs)
10386 {
10387   int unsorted_regs[MAX_LDM_STM_OPS];
10388   rtx unsorted_reg_rtxs[MAX_LDM_STM_OPS];
10389   HOST_WIDE_INT unsorted_offsets[MAX_LDM_STM_OPS];
10390   int order[MAX_LDM_STM_OPS];
10391   int base_reg = -1;
10392   rtx base_reg_rtx = NULL;
10393   int i, stm_case;
10394
10395   /* Write back of base register is currently only supported for Thumb 1.  */
10396   int base_writeback = TARGET_THUMB1;
10397
10398   /* Can only handle up to MAX_LDM_STM_OPS insns at present, though could be
10399      easily extended if required.  */
10400   gcc_assert (nops >= 2 && nops <= MAX_LDM_STM_OPS);
10401
10402   memset (order, 0, MAX_LDM_STM_OPS * sizeof (int));
10403
10404   /* Loop over the operands and check that the memory references are
10405      suitable (i.e. immediate offsets from the same base register).  At
10406      the same time, extract the target register, and the memory
10407      offsets.  */
10408   for (i = 0; i < nops; i++)
10409     {
10410       rtx reg;
10411       rtx offset;
10412
10413       /* Convert a subreg of a mem into the mem itself.  */
10414       if (GET_CODE (operands[nops + i]) == SUBREG)
10415         operands[nops + i] = alter_subreg (operands + (nops + i));
10416
10417       gcc_assert (GET_CODE (operands[nops + i]) == MEM);
10418
10419       /* Don't reorder volatile memory references; it doesn't seem worth
10420          looking for the case where the order is ok anyway.  */
10421       if (MEM_VOLATILE_P (operands[nops + i]))
10422         return 0;
10423
10424       offset = const0_rtx;
10425
10426       if ((GET_CODE (reg = XEXP (operands[nops + i], 0)) == REG
10427            || (GET_CODE (reg) == SUBREG
10428                && GET_CODE (reg = SUBREG_REG (reg)) == REG))
10429           || (GET_CODE (XEXP (operands[nops + i], 0)) == PLUS
10430               && ((GET_CODE (reg = XEXP (XEXP (operands[nops + i], 0), 0))
10431                    == REG)
10432                   || (GET_CODE (reg) == SUBREG
10433                       && GET_CODE (reg = SUBREG_REG (reg)) == REG))
10434               && (GET_CODE (offset = XEXP (XEXP (operands[nops + i], 0), 1))
10435                   == CONST_INT)))
10436         {
10437           unsorted_reg_rtxs[i] = (GET_CODE (operands[i]) == REG
10438                                   ? operands[i] : SUBREG_REG (operands[i]));
10439           unsorted_regs[i] = REGNO (unsorted_reg_rtxs[i]);
10440
10441           if (i == 0)
10442             {
10443               base_reg = REGNO (reg);
10444               base_reg_rtx = reg;
10445               if (TARGET_THUMB1 && base_reg > LAST_LO_REGNUM)
10446                 return 0;
10447             }
10448           else if (base_reg != (int) REGNO (reg))
10449             /* Not addressed from the same base register.  */
10450             return 0;
10451
10452           /* If it isn't an integer register, then we can't do this.  */
10453           if (unsorted_regs[i] < 0
10454               || (TARGET_THUMB1 && unsorted_regs[i] > LAST_LO_REGNUM)
10455               /* The effects are unpredictable if the base register is
10456                  both updated and stored.  */
10457               || (base_writeback && unsorted_regs[i] == base_reg)
10458               || (TARGET_THUMB2 && unsorted_regs[i] == SP_REGNUM)
10459               || unsorted_regs[i] > 14)
10460             return 0;
10461
10462           unsorted_offsets[i] = INTVAL (offset);
10463           if (i == 0 || unsorted_offsets[i] < unsorted_offsets[order[0]])
10464             order[0] = i;
10465         }
10466       else
10467         /* Not a suitable memory address.  */
10468         return 0;
10469     }
10470
10471   /* All the useful information has now been extracted from the
10472      operands into unsorted_regs and unsorted_offsets; additionally,
10473      order[0] has been set to the lowest offset in the list.  Sort
10474      the offsets into order, verifying that they are adjacent, and
10475      check that the register numbers are ascending.  */
10476   if (!compute_offset_order (nops, unsorted_offsets, order,
10477                              check_regs ? unsorted_regs : NULL))
10478     return 0;
10479
10480   if (saved_order)
10481     memcpy (saved_order, order, sizeof order);
10482
10483   if (base)
10484     {
10485       *base = base_reg;
10486
10487       for (i = 0; i < nops; i++)
10488         {
10489           regs[i] = unsorted_regs[check_regs ? order[i] : i];
10490           if (reg_rtxs)
10491             reg_rtxs[i] = unsorted_reg_rtxs[check_regs ? order[i] : i];
10492         }
10493
10494       *load_offset = unsorted_offsets[order[0]];
10495     }
10496
10497   if (TARGET_THUMB1
10498       && !peep2_reg_dead_p (nops_total, base_reg_rtx))
10499     return 0;
10500
10501   if (unsorted_offsets[order[0]] == 0)
10502     stm_case = 1; /* stmia */
10503   else if (TARGET_ARM && unsorted_offsets[order[0]] == 4)
10504     stm_case = 2; /* stmib */
10505   else if (TARGET_ARM && unsorted_offsets[order[nops - 1]] == 0)
10506     stm_case = 3; /* stmda */
10507   else if (TARGET_32BIT && unsorted_offsets[order[nops - 1]] == -4)
10508     stm_case = 4; /* stmdb */
10509   else
10510     return 0;
10511
10512   if (!multiple_operation_profitable_p (false, nops, 0))
10513     return 0;
10514
10515   return stm_case;
10516 }
10517 \f
10518 /* Routines for use in generating RTL.  */
10519
10520 /* Generate a load-multiple instruction.  COUNT is the number of loads in
10521    the instruction; REGS and MEMS are arrays containing the operands.
10522    BASEREG is the base register to be used in addressing the memory operands.
10523    WBACK_OFFSET is nonzero if the instruction should update the base
10524    register.  */
10525
10526 static rtx
10527 arm_gen_load_multiple_1 (int count, int *regs, rtx *mems, rtx basereg,
10528                          HOST_WIDE_INT wback_offset)
10529 {
10530   int i = 0, j;
10531   rtx result;
10532
10533   if (!multiple_operation_profitable_p (false, count, 0))
10534     {
10535       rtx seq;
10536
10537       start_sequence ();
10538
10539       for (i = 0; i < count; i++)
10540         emit_move_insn (gen_rtx_REG (SImode, regs[i]), mems[i]);
10541
10542       if (wback_offset != 0)
10543         emit_move_insn (basereg, plus_constant (basereg, wback_offset));
10544
10545       seq = get_insns ();
10546       end_sequence ();
10547
10548       return seq;
10549     }
10550
10551   result = gen_rtx_PARALLEL (VOIDmode,
10552                              rtvec_alloc (count + (wback_offset != 0 ? 1 : 0)));
10553   if (wback_offset != 0)
10554     {
10555       XVECEXP (result, 0, 0)
10556         = gen_rtx_SET (VOIDmode, basereg,
10557                        plus_constant (basereg, wback_offset));
10558       i = 1;
10559       count++;
10560     }
10561
10562   for (j = 0; i < count; i++, j++)
10563     XVECEXP (result, 0, i)
10564       = gen_rtx_SET (VOIDmode, gen_rtx_REG (SImode, regs[j]), mems[j]);
10565
10566   return result;
10567 }
10568
10569 /* Generate a store-multiple instruction.  COUNT is the number of stores in
10570    the instruction; REGS and MEMS are arrays containing the operands.
10571    BASEREG is the base register to be used in addressing the memory operands.
10572    WBACK_OFFSET is nonzero if the instruction should update the base
10573    register.  */
10574
10575 static rtx
10576 arm_gen_store_multiple_1 (int count, int *regs, rtx *mems, rtx basereg,
10577                           HOST_WIDE_INT wback_offset)
10578 {
10579   int i = 0, j;
10580   rtx result;
10581
10582   if (GET_CODE (basereg) == PLUS)
10583     basereg = XEXP (basereg, 0);
10584
10585   if (!multiple_operation_profitable_p (false, count, 0))
10586     {
10587       rtx seq;
10588
10589       start_sequence ();
10590
10591       for (i = 0; i < count; i++)
10592         emit_move_insn (mems[i], gen_rtx_REG (SImode, regs[i]));
10593
10594       if (wback_offset != 0)
10595         emit_move_insn (basereg, plus_constant (basereg, wback_offset));
10596
10597       seq = get_insns ();
10598       end_sequence ();
10599
10600       return seq;
10601     }
10602
10603   result = gen_rtx_PARALLEL (VOIDmode,
10604                              rtvec_alloc (count + (wback_offset != 0 ? 1 : 0)));
10605   if (wback_offset != 0)
10606     {
10607       XVECEXP (result, 0, 0)
10608         = gen_rtx_SET (VOIDmode, basereg,
10609                        plus_constant (basereg, wback_offset));
10610       i = 1;
10611       count++;
10612     }
10613
10614   for (j = 0; i < count; i++, j++)
10615     XVECEXP (result, 0, i)
10616       = gen_rtx_SET (VOIDmode, mems[j], gen_rtx_REG (SImode, regs[j]));
10617
10618   return result;
10619 }
10620
10621 /* Generate either a load-multiple or a store-multiple instruction.  This
10622    function can be used in situations where we can start with a single MEM
10623    rtx and adjust its address upwards.
10624    COUNT is the number of operations in the instruction, not counting a
10625    possible update of the base register.  REGS is an array containing the
10626    register operands.
10627    BASEREG is the base register to be used in addressing the memory operands,
10628    which are constructed from BASEMEM.
10629    WRITE_BACK specifies whether the generated instruction should include an
10630    update of the base register.
10631    OFFSETP is used to pass an offset to and from this function; this offset
10632    is not used when constructing the address (instead BASEMEM should have an
10633    appropriate offset in its address), it is used only for setting
10634    MEM_OFFSET.  It is updated only if WRITE_BACK is true.*/
10635
10636 static rtx
10637 arm_gen_multiple_op (bool is_load, int *regs, int count, rtx basereg,
10638                      bool write_back, rtx basemem, HOST_WIDE_INT *offsetp)
10639 {
10640   rtx mems[MAX_LDM_STM_OPS];
10641   HOST_WIDE_INT offset = *offsetp;
10642   int i;
10643
10644   gcc_assert (count <= MAX_LDM_STM_OPS);
10645
10646   if (GET_CODE (basereg) == PLUS)
10647     basereg = XEXP (basereg, 0);
10648
10649   for (i = 0; i < count; i++)
10650     {
10651       rtx addr = plus_constant (basereg, i * 4);
10652       mems[i] = adjust_automodify_address_nv (basemem, SImode, addr, offset);
10653       offset += 4;
10654     }
10655
10656   if (write_back)
10657     *offsetp = offset;
10658
10659   if (is_load)
10660     return arm_gen_load_multiple_1 (count, regs, mems, basereg,
10661                                     write_back ? 4 * count : 0);
10662   else
10663     return arm_gen_store_multiple_1 (count, regs, mems, basereg,
10664                                      write_back ? 4 * count : 0);
10665 }
10666
10667 rtx
10668 arm_gen_load_multiple (int *regs, int count, rtx basereg, int write_back,
10669                        rtx basemem, HOST_WIDE_INT *offsetp)
10670 {
10671   return arm_gen_multiple_op (TRUE, regs, count, basereg, write_back, basemem,
10672                               offsetp);
10673 }
10674
10675 rtx
10676 arm_gen_store_multiple (int *regs, int count, rtx basereg, int write_back,
10677                         rtx basemem, HOST_WIDE_INT *offsetp)
10678 {
10679   return arm_gen_multiple_op (FALSE, regs, count, basereg, write_back, basemem,
10680                               offsetp);
10681 }
10682
10683 /* Called from a peephole2 expander to turn a sequence of loads into an
10684    LDM instruction.  OPERANDS are the operands found by the peephole matcher;
10685    NOPS indicates how many separate loads we are trying to combine.  SORT_REGS
10686    is true if we can reorder the registers because they are used commutatively
10687    subsequently.
10688    Returns true iff we could generate a new instruction.  */
10689
10690 bool
10691 gen_ldm_seq (rtx *operands, int nops, bool sort_regs)
10692 {
10693   int regs[MAX_LDM_STM_OPS], mem_order[MAX_LDM_STM_OPS];
10694   rtx mems[MAX_LDM_STM_OPS];
10695   int i, j, base_reg;
10696   rtx base_reg_rtx;
10697   HOST_WIDE_INT offset;
10698   int write_back = FALSE;
10699   int ldm_case;
10700   rtx addr;
10701
10702   ldm_case = load_multiple_sequence (operands, nops, regs, mem_order,
10703                                      &base_reg, &offset, !sort_regs);
10704
10705   if (ldm_case == 0)
10706     return false;
10707
10708   if (sort_regs)
10709     for (i = 0; i < nops - 1; i++)
10710       for (j = i + 1; j < nops; j++)
10711         if (regs[i] > regs[j])
10712           {
10713             int t = regs[i];
10714             regs[i] = regs[j];
10715             regs[j] = t;
10716           }
10717   base_reg_rtx = gen_rtx_REG (Pmode, base_reg);
10718
10719   if (TARGET_THUMB1)
10720     {
10721       gcc_assert (peep2_reg_dead_p (nops, base_reg_rtx));
10722       gcc_assert (ldm_case == 1 || ldm_case == 5);
10723       write_back = TRUE;
10724     }
10725
10726   if (ldm_case == 5)
10727     {
10728       rtx newbase = TARGET_THUMB1 ? base_reg_rtx : gen_rtx_REG (SImode, regs[0]);
10729       emit_insn (gen_addsi3 (newbase, base_reg_rtx, GEN_INT (offset)));
10730       offset = 0;
10731       if (!TARGET_THUMB1)
10732         {
10733           base_reg = regs[0];
10734           base_reg_rtx = newbase;
10735         }
10736     }
10737
10738   for (i = 0; i < nops; i++)
10739     {
10740       addr = plus_constant (base_reg_rtx, offset + i * 4);
10741       mems[i] = adjust_automodify_address_nv (operands[nops + mem_order[i]],
10742                                               SImode, addr, 0);
10743     }
10744   emit_insn (arm_gen_load_multiple_1 (nops, regs, mems, base_reg_rtx,
10745                                       write_back ? offset + i * 4 : 0));
10746   return true;
10747 }
10748
10749 /* Called from a peephole2 expander to turn a sequence of stores into an
10750    STM instruction.  OPERANDS are the operands found by the peephole matcher;
10751    NOPS indicates how many separate stores we are trying to combine.
10752    Returns true iff we could generate a new instruction.  */
10753
10754 bool
10755 gen_stm_seq (rtx *operands, int nops)
10756 {
10757   int i;
10758   int regs[MAX_LDM_STM_OPS], mem_order[MAX_LDM_STM_OPS];
10759   rtx mems[MAX_LDM_STM_OPS];
10760   int base_reg;
10761   rtx base_reg_rtx;
10762   HOST_WIDE_INT offset;
10763   int write_back = FALSE;
10764   int stm_case;
10765   rtx addr;
10766   bool base_reg_dies;
10767
10768   stm_case = store_multiple_sequence (operands, nops, nops, regs, NULL,
10769                                       mem_order, &base_reg, &offset, true);
10770
10771   if (stm_case == 0)
10772     return false;
10773
10774   base_reg_rtx = gen_rtx_REG (Pmode, base_reg);
10775
10776   base_reg_dies = peep2_reg_dead_p (nops, base_reg_rtx);
10777   if (TARGET_THUMB1)
10778     {
10779       gcc_assert (base_reg_dies);
10780       write_back = TRUE;
10781     }
10782
10783   if (stm_case == 5)
10784     {
10785       gcc_assert (base_reg_dies);
10786       emit_insn (gen_addsi3 (base_reg_rtx, base_reg_rtx, GEN_INT (offset)));
10787       offset = 0;
10788     }
10789
10790   addr = plus_constant (base_reg_rtx, offset);
10791
10792   for (i = 0; i < nops; i++)
10793     {
10794       addr = plus_constant (base_reg_rtx, offset + i * 4);
10795       mems[i] = adjust_automodify_address_nv (operands[nops + mem_order[i]],
10796                                               SImode, addr, 0);
10797     }
10798   emit_insn (arm_gen_store_multiple_1 (nops, regs, mems, base_reg_rtx,
10799                                        write_back ? offset + i * 4 : 0));
10800   return true;
10801 }
10802
10803 /* Called from a peephole2 expander to turn a sequence of stores that are
10804    preceded by constant loads into an STM instruction.  OPERANDS are the
10805    operands found by the peephole matcher; NOPS indicates how many
10806    separate stores we are trying to combine; there are 2 * NOPS
10807    instructions in the peephole.
10808    Returns true iff we could generate a new instruction.  */
10809
10810 bool
10811 gen_const_stm_seq (rtx *operands, int nops)
10812 {
10813   int regs[MAX_LDM_STM_OPS], sorted_regs[MAX_LDM_STM_OPS];
10814   int reg_order[MAX_LDM_STM_OPS], mem_order[MAX_LDM_STM_OPS];
10815   rtx reg_rtxs[MAX_LDM_STM_OPS], orig_reg_rtxs[MAX_LDM_STM_OPS];
10816   rtx mems[MAX_LDM_STM_OPS];
10817   int base_reg;
10818   rtx base_reg_rtx;
10819   HOST_WIDE_INT offset;
10820   int write_back = FALSE;
10821   int stm_case;
10822   rtx addr;
10823   bool base_reg_dies;
10824   int i, j;
10825   HARD_REG_SET allocated;
10826
10827   stm_case = store_multiple_sequence (operands, nops, 2 * nops, regs, reg_rtxs,
10828                                       mem_order, &base_reg, &offset, false);
10829
10830   if (stm_case == 0)
10831     return false;
10832
10833   memcpy (orig_reg_rtxs, reg_rtxs, sizeof orig_reg_rtxs);
10834
10835   /* If the same register is used more than once, try to find a free
10836      register.  */
10837   CLEAR_HARD_REG_SET (allocated);
10838   for (i = 0; i < nops; i++)
10839     {
10840       for (j = i + 1; j < nops; j++)
10841         if (regs[i] == regs[j])
10842           {
10843             rtx t = peep2_find_free_register (0, nops * 2,
10844                                               TARGET_THUMB1 ? "l" : "r",
10845                                               SImode, &allocated);
10846             if (t == NULL_RTX)
10847               return false;
10848             reg_rtxs[i] = t;
10849             regs[i] = REGNO (t);
10850           }
10851     }
10852
10853   /* Compute an ordering that maps the register numbers to an ascending
10854      sequence.  */
10855   reg_order[0] = 0;
10856   for (i = 0; i < nops; i++)
10857     if (regs[i] < regs[reg_order[0]])
10858       reg_order[0] = i;
10859
10860   for (i = 1; i < nops; i++)
10861     {
10862       int this_order = reg_order[i - 1];
10863       for (j = 0; j < nops; j++)
10864         if (regs[j] > regs[reg_order[i - 1]]
10865             && (this_order == reg_order[i - 1]
10866                 || regs[j] < regs[this_order]))
10867           this_order = j;
10868       reg_order[i] = this_order;
10869     }
10870
10871   /* Ensure that registers that must be live after the instruction end
10872      up with the correct value.  */
10873   for (i = 0; i < nops; i++)
10874     {
10875       int this_order = reg_order[i];
10876       if ((this_order != mem_order[i]
10877            || orig_reg_rtxs[this_order] != reg_rtxs[this_order])
10878           && !peep2_reg_dead_p (nops * 2, orig_reg_rtxs[this_order]))
10879         return false;
10880     }
10881
10882   /* Load the constants.  */
10883   for (i = 0; i < nops; i++)
10884     {
10885       rtx op = operands[2 * nops + mem_order[i]];
10886       sorted_regs[i] = regs[reg_order[i]];
10887       emit_move_insn (reg_rtxs[reg_order[i]], op);
10888     }
10889
10890   base_reg_rtx = gen_rtx_REG (Pmode, base_reg);
10891
10892   base_reg_dies = peep2_reg_dead_p (nops * 2, base_reg_rtx);
10893   if (TARGET_THUMB1)
10894     {
10895       gcc_assert (base_reg_dies);
10896       write_back = TRUE;
10897     }
10898
10899   if (stm_case == 5)
10900     {
10901       gcc_assert (base_reg_dies);
10902       emit_insn (gen_addsi3 (base_reg_rtx, base_reg_rtx, GEN_INT (offset)));
10903       offset = 0;
10904     }
10905
10906   addr = plus_constant (base_reg_rtx, offset);
10907
10908   for (i = 0; i < nops; i++)
10909     {
10910       addr = plus_constant (base_reg_rtx, offset + i * 4);
10911       mems[i] = adjust_automodify_address_nv (operands[nops + mem_order[i]],
10912                                               SImode, addr, 0);
10913     }
10914   emit_insn (arm_gen_store_multiple_1 (nops, sorted_regs, mems, base_reg_rtx,
10915                                        write_back ? offset + i * 4 : 0));
10916   return true;
10917 }
10918
10919 /* Copy a block of memory using plain ldr/str/ldrh/strh instructions, to permit
10920    unaligned copies on processors which support unaligned semantics for those
10921    instructions.  INTERLEAVE_FACTOR can be used to attempt to hide load latency
10922    (using more registers) by doing e.g. load/load/store/store for a factor of 2.
10923    An interleave factor of 1 (the minimum) will perform no interleaving. 
10924    Load/store multiple are used for aligned addresses where possible.  */
10925
10926 static void
10927 arm_block_move_unaligned_straight (rtx dstbase, rtx srcbase,
10928                                    HOST_WIDE_INT length,
10929                                    unsigned int interleave_factor)
10930 {
10931   rtx *regs = XALLOCAVEC (rtx, interleave_factor);
10932   int *regnos = XALLOCAVEC (int, interleave_factor);
10933   HOST_WIDE_INT block_size_bytes = interleave_factor * UNITS_PER_WORD;
10934   HOST_WIDE_INT i, j;
10935   HOST_WIDE_INT remaining = length, words;
10936   rtx halfword_tmp = NULL, byte_tmp = NULL;
10937   rtx dst, src;
10938   bool src_aligned = MEM_ALIGN (srcbase) >= BITS_PER_WORD;
10939   bool dst_aligned = MEM_ALIGN (dstbase) >= BITS_PER_WORD;
10940   HOST_WIDE_INT srcoffset, dstoffset;
10941   HOST_WIDE_INT src_autoinc, dst_autoinc;
10942   rtx mem, addr;
10943   
10944   gcc_assert (1 <= interleave_factor && interleave_factor <= 4);
10945   
10946   /* Use hard registers if we have aligned source or destination so we can use
10947      load/store multiple with contiguous registers.  */
10948   if (dst_aligned || src_aligned)
10949     for (i = 0; i < interleave_factor; i++)
10950       regs[i] = gen_rtx_REG (SImode, i);
10951   else
10952     for (i = 0; i < interleave_factor; i++)
10953       regs[i] = gen_reg_rtx (SImode);
10954
10955   dst = copy_addr_to_reg (XEXP (dstbase, 0));
10956   src = copy_addr_to_reg (XEXP (srcbase, 0));
10957
10958   srcoffset = dstoffset = 0;
10959   
10960   /* Calls to arm_gen_load_multiple and arm_gen_store_multiple update SRC/DST.
10961      For copying the last bytes we want to subtract this offset again.  */
10962   src_autoinc = dst_autoinc = 0;
10963
10964   for (i = 0; i < interleave_factor; i++)
10965     regnos[i] = i;
10966
10967   /* Copy BLOCK_SIZE_BYTES chunks.  */
10968
10969   for (i = 0; i + block_size_bytes <= length; i += block_size_bytes)
10970     {
10971       /* Load words.  */
10972       if (src_aligned && interleave_factor > 1)
10973         {
10974           emit_insn (arm_gen_load_multiple (regnos, interleave_factor, src,
10975                                             TRUE, srcbase, &srcoffset));
10976           src_autoinc += UNITS_PER_WORD * interleave_factor;
10977         }
10978       else
10979         {
10980           for (j = 0; j < interleave_factor; j++)
10981             {
10982               addr = plus_constant (src, srcoffset + j * UNITS_PER_WORD
10983                                          - src_autoinc);
10984               mem = adjust_automodify_address (srcbase, SImode, addr,
10985                                                srcoffset + j * UNITS_PER_WORD);
10986               emit_insn (gen_unaligned_loadsi (regs[j], mem));
10987             }
10988           srcoffset += block_size_bytes;
10989         }
10990
10991       /* Store words.  */
10992       if (dst_aligned && interleave_factor > 1)
10993         {
10994           emit_insn (arm_gen_store_multiple (regnos, interleave_factor, dst,
10995                                              TRUE, dstbase, &dstoffset));
10996           dst_autoinc += UNITS_PER_WORD * interleave_factor;
10997         }
10998       else
10999         {
11000           for (j = 0; j < interleave_factor; j++)
11001             {
11002               addr = plus_constant (dst, dstoffset + j * UNITS_PER_WORD
11003                                          - dst_autoinc);
11004               mem = adjust_automodify_address (dstbase, SImode, addr,
11005                                                dstoffset + j * UNITS_PER_WORD);
11006               emit_insn (gen_unaligned_storesi (mem, regs[j]));
11007             }
11008           dstoffset += block_size_bytes;
11009         }
11010
11011       remaining -= block_size_bytes;
11012     }
11013   
11014   /* Copy any whole words left (note these aren't interleaved with any
11015      subsequent halfword/byte load/stores in the interests of simplicity).  */
11016   
11017   words = remaining / UNITS_PER_WORD;
11018
11019   gcc_assert (words < interleave_factor);
11020   
11021   if (src_aligned && words > 1)
11022     {
11023       emit_insn (arm_gen_load_multiple (regnos, words, src, TRUE, srcbase,
11024                                         &srcoffset));
11025       src_autoinc += UNITS_PER_WORD * words;
11026     }
11027   else
11028     {
11029       for (j = 0; j < words; j++)
11030         {
11031           addr = plus_constant (src,
11032                                 srcoffset + j * UNITS_PER_WORD - src_autoinc);
11033           mem = adjust_automodify_address (srcbase, SImode, addr,
11034                                            srcoffset + j * UNITS_PER_WORD);
11035           emit_insn (gen_unaligned_loadsi (regs[j], mem));
11036         }
11037       srcoffset += words * UNITS_PER_WORD;
11038     }
11039
11040   if (dst_aligned && words > 1)
11041     {
11042       emit_insn (arm_gen_store_multiple (regnos, words, dst, TRUE, dstbase,
11043                                          &dstoffset));
11044       dst_autoinc += words * UNITS_PER_WORD;
11045     }
11046   else
11047     {
11048       for (j = 0; j < words; j++)
11049         {
11050           addr = plus_constant (dst,
11051                                 dstoffset + j * UNITS_PER_WORD - dst_autoinc);
11052           mem = adjust_automodify_address (dstbase, SImode, addr,
11053                                            dstoffset + j * UNITS_PER_WORD);
11054           emit_insn (gen_unaligned_storesi (mem, regs[j]));
11055         }
11056       dstoffset += words * UNITS_PER_WORD;
11057     }
11058
11059   remaining -= words * UNITS_PER_WORD;
11060   
11061   gcc_assert (remaining < 4);
11062   
11063   /* Copy a halfword if necessary.  */
11064   
11065   if (remaining >= 2)
11066     {
11067       halfword_tmp = gen_reg_rtx (SImode);
11068
11069       addr = plus_constant (src, srcoffset - src_autoinc);
11070       mem = adjust_automodify_address (srcbase, HImode, addr, srcoffset);
11071       emit_insn (gen_unaligned_loadhiu (halfword_tmp, mem));
11072
11073       /* Either write out immediately, or delay until we've loaded the last
11074          byte, depending on interleave factor.  */
11075       if (interleave_factor == 1)
11076         {
11077           addr = plus_constant (dst, dstoffset - dst_autoinc);
11078           mem = adjust_automodify_address (dstbase, HImode, addr, dstoffset);
11079           emit_insn (gen_unaligned_storehi (mem,
11080                        gen_lowpart (HImode, halfword_tmp)));
11081           halfword_tmp = NULL;
11082           dstoffset += 2;
11083         }
11084
11085       remaining -= 2;
11086       srcoffset += 2;
11087     }
11088   
11089   gcc_assert (remaining < 2);
11090   
11091   /* Copy last byte.  */
11092   
11093   if ((remaining & 1) != 0)
11094     {
11095       byte_tmp = gen_reg_rtx (SImode);
11096
11097       addr = plus_constant (src, srcoffset - src_autoinc);
11098       mem = adjust_automodify_address (srcbase, QImode, addr, srcoffset);
11099       emit_move_insn (gen_lowpart (QImode, byte_tmp), mem);
11100
11101       if (interleave_factor == 1)
11102         {
11103           addr = plus_constant (dst, dstoffset - dst_autoinc);
11104           mem = adjust_automodify_address (dstbase, QImode, addr, dstoffset);
11105           emit_move_insn (mem, gen_lowpart (QImode, byte_tmp));
11106           byte_tmp = NULL;
11107           dstoffset++;
11108         }
11109
11110       remaining--;
11111       srcoffset++;
11112     }
11113   
11114   /* Store last halfword if we haven't done so already.  */
11115   
11116   if (halfword_tmp)
11117     {
11118       addr = plus_constant (dst, dstoffset - dst_autoinc);
11119       mem = adjust_automodify_address (dstbase, HImode, addr, dstoffset);
11120       emit_insn (gen_unaligned_storehi (mem,
11121                    gen_lowpart (HImode, halfword_tmp)));
11122       dstoffset += 2;
11123     }
11124
11125   /* Likewise for last byte.  */
11126
11127   if (byte_tmp)
11128     {
11129       addr = plus_constant (dst, dstoffset - dst_autoinc);
11130       mem = adjust_automodify_address (dstbase, QImode, addr, dstoffset);
11131       emit_move_insn (mem, gen_lowpart (QImode, byte_tmp));
11132       dstoffset++;
11133     }
11134   
11135   gcc_assert (remaining == 0 && srcoffset == dstoffset);
11136 }
11137
11138 /* From mips_adjust_block_mem:
11139
11140    Helper function for doing a loop-based block operation on memory
11141    reference MEM.  Each iteration of the loop will operate on LENGTH
11142    bytes of MEM.
11143
11144    Create a new base register for use within the loop and point it to
11145    the start of MEM.  Create a new memory reference that uses this
11146    register.  Store them in *LOOP_REG and *LOOP_MEM respectively.  */
11147
11148 static void
11149 arm_adjust_block_mem (rtx mem, HOST_WIDE_INT length, rtx *loop_reg,
11150                       rtx *loop_mem)
11151 {
11152   *loop_reg = copy_addr_to_reg (XEXP (mem, 0));
11153   
11154   /* Although the new mem does not refer to a known location,
11155      it does keep up to LENGTH bytes of alignment.  */
11156   *loop_mem = change_address (mem, BLKmode, *loop_reg);
11157   set_mem_align (*loop_mem, MIN (MEM_ALIGN (mem), length * BITS_PER_UNIT));
11158 }
11159
11160 /* From mips_block_move_loop:
11161
11162    Move LENGTH bytes from SRC to DEST using a loop that moves BYTES_PER_ITER
11163    bytes at a time.  LENGTH must be at least BYTES_PER_ITER.  Assume that
11164    the memory regions do not overlap.  */
11165
11166 static void
11167 arm_block_move_unaligned_loop (rtx dest, rtx src, HOST_WIDE_INT length,
11168                                unsigned int interleave_factor,
11169                                HOST_WIDE_INT bytes_per_iter)
11170 {
11171   rtx label, src_reg, dest_reg, final_src, test;
11172   HOST_WIDE_INT leftover;
11173   
11174   leftover = length % bytes_per_iter;
11175   length -= leftover;
11176   
11177   /* Create registers and memory references for use within the loop.  */
11178   arm_adjust_block_mem (src, bytes_per_iter, &src_reg, &src);
11179   arm_adjust_block_mem (dest, bytes_per_iter, &dest_reg, &dest);
11180   
11181   /* Calculate the value that SRC_REG should have after the last iteration of
11182      the loop.  */
11183   final_src = expand_simple_binop (Pmode, PLUS, src_reg, GEN_INT (length),
11184                                    0, 0, OPTAB_WIDEN);
11185
11186   /* Emit the start of the loop.  */
11187   label = gen_label_rtx ();
11188   emit_label (label);
11189   
11190   /* Emit the loop body.  */
11191   arm_block_move_unaligned_straight (dest, src, bytes_per_iter,
11192                                      interleave_factor);
11193
11194   /* Move on to the next block.  */
11195   emit_move_insn (src_reg, plus_constant (src_reg, bytes_per_iter));
11196   emit_move_insn (dest_reg, plus_constant (dest_reg, bytes_per_iter));
11197   
11198   /* Emit the loop condition.  */
11199   test = gen_rtx_NE (VOIDmode, src_reg, final_src);
11200   emit_jump_insn (gen_cbranchsi4 (test, src_reg, final_src, label));
11201   
11202   /* Mop up any left-over bytes.  */
11203   if (leftover)
11204     arm_block_move_unaligned_straight (dest, src, leftover, interleave_factor);
11205 }
11206
11207 /* Emit a block move when either the source or destination is unaligned (not
11208    aligned to a four-byte boundary).  This may need further tuning depending on
11209    core type, optimize_size setting, etc.  */
11210
11211 static int
11212 arm_movmemqi_unaligned (rtx *operands)
11213 {
11214   HOST_WIDE_INT length = INTVAL (operands[2]);
11215   
11216   if (optimize_size)
11217     {
11218       bool src_aligned = MEM_ALIGN (operands[1]) >= BITS_PER_WORD;
11219       bool dst_aligned = MEM_ALIGN (operands[0]) >= BITS_PER_WORD;
11220       /* Inlined memcpy using ldr/str/ldrh/strh can be quite big: try to limit
11221          size of code if optimizing for size.  We'll use ldm/stm if src_aligned
11222          or dst_aligned though: allow more interleaving in those cases since the
11223          resulting code can be smaller.  */
11224       unsigned int interleave_factor = (src_aligned || dst_aligned) ? 2 : 1;
11225       HOST_WIDE_INT bytes_per_iter = (src_aligned || dst_aligned) ? 8 : 4;
11226       
11227       if (length > 12)
11228         arm_block_move_unaligned_loop (operands[0], operands[1], length,
11229                                        interleave_factor, bytes_per_iter);
11230       else
11231         arm_block_move_unaligned_straight (operands[0], operands[1], length,
11232                                            interleave_factor);
11233     }
11234   else
11235     {
11236       /* Note that the loop created by arm_block_move_unaligned_loop may be
11237          subject to loop unrolling, which makes tuning this condition a little
11238          redundant.  */
11239       if (length > 32)
11240         arm_block_move_unaligned_loop (operands[0], operands[1], length, 4, 16);
11241       else
11242         arm_block_move_unaligned_straight (operands[0], operands[1], length, 4);
11243     }
11244   
11245   return 1;
11246 }
11247
11248 int
11249 arm_gen_movmemqi (rtx *operands)
11250 {
11251   HOST_WIDE_INT in_words_to_go, out_words_to_go, last_bytes;
11252   HOST_WIDE_INT srcoffset, dstoffset;
11253   int i;
11254   rtx src, dst, srcbase, dstbase;
11255   rtx part_bytes_reg = NULL;
11256   rtx mem;
11257
11258   if (GET_CODE (operands[2]) != CONST_INT
11259       || GET_CODE (operands[3]) != CONST_INT
11260       || INTVAL (operands[2]) > 64)
11261     return 0;
11262
11263   if (unaligned_access && (INTVAL (operands[3]) & 3) != 0)
11264     return arm_movmemqi_unaligned (operands);
11265
11266   if (INTVAL (operands[3]) & 3)
11267     return 0;
11268
11269   dstbase = operands[0];
11270   srcbase = operands[1];
11271
11272   dst = copy_to_mode_reg (SImode, XEXP (dstbase, 0));
11273   src = copy_to_mode_reg (SImode, XEXP (srcbase, 0));
11274
11275   in_words_to_go = ARM_NUM_INTS (INTVAL (operands[2]));
11276   out_words_to_go = INTVAL (operands[2]) / 4;
11277   last_bytes = INTVAL (operands[2]) & 3;
11278   dstoffset = srcoffset = 0;
11279
11280   if (out_words_to_go != in_words_to_go && ((in_words_to_go - 1) & 3) != 0)
11281     part_bytes_reg = gen_rtx_REG (SImode, (in_words_to_go - 1) & 3);
11282
11283   for (i = 0; in_words_to_go >= 2; i+=4)
11284     {
11285       if (in_words_to_go > 4)
11286         emit_insn (arm_gen_load_multiple (arm_regs_in_sequence, 4, src,
11287                                           TRUE, srcbase, &srcoffset));
11288       else
11289         emit_insn (arm_gen_load_multiple (arm_regs_in_sequence, in_words_to_go,
11290                                           src, FALSE, srcbase,
11291                                           &srcoffset));
11292
11293       if (out_words_to_go)
11294         {
11295           if (out_words_to_go > 4)
11296             emit_insn (arm_gen_store_multiple (arm_regs_in_sequence, 4, dst,
11297                                                TRUE, dstbase, &dstoffset));
11298           else if (out_words_to_go != 1)
11299             emit_insn (arm_gen_store_multiple (arm_regs_in_sequence,
11300                                                out_words_to_go, dst,
11301                                                (last_bytes == 0
11302                                                 ? FALSE : TRUE),
11303                                                dstbase, &dstoffset));
11304           else
11305             {
11306               mem = adjust_automodify_address (dstbase, SImode, dst, dstoffset);
11307               emit_move_insn (mem, gen_rtx_REG (SImode, 0));
11308               if (last_bytes != 0)
11309                 {
11310                   emit_insn (gen_addsi3 (dst, dst, GEN_INT (4)));
11311                   dstoffset += 4;
11312                 }
11313             }
11314         }
11315
11316       in_words_to_go -= in_words_to_go < 4 ? in_words_to_go : 4;
11317       out_words_to_go -= out_words_to_go < 4 ? out_words_to_go : 4;
11318     }
11319
11320   /* OUT_WORDS_TO_GO will be zero here if there are byte stores to do.  */
11321   if (out_words_to_go)
11322     {
11323       rtx sreg;
11324
11325       mem = adjust_automodify_address (srcbase, SImode, src, srcoffset);
11326       sreg = copy_to_reg (mem);
11327
11328       mem = adjust_automodify_address (dstbase, SImode, dst, dstoffset);
11329       emit_move_insn (mem, sreg);
11330       in_words_to_go--;
11331
11332       gcc_assert (!in_words_to_go);     /* Sanity check */
11333     }
11334
11335   if (in_words_to_go)
11336     {
11337       gcc_assert (in_words_to_go > 0);
11338
11339       mem = adjust_automodify_address (srcbase, SImode, src, srcoffset);
11340       part_bytes_reg = copy_to_mode_reg (SImode, mem);
11341     }
11342
11343   gcc_assert (!last_bytes || part_bytes_reg);
11344
11345   if (BYTES_BIG_ENDIAN && last_bytes)
11346     {
11347       rtx tmp = gen_reg_rtx (SImode);
11348
11349       /* The bytes we want are in the top end of the word.  */
11350       emit_insn (gen_lshrsi3 (tmp, part_bytes_reg,
11351                               GEN_INT (8 * (4 - last_bytes))));
11352       part_bytes_reg = tmp;
11353
11354       while (last_bytes)
11355         {
11356           mem = adjust_automodify_address (dstbase, QImode,
11357                                            plus_constant (dst, last_bytes - 1),
11358                                            dstoffset + last_bytes - 1);
11359           emit_move_insn (mem, gen_lowpart (QImode, part_bytes_reg));
11360
11361           if (--last_bytes)
11362             {
11363               tmp = gen_reg_rtx (SImode);
11364               emit_insn (gen_lshrsi3 (tmp, part_bytes_reg, GEN_INT (8)));
11365               part_bytes_reg = tmp;
11366             }
11367         }
11368
11369     }
11370   else
11371     {
11372       if (last_bytes > 1)
11373         {
11374           mem = adjust_automodify_address (dstbase, HImode, dst, dstoffset);
11375           emit_move_insn (mem, gen_lowpart (HImode, part_bytes_reg));
11376           last_bytes -= 2;
11377           if (last_bytes)
11378             {
11379               rtx tmp = gen_reg_rtx (SImode);
11380               emit_insn (gen_addsi3 (dst, dst, const2_rtx));
11381               emit_insn (gen_lshrsi3 (tmp, part_bytes_reg, GEN_INT (16)));
11382               part_bytes_reg = tmp;
11383               dstoffset += 2;
11384             }
11385         }
11386
11387       if (last_bytes)
11388         {
11389           mem = adjust_automodify_address (dstbase, QImode, dst, dstoffset);
11390           emit_move_insn (mem, gen_lowpart (QImode, part_bytes_reg));
11391         }
11392     }
11393
11394   return 1;
11395 }
11396
11397 /* Select a dominance comparison mode if possible for a test of the general
11398    form (OP (COND_OR (X) (Y)) (const_int 0)).  We support three forms.
11399    COND_OR == DOM_CC_X_AND_Y => (X && Y)
11400    COND_OR == DOM_CC_NX_OR_Y => ((! X) || Y)
11401    COND_OR == DOM_CC_X_OR_Y => (X || Y)
11402    In all cases OP will be either EQ or NE, but we don't need to know which
11403    here.  If we are unable to support a dominance comparison we return
11404    CC mode.  This will then fail to match for the RTL expressions that
11405    generate this call.  */
11406 enum machine_mode
11407 arm_select_dominance_cc_mode (rtx x, rtx y, HOST_WIDE_INT cond_or)
11408 {
11409   enum rtx_code cond1, cond2;
11410   int swapped = 0;
11411
11412   /* Currently we will probably get the wrong result if the individual
11413      comparisons are not simple.  This also ensures that it is safe to
11414      reverse a comparison if necessary.  */
11415   if ((arm_select_cc_mode (cond1 = GET_CODE (x), XEXP (x, 0), XEXP (x, 1))
11416        != CCmode)
11417       || (arm_select_cc_mode (cond2 = GET_CODE (y), XEXP (y, 0), XEXP (y, 1))
11418           != CCmode))
11419     return CCmode;
11420
11421   /* The if_then_else variant of this tests the second condition if the
11422      first passes, but is true if the first fails.  Reverse the first
11423      condition to get a true "inclusive-or" expression.  */
11424   if (cond_or == DOM_CC_NX_OR_Y)
11425     cond1 = reverse_condition (cond1);
11426
11427   /* If the comparisons are not equal, and one doesn't dominate the other,
11428      then we can't do this.  */
11429   if (cond1 != cond2
11430       && !comparison_dominates_p (cond1, cond2)
11431       && (swapped = 1, !comparison_dominates_p (cond2, cond1)))
11432     return CCmode;
11433
11434   if (swapped)
11435     {
11436       enum rtx_code temp = cond1;
11437       cond1 = cond2;
11438       cond2 = temp;
11439     }
11440
11441   switch (cond1)
11442     {
11443     case EQ:
11444       if (cond_or == DOM_CC_X_AND_Y)
11445         return CC_DEQmode;
11446
11447       switch (cond2)
11448         {
11449         case EQ: return CC_DEQmode;
11450         case LE: return CC_DLEmode;
11451         case LEU: return CC_DLEUmode;
11452         case GE: return CC_DGEmode;
11453         case GEU: return CC_DGEUmode;
11454         default: gcc_unreachable ();
11455         }
11456
11457     case LT:
11458       if (cond_or == DOM_CC_X_AND_Y)
11459         return CC_DLTmode;
11460
11461       switch (cond2)
11462         {
11463         case  LT:
11464             return CC_DLTmode;
11465         case LE:
11466           return CC_DLEmode;
11467         case NE:
11468           return CC_DNEmode;
11469         default:
11470           gcc_unreachable ();
11471         }
11472
11473     case GT:
11474       if (cond_or == DOM_CC_X_AND_Y)
11475         return CC_DGTmode;
11476
11477       switch (cond2)
11478         {
11479         case GT:
11480           return CC_DGTmode;
11481         case GE:
11482           return CC_DGEmode;
11483         case NE:
11484           return CC_DNEmode;
11485         default:
11486           gcc_unreachable ();
11487         }
11488
11489     case LTU:
11490       if (cond_or == DOM_CC_X_AND_Y)
11491         return CC_DLTUmode;
11492
11493       switch (cond2)
11494         {
11495         case LTU:
11496           return CC_DLTUmode;
11497         case LEU:
11498           return CC_DLEUmode;
11499         case NE:
11500           return CC_DNEmode;
11501         default:
11502           gcc_unreachable ();
11503         }
11504
11505     case GTU:
11506       if (cond_or == DOM_CC_X_AND_Y)
11507         return CC_DGTUmode;
11508
11509       switch (cond2)
11510         {
11511         case GTU:
11512           return CC_DGTUmode;
11513         case GEU:
11514           return CC_DGEUmode;
11515         case NE:
11516           return CC_DNEmode;
11517         default:
11518           gcc_unreachable ();
11519         }
11520
11521     /* The remaining cases only occur when both comparisons are the
11522        same.  */
11523     case NE:
11524       gcc_assert (cond1 == cond2);
11525       return CC_DNEmode;
11526
11527     case LE:
11528       gcc_assert (cond1 == cond2);
11529       return CC_DLEmode;
11530
11531     case GE:
11532       gcc_assert (cond1 == cond2);
11533       return CC_DGEmode;
11534
11535     case LEU:
11536       gcc_assert (cond1 == cond2);
11537       return CC_DLEUmode;
11538
11539     case GEU:
11540       gcc_assert (cond1 == cond2);
11541       return CC_DGEUmode;
11542
11543     default:
11544       gcc_unreachable ();
11545     }
11546 }
11547
11548 enum machine_mode
11549 arm_select_cc_mode (enum rtx_code op, rtx x, rtx y)
11550 {
11551   /* All floating point compares return CCFP if it is an equality
11552      comparison, and CCFPE otherwise.  */
11553   if (GET_MODE_CLASS (GET_MODE (x)) == MODE_FLOAT)
11554     {
11555       switch (op)
11556         {
11557         case EQ:
11558         case NE:
11559         case UNORDERED:
11560         case ORDERED:
11561         case UNLT:
11562         case UNLE:
11563         case UNGT:
11564         case UNGE:
11565         case UNEQ:
11566         case LTGT:
11567           return CCFPmode;
11568
11569         case LT:
11570         case LE:
11571         case GT:
11572         case GE:
11573           if (TARGET_HARD_FLOAT && TARGET_MAVERICK)
11574             return CCFPmode;
11575           return CCFPEmode;
11576
11577         default:
11578           gcc_unreachable ();
11579         }
11580     }
11581
11582   /* A compare with a shifted operand.  Because of canonicalization, the
11583      comparison will have to be swapped when we emit the assembler.  */
11584   if (GET_MODE (y) == SImode
11585       && (REG_P (y) || (GET_CODE (y) == SUBREG))
11586       && (GET_CODE (x) == ASHIFT || GET_CODE (x) == ASHIFTRT
11587           || GET_CODE (x) == LSHIFTRT || GET_CODE (x) == ROTATE
11588           || GET_CODE (x) == ROTATERT))
11589     return CC_SWPmode;
11590
11591   /* This operation is performed swapped, but since we only rely on the Z
11592      flag we don't need an additional mode.  */
11593   if (GET_MODE (y) == SImode
11594       && (REG_P (y) || (GET_CODE (y) == SUBREG))
11595       && GET_CODE (x) == NEG
11596       && (op == EQ || op == NE))
11597     return CC_Zmode;
11598
11599   /* This is a special case that is used by combine to allow a
11600      comparison of a shifted byte load to be split into a zero-extend
11601      followed by a comparison of the shifted integer (only valid for
11602      equalities and unsigned inequalities).  */
11603   if (GET_MODE (x) == SImode
11604       && GET_CODE (x) == ASHIFT
11605       && GET_CODE (XEXP (x, 1)) == CONST_INT && INTVAL (XEXP (x, 1)) == 24
11606       && GET_CODE (XEXP (x, 0)) == SUBREG
11607       && GET_CODE (SUBREG_REG (XEXP (x, 0))) == MEM
11608       && GET_MODE (SUBREG_REG (XEXP (x, 0))) == QImode
11609       && (op == EQ || op == NE
11610           || op == GEU || op == GTU || op == LTU || op == LEU)
11611       && GET_CODE (y) == CONST_INT)
11612     return CC_Zmode;
11613
11614   /* A construct for a conditional compare, if the false arm contains
11615      0, then both conditions must be true, otherwise either condition
11616      must be true.  Not all conditions are possible, so CCmode is
11617      returned if it can't be done.  */
11618   if (GET_CODE (x) == IF_THEN_ELSE
11619       && (XEXP (x, 2) == const0_rtx
11620           || XEXP (x, 2) == const1_rtx)
11621       && COMPARISON_P (XEXP (x, 0))
11622       && COMPARISON_P (XEXP (x, 1)))
11623     return arm_select_dominance_cc_mode (XEXP (x, 0), XEXP (x, 1),
11624                                          INTVAL (XEXP (x, 2)));
11625
11626   /* Alternate canonicalizations of the above.  These are somewhat cleaner.  */
11627   if (GET_CODE (x) == AND
11628       && (op == EQ || op == NE)
11629       && COMPARISON_P (XEXP (x, 0))
11630       && COMPARISON_P (XEXP (x, 1)))
11631     return arm_select_dominance_cc_mode (XEXP (x, 0), XEXP (x, 1),
11632                                          DOM_CC_X_AND_Y);
11633
11634   if (GET_CODE (x) == IOR
11635       && (op == EQ || op == NE)
11636       && COMPARISON_P (XEXP (x, 0))
11637       && COMPARISON_P (XEXP (x, 1)))
11638     return arm_select_dominance_cc_mode (XEXP (x, 0), XEXP (x, 1),
11639                                          DOM_CC_X_OR_Y);
11640
11641   /* An operation (on Thumb) where we want to test for a single bit.
11642      This is done by shifting that bit up into the top bit of a
11643      scratch register; we can then branch on the sign bit.  */
11644   if (TARGET_THUMB1
11645       && GET_MODE (x) == SImode
11646       && (op == EQ || op == NE)
11647       && GET_CODE (x) == ZERO_EXTRACT
11648       && XEXP (x, 1) == const1_rtx)
11649     return CC_Nmode;
11650
11651   /* An operation that sets the condition codes as a side-effect, the
11652      V flag is not set correctly, so we can only use comparisons where
11653      this doesn't matter.  (For LT and GE we can use "mi" and "pl"
11654      instead.)  */
11655   /* ??? Does the ZERO_EXTRACT case really apply to thumb2?  */
11656   if (GET_MODE (x) == SImode
11657       && y == const0_rtx
11658       && (op == EQ || op == NE || op == LT || op == GE)
11659       && (GET_CODE (x) == PLUS || GET_CODE (x) == MINUS
11660           || GET_CODE (x) == AND || GET_CODE (x) == IOR
11661           || GET_CODE (x) == XOR || GET_CODE (x) == MULT
11662           || GET_CODE (x) == NOT || GET_CODE (x) == NEG
11663           || GET_CODE (x) == LSHIFTRT
11664           || GET_CODE (x) == ASHIFT || GET_CODE (x) == ASHIFTRT
11665           || GET_CODE (x) == ROTATERT
11666           || (TARGET_32BIT && GET_CODE (x) == ZERO_EXTRACT)))
11667     return CC_NOOVmode;
11668
11669   if (GET_MODE (x) == QImode && (op == EQ || op == NE))
11670     return CC_Zmode;
11671
11672   if (GET_MODE (x) == SImode && (op == LTU || op == GEU)
11673       && GET_CODE (x) == PLUS
11674       && (rtx_equal_p (XEXP (x, 0), y) || rtx_equal_p (XEXP (x, 1), y)))
11675     return CC_Cmode;
11676
11677   if (GET_MODE (x) == DImode || GET_MODE (y) == DImode)
11678     {
11679       /* To keep things simple, always use the Cirrus cfcmp64 if it is
11680          available.  */
11681       if (TARGET_ARM && TARGET_HARD_FLOAT && TARGET_MAVERICK)
11682         return CCmode;
11683
11684       switch (op)
11685         {
11686         case EQ:
11687         case NE:
11688           /* A DImode comparison against zero can be implemented by
11689              or'ing the two halves together.  */
11690           if (y == const0_rtx)
11691             return CC_Zmode;
11692
11693           /* We can do an equality test in three Thumb instructions.  */
11694           if (!TARGET_32BIT)
11695             return CC_Zmode;
11696
11697           /* FALLTHROUGH */
11698
11699         case LTU:
11700         case LEU:
11701         case GTU:
11702         case GEU:
11703           /* DImode unsigned comparisons can be implemented by cmp +
11704              cmpeq without a scratch register.  Not worth doing in
11705              Thumb-2.  */
11706           if (TARGET_32BIT)
11707             return CC_CZmode;
11708
11709           /* FALLTHROUGH */
11710
11711         case LT:
11712         case LE:
11713         case GT:
11714         case GE:
11715           /* DImode signed and unsigned comparisons can be implemented
11716              by cmp + sbcs with a scratch register, but that does not
11717              set the Z flag - we must reverse GT/LE/GTU/LEU.  */
11718           gcc_assert (op != EQ && op != NE);
11719           return CC_NCVmode;
11720
11721         default:
11722           gcc_unreachable ();
11723         }
11724     }
11725
11726   return CCmode;
11727 }
11728
11729 /* X and Y are two things to compare using CODE.  Emit the compare insn and
11730    return the rtx for register 0 in the proper mode.  FP means this is a
11731    floating point compare: I don't think that it is needed on the arm.  */
11732 rtx
11733 arm_gen_compare_reg (enum rtx_code code, rtx x, rtx y, rtx scratch)
11734 {
11735   enum machine_mode mode;
11736   rtx cc_reg;
11737   int dimode_comparison = GET_MODE (x) == DImode || GET_MODE (y) == DImode;
11738
11739   /* We might have X as a constant, Y as a register because of the predicates
11740      used for cmpdi.  If so, force X to a register here.  */
11741   if (dimode_comparison && !REG_P (x))
11742     x = force_reg (DImode, x);
11743
11744   mode = SELECT_CC_MODE (code, x, y);
11745   cc_reg = gen_rtx_REG (mode, CC_REGNUM);
11746
11747   if (dimode_comparison
11748       && !(TARGET_HARD_FLOAT && TARGET_MAVERICK)
11749       && mode != CC_CZmode)
11750     {
11751       rtx clobber, set;
11752
11753       /* To compare two non-zero values for equality, XOR them and
11754          then compare against zero.  Not used for ARM mode; there
11755          CC_CZmode is cheaper.  */
11756       if (mode == CC_Zmode && y != const0_rtx)
11757         {
11758           gcc_assert (!reload_completed);
11759           x = expand_binop (DImode, xor_optab, x, y, NULL_RTX, 0, OPTAB_WIDEN);
11760           y = const0_rtx;
11761         }
11762
11763       /* A scratch register is required.  */
11764       if (reload_completed)
11765         gcc_assert (scratch != NULL && GET_MODE (scratch) == SImode);
11766       else
11767         scratch = gen_rtx_SCRATCH (SImode);
11768
11769       clobber = gen_rtx_CLOBBER (VOIDmode, scratch);
11770       set = gen_rtx_SET (VOIDmode, cc_reg, gen_rtx_COMPARE (mode, x, y));
11771       emit_insn (gen_rtx_PARALLEL (VOIDmode, gen_rtvec (2, set, clobber)));
11772     }
11773   else
11774     emit_set_insn (cc_reg, gen_rtx_COMPARE (mode, x, y));
11775
11776   return cc_reg;
11777 }
11778
11779 /* Generate a sequence of insns that will generate the correct return
11780    address mask depending on the physical architecture that the program
11781    is running on.  */
11782 rtx
11783 arm_gen_return_addr_mask (void)
11784 {
11785   rtx reg = gen_reg_rtx (Pmode);
11786
11787   emit_insn (gen_return_addr_mask (reg));
11788   return reg;
11789 }
11790
11791 void
11792 arm_reload_in_hi (rtx *operands)
11793 {
11794   rtx ref = operands[1];
11795   rtx base, scratch;
11796   HOST_WIDE_INT offset = 0;
11797
11798   if (GET_CODE (ref) == SUBREG)
11799     {
11800       offset = SUBREG_BYTE (ref);
11801       ref = SUBREG_REG (ref);
11802     }
11803
11804   if (GET_CODE (ref) == REG)
11805     {
11806       /* We have a pseudo which has been spilt onto the stack; there
11807          are two cases here: the first where there is a simple
11808          stack-slot replacement and a second where the stack-slot is
11809          out of range, or is used as a subreg.  */
11810       if (reg_equiv_mem (REGNO (ref)))
11811         {
11812           ref = reg_equiv_mem (REGNO (ref));
11813           base = find_replacement (&XEXP (ref, 0));
11814         }
11815       else
11816         /* The slot is out of range, or was dressed up in a SUBREG.  */
11817         base = reg_equiv_address (REGNO (ref));
11818     }
11819   else
11820     base = find_replacement (&XEXP (ref, 0));
11821
11822   /* Handle the case where the address is too complex to be offset by 1.  */
11823   if (GET_CODE (base) == MINUS
11824       || (GET_CODE (base) == PLUS && GET_CODE (XEXP (base, 1)) != CONST_INT))
11825     {
11826       rtx base_plus = gen_rtx_REG (SImode, REGNO (operands[2]) + 1);
11827
11828       emit_set_insn (base_plus, base);
11829       base = base_plus;
11830     }
11831   else if (GET_CODE (base) == PLUS)
11832     {
11833       /* The addend must be CONST_INT, or we would have dealt with it above.  */
11834       HOST_WIDE_INT hi, lo;
11835
11836       offset += INTVAL (XEXP (base, 1));
11837       base = XEXP (base, 0);
11838
11839       /* Rework the address into a legal sequence of insns.  */
11840       /* Valid range for lo is -4095 -> 4095 */
11841       lo = (offset >= 0
11842             ? (offset & 0xfff)
11843             : -((-offset) & 0xfff));
11844
11845       /* Corner case, if lo is the max offset then we would be out of range
11846          once we have added the additional 1 below, so bump the msb into the
11847          pre-loading insn(s).  */
11848       if (lo == 4095)
11849         lo &= 0x7ff;
11850
11851       hi = ((((offset - lo) & (HOST_WIDE_INT) 0xffffffff)
11852              ^ (HOST_WIDE_INT) 0x80000000)
11853             - (HOST_WIDE_INT) 0x80000000);
11854
11855       gcc_assert (hi + lo == offset);
11856
11857       if (hi != 0)
11858         {
11859           rtx base_plus = gen_rtx_REG (SImode, REGNO (operands[2]) + 1);
11860
11861           /* Get the base address; addsi3 knows how to handle constants
11862              that require more than one insn.  */
11863           emit_insn (gen_addsi3 (base_plus, base, GEN_INT (hi)));
11864           base = base_plus;
11865           offset = lo;
11866         }
11867     }
11868
11869   /* Operands[2] may overlap operands[0] (though it won't overlap
11870      operands[1]), that's why we asked for a DImode reg -- so we can
11871      use the bit that does not overlap.  */
11872   if (REGNO (operands[2]) == REGNO (operands[0]))
11873     scratch = gen_rtx_REG (SImode, REGNO (operands[2]) + 1);
11874   else
11875     scratch = gen_rtx_REG (SImode, REGNO (operands[2]));
11876
11877   emit_insn (gen_zero_extendqisi2 (scratch,
11878                                    gen_rtx_MEM (QImode,
11879                                                 plus_constant (base,
11880                                                                offset))));
11881   emit_insn (gen_zero_extendqisi2 (gen_rtx_SUBREG (SImode, operands[0], 0),
11882                                    gen_rtx_MEM (QImode,
11883                                                 plus_constant (base,
11884                                                                offset + 1))));
11885   if (!BYTES_BIG_ENDIAN)
11886     emit_set_insn (gen_rtx_SUBREG (SImode, operands[0], 0),
11887                    gen_rtx_IOR (SImode,
11888                                 gen_rtx_ASHIFT
11889                                 (SImode,
11890                                  gen_rtx_SUBREG (SImode, operands[0], 0),
11891                                  GEN_INT (8)),
11892                                 scratch));
11893   else
11894     emit_set_insn (gen_rtx_SUBREG (SImode, operands[0], 0),
11895                    gen_rtx_IOR (SImode,
11896                                 gen_rtx_ASHIFT (SImode, scratch,
11897                                                 GEN_INT (8)),
11898                                 gen_rtx_SUBREG (SImode, operands[0], 0)));
11899 }
11900
11901 /* Handle storing a half-word to memory during reload by synthesizing as two
11902    byte stores.  Take care not to clobber the input values until after we
11903    have moved them somewhere safe.  This code assumes that if the DImode
11904    scratch in operands[2] overlaps either the input value or output address
11905    in some way, then that value must die in this insn (we absolutely need
11906    two scratch registers for some corner cases).  */
11907 void
11908 arm_reload_out_hi (rtx *operands)
11909 {
11910   rtx ref = operands[0];
11911   rtx outval = operands[1];
11912   rtx base, scratch;
11913   HOST_WIDE_INT offset = 0;
11914
11915   if (GET_CODE (ref) == SUBREG)
11916     {
11917       offset = SUBREG_BYTE (ref);
11918       ref = SUBREG_REG (ref);
11919     }
11920
11921   if (GET_CODE (ref) == REG)
11922     {
11923       /* We have a pseudo which has been spilt onto the stack; there
11924          are two cases here: the first where there is a simple
11925          stack-slot replacement and a second where the stack-slot is
11926          out of range, or is used as a subreg.  */
11927       if (reg_equiv_mem (REGNO (ref)))
11928         {
11929           ref = reg_equiv_mem (REGNO (ref));
11930           base = find_replacement (&XEXP (ref, 0));
11931         }
11932       else
11933         /* The slot is out of range, or was dressed up in a SUBREG.  */
11934         base = reg_equiv_address (REGNO (ref));
11935     }
11936   else
11937     base = find_replacement (&XEXP (ref, 0));
11938
11939   scratch = gen_rtx_REG (SImode, REGNO (operands[2]));
11940
11941   /* Handle the case where the address is too complex to be offset by 1.  */
11942   if (GET_CODE (base) == MINUS
11943       || (GET_CODE (base) == PLUS && GET_CODE (XEXP (base, 1)) != CONST_INT))
11944     {
11945       rtx base_plus = gen_rtx_REG (SImode, REGNO (operands[2]) + 1);
11946
11947       /* Be careful not to destroy OUTVAL.  */
11948       if (reg_overlap_mentioned_p (base_plus, outval))
11949         {
11950           /* Updating base_plus might destroy outval, see if we can
11951              swap the scratch and base_plus.  */
11952           if (!reg_overlap_mentioned_p (scratch, outval))
11953             {
11954               rtx tmp = scratch;
11955               scratch = base_plus;
11956               base_plus = tmp;
11957             }
11958           else
11959             {
11960               rtx scratch_hi = gen_rtx_REG (HImode, REGNO (operands[2]));
11961
11962               /* Be conservative and copy OUTVAL into the scratch now,
11963                  this should only be necessary if outval is a subreg
11964                  of something larger than a word.  */
11965               /* XXX Might this clobber base?  I can't see how it can,
11966                  since scratch is known to overlap with OUTVAL, and
11967                  must be wider than a word.  */
11968               emit_insn (gen_movhi (scratch_hi, outval));
11969               outval = scratch_hi;
11970             }
11971         }
11972
11973       emit_set_insn (base_plus, base);
11974       base = base_plus;
11975     }
11976   else if (GET_CODE (base) == PLUS)
11977     {
11978       /* The addend must be CONST_INT, or we would have dealt with it above.  */
11979       HOST_WIDE_INT hi, lo;
11980
11981       offset += INTVAL (XEXP (base, 1));
11982       base = XEXP (base, 0);
11983
11984       /* Rework the address into a legal sequence of insns.  */
11985       /* Valid range for lo is -4095 -> 4095 */
11986       lo = (offset >= 0
11987             ? (offset & 0xfff)
11988             : -((-offset) & 0xfff));
11989
11990       /* Corner case, if lo is the max offset then we would be out of range
11991          once we have added the additional 1 below, so bump the msb into the
11992          pre-loading insn(s).  */
11993       if (lo == 4095)
11994         lo &= 0x7ff;
11995
11996       hi = ((((offset - lo) & (HOST_WIDE_INT) 0xffffffff)
11997              ^ (HOST_WIDE_INT) 0x80000000)
11998             - (HOST_WIDE_INT) 0x80000000);
11999
12000       gcc_assert (hi + lo == offset);
12001
12002       if (hi != 0)
12003         {
12004           rtx base_plus = gen_rtx_REG (SImode, REGNO (operands[2]) + 1);
12005
12006           /* Be careful not to destroy OUTVAL.  */
12007           if (reg_overlap_mentioned_p (base_plus, outval))
12008             {
12009               /* Updating base_plus might destroy outval, see if we
12010                  can swap the scratch and base_plus.  */
12011               if (!reg_overlap_mentioned_p (scratch, outval))
12012                 {
12013                   rtx tmp = scratch;
12014                   scratch = base_plus;
12015                   base_plus = tmp;
12016                 }
12017               else
12018                 {
12019                   rtx scratch_hi = gen_rtx_REG (HImode, REGNO (operands[2]));
12020
12021                   /* Be conservative and copy outval into scratch now,
12022                      this should only be necessary if outval is a
12023                      subreg of something larger than a word.  */
12024                   /* XXX Might this clobber base?  I can't see how it
12025                      can, since scratch is known to overlap with
12026                      outval.  */
12027                   emit_insn (gen_movhi (scratch_hi, outval));
12028                   outval = scratch_hi;
12029                 }
12030             }
12031
12032           /* Get the base address; addsi3 knows how to handle constants
12033              that require more than one insn.  */
12034           emit_insn (gen_addsi3 (base_plus, base, GEN_INT (hi)));
12035           base = base_plus;
12036           offset = lo;
12037         }
12038     }
12039
12040   if (BYTES_BIG_ENDIAN)
12041     {
12042       emit_insn (gen_movqi (gen_rtx_MEM (QImode,
12043                                          plus_constant (base, offset + 1)),
12044                             gen_lowpart (QImode, outval)));
12045       emit_insn (gen_lshrsi3 (scratch,
12046                               gen_rtx_SUBREG (SImode, outval, 0),
12047                               GEN_INT (8)));
12048       emit_insn (gen_movqi (gen_rtx_MEM (QImode, plus_constant (base, offset)),
12049                             gen_lowpart (QImode, scratch)));
12050     }
12051   else
12052     {
12053       emit_insn (gen_movqi (gen_rtx_MEM (QImode, plus_constant (base, offset)),
12054                             gen_lowpart (QImode, outval)));
12055       emit_insn (gen_lshrsi3 (scratch,
12056                               gen_rtx_SUBREG (SImode, outval, 0),
12057                               GEN_INT (8)));
12058       emit_insn (gen_movqi (gen_rtx_MEM (QImode,
12059                                          plus_constant (base, offset + 1)),
12060                             gen_lowpart (QImode, scratch)));
12061     }
12062 }
12063
12064 /* Return true if a type must be passed in memory. For AAPCS, small aggregates
12065    (padded to the size of a word) should be passed in a register.  */
12066
12067 static bool
12068 arm_must_pass_in_stack (enum machine_mode mode, const_tree type)
12069 {
12070   if (TARGET_AAPCS_BASED)
12071     return must_pass_in_stack_var_size (mode, type);
12072   else
12073     return must_pass_in_stack_var_size_or_pad (mode, type);
12074 }
12075
12076
12077 /* For use by FUNCTION_ARG_PADDING (MODE, TYPE).
12078    Return true if an argument passed on the stack should be padded upwards,
12079    i.e. if the least-significant byte has useful data.
12080    For legacy APCS ABIs we use the default.  For AAPCS based ABIs small
12081    aggregate types are placed in the lowest memory address.  */
12082
12083 bool
12084 arm_pad_arg_upward (enum machine_mode mode ATTRIBUTE_UNUSED, const_tree type)
12085 {
12086   if (!TARGET_AAPCS_BASED)
12087     return DEFAULT_FUNCTION_ARG_PADDING(mode, type) == upward;
12088
12089   if (type && BYTES_BIG_ENDIAN && INTEGRAL_TYPE_P (type))
12090     return false;
12091
12092   return true;
12093 }
12094
12095
12096 /* Similarly, for use by BLOCK_REG_PADDING (MODE, TYPE, FIRST).
12097    Return !BYTES_BIG_ENDIAN if the least significant byte of the
12098    register has useful data, and return the opposite if the most
12099    significant byte does.  */
12100
12101 bool
12102 arm_pad_reg_upward (enum machine_mode mode,
12103                     tree type, int first ATTRIBUTE_UNUSED)
12104 {
12105   if (TARGET_AAPCS_BASED && BYTES_BIG_ENDIAN)
12106     {
12107       /* For AAPCS, small aggregates, small fixed-point types,
12108          and small complex types are always padded upwards.  */
12109       if (type)
12110         {
12111           if ((AGGREGATE_TYPE_P (type)
12112                || TREE_CODE (type) == COMPLEX_TYPE
12113                || FIXED_POINT_TYPE_P (type))
12114               && int_size_in_bytes (type) <= 4)
12115             return true;
12116         }
12117       else
12118         {
12119           if ((COMPLEX_MODE_P (mode) || ALL_FIXED_POINT_MODE_P (mode))
12120               && GET_MODE_SIZE (mode) <= 4)
12121             return true;
12122         }
12123     }
12124
12125   /* Otherwise, use default padding.  */
12126   return !BYTES_BIG_ENDIAN;
12127 }
12128
12129 \f
12130 /* Print a symbolic form of X to the debug file, F.  */
12131 static void
12132 arm_print_value (FILE *f, rtx x)
12133 {
12134   switch (GET_CODE (x))
12135     {
12136     case CONST_INT:
12137       fprintf (f, HOST_WIDE_INT_PRINT_HEX, INTVAL (x));
12138       return;
12139
12140     case CONST_DOUBLE:
12141       fprintf (f, "<0x%lx,0x%lx>", (long)XWINT (x, 2), (long)XWINT (x, 3));
12142       return;
12143
12144     case CONST_VECTOR:
12145       {
12146         int i;
12147
12148         fprintf (f, "<");
12149         for (i = 0; i < CONST_VECTOR_NUNITS (x); i++)
12150           {
12151             fprintf (f, HOST_WIDE_INT_PRINT_HEX, INTVAL (CONST_VECTOR_ELT (x, i)));
12152             if (i < (CONST_VECTOR_NUNITS (x) - 1))
12153               fputc (',', f);
12154           }
12155         fprintf (f, ">");
12156       }
12157       return;
12158
12159     case CONST_STRING:
12160       fprintf (f, "\"%s\"", XSTR (x, 0));
12161       return;
12162
12163     case SYMBOL_REF:
12164       fprintf (f, "`%s'", XSTR (x, 0));
12165       return;
12166
12167     case LABEL_REF:
12168       fprintf (f, "L%d", INSN_UID (XEXP (x, 0)));
12169       return;
12170
12171     case CONST:
12172       arm_print_value (f, XEXP (x, 0));
12173       return;
12174
12175     case PLUS:
12176       arm_print_value (f, XEXP (x, 0));
12177       fprintf (f, "+");
12178       arm_print_value (f, XEXP (x, 1));
12179       return;
12180
12181     case PC:
12182       fprintf (f, "pc");
12183       return;
12184
12185     default:
12186       fprintf (f, "????");
12187       return;
12188     }
12189 }
12190 \f
12191 /* Routines for manipulation of the constant pool.  */
12192
12193 /* Arm instructions cannot load a large constant directly into a
12194    register; they have to come from a pc relative load.  The constant
12195    must therefore be placed in the addressable range of the pc
12196    relative load.  Depending on the precise pc relative load
12197    instruction the range is somewhere between 256 bytes and 4k.  This
12198    means that we often have to dump a constant inside a function, and
12199    generate code to branch around it.
12200
12201    It is important to minimize this, since the branches will slow
12202    things down and make the code larger.
12203
12204    Normally we can hide the table after an existing unconditional
12205    branch so that there is no interruption of the flow, but in the
12206    worst case the code looks like this:
12207
12208         ldr     rn, L1
12209         ...
12210         b       L2
12211         align
12212         L1:     .long value
12213         L2:
12214         ...
12215
12216         ldr     rn, L3
12217         ...
12218         b       L4
12219         align
12220         L3:     .long value
12221         L4:
12222         ...
12223
12224    We fix this by performing a scan after scheduling, which notices
12225    which instructions need to have their operands fetched from the
12226    constant table and builds the table.
12227
12228    The algorithm starts by building a table of all the constants that
12229    need fixing up and all the natural barriers in the function (places
12230    where a constant table can be dropped without breaking the flow).
12231    For each fixup we note how far the pc-relative replacement will be
12232    able to reach and the offset of the instruction into the function.
12233
12234    Having built the table we then group the fixes together to form
12235    tables that are as large as possible (subject to addressing
12236    constraints) and emit each table of constants after the last
12237    barrier that is within range of all the instructions in the group.
12238    If a group does not contain a barrier, then we forcibly create one
12239    by inserting a jump instruction into the flow.  Once the table has
12240    been inserted, the insns are then modified to reference the
12241    relevant entry in the pool.
12242
12243    Possible enhancements to the algorithm (not implemented) are:
12244
12245    1) For some processors and object formats, there may be benefit in
12246    aligning the pools to the start of cache lines; this alignment
12247    would need to be taken into account when calculating addressability
12248    of a pool.  */
12249
12250 /* These typedefs are located at the start of this file, so that
12251    they can be used in the prototypes there.  This comment is to
12252    remind readers of that fact so that the following structures
12253    can be understood more easily.
12254
12255      typedef struct minipool_node    Mnode;
12256      typedef struct minipool_fixup   Mfix;  */
12257
12258 struct minipool_node
12259 {
12260   /* Doubly linked chain of entries.  */
12261   Mnode * next;
12262   Mnode * prev;
12263   /* The maximum offset into the code that this entry can be placed.  While
12264      pushing fixes for forward references, all entries are sorted in order
12265      of increasing max_address.  */
12266   HOST_WIDE_INT max_address;
12267   /* Similarly for an entry inserted for a backwards ref.  */
12268   HOST_WIDE_INT min_address;
12269   /* The number of fixes referencing this entry.  This can become zero
12270      if we "unpush" an entry.  In this case we ignore the entry when we
12271      come to emit the code.  */
12272   int refcount;
12273   /* The offset from the start of the minipool.  */
12274   HOST_WIDE_INT offset;
12275   /* The value in table.  */
12276   rtx value;
12277   /* The mode of value.  */
12278   enum machine_mode mode;
12279   /* The size of the value.  With iWMMXt enabled
12280      sizes > 4 also imply an alignment of 8-bytes.  */
12281   int fix_size;
12282 };
12283
12284 struct minipool_fixup
12285 {
12286   Mfix *            next;
12287   rtx               insn;
12288   HOST_WIDE_INT     address;
12289   rtx *             loc;
12290   enum machine_mode mode;
12291   int               fix_size;
12292   rtx               value;
12293   Mnode *           minipool;
12294   HOST_WIDE_INT     forwards;
12295   HOST_WIDE_INT     backwards;
12296 };
12297
12298 /* Fixes less than a word need padding out to a word boundary.  */
12299 #define MINIPOOL_FIX_SIZE(mode) \
12300   (GET_MODE_SIZE ((mode)) >= 4 ? GET_MODE_SIZE ((mode)) : 4)
12301
12302 static Mnode *  minipool_vector_head;
12303 static Mnode *  minipool_vector_tail;
12304 static rtx      minipool_vector_label;
12305 static int      minipool_pad;
12306
12307 /* The linked list of all minipool fixes required for this function.  */
12308 Mfix *          minipool_fix_head;
12309 Mfix *          minipool_fix_tail;
12310 /* The fix entry for the current minipool, once it has been placed.  */
12311 Mfix *          minipool_barrier;
12312
12313 /* Determines if INSN is the start of a jump table.  Returns the end
12314    of the TABLE or NULL_RTX.  */
12315 static rtx
12316 is_jump_table (rtx insn)
12317 {
12318   rtx table;
12319
12320   if (jump_to_label_p (insn)
12321       && ((table = next_real_insn (JUMP_LABEL (insn)))
12322           == next_real_insn (insn))
12323       && table != NULL
12324       && GET_CODE (table) == JUMP_INSN
12325       && (GET_CODE (PATTERN (table)) == ADDR_VEC
12326           || GET_CODE (PATTERN (table)) == ADDR_DIFF_VEC))
12327     return table;
12328
12329   return NULL_RTX;
12330 }
12331
12332 #ifndef JUMP_TABLES_IN_TEXT_SECTION
12333 #define JUMP_TABLES_IN_TEXT_SECTION 0
12334 #endif
12335
12336 static HOST_WIDE_INT
12337 get_jump_table_size (rtx insn)
12338 {
12339   /* ADDR_VECs only take room if read-only data does into the text
12340      section.  */
12341   if (JUMP_TABLES_IN_TEXT_SECTION || readonly_data_section == text_section)
12342     {
12343       rtx body = PATTERN (insn);
12344       int elt = GET_CODE (body) == ADDR_DIFF_VEC ? 1 : 0;
12345       HOST_WIDE_INT size;
12346       HOST_WIDE_INT modesize;
12347
12348       modesize = GET_MODE_SIZE (GET_MODE (body));
12349       size = modesize * XVECLEN (body, elt);
12350       switch (modesize)
12351         {
12352         case 1:
12353           /* Round up size  of TBB table to a halfword boundary.  */
12354           size = (size + 1) & ~(HOST_WIDE_INT)1;
12355           break;
12356         case 2:
12357           /* No padding necessary for TBH.  */
12358           break;
12359         case 4:
12360           /* Add two bytes for alignment on Thumb.  */
12361           if (TARGET_THUMB)
12362             size += 2;
12363           break;
12364         default:
12365           gcc_unreachable ();
12366         }
12367       return size;
12368     }
12369
12370   return 0;
12371 }
12372
12373 /* Return the maximum amount of padding that will be inserted before
12374    label LABEL.  */
12375
12376 static HOST_WIDE_INT
12377 get_label_padding (rtx label)
12378 {
12379   HOST_WIDE_INT align, min_insn_size;
12380
12381   align = 1 << label_to_alignment (label);
12382   min_insn_size = TARGET_THUMB ? 2 : 4;
12383   return align > min_insn_size ? align - min_insn_size : 0;
12384 }
12385
12386 /* Move a minipool fix MP from its current location to before MAX_MP.
12387    If MAX_MP is NULL, then MP doesn't need moving, but the addressing
12388    constraints may need updating.  */
12389 static Mnode *
12390 move_minipool_fix_forward_ref (Mnode *mp, Mnode *max_mp,
12391                                HOST_WIDE_INT max_address)
12392 {
12393   /* The code below assumes these are different.  */
12394   gcc_assert (mp != max_mp);
12395
12396   if (max_mp == NULL)
12397     {
12398       if (max_address < mp->max_address)
12399         mp->max_address = max_address;
12400     }
12401   else
12402     {
12403       if (max_address > max_mp->max_address - mp->fix_size)
12404         mp->max_address = max_mp->max_address - mp->fix_size;
12405       else
12406         mp->max_address = max_address;
12407
12408       /* Unlink MP from its current position.  Since max_mp is non-null,
12409        mp->prev must be non-null.  */
12410       mp->prev->next = mp->next;
12411       if (mp->next != NULL)
12412         mp->next->prev = mp->prev;
12413       else
12414         minipool_vector_tail = mp->prev;
12415
12416       /* Re-insert it before MAX_MP.  */
12417       mp->next = max_mp;
12418       mp->prev = max_mp->prev;
12419       max_mp->prev = mp;
12420
12421       if (mp->prev != NULL)
12422         mp->prev->next = mp;
12423       else
12424         minipool_vector_head = mp;
12425     }
12426
12427   /* Save the new entry.  */
12428   max_mp = mp;
12429
12430   /* Scan over the preceding entries and adjust their addresses as
12431      required.  */
12432   while (mp->prev != NULL
12433          && mp->prev->max_address > mp->max_address - mp->prev->fix_size)
12434     {
12435       mp->prev->max_address = mp->max_address - mp->prev->fix_size;
12436       mp = mp->prev;
12437     }
12438
12439   return max_mp;
12440 }
12441
12442 /* Add a constant to the minipool for a forward reference.  Returns the
12443    node added or NULL if the constant will not fit in this pool.  */
12444 static Mnode *
12445 add_minipool_forward_ref (Mfix *fix)
12446 {
12447   /* If set, max_mp is the first pool_entry that has a lower
12448      constraint than the one we are trying to add.  */
12449   Mnode *       max_mp = NULL;
12450   HOST_WIDE_INT max_address = fix->address + fix->forwards - minipool_pad;
12451   Mnode *       mp;
12452
12453   /* If the minipool starts before the end of FIX->INSN then this FIX
12454      can not be placed into the current pool.  Furthermore, adding the
12455      new constant pool entry may cause the pool to start FIX_SIZE bytes
12456      earlier.  */
12457   if (minipool_vector_head &&
12458       (fix->address + get_attr_length (fix->insn)
12459        >= minipool_vector_head->max_address - fix->fix_size))
12460     return NULL;
12461
12462   /* Scan the pool to see if a constant with the same value has
12463      already been added.  While we are doing this, also note the
12464      location where we must insert the constant if it doesn't already
12465      exist.  */
12466   for (mp = minipool_vector_head; mp != NULL; mp = mp->next)
12467     {
12468       if (GET_CODE (fix->value) == GET_CODE (mp->value)
12469           && fix->mode == mp->mode
12470           && (GET_CODE (fix->value) != CODE_LABEL
12471               || (CODE_LABEL_NUMBER (fix->value)
12472                   == CODE_LABEL_NUMBER (mp->value)))
12473           && rtx_equal_p (fix->value, mp->value))
12474         {
12475           /* More than one fix references this entry.  */
12476           mp->refcount++;
12477           return move_minipool_fix_forward_ref (mp, max_mp, max_address);
12478         }
12479
12480       /* Note the insertion point if necessary.  */
12481       if (max_mp == NULL
12482           && mp->max_address > max_address)
12483         max_mp = mp;
12484
12485       /* If we are inserting an 8-bytes aligned quantity and
12486          we have not already found an insertion point, then
12487          make sure that all such 8-byte aligned quantities are
12488          placed at the start of the pool.  */
12489       if (ARM_DOUBLEWORD_ALIGN
12490           && max_mp == NULL
12491           && fix->fix_size >= 8
12492           && mp->fix_size < 8)
12493         {
12494           max_mp = mp;
12495           max_address = mp->max_address;
12496         }
12497     }
12498
12499   /* The value is not currently in the minipool, so we need to create
12500      a new entry for it.  If MAX_MP is NULL, the entry will be put on
12501      the end of the list since the placement is less constrained than
12502      any existing entry.  Otherwise, we insert the new fix before
12503      MAX_MP and, if necessary, adjust the constraints on the other
12504      entries.  */
12505   mp = XNEW (Mnode);
12506   mp->fix_size = fix->fix_size;
12507   mp->mode = fix->mode;
12508   mp->value = fix->value;
12509   mp->refcount = 1;
12510   /* Not yet required for a backwards ref.  */
12511   mp->min_address = -65536;
12512
12513   if (max_mp == NULL)
12514     {
12515       mp->max_address = max_address;
12516       mp->next = NULL;
12517       mp->prev = minipool_vector_tail;
12518
12519       if (mp->prev == NULL)
12520         {
12521           minipool_vector_head = mp;
12522           minipool_vector_label = gen_label_rtx ();
12523         }
12524       else
12525         mp->prev->next = mp;
12526
12527       minipool_vector_tail = mp;
12528     }
12529   else
12530     {
12531       if (max_address > max_mp->max_address - mp->fix_size)
12532         mp->max_address = max_mp->max_address - mp->fix_size;
12533       else
12534         mp->max_address = max_address;
12535
12536       mp->next = max_mp;
12537       mp->prev = max_mp->prev;
12538       max_mp->prev = mp;
12539       if (mp->prev != NULL)
12540         mp->prev->next = mp;
12541       else
12542         minipool_vector_head = mp;
12543     }
12544
12545   /* Save the new entry.  */
12546   max_mp = mp;
12547
12548   /* Scan over the preceding entries and adjust their addresses as
12549      required.  */
12550   while (mp->prev != NULL
12551          && mp->prev->max_address > mp->max_address - mp->prev->fix_size)
12552     {
12553       mp->prev->max_address = mp->max_address - mp->prev->fix_size;
12554       mp = mp->prev;
12555     }
12556
12557   return max_mp;
12558 }
12559
12560 static Mnode *
12561 move_minipool_fix_backward_ref (Mnode *mp, Mnode *min_mp,
12562                                 HOST_WIDE_INT  min_address)
12563 {
12564   HOST_WIDE_INT offset;
12565
12566   /* The code below assumes these are different.  */
12567   gcc_assert (mp != min_mp);
12568
12569   if (min_mp == NULL)
12570     {
12571       if (min_address > mp->min_address)
12572         mp->min_address = min_address;
12573     }
12574   else
12575     {
12576       /* We will adjust this below if it is too loose.  */
12577       mp->min_address = min_address;
12578
12579       /* Unlink MP from its current position.  Since min_mp is non-null,
12580          mp->next must be non-null.  */
12581       mp->next->prev = mp->prev;
12582       if (mp->prev != NULL)
12583         mp->prev->next = mp->next;
12584       else
12585         minipool_vector_head = mp->next;
12586
12587       /* Reinsert it after MIN_MP.  */
12588       mp->prev = min_mp;
12589       mp->next = min_mp->next;
12590       min_mp->next = mp;
12591       if (mp->next != NULL)
12592         mp->next->prev = mp;
12593       else
12594         minipool_vector_tail = mp;
12595     }
12596
12597   min_mp = mp;
12598
12599   offset = 0;
12600   for (mp = minipool_vector_head; mp != NULL; mp = mp->next)
12601     {
12602       mp->offset = offset;
12603       if (mp->refcount > 0)
12604         offset += mp->fix_size;
12605
12606       if (mp->next && mp->next->min_address < mp->min_address + mp->fix_size)
12607         mp->next->min_address = mp->min_address + mp->fix_size;
12608     }
12609
12610   return min_mp;
12611 }
12612
12613 /* Add a constant to the minipool for a backward reference.  Returns the
12614    node added or NULL if the constant will not fit in this pool.
12615
12616    Note that the code for insertion for a backwards reference can be
12617    somewhat confusing because the calculated offsets for each fix do
12618    not take into account the size of the pool (which is still under
12619    construction.  */
12620 static Mnode *
12621 add_minipool_backward_ref (Mfix *fix)
12622 {
12623   /* If set, min_mp is the last pool_entry that has a lower constraint
12624      than the one we are trying to add.  */
12625   Mnode *min_mp = NULL;
12626   /* This can be negative, since it is only a constraint.  */
12627   HOST_WIDE_INT  min_address = fix->address - fix->backwards;
12628   Mnode *mp;
12629
12630   /* If we can't reach the current pool from this insn, or if we can't
12631      insert this entry at the end of the pool without pushing other
12632      fixes out of range, then we don't try.  This ensures that we
12633      can't fail later on.  */
12634   if (min_address >= minipool_barrier->address
12635       || (minipool_vector_tail->min_address + fix->fix_size
12636           >= minipool_barrier->address))
12637     return NULL;
12638
12639   /* Scan the pool to see if a constant with the same value has
12640      already been added.  While we are doing this, also note the
12641      location where we must insert the constant if it doesn't already
12642      exist.  */
12643   for (mp = minipool_vector_tail; mp != NULL; mp = mp->prev)
12644     {
12645       if (GET_CODE (fix->value) == GET_CODE (mp->value)
12646           && fix->mode == mp->mode
12647           && (GET_CODE (fix->value) != CODE_LABEL
12648               || (CODE_LABEL_NUMBER (fix->value)
12649                   == CODE_LABEL_NUMBER (mp->value)))
12650           && rtx_equal_p (fix->value, mp->value)
12651           /* Check that there is enough slack to move this entry to the
12652              end of the table (this is conservative).  */
12653           && (mp->max_address
12654               > (minipool_barrier->address
12655                  + minipool_vector_tail->offset
12656                  + minipool_vector_tail->fix_size)))
12657         {
12658           mp->refcount++;
12659           return move_minipool_fix_backward_ref (mp, min_mp, min_address);
12660         }
12661
12662       if (min_mp != NULL)
12663         mp->min_address += fix->fix_size;
12664       else
12665         {
12666           /* Note the insertion point if necessary.  */
12667           if (mp->min_address < min_address)
12668             {
12669               /* For now, we do not allow the insertion of 8-byte alignment
12670                  requiring nodes anywhere but at the start of the pool.  */
12671               if (ARM_DOUBLEWORD_ALIGN
12672                   && fix->fix_size >= 8 && mp->fix_size < 8)
12673                 return NULL;
12674               else
12675                 min_mp = mp;
12676             }
12677           else if (mp->max_address
12678                    < minipool_barrier->address + mp->offset + fix->fix_size)
12679             {
12680               /* Inserting before this entry would push the fix beyond
12681                  its maximum address (which can happen if we have
12682                  re-located a forwards fix); force the new fix to come
12683                  after it.  */
12684               if (ARM_DOUBLEWORD_ALIGN
12685                   && fix->fix_size >= 8 && mp->fix_size < 8)
12686                 return NULL;
12687               else
12688                 {
12689                   min_mp = mp;
12690                   min_address = mp->min_address + fix->fix_size;
12691                 }
12692             }
12693           /* Do not insert a non-8-byte aligned quantity before 8-byte
12694              aligned quantities.  */
12695           else if (ARM_DOUBLEWORD_ALIGN
12696                    && fix->fix_size < 8
12697                    && mp->fix_size >= 8)
12698             {
12699               min_mp = mp;
12700               min_address = mp->min_address + fix->fix_size;
12701             }
12702         }
12703     }
12704
12705   /* We need to create a new entry.  */
12706   mp = XNEW (Mnode);
12707   mp->fix_size = fix->fix_size;
12708   mp->mode = fix->mode;
12709   mp->value = fix->value;
12710   mp->refcount = 1;
12711   mp->max_address = minipool_barrier->address + 65536;
12712
12713   mp->min_address = min_address;
12714
12715   if (min_mp == NULL)
12716     {
12717       mp->prev = NULL;
12718       mp->next = minipool_vector_head;
12719
12720       if (mp->next == NULL)
12721         {
12722           minipool_vector_tail = mp;
12723           minipool_vector_label = gen_label_rtx ();
12724         }
12725       else
12726         mp->next->prev = mp;
12727
12728       minipool_vector_head = mp;
12729     }
12730   else
12731     {
12732       mp->next = min_mp->next;
12733       mp->prev = min_mp;
12734       min_mp->next = mp;
12735
12736       if (mp->next != NULL)
12737         mp->next->prev = mp;
12738       else
12739         minipool_vector_tail = mp;
12740     }
12741
12742   /* Save the new entry.  */
12743   min_mp = mp;
12744
12745   if (mp->prev)
12746     mp = mp->prev;
12747   else
12748     mp->offset = 0;
12749
12750   /* Scan over the following entries and adjust their offsets.  */
12751   while (mp->next != NULL)
12752     {
12753       if (mp->next->min_address < mp->min_address + mp->fix_size)
12754         mp->next->min_address = mp->min_address + mp->fix_size;
12755
12756       if (mp->refcount)
12757         mp->next->offset = mp->offset + mp->fix_size;
12758       else
12759         mp->next->offset = mp->offset;
12760
12761       mp = mp->next;
12762     }
12763
12764   return min_mp;
12765 }
12766
12767 static void
12768 assign_minipool_offsets (Mfix *barrier)
12769 {
12770   HOST_WIDE_INT offset = 0;
12771   Mnode *mp;
12772
12773   minipool_barrier = barrier;
12774
12775   for (mp = minipool_vector_head; mp != NULL; mp = mp->next)
12776     {
12777       mp->offset = offset;
12778
12779       if (mp->refcount > 0)
12780         offset += mp->fix_size;
12781     }
12782 }
12783
12784 /* Output the literal table */
12785 static void
12786 dump_minipool (rtx scan)
12787 {
12788   Mnode * mp;
12789   Mnode * nmp;
12790   int align64 = 0;
12791
12792   if (ARM_DOUBLEWORD_ALIGN)
12793     for (mp = minipool_vector_head; mp != NULL; mp = mp->next)
12794       if (mp->refcount > 0 && mp->fix_size >= 8)
12795         {
12796           align64 = 1;
12797           break;
12798         }
12799
12800   if (dump_file)
12801     fprintf (dump_file,
12802              ";; Emitting minipool after insn %u; address %ld; align %d (bytes)\n",
12803              INSN_UID (scan), (unsigned long) minipool_barrier->address, align64 ? 8 : 4);
12804
12805   scan = emit_label_after (gen_label_rtx (), scan);
12806   scan = emit_insn_after (align64 ? gen_align_8 () : gen_align_4 (), scan);
12807   scan = emit_label_after (minipool_vector_label, scan);
12808
12809   for (mp = minipool_vector_head; mp != NULL; mp = nmp)
12810     {
12811       if (mp->refcount > 0)
12812         {
12813           if (dump_file)
12814             {
12815               fprintf (dump_file,
12816                        ";;  Offset %u, min %ld, max %ld ",
12817                        (unsigned) mp->offset, (unsigned long) mp->min_address,
12818                        (unsigned long) mp->max_address);
12819               arm_print_value (dump_file, mp->value);
12820               fputc ('\n', dump_file);
12821             }
12822
12823           switch (mp->fix_size)
12824             {
12825 #ifdef HAVE_consttable_1
12826             case 1:
12827               scan = emit_insn_after (gen_consttable_1 (mp->value), scan);
12828               break;
12829
12830 #endif
12831 #ifdef HAVE_consttable_2
12832             case 2:
12833               scan = emit_insn_after (gen_consttable_2 (mp->value), scan);
12834               break;
12835
12836 #endif
12837 #ifdef HAVE_consttable_4
12838             case 4:
12839               scan = emit_insn_after (gen_consttable_4 (mp->value), scan);
12840               break;
12841
12842 #endif
12843 #ifdef HAVE_consttable_8
12844             case 8:
12845               scan = emit_insn_after (gen_consttable_8 (mp->value), scan);
12846               break;
12847
12848 #endif
12849 #ifdef HAVE_consttable_16
12850             case 16:
12851               scan = emit_insn_after (gen_consttable_16 (mp->value), scan);
12852               break;
12853
12854 #endif
12855             default:
12856               gcc_unreachable ();
12857             }
12858         }
12859
12860       nmp = mp->next;
12861       free (mp);
12862     }
12863
12864   minipool_vector_head = minipool_vector_tail = NULL;
12865   scan = emit_insn_after (gen_consttable_end (), scan);
12866   scan = emit_barrier_after (scan);
12867 }
12868
12869 /* Return the cost of forcibly inserting a barrier after INSN.  */
12870 static int
12871 arm_barrier_cost (rtx insn)
12872 {
12873   /* Basing the location of the pool on the loop depth is preferable,
12874      but at the moment, the basic block information seems to be
12875      corrupt by this stage of the compilation.  */
12876   int base_cost = 50;
12877   rtx next = next_nonnote_insn (insn);
12878
12879   if (next != NULL && GET_CODE (next) == CODE_LABEL)
12880     base_cost -= 20;
12881
12882   switch (GET_CODE (insn))
12883     {
12884     case CODE_LABEL:
12885       /* It will always be better to place the table before the label, rather
12886          than after it.  */
12887       return 50;
12888
12889     case INSN:
12890     case CALL_INSN:
12891       return base_cost;
12892
12893     case JUMP_INSN:
12894       return base_cost - 10;
12895
12896     default:
12897       return base_cost + 10;
12898     }
12899 }
12900
12901 /* Find the best place in the insn stream in the range
12902    (FIX->address,MAX_ADDRESS) to forcibly insert a minipool barrier.
12903    Create the barrier by inserting a jump and add a new fix entry for
12904    it.  */
12905 static Mfix *
12906 create_fix_barrier (Mfix *fix, HOST_WIDE_INT max_address)
12907 {
12908   HOST_WIDE_INT count = 0;
12909   rtx barrier;
12910   rtx from = fix->insn;
12911   /* The instruction after which we will insert the jump.  */
12912   rtx selected = NULL;
12913   int selected_cost;
12914   /* The address at which the jump instruction will be placed.  */
12915   HOST_WIDE_INT selected_address;
12916   Mfix * new_fix;
12917   HOST_WIDE_INT max_count = max_address - fix->address;
12918   rtx label = gen_label_rtx ();
12919
12920   selected_cost = arm_barrier_cost (from);
12921   selected_address = fix->address;
12922
12923   while (from && count < max_count)
12924     {
12925       rtx tmp;
12926       int new_cost;
12927
12928       /* This code shouldn't have been called if there was a natural barrier
12929          within range.  */
12930       gcc_assert (GET_CODE (from) != BARRIER);
12931
12932       /* Count the length of this insn.  This must stay in sync with the
12933          code that pushes minipool fixes.  */
12934       if (LABEL_P (from))
12935         count += get_label_padding (from);
12936       else
12937         count += get_attr_length (from);
12938
12939       /* If there is a jump table, add its length.  */
12940       tmp = is_jump_table (from);
12941       if (tmp != NULL)
12942         {
12943           count += get_jump_table_size (tmp);
12944
12945           /* Jump tables aren't in a basic block, so base the cost on
12946              the dispatch insn.  If we select this location, we will
12947              still put the pool after the table.  */
12948           new_cost = arm_barrier_cost (from);
12949
12950           if (count < max_count
12951               && (!selected || new_cost <= selected_cost))
12952             {
12953               selected = tmp;
12954               selected_cost = new_cost;
12955               selected_address = fix->address + count;
12956             }
12957
12958           /* Continue after the dispatch table.  */
12959           from = NEXT_INSN (tmp);
12960           continue;
12961         }
12962
12963       new_cost = arm_barrier_cost (from);
12964
12965       if (count < max_count
12966           && (!selected || new_cost <= selected_cost))
12967         {
12968           selected = from;
12969           selected_cost = new_cost;
12970           selected_address = fix->address + count;
12971         }
12972
12973       from = NEXT_INSN (from);
12974     }
12975
12976   /* Make sure that we found a place to insert the jump.  */
12977   gcc_assert (selected);
12978
12979   /* Make sure we do not split a call and its corresponding
12980      CALL_ARG_LOCATION note.  */
12981   if (CALL_P (selected))
12982     {
12983       rtx next = NEXT_INSN (selected);
12984       if (next && NOTE_P (next)
12985           && NOTE_KIND (next) == NOTE_INSN_CALL_ARG_LOCATION)
12986           selected = next;
12987     }
12988
12989   /* Create a new JUMP_INSN that branches around a barrier.  */
12990   from = emit_jump_insn_after (gen_jump (label), selected);
12991   JUMP_LABEL (from) = label;
12992   barrier = emit_barrier_after (from);
12993   emit_label_after (label, barrier);
12994
12995   /* Create a minipool barrier entry for the new barrier.  */
12996   new_fix = (Mfix *) obstack_alloc (&minipool_obstack, sizeof (* new_fix));
12997   new_fix->insn = barrier;
12998   new_fix->address = selected_address;
12999   new_fix->next = fix->next;
13000   fix->next = new_fix;
13001
13002   return new_fix;
13003 }
13004
13005 /* Record that there is a natural barrier in the insn stream at
13006    ADDRESS.  */
13007 static void
13008 push_minipool_barrier (rtx insn, HOST_WIDE_INT address)
13009 {
13010   Mfix * fix = (Mfix *) obstack_alloc (&minipool_obstack, sizeof (* fix));
13011
13012   fix->insn = insn;
13013   fix->address = address;
13014
13015   fix->next = NULL;
13016   if (minipool_fix_head != NULL)
13017     minipool_fix_tail->next = fix;
13018   else
13019     minipool_fix_head = fix;
13020
13021   minipool_fix_tail = fix;
13022 }
13023
13024 /* Record INSN, which will need fixing up to load a value from the
13025    minipool.  ADDRESS is the offset of the insn since the start of the
13026    function; LOC is a pointer to the part of the insn which requires
13027    fixing; VALUE is the constant that must be loaded, which is of type
13028    MODE.  */
13029 static void
13030 push_minipool_fix (rtx insn, HOST_WIDE_INT address, rtx *loc,
13031                    enum machine_mode mode, rtx value)
13032 {
13033   Mfix * fix = (Mfix *) obstack_alloc (&minipool_obstack, sizeof (* fix));
13034
13035   fix->insn = insn;
13036   fix->address = address;
13037   fix->loc = loc;
13038   fix->mode = mode;
13039   fix->fix_size = MINIPOOL_FIX_SIZE (mode);
13040   fix->value = value;
13041   fix->forwards = get_attr_pool_range (insn);
13042   fix->backwards = get_attr_neg_pool_range (insn);
13043   fix->minipool = NULL;
13044
13045   /* If an insn doesn't have a range defined for it, then it isn't
13046      expecting to be reworked by this code.  Better to stop now than
13047      to generate duff assembly code.  */
13048   gcc_assert (fix->forwards || fix->backwards);
13049
13050   /* If an entry requires 8-byte alignment then assume all constant pools
13051      require 4 bytes of padding.  Trying to do this later on a per-pool
13052      basis is awkward because existing pool entries have to be modified.  */
13053   if (ARM_DOUBLEWORD_ALIGN && fix->fix_size >= 8)
13054     minipool_pad = 4;
13055
13056   if (dump_file)
13057     {
13058       fprintf (dump_file,
13059                ";; %smode fixup for i%d; addr %lu, range (%ld,%ld): ",
13060                GET_MODE_NAME (mode),
13061                INSN_UID (insn), (unsigned long) address,
13062                -1 * (long)fix->backwards, (long)fix->forwards);
13063       arm_print_value (dump_file, fix->value);
13064       fprintf (dump_file, "\n");
13065     }
13066
13067   /* Add it to the chain of fixes.  */
13068   fix->next = NULL;
13069
13070   if (minipool_fix_head != NULL)
13071     minipool_fix_tail->next = fix;
13072   else
13073     minipool_fix_head = fix;
13074
13075   minipool_fix_tail = fix;
13076 }
13077
13078 /* Return the cost of synthesizing a 64-bit constant VAL inline.
13079    Returns the number of insns needed, or 99 if we don't know how to
13080    do it.  */
13081 int
13082 arm_const_double_inline_cost (rtx val)
13083 {
13084   rtx lowpart, highpart;
13085   enum machine_mode mode;
13086
13087   mode = GET_MODE (val);
13088
13089   if (mode == VOIDmode)
13090     mode = DImode;
13091
13092   gcc_assert (GET_MODE_SIZE (mode) == 8);
13093
13094   lowpart = gen_lowpart (SImode, val);
13095   highpart = gen_highpart_mode (SImode, mode, val);
13096
13097   gcc_assert (GET_CODE (lowpart) == CONST_INT);
13098   gcc_assert (GET_CODE (highpart) == CONST_INT);
13099
13100   return (arm_gen_constant (SET, SImode, NULL_RTX, INTVAL (lowpart),
13101                             NULL_RTX, NULL_RTX, 0, 0)
13102           + arm_gen_constant (SET, SImode, NULL_RTX, INTVAL (highpart),
13103                               NULL_RTX, NULL_RTX, 0, 0));
13104 }
13105
13106 /* Return true if it is worthwhile to split a 64-bit constant into two
13107    32-bit operations.  This is the case if optimizing for size, or
13108    if we have load delay slots, or if one 32-bit part can be done with
13109    a single data operation.  */
13110 bool
13111 arm_const_double_by_parts (rtx val)
13112 {
13113   enum machine_mode mode = GET_MODE (val);
13114   rtx part;
13115
13116   if (optimize_size || arm_ld_sched)
13117     return true;
13118
13119   if (mode == VOIDmode)
13120     mode = DImode;
13121
13122   part = gen_highpart_mode (SImode, mode, val);
13123
13124   gcc_assert (GET_CODE (part) == CONST_INT);
13125
13126   if (const_ok_for_arm (INTVAL (part))
13127       || const_ok_for_arm (~INTVAL (part)))
13128     return true;
13129
13130   part = gen_lowpart (SImode, val);
13131
13132   gcc_assert (GET_CODE (part) == CONST_INT);
13133
13134   if (const_ok_for_arm (INTVAL (part))
13135       || const_ok_for_arm (~INTVAL (part)))
13136     return true;
13137
13138   return false;
13139 }
13140
13141 /* Return true if it is possible to inline both the high and low parts
13142    of a 64-bit constant into 32-bit data processing instructions.  */
13143 bool
13144 arm_const_double_by_immediates (rtx val)
13145 {
13146   enum machine_mode mode = GET_MODE (val);
13147   rtx part;
13148
13149   if (mode == VOIDmode)
13150     mode = DImode;
13151
13152   part = gen_highpart_mode (SImode, mode, val);
13153
13154   gcc_assert (GET_CODE (part) == CONST_INT);
13155
13156   if (!const_ok_for_arm (INTVAL (part)))
13157     return false;
13158
13159   part = gen_lowpart (SImode, val);
13160
13161   gcc_assert (GET_CODE (part) == CONST_INT);
13162
13163   if (!const_ok_for_arm (INTVAL (part)))
13164     return false;
13165
13166   return true;
13167 }
13168
13169 /* Scan INSN and note any of its operands that need fixing.
13170    If DO_PUSHES is false we do not actually push any of the fixups
13171    needed.  The function returns TRUE if any fixups were needed/pushed.
13172    This is used by arm_memory_load_p() which needs to know about loads
13173    of constants that will be converted into minipool loads.  */
13174 static bool
13175 note_invalid_constants (rtx insn, HOST_WIDE_INT address, int do_pushes)
13176 {
13177   bool result = false;
13178   int opno;
13179
13180   extract_insn (insn);
13181
13182   if (!constrain_operands (1))
13183     fatal_insn_not_found (insn);
13184
13185   if (recog_data.n_alternatives == 0)
13186     return false;
13187
13188   /* Fill in recog_op_alt with information about the constraints of
13189      this insn.  */
13190   preprocess_constraints ();
13191
13192   for (opno = 0; opno < recog_data.n_operands; opno++)
13193     {
13194       /* Things we need to fix can only occur in inputs.  */
13195       if (recog_data.operand_type[opno] != OP_IN)
13196         continue;
13197
13198       /* If this alternative is a memory reference, then any mention
13199          of constants in this alternative is really to fool reload
13200          into allowing us to accept one there.  We need to fix them up
13201          now so that we output the right code.  */
13202       if (recog_op_alt[opno][which_alternative].memory_ok)
13203         {
13204           rtx op = recog_data.operand[opno];
13205
13206           if (CONSTANT_P (op))
13207             {
13208               if (do_pushes)
13209                 push_minipool_fix (insn, address, recog_data.operand_loc[opno],
13210                                    recog_data.operand_mode[opno], op);
13211               result = true;
13212             }
13213           else if (GET_CODE (op) == MEM
13214                    && GET_CODE (XEXP (op, 0)) == SYMBOL_REF
13215                    && CONSTANT_POOL_ADDRESS_P (XEXP (op, 0)))
13216             {
13217               if (do_pushes)
13218                 {
13219                   rtx cop = avoid_constant_pool_reference (op);
13220
13221                   /* Casting the address of something to a mode narrower
13222                      than a word can cause avoid_constant_pool_reference()
13223                      to return the pool reference itself.  That's no good to
13224                      us here.  Lets just hope that we can use the
13225                      constant pool value directly.  */
13226                   if (op == cop)
13227                     cop = get_pool_constant (XEXP (op, 0));
13228
13229                   push_minipool_fix (insn, address,
13230                                      recog_data.operand_loc[opno],
13231                                      recog_data.operand_mode[opno], cop);
13232                 }
13233
13234               result = true;
13235             }
13236         }
13237     }
13238
13239   return result;
13240 }
13241
13242 /* Convert instructions to their cc-clobbering variant if possible, since
13243    that allows us to use smaller encodings.  */
13244
13245 static void
13246 thumb2_reorg (void)
13247 {
13248   basic_block bb;
13249   regset_head live;
13250
13251   INIT_REG_SET (&live);
13252
13253   /* We are freeing block_for_insn in the toplev to keep compatibility
13254      with old MDEP_REORGS that are not CFG based.  Recompute it now.  */
13255   compute_bb_for_insn ();
13256   df_analyze ();
13257
13258   FOR_EACH_BB (bb)
13259     {
13260       rtx insn;
13261
13262       COPY_REG_SET (&live, DF_LR_OUT (bb));
13263       df_simulate_initialize_backwards (bb, &live);
13264       FOR_BB_INSNS_REVERSE (bb, insn)
13265         {
13266           if (NONJUMP_INSN_P (insn)
13267               && !REGNO_REG_SET_P (&live, CC_REGNUM))
13268             {
13269               rtx pat = PATTERN (insn);
13270               if (GET_CODE (pat) == SET
13271                   && low_register_operand (XEXP (pat, 0), SImode)
13272                   && thumb_16bit_operator (XEXP (pat, 1), SImode)
13273                   && low_register_operand (XEXP (XEXP (pat, 1), 0), SImode)
13274                   && low_register_operand (XEXP (XEXP (pat, 1), 1), SImode))
13275                 {
13276                   rtx dst = XEXP (pat, 0);
13277                   rtx src = XEXP (pat, 1);
13278                   rtx op0 = XEXP (src, 0);
13279                   rtx op1 = (GET_RTX_CLASS (GET_CODE (src)) == RTX_COMM_ARITH
13280                              ? XEXP (src, 1) : NULL);
13281
13282                   if (rtx_equal_p (dst, op0)
13283                       || GET_CODE (src) == PLUS || GET_CODE (src) == MINUS)
13284                     {
13285                       rtx ccreg = gen_rtx_REG (CCmode, CC_REGNUM);
13286                       rtx clobber = gen_rtx_CLOBBER (VOIDmode, ccreg);
13287                       rtvec vec = gen_rtvec (2, pat, clobber);
13288
13289                       PATTERN (insn) = gen_rtx_PARALLEL (VOIDmode, vec);
13290                       INSN_CODE (insn) = -1;
13291                     }
13292                   /* We can also handle a commutative operation where the
13293                      second operand matches the destination.  */
13294                   else if (op1 && rtx_equal_p (dst, op1))
13295                     {
13296                       rtx ccreg = gen_rtx_REG (CCmode, CC_REGNUM);
13297                       rtx clobber = gen_rtx_CLOBBER (VOIDmode, ccreg);
13298                       rtvec vec;
13299
13300                       src = copy_rtx (src);
13301                       XEXP (src, 0) = op1;
13302                       XEXP (src, 1) = op0;
13303                       pat = gen_rtx_SET (VOIDmode, dst, src);
13304                       vec = gen_rtvec (2, pat, clobber);
13305                       PATTERN (insn) = gen_rtx_PARALLEL (VOIDmode, vec);
13306                       INSN_CODE (insn) = -1;
13307                     }
13308                 }
13309             }
13310
13311           if (NONDEBUG_INSN_P (insn))
13312             df_simulate_one_insn_backwards (bb, insn, &live);
13313         }
13314     }
13315
13316   CLEAR_REG_SET (&live);
13317 }
13318
13319 /* Gcc puts the pool in the wrong place for ARM, since we can only
13320    load addresses a limited distance around the pc.  We do some
13321    special munging to move the constant pool values to the correct
13322    point in the code.  */
13323 static void
13324 arm_reorg (void)
13325 {
13326   rtx insn;
13327   HOST_WIDE_INT address = 0;
13328   Mfix * fix;
13329
13330   if (TARGET_THUMB2)
13331     thumb2_reorg ();
13332
13333   minipool_fix_head = minipool_fix_tail = NULL;
13334
13335   /* The first insn must always be a note, or the code below won't
13336      scan it properly.  */
13337   insn = get_insns ();
13338   gcc_assert (GET_CODE (insn) == NOTE);
13339   minipool_pad = 0;
13340
13341   /* Scan all the insns and record the operands that will need fixing.  */
13342   for (insn = next_nonnote_insn (insn); insn; insn = next_nonnote_insn (insn))
13343     {
13344       if (TARGET_CIRRUS_FIX_INVALID_INSNS
13345           && (arm_cirrus_insn_p (insn)
13346               || GET_CODE (insn) == JUMP_INSN
13347               || arm_memory_load_p (insn)))
13348         cirrus_reorg (insn);
13349
13350       if (GET_CODE (insn) == BARRIER)
13351         push_minipool_barrier (insn, address);
13352       else if (INSN_P (insn))
13353         {
13354           rtx table;
13355
13356           note_invalid_constants (insn, address, true);
13357           address += get_attr_length (insn);
13358
13359           /* If the insn is a vector jump, add the size of the table
13360              and skip the table.  */
13361           if ((table = is_jump_table (insn)) != NULL)
13362             {
13363               address += get_jump_table_size (table);
13364               insn = table;
13365             }
13366         }
13367       else if (LABEL_P (insn))
13368         /* Add the worst-case padding due to alignment.  We don't add
13369            the _current_ padding because the minipool insertions
13370            themselves might change it.  */
13371         address += get_label_padding (insn);
13372     }
13373
13374   fix = minipool_fix_head;
13375
13376   /* Now scan the fixups and perform the required changes.  */
13377   while (fix)
13378     {
13379       Mfix * ftmp;
13380       Mfix * fdel;
13381       Mfix *  last_added_fix;
13382       Mfix * last_barrier = NULL;
13383       Mfix * this_fix;
13384
13385       /* Skip any further barriers before the next fix.  */
13386       while (fix && GET_CODE (fix->insn) == BARRIER)
13387         fix = fix->next;
13388
13389       /* No more fixes.  */
13390       if (fix == NULL)
13391         break;
13392
13393       last_added_fix = NULL;
13394
13395       for (ftmp = fix; ftmp; ftmp = ftmp->next)
13396         {
13397           if (GET_CODE (ftmp->insn) == BARRIER)
13398             {
13399               if (ftmp->address >= minipool_vector_head->max_address)
13400                 break;
13401
13402               last_barrier = ftmp;
13403             }
13404           else if ((ftmp->minipool = add_minipool_forward_ref (ftmp)) == NULL)
13405             break;
13406
13407           last_added_fix = ftmp;  /* Keep track of the last fix added.  */
13408         }
13409
13410       /* If we found a barrier, drop back to that; any fixes that we
13411          could have reached but come after the barrier will now go in
13412          the next mini-pool.  */
13413       if (last_barrier != NULL)
13414         {
13415           /* Reduce the refcount for those fixes that won't go into this
13416              pool after all.  */
13417           for (fdel = last_barrier->next;
13418                fdel && fdel != ftmp;
13419                fdel = fdel->next)
13420             {
13421               fdel->minipool->refcount--;
13422               fdel->minipool = NULL;
13423             }
13424
13425           ftmp = last_barrier;
13426         }
13427       else
13428         {
13429           /* ftmp is first fix that we can't fit into this pool and
13430              there no natural barriers that we could use.  Insert a
13431              new barrier in the code somewhere between the previous
13432              fix and this one, and arrange to jump around it.  */
13433           HOST_WIDE_INT max_address;
13434
13435           /* The last item on the list of fixes must be a barrier, so
13436              we can never run off the end of the list of fixes without
13437              last_barrier being set.  */
13438           gcc_assert (ftmp);
13439
13440           max_address = minipool_vector_head->max_address;
13441           /* Check that there isn't another fix that is in range that
13442              we couldn't fit into this pool because the pool was
13443              already too large: we need to put the pool before such an
13444              instruction.  The pool itself may come just after the
13445              fix because create_fix_barrier also allows space for a
13446              jump instruction.  */
13447           if (ftmp->address < max_address)
13448             max_address = ftmp->address + 1;
13449
13450           last_barrier = create_fix_barrier (last_added_fix, max_address);
13451         }
13452
13453       assign_minipool_offsets (last_barrier);
13454
13455       while (ftmp)
13456         {
13457           if (GET_CODE (ftmp->insn) != BARRIER
13458               && ((ftmp->minipool = add_minipool_backward_ref (ftmp))
13459                   == NULL))
13460             break;
13461
13462           ftmp = ftmp->next;
13463         }
13464
13465       /* Scan over the fixes we have identified for this pool, fixing them
13466          up and adding the constants to the pool itself.  */
13467       for (this_fix = fix; this_fix && ftmp != this_fix;
13468            this_fix = this_fix->next)
13469         if (GET_CODE (this_fix->insn) != BARRIER)
13470           {
13471             rtx addr
13472               = plus_constant (gen_rtx_LABEL_REF (VOIDmode,
13473                                                   minipool_vector_label),
13474                                this_fix->minipool->offset);
13475             *this_fix->loc = gen_rtx_MEM (this_fix->mode, addr);
13476           }
13477
13478       dump_minipool (last_barrier->insn);
13479       fix = ftmp;
13480     }
13481
13482   /* From now on we must synthesize any constants that we can't handle
13483      directly.  This can happen if the RTL gets split during final
13484      instruction generation.  */
13485   after_arm_reorg = 1;
13486
13487   /* Free the minipool memory.  */
13488   obstack_free (&minipool_obstack, minipool_startobj);
13489 }
13490 \f
13491 /* Routines to output assembly language.  */
13492
13493 /* If the rtx is the correct value then return the string of the number.
13494    In this way we can ensure that valid double constants are generated even
13495    when cross compiling.  */
13496 const char *
13497 fp_immediate_constant (rtx x)
13498 {
13499   REAL_VALUE_TYPE r;
13500   int i;
13501
13502   if (!fp_consts_inited)
13503     init_fp_table ();
13504
13505   REAL_VALUE_FROM_CONST_DOUBLE (r, x);
13506   for (i = 0; i < 8; i++)
13507     if (REAL_VALUES_EQUAL (r, values_fp[i]))
13508       return strings_fp[i];
13509
13510   gcc_unreachable ();
13511 }
13512
13513 /* As for fp_immediate_constant, but value is passed directly, not in rtx.  */
13514 static const char *
13515 fp_const_from_val (REAL_VALUE_TYPE *r)
13516 {
13517   int i;
13518
13519   if (!fp_consts_inited)
13520     init_fp_table ();
13521
13522   for (i = 0; i < 8; i++)
13523     if (REAL_VALUES_EQUAL (*r, values_fp[i]))
13524       return strings_fp[i];
13525
13526   gcc_unreachable ();
13527 }
13528
13529 /* Output the operands of a LDM/STM instruction to STREAM.
13530    MASK is the ARM register set mask of which only bits 0-15 are important.
13531    REG is the base register, either the frame pointer or the stack pointer,
13532    INSTR is the possibly suffixed load or store instruction.
13533    RFE is nonzero if the instruction should also copy spsr to cpsr.  */
13534
13535 static void
13536 print_multi_reg (FILE *stream, const char *instr, unsigned reg,
13537                  unsigned long mask, int rfe)
13538 {
13539   unsigned i;
13540   bool not_first = FALSE;
13541
13542   gcc_assert (!rfe || (mask & (1 << PC_REGNUM)));
13543   fputc ('\t', stream);
13544   asm_fprintf (stream, instr, reg);
13545   fputc ('{', stream);
13546
13547   for (i = 0; i <= LAST_ARM_REGNUM; i++)
13548     if (mask & (1 << i))
13549       {
13550         if (not_first)
13551           fprintf (stream, ", ");
13552
13553         asm_fprintf (stream, "%r", i);
13554         not_first = TRUE;
13555       }
13556
13557   if (rfe)
13558     fprintf (stream, "}^\n");
13559   else
13560     fprintf (stream, "}\n");
13561 }
13562
13563
13564 /* Output a FLDMD instruction to STREAM.
13565    BASE if the register containing the address.
13566    REG and COUNT specify the register range.
13567    Extra registers may be added to avoid hardware bugs.
13568
13569    We output FLDMD even for ARMv5 VFP implementations.  Although
13570    FLDMD is technically not supported until ARMv6, it is believed
13571    that all VFP implementations support its use in this context.  */
13572
13573 static void
13574 vfp_output_fldmd (FILE * stream, unsigned int base, int reg, int count)
13575 {
13576   int i;
13577
13578   /* Workaround ARM10 VFPr1 bug.  */
13579   if (count == 2 && !arm_arch6)
13580     {
13581       if (reg == 15)
13582         reg--;
13583       count++;
13584     }
13585
13586   /* FLDMD may not load more than 16 doubleword registers at a time. Split the
13587      load into multiple parts if we have to handle more than 16 registers.  */
13588   if (count > 16)
13589     {
13590       vfp_output_fldmd (stream, base, reg, 16);
13591       vfp_output_fldmd (stream, base, reg + 16, count - 16);
13592       return;
13593     }
13594
13595   fputc ('\t', stream);
13596   asm_fprintf (stream, "fldmfdd\t%r!, {", base);
13597
13598   for (i = reg; i < reg + count; i++)
13599     {
13600       if (i > reg)
13601         fputs (", ", stream);
13602       asm_fprintf (stream, "d%d", i);
13603     }
13604   fputs ("}\n", stream);
13605
13606 }
13607
13608
13609 /* Output the assembly for a store multiple.  */
13610
13611 const char *
13612 vfp_output_fstmd (rtx * operands)
13613 {
13614   char pattern[100];
13615   int p;
13616   int base;
13617   int i;
13618
13619   strcpy (pattern, "fstmfdd%?\t%m0!, {%P1");
13620   p = strlen (pattern);
13621
13622   gcc_assert (GET_CODE (operands[1]) == REG);
13623
13624   base = (REGNO (operands[1]) - FIRST_VFP_REGNUM) / 2;
13625   for (i = 1; i < XVECLEN (operands[2], 0); i++)
13626     {
13627       p += sprintf (&pattern[p], ", d%d", base + i);
13628     }
13629   strcpy (&pattern[p], "}");
13630
13631   output_asm_insn (pattern, operands);
13632   return "";
13633 }
13634
13635
13636 /* Emit RTL to save block of VFP register pairs to the stack.  Returns the
13637    number of bytes pushed.  */
13638
13639 static int
13640 vfp_emit_fstmd (int base_reg, int count)
13641 {
13642   rtx par;
13643   rtx dwarf;
13644   rtx tmp, reg;
13645   int i;
13646
13647   /* Workaround ARM10 VFPr1 bug.  Data corruption can occur when exactly two
13648      register pairs are stored by a store multiple insn.  We avoid this
13649      by pushing an extra pair.  */
13650   if (count == 2 && !arm_arch6)
13651     {
13652       if (base_reg == LAST_VFP_REGNUM - 3)
13653         base_reg -= 2;
13654       count++;
13655     }
13656
13657   /* FSTMD may not store more than 16 doubleword registers at once.  Split
13658      larger stores into multiple parts (up to a maximum of two, in
13659      practice).  */
13660   if (count > 16)
13661     {
13662       int saved;
13663       /* NOTE: base_reg is an internal register number, so each D register
13664          counts as 2.  */
13665       saved = vfp_emit_fstmd (base_reg + 32, count - 16);
13666       saved += vfp_emit_fstmd (base_reg, 16);
13667       return saved;
13668     }
13669
13670   par = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (count));
13671   dwarf = gen_rtx_SEQUENCE (VOIDmode, rtvec_alloc (count + 1));
13672
13673   reg = gen_rtx_REG (DFmode, base_reg);
13674   base_reg += 2;
13675
13676   XVECEXP (par, 0, 0)
13677     = gen_rtx_SET (VOIDmode,
13678                    gen_frame_mem
13679                    (BLKmode,
13680                     gen_rtx_PRE_MODIFY (Pmode,
13681                                         stack_pointer_rtx,
13682                                         plus_constant
13683                                         (stack_pointer_rtx,
13684                                          - (count * 8)))
13685                     ),
13686                    gen_rtx_UNSPEC (BLKmode,
13687                                    gen_rtvec (1, reg),
13688                                    UNSPEC_PUSH_MULT));
13689
13690   tmp = gen_rtx_SET (VOIDmode, stack_pointer_rtx,
13691                      plus_constant (stack_pointer_rtx, -(count * 8)));
13692   RTX_FRAME_RELATED_P (tmp) = 1;
13693   XVECEXP (dwarf, 0, 0) = tmp;
13694
13695   tmp = gen_rtx_SET (VOIDmode,
13696                      gen_frame_mem (DFmode, stack_pointer_rtx),
13697                      reg);
13698   RTX_FRAME_RELATED_P (tmp) = 1;
13699   XVECEXP (dwarf, 0, 1) = tmp;
13700
13701   for (i = 1; i < count; i++)
13702     {
13703       reg = gen_rtx_REG (DFmode, base_reg);
13704       base_reg += 2;
13705       XVECEXP (par, 0, i) = gen_rtx_USE (VOIDmode, reg);
13706
13707       tmp = gen_rtx_SET (VOIDmode,
13708                          gen_frame_mem (DFmode,
13709                                         plus_constant (stack_pointer_rtx,
13710                                                        i * 8)),
13711                          reg);
13712       RTX_FRAME_RELATED_P (tmp) = 1;
13713       XVECEXP (dwarf, 0, i + 1) = tmp;
13714     }
13715
13716   par = emit_insn (par);
13717   add_reg_note (par, REG_FRAME_RELATED_EXPR, dwarf);
13718   RTX_FRAME_RELATED_P (par) = 1;
13719
13720   return count * 8;
13721 }
13722
13723 /* Emit a call instruction with pattern PAT.  ADDR is the address of
13724    the call target.  */
13725
13726 void
13727 arm_emit_call_insn (rtx pat, rtx addr)
13728 {
13729   rtx insn;
13730
13731   insn = emit_call_insn (pat);
13732
13733   /* The PIC register is live on entry to VxWorks PIC PLT entries.
13734      If the call might use such an entry, add a use of the PIC register
13735      to the instruction's CALL_INSN_FUNCTION_USAGE.  */
13736   if (TARGET_VXWORKS_RTP
13737       && flag_pic
13738       && GET_CODE (addr) == SYMBOL_REF
13739       && (SYMBOL_REF_DECL (addr)
13740           ? !targetm.binds_local_p (SYMBOL_REF_DECL (addr))
13741           : !SYMBOL_REF_LOCAL_P (addr)))
13742     {
13743       require_pic_register ();
13744       use_reg (&CALL_INSN_FUNCTION_USAGE (insn), cfun->machine->pic_reg);
13745     }
13746 }
13747
13748 /* Output a 'call' insn.  */
13749 const char *
13750 output_call (rtx *operands)
13751 {
13752   gcc_assert (!arm_arch5); /* Patterns should call blx <reg> directly.  */
13753
13754   /* Handle calls to lr using ip (which may be clobbered in subr anyway).  */
13755   if (REGNO (operands[0]) == LR_REGNUM)
13756     {
13757       operands[0] = gen_rtx_REG (SImode, IP_REGNUM);
13758       output_asm_insn ("mov%?\t%0, %|lr", operands);
13759     }
13760
13761   output_asm_insn ("mov%?\t%|lr, %|pc", operands);
13762
13763   if (TARGET_INTERWORK || arm_arch4t)
13764     output_asm_insn ("bx%?\t%0", operands);
13765   else
13766     output_asm_insn ("mov%?\t%|pc, %0", operands);
13767
13768   return "";
13769 }
13770
13771 /* Output a 'call' insn that is a reference in memory. This is
13772    disabled for ARMv5 and we prefer a blx instead because otherwise
13773    there's a significant performance overhead.  */
13774 const char *
13775 output_call_mem (rtx *operands)
13776 {
13777   gcc_assert (!arm_arch5);
13778   if (TARGET_INTERWORK)
13779     {
13780       output_asm_insn ("ldr%?\t%|ip, %0", operands);
13781       output_asm_insn ("mov%?\t%|lr, %|pc", operands);
13782       output_asm_insn ("bx%?\t%|ip", operands);
13783     }
13784   else if (regno_use_in (LR_REGNUM, operands[0]))
13785     {
13786       /* LR is used in the memory address.  We load the address in the
13787          first instruction.  It's safe to use IP as the target of the
13788          load since the call will kill it anyway.  */
13789       output_asm_insn ("ldr%?\t%|ip, %0", operands);
13790       output_asm_insn ("mov%?\t%|lr, %|pc", operands);
13791       if (arm_arch4t)
13792         output_asm_insn ("bx%?\t%|ip", operands);
13793       else
13794         output_asm_insn ("mov%?\t%|pc, %|ip", operands);
13795     }
13796   else
13797     {
13798       output_asm_insn ("mov%?\t%|lr, %|pc", operands);
13799       output_asm_insn ("ldr%?\t%|pc, %0", operands);
13800     }
13801
13802   return "";
13803 }
13804
13805
13806 /* Output a move from arm registers to an fpa registers.
13807    OPERANDS[0] is an fpa register.
13808    OPERANDS[1] is the first registers of an arm register pair.  */
13809 const char *
13810 output_mov_long_double_fpa_from_arm (rtx *operands)
13811 {
13812   int arm_reg0 = REGNO (operands[1]);
13813   rtx ops[3];
13814
13815   gcc_assert (arm_reg0 != IP_REGNUM);
13816
13817   ops[0] = gen_rtx_REG (SImode, arm_reg0);
13818   ops[1] = gen_rtx_REG (SImode, 1 + arm_reg0);
13819   ops[2] = gen_rtx_REG (SImode, 2 + arm_reg0);
13820
13821   output_asm_insn ("stm%(fd%)\t%|sp!, {%0, %1, %2}", ops);
13822   output_asm_insn ("ldf%?e\t%0, [%|sp], #12", operands);
13823
13824   return "";
13825 }
13826
13827 /* Output a move from an fpa register to arm registers.
13828    OPERANDS[0] is the first registers of an arm register pair.
13829    OPERANDS[1] is an fpa register.  */
13830 const char *
13831 output_mov_long_double_arm_from_fpa (rtx *operands)
13832 {
13833   int arm_reg0 = REGNO (operands[0]);
13834   rtx ops[3];
13835
13836   gcc_assert (arm_reg0 != IP_REGNUM);
13837
13838   ops[0] = gen_rtx_REG (SImode, arm_reg0);
13839   ops[1] = gen_rtx_REG (SImode, 1 + arm_reg0);
13840   ops[2] = gen_rtx_REG (SImode, 2 + arm_reg0);
13841
13842   output_asm_insn ("stf%?e\t%1, [%|sp, #-12]!", operands);
13843   output_asm_insn ("ldm%(fd%)\t%|sp!, {%0, %1, %2}", ops);
13844   return "";
13845 }
13846
13847 /* Output a move from arm registers to arm registers of a long double
13848    OPERANDS[0] is the destination.
13849    OPERANDS[1] is the source.  */
13850 const char *
13851 output_mov_long_double_arm_from_arm (rtx *operands)
13852 {
13853   /* We have to be careful here because the two might overlap.  */
13854   int dest_start = REGNO (operands[0]);
13855   int src_start = REGNO (operands[1]);
13856   rtx ops[2];
13857   int i;
13858
13859   if (dest_start < src_start)
13860     {
13861       for (i = 0; i < 3; i++)
13862         {
13863           ops[0] = gen_rtx_REG (SImode, dest_start + i);
13864           ops[1] = gen_rtx_REG (SImode, src_start + i);
13865           output_asm_insn ("mov%?\t%0, %1", ops);
13866         }
13867     }
13868   else
13869     {
13870       for (i = 2; i >= 0; i--)
13871         {
13872           ops[0] = gen_rtx_REG (SImode, dest_start + i);
13873           ops[1] = gen_rtx_REG (SImode, src_start + i);
13874           output_asm_insn ("mov%?\t%0, %1", ops);
13875         }
13876     }
13877
13878   return "";
13879 }
13880
13881 void
13882 arm_emit_movpair (rtx dest, rtx src)
13883  {
13884   /* If the src is an immediate, simplify it.  */
13885   if (CONST_INT_P (src))
13886     {
13887       HOST_WIDE_INT val = INTVAL (src);
13888       emit_set_insn (dest, GEN_INT (val & 0x0000ffff));
13889       if ((val >> 16) & 0x0000ffff)
13890         emit_set_insn (gen_rtx_ZERO_EXTRACT (SImode, dest, GEN_INT (16),
13891                                              GEN_INT (16)),
13892                        GEN_INT ((val >> 16) & 0x0000ffff));
13893       return;
13894     }
13895    emit_set_insn (dest, gen_rtx_HIGH (SImode, src));
13896    emit_set_insn (dest, gen_rtx_LO_SUM (SImode, dest, src));
13897  }
13898
13899 /* Output a move from arm registers to an fpa registers.
13900    OPERANDS[0] is an fpa register.
13901    OPERANDS[1] is the first registers of an arm register pair.  */
13902 const char *
13903 output_mov_double_fpa_from_arm (rtx *operands)
13904 {
13905   int arm_reg0 = REGNO (operands[1]);
13906   rtx ops[2];
13907
13908   gcc_assert (arm_reg0 != IP_REGNUM);
13909
13910   ops[0] = gen_rtx_REG (SImode, arm_reg0);
13911   ops[1] = gen_rtx_REG (SImode, 1 + arm_reg0);
13912   output_asm_insn ("stm%(fd%)\t%|sp!, {%0, %1}", ops);
13913   output_asm_insn ("ldf%?d\t%0, [%|sp], #8", operands);
13914   return "";
13915 }
13916
13917 /* Output a move from an fpa register to arm registers.
13918    OPERANDS[0] is the first registers of an arm register pair.
13919    OPERANDS[1] is an fpa register.  */
13920 const char *
13921 output_mov_double_arm_from_fpa (rtx *operands)
13922 {
13923   int arm_reg0 = REGNO (operands[0]);
13924   rtx ops[2];
13925
13926   gcc_assert (arm_reg0 != IP_REGNUM);
13927
13928   ops[0] = gen_rtx_REG (SImode, arm_reg0);
13929   ops[1] = gen_rtx_REG (SImode, 1 + arm_reg0);
13930   output_asm_insn ("stf%?d\t%1, [%|sp, #-8]!", operands);
13931   output_asm_insn ("ldm%(fd%)\t%|sp!, {%0, %1}", ops);
13932   return "";
13933 }
13934
13935 /* Output a move between double words.  It must be REG<-MEM
13936    or MEM<-REG.  */
13937 const char *
13938 output_move_double (rtx *operands, bool emit, int *count)
13939 {
13940   enum rtx_code code0 = GET_CODE (operands[0]);
13941   enum rtx_code code1 = GET_CODE (operands[1]);
13942   rtx otherops[3];
13943   if (count)
13944     *count = 1;
13945
13946   /* The only case when this might happen is when
13947      you are looking at the length of a DImode instruction
13948      that has an invalid constant in it.  */
13949   if (code0 == REG && code1 != MEM)
13950     {
13951       gcc_assert (!emit);
13952       *count = 2;
13953       return "";
13954     }
13955
13956   if (code0 == REG)
13957     {
13958       unsigned int reg0 = REGNO (operands[0]);
13959
13960       otherops[0] = gen_rtx_REG (SImode, 1 + reg0);
13961
13962       gcc_assert (code1 == MEM);  /* Constraints should ensure this.  */
13963
13964       switch (GET_CODE (XEXP (operands[1], 0)))
13965         {
13966         case REG:
13967
13968           if (emit)
13969             {
13970               if (TARGET_LDRD
13971                   && !(fix_cm3_ldrd && reg0 == REGNO(XEXP (operands[1], 0))))
13972                 output_asm_insn ("ldr%(d%)\t%0, [%m1]", operands);
13973               else
13974                 output_asm_insn ("ldm%(ia%)\t%m1, %M0", operands);
13975             }
13976           break;
13977
13978         case PRE_INC:
13979           gcc_assert (TARGET_LDRD);
13980           if (emit)
13981             output_asm_insn ("ldr%(d%)\t%0, [%m1, #8]!", operands);
13982           break;
13983
13984         case PRE_DEC:
13985           if (emit)
13986             {
13987               if (TARGET_LDRD)
13988                 output_asm_insn ("ldr%(d%)\t%0, [%m1, #-8]!", operands);
13989               else
13990                 output_asm_insn ("ldm%(db%)\t%m1!, %M0", operands);
13991             }
13992           break;
13993
13994         case POST_INC:
13995           if (emit)
13996             {
13997               if (TARGET_LDRD)
13998                 output_asm_insn ("ldr%(d%)\t%0, [%m1], #8", operands);
13999               else
14000                 output_asm_insn ("ldm%(ia%)\t%m1!, %M0", operands);
14001             }
14002           break;
14003
14004         case POST_DEC:
14005           gcc_assert (TARGET_LDRD);
14006           if (emit)
14007             output_asm_insn ("ldr%(d%)\t%0, [%m1], #-8", operands);
14008           break;
14009
14010         case PRE_MODIFY:
14011         case POST_MODIFY:
14012           /* Autoicrement addressing modes should never have overlapping
14013              base and destination registers, and overlapping index registers
14014              are already prohibited, so this doesn't need to worry about
14015              fix_cm3_ldrd.  */
14016           otherops[0] = operands[0];
14017           otherops[1] = XEXP (XEXP (XEXP (operands[1], 0), 1), 0);
14018           otherops[2] = XEXP (XEXP (XEXP (operands[1], 0), 1), 1);
14019
14020           if (GET_CODE (XEXP (operands[1], 0)) == PRE_MODIFY)
14021             {
14022               if (reg_overlap_mentioned_p (otherops[0], otherops[2]))
14023                 {
14024                   /* Registers overlap so split out the increment.  */
14025                   if (emit)
14026                     {
14027                       output_asm_insn ("add%?\t%1, %1, %2", otherops);
14028                       output_asm_insn ("ldr%(d%)\t%0, [%1] @split", otherops);
14029                     }
14030                   if (count)
14031                     *count = 2;
14032                 }
14033               else
14034                 {
14035                   /* Use a single insn if we can.
14036                      FIXME: IWMMXT allows offsets larger than ldrd can
14037                      handle, fix these up with a pair of ldr.  */
14038                   if (TARGET_THUMB2
14039                       || GET_CODE (otherops[2]) != CONST_INT
14040                       || (INTVAL (otherops[2]) > -256
14041                           && INTVAL (otherops[2]) < 256))
14042                     {
14043                       if (emit)
14044                         output_asm_insn ("ldr%(d%)\t%0, [%1, %2]!", otherops);
14045                     }
14046                   else
14047                     {
14048                       if (emit)
14049                         {
14050                           output_asm_insn ("ldr%?\t%0, [%1, %2]!", otherops);
14051                           output_asm_insn ("ldr%?\t%H0, [%1, #4]", otherops);
14052                         }
14053                       if (count)
14054                         *count = 2;
14055
14056                     }
14057                 }
14058             }
14059           else
14060             {
14061               /* Use a single insn if we can.
14062                  FIXME: IWMMXT allows offsets larger than ldrd can handle,
14063                  fix these up with a pair of ldr.  */
14064               if (TARGET_THUMB2
14065                   || GET_CODE (otherops[2]) != CONST_INT
14066                   || (INTVAL (otherops[2]) > -256
14067                       && INTVAL (otherops[2]) < 256))
14068                 {
14069                   if (emit)
14070                     output_asm_insn ("ldr%(d%)\t%0, [%1], %2", otherops);
14071                 }
14072               else
14073                 {
14074                   if (emit)
14075                     {
14076                       output_asm_insn ("ldr%?\t%H0, [%1, #4]", otherops);
14077                       output_asm_insn ("ldr%?\t%0, [%1], %2", otherops);
14078                     }
14079                   if (count)
14080                     *count = 2;
14081                 }
14082             }
14083           break;
14084
14085         case LABEL_REF:
14086         case CONST:
14087           /* We might be able to use ldrd %0, %1 here.  However the range is
14088              different to ldr/adr, and it is broken on some ARMv7-M
14089              implementations.  */
14090           /* Use the second register of the pair to avoid problematic
14091              overlap.  */
14092           otherops[1] = operands[1];
14093           if (emit)
14094             output_asm_insn ("adr%?\t%0, %1", otherops);
14095           operands[1] = otherops[0];
14096           if (emit)
14097             {
14098               if (TARGET_LDRD)
14099                 output_asm_insn ("ldr%(d%)\t%0, [%1]", operands);
14100               else
14101                 output_asm_insn ("ldm%(ia%)\t%1, %M0", operands);
14102             }
14103
14104           if (count)
14105             *count = 2;
14106           break;
14107
14108           /* ??? This needs checking for thumb2.  */
14109         default:
14110           if (arm_add_operand (XEXP (XEXP (operands[1], 0), 1),
14111                                GET_MODE (XEXP (XEXP (operands[1], 0), 1))))
14112             {
14113               otherops[0] = operands[0];
14114               otherops[1] = XEXP (XEXP (operands[1], 0), 0);
14115               otherops[2] = XEXP (XEXP (operands[1], 0), 1);
14116
14117               if (GET_CODE (XEXP (operands[1], 0)) == PLUS)
14118                 {
14119                   if (GET_CODE (otherops[2]) == CONST_INT && !TARGET_LDRD)
14120                     {
14121                       switch ((int) INTVAL (otherops[2]))
14122                         {
14123                         case -8:
14124                           if (emit)
14125                             output_asm_insn ("ldm%(db%)\t%1, %M0", otherops);
14126                           return "";
14127                         case -4:
14128                           if (TARGET_THUMB2)
14129                             break;
14130                           if (emit)
14131                             output_asm_insn ("ldm%(da%)\t%1, %M0", otherops);
14132                           return "";
14133                         case 4:
14134                           if (TARGET_THUMB2)
14135                             break;
14136                           if (emit)
14137                             output_asm_insn ("ldm%(ib%)\t%1, %M0", otherops);
14138                           return "";
14139                         }
14140                     }
14141                   otherops[0] = gen_rtx_REG(SImode, REGNO(operands[0]) + 1);
14142                   operands[1] = otherops[0];
14143                   if (TARGET_LDRD
14144                       && (GET_CODE (otherops[2]) == REG
14145                           || TARGET_THUMB2
14146                           || (GET_CODE (otherops[2]) == CONST_INT
14147                               && INTVAL (otherops[2]) > -256
14148                               && INTVAL (otherops[2]) < 256)))
14149                     {
14150                       if (reg_overlap_mentioned_p (operands[0],
14151                                                    otherops[2]))
14152                         {
14153                           rtx tmp;
14154                           /* Swap base and index registers over to
14155                              avoid a conflict.  */
14156                           tmp = otherops[1];
14157                           otherops[1] = otherops[2];
14158                           otherops[2] = tmp;
14159                         }
14160                       /* If both registers conflict, it will usually
14161                          have been fixed by a splitter.  */
14162                       if (reg_overlap_mentioned_p (operands[0], otherops[2])
14163                           || (fix_cm3_ldrd && reg0 == REGNO (otherops[1])))
14164                         {
14165                           if (emit)
14166                             {
14167                               output_asm_insn ("add%?\t%0, %1, %2", otherops);
14168                               output_asm_insn ("ldr%(d%)\t%0, [%1]", operands);
14169                             }
14170                           if (count)
14171                             *count = 2;
14172                         }
14173                       else
14174                         {
14175                           otherops[0] = operands[0];
14176                           if (emit)
14177                             output_asm_insn ("ldr%(d%)\t%0, [%1, %2]", otherops);
14178                         }
14179                       return "";
14180                     }
14181
14182                   if (GET_CODE (otherops[2]) == CONST_INT)
14183                     {
14184                       if (emit)
14185                         {
14186                           if (!(const_ok_for_arm (INTVAL (otherops[2]))))
14187                             output_asm_insn ("sub%?\t%0, %1, #%n2", otherops);
14188                           else
14189                             output_asm_insn ("add%?\t%0, %1, %2", otherops);
14190                         }
14191                     }
14192                   else
14193                     {
14194                       if (emit)
14195                         output_asm_insn ("add%?\t%0, %1, %2", otherops);
14196                     }
14197                 }
14198               else
14199                 {
14200                   if (emit)
14201                     output_asm_insn ("sub%?\t%0, %1, %2", otherops);
14202                 }
14203
14204               if (TARGET_LDRD)
14205                 return "ldr%(d%)\t%0, [%1]";
14206
14207               return "ldm%(ia%)\t%1, %M0";
14208             }
14209           else
14210             {
14211               otherops[1] = adjust_address (operands[1], SImode, 4);
14212               /* Take care of overlapping base/data reg.  */
14213               if (reg_mentioned_p (operands[0], operands[1]))
14214                 {
14215                   if (emit)
14216                     {
14217                       output_asm_insn ("ldr%?\t%0, %1", otherops);
14218                       output_asm_insn ("ldr%?\t%0, %1", operands);
14219                     }
14220                   if (count)
14221                     *count = 2;
14222
14223                 }
14224               else
14225                 {
14226                   if (emit)
14227                     {
14228                       output_asm_insn ("ldr%?\t%0, %1", operands);
14229                       output_asm_insn ("ldr%?\t%0, %1", otherops);
14230                     }
14231                   if (count)
14232                     *count = 2;
14233                 }
14234             }
14235         }
14236     }
14237   else
14238     {
14239       /* Constraints should ensure this.  */
14240       gcc_assert (code0 == MEM && code1 == REG);
14241       gcc_assert (REGNO (operands[1]) != IP_REGNUM);
14242
14243       switch (GET_CODE (XEXP (operands[0], 0)))
14244         {
14245         case REG:
14246           if (emit)
14247             {
14248               if (TARGET_LDRD)
14249                 output_asm_insn ("str%(d%)\t%1, [%m0]", operands);
14250               else
14251                 output_asm_insn ("stm%(ia%)\t%m0, %M1", operands);
14252             }
14253           break;
14254
14255         case PRE_INC:
14256           gcc_assert (TARGET_LDRD);
14257           if (emit)
14258             output_asm_insn ("str%(d%)\t%1, [%m0, #8]!", operands);
14259           break;
14260
14261         case PRE_DEC:
14262           if (emit)
14263             {
14264               if (TARGET_LDRD)
14265                 output_asm_insn ("str%(d%)\t%1, [%m0, #-8]!", operands);
14266               else
14267                 output_asm_insn ("stm%(db%)\t%m0!, %M1", operands);
14268             }
14269           break;
14270
14271         case POST_INC:
14272           if (emit)
14273             {
14274               if (TARGET_LDRD)
14275                 output_asm_insn ("str%(d%)\t%1, [%m0], #8", operands);
14276               else
14277                 output_asm_insn ("stm%(ia%)\t%m0!, %M1", operands);
14278             }
14279           break;
14280
14281         case POST_DEC:
14282           gcc_assert (TARGET_LDRD);
14283           if (emit)
14284             output_asm_insn ("str%(d%)\t%1, [%m0], #-8", operands);
14285           break;
14286
14287         case PRE_MODIFY:
14288         case POST_MODIFY:
14289           otherops[0] = operands[1];
14290           otherops[1] = XEXP (XEXP (XEXP (operands[0], 0), 1), 0);
14291           otherops[2] = XEXP (XEXP (XEXP (operands[0], 0), 1), 1);
14292
14293           /* IWMMXT allows offsets larger than ldrd can handle,
14294              fix these up with a pair of ldr.  */
14295           if (!TARGET_THUMB2
14296               && GET_CODE (otherops[2]) == CONST_INT
14297               && (INTVAL(otherops[2]) <= -256
14298                   || INTVAL(otherops[2]) >= 256))
14299             {
14300               if (GET_CODE (XEXP (operands[0], 0)) == PRE_MODIFY)
14301                 {
14302                   if (emit)
14303                     {
14304                       output_asm_insn ("str%?\t%0, [%1, %2]!", otherops);
14305                       output_asm_insn ("str%?\t%H0, [%1, #4]", otherops);
14306                     }
14307                   if (count)
14308                     *count = 2;
14309                 }
14310               else
14311                 {
14312                   if (emit)
14313                     {
14314                       output_asm_insn ("str%?\t%H0, [%1, #4]", otherops);
14315                       output_asm_insn ("str%?\t%0, [%1], %2", otherops);
14316                     }
14317                   if (count)
14318                     *count = 2;
14319                 }
14320             }
14321           else if (GET_CODE (XEXP (operands[0], 0)) == PRE_MODIFY)
14322             {
14323               if (emit)
14324                 output_asm_insn ("str%(d%)\t%0, [%1, %2]!", otherops);
14325             }
14326           else
14327             {
14328               if (emit)
14329                 output_asm_insn ("str%(d%)\t%0, [%1], %2", otherops);
14330             }
14331           break;
14332
14333         case PLUS:
14334           otherops[2] = XEXP (XEXP (operands[0], 0), 1);
14335           if (GET_CODE (otherops[2]) == CONST_INT && !TARGET_LDRD)
14336             {
14337               switch ((int) INTVAL (XEXP (XEXP (operands[0], 0), 1)))
14338                 {
14339                 case -8:
14340                   if (emit)
14341                     output_asm_insn ("stm%(db%)\t%m0, %M1", operands);
14342                   return "";
14343
14344                 case -4:
14345                   if (TARGET_THUMB2)
14346                     break;
14347                   if (emit)
14348                     output_asm_insn ("stm%(da%)\t%m0, %M1", operands);
14349                   return "";
14350
14351                 case 4:
14352                   if (TARGET_THUMB2)
14353                     break;
14354                   if (emit)
14355                     output_asm_insn ("stm%(ib%)\t%m0, %M1", operands);
14356                   return "";
14357                 }
14358             }
14359           if (TARGET_LDRD
14360               && (GET_CODE (otherops[2]) == REG
14361                   || TARGET_THUMB2
14362                   || (GET_CODE (otherops[2]) == CONST_INT
14363                       && INTVAL (otherops[2]) > -256
14364                       && INTVAL (otherops[2]) < 256)))
14365             {
14366               otherops[0] = operands[1];
14367               otherops[1] = XEXP (XEXP (operands[0], 0), 0);
14368               if (emit)
14369                 output_asm_insn ("str%(d%)\t%0, [%1, %2]", otherops);
14370               return "";
14371             }
14372           /* Fall through */
14373
14374         default:
14375           otherops[0] = adjust_address (operands[0], SImode, 4);
14376           otherops[1] = operands[1];
14377           if (emit)
14378             {
14379               output_asm_insn ("str%?\t%1, %0", operands);
14380               output_asm_insn ("str%?\t%H1, %0", otherops);
14381             }
14382           if (count)
14383             *count = 2;
14384         }
14385     }
14386
14387   return "";
14388 }
14389
14390 /* Output a move, load or store for quad-word vectors in ARM registers.  Only
14391    handles MEMs accepted by neon_vector_mem_operand with TYPE=1.  */
14392
14393 const char *
14394 output_move_quad (rtx *operands)
14395 {
14396   if (REG_P (operands[0]))
14397     {
14398       /* Load, or reg->reg move.  */
14399
14400       if (MEM_P (operands[1]))
14401         {
14402           switch (GET_CODE (XEXP (operands[1], 0)))
14403             {
14404             case REG:
14405               output_asm_insn ("ldm%(ia%)\t%m1, %M0", operands);
14406               break;
14407
14408             case LABEL_REF:
14409             case CONST:
14410               output_asm_insn ("adr%?\t%0, %1", operands);
14411               output_asm_insn ("ldm%(ia%)\t%0, %M0", operands);
14412               break;
14413
14414             default:
14415               gcc_unreachable ();
14416             }
14417         }
14418       else
14419         {
14420           rtx ops[2];
14421           int dest, src, i;
14422
14423           gcc_assert (REG_P (operands[1]));
14424
14425           dest = REGNO (operands[0]);
14426           src = REGNO (operands[1]);
14427
14428           /* This seems pretty dumb, but hopefully GCC won't try to do it
14429              very often.  */
14430           if (dest < src)
14431             for (i = 0; i < 4; i++)
14432               {
14433                 ops[0] = gen_rtx_REG (SImode, dest + i);
14434                 ops[1] = gen_rtx_REG (SImode, src + i);
14435                 output_asm_insn ("mov%?\t%0, %1", ops);
14436               }
14437           else
14438             for (i = 3; i >= 0; i--)
14439               {
14440                 ops[0] = gen_rtx_REG (SImode, dest + i);
14441                 ops[1] = gen_rtx_REG (SImode, src + i);
14442                 output_asm_insn ("mov%?\t%0, %1", ops);
14443               }
14444         }
14445     }
14446   else
14447     {
14448       gcc_assert (MEM_P (operands[0]));
14449       gcc_assert (REG_P (operands[1]));
14450       gcc_assert (!reg_overlap_mentioned_p (operands[1], operands[0]));
14451
14452       switch (GET_CODE (XEXP (operands[0], 0)))
14453         {
14454         case REG:
14455           output_asm_insn ("stm%(ia%)\t%m0, %M1", operands);
14456           break;
14457
14458         default:
14459           gcc_unreachable ();
14460         }
14461     }
14462
14463   return "";
14464 }
14465
14466 /* Output a VFP load or store instruction.  */
14467
14468 const char *
14469 output_move_vfp (rtx *operands)
14470 {
14471   rtx reg, mem, addr, ops[2];
14472   int load = REG_P (operands[0]);
14473   int dp = GET_MODE_SIZE (GET_MODE (operands[0])) == 8;
14474   int integer_p = GET_MODE_CLASS (GET_MODE (operands[0])) == MODE_INT;
14475   const char *templ;
14476   char buff[50];
14477   enum machine_mode mode;
14478
14479   reg = operands[!load];
14480   mem = operands[load];
14481
14482   mode = GET_MODE (reg);
14483
14484   gcc_assert (REG_P (reg));
14485   gcc_assert (IS_VFP_REGNUM (REGNO (reg)));
14486   gcc_assert (mode == SFmode
14487               || mode == DFmode
14488               || mode == SImode
14489               || mode == DImode
14490               || (TARGET_NEON && VALID_NEON_DREG_MODE (mode)));
14491   gcc_assert (MEM_P (mem));
14492
14493   addr = XEXP (mem, 0);
14494
14495   switch (GET_CODE (addr))
14496     {
14497     case PRE_DEC:
14498       templ = "f%smdb%c%%?\t%%0!, {%%%s1}%s";
14499       ops[0] = XEXP (addr, 0);
14500       ops[1] = reg;
14501       break;
14502
14503     case POST_INC:
14504       templ = "f%smia%c%%?\t%%0!, {%%%s1}%s";
14505       ops[0] = XEXP (addr, 0);
14506       ops[1] = reg;
14507       break;
14508
14509     default:
14510       templ = "f%s%c%%?\t%%%s0, %%1%s";
14511       ops[0] = reg;
14512       ops[1] = mem;
14513       break;
14514     }
14515
14516   sprintf (buff, templ,
14517            load ? "ld" : "st",
14518            dp ? 'd' : 's',
14519            dp ? "P" : "",
14520            integer_p ? "\t%@ int" : "");
14521   output_asm_insn (buff, ops);
14522
14523   return "";
14524 }
14525
14526 /* Output a Neon quad-word load or store, or a load or store for
14527    larger structure modes.
14528
14529    WARNING: The ordering of elements is weird in big-endian mode,
14530    because we use VSTM, as required by the EABI.  GCC RTL defines
14531    element ordering based on in-memory order.  This can be differ
14532    from the architectural ordering of elements within a NEON register.
14533    The intrinsics defined in arm_neon.h use the NEON register element
14534    ordering, not the GCC RTL element ordering.
14535
14536    For example, the in-memory ordering of a big-endian a quadword
14537    vector with 16-bit elements when stored from register pair {d0,d1}
14538    will be (lowest address first, d0[N] is NEON register element N):
14539
14540      [d0[3], d0[2], d0[1], d0[0], d1[7], d1[6], d1[5], d1[4]]
14541
14542    When necessary, quadword registers (dN, dN+1) are moved to ARM
14543    registers from rN in the order:
14544
14545      dN -> (rN+1, rN), dN+1 -> (rN+3, rN+2)
14546
14547    So that STM/LDM can be used on vectors in ARM registers, and the
14548    same memory layout will result as if VSTM/VLDM were used.  */
14549
14550 const char *
14551 output_move_neon (rtx *operands)
14552 {
14553   rtx reg, mem, addr, ops[2];
14554   int regno, load = REG_P (operands[0]);
14555   const char *templ;
14556   char buff[50];
14557   enum machine_mode mode;
14558
14559   reg = operands[!load];
14560   mem = operands[load];
14561
14562   mode = GET_MODE (reg);
14563
14564   gcc_assert (REG_P (reg));
14565   regno = REGNO (reg);
14566   gcc_assert (VFP_REGNO_OK_FOR_DOUBLE (regno)
14567               || NEON_REGNO_OK_FOR_QUAD (regno));
14568   gcc_assert (VALID_NEON_DREG_MODE (mode)
14569               || VALID_NEON_QREG_MODE (mode)
14570               || VALID_NEON_STRUCT_MODE (mode));
14571   gcc_assert (MEM_P (mem));
14572
14573   addr = XEXP (mem, 0);
14574
14575   /* Strip off const from addresses like (const (plus (...))).  */
14576   if (GET_CODE (addr) == CONST && GET_CODE (XEXP (addr, 0)) == PLUS)
14577     addr = XEXP (addr, 0);
14578
14579   switch (GET_CODE (addr))
14580     {
14581     case POST_INC:
14582       templ = "v%smia%%?\t%%0!, %%h1";
14583       ops[0] = XEXP (addr, 0);
14584       ops[1] = reg;
14585       break;
14586
14587     case PRE_DEC:
14588       /* FIXME: We should be using vld1/vst1 here in BE mode?  */
14589       templ = "v%smdb%%?\t%%0!, %%h1";
14590       ops[0] = XEXP (addr, 0);
14591       ops[1] = reg;
14592       break;
14593
14594     case POST_MODIFY:
14595       /* FIXME: Not currently enabled in neon_vector_mem_operand.  */
14596       gcc_unreachable ();
14597
14598     case LABEL_REF:
14599     case PLUS:
14600       {
14601         int nregs = HARD_REGNO_NREGS (REGNO (reg), mode) / 2;
14602         int i;
14603         int overlap = -1;
14604         for (i = 0; i < nregs; i++)
14605           {
14606             /* We're only using DImode here because it's a convenient size.  */
14607             ops[0] = gen_rtx_REG (DImode, REGNO (reg) + 2 * i);
14608             ops[1] = adjust_address (mem, DImode, 8 * i);
14609             if (reg_overlap_mentioned_p (ops[0], mem))
14610               {
14611                 gcc_assert (overlap == -1);
14612                 overlap = i;
14613               }
14614             else
14615               {
14616                 sprintf (buff, "v%sr%%?\t%%P0, %%1", load ? "ld" : "st");
14617                 output_asm_insn (buff, ops);
14618               }
14619           }
14620         if (overlap != -1)
14621           {
14622             ops[0] = gen_rtx_REG (DImode, REGNO (reg) + 2 * overlap);
14623             ops[1] = adjust_address (mem, SImode, 8 * overlap);
14624             sprintf (buff, "v%sr%%?\t%%P0, %%1", load ? "ld" : "st");
14625             output_asm_insn (buff, ops);
14626           }
14627
14628         return "";
14629       }
14630
14631     default:
14632       templ = "v%smia%%?\t%%m0, %%h1";
14633       ops[0] = mem;
14634       ops[1] = reg;
14635     }
14636
14637   sprintf (buff, templ, load ? "ld" : "st");
14638   output_asm_insn (buff, ops);
14639
14640   return "";
14641 }
14642
14643 /* Compute and return the length of neon_mov<mode>, where <mode> is
14644    one of VSTRUCT modes: EI, OI, CI or XI.  */
14645 int
14646 arm_attr_length_move_neon (rtx insn)
14647 {
14648   rtx reg, mem, addr;
14649   int load;
14650   enum machine_mode mode;
14651
14652   extract_insn_cached (insn);
14653
14654   if (REG_P (recog_data.operand[0]) && REG_P (recog_data.operand[1]))
14655     {
14656       mode = GET_MODE (recog_data.operand[0]);
14657       switch (mode)
14658         {
14659         case EImode:
14660         case OImode:
14661           return 8;
14662         case CImode:
14663           return 12;
14664         case XImode:
14665           return 16;
14666         default:
14667           gcc_unreachable ();
14668         }
14669     }
14670
14671   load = REG_P (recog_data.operand[0]);
14672   reg = recog_data.operand[!load];
14673   mem = recog_data.operand[load];
14674
14675   gcc_assert (MEM_P (mem));
14676
14677   mode = GET_MODE (reg);
14678   addr = XEXP (mem, 0);
14679
14680   /* Strip off const from addresses like (const (plus (...))).  */
14681   if (GET_CODE (addr) == CONST && GET_CODE (XEXP (addr, 0)) == PLUS)
14682     addr = XEXP (addr, 0);
14683
14684   if (GET_CODE (addr) == LABEL_REF || GET_CODE (addr) == PLUS)
14685     {
14686       int insns = HARD_REGNO_NREGS (REGNO (reg), mode) / 2;
14687       return insns * 4;
14688     }
14689   else
14690     return 4;
14691 }
14692
14693 /* Return nonzero if the offset in the address is an immediate.  Otherwise,
14694    return zero.  */
14695
14696 int
14697 arm_address_offset_is_imm (rtx insn)
14698 {
14699   rtx mem, addr;
14700
14701   extract_insn_cached (insn);
14702
14703   if (REG_P (recog_data.operand[0]))
14704     return 0;
14705
14706   mem = recog_data.operand[0];
14707
14708   gcc_assert (MEM_P (mem));
14709
14710   addr = XEXP (mem, 0);
14711
14712   if (GET_CODE (addr) == REG
14713       || (GET_CODE (addr) == PLUS
14714           && GET_CODE (XEXP (addr, 0)) == REG
14715           && GET_CODE (XEXP (addr, 1)) == CONST_INT))
14716     return 1;
14717   else
14718     return 0;
14719 }
14720
14721 /* Output an ADD r, s, #n where n may be too big for one instruction.
14722    If adding zero to one register, output nothing.  */
14723 const char *
14724 output_add_immediate (rtx *operands)
14725 {
14726   HOST_WIDE_INT n = INTVAL (operands[2]);
14727
14728   if (n != 0 || REGNO (operands[0]) != REGNO (operands[1]))
14729     {
14730       if (n < 0)
14731         output_multi_immediate (operands,
14732                                 "sub%?\t%0, %1, %2", "sub%?\t%0, %0, %2", 2,
14733                                 -n);
14734       else
14735         output_multi_immediate (operands,
14736                                 "add%?\t%0, %1, %2", "add%?\t%0, %0, %2", 2,
14737                                 n);
14738     }
14739
14740   return "";
14741 }
14742
14743 /* Output a multiple immediate operation.
14744    OPERANDS is the vector of operands referred to in the output patterns.
14745    INSTR1 is the output pattern to use for the first constant.
14746    INSTR2 is the output pattern to use for subsequent constants.
14747    IMMED_OP is the index of the constant slot in OPERANDS.
14748    N is the constant value.  */
14749 static const char *
14750 output_multi_immediate (rtx *operands, const char *instr1, const char *instr2,
14751                         int immed_op, HOST_WIDE_INT n)
14752 {
14753 #if HOST_BITS_PER_WIDE_INT > 32
14754   n &= 0xffffffff;
14755 #endif
14756
14757   if (n == 0)
14758     {
14759       /* Quick and easy output.  */
14760       operands[immed_op] = const0_rtx;
14761       output_asm_insn (instr1, operands);
14762     }
14763   else
14764     {
14765       int i;
14766       const char * instr = instr1;
14767
14768       /* Note that n is never zero here (which would give no output).  */
14769       for (i = 0; i < 32; i += 2)
14770         {
14771           if (n & (3 << i))
14772             {
14773               operands[immed_op] = GEN_INT (n & (255 << i));
14774               output_asm_insn (instr, operands);
14775               instr = instr2;
14776               i += 6;
14777             }
14778         }
14779     }
14780
14781   return "";
14782 }
14783
14784 /* Return the name of a shifter operation.  */
14785 static const char *
14786 arm_shift_nmem(enum rtx_code code)
14787 {
14788   switch (code)
14789     {
14790     case ASHIFT:
14791       return ARM_LSL_NAME;
14792
14793     case ASHIFTRT:
14794       return "asr";
14795
14796     case LSHIFTRT:
14797       return "lsr";
14798
14799     case ROTATERT:
14800       return "ror";
14801
14802     default:
14803       abort();
14804     }
14805 }
14806
14807 /* Return the appropriate ARM instruction for the operation code.
14808    The returned result should not be overwritten.  OP is the rtx of the
14809    operation.  SHIFT_FIRST_ARG is TRUE if the first argument of the operator
14810    was shifted.  */
14811 const char *
14812 arithmetic_instr (rtx op, int shift_first_arg)
14813 {
14814   switch (GET_CODE (op))
14815     {
14816     case PLUS:
14817       return "add";
14818
14819     case MINUS:
14820       return shift_first_arg ? "rsb" : "sub";
14821
14822     case IOR:
14823       return "orr";
14824
14825     case XOR:
14826       return "eor";
14827
14828     case AND:
14829       return "and";
14830
14831     case ASHIFT:
14832     case ASHIFTRT:
14833     case LSHIFTRT:
14834     case ROTATERT:
14835       return arm_shift_nmem(GET_CODE(op));
14836
14837     default:
14838       gcc_unreachable ();
14839     }
14840 }
14841
14842 /* Ensure valid constant shifts and return the appropriate shift mnemonic
14843    for the operation code.  The returned result should not be overwritten.
14844    OP is the rtx code of the shift.
14845    On exit, *AMOUNTP will be -1 if the shift is by a register, or a constant
14846    shift.  */
14847 static const char *
14848 shift_op (rtx op, HOST_WIDE_INT *amountp)
14849 {
14850   const char * mnem;
14851   enum rtx_code code = GET_CODE (op);
14852
14853   switch (GET_CODE (XEXP (op, 1)))
14854     {
14855     case REG:
14856     case SUBREG:
14857       *amountp = -1;
14858       break;
14859
14860     case CONST_INT:
14861       *amountp = INTVAL (XEXP (op, 1));
14862       break;
14863
14864     default:
14865       gcc_unreachable ();
14866     }
14867
14868   switch (code)
14869     {
14870     case ROTATE:
14871       gcc_assert (*amountp != -1);
14872       *amountp = 32 - *amountp;
14873       code = ROTATERT;
14874
14875       /* Fall through.  */
14876
14877     case ASHIFT:
14878     case ASHIFTRT:
14879     case LSHIFTRT:
14880     case ROTATERT:
14881       mnem = arm_shift_nmem(code);
14882       break;
14883
14884     case MULT:
14885       /* We never have to worry about the amount being other than a
14886          power of 2, since this case can never be reloaded from a reg.  */
14887       gcc_assert (*amountp != -1);
14888       *amountp = int_log2 (*amountp);
14889       return ARM_LSL_NAME;
14890
14891     default:
14892       gcc_unreachable ();
14893     }
14894
14895   if (*amountp != -1)
14896     {
14897       /* This is not 100% correct, but follows from the desire to merge
14898          multiplication by a power of 2 with the recognizer for a
14899          shift.  >=32 is not a valid shift for "lsl", so we must try and
14900          output a shift that produces the correct arithmetical result.
14901          Using lsr #32 is identical except for the fact that the carry bit
14902          is not set correctly if we set the flags; but we never use the
14903          carry bit from such an operation, so we can ignore that.  */
14904       if (code == ROTATERT)
14905         /* Rotate is just modulo 32.  */
14906         *amountp &= 31;
14907       else if (*amountp != (*amountp & 31))
14908         {
14909           if (code == ASHIFT)
14910             mnem = "lsr";
14911           *amountp = 32;
14912         }
14913
14914       /* Shifts of 0 are no-ops.  */
14915       if (*amountp == 0)
14916         return NULL;
14917     }
14918
14919   return mnem;
14920 }
14921
14922 /* Obtain the shift from the POWER of two.  */
14923
14924 static HOST_WIDE_INT
14925 int_log2 (HOST_WIDE_INT power)
14926 {
14927   HOST_WIDE_INT shift = 0;
14928
14929   while ((((HOST_WIDE_INT) 1 << shift) & power) == 0)
14930     {
14931       gcc_assert (shift <= 31);
14932       shift++;
14933     }
14934
14935   return shift;
14936 }
14937
14938 /* Output a .ascii pseudo-op, keeping track of lengths.  This is
14939    because /bin/as is horribly restrictive.  The judgement about
14940    whether or not each character is 'printable' (and can be output as
14941    is) or not (and must be printed with an octal escape) must be made
14942    with reference to the *host* character set -- the situation is
14943    similar to that discussed in the comments above pp_c_char in
14944    c-pretty-print.c.  */
14945
14946 #define MAX_ASCII_LEN 51
14947
14948 void
14949 output_ascii_pseudo_op (FILE *stream, const unsigned char *p, int len)
14950 {
14951   int i;
14952   int len_so_far = 0;
14953
14954   fputs ("\t.ascii\t\"", stream);
14955
14956   for (i = 0; i < len; i++)
14957     {
14958       int c = p[i];
14959
14960       if (len_so_far >= MAX_ASCII_LEN)
14961         {
14962           fputs ("\"\n\t.ascii\t\"", stream);
14963           len_so_far = 0;
14964         }
14965
14966       if (ISPRINT (c))
14967         {
14968           if (c == '\\' || c == '\"')
14969             {
14970               putc ('\\', stream);
14971               len_so_far++;
14972             }
14973           putc (c, stream);
14974           len_so_far++;
14975         }
14976       else
14977         {
14978           fprintf (stream, "\\%03o", c);
14979           len_so_far += 4;
14980         }
14981     }
14982
14983   fputs ("\"\n", stream);
14984 }
14985 \f
14986 /* Compute the register save mask for registers 0 through 12
14987    inclusive.  This code is used by arm_compute_save_reg_mask.  */
14988
14989 static unsigned long
14990 arm_compute_save_reg0_reg12_mask (void)
14991 {
14992   unsigned long func_type = arm_current_func_type ();
14993   unsigned long save_reg_mask = 0;
14994   unsigned int reg;
14995
14996   if (IS_INTERRUPT (func_type))
14997     {
14998       unsigned int max_reg;
14999       /* Interrupt functions must not corrupt any registers,
15000          even call clobbered ones.  If this is a leaf function
15001          we can just examine the registers used by the RTL, but
15002          otherwise we have to assume that whatever function is
15003          called might clobber anything, and so we have to save
15004          all the call-clobbered registers as well.  */
15005       if (ARM_FUNC_TYPE (func_type) == ARM_FT_FIQ)
15006         /* FIQ handlers have registers r8 - r12 banked, so
15007            we only need to check r0 - r7, Normal ISRs only
15008            bank r14 and r15, so we must check up to r12.
15009            r13 is the stack pointer which is always preserved,
15010            so we do not need to consider it here.  */
15011         max_reg = 7;
15012       else
15013         max_reg = 12;
15014
15015       for (reg = 0; reg <= max_reg; reg++)
15016         if (df_regs_ever_live_p (reg)
15017             || (! current_function_is_leaf && call_used_regs[reg]))
15018           save_reg_mask |= (1 << reg);
15019
15020       /* Also save the pic base register if necessary.  */
15021       if (flag_pic
15022           && !TARGET_SINGLE_PIC_BASE
15023           && arm_pic_register != INVALID_REGNUM
15024           && crtl->uses_pic_offset_table)
15025         save_reg_mask |= 1 << PIC_OFFSET_TABLE_REGNUM;
15026     }
15027   else if (IS_VOLATILE(func_type))
15028     {
15029       /* For noreturn functions we historically omitted register saves
15030          altogether.  However this really messes up debugging.  As a
15031          compromise save just the frame pointers.  Combined with the link
15032          register saved elsewhere this should be sufficient to get
15033          a backtrace.  */
15034       if (frame_pointer_needed)
15035         save_reg_mask |= 1 << HARD_FRAME_POINTER_REGNUM;
15036       if (df_regs_ever_live_p (ARM_HARD_FRAME_POINTER_REGNUM))
15037         save_reg_mask |= 1 << ARM_HARD_FRAME_POINTER_REGNUM;
15038       if (df_regs_ever_live_p (THUMB_HARD_FRAME_POINTER_REGNUM))
15039         save_reg_mask |= 1 << THUMB_HARD_FRAME_POINTER_REGNUM;
15040     }
15041   else
15042     {
15043       /* In the normal case we only need to save those registers
15044          which are call saved and which are used by this function.  */
15045       for (reg = 0; reg <= 11; reg++)
15046         if (df_regs_ever_live_p (reg) && ! call_used_regs[reg])
15047           save_reg_mask |= (1 << reg);
15048
15049       /* Handle the frame pointer as a special case.  */
15050       if (frame_pointer_needed)
15051         save_reg_mask |= 1 << HARD_FRAME_POINTER_REGNUM;
15052
15053       /* If we aren't loading the PIC register,
15054          don't stack it even though it may be live.  */
15055       if (flag_pic
15056           && !TARGET_SINGLE_PIC_BASE
15057           && arm_pic_register != INVALID_REGNUM
15058           && (df_regs_ever_live_p (PIC_OFFSET_TABLE_REGNUM)
15059               || crtl->uses_pic_offset_table))
15060         save_reg_mask |= 1 << PIC_OFFSET_TABLE_REGNUM;
15061
15062       /* The prologue will copy SP into R0, so save it.  */
15063       if (IS_STACKALIGN (func_type))
15064         save_reg_mask |= 1;
15065     }
15066
15067   /* Save registers so the exception handler can modify them.  */
15068   if (crtl->calls_eh_return)
15069     {
15070       unsigned int i;
15071
15072       for (i = 0; ; i++)
15073         {
15074           reg = EH_RETURN_DATA_REGNO (i);
15075           if (reg == INVALID_REGNUM)
15076             break;
15077           save_reg_mask |= 1 << reg;
15078         }
15079     }
15080
15081   return save_reg_mask;
15082 }
15083
15084
15085 /* Compute the number of bytes used to store the static chain register on the
15086    stack, above the stack frame. We need to know this accurately to get the
15087    alignment of the rest of the stack frame correct. */
15088
15089 static int arm_compute_static_chain_stack_bytes (void)
15090 {
15091   unsigned long func_type = arm_current_func_type ();
15092   int static_chain_stack_bytes = 0;
15093
15094   if (TARGET_APCS_FRAME && frame_pointer_needed && TARGET_ARM &&
15095       IS_NESTED (func_type) &&
15096       df_regs_ever_live_p (3) && crtl->args.pretend_args_size == 0)
15097     static_chain_stack_bytes = 4;
15098
15099   return static_chain_stack_bytes;
15100 }
15101
15102
15103 /* Compute a bit mask of which registers need to be
15104    saved on the stack for the current function.
15105    This is used by arm_get_frame_offsets, which may add extra registers.  */
15106
15107 static unsigned long
15108 arm_compute_save_reg_mask (void)
15109 {
15110   unsigned int save_reg_mask = 0;
15111   unsigned long func_type = arm_current_func_type ();
15112   unsigned int reg;
15113
15114   if (IS_NAKED (func_type))
15115     /* This should never really happen.  */
15116     return 0;
15117
15118   /* If we are creating a stack frame, then we must save the frame pointer,
15119      IP (which will hold the old stack pointer), LR and the PC.  */
15120   if (TARGET_APCS_FRAME && frame_pointer_needed && TARGET_ARM)
15121     save_reg_mask |=
15122       (1 << ARM_HARD_FRAME_POINTER_REGNUM)
15123       | (1 << IP_REGNUM)
15124       | (1 << LR_REGNUM)
15125       | (1 << PC_REGNUM);
15126
15127   save_reg_mask |= arm_compute_save_reg0_reg12_mask ();
15128
15129   /* Decide if we need to save the link register.
15130      Interrupt routines have their own banked link register,
15131      so they never need to save it.
15132      Otherwise if we do not use the link register we do not need to save
15133      it.  If we are pushing other registers onto the stack however, we
15134      can save an instruction in the epilogue by pushing the link register
15135      now and then popping it back into the PC.  This incurs extra memory
15136      accesses though, so we only do it when optimizing for size, and only
15137      if we know that we will not need a fancy return sequence.  */
15138   if (df_regs_ever_live_p (LR_REGNUM)
15139       || (save_reg_mask
15140           && optimize_size
15141           && ARM_FUNC_TYPE (func_type) == ARM_FT_NORMAL
15142           && !crtl->calls_eh_return))
15143     save_reg_mask |= 1 << LR_REGNUM;
15144
15145   if (cfun->machine->lr_save_eliminated)
15146     save_reg_mask &= ~ (1 << LR_REGNUM);
15147
15148   if (TARGET_REALLY_IWMMXT
15149       && ((bit_count (save_reg_mask)
15150            + ARM_NUM_INTS (crtl->args.pretend_args_size +
15151                            arm_compute_static_chain_stack_bytes())
15152            ) % 2) != 0)
15153     {
15154       /* The total number of registers that are going to be pushed
15155          onto the stack is odd.  We need to ensure that the stack
15156          is 64-bit aligned before we start to save iWMMXt registers,
15157          and also before we start to create locals.  (A local variable
15158          might be a double or long long which we will load/store using
15159          an iWMMXt instruction).  Therefore we need to push another
15160          ARM register, so that the stack will be 64-bit aligned.  We
15161          try to avoid using the arg registers (r0 -r3) as they might be
15162          used to pass values in a tail call.  */
15163       for (reg = 4; reg <= 12; reg++)
15164         if ((save_reg_mask & (1 << reg)) == 0)
15165           break;
15166
15167       if (reg <= 12)
15168         save_reg_mask |= (1 << reg);
15169       else
15170         {
15171           cfun->machine->sibcall_blocked = 1;
15172           save_reg_mask |= (1 << 3);
15173         }
15174     }
15175
15176   /* We may need to push an additional register for use initializing the
15177      PIC base register.  */
15178   if (TARGET_THUMB2 && IS_NESTED (func_type) && flag_pic
15179       && (save_reg_mask & THUMB2_WORK_REGS) == 0)
15180     {
15181       reg = thumb_find_work_register (1 << 4);
15182       if (!call_used_regs[reg])
15183         save_reg_mask |= (1 << reg);
15184     }
15185
15186   return save_reg_mask;
15187 }
15188
15189
15190 /* Compute a bit mask of which registers need to be
15191    saved on the stack for the current function.  */
15192 static unsigned long
15193 thumb1_compute_save_reg_mask (void)
15194 {
15195   unsigned long mask;
15196   unsigned reg;
15197
15198   mask = 0;
15199   for (reg = 0; reg < 12; reg ++)
15200     if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
15201       mask |= 1 << reg;
15202
15203   if (flag_pic
15204       && !TARGET_SINGLE_PIC_BASE
15205       && arm_pic_register != INVALID_REGNUM
15206       && crtl->uses_pic_offset_table)
15207     mask |= 1 << PIC_OFFSET_TABLE_REGNUM;
15208
15209   /* See if we might need r11 for calls to _interwork_r11_call_via_rN().  */
15210   if (!frame_pointer_needed && CALLER_INTERWORKING_SLOT_SIZE > 0)
15211     mask |= 1 << ARM_HARD_FRAME_POINTER_REGNUM;
15212
15213   /* LR will also be pushed if any lo regs are pushed.  */
15214   if (mask & 0xff || thumb_force_lr_save ())
15215     mask |= (1 << LR_REGNUM);
15216
15217   /* Make sure we have a low work register if we need one.
15218      We will need one if we are going to push a high register,
15219      but we are not currently intending to push a low register.  */
15220   if ((mask & 0xff) == 0
15221       && ((mask & 0x0f00) || TARGET_BACKTRACE))
15222     {
15223       /* Use thumb_find_work_register to choose which register
15224          we will use.  If the register is live then we will
15225          have to push it.  Use LAST_LO_REGNUM as our fallback
15226          choice for the register to select.  */
15227       reg = thumb_find_work_register (1 << LAST_LO_REGNUM);
15228       /* Make sure the register returned by thumb_find_work_register is
15229          not part of the return value.  */
15230       if (reg * UNITS_PER_WORD <= (unsigned) arm_size_return_regs ())
15231         reg = LAST_LO_REGNUM;
15232
15233       if (! call_used_regs[reg])
15234         mask |= 1 << reg;
15235     }
15236
15237   /* The 504 below is 8 bytes less than 512 because there are two possible
15238      alignment words.  We can't tell here if they will be present or not so we
15239      have to play it safe and assume that they are. */
15240   if ((CALLER_INTERWORKING_SLOT_SIZE +
15241        ROUND_UP_WORD (get_frame_size ()) +
15242        crtl->outgoing_args_size) >= 504)
15243     {
15244       /* This is the same as the code in thumb1_expand_prologue() which
15245          determines which register to use for stack decrement. */
15246       for (reg = LAST_ARG_REGNUM + 1; reg <= LAST_LO_REGNUM; reg++)
15247         if (mask & (1 << reg))
15248           break;
15249
15250       if (reg > LAST_LO_REGNUM)
15251         {
15252           /* Make sure we have a register available for stack decrement. */
15253           mask |= 1 << LAST_LO_REGNUM;
15254         }
15255     }
15256
15257   return mask;
15258 }
15259
15260
15261 /* Return the number of bytes required to save VFP registers.  */
15262 static int
15263 arm_get_vfp_saved_size (void)
15264 {
15265   unsigned int regno;
15266   int count;
15267   int saved;
15268
15269   saved = 0;
15270   /* Space for saved VFP registers.  */
15271   if (TARGET_HARD_FLOAT && TARGET_VFP)
15272     {
15273       count = 0;
15274       for (regno = FIRST_VFP_REGNUM;
15275            regno < LAST_VFP_REGNUM;
15276            regno += 2)
15277         {
15278           if ((!df_regs_ever_live_p (regno) || call_used_regs[regno])
15279               && (!df_regs_ever_live_p (regno + 1) || call_used_regs[regno + 1]))
15280             {
15281               if (count > 0)
15282                 {
15283                   /* Workaround ARM10 VFPr1 bug.  */
15284                   if (count == 2 && !arm_arch6)
15285                     count++;
15286                   saved += count * 8;
15287                 }
15288               count = 0;
15289             }
15290           else
15291             count++;
15292         }
15293       if (count > 0)
15294         {
15295           if (count == 2 && !arm_arch6)
15296             count++;
15297           saved += count * 8;
15298         }
15299     }
15300   return saved;
15301 }
15302
15303
15304 /* Generate a function exit sequence.  If REALLY_RETURN is false, then do
15305    everything bar the final return instruction.  */
15306 const char *
15307 output_return_instruction (rtx operand, int really_return, int reverse)
15308 {
15309   char conditional[10];
15310   char instr[100];
15311   unsigned reg;
15312   unsigned long live_regs_mask;
15313   unsigned long func_type;
15314   arm_stack_offsets *offsets;
15315
15316   func_type = arm_current_func_type ();
15317
15318   if (IS_NAKED (func_type))
15319     return "";
15320
15321   if (IS_VOLATILE (func_type) && TARGET_ABORT_NORETURN)
15322     {
15323       /* If this function was declared non-returning, and we have
15324          found a tail call, then we have to trust that the called
15325          function won't return.  */
15326       if (really_return)
15327         {
15328           rtx ops[2];
15329
15330           /* Otherwise, trap an attempted return by aborting.  */
15331           ops[0] = operand;
15332           ops[1] = gen_rtx_SYMBOL_REF (Pmode, NEED_PLT_RELOC ? "abort(PLT)"
15333                                        : "abort");
15334           assemble_external_libcall (ops[1]);
15335           output_asm_insn (reverse ? "bl%D0\t%a1" : "bl%d0\t%a1", ops);
15336         }
15337
15338       return "";
15339     }
15340
15341   gcc_assert (!cfun->calls_alloca || really_return);
15342
15343   sprintf (conditional, "%%?%%%c0", reverse ? 'D' : 'd');
15344
15345   cfun->machine->return_used_this_function = 1;
15346
15347   offsets = arm_get_frame_offsets ();
15348   live_regs_mask = offsets->saved_regs_mask;
15349
15350   if (live_regs_mask)
15351     {
15352       const char * return_reg;
15353
15354       /* If we do not have any special requirements for function exit
15355          (e.g. interworking) then we can load the return address
15356          directly into the PC.  Otherwise we must load it into LR.  */
15357       if (really_return
15358           && (IS_INTERRUPT (func_type) || !TARGET_INTERWORK))
15359         return_reg = reg_names[PC_REGNUM];
15360       else
15361         return_reg = reg_names[LR_REGNUM];
15362
15363       if ((live_regs_mask & (1 << IP_REGNUM)) == (1 << IP_REGNUM))
15364         {
15365           /* There are three possible reasons for the IP register
15366              being saved.  1) a stack frame was created, in which case
15367              IP contains the old stack pointer, or 2) an ISR routine
15368              corrupted it, or 3) it was saved to align the stack on
15369              iWMMXt.  In case 1, restore IP into SP, otherwise just
15370              restore IP.  */
15371           if (frame_pointer_needed)
15372             {
15373               live_regs_mask &= ~ (1 << IP_REGNUM);
15374               live_regs_mask |=   (1 << SP_REGNUM);
15375             }
15376           else
15377             gcc_assert (IS_INTERRUPT (func_type) || TARGET_REALLY_IWMMXT);
15378         }
15379
15380       /* On some ARM architectures it is faster to use LDR rather than
15381          LDM to load a single register.  On other architectures, the
15382          cost is the same.  In 26 bit mode, or for exception handlers,
15383          we have to use LDM to load the PC so that the CPSR is also
15384          restored.  */
15385       for (reg = 0; reg <= LAST_ARM_REGNUM; reg++)
15386         if (live_regs_mask == (1U << reg))
15387           break;
15388
15389       if (reg <= LAST_ARM_REGNUM
15390           && (reg != LR_REGNUM
15391               || ! really_return
15392               || ! IS_INTERRUPT (func_type)))
15393         {
15394           sprintf (instr, "ldr%s\t%%|%s, [%%|sp], #4", conditional,
15395                    (reg == LR_REGNUM) ? return_reg : reg_names[reg]);
15396         }
15397       else
15398         {
15399           char *p;
15400           int first = 1;
15401
15402           /* Generate the load multiple instruction to restore the
15403              registers.  Note we can get here, even if
15404              frame_pointer_needed is true, but only if sp already
15405              points to the base of the saved core registers.  */
15406           if (live_regs_mask & (1 << SP_REGNUM))
15407             {
15408               unsigned HOST_WIDE_INT stack_adjust;
15409
15410               stack_adjust = offsets->outgoing_args - offsets->saved_regs;
15411               gcc_assert (stack_adjust == 0 || stack_adjust == 4);
15412
15413               if (stack_adjust && arm_arch5 && TARGET_ARM)
15414                 if (TARGET_UNIFIED_ASM)
15415                   sprintf (instr, "ldmib%s\t%%|sp, {", conditional);
15416                 else
15417                   sprintf (instr, "ldm%sib\t%%|sp, {", conditional);
15418               else
15419                 {
15420                   /* If we can't use ldmib (SA110 bug),
15421                      then try to pop r3 instead.  */
15422                   if (stack_adjust)
15423                     live_regs_mask |= 1 << 3;
15424
15425                   if (TARGET_UNIFIED_ASM)
15426                     sprintf (instr, "ldmfd%s\t%%|sp, {", conditional);
15427                   else
15428                     sprintf (instr, "ldm%sfd\t%%|sp, {", conditional);
15429                 }
15430             }
15431           else
15432             if (TARGET_UNIFIED_ASM)
15433               sprintf (instr, "pop%s\t{", conditional);
15434             else
15435               sprintf (instr, "ldm%sfd\t%%|sp!, {", conditional);
15436
15437           p = instr + strlen (instr);
15438
15439           for (reg = 0; reg <= SP_REGNUM; reg++)
15440             if (live_regs_mask & (1 << reg))
15441               {
15442                 int l = strlen (reg_names[reg]);
15443
15444                 if (first)
15445                   first = 0;
15446                 else
15447                   {
15448                     memcpy (p, ", ", 2);
15449                     p += 2;
15450                   }
15451
15452                 memcpy (p, "%|", 2);
15453                 memcpy (p + 2, reg_names[reg], l);
15454                 p += l + 2;
15455               }
15456
15457           if (live_regs_mask & (1 << LR_REGNUM))
15458             {
15459               sprintf (p, "%s%%|%s}", first ? "" : ", ", return_reg);
15460               /* If returning from an interrupt, restore the CPSR.  */
15461               if (IS_INTERRUPT (func_type))
15462                 strcat (p, "^");
15463             }
15464           else
15465             strcpy (p, "}");
15466         }
15467
15468       output_asm_insn (instr, & operand);
15469
15470       /* See if we need to generate an extra instruction to
15471          perform the actual function return.  */
15472       if (really_return
15473           && func_type != ARM_FT_INTERWORKED
15474           && (live_regs_mask & (1 << LR_REGNUM)) != 0)
15475         {
15476           /* The return has already been handled
15477              by loading the LR into the PC.  */
15478           really_return = 0;
15479         }
15480     }
15481
15482   if (really_return)
15483     {
15484       switch ((int) ARM_FUNC_TYPE (func_type))
15485         {
15486         case ARM_FT_ISR:
15487         case ARM_FT_FIQ:
15488           /* ??? This is wrong for unified assembly syntax.  */
15489           sprintf (instr, "sub%ss\t%%|pc, %%|lr, #4", conditional);
15490           break;
15491
15492         case ARM_FT_INTERWORKED:
15493           sprintf (instr, "bx%s\t%%|lr", conditional);
15494           break;
15495
15496         case ARM_FT_EXCEPTION:
15497           /* ??? This is wrong for unified assembly syntax.  */
15498           sprintf (instr, "mov%ss\t%%|pc, %%|lr", conditional);
15499           break;
15500
15501         default:
15502           /* Use bx if it's available.  */
15503           if (arm_arch5 || arm_arch4t)
15504             sprintf (instr, "bx%s\t%%|lr", conditional);
15505           else
15506             sprintf (instr, "mov%s\t%%|pc, %%|lr", conditional);
15507           break;
15508         }
15509
15510       output_asm_insn (instr, & operand);
15511     }
15512
15513   return "";
15514 }
15515
15516 /* Write the function name into the code section, directly preceding
15517    the function prologue.
15518
15519    Code will be output similar to this:
15520      t0
15521          .ascii "arm_poke_function_name", 0
15522          .align
15523      t1
15524          .word 0xff000000 + (t1 - t0)
15525      arm_poke_function_name
15526          mov     ip, sp
15527          stmfd   sp!, {fp, ip, lr, pc}
15528          sub     fp, ip, #4
15529
15530    When performing a stack backtrace, code can inspect the value
15531    of 'pc' stored at 'fp' + 0.  If the trace function then looks
15532    at location pc - 12 and the top 8 bits are set, then we know
15533    that there is a function name embedded immediately preceding this
15534    location and has length ((pc[-3]) & 0xff000000).
15535
15536    We assume that pc is declared as a pointer to an unsigned long.
15537
15538    It is of no benefit to output the function name if we are assembling
15539    a leaf function.  These function types will not contain a stack
15540    backtrace structure, therefore it is not possible to determine the
15541    function name.  */
15542 void
15543 arm_poke_function_name (FILE *stream, const char *name)
15544 {
15545   unsigned long alignlength;
15546   unsigned long length;
15547   rtx           x;
15548
15549   length      = strlen (name) + 1;
15550   alignlength = ROUND_UP_WORD (length);
15551
15552   ASM_OUTPUT_ASCII (stream, name, length);
15553   ASM_OUTPUT_ALIGN (stream, 2);
15554   x = GEN_INT ((unsigned HOST_WIDE_INT) 0xff000000 + alignlength);
15555   assemble_aligned_integer (UNITS_PER_WORD, x);
15556 }
15557
15558 /* Place some comments into the assembler stream
15559    describing the current function.  */
15560 static void
15561 arm_output_function_prologue (FILE *f, HOST_WIDE_INT frame_size)
15562 {
15563   unsigned long func_type;
15564
15565   /* ??? Do we want to print some of the below anyway?  */
15566   if (TARGET_THUMB1)
15567     return;
15568
15569   /* Sanity check.  */
15570   gcc_assert (!arm_ccfsm_state && !arm_target_insn);
15571
15572   func_type = arm_current_func_type ();
15573
15574   switch ((int) ARM_FUNC_TYPE (func_type))
15575     {
15576     default:
15577     case ARM_FT_NORMAL:
15578       break;
15579     case ARM_FT_INTERWORKED:
15580       asm_fprintf (f, "\t%@ Function supports interworking.\n");
15581       break;
15582     case ARM_FT_ISR:
15583       asm_fprintf (f, "\t%@ Interrupt Service Routine.\n");
15584       break;
15585     case ARM_FT_FIQ:
15586       asm_fprintf (f, "\t%@ Fast Interrupt Service Routine.\n");
15587       break;
15588     case ARM_FT_EXCEPTION:
15589       asm_fprintf (f, "\t%@ ARM Exception Handler.\n");
15590       break;
15591     }
15592
15593   if (IS_NAKED (func_type))
15594     asm_fprintf (f, "\t%@ Naked Function: prologue and epilogue provided by programmer.\n");
15595
15596   if (IS_VOLATILE (func_type))
15597     asm_fprintf (f, "\t%@ Volatile: function does not return.\n");
15598
15599   if (IS_NESTED (func_type))
15600     asm_fprintf (f, "\t%@ Nested: function declared inside another function.\n");
15601   if (IS_STACKALIGN (func_type))
15602     asm_fprintf (f, "\t%@ Stack Align: May be called with mis-aligned SP.\n");
15603
15604   asm_fprintf (f, "\t%@ args = %d, pretend = %d, frame = %wd\n",
15605                crtl->args.size,
15606                crtl->args.pretend_args_size, frame_size);
15607
15608   asm_fprintf (f, "\t%@ frame_needed = %d, uses_anonymous_args = %d\n",
15609                frame_pointer_needed,
15610                cfun->machine->uses_anonymous_args);
15611
15612   if (cfun->machine->lr_save_eliminated)
15613     asm_fprintf (f, "\t%@ link register save eliminated.\n");
15614
15615   if (crtl->calls_eh_return)
15616     asm_fprintf (f, "\t@ Calls __builtin_eh_return.\n");
15617
15618 }
15619
15620 const char *
15621 arm_output_epilogue (rtx sibling)
15622 {
15623   int reg;
15624   unsigned long saved_regs_mask;
15625   unsigned long func_type;
15626   /* Floats_offset is the offset from the "virtual" frame.  In an APCS
15627      frame that is $fp + 4 for a non-variadic function.  */
15628   int floats_offset = 0;
15629   rtx operands[3];
15630   FILE * f = asm_out_file;
15631   unsigned int lrm_count = 0;
15632   int really_return = (sibling == NULL);
15633   int start_reg;
15634   arm_stack_offsets *offsets;
15635
15636   /* If we have already generated the return instruction
15637      then it is futile to generate anything else.  */
15638   if (use_return_insn (FALSE, sibling) &&
15639       (cfun->machine->return_used_this_function != 0))
15640     return "";
15641
15642   func_type = arm_current_func_type ();
15643
15644   if (IS_NAKED (func_type))
15645     /* Naked functions don't have epilogues.  */
15646     return "";
15647
15648   if (IS_VOLATILE (func_type) && TARGET_ABORT_NORETURN)
15649     {
15650       rtx op;
15651
15652       /* A volatile function should never return.  Call abort.  */
15653       op = gen_rtx_SYMBOL_REF (Pmode, NEED_PLT_RELOC ? "abort(PLT)" : "abort");
15654       assemble_external_libcall (op);
15655       output_asm_insn ("bl\t%a0", &op);
15656
15657       return "";
15658     }
15659
15660   /* If we are throwing an exception, then we really must be doing a
15661      return, so we can't tail-call.  */
15662   gcc_assert (!crtl->calls_eh_return || really_return);
15663
15664   offsets = arm_get_frame_offsets ();
15665   saved_regs_mask = offsets->saved_regs_mask;
15666
15667   if (TARGET_IWMMXT)
15668     lrm_count = bit_count (saved_regs_mask);
15669
15670   floats_offset = offsets->saved_args;
15671   /* Compute how far away the floats will be.  */
15672   for (reg = 0; reg <= LAST_ARM_REGNUM; reg++)
15673     if (saved_regs_mask & (1 << reg))
15674       floats_offset += 4;
15675
15676   if (TARGET_APCS_FRAME && frame_pointer_needed && TARGET_ARM)
15677     {
15678       /* This variable is for the Virtual Frame Pointer, not VFP regs.  */
15679       int vfp_offset = offsets->frame;
15680
15681       if (TARGET_FPA_EMU2)
15682         {
15683           for (reg = LAST_FPA_REGNUM; reg >= FIRST_FPA_REGNUM; reg--)
15684             if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
15685               {
15686                 floats_offset += 12;
15687                 asm_fprintf (f, "\tldfe\t%r, [%r, #-%d]\n",
15688                              reg, FP_REGNUM, floats_offset - vfp_offset);
15689               }
15690         }
15691       else
15692         {
15693           start_reg = LAST_FPA_REGNUM;
15694
15695           for (reg = LAST_FPA_REGNUM; reg >= FIRST_FPA_REGNUM; reg--)
15696             {
15697               if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
15698                 {
15699                   floats_offset += 12;
15700
15701                   /* We can't unstack more than four registers at once.  */
15702                   if (start_reg - reg == 3)
15703                     {
15704                       asm_fprintf (f, "\tlfm\t%r, 4, [%r, #-%d]\n",
15705                                    reg, FP_REGNUM, floats_offset - vfp_offset);
15706                       start_reg = reg - 1;
15707                     }
15708                 }
15709               else
15710                 {
15711                   if (reg != start_reg)
15712                     asm_fprintf (f, "\tlfm\t%r, %d, [%r, #-%d]\n",
15713                                  reg + 1, start_reg - reg,
15714                                  FP_REGNUM, floats_offset - vfp_offset);
15715                   start_reg = reg - 1;
15716                 }
15717             }
15718
15719           /* Just in case the last register checked also needs unstacking.  */
15720           if (reg != start_reg)
15721             asm_fprintf (f, "\tlfm\t%r, %d, [%r, #-%d]\n",
15722                          reg + 1, start_reg - reg,
15723                          FP_REGNUM, floats_offset - vfp_offset);
15724         }
15725
15726       if (TARGET_HARD_FLOAT && TARGET_VFP)
15727         {
15728           int saved_size;
15729
15730           /* The fldmd insns do not have base+offset addressing
15731              modes, so we use IP to hold the address.  */
15732           saved_size = arm_get_vfp_saved_size ();
15733
15734           if (saved_size > 0)
15735             {
15736               floats_offset += saved_size;
15737               asm_fprintf (f, "\tsub\t%r, %r, #%d\n", IP_REGNUM,
15738                            FP_REGNUM, floats_offset - vfp_offset);
15739             }
15740           start_reg = FIRST_VFP_REGNUM;
15741           for (reg = FIRST_VFP_REGNUM; reg < LAST_VFP_REGNUM; reg += 2)
15742             {
15743               if ((!df_regs_ever_live_p (reg) || call_used_regs[reg])
15744                   && (!df_regs_ever_live_p (reg + 1) || call_used_regs[reg + 1]))
15745                 {
15746                   if (start_reg != reg)
15747                     vfp_output_fldmd (f, IP_REGNUM,
15748                                       (start_reg - FIRST_VFP_REGNUM) / 2,
15749                                       (reg - start_reg) / 2);
15750                   start_reg = reg + 2;
15751                 }
15752             }
15753           if (start_reg != reg)
15754             vfp_output_fldmd (f, IP_REGNUM,
15755                               (start_reg - FIRST_VFP_REGNUM) / 2,
15756                               (reg - start_reg) / 2);
15757         }
15758
15759       if (TARGET_IWMMXT)
15760         {
15761           /* The frame pointer is guaranteed to be non-double-word aligned.
15762              This is because it is set to (old_stack_pointer - 4) and the
15763              old_stack_pointer was double word aligned.  Thus the offset to
15764              the iWMMXt registers to be loaded must also be non-double-word
15765              sized, so that the resultant address *is* double-word aligned.
15766              We can ignore floats_offset since that was already included in
15767              the live_regs_mask.  */
15768           lrm_count += (lrm_count % 2 ? 2 : 1);
15769
15770           for (reg = LAST_IWMMXT_REGNUM; reg >= FIRST_IWMMXT_REGNUM; reg--)
15771             if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
15772               {
15773                 asm_fprintf (f, "\twldrd\t%r, [%r, #-%d]\n",
15774                              reg, FP_REGNUM, lrm_count * 4);
15775                 lrm_count += 2;
15776               }
15777         }
15778
15779       /* saved_regs_mask should contain the IP, which at the time of stack
15780          frame generation actually contains the old stack pointer.  So a
15781          quick way to unwind the stack is just pop the IP register directly
15782          into the stack pointer.  */
15783       gcc_assert (saved_regs_mask & (1 << IP_REGNUM));
15784       saved_regs_mask &= ~ (1 << IP_REGNUM);
15785       saved_regs_mask |=   (1 << SP_REGNUM);
15786
15787       /* There are two registers left in saved_regs_mask - LR and PC.  We
15788          only need to restore the LR register (the return address), but to
15789          save time we can load it directly into the PC, unless we need a
15790          special function exit sequence, or we are not really returning.  */
15791       if (really_return
15792           && ARM_FUNC_TYPE (func_type) == ARM_FT_NORMAL
15793           && !crtl->calls_eh_return)
15794         /* Delete the LR from the register mask, so that the LR on
15795            the stack is loaded into the PC in the register mask.  */
15796         saved_regs_mask &= ~ (1 << LR_REGNUM);
15797       else
15798         saved_regs_mask &= ~ (1 << PC_REGNUM);
15799
15800       /* We must use SP as the base register, because SP is one of the
15801          registers being restored.  If an interrupt or page fault
15802          happens in the ldm instruction, the SP might or might not
15803          have been restored.  That would be bad, as then SP will no
15804          longer indicate the safe area of stack, and we can get stack
15805          corruption.  Using SP as the base register means that it will
15806          be reset correctly to the original value, should an interrupt
15807          occur.  If the stack pointer already points at the right
15808          place, then omit the subtraction.  */
15809       if (offsets->outgoing_args != (1 + (int) bit_count (saved_regs_mask))
15810           || cfun->calls_alloca)
15811         asm_fprintf (f, "\tsub\t%r, %r, #%d\n", SP_REGNUM, FP_REGNUM,
15812                      4 * bit_count (saved_regs_mask));
15813       print_multi_reg (f, "ldmfd\t%r, ", SP_REGNUM, saved_regs_mask, 0);
15814
15815       if (IS_INTERRUPT (func_type))
15816         /* Interrupt handlers will have pushed the
15817            IP onto the stack, so restore it now.  */
15818         print_multi_reg (f, "ldmfd\t%r!, ", SP_REGNUM, 1 << IP_REGNUM, 0);
15819     }
15820   else
15821     {
15822       /* This branch is executed for ARM mode (non-apcs frames) and
15823          Thumb-2 mode. Frame layout is essentially the same for those
15824          cases, except that in ARM mode frame pointer points to the
15825          first saved register, while in Thumb-2 mode the frame pointer points
15826          to the last saved register.
15827
15828          It is possible to make frame pointer point to last saved
15829          register in both cases, and remove some conditionals below.
15830          That means that fp setup in prologue would be just "mov fp, sp"
15831          and sp restore in epilogue would be just "mov sp, fp", whereas
15832          now we have to use add/sub in those cases. However, the value
15833          of that would be marginal, as both mov and add/sub are 32-bit
15834          in ARM mode, and it would require extra conditionals
15835          in arm_expand_prologue to distingish ARM-apcs-frame case
15836          (where frame pointer is required to point at first register)
15837          and ARM-non-apcs-frame. Therefore, such change is postponed
15838          until real need arise.  */
15839       unsigned HOST_WIDE_INT amount;
15840       int rfe;
15841       /* Restore stack pointer if necessary.  */
15842       if (TARGET_ARM && frame_pointer_needed)
15843         {
15844           operands[0] = stack_pointer_rtx;
15845           operands[1] = hard_frame_pointer_rtx;
15846
15847           operands[2] = GEN_INT (offsets->frame - offsets->saved_regs);
15848           output_add_immediate (operands);
15849         }
15850       else
15851         {
15852           if (frame_pointer_needed)
15853             {
15854               /* For Thumb-2 restore sp from the frame pointer.
15855                  Operand restrictions mean we have to incrememnt FP, then copy
15856                  to SP.  */
15857               amount = offsets->locals_base - offsets->saved_regs;
15858               operands[0] = hard_frame_pointer_rtx;
15859             }
15860           else
15861             {
15862               unsigned long count;
15863               operands[0] = stack_pointer_rtx;
15864               amount = offsets->outgoing_args - offsets->saved_regs;
15865               /* pop call clobbered registers if it avoids a
15866                  separate stack adjustment.  */
15867               count = offsets->saved_regs - offsets->saved_args;
15868               if (optimize_size
15869                   && count != 0
15870                   && !crtl->calls_eh_return
15871                   && bit_count(saved_regs_mask) * 4 == count
15872                   && !IS_INTERRUPT (func_type)
15873                   && !IS_STACKALIGN (func_type)
15874                   && !crtl->tail_call_emit)
15875                 {
15876                   unsigned long mask;
15877                   /* Preserve return values, of any size.  */
15878                   mask = (1 << ((arm_size_return_regs() + 3) / 4)) - 1;
15879                   mask ^= 0xf;
15880                   mask &= ~saved_regs_mask;
15881                   reg = 0;
15882                   while (bit_count (mask) * 4 > amount)
15883                     {
15884                       while ((mask & (1 << reg)) == 0)
15885                         reg++;
15886                       mask &= ~(1 << reg);
15887                     }
15888                   if (bit_count (mask) * 4 == amount) {
15889                       amount = 0;
15890                       saved_regs_mask |= mask;
15891                   }
15892                 }
15893             }
15894
15895           if (amount)
15896             {
15897               operands[1] = operands[0];
15898               operands[2] = GEN_INT (amount);
15899               output_add_immediate (operands);
15900             }
15901           if (frame_pointer_needed)
15902             asm_fprintf (f, "\tmov\t%r, %r\n",
15903                          SP_REGNUM, HARD_FRAME_POINTER_REGNUM);
15904         }
15905
15906       if (TARGET_FPA_EMU2)
15907         {
15908           for (reg = FIRST_FPA_REGNUM; reg <= LAST_FPA_REGNUM; reg++)
15909             if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
15910               asm_fprintf (f, "\tldfe\t%r, [%r], #12\n",
15911                            reg, SP_REGNUM);
15912         }
15913       else
15914         {
15915           start_reg = FIRST_FPA_REGNUM;
15916
15917           for (reg = FIRST_FPA_REGNUM; reg <= LAST_FPA_REGNUM; reg++)
15918             {
15919               if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
15920                 {
15921                   if (reg - start_reg == 3)
15922                     {
15923                       asm_fprintf (f, "\tlfmfd\t%r, 4, [%r]!\n",
15924                                    start_reg, SP_REGNUM);
15925                       start_reg = reg + 1;
15926                     }
15927                 }
15928               else
15929                 {
15930                   if (reg != start_reg)
15931                     asm_fprintf (f, "\tlfmfd\t%r, %d, [%r]!\n",
15932                                  start_reg, reg - start_reg,
15933                                  SP_REGNUM);
15934
15935                   start_reg = reg + 1;
15936                 }
15937             }
15938
15939           /* Just in case the last register checked also needs unstacking.  */
15940           if (reg != start_reg)
15941             asm_fprintf (f, "\tlfmfd\t%r, %d, [%r]!\n",
15942                          start_reg, reg - start_reg, SP_REGNUM);
15943         }
15944
15945       if (TARGET_HARD_FLOAT && TARGET_VFP)
15946         {
15947           int end_reg = LAST_VFP_REGNUM + 1;
15948
15949           /* Scan the registers in reverse order.  We need to match
15950              any groupings made in the prologue and generate matching
15951              pop operations.  */
15952           for (reg = LAST_VFP_REGNUM - 1; reg >= FIRST_VFP_REGNUM; reg -= 2)
15953             {
15954               if ((!df_regs_ever_live_p (reg) || call_used_regs[reg])
15955                   && (!df_regs_ever_live_p (reg + 1)
15956                       || call_used_regs[reg + 1]))
15957                 {
15958                   if (end_reg > reg + 2)
15959                     vfp_output_fldmd (f, SP_REGNUM,
15960                                       (reg + 2 - FIRST_VFP_REGNUM) / 2,
15961                                       (end_reg - (reg + 2)) / 2);
15962                   end_reg = reg;
15963                 }
15964             }
15965           if (end_reg > reg + 2)
15966             vfp_output_fldmd (f, SP_REGNUM, 0,
15967                               (end_reg - (reg + 2)) / 2);
15968         }
15969
15970       if (TARGET_IWMMXT)
15971         for (reg = FIRST_IWMMXT_REGNUM; reg <= LAST_IWMMXT_REGNUM; reg++)
15972           if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
15973             asm_fprintf (f, "\twldrd\t%r, [%r], #8\n", reg, SP_REGNUM);
15974
15975       /* If we can, restore the LR into the PC.  */
15976       if (ARM_FUNC_TYPE (func_type) != ARM_FT_INTERWORKED
15977           && (TARGET_ARM || ARM_FUNC_TYPE (func_type) == ARM_FT_NORMAL)
15978           && !IS_STACKALIGN (func_type)
15979           && really_return
15980           && crtl->args.pretend_args_size == 0
15981           && saved_regs_mask & (1 << LR_REGNUM)
15982           && !crtl->calls_eh_return)
15983         {
15984           saved_regs_mask &= ~ (1 << LR_REGNUM);
15985           saved_regs_mask |=   (1 << PC_REGNUM);
15986           rfe = IS_INTERRUPT (func_type);
15987         }
15988       else
15989         rfe = 0;
15990
15991       /* Load the registers off the stack.  If we only have one register
15992          to load use the LDR instruction - it is faster.  For Thumb-2
15993          always use pop and the assembler will pick the best instruction.*/
15994       if (TARGET_ARM && saved_regs_mask == (1 << LR_REGNUM)
15995           && !IS_INTERRUPT(func_type))
15996         {
15997           asm_fprintf (f, "\tldr\t%r, [%r], #4\n", LR_REGNUM, SP_REGNUM);
15998         }
15999       else if (saved_regs_mask)
16000         {
16001           if (saved_regs_mask & (1 << SP_REGNUM))
16002             /* Note - write back to the stack register is not enabled
16003                (i.e. "ldmfd sp!...").  We know that the stack pointer is
16004                in the list of registers and if we add writeback the
16005                instruction becomes UNPREDICTABLE.  */
16006             print_multi_reg (f, "ldmfd\t%r, ", SP_REGNUM, saved_regs_mask,
16007                              rfe);
16008           else if (TARGET_ARM)
16009             print_multi_reg (f, "ldmfd\t%r!, ", SP_REGNUM, saved_regs_mask,
16010                              rfe);
16011           else
16012             print_multi_reg (f, "pop\t", SP_REGNUM, saved_regs_mask, 0);
16013         }
16014
16015       if (crtl->args.pretend_args_size)
16016         {
16017           /* Unwind the pre-pushed regs.  */
16018           operands[0] = operands[1] = stack_pointer_rtx;
16019           operands[2] = GEN_INT (crtl->args.pretend_args_size);
16020           output_add_immediate (operands);
16021         }
16022     }
16023
16024   /* We may have already restored PC directly from the stack.  */
16025   if (!really_return || saved_regs_mask & (1 << PC_REGNUM))
16026     return "";
16027
16028   /* Stack adjustment for exception handler.  */
16029   if (crtl->calls_eh_return)
16030     asm_fprintf (f, "\tadd\t%r, %r, %r\n", SP_REGNUM, SP_REGNUM,
16031                  ARM_EH_STACKADJ_REGNUM);
16032
16033   /* Generate the return instruction.  */
16034   switch ((int) ARM_FUNC_TYPE (func_type))
16035     {
16036     case ARM_FT_ISR:
16037     case ARM_FT_FIQ:
16038       asm_fprintf (f, "\tsubs\t%r, %r, #4\n", PC_REGNUM, LR_REGNUM);
16039       break;
16040
16041     case ARM_FT_EXCEPTION:
16042       asm_fprintf (f, "\tmovs\t%r, %r\n", PC_REGNUM, LR_REGNUM);
16043       break;
16044
16045     case ARM_FT_INTERWORKED:
16046       asm_fprintf (f, "\tbx\t%r\n", LR_REGNUM);
16047       break;
16048
16049     default:
16050       if (IS_STACKALIGN (func_type))
16051         {
16052           /* See comment in arm_expand_prologue.  */
16053           asm_fprintf (f, "\tmov\t%r, %r\n", SP_REGNUM, 0);
16054         }
16055       if (arm_arch5 || arm_arch4t)
16056         asm_fprintf (f, "\tbx\t%r\n", LR_REGNUM);
16057       else
16058         asm_fprintf (f, "\tmov\t%r, %r\n", PC_REGNUM, LR_REGNUM);
16059       break;
16060     }
16061
16062   return "";
16063 }
16064
16065 static void
16066 arm_output_function_epilogue (FILE *file ATTRIBUTE_UNUSED,
16067                               HOST_WIDE_INT frame_size ATTRIBUTE_UNUSED)
16068 {
16069   arm_stack_offsets *offsets;
16070
16071   if (TARGET_THUMB1)
16072     {
16073       int regno;
16074
16075       /* Emit any call-via-reg trampolines that are needed for v4t support
16076          of call_reg and call_value_reg type insns.  */
16077       for (regno = 0; regno < LR_REGNUM; regno++)
16078         {
16079           rtx label = cfun->machine->call_via[regno];
16080
16081           if (label != NULL)
16082             {
16083               switch_to_section (function_section (current_function_decl));
16084               targetm.asm_out.internal_label (asm_out_file, "L",
16085                                               CODE_LABEL_NUMBER (label));
16086               asm_fprintf (asm_out_file, "\tbx\t%r\n", regno);
16087             }
16088         }
16089
16090       /* ??? Probably not safe to set this here, since it assumes that a
16091          function will be emitted as assembly immediately after we generate
16092          RTL for it.  This does not happen for inline functions.  */
16093       cfun->machine->return_used_this_function = 0;
16094     }
16095   else /* TARGET_32BIT */
16096     {
16097       /* We need to take into account any stack-frame rounding.  */
16098       offsets = arm_get_frame_offsets ();
16099
16100       gcc_assert (!use_return_insn (FALSE, NULL)
16101                   || (cfun->machine->return_used_this_function != 0)
16102                   || offsets->saved_regs == offsets->outgoing_args
16103                   || frame_pointer_needed);
16104
16105       /* Reset the ARM-specific per-function variables.  */
16106       after_arm_reorg = 0;
16107     }
16108 }
16109
16110 /* Generate and emit an insn that we will recognize as a push_multi.
16111    Unfortunately, since this insn does not reflect very well the actual
16112    semantics of the operation, we need to annotate the insn for the benefit
16113    of DWARF2 frame unwind information.  */
16114 static rtx
16115 emit_multi_reg_push (unsigned long mask)
16116 {
16117   int num_regs = 0;
16118   int num_dwarf_regs;
16119   int i, j;
16120   rtx par;
16121   rtx dwarf;
16122   int dwarf_par_index;
16123   rtx tmp, reg;
16124
16125   for (i = 0; i <= LAST_ARM_REGNUM; i++)
16126     if (mask & (1 << i))
16127       num_regs++;
16128
16129   gcc_assert (num_regs && num_regs <= 16);
16130
16131   /* We don't record the PC in the dwarf frame information.  */
16132   num_dwarf_regs = num_regs;
16133   if (mask & (1 << PC_REGNUM))
16134     num_dwarf_regs--;
16135
16136   /* For the body of the insn we are going to generate an UNSPEC in
16137      parallel with several USEs.  This allows the insn to be recognized
16138      by the push_multi pattern in the arm.md file.
16139
16140      The body of the insn looks something like this:
16141
16142        (parallel [
16143            (set (mem:BLK (pre_modify:SI (reg:SI sp)
16144                                         (const_int:SI <num>)))
16145                 (unspec:BLK [(reg:SI r4)] UNSPEC_PUSH_MULT))
16146            (use (reg:SI XX))
16147            (use (reg:SI YY))
16148            ...
16149         ])
16150
16151      For the frame note however, we try to be more explicit and actually
16152      show each register being stored into the stack frame, plus a (single)
16153      decrement of the stack pointer.  We do it this way in order to be
16154      friendly to the stack unwinding code, which only wants to see a single
16155      stack decrement per instruction.  The RTL we generate for the note looks
16156      something like this:
16157
16158       (sequence [
16159            (set (reg:SI sp) (plus:SI (reg:SI sp) (const_int -20)))
16160            (set (mem:SI (reg:SI sp)) (reg:SI r4))
16161            (set (mem:SI (plus:SI (reg:SI sp) (const_int 4))) (reg:SI XX))
16162            (set (mem:SI (plus:SI (reg:SI sp) (const_int 8))) (reg:SI YY))
16163            ...
16164         ])
16165
16166      FIXME:: In an ideal world the PRE_MODIFY would not exist and
16167      instead we'd have a parallel expression detailing all
16168      the stores to the various memory addresses so that debug
16169      information is more up-to-date. Remember however while writing
16170      this to take care of the constraints with the push instruction.
16171
16172      Note also that this has to be taken care of for the VFP registers.
16173
16174      For more see PR43399.  */
16175
16176   par = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (num_regs));
16177   dwarf = gen_rtx_SEQUENCE (VOIDmode, rtvec_alloc (num_dwarf_regs + 1));
16178   dwarf_par_index = 1;
16179
16180   for (i = 0; i <= LAST_ARM_REGNUM; i++)
16181     {
16182       if (mask & (1 << i))
16183         {
16184           reg = gen_rtx_REG (SImode, i);
16185
16186           XVECEXP (par, 0, 0)
16187             = gen_rtx_SET (VOIDmode,
16188                            gen_frame_mem
16189                            (BLKmode,
16190                             gen_rtx_PRE_MODIFY (Pmode,
16191                                                 stack_pointer_rtx,
16192                                                 plus_constant
16193                                                 (stack_pointer_rtx,
16194                                                  -4 * num_regs))
16195                             ),
16196                            gen_rtx_UNSPEC (BLKmode,
16197                                            gen_rtvec (1, reg),
16198                                            UNSPEC_PUSH_MULT));
16199
16200           if (i != PC_REGNUM)
16201             {
16202               tmp = gen_rtx_SET (VOIDmode,
16203                                  gen_frame_mem (SImode, stack_pointer_rtx),
16204                                  reg);
16205               RTX_FRAME_RELATED_P (tmp) = 1;
16206               XVECEXP (dwarf, 0, dwarf_par_index) = tmp;
16207               dwarf_par_index++;
16208             }
16209
16210           break;
16211         }
16212     }
16213
16214   for (j = 1, i++; j < num_regs; i++)
16215     {
16216       if (mask & (1 << i))
16217         {
16218           reg = gen_rtx_REG (SImode, i);
16219
16220           XVECEXP (par, 0, j) = gen_rtx_USE (VOIDmode, reg);
16221
16222           if (i != PC_REGNUM)
16223             {
16224               tmp
16225                 = gen_rtx_SET (VOIDmode,
16226                                gen_frame_mem
16227                                (SImode,
16228                                 plus_constant (stack_pointer_rtx,
16229                                                4 * j)),
16230                                reg);
16231               RTX_FRAME_RELATED_P (tmp) = 1;
16232               XVECEXP (dwarf, 0, dwarf_par_index++) = tmp;
16233             }
16234
16235           j++;
16236         }
16237     }
16238
16239   par = emit_insn (par);
16240
16241   tmp = gen_rtx_SET (VOIDmode,
16242                      stack_pointer_rtx,
16243                      plus_constant (stack_pointer_rtx, -4 * num_regs));
16244   RTX_FRAME_RELATED_P (tmp) = 1;
16245   XVECEXP (dwarf, 0, 0) = tmp;
16246
16247   add_reg_note (par, REG_FRAME_RELATED_EXPR, dwarf);
16248
16249   return par;
16250 }
16251
16252 /* Calculate the size of the return value that is passed in registers.  */
16253 static unsigned
16254 arm_size_return_regs (void)
16255 {
16256   enum machine_mode mode;
16257
16258   if (crtl->return_rtx != 0)
16259     mode = GET_MODE (crtl->return_rtx);
16260   else
16261     mode = DECL_MODE (DECL_RESULT (current_function_decl));
16262
16263   return GET_MODE_SIZE (mode);
16264 }
16265
16266 static rtx
16267 emit_sfm (int base_reg, int count)
16268 {
16269   rtx par;
16270   rtx dwarf;
16271   rtx tmp, reg;
16272   int i;
16273
16274   par = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (count));
16275   dwarf = gen_rtx_SEQUENCE (VOIDmode, rtvec_alloc (count + 1));
16276
16277   reg = gen_rtx_REG (XFmode, base_reg++);
16278
16279   XVECEXP (par, 0, 0)
16280     = gen_rtx_SET (VOIDmode,
16281                    gen_frame_mem
16282                    (BLKmode,
16283                     gen_rtx_PRE_MODIFY (Pmode,
16284                                         stack_pointer_rtx,
16285                                         plus_constant
16286                                         (stack_pointer_rtx,
16287                                          -12 * count))
16288                     ),
16289                    gen_rtx_UNSPEC (BLKmode,
16290                                    gen_rtvec (1, reg),
16291                                    UNSPEC_PUSH_MULT));
16292   tmp = gen_rtx_SET (VOIDmode,
16293                      gen_frame_mem (XFmode, stack_pointer_rtx), reg);
16294   RTX_FRAME_RELATED_P (tmp) = 1;
16295   XVECEXP (dwarf, 0, 1) = tmp;
16296
16297   for (i = 1; i < count; i++)
16298     {
16299       reg = gen_rtx_REG (XFmode, base_reg++);
16300       XVECEXP (par, 0, i) = gen_rtx_USE (VOIDmode, reg);
16301
16302       tmp = gen_rtx_SET (VOIDmode,
16303                          gen_frame_mem (XFmode,
16304                                         plus_constant (stack_pointer_rtx,
16305                                                        i * 12)),
16306                          reg);
16307       RTX_FRAME_RELATED_P (tmp) = 1;
16308       XVECEXP (dwarf, 0, i + 1) = tmp;
16309     }
16310
16311   tmp = gen_rtx_SET (VOIDmode,
16312                      stack_pointer_rtx,
16313                      plus_constant (stack_pointer_rtx, -12 * count));
16314
16315   RTX_FRAME_RELATED_P (tmp) = 1;
16316   XVECEXP (dwarf, 0, 0) = tmp;
16317
16318   par = emit_insn (par);
16319   add_reg_note (par, REG_FRAME_RELATED_EXPR, dwarf);
16320
16321   return par;
16322 }
16323
16324
16325 /* Return true if the current function needs to save/restore LR.  */
16326
16327 static bool
16328 thumb_force_lr_save (void)
16329 {
16330   return !cfun->machine->lr_save_eliminated
16331          && (!leaf_function_p ()
16332              || thumb_far_jump_used_p ()
16333              || df_regs_ever_live_p (LR_REGNUM));
16334 }
16335
16336
16337 /* Return true if r3 is used by any of the tail call insns in the
16338    current function.  */
16339
16340 static bool
16341 any_sibcall_uses_r3 (void)
16342 {
16343   edge_iterator ei;
16344   edge e;
16345
16346   if (!crtl->tail_call_emit)
16347     return false;
16348   FOR_EACH_EDGE (e, ei, EXIT_BLOCK_PTR->preds)
16349     if (e->flags & EDGE_SIBCALL)
16350       {
16351         rtx call = BB_END (e->src);
16352         if (!CALL_P (call))
16353           call = prev_nonnote_nondebug_insn (call);
16354         gcc_assert (CALL_P (call) && SIBLING_CALL_P (call));
16355         if (find_regno_fusage (call, USE, 3))
16356           return true;
16357       }
16358   return false;
16359 }
16360
16361
16362 /* Compute the distance from register FROM to register TO.
16363    These can be the arg pointer (26), the soft frame pointer (25),
16364    the stack pointer (13) or the hard frame pointer (11).
16365    In thumb mode r7 is used as the soft frame pointer, if needed.
16366    Typical stack layout looks like this:
16367
16368        old stack pointer -> |    |
16369                              ----
16370                             |    | \
16371                             |    |   saved arguments for
16372                             |    |   vararg functions
16373                             |    | /
16374                               --
16375    hard FP & arg pointer -> |    | \
16376                             |    |   stack
16377                             |    |   frame
16378                             |    | /
16379                               --
16380                             |    | \
16381                             |    |   call saved
16382                             |    |   registers
16383       soft frame pointer -> |    | /
16384                               --
16385                             |    | \
16386                             |    |   local
16387                             |    |   variables
16388      locals base pointer -> |    | /
16389                               --
16390                             |    | \
16391                             |    |   outgoing
16392                             |    |   arguments
16393    current stack pointer -> |    | /
16394                               --
16395
16396   For a given function some or all of these stack components
16397   may not be needed, giving rise to the possibility of
16398   eliminating some of the registers.
16399
16400   The values returned by this function must reflect the behavior
16401   of arm_expand_prologue() and arm_compute_save_reg_mask().
16402
16403   The sign of the number returned reflects the direction of stack
16404   growth, so the values are positive for all eliminations except
16405   from the soft frame pointer to the hard frame pointer.
16406
16407   SFP may point just inside the local variables block to ensure correct
16408   alignment.  */
16409
16410
16411 /* Calculate stack offsets.  These are used to calculate register elimination
16412    offsets and in prologue/epilogue code.  Also calculates which registers
16413    should be saved.  */
16414
16415 static arm_stack_offsets *
16416 arm_get_frame_offsets (void)
16417 {
16418   struct arm_stack_offsets *offsets;
16419   unsigned long func_type;
16420   int leaf;
16421   int saved;
16422   int core_saved;
16423   HOST_WIDE_INT frame_size;
16424   int i;
16425
16426   offsets = &cfun->machine->stack_offsets;
16427
16428   /* We need to know if we are a leaf function.  Unfortunately, it
16429      is possible to be called after start_sequence has been called,
16430      which causes get_insns to return the insns for the sequence,
16431      not the function, which will cause leaf_function_p to return
16432      the incorrect result.
16433
16434      to know about leaf functions once reload has completed, and the
16435      frame size cannot be changed after that time, so we can safely
16436      use the cached value.  */
16437
16438   if (reload_completed)
16439     return offsets;
16440
16441   /* Initially this is the size of the local variables.  It will translated
16442      into an offset once we have determined the size of preceding data.  */
16443   frame_size = ROUND_UP_WORD (get_frame_size ());
16444
16445   leaf = leaf_function_p ();
16446
16447   /* Space for variadic functions.  */
16448   offsets->saved_args = crtl->args.pretend_args_size;
16449
16450   /* In Thumb mode this is incorrect, but never used.  */
16451   offsets->frame = offsets->saved_args + (frame_pointer_needed ? 4 : 0) +
16452                    arm_compute_static_chain_stack_bytes();
16453
16454   if (TARGET_32BIT)
16455     {
16456       unsigned int regno;
16457
16458       offsets->saved_regs_mask = arm_compute_save_reg_mask ();
16459       core_saved = bit_count (offsets->saved_regs_mask) * 4;
16460       saved = core_saved;
16461
16462       /* We know that SP will be doubleword aligned on entry, and we must
16463          preserve that condition at any subroutine call.  We also require the
16464          soft frame pointer to be doubleword aligned.  */
16465
16466       if (TARGET_REALLY_IWMMXT)
16467         {
16468           /* Check for the call-saved iWMMXt registers.  */
16469           for (regno = FIRST_IWMMXT_REGNUM;
16470                regno <= LAST_IWMMXT_REGNUM;
16471                regno++)
16472             if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
16473               saved += 8;
16474         }
16475
16476       func_type = arm_current_func_type ();
16477       if (! IS_VOLATILE (func_type))
16478         {
16479           /* Space for saved FPA registers.  */
16480           for (regno = FIRST_FPA_REGNUM; regno <= LAST_FPA_REGNUM; regno++)
16481             if (df_regs_ever_live_p (regno) && ! call_used_regs[regno])
16482             saved += 12;
16483
16484           /* Space for saved VFP registers.  */
16485           if (TARGET_HARD_FLOAT && TARGET_VFP)
16486             saved += arm_get_vfp_saved_size ();
16487         }
16488     }
16489   else /* TARGET_THUMB1 */
16490     {
16491       offsets->saved_regs_mask = thumb1_compute_save_reg_mask ();
16492       core_saved = bit_count (offsets->saved_regs_mask) * 4;
16493       saved = core_saved;
16494       if (TARGET_BACKTRACE)
16495         saved += 16;
16496     }
16497
16498   /* Saved registers include the stack frame.  */
16499   offsets->saved_regs = offsets->saved_args + saved +
16500                         arm_compute_static_chain_stack_bytes();
16501   offsets->soft_frame = offsets->saved_regs + CALLER_INTERWORKING_SLOT_SIZE;
16502   /* A leaf function does not need any stack alignment if it has nothing
16503      on the stack.  */
16504   if (leaf && frame_size == 0
16505       /* However if it calls alloca(), we have a dynamically allocated
16506          block of BIGGEST_ALIGNMENT on stack, so still do stack alignment.  */
16507       && ! cfun->calls_alloca)
16508     {
16509       offsets->outgoing_args = offsets->soft_frame;
16510       offsets->locals_base = offsets->soft_frame;
16511       return offsets;
16512     }
16513
16514   /* Ensure SFP has the correct alignment.  */
16515   if (ARM_DOUBLEWORD_ALIGN
16516       && (offsets->soft_frame & 7))
16517     {
16518       offsets->soft_frame += 4;
16519       /* Try to align stack by pushing an extra reg.  Don't bother doing this
16520          when there is a stack frame as the alignment will be rolled into
16521          the normal stack adjustment.  */
16522       if (frame_size + crtl->outgoing_args_size == 0)
16523         {
16524           int reg = -1;
16525
16526           /* If it is safe to use r3, then do so.  This sometimes
16527              generates better code on Thumb-2 by avoiding the need to
16528              use 32-bit push/pop instructions.  */
16529           if (! any_sibcall_uses_r3 ()
16530               && arm_size_return_regs () <= 12
16531               && (offsets->saved_regs_mask & (1 << 3)) == 0)
16532             {
16533               reg = 3;
16534             }
16535           else
16536             for (i = 4; i <= (TARGET_THUMB1 ? LAST_LO_REGNUM : 11); i++)
16537               {
16538                 if ((offsets->saved_regs_mask & (1 << i)) == 0)
16539                   {
16540                     reg = i;
16541                     break;
16542                   }
16543               }
16544
16545           if (reg != -1)
16546             {
16547               offsets->saved_regs += 4;
16548               offsets->saved_regs_mask |= (1 << reg);
16549             }
16550         }
16551     }
16552
16553   offsets->locals_base = offsets->soft_frame + frame_size;
16554   offsets->outgoing_args = (offsets->locals_base
16555                             + crtl->outgoing_args_size);
16556
16557   if (ARM_DOUBLEWORD_ALIGN)
16558     {
16559       /* Ensure SP remains doubleword aligned.  */
16560       if (offsets->outgoing_args & 7)
16561         offsets->outgoing_args += 4;
16562       gcc_assert (!(offsets->outgoing_args & 7));
16563     }
16564
16565   return offsets;
16566 }
16567
16568
16569 /* Calculate the relative offsets for the different stack pointers.  Positive
16570    offsets are in the direction of stack growth.  */
16571
16572 HOST_WIDE_INT
16573 arm_compute_initial_elimination_offset (unsigned int from, unsigned int to)
16574 {
16575   arm_stack_offsets *offsets;
16576
16577   offsets = arm_get_frame_offsets ();
16578
16579   /* OK, now we have enough information to compute the distances.
16580      There must be an entry in these switch tables for each pair
16581      of registers in ELIMINABLE_REGS, even if some of the entries
16582      seem to be redundant or useless.  */
16583   switch (from)
16584     {
16585     case ARG_POINTER_REGNUM:
16586       switch (to)
16587         {
16588         case THUMB_HARD_FRAME_POINTER_REGNUM:
16589           return 0;
16590
16591         case FRAME_POINTER_REGNUM:
16592           /* This is the reverse of the soft frame pointer
16593              to hard frame pointer elimination below.  */
16594           return offsets->soft_frame - offsets->saved_args;
16595
16596         case ARM_HARD_FRAME_POINTER_REGNUM:
16597           /* This is only non-zero in the case where the static chain register
16598              is stored above the frame.  */
16599           return offsets->frame - offsets->saved_args - 4;
16600
16601         case STACK_POINTER_REGNUM:
16602           /* If nothing has been pushed on the stack at all
16603              then this will return -4.  This *is* correct!  */
16604           return offsets->outgoing_args - (offsets->saved_args + 4);
16605
16606         default:
16607           gcc_unreachable ();
16608         }
16609       gcc_unreachable ();
16610
16611     case FRAME_POINTER_REGNUM:
16612       switch (to)
16613         {
16614         case THUMB_HARD_FRAME_POINTER_REGNUM:
16615           return 0;
16616
16617         case ARM_HARD_FRAME_POINTER_REGNUM:
16618           /* The hard frame pointer points to the top entry in the
16619              stack frame.  The soft frame pointer to the bottom entry
16620              in the stack frame.  If there is no stack frame at all,
16621              then they are identical.  */
16622
16623           return offsets->frame - offsets->soft_frame;
16624
16625         case STACK_POINTER_REGNUM:
16626           return offsets->outgoing_args - offsets->soft_frame;
16627
16628         default:
16629           gcc_unreachable ();
16630         }
16631       gcc_unreachable ();
16632
16633     default:
16634       /* You cannot eliminate from the stack pointer.
16635          In theory you could eliminate from the hard frame
16636          pointer to the stack pointer, but this will never
16637          happen, since if a stack frame is not needed the
16638          hard frame pointer will never be used.  */
16639       gcc_unreachable ();
16640     }
16641 }
16642
16643 /* Given FROM and TO register numbers, say whether this elimination is
16644    allowed.  Frame pointer elimination is automatically handled.
16645
16646    All eliminations are permissible.  Note that ARG_POINTER_REGNUM and
16647    HARD_FRAME_POINTER_REGNUM are in fact the same thing.  If we need a frame
16648    pointer, we must eliminate FRAME_POINTER_REGNUM into
16649    HARD_FRAME_POINTER_REGNUM and not into STACK_POINTER_REGNUM or
16650    ARG_POINTER_REGNUM.  */
16651
16652 bool
16653 arm_can_eliminate (const int from, const int to)
16654 {
16655   return ((to == FRAME_POINTER_REGNUM && from == ARG_POINTER_REGNUM) ? false :
16656           (to == STACK_POINTER_REGNUM && frame_pointer_needed) ? false :
16657           (to == ARM_HARD_FRAME_POINTER_REGNUM && TARGET_THUMB) ? false :
16658           (to == THUMB_HARD_FRAME_POINTER_REGNUM && TARGET_ARM) ? false :
16659            true);
16660 }
16661
16662 /* Emit RTL to save coprocessor registers on function entry.  Returns the
16663    number of bytes pushed.  */
16664
16665 static int
16666 arm_save_coproc_regs(void)
16667 {
16668   int saved_size = 0;
16669   unsigned reg;
16670   unsigned start_reg;
16671   rtx insn;
16672
16673   for (reg = LAST_IWMMXT_REGNUM; reg >= FIRST_IWMMXT_REGNUM; reg--)
16674     if (df_regs_ever_live_p (reg) && ! call_used_regs[reg])
16675       {
16676         insn = gen_rtx_PRE_DEC (Pmode, stack_pointer_rtx);
16677         insn = gen_rtx_MEM (V2SImode, insn);
16678         insn = emit_set_insn (insn, gen_rtx_REG (V2SImode, reg));
16679         RTX_FRAME_RELATED_P (insn) = 1;
16680         saved_size += 8;
16681       }
16682
16683   /* Save any floating point call-saved registers used by this
16684      function.  */
16685   if (TARGET_FPA_EMU2)
16686     {
16687       for (reg = LAST_FPA_REGNUM; reg >= FIRST_FPA_REGNUM; reg--)
16688         if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
16689           {
16690             insn = gen_rtx_PRE_DEC (Pmode, stack_pointer_rtx);
16691             insn = gen_rtx_MEM (XFmode, insn);
16692             insn = emit_set_insn (insn, gen_rtx_REG (XFmode, reg));
16693             RTX_FRAME_RELATED_P (insn) = 1;
16694             saved_size += 12;
16695           }
16696     }
16697   else
16698     {
16699       start_reg = LAST_FPA_REGNUM;
16700
16701       for (reg = LAST_FPA_REGNUM; reg >= FIRST_FPA_REGNUM; reg--)
16702         {
16703           if (df_regs_ever_live_p (reg) && !call_used_regs[reg])
16704             {
16705               if (start_reg - reg == 3)
16706                 {
16707                   insn = emit_sfm (reg, 4);
16708                   RTX_FRAME_RELATED_P (insn) = 1;
16709                   saved_size += 48;
16710                   start_reg = reg - 1;
16711                 }
16712             }
16713           else
16714             {
16715               if (start_reg != reg)
16716                 {
16717                   insn = emit_sfm (reg + 1, start_reg - reg);
16718                   RTX_FRAME_RELATED_P (insn) = 1;
16719                   saved_size += (start_reg - reg) * 12;
16720                 }
16721               start_reg = reg - 1;
16722             }
16723         }
16724
16725       if (start_reg != reg)
16726         {
16727           insn = emit_sfm (reg + 1, start_reg - reg);
16728           saved_size += (start_reg - reg) * 12;
16729           RTX_FRAME_RELATED_P (insn) = 1;
16730         }
16731     }
16732   if (TARGET_HARD_FLOAT && TARGET_VFP)
16733     {
16734       start_reg = FIRST_VFP_REGNUM;
16735
16736       for (reg = FIRST_VFP_REGNUM; reg < LAST_VFP_REGNUM; reg += 2)
16737         {
16738           if ((!df_regs_ever_live_p (reg) || call_used_regs[reg])
16739               && (!df_regs_ever_live_p (reg + 1) || call_used_regs[reg + 1]))
16740             {
16741               if (start_reg != reg)
16742                 saved_size += vfp_emit_fstmd (start_reg,
16743                                               (reg - start_reg) / 2);
16744               start_reg = reg + 2;
16745             }
16746         }
16747       if (start_reg != reg)
16748         saved_size += vfp_emit_fstmd (start_reg,
16749                                       (reg - start_reg) / 2);
16750     }
16751   return saved_size;
16752 }
16753
16754
16755 /* Set the Thumb frame pointer from the stack pointer.  */
16756
16757 static void
16758 thumb_set_frame_pointer (arm_stack_offsets *offsets)
16759 {
16760   HOST_WIDE_INT amount;
16761   rtx insn, dwarf;
16762
16763   amount = offsets->outgoing_args - offsets->locals_base;
16764   if (amount < 1024)
16765     insn = emit_insn (gen_addsi3 (hard_frame_pointer_rtx,
16766                                   stack_pointer_rtx, GEN_INT (amount)));
16767   else
16768     {
16769       emit_insn (gen_movsi (hard_frame_pointer_rtx, GEN_INT (amount)));
16770       /* Thumb-2 RTL patterns expect sp as the first input.  Thumb-1
16771          expects the first two operands to be the same.  */
16772       if (TARGET_THUMB2)
16773         {
16774           insn = emit_insn (gen_addsi3 (hard_frame_pointer_rtx,
16775                                         stack_pointer_rtx,
16776                                         hard_frame_pointer_rtx));
16777         }
16778       else
16779         {
16780           insn = emit_insn (gen_addsi3 (hard_frame_pointer_rtx,
16781                                         hard_frame_pointer_rtx,
16782                                         stack_pointer_rtx));
16783         }
16784       dwarf = gen_rtx_SET (VOIDmode, hard_frame_pointer_rtx,
16785                            plus_constant (stack_pointer_rtx, amount));
16786       RTX_FRAME_RELATED_P (dwarf) = 1;
16787       add_reg_note (insn, REG_FRAME_RELATED_EXPR, dwarf);
16788     }
16789
16790   RTX_FRAME_RELATED_P (insn) = 1;
16791 }
16792
16793 /* Generate the prologue instructions for entry into an ARM or Thumb-2
16794    function.  */
16795 void
16796 arm_expand_prologue (void)
16797 {
16798   rtx amount;
16799   rtx insn;
16800   rtx ip_rtx;
16801   unsigned long live_regs_mask;
16802   unsigned long func_type;
16803   int fp_offset = 0;
16804   int saved_pretend_args = 0;
16805   int saved_regs = 0;
16806   unsigned HOST_WIDE_INT args_to_push;
16807   arm_stack_offsets *offsets;
16808
16809   func_type = arm_current_func_type ();
16810
16811   /* Naked functions don't have prologues.  */
16812   if (IS_NAKED (func_type))
16813     return;
16814
16815   /* Make a copy of c_f_p_a_s as we may need to modify it locally.  */
16816   args_to_push = crtl->args.pretend_args_size;
16817
16818   /* Compute which register we will have to save onto the stack.  */
16819   offsets = arm_get_frame_offsets ();
16820   live_regs_mask = offsets->saved_regs_mask;
16821
16822   ip_rtx = gen_rtx_REG (SImode, IP_REGNUM);
16823
16824   if (IS_STACKALIGN (func_type))
16825     {
16826       rtx r0, r1;
16827
16828       /* Handle a word-aligned stack pointer.  We generate the following:
16829
16830           mov r0, sp
16831           bic r1, r0, #7
16832           mov sp, r1
16833           <save and restore r0 in normal prologue/epilogue>
16834           mov sp, r0
16835           bx lr
16836
16837          The unwinder doesn't need to know about the stack realignment.
16838          Just tell it we saved SP in r0.  */
16839       gcc_assert (TARGET_THUMB2 && !arm_arch_notm && args_to_push == 0);
16840
16841       r0 = gen_rtx_REG (SImode, 0);
16842       r1 = gen_rtx_REG (SImode, 1);
16843
16844       insn = emit_insn (gen_movsi (r0, stack_pointer_rtx));
16845       RTX_FRAME_RELATED_P (insn) = 1;
16846       add_reg_note (insn, REG_CFA_REGISTER, NULL);
16847
16848       emit_insn (gen_andsi3 (r1, r0, GEN_INT (~(HOST_WIDE_INT)7)));
16849
16850       /* ??? The CFA changes here, which may cause GDB to conclude that it
16851          has entered a different function.  That said, the unwind info is
16852          correct, individually, before and after this instruction because
16853          we've described the save of SP, which will override the default
16854          handling of SP as restoring from the CFA.  */
16855       emit_insn (gen_movsi (stack_pointer_rtx, r1));
16856     }
16857
16858   /* For APCS frames, if IP register is clobbered
16859      when creating frame, save that register in a special
16860      way.  */
16861   if (TARGET_APCS_FRAME && frame_pointer_needed && TARGET_ARM)
16862     {
16863       if (IS_INTERRUPT (func_type))
16864         {
16865           /* Interrupt functions must not corrupt any registers.
16866              Creating a frame pointer however, corrupts the IP
16867              register, so we must push it first.  */
16868           emit_multi_reg_push (1 << IP_REGNUM);
16869
16870           /* Do not set RTX_FRAME_RELATED_P on this insn.
16871              The dwarf stack unwinding code only wants to see one
16872              stack decrement per function, and this is not it.  If
16873              this instruction is labeled as being part of the frame
16874              creation sequence then dwarf2out_frame_debug_expr will
16875              die when it encounters the assignment of IP to FP
16876              later on, since the use of SP here establishes SP as
16877              the CFA register and not IP.
16878
16879              Anyway this instruction is not really part of the stack
16880              frame creation although it is part of the prologue.  */
16881         }
16882       else if (IS_NESTED (func_type))
16883         {
16884           /* The Static chain register is the same as the IP register
16885              used as a scratch register during stack frame creation.
16886              To get around this need to find somewhere to store IP
16887              whilst the frame is being created.  We try the following
16888              places in order:
16889
16890                1. The last argument register.
16891                2. A slot on the stack above the frame.  (This only
16892                   works if the function is not a varargs function).
16893                3. Register r3, after pushing the argument registers
16894                   onto the stack.
16895
16896              Note - we only need to tell the dwarf2 backend about the SP
16897              adjustment in the second variant; the static chain register
16898              doesn't need to be unwound, as it doesn't contain a value
16899              inherited from the caller.  */
16900
16901           if (df_regs_ever_live_p (3) == false)
16902             insn = emit_set_insn (gen_rtx_REG (SImode, 3), ip_rtx);
16903           else if (args_to_push == 0)
16904             {
16905               rtx dwarf;
16906
16907               gcc_assert(arm_compute_static_chain_stack_bytes() == 4);
16908               saved_regs += 4;
16909
16910               insn = gen_rtx_PRE_DEC (SImode, stack_pointer_rtx);
16911               insn = emit_set_insn (gen_frame_mem (SImode, insn), ip_rtx);
16912               fp_offset = 4;
16913
16914               /* Just tell the dwarf backend that we adjusted SP.  */
16915               dwarf = gen_rtx_SET (VOIDmode, stack_pointer_rtx,
16916                                    plus_constant (stack_pointer_rtx,
16917                                                   -fp_offset));
16918               RTX_FRAME_RELATED_P (insn) = 1;
16919               add_reg_note (insn, REG_FRAME_RELATED_EXPR, dwarf);
16920             }
16921           else
16922             {
16923               /* Store the args on the stack.  */
16924               if (cfun->machine->uses_anonymous_args)
16925                 insn = emit_multi_reg_push
16926                   ((0xf0 >> (args_to_push / 4)) & 0xf);
16927               else
16928                 insn = emit_insn
16929                   (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx,
16930                                GEN_INT (- args_to_push)));
16931
16932               RTX_FRAME_RELATED_P (insn) = 1;
16933
16934               saved_pretend_args = 1;
16935               fp_offset = args_to_push;
16936               args_to_push = 0;
16937
16938               /* Now reuse r3 to preserve IP.  */
16939               emit_set_insn (gen_rtx_REG (SImode, 3), ip_rtx);
16940             }
16941         }
16942
16943       insn = emit_set_insn (ip_rtx,
16944                             plus_constant (stack_pointer_rtx, fp_offset));
16945       RTX_FRAME_RELATED_P (insn) = 1;
16946     }
16947
16948   if (args_to_push)
16949     {
16950       /* Push the argument registers, or reserve space for them.  */
16951       if (cfun->machine->uses_anonymous_args)
16952         insn = emit_multi_reg_push
16953           ((0xf0 >> (args_to_push / 4)) & 0xf);
16954       else
16955         insn = emit_insn
16956           (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx,
16957                        GEN_INT (- args_to_push)));
16958       RTX_FRAME_RELATED_P (insn) = 1;
16959     }
16960
16961   /* If this is an interrupt service routine, and the link register
16962      is going to be pushed, and we're not generating extra
16963      push of IP (needed when frame is needed and frame layout if apcs),
16964      subtracting four from LR now will mean that the function return
16965      can be done with a single instruction.  */
16966   if ((func_type == ARM_FT_ISR || func_type == ARM_FT_FIQ)
16967       && (live_regs_mask & (1 << LR_REGNUM)) != 0
16968       && !(frame_pointer_needed && TARGET_APCS_FRAME)
16969       && TARGET_ARM)
16970     {
16971       rtx lr = gen_rtx_REG (SImode, LR_REGNUM);
16972
16973       emit_set_insn (lr, plus_constant (lr, -4));
16974     }
16975
16976   if (live_regs_mask)
16977     {
16978       saved_regs += bit_count (live_regs_mask) * 4;
16979       if (optimize_size && !frame_pointer_needed
16980           && saved_regs == offsets->saved_regs - offsets->saved_args)
16981         {
16982           /* If no coprocessor registers are being pushed and we don't have
16983              to worry about a frame pointer then push extra registers to
16984              create the stack frame.  This is done is a way that does not
16985              alter the frame layout, so is independent of the epilogue.  */
16986           int n;
16987           int frame;
16988           n = 0;
16989           while (n < 8 && (live_regs_mask & (1 << n)) == 0)
16990             n++;
16991           frame = offsets->outgoing_args - (offsets->saved_args + saved_regs);
16992           if (frame && n * 4 >= frame)
16993             {
16994               n = frame / 4;
16995               live_regs_mask |= (1 << n) - 1;
16996               saved_regs += frame;
16997             }
16998         }
16999       insn = emit_multi_reg_push (live_regs_mask);
17000       RTX_FRAME_RELATED_P (insn) = 1;
17001     }
17002
17003   if (! IS_VOLATILE (func_type))
17004     saved_regs += arm_save_coproc_regs ();
17005
17006   if (frame_pointer_needed && TARGET_ARM)
17007     {
17008       /* Create the new frame pointer.  */
17009       if (TARGET_APCS_FRAME)
17010         {
17011           insn = GEN_INT (-(4 + args_to_push + fp_offset));
17012           insn = emit_insn (gen_addsi3 (hard_frame_pointer_rtx, ip_rtx, insn));
17013           RTX_FRAME_RELATED_P (insn) = 1;
17014
17015           if (IS_NESTED (func_type))
17016             {
17017               /* Recover the static chain register.  */
17018               if (!df_regs_ever_live_p (3)
17019                   || saved_pretend_args)
17020                 insn = gen_rtx_REG (SImode, 3);
17021               else /* if (crtl->args.pretend_args_size == 0) */
17022                 {
17023                   insn = plus_constant (hard_frame_pointer_rtx, 4);
17024                   insn = gen_frame_mem (SImode, insn);
17025                 }
17026               emit_set_insn (ip_rtx, insn);
17027               /* Add a USE to stop propagate_one_insn() from barfing.  */
17028               emit_insn (gen_prologue_use (ip_rtx));
17029             }
17030         }
17031       else
17032         {
17033           insn = GEN_INT (saved_regs - 4);
17034           insn = emit_insn (gen_addsi3 (hard_frame_pointer_rtx,
17035                                         stack_pointer_rtx, insn));
17036           RTX_FRAME_RELATED_P (insn) = 1;
17037         }
17038     }
17039
17040   if (flag_stack_usage_info)
17041     current_function_static_stack_size
17042       = offsets->outgoing_args - offsets->saved_args;
17043
17044   if (offsets->outgoing_args != offsets->saved_args + saved_regs)
17045     {
17046       /* This add can produce multiple insns for a large constant, so we
17047          need to get tricky.  */
17048       rtx last = get_last_insn ();
17049
17050       amount = GEN_INT (offsets->saved_args + saved_regs
17051                         - offsets->outgoing_args);
17052
17053       insn = emit_insn (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx,
17054                                     amount));
17055       do
17056         {
17057           last = last ? NEXT_INSN (last) : get_insns ();
17058           RTX_FRAME_RELATED_P (last) = 1;
17059         }
17060       while (last != insn);
17061
17062       /* If the frame pointer is needed, emit a special barrier that
17063          will prevent the scheduler from moving stores to the frame
17064          before the stack adjustment.  */
17065       if (frame_pointer_needed)
17066         insn = emit_insn (gen_stack_tie (stack_pointer_rtx,
17067                                          hard_frame_pointer_rtx));
17068     }
17069
17070
17071   if (frame_pointer_needed && TARGET_THUMB2)
17072     thumb_set_frame_pointer (offsets);
17073
17074   if (flag_pic && arm_pic_register != INVALID_REGNUM)
17075     {
17076       unsigned long mask;
17077
17078       mask = live_regs_mask;
17079       mask &= THUMB2_WORK_REGS;
17080       if (!IS_NESTED (func_type))
17081         mask |= (1 << IP_REGNUM);
17082       arm_load_pic_register (mask);
17083     }
17084
17085   /* If we are profiling, make sure no instructions are scheduled before
17086      the call to mcount.  Similarly if the user has requested no
17087      scheduling in the prolog.  Similarly if we want non-call exceptions
17088      using the EABI unwinder, to prevent faulting instructions from being
17089      swapped with a stack adjustment.  */
17090   if (crtl->profile || !TARGET_SCHED_PROLOG
17091       || (arm_except_unwind_info (&global_options) == UI_TARGET
17092           && cfun->can_throw_non_call_exceptions))
17093     emit_insn (gen_blockage ());
17094
17095   /* If the link register is being kept alive, with the return address in it,
17096      then make sure that it does not get reused by the ce2 pass.  */
17097   if ((live_regs_mask & (1 << LR_REGNUM)) == 0)
17098     cfun->machine->lr_save_eliminated = 1;
17099 }
17100 \f
17101 /* Print condition code to STREAM.  Helper function for arm_print_operand.  */
17102 static void
17103 arm_print_condition (FILE *stream)
17104 {
17105   if (arm_ccfsm_state == 3 || arm_ccfsm_state == 4)
17106     {
17107       /* Branch conversion is not implemented for Thumb-2.  */
17108       if (TARGET_THUMB)
17109         {
17110           output_operand_lossage ("predicated Thumb instruction");
17111           return;
17112         }
17113       if (current_insn_predicate != NULL)
17114         {
17115           output_operand_lossage
17116             ("predicated instruction in conditional sequence");
17117           return;
17118         }
17119
17120       fputs (arm_condition_codes[arm_current_cc], stream);
17121     }
17122   else if (current_insn_predicate)
17123     {
17124       enum arm_cond_code code;
17125
17126       if (TARGET_THUMB1)
17127         {
17128           output_operand_lossage ("predicated Thumb instruction");
17129           return;
17130         }
17131
17132       code = get_arm_condition_code (current_insn_predicate);
17133       fputs (arm_condition_codes[code], stream);
17134     }
17135 }
17136
17137
17138 /* If CODE is 'd', then the X is a condition operand and the instruction
17139    should only be executed if the condition is true.
17140    if CODE is 'D', then the X is a condition operand and the instruction
17141    should only be executed if the condition is false: however, if the mode
17142    of the comparison is CCFPEmode, then always execute the instruction -- we
17143    do this because in these circumstances !GE does not necessarily imply LT;
17144    in these cases the instruction pattern will take care to make sure that
17145    an instruction containing %d will follow, thereby undoing the effects of
17146    doing this instruction unconditionally.
17147    If CODE is 'N' then X is a floating point operand that must be negated
17148    before output.
17149    If CODE is 'B' then output a bitwise inverted value of X (a const int).
17150    If X is a REG and CODE is `M', output a ldm/stm style multi-reg.  */
17151 static void
17152 arm_print_operand (FILE *stream, rtx x, int code)
17153 {
17154   switch (code)
17155     {
17156     case '@':
17157       fputs (ASM_COMMENT_START, stream);
17158       return;
17159
17160     case '_':
17161       fputs (user_label_prefix, stream);
17162       return;
17163
17164     case '|':
17165       fputs (REGISTER_PREFIX, stream);
17166       return;
17167
17168     case '?':
17169       arm_print_condition (stream);
17170       return;
17171
17172     case '(':
17173       /* Nothing in unified syntax, otherwise the current condition code.  */
17174       if (!TARGET_UNIFIED_ASM)
17175         arm_print_condition (stream);
17176       break;
17177
17178     case ')':
17179       /* The current condition code in unified syntax, otherwise nothing.  */
17180       if (TARGET_UNIFIED_ASM)
17181         arm_print_condition (stream);
17182       break;
17183
17184     case '.':
17185       /* The current condition code for a condition code setting instruction.
17186          Preceded by 's' in unified syntax, otherwise followed by 's'.  */
17187       if (TARGET_UNIFIED_ASM)
17188         {
17189           fputc('s', stream);
17190           arm_print_condition (stream);
17191         }
17192       else
17193         {
17194           arm_print_condition (stream);
17195           fputc('s', stream);
17196         }
17197       return;
17198
17199     case '!':
17200       /* If the instruction is conditionally executed then print
17201          the current condition code, otherwise print 's'.  */
17202       gcc_assert (TARGET_THUMB2 && TARGET_UNIFIED_ASM);
17203       if (current_insn_predicate)
17204         arm_print_condition (stream);
17205       else
17206         fputc('s', stream);
17207       break;
17208
17209     /* %# is a "break" sequence. It doesn't output anything, but is used to
17210        separate e.g. operand numbers from following text, if that text consists
17211        of further digits which we don't want to be part of the operand
17212        number.  */
17213     case '#':
17214       return;
17215
17216     case 'N':
17217       {
17218         REAL_VALUE_TYPE r;
17219         REAL_VALUE_FROM_CONST_DOUBLE (r, x);
17220         r = real_value_negate (&r);
17221         fprintf (stream, "%s", fp_const_from_val (&r));
17222       }
17223       return;
17224
17225     /* An integer or symbol address without a preceding # sign.  */
17226     case 'c':
17227       switch (GET_CODE (x))
17228         {
17229         case CONST_INT:
17230           fprintf (stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (x));
17231           break;
17232
17233         case SYMBOL_REF:
17234           output_addr_const (stream, x);
17235           break;
17236
17237         case CONST:
17238           if (GET_CODE (XEXP (x, 0)) == PLUS
17239               && GET_CODE (XEXP (XEXP (x, 0), 0)) == SYMBOL_REF)
17240             {
17241               output_addr_const (stream, x);
17242               break;
17243             }
17244           /* Fall through.  */
17245
17246         default:
17247           output_operand_lossage ("Unsupported operand for code '%c'", code);
17248         }
17249       return;
17250
17251     case 'B':
17252       if (GET_CODE (x) == CONST_INT)
17253         {
17254           HOST_WIDE_INT val;
17255           val = ARM_SIGN_EXTEND (~INTVAL (x));
17256           fprintf (stream, HOST_WIDE_INT_PRINT_DEC, val);
17257         }
17258       else
17259         {
17260           putc ('~', stream);
17261           output_addr_const (stream, x);
17262         }
17263       return;
17264
17265     case 'L':
17266       /* The low 16 bits of an immediate constant.  */
17267       fprintf (stream, HOST_WIDE_INT_PRINT_DEC, INTVAL(x) & 0xffff);
17268       return;
17269
17270     case 'i':
17271       fprintf (stream, "%s", arithmetic_instr (x, 1));
17272       return;
17273
17274     /* Truncate Cirrus shift counts.  */
17275     case 's':
17276       if (GET_CODE (x) == CONST_INT)
17277         {
17278           fprintf (stream, HOST_WIDE_INT_PRINT_DEC, INTVAL (x) & 0x3f);
17279           return;
17280         }
17281       arm_print_operand (stream, x, 0);
17282       return;
17283
17284     case 'I':
17285       fprintf (stream, "%s", arithmetic_instr (x, 0));
17286       return;
17287
17288     case 'S':
17289       {
17290         HOST_WIDE_INT val;
17291         const char *shift;
17292
17293         if (!shift_operator (x, SImode))
17294           {
17295             output_operand_lossage ("invalid shift operand");
17296             break;
17297           }
17298
17299         shift = shift_op (x, &val);
17300
17301         if (shift)
17302           {
17303             fprintf (stream, ", %s ", shift);
17304             if (val == -1)
17305               arm_print_operand (stream, XEXP (x, 1), 0);
17306             else
17307               fprintf (stream, "#" HOST_WIDE_INT_PRINT_DEC, val);
17308           }
17309       }
17310       return;
17311
17312       /* An explanation of the 'Q', 'R' and 'H' register operands:
17313
17314          In a pair of registers containing a DI or DF value the 'Q'
17315          operand returns the register number of the register containing
17316          the least significant part of the value.  The 'R' operand returns
17317          the register number of the register containing the most
17318          significant part of the value.
17319
17320          The 'H' operand returns the higher of the two register numbers.
17321          On a run where WORDS_BIG_ENDIAN is true the 'H' operand is the
17322          same as the 'Q' operand, since the most significant part of the
17323          value is held in the lower number register.  The reverse is true
17324          on systems where WORDS_BIG_ENDIAN is false.
17325
17326          The purpose of these operands is to distinguish between cases
17327          where the endian-ness of the values is important (for example
17328          when they are added together), and cases where the endian-ness
17329          is irrelevant, but the order of register operations is important.
17330          For example when loading a value from memory into a register
17331          pair, the endian-ness does not matter.  Provided that the value
17332          from the lower memory address is put into the lower numbered
17333          register, and the value from the higher address is put into the
17334          higher numbered register, the load will work regardless of whether
17335          the value being loaded is big-wordian or little-wordian.  The
17336          order of the two register loads can matter however, if the address
17337          of the memory location is actually held in one of the registers
17338          being overwritten by the load.
17339
17340          The 'Q' and 'R' constraints are also available for 64-bit
17341          constants.  */
17342     case 'Q':
17343       if (GET_CODE (x) == CONST_INT || GET_CODE (x) == CONST_DOUBLE)
17344         {
17345           rtx part = gen_lowpart (SImode, x);
17346           fprintf (stream, "#" HOST_WIDE_INT_PRINT_DEC, INTVAL (part));
17347           return;
17348         }
17349
17350       if (GET_CODE (x) != REG || REGNO (x) > LAST_ARM_REGNUM)
17351         {
17352           output_operand_lossage ("invalid operand for code '%c'", code);
17353           return;
17354         }
17355
17356       asm_fprintf (stream, "%r", REGNO (x) + (WORDS_BIG_ENDIAN ? 1 : 0));
17357       return;
17358
17359     case 'R':
17360       if (GET_CODE (x) == CONST_INT || GET_CODE (x) == CONST_DOUBLE)
17361         {
17362           enum machine_mode mode = GET_MODE (x);
17363           rtx part;
17364
17365           if (mode == VOIDmode)
17366             mode = DImode;
17367           part = gen_highpart_mode (SImode, mode, x);
17368           fprintf (stream, "#" HOST_WIDE_INT_PRINT_DEC, INTVAL (part));
17369           return;
17370         }
17371
17372       if (GET_CODE (x) != REG || REGNO (x) > LAST_ARM_REGNUM)
17373         {
17374           output_operand_lossage ("invalid operand for code '%c'", code);
17375           return;
17376         }
17377
17378       asm_fprintf (stream, "%r", REGNO (x) + (WORDS_BIG_ENDIAN ? 0 : 1));
17379       return;
17380
17381     case 'H':
17382       if (GET_CODE (x) != REG || REGNO (x) > LAST_ARM_REGNUM)
17383         {
17384           output_operand_lossage ("invalid operand for code '%c'", code);
17385           return;
17386         }
17387
17388       asm_fprintf (stream, "%r", REGNO (x) + 1);
17389       return;
17390
17391     case 'J':
17392       if (GET_CODE (x) != REG || REGNO (x) > LAST_ARM_REGNUM)
17393         {
17394           output_operand_lossage ("invalid operand for code '%c'", code);
17395           return;
17396         }
17397
17398       asm_fprintf (stream, "%r", REGNO (x) + (WORDS_BIG_ENDIAN ? 3 : 2));
17399       return;
17400
17401     case 'K':
17402       if (GET_CODE (x) != REG || REGNO (x) > LAST_ARM_REGNUM)
17403         {
17404           output_operand_lossage ("invalid operand for code '%c'", code);
17405           return;
17406         }
17407
17408       asm_fprintf (stream, "%r", REGNO (x) + (WORDS_BIG_ENDIAN ? 2 : 3));
17409       return;
17410
17411     case 'm':
17412       asm_fprintf (stream, "%r",
17413                    GET_CODE (XEXP (x, 0)) == REG
17414                    ? REGNO (XEXP (x, 0)) : REGNO (XEXP (XEXP (x, 0), 0)));
17415       return;
17416
17417     case 'M':
17418       asm_fprintf (stream, "{%r-%r}",
17419                    REGNO (x),
17420                    REGNO (x) + ARM_NUM_REGS (GET_MODE (x)) - 1);
17421       return;
17422
17423     /* Like 'M', but writing doubleword vector registers, for use by Neon
17424        insns.  */
17425     case 'h':
17426       {
17427         int regno = (REGNO (x) - FIRST_VFP_REGNUM) / 2;
17428         int numregs = ARM_NUM_REGS (GET_MODE (x)) / 2;
17429         if (numregs == 1)
17430           asm_fprintf (stream, "{d%d}", regno);
17431         else
17432           asm_fprintf (stream, "{d%d-d%d}", regno, regno + numregs - 1);
17433       }
17434       return;
17435
17436     case 'd':
17437       /* CONST_TRUE_RTX means always -- that's the default.  */
17438       if (x == const_true_rtx)
17439         return;
17440
17441       if (!COMPARISON_P (x))
17442         {
17443           output_operand_lossage ("invalid operand for code '%c'", code);
17444           return;
17445         }
17446
17447       fputs (arm_condition_codes[get_arm_condition_code (x)],
17448              stream);
17449       return;
17450
17451     case 'D':
17452       /* CONST_TRUE_RTX means not always -- i.e. never.  We shouldn't ever
17453          want to do that.  */
17454       if (x == const_true_rtx)
17455         {
17456           output_operand_lossage ("instruction never executed");
17457           return;
17458         }
17459       if (!COMPARISON_P (x))
17460         {
17461           output_operand_lossage ("invalid operand for code '%c'", code);
17462           return;
17463         }
17464
17465       fputs (arm_condition_codes[ARM_INVERSE_CONDITION_CODE
17466                                  (get_arm_condition_code (x))],
17467              stream);
17468       return;
17469
17470     /* Cirrus registers can be accessed in a variety of ways:
17471          single floating point (f)
17472          double floating point (d)
17473          32bit integer         (fx)
17474          64bit integer         (dx).  */
17475     case 'W':                   /* Cirrus register in F mode.  */
17476     case 'X':                   /* Cirrus register in D mode.  */
17477     case 'Y':                   /* Cirrus register in FX mode.  */
17478     case 'Z':                   /* Cirrus register in DX mode.  */
17479       gcc_assert (GET_CODE (x) == REG
17480                   && REGNO_REG_CLASS (REGNO (x)) == CIRRUS_REGS);
17481
17482       fprintf (stream, "mv%s%s",
17483                code == 'W' ? "f"
17484                : code == 'X' ? "d"
17485                : code == 'Y' ? "fx" : "dx", reg_names[REGNO (x)] + 2);
17486
17487       return;
17488
17489     /* Print cirrus register in the mode specified by the register's mode.  */
17490     case 'V':
17491       {
17492         int mode = GET_MODE (x);
17493
17494         if (GET_CODE (x) != REG || REGNO_REG_CLASS (REGNO (x)) != CIRRUS_REGS)
17495           {
17496             output_operand_lossage ("invalid operand for code '%c'", code);
17497             return;
17498           }
17499
17500         fprintf (stream, "mv%s%s",
17501                  mode == DFmode ? "d"
17502                  : mode == SImode ? "fx"
17503                  : mode == DImode ? "dx"
17504                  : "f", reg_names[REGNO (x)] + 2);
17505
17506         return;
17507       }
17508
17509     case 'U':
17510       if (GET_CODE (x) != REG
17511           || REGNO (x) < FIRST_IWMMXT_GR_REGNUM
17512           || REGNO (x) > LAST_IWMMXT_GR_REGNUM)
17513         /* Bad value for wCG register number.  */
17514         {
17515           output_operand_lossage ("invalid operand for code '%c'", code);
17516           return;
17517         }
17518
17519       else
17520         fprintf (stream, "%d", REGNO (x) - FIRST_IWMMXT_GR_REGNUM);
17521       return;
17522
17523       /* Print an iWMMXt control register name.  */
17524     case 'w':
17525       if (GET_CODE (x) != CONST_INT
17526           || INTVAL (x) < 0
17527           || INTVAL (x) >= 16)
17528         /* Bad value for wC register number.  */
17529         {
17530           output_operand_lossage ("invalid operand for code '%c'", code);
17531           return;
17532         }
17533
17534       else
17535         {
17536           static const char * wc_reg_names [16] =
17537             {
17538               "wCID",  "wCon",  "wCSSF", "wCASF",
17539               "wC4",   "wC5",   "wC6",   "wC7",
17540               "wCGR0", "wCGR1", "wCGR2", "wCGR3",
17541               "wC12",  "wC13",  "wC14",  "wC15"
17542             };
17543
17544           fprintf (stream, wc_reg_names [INTVAL (x)]);
17545         }
17546       return;
17547
17548     /* Print the high single-precision register of a VFP double-precision
17549        register.  */
17550     case 'p':
17551       {
17552         int mode = GET_MODE (x);
17553         int regno;
17554
17555         if (GET_MODE_SIZE (mode) != 8 || GET_CODE (x) != REG)
17556           {
17557             output_operand_lossage ("invalid operand for code '%c'", code);
17558             return;
17559           }
17560
17561         regno = REGNO (x);
17562         if (!VFP_REGNO_OK_FOR_DOUBLE (regno))
17563           {
17564             output_operand_lossage ("invalid operand for code '%c'", code);
17565             return;
17566           }
17567
17568         fprintf (stream, "s%d", regno - FIRST_VFP_REGNUM + 1);
17569       }
17570       return;
17571
17572     /* Print a VFP/Neon double precision or quad precision register name.  */
17573     case 'P':
17574     case 'q':
17575       {
17576         int mode = GET_MODE (x);
17577         int is_quad = (code == 'q');
17578         int regno;
17579
17580         if (GET_MODE_SIZE (mode) != (is_quad ? 16 : 8))
17581           {
17582             output_operand_lossage ("invalid operand for code '%c'", code);
17583             return;
17584           }
17585
17586         if (GET_CODE (x) != REG
17587             || !IS_VFP_REGNUM (REGNO (x)))
17588           {
17589             output_operand_lossage ("invalid operand for code '%c'", code);
17590             return;
17591           }
17592
17593         regno = REGNO (x);
17594         if ((is_quad && !NEON_REGNO_OK_FOR_QUAD (regno))
17595             || (!is_quad && !VFP_REGNO_OK_FOR_DOUBLE (regno)))
17596           {
17597             output_operand_lossage ("invalid operand for code '%c'", code);
17598             return;
17599           }
17600
17601         fprintf (stream, "%c%d", is_quad ? 'q' : 'd',
17602           (regno - FIRST_VFP_REGNUM) >> (is_quad ? 2 : 1));
17603       }
17604       return;
17605
17606     /* These two codes print the low/high doubleword register of a Neon quad
17607        register, respectively.  For pair-structure types, can also print
17608        low/high quadword registers.  */
17609     case 'e':
17610     case 'f':
17611       {
17612         int mode = GET_MODE (x);
17613         int regno;
17614
17615         if ((GET_MODE_SIZE (mode) != 16
17616              && GET_MODE_SIZE (mode) != 32) || GET_CODE (x) != REG)
17617           {
17618             output_operand_lossage ("invalid operand for code '%c'", code);
17619             return;
17620           }
17621
17622         regno = REGNO (x);
17623         if (!NEON_REGNO_OK_FOR_QUAD (regno))
17624           {
17625             output_operand_lossage ("invalid operand for code '%c'", code);
17626             return;
17627           }
17628
17629         if (GET_MODE_SIZE (mode) == 16)
17630           fprintf (stream, "d%d", ((regno - FIRST_VFP_REGNUM) >> 1)
17631                                   + (code == 'f' ? 1 : 0));
17632         else
17633           fprintf (stream, "q%d", ((regno - FIRST_VFP_REGNUM) >> 2)
17634                                   + (code == 'f' ? 1 : 0));
17635       }
17636       return;
17637
17638     /* Print a VFPv3 floating-point constant, represented as an integer
17639        index.  */
17640     case 'G':
17641       {
17642         int index = vfp3_const_double_index (x);
17643         gcc_assert (index != -1);
17644         fprintf (stream, "%d", index);
17645       }
17646       return;
17647
17648     /* Print bits representing opcode features for Neon.
17649
17650        Bit 0 is 1 for signed, 0 for unsigned.  Floats count as signed
17651        and polynomials as unsigned.
17652
17653        Bit 1 is 1 for floats and polynomials, 0 for ordinary integers.
17654
17655        Bit 2 is 1 for rounding functions, 0 otherwise.  */
17656
17657     /* Identify the type as 's', 'u', 'p' or 'f'.  */
17658     case 'T':
17659       {
17660         HOST_WIDE_INT bits = INTVAL (x);
17661         fputc ("uspf"[bits & 3], stream);
17662       }
17663       return;
17664
17665     /* Likewise, but signed and unsigned integers are both 'i'.  */
17666     case 'F':
17667       {
17668         HOST_WIDE_INT bits = INTVAL (x);
17669         fputc ("iipf"[bits & 3], stream);
17670       }
17671       return;
17672
17673     /* As for 'T', but emit 'u' instead of 'p'.  */
17674     case 't':
17675       {
17676         HOST_WIDE_INT bits = INTVAL (x);
17677         fputc ("usuf"[bits & 3], stream);
17678       }
17679       return;
17680
17681     /* Bit 2: rounding (vs none).  */
17682     case 'O':
17683       {
17684         HOST_WIDE_INT bits = INTVAL (x);
17685         fputs ((bits & 4) != 0 ? "r" : "", stream);
17686       }
17687       return;
17688
17689     /* Memory operand for vld1/vst1 instruction.  */
17690     case 'A':
17691       {
17692         rtx addr;
17693         bool postinc = FALSE;
17694         unsigned align, memsize, align_bits;
17695
17696         gcc_assert (GET_CODE (x) == MEM);
17697         addr = XEXP (x, 0);
17698         if (GET_CODE (addr) == POST_INC)
17699           {
17700             postinc = 1;
17701             addr = XEXP (addr, 0);
17702           }
17703         asm_fprintf (stream, "[%r", REGNO (addr));
17704
17705         /* We know the alignment of this access, so we can emit a hint in the
17706            instruction (for some alignments) as an aid to the memory subsystem
17707            of the target.  */
17708         align = MEM_ALIGN (x) >> 3;
17709         memsize = MEM_SIZE (x);
17710
17711         /* Only certain alignment specifiers are supported by the hardware.  */
17712         if (memsize == 16 && (align % 32) == 0)
17713           align_bits = 256;
17714         else if ((memsize == 8 || memsize == 16) && (align % 16) == 0)
17715           align_bits = 128;
17716         else if ((align % 8) == 0)
17717           align_bits = 64;
17718         else
17719           align_bits = 0;
17720
17721         if (align_bits != 0)
17722           asm_fprintf (stream, ":%d", align_bits);
17723
17724         asm_fprintf (stream, "]");
17725
17726         if (postinc)
17727           fputs("!", stream);
17728       }
17729       return;
17730
17731     case 'C':
17732       {
17733         rtx addr;
17734
17735         gcc_assert (GET_CODE (x) == MEM);
17736         addr = XEXP (x, 0);
17737         gcc_assert (GET_CODE (addr) == REG);
17738         asm_fprintf (stream, "[%r]", REGNO (addr));
17739       }
17740       return;
17741
17742     /* Translate an S register number into a D register number and element index.  */
17743     case 'y':
17744       {
17745         int mode = GET_MODE (x);
17746         int regno;
17747
17748         if (GET_MODE_SIZE (mode) != 4 || GET_CODE (x) != REG)
17749           {
17750             output_operand_lossage ("invalid operand for code '%c'", code);
17751             return;
17752           }
17753
17754         regno = REGNO (x);
17755         if (!VFP_REGNO_OK_FOR_SINGLE (regno))
17756           {
17757             output_operand_lossage ("invalid operand for code '%c'", code);
17758             return;
17759           }
17760
17761         regno = regno - FIRST_VFP_REGNUM;
17762         fprintf (stream, "d%d[%d]", regno / 2, regno % 2);
17763       }
17764       return;
17765
17766     case 'v':
17767         gcc_assert (GET_CODE (x) == CONST_DOUBLE);
17768         fprintf (stream, "#%d", vfp3_const_double_for_fract_bits (x));
17769         return;
17770
17771     /* Register specifier for vld1.16/vst1.16.  Translate the S register
17772        number into a D register number and element index.  */
17773     case 'z':
17774       {
17775         int mode = GET_MODE (x);
17776         int regno;
17777
17778         if (GET_MODE_SIZE (mode) != 2 || GET_CODE (x) != REG)
17779           {
17780             output_operand_lossage ("invalid operand for code '%c'", code);
17781             return;
17782           }
17783
17784         regno = REGNO (x);
17785         if (!VFP_REGNO_OK_FOR_SINGLE (regno))
17786           {
17787             output_operand_lossage ("invalid operand for code '%c'", code);
17788             return;
17789           }
17790
17791         regno = regno - FIRST_VFP_REGNUM;
17792         fprintf (stream, "d%d[%d]", regno/2, ((regno % 2) ? 2 : 0));
17793       }
17794       return;
17795
17796     default:
17797       if (x == 0)
17798         {
17799           output_operand_lossage ("missing operand");
17800           return;
17801         }
17802
17803       switch (GET_CODE (x))
17804         {
17805         case REG:
17806           asm_fprintf (stream, "%r", REGNO (x));
17807           break;
17808
17809         case MEM:
17810           output_memory_reference_mode = GET_MODE (x);
17811           output_address (XEXP (x, 0));
17812           break;
17813
17814         case CONST_DOUBLE:
17815           if (TARGET_NEON)
17816             {
17817               char fpstr[20];
17818               real_to_decimal (fpstr, CONST_DOUBLE_REAL_VALUE (x),
17819                                sizeof (fpstr), 0, 1);
17820               fprintf (stream, "#%s", fpstr);
17821             }
17822           else
17823             fprintf (stream, "#%s", fp_immediate_constant (x));
17824           break;
17825
17826         default:
17827           gcc_assert (GET_CODE (x) != NEG);
17828           fputc ('#', stream);
17829           if (GET_CODE (x) == HIGH)
17830             {
17831               fputs (":lower16:", stream);
17832               x = XEXP (x, 0);
17833             }
17834
17835           output_addr_const (stream, x);
17836           break;
17837         }
17838     }
17839 }
17840 \f
17841 /* Target hook for printing a memory address.  */
17842 static void
17843 arm_print_operand_address (FILE *stream, rtx x)
17844 {
17845   if (TARGET_32BIT)
17846     {
17847       int is_minus = GET_CODE (x) == MINUS;
17848
17849       if (GET_CODE (x) == REG)
17850         asm_fprintf (stream, "[%r, #0]", REGNO (x));
17851       else if (GET_CODE (x) == PLUS || is_minus)
17852         {
17853           rtx base = XEXP (x, 0);
17854           rtx index = XEXP (x, 1);
17855           HOST_WIDE_INT offset = 0;
17856           if (GET_CODE (base) != REG
17857               || (GET_CODE (index) == REG && REGNO (index) == SP_REGNUM))
17858             {
17859               /* Ensure that BASE is a register.  */
17860               /* (one of them must be).  */
17861               /* Also ensure the SP is not used as in index register.  */
17862               rtx temp = base;
17863               base = index;
17864               index = temp;
17865             }
17866           switch (GET_CODE (index))
17867             {
17868             case CONST_INT:
17869               offset = INTVAL (index);
17870               if (is_minus)
17871                 offset = -offset;
17872               asm_fprintf (stream, "[%r, #%wd]",
17873                            REGNO (base), offset);
17874               break;
17875
17876             case REG:
17877               asm_fprintf (stream, "[%r, %s%r]",
17878                            REGNO (base), is_minus ? "-" : "",
17879                            REGNO (index));
17880               break;
17881
17882             case MULT:
17883             case ASHIFTRT:
17884             case LSHIFTRT:
17885             case ASHIFT:
17886             case ROTATERT:
17887               {
17888                 asm_fprintf (stream, "[%r, %s%r",
17889                              REGNO (base), is_minus ? "-" : "",
17890                              REGNO (XEXP (index, 0)));
17891                 arm_print_operand (stream, index, 'S');
17892                 fputs ("]", stream);
17893                 break;
17894               }
17895
17896             default:
17897               gcc_unreachable ();
17898             }
17899         }
17900       else if (GET_CODE (x) == PRE_INC || GET_CODE (x) == POST_INC
17901                || GET_CODE (x) == PRE_DEC || GET_CODE (x) == POST_DEC)
17902         {
17903           extern enum machine_mode output_memory_reference_mode;
17904
17905           gcc_assert (GET_CODE (XEXP (x, 0)) == REG);
17906
17907           if (GET_CODE (x) == PRE_DEC || GET_CODE (x) == PRE_INC)
17908             asm_fprintf (stream, "[%r, #%s%d]!",
17909                          REGNO (XEXP (x, 0)),
17910                          GET_CODE (x) == PRE_DEC ? "-" : "",
17911                          GET_MODE_SIZE (output_memory_reference_mode));
17912           else
17913             asm_fprintf (stream, "[%r], #%s%d",
17914                          REGNO (XEXP (x, 0)),
17915                          GET_CODE (x) == POST_DEC ? "-" : "",
17916                          GET_MODE_SIZE (output_memory_reference_mode));
17917         }
17918       else if (GET_CODE (x) == PRE_MODIFY)
17919         {
17920           asm_fprintf (stream, "[%r, ", REGNO (XEXP (x, 0)));
17921           if (GET_CODE (XEXP (XEXP (x, 1), 1)) == CONST_INT)
17922             asm_fprintf (stream, "#%wd]!",
17923                          INTVAL (XEXP (XEXP (x, 1), 1)));
17924           else
17925             asm_fprintf (stream, "%r]!",
17926                          REGNO (XEXP (XEXP (x, 1), 1)));
17927         }
17928       else if (GET_CODE (x) == POST_MODIFY)
17929         {
17930           asm_fprintf (stream, "[%r], ", REGNO (XEXP (x, 0)));
17931           if (GET_CODE (XEXP (XEXP (x, 1), 1)) == CONST_INT)
17932             asm_fprintf (stream, "#%wd",
17933                          INTVAL (XEXP (XEXP (x, 1), 1)));
17934           else
17935             asm_fprintf (stream, "%r",
17936                          REGNO (XEXP (XEXP (x, 1), 1)));
17937         }
17938       else output_addr_const (stream, x);
17939     }
17940   else
17941     {
17942       if (GET_CODE (x) == REG)
17943         asm_fprintf (stream, "[%r]", REGNO (x));
17944       else if (GET_CODE (x) == POST_INC)
17945         asm_fprintf (stream, "%r!", REGNO (XEXP (x, 0)));
17946       else if (GET_CODE (x) == PLUS)
17947         {
17948           gcc_assert (GET_CODE (XEXP (x, 0)) == REG);
17949           if (GET_CODE (XEXP (x, 1)) == CONST_INT)
17950             asm_fprintf (stream, "[%r, #%wd]",
17951                          REGNO (XEXP (x, 0)),
17952                          INTVAL (XEXP (x, 1)));
17953           else
17954             asm_fprintf (stream, "[%r, %r]",
17955                          REGNO (XEXP (x, 0)),
17956                          REGNO (XEXP (x, 1)));
17957         }
17958       else
17959         output_addr_const (stream, x);
17960     }
17961 }
17962 \f
17963 /* Target hook for indicating whether a punctuation character for
17964    TARGET_PRINT_OPERAND is valid.  */
17965 static bool
17966 arm_print_operand_punct_valid_p (unsigned char code)
17967 {
17968   return (code == '@' || code == '|' || code == '.'
17969           || code == '(' || code == ')' || code == '#'
17970           || (TARGET_32BIT && (code == '?'))
17971           || (TARGET_THUMB2 && (code == '!'))
17972           || (TARGET_THUMB && (code == '_')));
17973 }
17974 \f
17975 /* Target hook for assembling integer objects.  The ARM version needs to
17976    handle word-sized values specially.  */
17977 static bool
17978 arm_assemble_integer (rtx x, unsigned int size, int aligned_p)
17979 {
17980   enum machine_mode mode;
17981
17982   if (size == UNITS_PER_WORD && aligned_p)
17983     {
17984       fputs ("\t.word\t", asm_out_file);
17985       output_addr_const (asm_out_file, x);
17986
17987       /* Mark symbols as position independent.  We only do this in the
17988          .text segment, not in the .data segment.  */
17989       if (NEED_GOT_RELOC && flag_pic && making_const_table &&
17990           (GET_CODE (x) == SYMBOL_REF || GET_CODE (x) == LABEL_REF))
17991         {
17992           /* See legitimize_pic_address for an explanation of the
17993              TARGET_VXWORKS_RTP check.  */
17994           if (TARGET_VXWORKS_RTP
17995               || (GET_CODE (x) == SYMBOL_REF && !SYMBOL_REF_LOCAL_P (x)))
17996             fputs ("(GOT)", asm_out_file);
17997           else
17998             fputs ("(GOTOFF)", asm_out_file);
17999         }
18000       fputc ('\n', asm_out_file);
18001       return true;
18002     }
18003
18004   mode = GET_MODE (x);
18005
18006   if (arm_vector_mode_supported_p (mode))
18007     {
18008       int i, units;
18009
18010       gcc_assert (GET_CODE (x) == CONST_VECTOR);
18011
18012       units = CONST_VECTOR_NUNITS (x);
18013       size = GET_MODE_SIZE (GET_MODE_INNER (mode));
18014
18015       if (GET_MODE_CLASS (mode) == MODE_VECTOR_INT)
18016         for (i = 0; i < units; i++)
18017           {
18018             rtx elt = CONST_VECTOR_ELT (x, i);
18019             assemble_integer
18020               (elt, size, i == 0 ? BIGGEST_ALIGNMENT : size * BITS_PER_UNIT, 1);
18021           }
18022       else
18023         for (i = 0; i < units; i++)
18024           {
18025             rtx elt = CONST_VECTOR_ELT (x, i);
18026             REAL_VALUE_TYPE rval;
18027
18028             REAL_VALUE_FROM_CONST_DOUBLE (rval, elt);
18029
18030             assemble_real
18031               (rval, GET_MODE_INNER (mode),
18032               i == 0 ? BIGGEST_ALIGNMENT : size * BITS_PER_UNIT);
18033           }
18034
18035       return true;
18036     }
18037
18038   return default_assemble_integer (x, size, aligned_p);
18039 }
18040
18041 static void
18042 arm_elf_asm_cdtor (rtx symbol, int priority, bool is_ctor)
18043 {
18044   section *s;
18045
18046   if (!TARGET_AAPCS_BASED)
18047     {
18048       (is_ctor ?
18049        default_named_section_asm_out_constructor
18050        : default_named_section_asm_out_destructor) (symbol, priority);
18051       return;
18052     }
18053
18054   /* Put these in the .init_array section, using a special relocation.  */
18055   if (priority != DEFAULT_INIT_PRIORITY)
18056     {
18057       char buf[18];
18058       sprintf (buf, "%s.%.5u",
18059                is_ctor ? ".init_array" : ".fini_array",
18060                priority);
18061       s = get_section (buf, SECTION_WRITE, NULL_TREE);
18062     }
18063   else if (is_ctor)
18064     s = ctors_section;
18065   else
18066     s = dtors_section;
18067
18068   switch_to_section (s);
18069   assemble_align (POINTER_SIZE);
18070   fputs ("\t.word\t", asm_out_file);
18071   output_addr_const (asm_out_file, symbol);
18072   fputs ("(target1)\n", asm_out_file);
18073 }
18074
18075 /* Add a function to the list of static constructors.  */
18076
18077 static void
18078 arm_elf_asm_constructor (rtx symbol, int priority)
18079 {
18080   arm_elf_asm_cdtor (symbol, priority, /*is_ctor=*/true);
18081 }
18082
18083 /* Add a function to the list of static destructors.  */
18084
18085 static void
18086 arm_elf_asm_destructor (rtx symbol, int priority)
18087 {
18088   arm_elf_asm_cdtor (symbol, priority, /*is_ctor=*/false);
18089 }
18090 \f
18091 /* A finite state machine takes care of noticing whether or not instructions
18092    can be conditionally executed, and thus decrease execution time and code
18093    size by deleting branch instructions.  The fsm is controlled by
18094    final_prescan_insn, and controls the actions of ASM_OUTPUT_OPCODE.  */
18095
18096 /* The state of the fsm controlling condition codes are:
18097    0: normal, do nothing special
18098    1: make ASM_OUTPUT_OPCODE not output this instruction
18099    2: make ASM_OUTPUT_OPCODE not output this instruction
18100    3: make instructions conditional
18101    4: make instructions conditional
18102
18103    State transitions (state->state by whom under condition):
18104    0 -> 1 final_prescan_insn if the `target' is a label
18105    0 -> 2 final_prescan_insn if the `target' is an unconditional branch
18106    1 -> 3 ASM_OUTPUT_OPCODE after not having output the conditional branch
18107    2 -> 4 ASM_OUTPUT_OPCODE after not having output the conditional branch
18108    3 -> 0 (*targetm.asm_out.internal_label) if the `target' label is reached
18109           (the target label has CODE_LABEL_NUMBER equal to arm_target_label).
18110    4 -> 0 final_prescan_insn if the `target' unconditional branch is reached
18111           (the target insn is arm_target_insn).
18112
18113    If the jump clobbers the conditions then we use states 2 and 4.
18114
18115    A similar thing can be done with conditional return insns.
18116
18117    XXX In case the `target' is an unconditional branch, this conditionalising
18118    of the instructions always reduces code size, but not always execution
18119    time.  But then, I want to reduce the code size to somewhere near what
18120    /bin/cc produces.  */
18121
18122 /* In addition to this, state is maintained for Thumb-2 COND_EXEC
18123    instructions.  When a COND_EXEC instruction is seen the subsequent
18124    instructions are scanned so that multiple conditional instructions can be
18125    combined into a single IT block.  arm_condexec_count and arm_condexec_mask
18126    specify the length and true/false mask for the IT block.  These will be
18127    decremented/zeroed by arm_asm_output_opcode as the insns are output.  */
18128
18129 /* Returns the index of the ARM condition code string in
18130    `arm_condition_codes', or ARM_NV if the comparison is invalid.
18131    COMPARISON should be an rtx like `(eq (...) (...))'.  */
18132
18133 enum arm_cond_code
18134 maybe_get_arm_condition_code (rtx comparison)
18135 {
18136   enum machine_mode mode = GET_MODE (XEXP (comparison, 0));
18137   enum arm_cond_code code;
18138   enum rtx_code comp_code = GET_CODE (comparison);
18139
18140   if (GET_MODE_CLASS (mode) != MODE_CC)
18141     mode = SELECT_CC_MODE (comp_code, XEXP (comparison, 0),
18142                            XEXP (comparison, 1));
18143
18144   switch (mode)
18145     {
18146     case CC_DNEmode: code = ARM_NE; goto dominance;
18147     case CC_DEQmode: code = ARM_EQ; goto dominance;
18148     case CC_DGEmode: code = ARM_GE; goto dominance;
18149     case CC_DGTmode: code = ARM_GT; goto dominance;
18150     case CC_DLEmode: code = ARM_LE; goto dominance;
18151     case CC_DLTmode: code = ARM_LT; goto dominance;
18152     case CC_DGEUmode: code = ARM_CS; goto dominance;
18153     case CC_DGTUmode: code = ARM_HI; goto dominance;
18154     case CC_DLEUmode: code = ARM_LS; goto dominance;
18155     case CC_DLTUmode: code = ARM_CC;
18156
18157     dominance:
18158       if (comp_code == EQ)
18159         return ARM_INVERSE_CONDITION_CODE (code);
18160       if (comp_code == NE)
18161         return code;
18162       return ARM_NV;
18163
18164     case CC_NOOVmode:
18165       switch (comp_code)
18166         {
18167         case NE: return ARM_NE;
18168         case EQ: return ARM_EQ;
18169         case GE: return ARM_PL;
18170         case LT: return ARM_MI;
18171         default: return ARM_NV;
18172         }
18173
18174     case CC_Zmode:
18175       switch (comp_code)
18176         {
18177         case NE: return ARM_NE;
18178         case EQ: return ARM_EQ;
18179         default: return ARM_NV;
18180         }
18181
18182     case CC_Nmode:
18183       switch (comp_code)
18184         {
18185         case NE: return ARM_MI;
18186         case EQ: return ARM_PL;
18187         default: return ARM_NV;
18188         }
18189
18190     case CCFPEmode:
18191     case CCFPmode:
18192       /* These encodings assume that AC=1 in the FPA system control
18193          byte.  This allows us to handle all cases except UNEQ and
18194          LTGT.  */
18195       switch (comp_code)
18196         {
18197         case GE: return ARM_GE;
18198         case GT: return ARM_GT;
18199         case LE: return ARM_LS;
18200         case LT: return ARM_MI;
18201         case NE: return ARM_NE;
18202         case EQ: return ARM_EQ;
18203         case ORDERED: return ARM_VC;
18204         case UNORDERED: return ARM_VS;
18205         case UNLT: return ARM_LT;
18206         case UNLE: return ARM_LE;
18207         case UNGT: return ARM_HI;
18208         case UNGE: return ARM_PL;
18209           /* UNEQ and LTGT do not have a representation.  */
18210         case UNEQ: /* Fall through.  */
18211         case LTGT: /* Fall through.  */
18212         default: return ARM_NV;
18213         }
18214
18215     case CC_SWPmode:
18216       switch (comp_code)
18217         {
18218         case NE: return ARM_NE;
18219         case EQ: return ARM_EQ;
18220         case GE: return ARM_LE;
18221         case GT: return ARM_LT;
18222         case LE: return ARM_GE;
18223         case LT: return ARM_GT;
18224         case GEU: return ARM_LS;
18225         case GTU: return ARM_CC;
18226         case LEU: return ARM_CS;
18227         case LTU: return ARM_HI;
18228         default: return ARM_NV;
18229         }
18230
18231     case CC_Cmode:
18232       switch (comp_code)
18233         {
18234         case LTU: return ARM_CS;
18235         case GEU: return ARM_CC;
18236         default: return ARM_NV;
18237         }
18238
18239     case CC_CZmode:
18240       switch (comp_code)
18241         {
18242         case NE: return ARM_NE;
18243         case EQ: return ARM_EQ;
18244         case GEU: return ARM_CS;
18245         case GTU: return ARM_HI;
18246         case LEU: return ARM_LS;
18247         case LTU: return ARM_CC;
18248         default: return ARM_NV;
18249         }
18250
18251     case CC_NCVmode:
18252       switch (comp_code)
18253         {
18254         case GE: return ARM_GE;
18255         case LT: return ARM_LT;
18256         case GEU: return ARM_CS;
18257         case LTU: return ARM_CC;
18258         default: return ARM_NV;
18259         }
18260
18261     case CCmode:
18262       switch (comp_code)
18263         {
18264         case NE: return ARM_NE;
18265         case EQ: return ARM_EQ;
18266         case GE: return ARM_GE;
18267         case GT: return ARM_GT;
18268         case LE: return ARM_LE;
18269         case LT: return ARM_LT;
18270         case GEU: return ARM_CS;
18271         case GTU: return ARM_HI;
18272         case LEU: return ARM_LS;
18273         case LTU: return ARM_CC;
18274         default: return ARM_NV;
18275         }
18276
18277     default: gcc_unreachable ();
18278     }
18279 }
18280
18281 /* Like maybe_get_arm_condition_code, but never return ARM_NV.  */
18282 static enum arm_cond_code
18283 get_arm_condition_code (rtx comparison)
18284 {
18285   enum arm_cond_code code = maybe_get_arm_condition_code (comparison);
18286   gcc_assert (code != ARM_NV);
18287   return code;
18288 }
18289
18290 /* Tell arm_asm_output_opcode to output IT blocks for conditionally executed
18291    instructions.  */
18292 void
18293 thumb2_final_prescan_insn (rtx insn)
18294 {
18295   rtx first_insn = insn;
18296   rtx body = PATTERN (insn);
18297   rtx predicate;
18298   enum arm_cond_code code;
18299   int n;
18300   int mask;
18301
18302   /* Remove the previous insn from the count of insns to be output.  */
18303   if (arm_condexec_count)
18304       arm_condexec_count--;
18305
18306   /* Nothing to do if we are already inside a conditional block.  */
18307   if (arm_condexec_count)
18308     return;
18309
18310   if (GET_CODE (body) != COND_EXEC)
18311     return;
18312
18313   /* Conditional jumps are implemented directly.  */
18314   if (GET_CODE (insn) == JUMP_INSN)
18315     return;
18316
18317   predicate = COND_EXEC_TEST (body);
18318   arm_current_cc = get_arm_condition_code (predicate);
18319
18320   n = get_attr_ce_count (insn);
18321   arm_condexec_count = 1;
18322   arm_condexec_mask = (1 << n) - 1;
18323   arm_condexec_masklen = n;
18324   /* See if subsequent instructions can be combined into the same block.  */
18325   for (;;)
18326     {
18327       insn = next_nonnote_insn (insn);
18328
18329       /* Jumping into the middle of an IT block is illegal, so a label or
18330          barrier terminates the block.  */
18331       if (GET_CODE (insn) != INSN && GET_CODE(insn) != JUMP_INSN)
18332         break;
18333
18334       body = PATTERN (insn);
18335       /* USE and CLOBBER aren't really insns, so just skip them.  */
18336       if (GET_CODE (body) == USE
18337           || GET_CODE (body) == CLOBBER)
18338         continue;
18339
18340       /* ??? Recognize conditional jumps, and combine them with IT blocks.  */
18341       if (GET_CODE (body) != COND_EXEC)
18342         break;
18343       /* Allow up to 4 conditionally executed instructions in a block.  */
18344       n = get_attr_ce_count (insn);
18345       if (arm_condexec_masklen + n > 4)
18346         break;
18347
18348       predicate = COND_EXEC_TEST (body);
18349       code = get_arm_condition_code (predicate);
18350       mask = (1 << n) - 1;
18351       if (arm_current_cc == code)
18352         arm_condexec_mask |= (mask << arm_condexec_masklen);
18353       else if (arm_current_cc != ARM_INVERSE_CONDITION_CODE(code))
18354         break;
18355
18356       arm_condexec_count++;
18357       arm_condexec_masklen += n;
18358
18359       /* A jump must be the last instruction in a conditional block.  */
18360       if (GET_CODE(insn) == JUMP_INSN)
18361         break;
18362     }
18363   /* Restore recog_data (getting the attributes of other insns can
18364      destroy this array, but final.c assumes that it remains intact
18365      across this call).  */
18366   extract_constrain_insn_cached (first_insn);
18367 }
18368
18369 void
18370 arm_final_prescan_insn (rtx insn)
18371 {
18372   /* BODY will hold the body of INSN.  */
18373   rtx body = PATTERN (insn);
18374
18375   /* This will be 1 if trying to repeat the trick, and things need to be
18376      reversed if it appears to fail.  */
18377   int reverse = 0;
18378
18379   /* If we start with a return insn, we only succeed if we find another one.  */
18380   int seeking_return = 0;
18381   enum rtx_code return_code = UNKNOWN;
18382
18383   /* START_INSN will hold the insn from where we start looking.  This is the
18384      first insn after the following code_label if REVERSE is true.  */
18385   rtx start_insn = insn;
18386
18387   /* If in state 4, check if the target branch is reached, in order to
18388      change back to state 0.  */
18389   if (arm_ccfsm_state == 4)
18390     {
18391       if (insn == arm_target_insn)
18392         {
18393           arm_target_insn = NULL;
18394           arm_ccfsm_state = 0;
18395         }
18396       return;
18397     }
18398
18399   /* If in state 3, it is possible to repeat the trick, if this insn is an
18400      unconditional branch to a label, and immediately following this branch
18401      is the previous target label which is only used once, and the label this
18402      branch jumps to is not too far off.  */
18403   if (arm_ccfsm_state == 3)
18404     {
18405       if (simplejump_p (insn))
18406         {
18407           start_insn = next_nonnote_insn (start_insn);
18408           if (GET_CODE (start_insn) == BARRIER)
18409             {
18410               /* XXX Isn't this always a barrier?  */
18411               start_insn = next_nonnote_insn (start_insn);
18412             }
18413           if (GET_CODE (start_insn) == CODE_LABEL
18414               && CODE_LABEL_NUMBER (start_insn) == arm_target_label
18415               && LABEL_NUSES (start_insn) == 1)
18416             reverse = TRUE;
18417           else
18418             return;
18419         }
18420       else if (ANY_RETURN_P (body))
18421         {
18422           start_insn = next_nonnote_insn (start_insn);
18423           if (GET_CODE (start_insn) == BARRIER)
18424             start_insn = next_nonnote_insn (start_insn);
18425           if (GET_CODE (start_insn) == CODE_LABEL
18426               && CODE_LABEL_NUMBER (start_insn) == arm_target_label
18427               && LABEL_NUSES (start_insn) == 1)
18428             {
18429               reverse = TRUE;
18430               seeking_return = 1;
18431               return_code = GET_CODE (body);
18432             }
18433           else
18434             return;
18435         }
18436       else
18437         return;
18438     }
18439
18440   gcc_assert (!arm_ccfsm_state || reverse);
18441   if (GET_CODE (insn) != JUMP_INSN)
18442     return;
18443
18444   /* This jump might be paralleled with a clobber of the condition codes
18445      the jump should always come first */
18446   if (GET_CODE (body) == PARALLEL && XVECLEN (body, 0) > 0)
18447     body = XVECEXP (body, 0, 0);
18448
18449   if (reverse
18450       || (GET_CODE (body) == SET && GET_CODE (SET_DEST (body)) == PC
18451           && GET_CODE (SET_SRC (body)) == IF_THEN_ELSE))
18452     {
18453       int insns_skipped;
18454       int fail = FALSE, succeed = FALSE;
18455       /* Flag which part of the IF_THEN_ELSE is the LABEL_REF.  */
18456       int then_not_else = TRUE;
18457       rtx this_insn = start_insn, label = 0;
18458
18459       /* Register the insn jumped to.  */
18460       if (reverse)
18461         {
18462           if (!seeking_return)
18463             label = XEXP (SET_SRC (body), 0);
18464         }
18465       else if (GET_CODE (XEXP (SET_SRC (body), 1)) == LABEL_REF)
18466         label = XEXP (XEXP (SET_SRC (body), 1), 0);
18467       else if (GET_CODE (XEXP (SET_SRC (body), 2)) == LABEL_REF)
18468         {
18469           label = XEXP (XEXP (SET_SRC (body), 2), 0);
18470           then_not_else = FALSE;
18471         }
18472       else if (ANY_RETURN_P (XEXP (SET_SRC (body), 1)))
18473         {
18474           seeking_return = 1;
18475           return_code = GET_CODE (XEXP (SET_SRC (body), 1));
18476         }
18477       else if (ANY_RETURN_P (XEXP (SET_SRC (body), 2)))
18478         {
18479           seeking_return = 1;
18480           return_code = GET_CODE (XEXP (SET_SRC (body), 2));
18481           then_not_else = FALSE;
18482         }
18483       else
18484         gcc_unreachable ();
18485
18486       /* See how many insns this branch skips, and what kind of insns.  If all
18487          insns are okay, and the label or unconditional branch to the same
18488          label is not too far away, succeed.  */
18489       for (insns_skipped = 0;
18490            !fail && !succeed && insns_skipped++ < max_insns_skipped;)
18491         {
18492           rtx scanbody;
18493
18494           this_insn = next_nonnote_insn (this_insn);
18495           if (!this_insn)
18496             break;
18497
18498           switch (GET_CODE (this_insn))
18499             {
18500             case CODE_LABEL:
18501               /* Succeed if it is the target label, otherwise fail since
18502                  control falls in from somewhere else.  */
18503               if (this_insn == label)
18504                 {
18505                   arm_ccfsm_state = 1;
18506                   succeed = TRUE;
18507                 }
18508               else
18509                 fail = TRUE;
18510               break;
18511
18512             case BARRIER:
18513               /* Succeed if the following insn is the target label.
18514                  Otherwise fail.
18515                  If return insns are used then the last insn in a function
18516                  will be a barrier.  */
18517               this_insn = next_nonnote_insn (this_insn);
18518               if (this_insn && this_insn == label)
18519                 {
18520                   arm_ccfsm_state = 1;
18521                   succeed = TRUE;
18522                 }
18523               else
18524                 fail = TRUE;
18525               break;
18526
18527             case CALL_INSN:
18528               /* The AAPCS says that conditional calls should not be
18529                  used since they make interworking inefficient (the
18530                  linker can't transform BL<cond> into BLX).  That's
18531                  only a problem if the machine has BLX.  */
18532               if (arm_arch5)
18533                 {
18534                   fail = TRUE;
18535                   break;
18536                 }
18537
18538               /* Succeed if the following insn is the target label, or
18539                  if the following two insns are a barrier and the
18540                  target label.  */
18541               this_insn = next_nonnote_insn (this_insn);
18542               if (this_insn && GET_CODE (this_insn) == BARRIER)
18543                 this_insn = next_nonnote_insn (this_insn);
18544
18545               if (this_insn && this_insn == label
18546                   && insns_skipped < max_insns_skipped)
18547                 {
18548                   arm_ccfsm_state = 1;
18549                   succeed = TRUE;
18550                 }
18551               else
18552                 fail = TRUE;
18553               break;
18554
18555             case JUMP_INSN:
18556               /* If this is an unconditional branch to the same label, succeed.
18557                  If it is to another label, do nothing.  If it is conditional,
18558                  fail.  */
18559               /* XXX Probably, the tests for SET and the PC are
18560                  unnecessary.  */
18561
18562               scanbody = PATTERN (this_insn);
18563               if (GET_CODE (scanbody) == SET
18564                   && GET_CODE (SET_DEST (scanbody)) == PC)
18565                 {
18566                   if (GET_CODE (SET_SRC (scanbody)) == LABEL_REF
18567                       && XEXP (SET_SRC (scanbody), 0) == label && !reverse)
18568                     {
18569                       arm_ccfsm_state = 2;
18570                       succeed = TRUE;
18571                     }
18572                   else if (GET_CODE (SET_SRC (scanbody)) == IF_THEN_ELSE)
18573                     fail = TRUE;
18574                 }
18575               /* Fail if a conditional return is undesirable (e.g. on a
18576                  StrongARM), but still allow this if optimizing for size.  */
18577               else if (GET_CODE (scanbody) == return_code
18578                        && !use_return_insn (TRUE, NULL)
18579                        && !optimize_size)
18580                 fail = TRUE;
18581               else if (GET_CODE (scanbody) == return_code)
18582                 {
18583                   arm_ccfsm_state = 2;
18584                   succeed = TRUE;
18585                 }
18586               else if (GET_CODE (scanbody) == PARALLEL)
18587                 {
18588                   switch (get_attr_conds (this_insn))
18589                     {
18590                     case CONDS_NOCOND:
18591                       break;
18592                     default:
18593                       fail = TRUE;
18594                       break;
18595                     }
18596                 }
18597               else
18598                 fail = TRUE;    /* Unrecognized jump (e.g. epilogue).  */
18599
18600               break;
18601
18602             case INSN:
18603               /* Instructions using or affecting the condition codes make it
18604                  fail.  */
18605               scanbody = PATTERN (this_insn);
18606               if (!(GET_CODE (scanbody) == SET
18607                     || GET_CODE (scanbody) == PARALLEL)
18608                   || get_attr_conds (this_insn) != CONDS_NOCOND)
18609                 fail = TRUE;
18610
18611               /* A conditional cirrus instruction must be followed by
18612                  a non Cirrus instruction.  However, since we
18613                  conditionalize instructions in this function and by
18614                  the time we get here we can't add instructions
18615                  (nops), because shorten_branches() has already been
18616                  called, we will disable conditionalizing Cirrus
18617                  instructions to be safe.  */
18618               if (GET_CODE (scanbody) != USE
18619                   && GET_CODE (scanbody) != CLOBBER
18620                   && get_attr_cirrus (this_insn) != CIRRUS_NOT)
18621                 fail = TRUE;
18622               break;
18623
18624             default:
18625               break;
18626             }
18627         }
18628       if (succeed)
18629         {
18630           if ((!seeking_return) && (arm_ccfsm_state == 1 || reverse))
18631             arm_target_label = CODE_LABEL_NUMBER (label);
18632           else
18633             {
18634               gcc_assert (seeking_return || arm_ccfsm_state == 2);
18635
18636               while (this_insn && GET_CODE (PATTERN (this_insn)) == USE)
18637                 {
18638                   this_insn = next_nonnote_insn (this_insn);
18639                   gcc_assert (!this_insn
18640                               || (GET_CODE (this_insn) != BARRIER
18641                                   && GET_CODE (this_insn) != CODE_LABEL));
18642                 }
18643               if (!this_insn)
18644                 {
18645                   /* Oh, dear! we ran off the end.. give up.  */
18646                   extract_constrain_insn_cached (insn);
18647                   arm_ccfsm_state = 0;
18648                   arm_target_insn = NULL;
18649                   return;
18650                 }
18651               arm_target_insn = this_insn;
18652             }
18653
18654           /* If REVERSE is true, ARM_CURRENT_CC needs to be inverted from
18655              what it was.  */
18656           if (!reverse)
18657             arm_current_cc = get_arm_condition_code (XEXP (SET_SRC (body), 0));
18658
18659           if (reverse || then_not_else)
18660             arm_current_cc = ARM_INVERSE_CONDITION_CODE (arm_current_cc);
18661         }
18662
18663       /* Restore recog_data (getting the attributes of other insns can
18664          destroy this array, but final.c assumes that it remains intact
18665          across this call.  */
18666       extract_constrain_insn_cached (insn);
18667     }
18668 }
18669
18670 /* Output IT instructions.  */
18671 void
18672 thumb2_asm_output_opcode (FILE * stream)
18673 {
18674   char buff[5];
18675   int n;
18676
18677   if (arm_condexec_mask)
18678     {
18679       for (n = 0; n < arm_condexec_masklen; n++)
18680         buff[n] = (arm_condexec_mask & (1 << n)) ? 't' : 'e';
18681       buff[n] = 0;
18682       asm_fprintf(stream, "i%s\t%s\n\t", buff,
18683                   arm_condition_codes[arm_current_cc]);
18684       arm_condexec_mask = 0;
18685     }
18686 }
18687
18688 /* Returns true if REGNO is a valid register
18689    for holding a quantity of type MODE.  */
18690 int
18691 arm_hard_regno_mode_ok (unsigned int regno, enum machine_mode mode)
18692 {
18693   if (GET_MODE_CLASS (mode) == MODE_CC)
18694     return (regno == CC_REGNUM
18695             || (TARGET_HARD_FLOAT && TARGET_VFP
18696                 && regno == VFPCC_REGNUM));
18697
18698   if (TARGET_THUMB1)
18699     /* For the Thumb we only allow values bigger than SImode in
18700        registers 0 - 6, so that there is always a second low
18701        register available to hold the upper part of the value.
18702        We probably we ought to ensure that the register is the
18703        start of an even numbered register pair.  */
18704     return (ARM_NUM_REGS (mode) < 2) || (regno < LAST_LO_REGNUM);
18705
18706   if (TARGET_HARD_FLOAT && TARGET_MAVERICK
18707       && IS_CIRRUS_REGNUM (regno))
18708     /* We have outlawed SI values in Cirrus registers because they
18709        reside in the lower 32 bits, but SF values reside in the
18710        upper 32 bits.  This causes gcc all sorts of grief.  We can't
18711        even split the registers into pairs because Cirrus SI values
18712        get sign extended to 64bits-- aldyh.  */
18713     return (GET_MODE_CLASS (mode) == MODE_FLOAT) || (mode == DImode);
18714
18715   if (TARGET_HARD_FLOAT && TARGET_VFP
18716       && IS_VFP_REGNUM (regno))
18717     {
18718       if (mode == SFmode || mode == SImode)
18719         return VFP_REGNO_OK_FOR_SINGLE (regno);
18720
18721       if (mode == DFmode)
18722         return VFP_REGNO_OK_FOR_DOUBLE (regno);
18723
18724       /* VFP registers can hold HFmode values, but there is no point in
18725          putting them there unless we have hardware conversion insns. */
18726       if (mode == HFmode)
18727         return TARGET_FP16 && VFP_REGNO_OK_FOR_SINGLE (regno);
18728
18729       if (TARGET_NEON)
18730         return (VALID_NEON_DREG_MODE (mode) && VFP_REGNO_OK_FOR_DOUBLE (regno))
18731                || (VALID_NEON_QREG_MODE (mode)
18732                    && NEON_REGNO_OK_FOR_QUAD (regno))
18733                || (mode == TImode && NEON_REGNO_OK_FOR_NREGS (regno, 2))
18734                || (mode == EImode && NEON_REGNO_OK_FOR_NREGS (regno, 3))
18735                || (mode == OImode && NEON_REGNO_OK_FOR_NREGS (regno, 4))
18736                || (mode == CImode && NEON_REGNO_OK_FOR_NREGS (regno, 6))
18737                || (mode == XImode && NEON_REGNO_OK_FOR_NREGS (regno, 8));
18738
18739       return FALSE;
18740     }
18741
18742   if (TARGET_REALLY_IWMMXT)
18743     {
18744       if (IS_IWMMXT_GR_REGNUM (regno))
18745         return mode == SImode;
18746
18747       if (IS_IWMMXT_REGNUM (regno))
18748         return VALID_IWMMXT_REG_MODE (mode);
18749     }
18750
18751   /* We allow almost any value to be stored in the general registers.
18752      Restrict doubleword quantities to even register pairs so that we can
18753      use ldrd.  Do not allow very large Neon structure opaque modes in
18754      general registers; they would use too many.  */
18755   if (regno <= LAST_ARM_REGNUM)
18756     return !(TARGET_LDRD && GET_MODE_SIZE (mode) > 4 && (regno & 1) != 0)
18757       && ARM_NUM_REGS (mode) <= 4;
18758
18759   if (regno == FRAME_POINTER_REGNUM
18760       || regno == ARG_POINTER_REGNUM)
18761     /* We only allow integers in the fake hard registers.  */
18762     return GET_MODE_CLASS (mode) == MODE_INT;
18763
18764   /* The only registers left are the FPA registers
18765      which we only allow to hold FP values.  */
18766   return (TARGET_HARD_FLOAT && TARGET_FPA
18767           && GET_MODE_CLASS (mode) == MODE_FLOAT
18768           && regno >= FIRST_FPA_REGNUM
18769           && regno <= LAST_FPA_REGNUM);
18770 }
18771
18772 /* Implement MODES_TIEABLE_P.  */
18773
18774 bool
18775 arm_modes_tieable_p (enum machine_mode mode1, enum machine_mode mode2)
18776 {
18777   if (GET_MODE_CLASS (mode1) == GET_MODE_CLASS (mode2))
18778     return true;
18779
18780   /* We specifically want to allow elements of "structure" modes to
18781      be tieable to the structure.  This more general condition allows
18782      other rarer situations too.  */
18783   if (TARGET_NEON
18784       && (VALID_NEON_DREG_MODE (mode1)
18785           || VALID_NEON_QREG_MODE (mode1)
18786           || VALID_NEON_STRUCT_MODE (mode1))
18787       && (VALID_NEON_DREG_MODE (mode2)
18788           || VALID_NEON_QREG_MODE (mode2)
18789           || VALID_NEON_STRUCT_MODE (mode2)))
18790     return true;
18791
18792   return false;
18793 }
18794
18795 /* For efficiency and historical reasons LO_REGS, HI_REGS and CC_REGS are
18796    not used in arm mode.  */
18797
18798 enum reg_class
18799 arm_regno_class (int regno)
18800 {
18801   if (TARGET_THUMB1)
18802     {
18803       if (regno == STACK_POINTER_REGNUM)
18804         return STACK_REG;
18805       if (regno == CC_REGNUM)
18806         return CC_REG;
18807       if (regno < 8)
18808         return LO_REGS;
18809       return HI_REGS;
18810     }
18811
18812   if (TARGET_THUMB2 && regno < 8)
18813     return LO_REGS;
18814
18815   if (   regno <= LAST_ARM_REGNUM
18816       || regno == FRAME_POINTER_REGNUM
18817       || regno == ARG_POINTER_REGNUM)
18818     return TARGET_THUMB2 ? HI_REGS : GENERAL_REGS;
18819
18820   if (regno == CC_REGNUM || regno == VFPCC_REGNUM)
18821     return TARGET_THUMB2 ? CC_REG : NO_REGS;
18822
18823   if (IS_CIRRUS_REGNUM (regno))
18824     return CIRRUS_REGS;
18825
18826   if (IS_VFP_REGNUM (regno))
18827     {
18828       if (regno <= D7_VFP_REGNUM)
18829         return VFP_D0_D7_REGS;
18830       else if (regno <= LAST_LO_VFP_REGNUM)
18831         return VFP_LO_REGS;
18832       else
18833         return VFP_HI_REGS;
18834     }
18835
18836   if (IS_IWMMXT_REGNUM (regno))
18837     return IWMMXT_REGS;
18838
18839   if (IS_IWMMXT_GR_REGNUM (regno))
18840     return IWMMXT_GR_REGS;
18841
18842   return FPA_REGS;
18843 }
18844
18845 /* Handle a special case when computing the offset
18846    of an argument from the frame pointer.  */
18847 int
18848 arm_debugger_arg_offset (int value, rtx addr)
18849 {
18850   rtx insn;
18851
18852   /* We are only interested if dbxout_parms() failed to compute the offset.  */
18853   if (value != 0)
18854     return 0;
18855
18856   /* We can only cope with the case where the address is held in a register.  */
18857   if (GET_CODE (addr) != REG)
18858     return 0;
18859
18860   /* If we are using the frame pointer to point at the argument, then
18861      an offset of 0 is correct.  */
18862   if (REGNO (addr) == (unsigned) HARD_FRAME_POINTER_REGNUM)
18863     return 0;
18864
18865   /* If we are using the stack pointer to point at the
18866      argument, then an offset of 0 is correct.  */
18867   /* ??? Check this is consistent with thumb2 frame layout.  */
18868   if ((TARGET_THUMB || !frame_pointer_needed)
18869       && REGNO (addr) == SP_REGNUM)
18870     return 0;
18871
18872   /* Oh dear.  The argument is pointed to by a register rather
18873      than being held in a register, or being stored at a known
18874      offset from the frame pointer.  Since GDB only understands
18875      those two kinds of argument we must translate the address
18876      held in the register into an offset from the frame pointer.
18877      We do this by searching through the insns for the function
18878      looking to see where this register gets its value.  If the
18879      register is initialized from the frame pointer plus an offset
18880      then we are in luck and we can continue, otherwise we give up.
18881
18882      This code is exercised by producing debugging information
18883      for a function with arguments like this:
18884
18885            double func (double a, double b, int c, double d) {return d;}
18886
18887      Without this code the stab for parameter 'd' will be set to
18888      an offset of 0 from the frame pointer, rather than 8.  */
18889
18890   /* The if() statement says:
18891
18892      If the insn is a normal instruction
18893      and if the insn is setting the value in a register
18894      and if the register being set is the register holding the address of the argument
18895      and if the address is computing by an addition
18896      that involves adding to a register
18897      which is the frame pointer
18898      a constant integer
18899
18900      then...  */
18901
18902   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
18903     {
18904       if (   GET_CODE (insn) == INSN
18905           && GET_CODE (PATTERN (insn)) == SET
18906           && REGNO    (XEXP (PATTERN (insn), 0)) == REGNO (addr)
18907           && GET_CODE (XEXP (PATTERN (insn), 1)) == PLUS
18908           && GET_CODE (XEXP (XEXP (PATTERN (insn), 1), 0)) == REG
18909           && REGNO    (XEXP (XEXP (PATTERN (insn), 1), 0)) == (unsigned) HARD_FRAME_POINTER_REGNUM
18910           && GET_CODE (XEXP (XEXP (PATTERN (insn), 1), 1)) == CONST_INT
18911              )
18912         {
18913           value = INTVAL (XEXP (XEXP (PATTERN (insn), 1), 1));
18914
18915           break;
18916         }
18917     }
18918
18919   if (value == 0)
18920     {
18921       debug_rtx (addr);
18922       warning (0, "unable to compute real location of stacked parameter");
18923       value = 8; /* XXX magic hack */
18924     }
18925
18926   return value;
18927 }
18928 \f
18929 typedef enum {
18930   T_V8QI,
18931   T_V4HI,
18932   T_V2SI,
18933   T_V2SF,
18934   T_DI,
18935   T_V16QI,
18936   T_V8HI,
18937   T_V4SI,
18938   T_V4SF,
18939   T_V2DI,
18940   T_TI,
18941   T_EI,
18942   T_OI,
18943   T_MAX         /* Size of enum.  Keep last.  */
18944 } neon_builtin_type_mode;
18945
18946 #define TYPE_MODE_BIT(X) (1 << (X))
18947
18948 #define TB_DREG (TYPE_MODE_BIT (T_V8QI) | TYPE_MODE_BIT (T_V4HI)        \
18949                  | TYPE_MODE_BIT (T_V2SI) | TYPE_MODE_BIT (T_V2SF)      \
18950                  | TYPE_MODE_BIT (T_DI))
18951 #define TB_QREG (TYPE_MODE_BIT (T_V16QI) | TYPE_MODE_BIT (T_V8HI)       \
18952                  | TYPE_MODE_BIT (T_V4SI) | TYPE_MODE_BIT (T_V4SF)      \
18953                  | TYPE_MODE_BIT (T_V2DI) | TYPE_MODE_BIT (T_TI))
18954
18955 #define v8qi_UP  T_V8QI
18956 #define v4hi_UP  T_V4HI
18957 #define v2si_UP  T_V2SI
18958 #define v2sf_UP  T_V2SF
18959 #define di_UP    T_DI
18960 #define v16qi_UP T_V16QI
18961 #define v8hi_UP  T_V8HI
18962 #define v4si_UP  T_V4SI
18963 #define v4sf_UP  T_V4SF
18964 #define v2di_UP  T_V2DI
18965 #define ti_UP    T_TI
18966 #define ei_UP    T_EI
18967 #define oi_UP    T_OI
18968
18969 #define UP(X) X##_UP
18970
18971 typedef enum {
18972   NEON_BINOP,
18973   NEON_TERNOP,
18974   NEON_UNOP,
18975   NEON_GETLANE,
18976   NEON_SETLANE,
18977   NEON_CREATE,
18978   NEON_DUP,
18979   NEON_DUPLANE,
18980   NEON_COMBINE,
18981   NEON_SPLIT,
18982   NEON_LANEMUL,
18983   NEON_LANEMULL,
18984   NEON_LANEMULH,
18985   NEON_LANEMAC,
18986   NEON_SCALARMUL,
18987   NEON_SCALARMULL,
18988   NEON_SCALARMULH,
18989   NEON_SCALARMAC,
18990   NEON_CONVERT,
18991   NEON_FIXCONV,
18992   NEON_SELECT,
18993   NEON_RESULTPAIR,
18994   NEON_REINTERP,
18995   NEON_VTBL,
18996   NEON_VTBX,
18997   NEON_LOAD1,
18998   NEON_LOAD1LANE,
18999   NEON_STORE1,
19000   NEON_STORE1LANE,
19001   NEON_LOADSTRUCT,
19002   NEON_LOADSTRUCTLANE,
19003   NEON_STORESTRUCT,
19004   NEON_STORESTRUCTLANE,
19005   NEON_LOGICBINOP,
19006   NEON_SHIFTINSERT,
19007   NEON_SHIFTIMM,
19008   NEON_SHIFTACC
19009 } neon_itype;
19010
19011 typedef struct {
19012   const char *name;
19013   const neon_itype itype;
19014   const neon_builtin_type_mode mode;
19015   const enum insn_code code;
19016   unsigned int fcode;
19017 } neon_builtin_datum;
19018
19019 #define CF(N,X) CODE_FOR_neon_##N##X
19020
19021 #define VAR1(T, N, A) \
19022   {#N, NEON_##T, UP (A), CF (N, A), 0}
19023 #define VAR2(T, N, A, B) \
19024   VAR1 (T, N, A), \
19025   {#N, NEON_##T, UP (B), CF (N, B), 0}
19026 #define VAR3(T, N, A, B, C) \
19027   VAR2 (T, N, A, B), \
19028   {#N, NEON_##T, UP (C), CF (N, C), 0}
19029 #define VAR4(T, N, A, B, C, D) \
19030   VAR3 (T, N, A, B, C), \
19031   {#N, NEON_##T, UP (D), CF (N, D), 0}
19032 #define VAR5(T, N, A, B, C, D, E) \
19033   VAR4 (T, N, A, B, C, D), \
19034   {#N, NEON_##T, UP (E), CF (N, E), 0}
19035 #define VAR6(T, N, A, B, C, D, E, F) \
19036   VAR5 (T, N, A, B, C, D, E), \
19037   {#N, NEON_##T, UP (F), CF (N, F), 0}
19038 #define VAR7(T, N, A, B, C, D, E, F, G) \
19039   VAR6 (T, N, A, B, C, D, E, F), \
19040   {#N, NEON_##T, UP (G), CF (N, G), 0}
19041 #define VAR8(T, N, A, B, C, D, E, F, G, H) \
19042   VAR7 (T, N, A, B, C, D, E, F, G), \
19043   {#N, NEON_##T, UP (H), CF (N, H), 0}
19044 #define VAR9(T, N, A, B, C, D, E, F, G, H, I) \
19045   VAR8 (T, N, A, B, C, D, E, F, G, H), \
19046   {#N, NEON_##T, UP (I), CF (N, I), 0}
19047 #define VAR10(T, N, A, B, C, D, E, F, G, H, I, J) \
19048   VAR9 (T, N, A, B, C, D, E, F, G, H, I), \
19049   {#N, NEON_##T, UP (J), CF (N, J), 0}
19050
19051 /* The mode entries in the following table correspond to the "key" type of the
19052    instruction variant, i.e. equivalent to that which would be specified after
19053    the assembler mnemonic, which usually refers to the last vector operand.
19054    (Signed/unsigned/polynomial types are not differentiated between though, and
19055    are all mapped onto the same mode for a given element size.) The modes
19056    listed per instruction should be the same as those defined for that
19057    instruction's pattern in neon.md.  */
19058
19059 static neon_builtin_datum neon_builtin_data[] =
19060 {
19061   VAR10 (BINOP, vadd,
19062          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19063   VAR3 (BINOP, vaddl, v8qi, v4hi, v2si),
19064   VAR3 (BINOP, vaddw, v8qi, v4hi, v2si),
19065   VAR6 (BINOP, vhadd, v8qi, v4hi, v2si, v16qi, v8hi, v4si),
19066   VAR8 (BINOP, vqadd, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di),
19067   VAR3 (BINOP, vaddhn, v8hi, v4si, v2di),
19068   VAR8 (BINOP, vmul, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19069   VAR8 (TERNOP, vmla, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19070   VAR3 (TERNOP, vmlal, v8qi, v4hi, v2si),
19071   VAR8 (TERNOP, vmls, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19072   VAR3 (TERNOP, vmlsl, v8qi, v4hi, v2si),
19073   VAR4 (BINOP, vqdmulh, v4hi, v2si, v8hi, v4si),
19074   VAR2 (TERNOP, vqdmlal, v4hi, v2si),
19075   VAR2 (TERNOP, vqdmlsl, v4hi, v2si),
19076   VAR3 (BINOP, vmull, v8qi, v4hi, v2si),
19077   VAR2 (SCALARMULL, vmull_n, v4hi, v2si),
19078   VAR2 (LANEMULL, vmull_lane, v4hi, v2si),
19079   VAR2 (SCALARMULL, vqdmull_n, v4hi, v2si),
19080   VAR2 (LANEMULL, vqdmull_lane, v4hi, v2si),
19081   VAR4 (SCALARMULH, vqdmulh_n, v4hi, v2si, v8hi, v4si),
19082   VAR4 (LANEMULH, vqdmulh_lane, v4hi, v2si, v8hi, v4si),
19083   VAR2 (BINOP, vqdmull, v4hi, v2si),
19084   VAR8 (BINOP, vshl, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di),
19085   VAR8 (BINOP, vqshl, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di),
19086   VAR8 (SHIFTIMM, vshr_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di),
19087   VAR3 (SHIFTIMM, vshrn_n, v8hi, v4si, v2di),
19088   VAR3 (SHIFTIMM, vqshrn_n, v8hi, v4si, v2di),
19089   VAR3 (SHIFTIMM, vqshrun_n, v8hi, v4si, v2di),
19090   VAR8 (SHIFTIMM, vshl_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di),
19091   VAR8 (SHIFTIMM, vqshl_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di),
19092   VAR8 (SHIFTIMM, vqshlu_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di),
19093   VAR3 (SHIFTIMM, vshll_n, v8qi, v4hi, v2si),
19094   VAR8 (SHIFTACC, vsra_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di),
19095   VAR10 (BINOP, vsub,
19096          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19097   VAR3 (BINOP, vsubl, v8qi, v4hi, v2si),
19098   VAR3 (BINOP, vsubw, v8qi, v4hi, v2si),
19099   VAR8 (BINOP, vqsub, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di),
19100   VAR6 (BINOP, vhsub, v8qi, v4hi, v2si, v16qi, v8hi, v4si),
19101   VAR3 (BINOP, vsubhn, v8hi, v4si, v2di),
19102   VAR8 (BINOP, vceq, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19103   VAR8 (BINOP, vcge, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19104   VAR8 (BINOP, vcgt, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19105   VAR2 (BINOP, vcage, v2sf, v4sf),
19106   VAR2 (BINOP, vcagt, v2sf, v4sf),
19107   VAR6 (BINOP, vtst, v8qi, v4hi, v2si, v16qi, v8hi, v4si),
19108   VAR8 (BINOP, vabd, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19109   VAR3 (BINOP, vabdl, v8qi, v4hi, v2si),
19110   VAR6 (TERNOP, vaba, v8qi, v4hi, v2si, v16qi, v8hi, v4si),
19111   VAR3 (TERNOP, vabal, v8qi, v4hi, v2si),
19112   VAR8 (BINOP, vmax, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19113   VAR8 (BINOP, vmin, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19114   VAR4 (BINOP, vpadd, v8qi, v4hi, v2si, v2sf),
19115   VAR6 (UNOP, vpaddl, v8qi, v4hi, v2si, v16qi, v8hi, v4si),
19116   VAR6 (BINOP, vpadal, v8qi, v4hi, v2si, v16qi, v8hi, v4si),
19117   VAR4 (BINOP, vpmax, v8qi, v4hi, v2si, v2sf),
19118   VAR4 (BINOP, vpmin, v8qi, v4hi, v2si, v2sf),
19119   VAR2 (BINOP, vrecps, v2sf, v4sf),
19120   VAR2 (BINOP, vrsqrts, v2sf, v4sf),
19121   VAR8 (SHIFTINSERT, vsri_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di),
19122   VAR8 (SHIFTINSERT, vsli_n, v8qi, v4hi, v2si, di, v16qi, v8hi, v4si, v2di),
19123   VAR8 (UNOP, vabs, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19124   VAR6 (UNOP, vqabs, v8qi, v4hi, v2si, v16qi, v8hi, v4si),
19125   VAR8 (UNOP, vneg, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19126   VAR6 (UNOP, vqneg, v8qi, v4hi, v2si, v16qi, v8hi, v4si),
19127   VAR6 (UNOP, vcls, v8qi, v4hi, v2si, v16qi, v8hi, v4si),
19128   VAR6 (UNOP, vclz, v8qi, v4hi, v2si, v16qi, v8hi, v4si),
19129   VAR2 (UNOP, vcnt, v8qi, v16qi),
19130   VAR4 (UNOP, vrecpe, v2si, v2sf, v4si, v4sf),
19131   VAR4 (UNOP, vrsqrte, v2si, v2sf, v4si, v4sf),
19132   VAR6 (UNOP, vmvn, v8qi, v4hi, v2si, v16qi, v8hi, v4si),
19133   /* FIXME: vget_lane supports more variants than this!  */
19134   VAR10 (GETLANE, vget_lane,
19135          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19136   VAR10 (SETLANE, vset_lane,
19137          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19138   VAR5 (CREATE, vcreate, v8qi, v4hi, v2si, v2sf, di),
19139   VAR10 (DUP, vdup_n,
19140          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19141   VAR10 (DUPLANE, vdup_lane,
19142          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19143   VAR5 (COMBINE, vcombine, v8qi, v4hi, v2si, v2sf, di),
19144   VAR5 (SPLIT, vget_high, v16qi, v8hi, v4si, v4sf, v2di),
19145   VAR5 (SPLIT, vget_low, v16qi, v8hi, v4si, v4sf, v2di),
19146   VAR3 (UNOP, vmovn, v8hi, v4si, v2di),
19147   VAR3 (UNOP, vqmovn, v8hi, v4si, v2di),
19148   VAR3 (UNOP, vqmovun, v8hi, v4si, v2di),
19149   VAR3 (UNOP, vmovl, v8qi, v4hi, v2si),
19150   VAR6 (LANEMUL, vmul_lane, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19151   VAR6 (LANEMAC, vmla_lane, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19152   VAR2 (LANEMAC, vmlal_lane, v4hi, v2si),
19153   VAR2 (LANEMAC, vqdmlal_lane, v4hi, v2si),
19154   VAR6 (LANEMAC, vmls_lane, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19155   VAR2 (LANEMAC, vmlsl_lane, v4hi, v2si),
19156   VAR2 (LANEMAC, vqdmlsl_lane, v4hi, v2si),
19157   VAR6 (SCALARMUL, vmul_n, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19158   VAR6 (SCALARMAC, vmla_n, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19159   VAR2 (SCALARMAC, vmlal_n, v4hi, v2si),
19160   VAR2 (SCALARMAC, vqdmlal_n, v4hi, v2si),
19161   VAR6 (SCALARMAC, vmls_n, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19162   VAR2 (SCALARMAC, vmlsl_n, v4hi, v2si),
19163   VAR2 (SCALARMAC, vqdmlsl_n, v4hi, v2si),
19164   VAR10 (BINOP, vext,
19165          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19166   VAR8 (UNOP, vrev64, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19167   VAR4 (UNOP, vrev32, v8qi, v4hi, v16qi, v8hi),
19168   VAR2 (UNOP, vrev16, v8qi, v16qi),
19169   VAR4 (CONVERT, vcvt, v2si, v2sf, v4si, v4sf),
19170   VAR4 (FIXCONV, vcvt_n, v2si, v2sf, v4si, v4sf),
19171   VAR10 (SELECT, vbsl,
19172          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19173   VAR1 (VTBL, vtbl1, v8qi),
19174   VAR1 (VTBL, vtbl2, v8qi),
19175   VAR1 (VTBL, vtbl3, v8qi),
19176   VAR1 (VTBL, vtbl4, v8qi),
19177   VAR1 (VTBX, vtbx1, v8qi),
19178   VAR1 (VTBX, vtbx2, v8qi),
19179   VAR1 (VTBX, vtbx3, v8qi),
19180   VAR1 (VTBX, vtbx4, v8qi),
19181   VAR8 (RESULTPAIR, vtrn, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19182   VAR8 (RESULTPAIR, vzip, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19183   VAR8 (RESULTPAIR, vuzp, v8qi, v4hi, v2si, v2sf, v16qi, v8hi, v4si, v4sf),
19184   VAR5 (REINTERP, vreinterpretv8qi, v8qi, v4hi, v2si, v2sf, di),
19185   VAR5 (REINTERP, vreinterpretv4hi, v8qi, v4hi, v2si, v2sf, di),
19186   VAR5 (REINTERP, vreinterpretv2si, v8qi, v4hi, v2si, v2sf, di),
19187   VAR5 (REINTERP, vreinterpretv2sf, v8qi, v4hi, v2si, v2sf, di),
19188   VAR5 (REINTERP, vreinterpretdi, v8qi, v4hi, v2si, v2sf, di),
19189   VAR5 (REINTERP, vreinterpretv16qi, v16qi, v8hi, v4si, v4sf, v2di),
19190   VAR5 (REINTERP, vreinterpretv8hi, v16qi, v8hi, v4si, v4sf, v2di),
19191   VAR5 (REINTERP, vreinterpretv4si, v16qi, v8hi, v4si, v4sf, v2di),
19192   VAR5 (REINTERP, vreinterpretv4sf, v16qi, v8hi, v4si, v4sf, v2di),
19193   VAR5 (REINTERP, vreinterpretv2di, v16qi, v8hi, v4si, v4sf, v2di),
19194   VAR10 (LOAD1, vld1,
19195          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19196   VAR10 (LOAD1LANE, vld1_lane,
19197          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19198   VAR10 (LOAD1, vld1_dup,
19199          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19200   VAR10 (STORE1, vst1,
19201          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19202   VAR10 (STORE1LANE, vst1_lane,
19203          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19204   VAR9 (LOADSTRUCT,
19205         vld2, v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf),
19206   VAR7 (LOADSTRUCTLANE, vld2_lane,
19207         v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19208   VAR5 (LOADSTRUCT, vld2_dup, v8qi, v4hi, v2si, v2sf, di),
19209   VAR9 (STORESTRUCT, vst2,
19210         v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf),
19211   VAR7 (STORESTRUCTLANE, vst2_lane,
19212         v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19213   VAR9 (LOADSTRUCT,
19214         vld3, v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf),
19215   VAR7 (LOADSTRUCTLANE, vld3_lane,
19216         v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19217   VAR5 (LOADSTRUCT, vld3_dup, v8qi, v4hi, v2si, v2sf, di),
19218   VAR9 (STORESTRUCT, vst3,
19219         v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf),
19220   VAR7 (STORESTRUCTLANE, vst3_lane,
19221         v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19222   VAR9 (LOADSTRUCT, vld4,
19223         v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf),
19224   VAR7 (LOADSTRUCTLANE, vld4_lane,
19225         v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19226   VAR5 (LOADSTRUCT, vld4_dup, v8qi, v4hi, v2si, v2sf, di),
19227   VAR9 (STORESTRUCT, vst4,
19228         v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf),
19229   VAR7 (STORESTRUCTLANE, vst4_lane,
19230         v8qi, v4hi, v2si, v2sf, v8hi, v4si, v4sf),
19231   VAR10 (LOGICBINOP, vand,
19232          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19233   VAR10 (LOGICBINOP, vorr,
19234          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19235   VAR10 (BINOP, veor,
19236          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19237   VAR10 (LOGICBINOP, vbic,
19238          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di),
19239   VAR10 (LOGICBINOP, vorn,
19240          v8qi, v4hi, v2si, v2sf, di, v16qi, v8hi, v4si, v4sf, v2di)
19241 };
19242
19243 #undef CF
19244 #undef VAR1
19245 #undef VAR2
19246 #undef VAR3
19247 #undef VAR4
19248 #undef VAR5
19249 #undef VAR6
19250 #undef VAR7
19251 #undef VAR8
19252 #undef VAR9
19253 #undef VAR10
19254
19255 /* Neon defines builtins from ARM_BUILTIN_MAX upwards, though they don't have
19256    symbolic names defined here (which would require too much duplication).
19257    FIXME?  */
19258 enum arm_builtins
19259 {
19260   ARM_BUILTIN_GETWCX,
19261   ARM_BUILTIN_SETWCX,
19262
19263   ARM_BUILTIN_WZERO,
19264
19265   ARM_BUILTIN_WAVG2BR,
19266   ARM_BUILTIN_WAVG2HR,
19267   ARM_BUILTIN_WAVG2B,
19268   ARM_BUILTIN_WAVG2H,
19269
19270   ARM_BUILTIN_WACCB,
19271   ARM_BUILTIN_WACCH,
19272   ARM_BUILTIN_WACCW,
19273
19274   ARM_BUILTIN_WMACS,
19275   ARM_BUILTIN_WMACSZ,
19276   ARM_BUILTIN_WMACU,
19277   ARM_BUILTIN_WMACUZ,
19278
19279   ARM_BUILTIN_WSADB,
19280   ARM_BUILTIN_WSADBZ,
19281   ARM_BUILTIN_WSADH,
19282   ARM_BUILTIN_WSADHZ,
19283
19284   ARM_BUILTIN_WALIGN,
19285
19286   ARM_BUILTIN_TMIA,
19287   ARM_BUILTIN_TMIAPH,
19288   ARM_BUILTIN_TMIABB,
19289   ARM_BUILTIN_TMIABT,
19290   ARM_BUILTIN_TMIATB,
19291   ARM_BUILTIN_TMIATT,
19292
19293   ARM_BUILTIN_TMOVMSKB,
19294   ARM_BUILTIN_TMOVMSKH,
19295   ARM_BUILTIN_TMOVMSKW,
19296
19297   ARM_BUILTIN_TBCSTB,
19298   ARM_BUILTIN_TBCSTH,
19299   ARM_BUILTIN_TBCSTW,
19300
19301   ARM_BUILTIN_WMADDS,
19302   ARM_BUILTIN_WMADDU,
19303
19304   ARM_BUILTIN_WPACKHSS,
19305   ARM_BUILTIN_WPACKWSS,
19306   ARM_BUILTIN_WPACKDSS,
19307   ARM_BUILTIN_WPACKHUS,
19308   ARM_BUILTIN_WPACKWUS,
19309   ARM_BUILTIN_WPACKDUS,
19310
19311   ARM_BUILTIN_WADDB,
19312   ARM_BUILTIN_WADDH,
19313   ARM_BUILTIN_WADDW,
19314   ARM_BUILTIN_WADDSSB,
19315   ARM_BUILTIN_WADDSSH,
19316   ARM_BUILTIN_WADDSSW,
19317   ARM_BUILTIN_WADDUSB,
19318   ARM_BUILTIN_WADDUSH,
19319   ARM_BUILTIN_WADDUSW,
19320   ARM_BUILTIN_WSUBB,
19321   ARM_BUILTIN_WSUBH,
19322   ARM_BUILTIN_WSUBW,
19323   ARM_BUILTIN_WSUBSSB,
19324   ARM_BUILTIN_WSUBSSH,
19325   ARM_BUILTIN_WSUBSSW,
19326   ARM_BUILTIN_WSUBUSB,
19327   ARM_BUILTIN_WSUBUSH,
19328   ARM_BUILTIN_WSUBUSW,
19329
19330   ARM_BUILTIN_WAND,
19331   ARM_BUILTIN_WANDN,
19332   ARM_BUILTIN_WOR,
19333   ARM_BUILTIN_WXOR,
19334
19335   ARM_BUILTIN_WCMPEQB,
19336   ARM_BUILTIN_WCMPEQH,
19337   ARM_BUILTIN_WCMPEQW,
19338   ARM_BUILTIN_WCMPGTUB,
19339   ARM_BUILTIN_WCMPGTUH,
19340   ARM_BUILTIN_WCMPGTUW,
19341   ARM_BUILTIN_WCMPGTSB,
19342   ARM_BUILTIN_WCMPGTSH,
19343   ARM_BUILTIN_WCMPGTSW,
19344
19345   ARM_BUILTIN_TEXTRMSB,
19346   ARM_BUILTIN_TEXTRMSH,
19347   ARM_BUILTIN_TEXTRMSW,
19348   ARM_BUILTIN_TEXTRMUB,
19349   ARM_BUILTIN_TEXTRMUH,
19350   ARM_BUILTIN_TEXTRMUW,
19351   ARM_BUILTIN_TINSRB,
19352   ARM_BUILTIN_TINSRH,
19353   ARM_BUILTIN_TINSRW,
19354
19355   ARM_BUILTIN_WMAXSW,
19356   ARM_BUILTIN_WMAXSH,
19357   ARM_BUILTIN_WMAXSB,
19358   ARM_BUILTIN_WMAXUW,
19359   ARM_BUILTIN_WMAXUH,
19360   ARM_BUILTIN_WMAXUB,
19361   ARM_BUILTIN_WMINSW,
19362   ARM_BUILTIN_WMINSH,
19363   ARM_BUILTIN_WMINSB,
19364   ARM_BUILTIN_WMINUW,
19365   ARM_BUILTIN_WMINUH,
19366   ARM_BUILTIN_WMINUB,
19367
19368   ARM_BUILTIN_WMULUM,
19369   ARM_BUILTIN_WMULSM,
19370   ARM_BUILTIN_WMULUL,
19371
19372   ARM_BUILTIN_PSADBH,
19373   ARM_BUILTIN_WSHUFH,
19374
19375   ARM_BUILTIN_WSLLH,
19376   ARM_BUILTIN_WSLLW,
19377   ARM_BUILTIN_WSLLD,
19378   ARM_BUILTIN_WSRAH,
19379   ARM_BUILTIN_WSRAW,
19380   ARM_BUILTIN_WSRAD,
19381   ARM_BUILTIN_WSRLH,
19382   ARM_BUILTIN_WSRLW,
19383   ARM_BUILTIN_WSRLD,
19384   ARM_BUILTIN_WRORH,
19385   ARM_BUILTIN_WRORW,
19386   ARM_BUILTIN_WRORD,
19387   ARM_BUILTIN_WSLLHI,
19388   ARM_BUILTIN_WSLLWI,
19389   ARM_BUILTIN_WSLLDI,
19390   ARM_BUILTIN_WSRAHI,
19391   ARM_BUILTIN_WSRAWI,
19392   ARM_BUILTIN_WSRADI,
19393   ARM_BUILTIN_WSRLHI,
19394   ARM_BUILTIN_WSRLWI,
19395   ARM_BUILTIN_WSRLDI,
19396   ARM_BUILTIN_WRORHI,
19397   ARM_BUILTIN_WRORWI,
19398   ARM_BUILTIN_WRORDI,
19399
19400   ARM_BUILTIN_WUNPCKIHB,
19401   ARM_BUILTIN_WUNPCKIHH,
19402   ARM_BUILTIN_WUNPCKIHW,
19403   ARM_BUILTIN_WUNPCKILB,
19404   ARM_BUILTIN_WUNPCKILH,
19405   ARM_BUILTIN_WUNPCKILW,
19406
19407   ARM_BUILTIN_WUNPCKEHSB,
19408   ARM_BUILTIN_WUNPCKEHSH,
19409   ARM_BUILTIN_WUNPCKEHSW,
19410   ARM_BUILTIN_WUNPCKEHUB,
19411   ARM_BUILTIN_WUNPCKEHUH,
19412   ARM_BUILTIN_WUNPCKEHUW,
19413   ARM_BUILTIN_WUNPCKELSB,
19414   ARM_BUILTIN_WUNPCKELSH,
19415   ARM_BUILTIN_WUNPCKELSW,
19416   ARM_BUILTIN_WUNPCKELUB,
19417   ARM_BUILTIN_WUNPCKELUH,
19418   ARM_BUILTIN_WUNPCKELUW,
19419
19420   ARM_BUILTIN_THREAD_POINTER,
19421
19422   ARM_BUILTIN_NEON_BASE,
19423
19424   ARM_BUILTIN_MAX = ARM_BUILTIN_NEON_BASE + ARRAY_SIZE (neon_builtin_data)
19425 };
19426
19427 static GTY(()) tree arm_builtin_decls[ARM_BUILTIN_MAX];
19428
19429 static void
19430 arm_init_neon_builtins (void)
19431 {
19432   unsigned int i, fcode;
19433   tree decl;
19434
19435   tree neon_intQI_type_node;
19436   tree neon_intHI_type_node;
19437   tree neon_polyQI_type_node;
19438   tree neon_polyHI_type_node;
19439   tree neon_intSI_type_node;
19440   tree neon_intDI_type_node;
19441   tree neon_float_type_node;
19442
19443   tree intQI_pointer_node;
19444   tree intHI_pointer_node;
19445   tree intSI_pointer_node;
19446   tree intDI_pointer_node;
19447   tree float_pointer_node;
19448
19449   tree const_intQI_node;
19450   tree const_intHI_node;
19451   tree const_intSI_node;
19452   tree const_intDI_node;
19453   tree const_float_node;
19454
19455   tree const_intQI_pointer_node;
19456   tree const_intHI_pointer_node;
19457   tree const_intSI_pointer_node;
19458   tree const_intDI_pointer_node;
19459   tree const_float_pointer_node;
19460
19461   tree V8QI_type_node;
19462   tree V4HI_type_node;
19463   tree V2SI_type_node;
19464   tree V2SF_type_node;
19465   tree V16QI_type_node;
19466   tree V8HI_type_node;
19467   tree V4SI_type_node;
19468   tree V4SF_type_node;
19469   tree V2DI_type_node;
19470
19471   tree intUQI_type_node;
19472   tree intUHI_type_node;
19473   tree intUSI_type_node;
19474   tree intUDI_type_node;
19475
19476   tree intEI_type_node;
19477   tree intOI_type_node;
19478   tree intCI_type_node;
19479   tree intXI_type_node;
19480
19481   tree V8QI_pointer_node;
19482   tree V4HI_pointer_node;
19483   tree V2SI_pointer_node;
19484   tree V2SF_pointer_node;
19485   tree V16QI_pointer_node;
19486   tree V8HI_pointer_node;
19487   tree V4SI_pointer_node;
19488   tree V4SF_pointer_node;
19489   tree V2DI_pointer_node;
19490
19491   tree void_ftype_pv8qi_v8qi_v8qi;
19492   tree void_ftype_pv4hi_v4hi_v4hi;
19493   tree void_ftype_pv2si_v2si_v2si;
19494   tree void_ftype_pv2sf_v2sf_v2sf;
19495   tree void_ftype_pdi_di_di;
19496   tree void_ftype_pv16qi_v16qi_v16qi;
19497   tree void_ftype_pv8hi_v8hi_v8hi;
19498   tree void_ftype_pv4si_v4si_v4si;
19499   tree void_ftype_pv4sf_v4sf_v4sf;
19500   tree void_ftype_pv2di_v2di_v2di;
19501
19502   tree reinterp_ftype_dreg[5][5];
19503   tree reinterp_ftype_qreg[5][5];
19504   tree dreg_types[5], qreg_types[5];
19505
19506   /* Create distinguished type nodes for NEON vector element types,
19507      and pointers to values of such types, so we can detect them later.  */
19508   neon_intQI_type_node = make_signed_type (GET_MODE_PRECISION (QImode));
19509   neon_intHI_type_node = make_signed_type (GET_MODE_PRECISION (HImode));
19510   neon_polyQI_type_node = make_signed_type (GET_MODE_PRECISION (QImode));
19511   neon_polyHI_type_node = make_signed_type (GET_MODE_PRECISION (HImode));
19512   neon_intSI_type_node = make_signed_type (GET_MODE_PRECISION (SImode));
19513   neon_intDI_type_node = make_signed_type (GET_MODE_PRECISION (DImode));
19514   neon_float_type_node = make_node (REAL_TYPE);
19515   TYPE_PRECISION (neon_float_type_node) = FLOAT_TYPE_SIZE;
19516   layout_type (neon_float_type_node);
19517
19518   /* Define typedefs which exactly correspond to the modes we are basing vector
19519      types on.  If you change these names you'll need to change
19520      the table used by arm_mangle_type too.  */
19521   (*lang_hooks.types.register_builtin_type) (neon_intQI_type_node,
19522                                              "__builtin_neon_qi");
19523   (*lang_hooks.types.register_builtin_type) (neon_intHI_type_node,
19524                                              "__builtin_neon_hi");
19525   (*lang_hooks.types.register_builtin_type) (neon_intSI_type_node,
19526                                              "__builtin_neon_si");
19527   (*lang_hooks.types.register_builtin_type) (neon_float_type_node,
19528                                              "__builtin_neon_sf");
19529   (*lang_hooks.types.register_builtin_type) (neon_intDI_type_node,
19530                                              "__builtin_neon_di");
19531   (*lang_hooks.types.register_builtin_type) (neon_polyQI_type_node,
19532                                              "__builtin_neon_poly8");
19533   (*lang_hooks.types.register_builtin_type) (neon_polyHI_type_node,
19534                                              "__builtin_neon_poly16");
19535
19536   intQI_pointer_node = build_pointer_type (neon_intQI_type_node);
19537   intHI_pointer_node = build_pointer_type (neon_intHI_type_node);
19538   intSI_pointer_node = build_pointer_type (neon_intSI_type_node);
19539   intDI_pointer_node = build_pointer_type (neon_intDI_type_node);
19540   float_pointer_node = build_pointer_type (neon_float_type_node);
19541
19542   /* Next create constant-qualified versions of the above types.  */
19543   const_intQI_node = build_qualified_type (neon_intQI_type_node,
19544                                            TYPE_QUAL_CONST);
19545   const_intHI_node = build_qualified_type (neon_intHI_type_node,
19546                                            TYPE_QUAL_CONST);
19547   const_intSI_node = build_qualified_type (neon_intSI_type_node,
19548                                            TYPE_QUAL_CONST);
19549   const_intDI_node = build_qualified_type (neon_intDI_type_node,
19550                                            TYPE_QUAL_CONST);
19551   const_float_node = build_qualified_type (neon_float_type_node,
19552                                            TYPE_QUAL_CONST);
19553
19554   const_intQI_pointer_node = build_pointer_type (const_intQI_node);
19555   const_intHI_pointer_node = build_pointer_type (const_intHI_node);
19556   const_intSI_pointer_node = build_pointer_type (const_intSI_node);
19557   const_intDI_pointer_node = build_pointer_type (const_intDI_node);
19558   const_float_pointer_node = build_pointer_type (const_float_node);
19559
19560   /* Now create vector types based on our NEON element types.  */
19561   /* 64-bit vectors.  */
19562   V8QI_type_node =
19563     build_vector_type_for_mode (neon_intQI_type_node, V8QImode);
19564   V4HI_type_node =
19565     build_vector_type_for_mode (neon_intHI_type_node, V4HImode);
19566   V2SI_type_node =
19567     build_vector_type_for_mode (neon_intSI_type_node, V2SImode);
19568   V2SF_type_node =
19569     build_vector_type_for_mode (neon_float_type_node, V2SFmode);
19570   /* 128-bit vectors.  */
19571   V16QI_type_node =
19572     build_vector_type_for_mode (neon_intQI_type_node, V16QImode);
19573   V8HI_type_node =
19574     build_vector_type_for_mode (neon_intHI_type_node, V8HImode);
19575   V4SI_type_node =
19576     build_vector_type_for_mode (neon_intSI_type_node, V4SImode);
19577   V4SF_type_node =
19578     build_vector_type_for_mode (neon_float_type_node, V4SFmode);
19579   V2DI_type_node =
19580     build_vector_type_for_mode (neon_intDI_type_node, V2DImode);
19581
19582   /* Unsigned integer types for various mode sizes.  */
19583   intUQI_type_node = make_unsigned_type (GET_MODE_PRECISION (QImode));
19584   intUHI_type_node = make_unsigned_type (GET_MODE_PRECISION (HImode));
19585   intUSI_type_node = make_unsigned_type (GET_MODE_PRECISION (SImode));
19586   intUDI_type_node = make_unsigned_type (GET_MODE_PRECISION (DImode));
19587
19588   (*lang_hooks.types.register_builtin_type) (intUQI_type_node,
19589                                              "__builtin_neon_uqi");
19590   (*lang_hooks.types.register_builtin_type) (intUHI_type_node,
19591                                              "__builtin_neon_uhi");
19592   (*lang_hooks.types.register_builtin_type) (intUSI_type_node,
19593                                              "__builtin_neon_usi");
19594   (*lang_hooks.types.register_builtin_type) (intUDI_type_node,
19595                                              "__builtin_neon_udi");
19596
19597   /* Opaque integer types for structures of vectors.  */
19598   intEI_type_node = make_signed_type (GET_MODE_PRECISION (EImode));
19599   intOI_type_node = make_signed_type (GET_MODE_PRECISION (OImode));
19600   intCI_type_node = make_signed_type (GET_MODE_PRECISION (CImode));
19601   intXI_type_node = make_signed_type (GET_MODE_PRECISION (XImode));
19602
19603   (*lang_hooks.types.register_builtin_type) (intTI_type_node,
19604                                              "__builtin_neon_ti");
19605   (*lang_hooks.types.register_builtin_type) (intEI_type_node,
19606                                              "__builtin_neon_ei");
19607   (*lang_hooks.types.register_builtin_type) (intOI_type_node,
19608                                              "__builtin_neon_oi");
19609   (*lang_hooks.types.register_builtin_type) (intCI_type_node,
19610                                              "__builtin_neon_ci");
19611   (*lang_hooks.types.register_builtin_type) (intXI_type_node,
19612                                              "__builtin_neon_xi");
19613
19614   /* Pointers to vector types.  */
19615   V8QI_pointer_node = build_pointer_type (V8QI_type_node);
19616   V4HI_pointer_node = build_pointer_type (V4HI_type_node);
19617   V2SI_pointer_node = build_pointer_type (V2SI_type_node);
19618   V2SF_pointer_node = build_pointer_type (V2SF_type_node);
19619   V16QI_pointer_node = build_pointer_type (V16QI_type_node);
19620   V8HI_pointer_node = build_pointer_type (V8HI_type_node);
19621   V4SI_pointer_node = build_pointer_type (V4SI_type_node);
19622   V4SF_pointer_node = build_pointer_type (V4SF_type_node);
19623   V2DI_pointer_node = build_pointer_type (V2DI_type_node);
19624
19625   /* Operations which return results as pairs.  */
19626   void_ftype_pv8qi_v8qi_v8qi =
19627     build_function_type_list (void_type_node, V8QI_pointer_node, V8QI_type_node,
19628                               V8QI_type_node, NULL);
19629   void_ftype_pv4hi_v4hi_v4hi =
19630     build_function_type_list (void_type_node, V4HI_pointer_node, V4HI_type_node,
19631                               V4HI_type_node, NULL);
19632   void_ftype_pv2si_v2si_v2si =
19633     build_function_type_list (void_type_node, V2SI_pointer_node, V2SI_type_node,
19634                               V2SI_type_node, NULL);
19635   void_ftype_pv2sf_v2sf_v2sf =
19636     build_function_type_list (void_type_node, V2SF_pointer_node, V2SF_type_node,
19637                               V2SF_type_node, NULL);
19638   void_ftype_pdi_di_di =
19639     build_function_type_list (void_type_node, intDI_pointer_node,
19640                               neon_intDI_type_node, neon_intDI_type_node, NULL);
19641   void_ftype_pv16qi_v16qi_v16qi =
19642     build_function_type_list (void_type_node, V16QI_pointer_node,
19643                               V16QI_type_node, V16QI_type_node, NULL);
19644   void_ftype_pv8hi_v8hi_v8hi =
19645     build_function_type_list (void_type_node, V8HI_pointer_node, V8HI_type_node,
19646                               V8HI_type_node, NULL);
19647   void_ftype_pv4si_v4si_v4si =
19648     build_function_type_list (void_type_node, V4SI_pointer_node, V4SI_type_node,
19649                               V4SI_type_node, NULL);
19650   void_ftype_pv4sf_v4sf_v4sf =
19651     build_function_type_list (void_type_node, V4SF_pointer_node, V4SF_type_node,
19652                               V4SF_type_node, NULL);
19653   void_ftype_pv2di_v2di_v2di =
19654     build_function_type_list (void_type_node, V2DI_pointer_node, V2DI_type_node,
19655                               V2DI_type_node, NULL);
19656
19657   dreg_types[0] = V8QI_type_node;
19658   dreg_types[1] = V4HI_type_node;
19659   dreg_types[2] = V2SI_type_node;
19660   dreg_types[3] = V2SF_type_node;
19661   dreg_types[4] = neon_intDI_type_node;
19662
19663   qreg_types[0] = V16QI_type_node;
19664   qreg_types[1] = V8HI_type_node;
19665   qreg_types[2] = V4SI_type_node;
19666   qreg_types[3] = V4SF_type_node;
19667   qreg_types[4] = V2DI_type_node;
19668
19669   for (i = 0; i < 5; i++)
19670     {
19671       int j;
19672       for (j = 0; j < 5; j++)
19673         {
19674           reinterp_ftype_dreg[i][j]
19675             = build_function_type_list (dreg_types[i], dreg_types[j], NULL);
19676           reinterp_ftype_qreg[i][j]
19677             = build_function_type_list (qreg_types[i], qreg_types[j], NULL);
19678         }
19679     }
19680
19681   for (i = 0, fcode = ARM_BUILTIN_NEON_BASE;
19682        i < ARRAY_SIZE (neon_builtin_data);
19683        i++, fcode++)
19684     {
19685       neon_builtin_datum *d = &neon_builtin_data[i];
19686
19687       const char* const modenames[] = {
19688         "v8qi", "v4hi", "v2si", "v2sf", "di",
19689         "v16qi", "v8hi", "v4si", "v4sf", "v2di",
19690         "ti", "ei", "oi"
19691       };
19692       char namebuf[60];
19693       tree ftype = NULL;
19694       int is_load = 0, is_store = 0;
19695
19696       gcc_assert (ARRAY_SIZE (modenames) == T_MAX);
19697
19698       d->fcode = fcode;
19699
19700       switch (d->itype)
19701         {
19702         case NEON_LOAD1:
19703         case NEON_LOAD1LANE:
19704         case NEON_LOADSTRUCT:
19705         case NEON_LOADSTRUCTLANE:
19706           is_load = 1;
19707           /* Fall through.  */
19708         case NEON_STORE1:
19709         case NEON_STORE1LANE:
19710         case NEON_STORESTRUCT:
19711         case NEON_STORESTRUCTLANE:
19712           if (!is_load)
19713             is_store = 1;
19714           /* Fall through.  */
19715         case NEON_UNOP:
19716         case NEON_BINOP:
19717         case NEON_LOGICBINOP:
19718         case NEON_SHIFTINSERT:
19719         case NEON_TERNOP:
19720         case NEON_GETLANE:
19721         case NEON_SETLANE:
19722         case NEON_CREATE:
19723         case NEON_DUP:
19724         case NEON_DUPLANE:
19725         case NEON_SHIFTIMM:
19726         case NEON_SHIFTACC:
19727         case NEON_COMBINE:
19728         case NEON_SPLIT:
19729         case NEON_CONVERT:
19730         case NEON_FIXCONV:
19731         case NEON_LANEMUL:
19732         case NEON_LANEMULL:
19733         case NEON_LANEMULH:
19734         case NEON_LANEMAC:
19735         case NEON_SCALARMUL:
19736         case NEON_SCALARMULL:
19737         case NEON_SCALARMULH:
19738         case NEON_SCALARMAC:
19739         case NEON_SELECT:
19740         case NEON_VTBL:
19741         case NEON_VTBX:
19742           {
19743             int k;
19744             tree return_type = void_type_node, args = void_list_node;
19745
19746             /* Build a function type directly from the insn_data for
19747                this builtin.  The build_function_type() function takes
19748                care of removing duplicates for us.  */
19749             for (k = insn_data[d->code].n_generator_args - 1; k >= 0; k--)
19750               {
19751                 tree eltype;
19752
19753                 if (is_load && k == 1)
19754                   {
19755                     /* Neon load patterns always have the memory
19756                        operand in the operand 1 position.  */
19757                     gcc_assert (insn_data[d->code].operand[k].predicate
19758                                 == neon_struct_operand);
19759
19760                     switch (d->mode)
19761                       {
19762                       case T_V8QI:
19763                       case T_V16QI:
19764                         eltype = const_intQI_pointer_node;
19765                         break;
19766
19767                       case T_V4HI:
19768                       case T_V8HI:
19769                         eltype = const_intHI_pointer_node;
19770                         break;
19771
19772                       case T_V2SI:
19773                       case T_V4SI:
19774                         eltype = const_intSI_pointer_node;
19775                         break;
19776
19777                       case T_V2SF:
19778                       case T_V4SF:
19779                         eltype = const_float_pointer_node;
19780                         break;
19781
19782                       case T_DI:
19783                       case T_V2DI:
19784                         eltype = const_intDI_pointer_node;
19785                         break;
19786
19787                       default: gcc_unreachable ();
19788                       }
19789                   }
19790                 else if (is_store && k == 0)
19791                   {
19792                     /* Similarly, Neon store patterns use operand 0 as
19793                        the memory location to store to.  */
19794                     gcc_assert (insn_data[d->code].operand[k].predicate
19795                                 == neon_struct_operand);
19796
19797                     switch (d->mode)
19798                       {
19799                       case T_V8QI:
19800                       case T_V16QI:
19801                         eltype = intQI_pointer_node;
19802                         break;
19803
19804                       case T_V4HI:
19805                       case T_V8HI:
19806                         eltype = intHI_pointer_node;
19807                         break;
19808
19809                       case T_V2SI:
19810                       case T_V4SI:
19811                         eltype = intSI_pointer_node;
19812                         break;
19813
19814                       case T_V2SF:
19815                       case T_V4SF:
19816                         eltype = float_pointer_node;
19817                         break;
19818
19819                       case T_DI:
19820                       case T_V2DI:
19821                         eltype = intDI_pointer_node;
19822                         break;
19823
19824                       default: gcc_unreachable ();
19825                       }
19826                   }
19827                 else
19828                   {
19829                     switch (insn_data[d->code].operand[k].mode)
19830                       {
19831                       case VOIDmode: eltype = void_type_node; break;
19832                         /* Scalars.  */
19833                       case QImode: eltype = neon_intQI_type_node; break;
19834                       case HImode: eltype = neon_intHI_type_node; break;
19835                       case SImode: eltype = neon_intSI_type_node; break;
19836                       case SFmode: eltype = neon_float_type_node; break;
19837                       case DImode: eltype = neon_intDI_type_node; break;
19838                       case TImode: eltype = intTI_type_node; break;
19839                       case EImode: eltype = intEI_type_node; break;
19840                       case OImode: eltype = intOI_type_node; break;
19841                       case CImode: eltype = intCI_type_node; break;
19842                       case XImode: eltype = intXI_type_node; break;
19843                         /* 64-bit vectors.  */
19844                       case V8QImode: eltype = V8QI_type_node; break;
19845                       case V4HImode: eltype = V4HI_type_node; break;
19846                       case V2SImode: eltype = V2SI_type_node; break;
19847                       case V2SFmode: eltype = V2SF_type_node; break;
19848                         /* 128-bit vectors.  */
19849                       case V16QImode: eltype = V16QI_type_node; break;
19850                       case V8HImode: eltype = V8HI_type_node; break;
19851                       case V4SImode: eltype = V4SI_type_node; break;
19852                       case V4SFmode: eltype = V4SF_type_node; break;
19853                       case V2DImode: eltype = V2DI_type_node; break;
19854                       default: gcc_unreachable ();
19855                       }
19856                   }
19857
19858                 if (k == 0 && !is_store)
19859                   return_type = eltype;
19860                 else
19861                   args = tree_cons (NULL_TREE, eltype, args);
19862               }
19863
19864             ftype = build_function_type (return_type, args);
19865           }
19866           break;
19867
19868         case NEON_RESULTPAIR:
19869           {
19870             switch (insn_data[d->code].operand[1].mode)
19871               {
19872               case V8QImode: ftype = void_ftype_pv8qi_v8qi_v8qi; break;
19873               case V4HImode: ftype = void_ftype_pv4hi_v4hi_v4hi; break;
19874               case V2SImode: ftype = void_ftype_pv2si_v2si_v2si; break;
19875               case V2SFmode: ftype = void_ftype_pv2sf_v2sf_v2sf; break;
19876               case DImode: ftype = void_ftype_pdi_di_di; break;
19877               case V16QImode: ftype = void_ftype_pv16qi_v16qi_v16qi; break;
19878               case V8HImode: ftype = void_ftype_pv8hi_v8hi_v8hi; break;
19879               case V4SImode: ftype = void_ftype_pv4si_v4si_v4si; break;
19880               case V4SFmode: ftype = void_ftype_pv4sf_v4sf_v4sf; break;
19881               case V2DImode: ftype = void_ftype_pv2di_v2di_v2di; break;
19882               default: gcc_unreachable ();
19883               }
19884           }
19885           break;
19886
19887         case NEON_REINTERP:
19888           {
19889             /* We iterate over 5 doubleword types, then 5 quadword
19890                types.  */
19891             int rhs = d->mode % 5;
19892             switch (insn_data[d->code].operand[0].mode)
19893               {
19894               case V8QImode: ftype = reinterp_ftype_dreg[0][rhs]; break;
19895               case V4HImode: ftype = reinterp_ftype_dreg[1][rhs]; break;
19896               case V2SImode: ftype = reinterp_ftype_dreg[2][rhs]; break;
19897               case V2SFmode: ftype = reinterp_ftype_dreg[3][rhs]; break;
19898               case DImode: ftype = reinterp_ftype_dreg[4][rhs]; break;
19899               case V16QImode: ftype = reinterp_ftype_qreg[0][rhs]; break;
19900               case V8HImode: ftype = reinterp_ftype_qreg[1][rhs]; break;
19901               case V4SImode: ftype = reinterp_ftype_qreg[2][rhs]; break;
19902               case V4SFmode: ftype = reinterp_ftype_qreg[3][rhs]; break;
19903               case V2DImode: ftype = reinterp_ftype_qreg[4][rhs]; break;
19904               default: gcc_unreachable ();
19905               }
19906           }
19907           break;
19908
19909         default:
19910           gcc_unreachable ();
19911         }
19912
19913       gcc_assert (ftype != NULL);
19914
19915       sprintf (namebuf, "__builtin_neon_%s%s", d->name, modenames[d->mode]);
19916
19917       decl = add_builtin_function (namebuf, ftype, fcode, BUILT_IN_MD, NULL,
19918                                    NULL_TREE);
19919       arm_builtin_decls[fcode] = decl;
19920     }
19921 }
19922
19923 #define def_mbuiltin(MASK, NAME, TYPE, CODE)                            \
19924   do                                                                    \
19925     {                                                                   \
19926       if ((MASK) & insn_flags)                                          \
19927         {                                                               \
19928           tree bdecl;                                                   \
19929           bdecl = add_builtin_function ((NAME), (TYPE), (CODE),         \
19930                                         BUILT_IN_MD, NULL, NULL_TREE);  \
19931           arm_builtin_decls[CODE] = bdecl;                              \
19932         }                                                               \
19933     }                                                                   \
19934   while (0)
19935
19936 struct builtin_description
19937 {
19938   const unsigned int       mask;
19939   const enum insn_code     icode;
19940   const char * const       name;
19941   const enum arm_builtins  code;
19942   const enum rtx_code      comparison;
19943   const unsigned int       flag;
19944 };
19945   
19946 static const struct builtin_description bdesc_2arg[] =
19947 {
19948 #define IWMMXT_BUILTIN(code, string, builtin) \
19949   { FL_IWMMXT, CODE_FOR_##code, "__builtin_arm_" string, \
19950     ARM_BUILTIN_##builtin, UNKNOWN, 0 },
19951
19952   IWMMXT_BUILTIN (addv8qi3, "waddb", WADDB)
19953   IWMMXT_BUILTIN (addv4hi3, "waddh", WADDH)
19954   IWMMXT_BUILTIN (addv2si3, "waddw", WADDW)
19955   IWMMXT_BUILTIN (subv8qi3, "wsubb", WSUBB)
19956   IWMMXT_BUILTIN (subv4hi3, "wsubh", WSUBH)
19957   IWMMXT_BUILTIN (subv2si3, "wsubw", WSUBW)
19958   IWMMXT_BUILTIN (ssaddv8qi3, "waddbss", WADDSSB)
19959   IWMMXT_BUILTIN (ssaddv4hi3, "waddhss", WADDSSH)
19960   IWMMXT_BUILTIN (ssaddv2si3, "waddwss", WADDSSW)
19961   IWMMXT_BUILTIN (sssubv8qi3, "wsubbss", WSUBSSB)
19962   IWMMXT_BUILTIN (sssubv4hi3, "wsubhss", WSUBSSH)
19963   IWMMXT_BUILTIN (sssubv2si3, "wsubwss", WSUBSSW)
19964   IWMMXT_BUILTIN (usaddv8qi3, "waddbus", WADDUSB)
19965   IWMMXT_BUILTIN (usaddv4hi3, "waddhus", WADDUSH)
19966   IWMMXT_BUILTIN (usaddv2si3, "waddwus", WADDUSW)
19967   IWMMXT_BUILTIN (ussubv8qi3, "wsubbus", WSUBUSB)
19968   IWMMXT_BUILTIN (ussubv4hi3, "wsubhus", WSUBUSH)
19969   IWMMXT_BUILTIN (ussubv2si3, "wsubwus", WSUBUSW)
19970   IWMMXT_BUILTIN (mulv4hi3, "wmulul", WMULUL)
19971   IWMMXT_BUILTIN (smulv4hi3_highpart, "wmulsm", WMULSM)
19972   IWMMXT_BUILTIN (umulv4hi3_highpart, "wmulum", WMULUM)
19973   IWMMXT_BUILTIN (eqv8qi3, "wcmpeqb", WCMPEQB)
19974   IWMMXT_BUILTIN (eqv4hi3, "wcmpeqh", WCMPEQH)
19975   IWMMXT_BUILTIN (eqv2si3, "wcmpeqw", WCMPEQW)
19976   IWMMXT_BUILTIN (gtuv8qi3, "wcmpgtub", WCMPGTUB)
19977   IWMMXT_BUILTIN (gtuv4hi3, "wcmpgtuh", WCMPGTUH)
19978   IWMMXT_BUILTIN (gtuv2si3, "wcmpgtuw", WCMPGTUW)
19979   IWMMXT_BUILTIN (gtv8qi3, "wcmpgtsb", WCMPGTSB)
19980   IWMMXT_BUILTIN (gtv4hi3, "wcmpgtsh", WCMPGTSH)
19981   IWMMXT_BUILTIN (gtv2si3, "wcmpgtsw", WCMPGTSW)
19982   IWMMXT_BUILTIN (umaxv8qi3, "wmaxub", WMAXUB)
19983   IWMMXT_BUILTIN (smaxv8qi3, "wmaxsb", WMAXSB)
19984   IWMMXT_BUILTIN (umaxv4hi3, "wmaxuh", WMAXUH)
19985   IWMMXT_BUILTIN (smaxv4hi3, "wmaxsh", WMAXSH)
19986   IWMMXT_BUILTIN (umaxv2si3, "wmaxuw", WMAXUW)
19987   IWMMXT_BUILTIN (smaxv2si3, "wmaxsw", WMAXSW)
19988   IWMMXT_BUILTIN (uminv8qi3, "wminub", WMINUB)
19989   IWMMXT_BUILTIN (sminv8qi3, "wminsb", WMINSB)
19990   IWMMXT_BUILTIN (uminv4hi3, "wminuh", WMINUH)
19991   IWMMXT_BUILTIN (sminv4hi3, "wminsh", WMINSH)
19992   IWMMXT_BUILTIN (uminv2si3, "wminuw", WMINUW)
19993   IWMMXT_BUILTIN (sminv2si3, "wminsw", WMINSW)
19994   IWMMXT_BUILTIN (iwmmxt_anddi3, "wand", WAND)
19995   IWMMXT_BUILTIN (iwmmxt_nanddi3, "wandn", WANDN)
19996   IWMMXT_BUILTIN (iwmmxt_iordi3, "wor", WOR)
19997   IWMMXT_BUILTIN (iwmmxt_xordi3, "wxor", WXOR)
19998   IWMMXT_BUILTIN (iwmmxt_uavgv8qi3, "wavg2b", WAVG2B)
19999   IWMMXT_BUILTIN (iwmmxt_uavgv4hi3, "wavg2h", WAVG2H)
20000   IWMMXT_BUILTIN (iwmmxt_uavgrndv8qi3, "wavg2br", WAVG2BR)
20001   IWMMXT_BUILTIN (iwmmxt_uavgrndv4hi3, "wavg2hr", WAVG2HR)
20002   IWMMXT_BUILTIN (iwmmxt_wunpckilb, "wunpckilb", WUNPCKILB)
20003   IWMMXT_BUILTIN (iwmmxt_wunpckilh, "wunpckilh", WUNPCKILH)
20004   IWMMXT_BUILTIN (iwmmxt_wunpckilw, "wunpckilw", WUNPCKILW)
20005   IWMMXT_BUILTIN (iwmmxt_wunpckihb, "wunpckihb", WUNPCKIHB)
20006   IWMMXT_BUILTIN (iwmmxt_wunpckihh, "wunpckihh", WUNPCKIHH)
20007   IWMMXT_BUILTIN (iwmmxt_wunpckihw, "wunpckihw", WUNPCKIHW)
20008   IWMMXT_BUILTIN (iwmmxt_wmadds, "wmadds", WMADDS)
20009   IWMMXT_BUILTIN (iwmmxt_wmaddu, "wmaddu", WMADDU)
20010
20011 #define IWMMXT_BUILTIN2(code, builtin) \
20012   { FL_IWMMXT, CODE_FOR_##code, NULL, ARM_BUILTIN_##builtin, UNKNOWN, 0 },
20013
20014   IWMMXT_BUILTIN2 (iwmmxt_wpackhss, WPACKHSS)
20015   IWMMXT_BUILTIN2 (iwmmxt_wpackwss, WPACKWSS)
20016   IWMMXT_BUILTIN2 (iwmmxt_wpackdss, WPACKDSS)
20017   IWMMXT_BUILTIN2 (iwmmxt_wpackhus, WPACKHUS)
20018   IWMMXT_BUILTIN2 (iwmmxt_wpackwus, WPACKWUS)
20019   IWMMXT_BUILTIN2 (iwmmxt_wpackdus, WPACKDUS)
20020   IWMMXT_BUILTIN2 (ashlv4hi3_di,    WSLLH)
20021   IWMMXT_BUILTIN2 (ashlv4hi3_iwmmxt, WSLLHI)
20022   IWMMXT_BUILTIN2 (ashlv2si3_di,    WSLLW)
20023   IWMMXT_BUILTIN2 (ashlv2si3_iwmmxt, WSLLWI)
20024   IWMMXT_BUILTIN2 (ashldi3_di,      WSLLD)
20025   IWMMXT_BUILTIN2 (ashldi3_iwmmxt,  WSLLDI)
20026   IWMMXT_BUILTIN2 (lshrv4hi3_di,    WSRLH)
20027   IWMMXT_BUILTIN2 (lshrv4hi3_iwmmxt, WSRLHI)
20028   IWMMXT_BUILTIN2 (lshrv2si3_di,    WSRLW)
20029   IWMMXT_BUILTIN2 (lshrv2si3_iwmmxt, WSRLWI)
20030   IWMMXT_BUILTIN2 (lshrdi3_di,      WSRLD)
20031   IWMMXT_BUILTIN2 (lshrdi3_iwmmxt,  WSRLDI)
20032   IWMMXT_BUILTIN2 (ashrv4hi3_di,    WSRAH)
20033   IWMMXT_BUILTIN2 (ashrv4hi3_iwmmxt, WSRAHI)
20034   IWMMXT_BUILTIN2 (ashrv2si3_di,    WSRAW)
20035   IWMMXT_BUILTIN2 (ashrv2si3_iwmmxt, WSRAWI)
20036   IWMMXT_BUILTIN2 (ashrdi3_di,      WSRAD)
20037   IWMMXT_BUILTIN2 (ashrdi3_iwmmxt,  WSRADI)
20038   IWMMXT_BUILTIN2 (rorv4hi3_di,     WRORH)
20039   IWMMXT_BUILTIN2 (rorv4hi3,        WRORHI)
20040   IWMMXT_BUILTIN2 (rorv2si3_di,     WRORW)
20041   IWMMXT_BUILTIN2 (rorv2si3,        WRORWI)
20042   IWMMXT_BUILTIN2 (rordi3_di,       WRORD)
20043   IWMMXT_BUILTIN2 (rordi3,          WRORDI)
20044   IWMMXT_BUILTIN2 (iwmmxt_wmacuz,   WMACUZ)
20045   IWMMXT_BUILTIN2 (iwmmxt_wmacsz,   WMACSZ)
20046 };
20047
20048 static const struct builtin_description bdesc_1arg[] =
20049 {
20050   IWMMXT_BUILTIN (iwmmxt_tmovmskb, "tmovmskb", TMOVMSKB)
20051   IWMMXT_BUILTIN (iwmmxt_tmovmskh, "tmovmskh", TMOVMSKH)
20052   IWMMXT_BUILTIN (iwmmxt_tmovmskw, "tmovmskw", TMOVMSKW)
20053   IWMMXT_BUILTIN (iwmmxt_waccb, "waccb", WACCB)
20054   IWMMXT_BUILTIN (iwmmxt_wacch, "wacch", WACCH)
20055   IWMMXT_BUILTIN (iwmmxt_waccw, "waccw", WACCW)
20056   IWMMXT_BUILTIN (iwmmxt_wunpckehub, "wunpckehub", WUNPCKEHUB)
20057   IWMMXT_BUILTIN (iwmmxt_wunpckehuh, "wunpckehuh", WUNPCKEHUH)
20058   IWMMXT_BUILTIN (iwmmxt_wunpckehuw, "wunpckehuw", WUNPCKEHUW)
20059   IWMMXT_BUILTIN (iwmmxt_wunpckehsb, "wunpckehsb", WUNPCKEHSB)
20060   IWMMXT_BUILTIN (iwmmxt_wunpckehsh, "wunpckehsh", WUNPCKEHSH)
20061   IWMMXT_BUILTIN (iwmmxt_wunpckehsw, "wunpckehsw", WUNPCKEHSW)
20062   IWMMXT_BUILTIN (iwmmxt_wunpckelub, "wunpckelub", WUNPCKELUB)
20063   IWMMXT_BUILTIN (iwmmxt_wunpckeluh, "wunpckeluh", WUNPCKELUH)
20064   IWMMXT_BUILTIN (iwmmxt_wunpckeluw, "wunpckeluw", WUNPCKELUW)
20065   IWMMXT_BUILTIN (iwmmxt_wunpckelsb, "wunpckelsb", WUNPCKELSB)
20066   IWMMXT_BUILTIN (iwmmxt_wunpckelsh, "wunpckelsh", WUNPCKELSH)
20067   IWMMXT_BUILTIN (iwmmxt_wunpckelsw, "wunpckelsw", WUNPCKELSW)
20068 };
20069
20070 /* Set up all the iWMMXt builtins.  This is not called if
20071    TARGET_IWMMXT is zero.  */
20072
20073 static void
20074 arm_init_iwmmxt_builtins (void)
20075 {
20076   const struct builtin_description * d;
20077   size_t i;
20078
20079   tree V2SI_type_node = build_vector_type_for_mode (intSI_type_node, V2SImode);
20080   tree V4HI_type_node = build_vector_type_for_mode (intHI_type_node, V4HImode);
20081   tree V8QI_type_node = build_vector_type_for_mode (intQI_type_node, V8QImode);
20082
20083   tree int_ftype_int
20084     = build_function_type_list (integer_type_node,
20085                                 integer_type_node, NULL_TREE);
20086   tree v8qi_ftype_v8qi_v8qi_int
20087     = build_function_type_list (V8QI_type_node,
20088                                 V8QI_type_node, V8QI_type_node,
20089                                 integer_type_node, NULL_TREE);
20090   tree v4hi_ftype_v4hi_int
20091     = build_function_type_list (V4HI_type_node,
20092                                 V4HI_type_node, integer_type_node, NULL_TREE);
20093   tree v2si_ftype_v2si_int
20094     = build_function_type_list (V2SI_type_node,
20095                                 V2SI_type_node, integer_type_node, NULL_TREE);
20096   tree v2si_ftype_di_di
20097     = build_function_type_list (V2SI_type_node,
20098                                 long_long_integer_type_node,
20099                                 long_long_integer_type_node,
20100                                 NULL_TREE);
20101   tree di_ftype_di_int
20102     = build_function_type_list (long_long_integer_type_node,
20103                                 long_long_integer_type_node,
20104                                 integer_type_node, NULL_TREE);
20105   tree di_ftype_di_int_int
20106     = build_function_type_list (long_long_integer_type_node,
20107                                 long_long_integer_type_node,
20108                                 integer_type_node,
20109                                 integer_type_node, NULL_TREE);
20110   tree int_ftype_v8qi
20111     = build_function_type_list (integer_type_node,
20112                                 V8QI_type_node, NULL_TREE);
20113   tree int_ftype_v4hi
20114     = build_function_type_list (integer_type_node,
20115                                 V4HI_type_node, NULL_TREE);
20116   tree int_ftype_v2si
20117     = build_function_type_list (integer_type_node,
20118                                 V2SI_type_node, NULL_TREE);
20119   tree int_ftype_v8qi_int
20120     = build_function_type_list (integer_type_node,
20121                                 V8QI_type_node, integer_type_node, NULL_TREE);
20122   tree int_ftype_v4hi_int
20123     = build_function_type_list (integer_type_node,
20124                                 V4HI_type_node, integer_type_node, NULL_TREE);
20125   tree int_ftype_v2si_int
20126     = build_function_type_list (integer_type_node,
20127                                 V2SI_type_node, integer_type_node, NULL_TREE);
20128   tree v8qi_ftype_v8qi_int_int
20129     = build_function_type_list (V8QI_type_node,
20130                                 V8QI_type_node, integer_type_node,
20131                                 integer_type_node, NULL_TREE);
20132   tree v4hi_ftype_v4hi_int_int
20133     = build_function_type_list (V4HI_type_node,
20134                                 V4HI_type_node, integer_type_node,
20135                                 integer_type_node, NULL_TREE);
20136   tree v2si_ftype_v2si_int_int
20137     = build_function_type_list (V2SI_type_node,
20138                                 V2SI_type_node, integer_type_node,
20139                                 integer_type_node, NULL_TREE);
20140   /* Miscellaneous.  */
20141   tree v8qi_ftype_v4hi_v4hi
20142     = build_function_type_list (V8QI_type_node,
20143                                 V4HI_type_node, V4HI_type_node, NULL_TREE);
20144   tree v4hi_ftype_v2si_v2si
20145     = build_function_type_list (V4HI_type_node,
20146                                 V2SI_type_node, V2SI_type_node, NULL_TREE);
20147   tree v2si_ftype_v4hi_v4hi
20148     = build_function_type_list (V2SI_type_node,
20149                                 V4HI_type_node, V4HI_type_node, NULL_TREE);
20150   tree v2si_ftype_v8qi_v8qi
20151     = build_function_type_list (V2SI_type_node,
20152                                 V8QI_type_node, V8QI_type_node, NULL_TREE);
20153   tree v4hi_ftype_v4hi_di
20154     = build_function_type_list (V4HI_type_node,
20155                                 V4HI_type_node, long_long_integer_type_node,
20156                                 NULL_TREE);
20157   tree v2si_ftype_v2si_di
20158     = build_function_type_list (V2SI_type_node,
20159                                 V2SI_type_node, long_long_integer_type_node,
20160                                 NULL_TREE);
20161   tree void_ftype_int_int
20162     = build_function_type_list (void_type_node,
20163                                 integer_type_node, integer_type_node,
20164                                 NULL_TREE);
20165   tree di_ftype_void
20166     = build_function_type_list (long_long_unsigned_type_node, NULL_TREE);
20167   tree di_ftype_v8qi
20168     = build_function_type_list (long_long_integer_type_node,
20169                                 V8QI_type_node, NULL_TREE);
20170   tree di_ftype_v4hi
20171     = build_function_type_list (long_long_integer_type_node,
20172                                 V4HI_type_node, NULL_TREE);
20173   tree di_ftype_v2si
20174     = build_function_type_list (long_long_integer_type_node,
20175                                 V2SI_type_node, NULL_TREE);
20176   tree v2si_ftype_v4hi
20177     = build_function_type_list (V2SI_type_node,
20178                                 V4HI_type_node, NULL_TREE);
20179   tree v4hi_ftype_v8qi
20180     = build_function_type_list (V4HI_type_node,
20181                                 V8QI_type_node, NULL_TREE);
20182
20183   tree di_ftype_di_v4hi_v4hi
20184     = build_function_type_list (long_long_unsigned_type_node,
20185                                 long_long_unsigned_type_node,
20186                                 V4HI_type_node, V4HI_type_node,
20187                                 NULL_TREE);
20188
20189   tree di_ftype_v4hi_v4hi
20190     = build_function_type_list (long_long_unsigned_type_node,
20191                                 V4HI_type_node,V4HI_type_node,
20192                                 NULL_TREE);
20193
20194   /* Normal vector binops.  */
20195   tree v8qi_ftype_v8qi_v8qi
20196     = build_function_type_list (V8QI_type_node,
20197                                 V8QI_type_node, V8QI_type_node, NULL_TREE);
20198   tree v4hi_ftype_v4hi_v4hi
20199     = build_function_type_list (V4HI_type_node,
20200                                 V4HI_type_node,V4HI_type_node, NULL_TREE);
20201   tree v2si_ftype_v2si_v2si
20202     = build_function_type_list (V2SI_type_node,
20203                                 V2SI_type_node, V2SI_type_node, NULL_TREE);
20204   tree di_ftype_di_di
20205     = build_function_type_list (long_long_unsigned_type_node,
20206                                 long_long_unsigned_type_node,
20207                                 long_long_unsigned_type_node,
20208                                 NULL_TREE);
20209
20210   /* Add all builtins that are more or less simple operations on two
20211      operands.  */
20212   for (i = 0, d = bdesc_2arg; i < ARRAY_SIZE (bdesc_2arg); i++, d++)
20213     {
20214       /* Use one of the operands; the target can have a different mode for
20215          mask-generating compares.  */
20216       enum machine_mode mode;
20217       tree type;
20218
20219       if (d->name == 0)
20220         continue;
20221
20222       mode = insn_data[d->icode].operand[1].mode;
20223
20224       switch (mode)
20225         {
20226         case V8QImode:
20227           type = v8qi_ftype_v8qi_v8qi;
20228           break;
20229         case V4HImode:
20230           type = v4hi_ftype_v4hi_v4hi;
20231           break;
20232         case V2SImode:
20233           type = v2si_ftype_v2si_v2si;
20234           break;
20235         case DImode:
20236           type = di_ftype_di_di;
20237           break;
20238
20239         default:
20240           gcc_unreachable ();
20241         }
20242
20243       def_mbuiltin (d->mask, d->name, type, d->code);
20244     }
20245
20246   /* Add the remaining MMX insns with somewhat more complicated types.  */
20247 #define iwmmx_mbuiltin(NAME, TYPE, CODE)                        \
20248   def_mbuiltin (FL_IWMMXT, "__builtin_arm_" NAME, (TYPE),       \
20249                 ARM_BUILTIN_ ## CODE)
20250
20251   iwmmx_mbuiltin ("wzero", di_ftype_void, WZERO);
20252   iwmmx_mbuiltin ("setwcx", void_ftype_int_int, SETWCX);
20253   iwmmx_mbuiltin ("getwcx", int_ftype_int, GETWCX);
20254
20255   iwmmx_mbuiltin ("wsllh", v4hi_ftype_v4hi_di, WSLLH);
20256   iwmmx_mbuiltin ("wsllw", v2si_ftype_v2si_di, WSLLW);
20257   iwmmx_mbuiltin ("wslld", di_ftype_di_di, WSLLD);
20258   iwmmx_mbuiltin ("wsllhi", v4hi_ftype_v4hi_int, WSLLHI);
20259   iwmmx_mbuiltin ("wsllwi", v2si_ftype_v2si_int, WSLLWI);
20260   iwmmx_mbuiltin ("wslldi", di_ftype_di_int, WSLLDI);
20261
20262   iwmmx_mbuiltin ("wsrlh", v4hi_ftype_v4hi_di, WSRLH);
20263   iwmmx_mbuiltin ("wsrlw", v2si_ftype_v2si_di, WSRLW);
20264   iwmmx_mbuiltin ("wsrld", di_ftype_di_di, WSRLD);
20265   iwmmx_mbuiltin ("wsrlhi", v4hi_ftype_v4hi_int, WSRLHI);
20266   iwmmx_mbuiltin ("wsrlwi", v2si_ftype_v2si_int, WSRLWI);
20267   iwmmx_mbuiltin ("wsrldi", di_ftype_di_int, WSRLDI);
20268
20269   iwmmx_mbuiltin ("wsrah", v4hi_ftype_v4hi_di, WSRAH);
20270   iwmmx_mbuiltin ("wsraw", v2si_ftype_v2si_di, WSRAW);
20271   iwmmx_mbuiltin ("wsrad", di_ftype_di_di, WSRAD);
20272   iwmmx_mbuiltin ("wsrahi", v4hi_ftype_v4hi_int, WSRAHI);
20273   iwmmx_mbuiltin ("wsrawi", v2si_ftype_v2si_int, WSRAWI);
20274   iwmmx_mbuiltin ("wsradi", di_ftype_di_int, WSRADI);
20275
20276   iwmmx_mbuiltin ("wrorh", v4hi_ftype_v4hi_di, WRORH);
20277   iwmmx_mbuiltin ("wrorw", v2si_ftype_v2si_di, WRORW);
20278   iwmmx_mbuiltin ("wrord", di_ftype_di_di, WRORD);
20279   iwmmx_mbuiltin ("wrorhi", v4hi_ftype_v4hi_int, WRORHI);
20280   iwmmx_mbuiltin ("wrorwi", v2si_ftype_v2si_int, WRORWI);
20281   iwmmx_mbuiltin ("wrordi", di_ftype_di_int, WRORDI);
20282
20283   iwmmx_mbuiltin ("wshufh", v4hi_ftype_v4hi_int, WSHUFH);
20284
20285   iwmmx_mbuiltin ("wsadb", v2si_ftype_v8qi_v8qi, WSADB);
20286   iwmmx_mbuiltin ("wsadh", v2si_ftype_v4hi_v4hi, WSADH);
20287   iwmmx_mbuiltin ("wsadbz", v2si_ftype_v8qi_v8qi, WSADBZ);
20288   iwmmx_mbuiltin ("wsadhz", v2si_ftype_v4hi_v4hi, WSADHZ);
20289
20290   iwmmx_mbuiltin ("textrmsb", int_ftype_v8qi_int, TEXTRMSB);
20291   iwmmx_mbuiltin ("textrmsh", int_ftype_v4hi_int, TEXTRMSH);
20292   iwmmx_mbuiltin ("textrmsw", int_ftype_v2si_int, TEXTRMSW);
20293   iwmmx_mbuiltin ("textrmub", int_ftype_v8qi_int, TEXTRMUB);
20294   iwmmx_mbuiltin ("textrmuh", int_ftype_v4hi_int, TEXTRMUH);
20295   iwmmx_mbuiltin ("textrmuw", int_ftype_v2si_int, TEXTRMUW);
20296   iwmmx_mbuiltin ("tinsrb", v8qi_ftype_v8qi_int_int, TINSRB);
20297   iwmmx_mbuiltin ("tinsrh", v4hi_ftype_v4hi_int_int, TINSRH);
20298   iwmmx_mbuiltin ("tinsrw", v2si_ftype_v2si_int_int, TINSRW);
20299
20300   iwmmx_mbuiltin ("waccb", di_ftype_v8qi, WACCB);
20301   iwmmx_mbuiltin ("wacch", di_ftype_v4hi, WACCH);
20302   iwmmx_mbuiltin ("waccw", di_ftype_v2si, WACCW);
20303
20304   iwmmx_mbuiltin ("tmovmskb", int_ftype_v8qi, TMOVMSKB);
20305   iwmmx_mbuiltin ("tmovmskh", int_ftype_v4hi, TMOVMSKH);
20306   iwmmx_mbuiltin ("tmovmskw", int_ftype_v2si, TMOVMSKW);
20307
20308   iwmmx_mbuiltin ("wpackhss", v8qi_ftype_v4hi_v4hi, WPACKHSS);
20309   iwmmx_mbuiltin ("wpackhus", v8qi_ftype_v4hi_v4hi, WPACKHUS);
20310   iwmmx_mbuiltin ("wpackwus", v4hi_ftype_v2si_v2si, WPACKWUS);
20311   iwmmx_mbuiltin ("wpackwss", v4hi_ftype_v2si_v2si, WPACKWSS);
20312   iwmmx_mbuiltin ("wpackdus", v2si_ftype_di_di, WPACKDUS);
20313   iwmmx_mbuiltin ("wpackdss", v2si_ftype_di_di, WPACKDSS);
20314
20315   iwmmx_mbuiltin ("wunpckehub", v4hi_ftype_v8qi, WUNPCKEHUB);
20316   iwmmx_mbuiltin ("wunpckehuh", v2si_ftype_v4hi, WUNPCKEHUH);
20317   iwmmx_mbuiltin ("wunpckehuw", di_ftype_v2si, WUNPCKEHUW);
20318   iwmmx_mbuiltin ("wunpckehsb", v4hi_ftype_v8qi, WUNPCKEHSB);
20319   iwmmx_mbuiltin ("wunpckehsh", v2si_ftype_v4hi, WUNPCKEHSH);
20320   iwmmx_mbuiltin ("wunpckehsw", di_ftype_v2si, WUNPCKEHSW);
20321   iwmmx_mbuiltin ("wunpckelub", v4hi_ftype_v8qi, WUNPCKELUB);
20322   iwmmx_mbuiltin ("wunpckeluh", v2si_ftype_v4hi, WUNPCKELUH);
20323   iwmmx_mbuiltin ("wunpckeluw", di_ftype_v2si, WUNPCKELUW);
20324   iwmmx_mbuiltin ("wunpckelsb", v4hi_ftype_v8qi, WUNPCKELSB);
20325   iwmmx_mbuiltin ("wunpckelsh", v2si_ftype_v4hi, WUNPCKELSH);
20326   iwmmx_mbuiltin ("wunpckelsw", di_ftype_v2si, WUNPCKELSW);
20327
20328   iwmmx_mbuiltin ("wmacs", di_ftype_di_v4hi_v4hi, WMACS);
20329   iwmmx_mbuiltin ("wmacsz", di_ftype_v4hi_v4hi, WMACSZ);
20330   iwmmx_mbuiltin ("wmacu", di_ftype_di_v4hi_v4hi, WMACU);
20331   iwmmx_mbuiltin ("wmacuz", di_ftype_v4hi_v4hi, WMACUZ);
20332
20333   iwmmx_mbuiltin ("walign", v8qi_ftype_v8qi_v8qi_int, WALIGN);
20334   iwmmx_mbuiltin ("tmia", di_ftype_di_int_int, TMIA);
20335   iwmmx_mbuiltin ("tmiaph", di_ftype_di_int_int, TMIAPH);
20336   iwmmx_mbuiltin ("tmiabb", di_ftype_di_int_int, TMIABB);
20337   iwmmx_mbuiltin ("tmiabt", di_ftype_di_int_int, TMIABT);
20338   iwmmx_mbuiltin ("tmiatb", di_ftype_di_int_int, TMIATB);
20339   iwmmx_mbuiltin ("tmiatt", di_ftype_di_int_int, TMIATT);
20340
20341 #undef iwmmx_mbuiltin
20342 }
20343
20344 static void
20345 arm_init_tls_builtins (void)
20346 {
20347   tree ftype, decl;
20348
20349   ftype = build_function_type (ptr_type_node, void_list_node);
20350   decl = add_builtin_function ("__builtin_thread_pointer", ftype,
20351                                ARM_BUILTIN_THREAD_POINTER, BUILT_IN_MD,
20352                                NULL, NULL_TREE);
20353   TREE_NOTHROW (decl) = 1;
20354   TREE_READONLY (decl) = 1;
20355   arm_builtin_decls[ARM_BUILTIN_THREAD_POINTER] = decl;
20356 }
20357
20358 static void
20359 arm_init_fp16_builtins (void)
20360 {
20361   tree fp16_type = make_node (REAL_TYPE);
20362   TYPE_PRECISION (fp16_type) = 16;
20363   layout_type (fp16_type);
20364   (*lang_hooks.types.register_builtin_type) (fp16_type, "__fp16");
20365 }
20366
20367 static void
20368 arm_init_builtins (void)
20369 {
20370   arm_init_tls_builtins ();
20371
20372   if (TARGET_REALLY_IWMMXT)
20373     arm_init_iwmmxt_builtins ();
20374
20375   if (TARGET_NEON)
20376     arm_init_neon_builtins ();
20377
20378   if (arm_fp16_format)
20379     arm_init_fp16_builtins ();
20380 }
20381
20382 /* Return the ARM builtin for CODE.  */
20383
20384 static tree
20385 arm_builtin_decl (unsigned code, bool initialize_p ATTRIBUTE_UNUSED)
20386 {
20387   if (code >= ARM_BUILTIN_MAX)
20388     return error_mark_node;
20389
20390   return arm_builtin_decls[code];
20391 }
20392
20393 /* Implement TARGET_INVALID_PARAMETER_TYPE.  */
20394
20395 static const char *
20396 arm_invalid_parameter_type (const_tree t)
20397 {
20398   if (SCALAR_FLOAT_TYPE_P (t) && TYPE_PRECISION (t) == 16)
20399     return N_("function parameters cannot have __fp16 type");
20400   return NULL;
20401 }
20402
20403 /* Implement TARGET_INVALID_PARAMETER_TYPE.  */
20404
20405 static const char *
20406 arm_invalid_return_type (const_tree t)
20407 {
20408   if (SCALAR_FLOAT_TYPE_P (t) && TYPE_PRECISION (t) == 16)
20409     return N_("functions cannot return __fp16 type");
20410   return NULL;
20411 }
20412
20413 /* Implement TARGET_PROMOTED_TYPE.  */
20414
20415 static tree
20416 arm_promoted_type (const_tree t)
20417 {
20418   if (SCALAR_FLOAT_TYPE_P (t) && TYPE_PRECISION (t) == 16)
20419     return float_type_node;
20420   return NULL_TREE;
20421 }
20422
20423 /* Implement TARGET_CONVERT_TO_TYPE.
20424    Specifically, this hook implements the peculiarity of the ARM
20425    half-precision floating-point C semantics that requires conversions between
20426    __fp16 to or from double to do an intermediate conversion to float.  */
20427
20428 static tree
20429 arm_convert_to_type (tree type, tree expr)
20430 {
20431   tree fromtype = TREE_TYPE (expr);
20432   if (!SCALAR_FLOAT_TYPE_P (fromtype) || !SCALAR_FLOAT_TYPE_P (type))
20433     return NULL_TREE;
20434   if ((TYPE_PRECISION (fromtype) == 16 && TYPE_PRECISION (type) > 32)
20435       || (TYPE_PRECISION (type) == 16 && TYPE_PRECISION (fromtype) > 32))
20436     return convert (type, convert (float_type_node, expr));
20437   return NULL_TREE;
20438 }
20439
20440 /* Implement TARGET_SCALAR_MODE_SUPPORTED_P.
20441    This simply adds HFmode as a supported mode; even though we don't
20442    implement arithmetic on this type directly, it's supported by
20443    optabs conversions, much the way the double-word arithmetic is
20444    special-cased in the default hook.  */
20445
20446 static bool
20447 arm_scalar_mode_supported_p (enum machine_mode mode)
20448 {
20449   if (mode == HFmode)
20450     return (arm_fp16_format != ARM_FP16_FORMAT_NONE);
20451   else if (ALL_FIXED_POINT_MODE_P (mode))
20452     return true;
20453   else
20454     return default_scalar_mode_supported_p (mode);
20455 }
20456
20457 /* Errors in the source file can cause expand_expr to return const0_rtx
20458    where we expect a vector.  To avoid crashing, use one of the vector
20459    clear instructions.  */
20460
20461 static rtx
20462 safe_vector_operand (rtx x, enum machine_mode mode)
20463 {
20464   if (x != const0_rtx)
20465     return x;
20466   x = gen_reg_rtx (mode);
20467
20468   emit_insn (gen_iwmmxt_clrdi (mode == DImode ? x
20469                                : gen_rtx_SUBREG (DImode, x, 0)));
20470   return x;
20471 }
20472
20473 /* Subroutine of arm_expand_builtin to take care of binop insns.  */
20474
20475 static rtx
20476 arm_expand_binop_builtin (enum insn_code icode,
20477                           tree exp, rtx target)
20478 {
20479   rtx pat;
20480   tree arg0 = CALL_EXPR_ARG (exp, 0);
20481   tree arg1 = CALL_EXPR_ARG (exp, 1);
20482   rtx op0 = expand_normal (arg0);
20483   rtx op1 = expand_normal (arg1);
20484   enum machine_mode tmode = insn_data[icode].operand[0].mode;
20485   enum machine_mode mode0 = insn_data[icode].operand[1].mode;
20486   enum machine_mode mode1 = insn_data[icode].operand[2].mode;
20487
20488   if (VECTOR_MODE_P (mode0))
20489     op0 = safe_vector_operand (op0, mode0);
20490   if (VECTOR_MODE_P (mode1))
20491     op1 = safe_vector_operand (op1, mode1);
20492
20493   if (! target
20494       || GET_MODE (target) != tmode
20495       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
20496     target = gen_reg_rtx (tmode);
20497
20498   gcc_assert (GET_MODE (op0) == mode0 && GET_MODE (op1) == mode1);
20499
20500   if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
20501     op0 = copy_to_mode_reg (mode0, op0);
20502   if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
20503     op1 = copy_to_mode_reg (mode1, op1);
20504
20505   pat = GEN_FCN (icode) (target, op0, op1);
20506   if (! pat)
20507     return 0;
20508   emit_insn (pat);
20509   return target;
20510 }
20511
20512 /* Subroutine of arm_expand_builtin to take care of unop insns.  */
20513
20514 static rtx
20515 arm_expand_unop_builtin (enum insn_code icode,
20516                          tree exp, rtx target, int do_load)
20517 {
20518   rtx pat;
20519   tree arg0 = CALL_EXPR_ARG (exp, 0);
20520   rtx op0 = expand_normal (arg0);
20521   enum machine_mode tmode = insn_data[icode].operand[0].mode;
20522   enum machine_mode mode0 = insn_data[icode].operand[1].mode;
20523
20524   if (! target
20525       || GET_MODE (target) != tmode
20526       || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
20527     target = gen_reg_rtx (tmode);
20528   if (do_load)
20529     op0 = gen_rtx_MEM (mode0, copy_to_mode_reg (Pmode, op0));
20530   else
20531     {
20532       if (VECTOR_MODE_P (mode0))
20533         op0 = safe_vector_operand (op0, mode0);
20534
20535       if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
20536         op0 = copy_to_mode_reg (mode0, op0);
20537     }
20538
20539   pat = GEN_FCN (icode) (target, op0);
20540   if (! pat)
20541     return 0;
20542   emit_insn (pat);
20543   return target;
20544 }
20545
20546 typedef enum {
20547   NEON_ARG_COPY_TO_REG,
20548   NEON_ARG_CONSTANT,
20549   NEON_ARG_MEMORY,
20550   NEON_ARG_STOP
20551 } builtin_arg;
20552
20553 #define NEON_MAX_BUILTIN_ARGS 5
20554
20555 /* EXP is a pointer argument to a Neon load or store intrinsic.  Derive
20556    and return an expression for the accessed memory.
20557
20558    The intrinsic function operates on a block of registers that has
20559    mode REG_MODE.  This block contains vectors of type TYPE_MODE.
20560    The function references the memory at EXP in mode MEM_MODE;
20561    this mode may be BLKmode if no more suitable mode is available.  */
20562
20563 static tree
20564 neon_dereference_pointer (tree exp, enum machine_mode mem_mode,
20565                           enum machine_mode reg_mode,
20566                           neon_builtin_type_mode type_mode)
20567 {
20568   HOST_WIDE_INT reg_size, vector_size, nvectors, nelems;
20569   tree elem_type, upper_bound, array_type;
20570
20571   /* Work out the size of the register block in bytes.  */
20572   reg_size = GET_MODE_SIZE (reg_mode);
20573
20574   /* Work out the size of each vector in bytes.  */
20575   gcc_assert (TYPE_MODE_BIT (type_mode) & (TB_DREG | TB_QREG));
20576   vector_size = (TYPE_MODE_BIT (type_mode) & TB_QREG ? 16 : 8);
20577
20578   /* Work out how many vectors there are.  */
20579   gcc_assert (reg_size % vector_size == 0);
20580   nvectors = reg_size / vector_size;
20581
20582   /* Work out how many elements are being loaded or stored.
20583      MEM_MODE == REG_MODE implies a one-to-one mapping between register
20584      and memory elements; anything else implies a lane load or store.  */
20585   if (mem_mode == reg_mode)
20586     nelems = vector_size * nvectors;
20587   else
20588     nelems = nvectors;
20589
20590   /* Work out the type of each element.  */
20591   gcc_assert (POINTER_TYPE_P (TREE_TYPE (exp)));
20592   elem_type = TREE_TYPE (TREE_TYPE (exp));
20593
20594   /* Create a type that describes the full access.  */
20595   upper_bound = build_int_cst (size_type_node, nelems - 1);
20596   array_type = build_array_type (elem_type, build_index_type (upper_bound));
20597
20598   /* Dereference EXP using that type.  */
20599   exp = convert (build_pointer_type (array_type), exp);
20600   return fold_build2 (MEM_REF, array_type, exp,
20601                       build_int_cst (TREE_TYPE (exp), 0));
20602 }
20603
20604 /* Expand a Neon builtin.  */
20605 static rtx
20606 arm_expand_neon_args (rtx target, int icode, int have_retval,
20607                       neon_builtin_type_mode type_mode,
20608                       tree exp, ...)
20609 {
20610   va_list ap;
20611   rtx pat;
20612   tree arg[NEON_MAX_BUILTIN_ARGS];
20613   rtx op[NEON_MAX_BUILTIN_ARGS];
20614   enum machine_mode tmode = insn_data[icode].operand[0].mode;
20615   enum machine_mode mode[NEON_MAX_BUILTIN_ARGS];
20616   enum machine_mode other_mode;
20617   int argc = 0;
20618   int opno;
20619
20620   if (have_retval
20621       && (!target
20622           || GET_MODE (target) != tmode
20623           || !(*insn_data[icode].operand[0].predicate) (target, tmode)))
20624     target = gen_reg_rtx (tmode);
20625
20626   va_start (ap, exp);
20627
20628   for (;;)
20629     {
20630       builtin_arg thisarg = (builtin_arg) va_arg (ap, int);
20631
20632       if (thisarg == NEON_ARG_STOP)
20633         break;
20634       else
20635         {
20636           opno = argc + have_retval;
20637           mode[argc] = insn_data[icode].operand[opno].mode;
20638           arg[argc] = CALL_EXPR_ARG (exp, argc);
20639           if (thisarg == NEON_ARG_MEMORY)
20640             {
20641               other_mode = insn_data[icode].operand[1 - opno].mode;
20642               arg[argc] = neon_dereference_pointer (arg[argc], mode[argc],
20643                                                     other_mode, type_mode);
20644             }
20645           op[argc] = expand_normal (arg[argc]);
20646
20647           switch (thisarg)
20648             {
20649             case NEON_ARG_COPY_TO_REG:
20650               /*gcc_assert (GET_MODE (op[argc]) == mode[argc]);*/
20651               if (!(*insn_data[icode].operand[opno].predicate)
20652                      (op[argc], mode[argc]))
20653                 op[argc] = copy_to_mode_reg (mode[argc], op[argc]);
20654               break;
20655
20656             case NEON_ARG_CONSTANT:
20657               /* FIXME: This error message is somewhat unhelpful.  */
20658               if (!(*insn_data[icode].operand[opno].predicate)
20659                     (op[argc], mode[argc]))
20660                 error ("argument must be a constant");
20661               break;
20662
20663             case NEON_ARG_MEMORY:
20664               gcc_assert (MEM_P (op[argc]));
20665               PUT_MODE (op[argc], mode[argc]);
20666               /* ??? arm_neon.h uses the same built-in functions for signed
20667                  and unsigned accesses, casting where necessary.  This isn't
20668                  alias safe.  */
20669               set_mem_alias_set (op[argc], 0);
20670               if (!(*insn_data[icode].operand[opno].predicate)
20671                     (op[argc], mode[argc]))
20672                 op[argc] = (replace_equiv_address
20673                             (op[argc], force_reg (Pmode, XEXP (op[argc], 0))));
20674               break;
20675
20676             case NEON_ARG_STOP:
20677               gcc_unreachable ();
20678             }
20679
20680           argc++;
20681         }
20682     }
20683
20684   va_end (ap);
20685
20686   if (have_retval)
20687     switch (argc)
20688       {
20689       case 1:
20690         pat = GEN_FCN (icode) (target, op[0]);
20691         break;
20692
20693       case 2:
20694         pat = GEN_FCN (icode) (target, op[0], op[1]);
20695         break;
20696
20697       case 3:
20698         pat = GEN_FCN (icode) (target, op[0], op[1], op[2]);
20699         break;
20700
20701       case 4:
20702         pat = GEN_FCN (icode) (target, op[0], op[1], op[2], op[3]);
20703         break;
20704
20705       case 5:
20706         pat = GEN_FCN (icode) (target, op[0], op[1], op[2], op[3], op[4]);
20707         break;
20708
20709       default:
20710         gcc_unreachable ();
20711       }
20712   else
20713     switch (argc)
20714       {
20715       case 1:
20716         pat = GEN_FCN (icode) (op[0]);
20717         break;
20718
20719       case 2:
20720         pat = GEN_FCN (icode) (op[0], op[1]);
20721         break;
20722
20723       case 3:
20724         pat = GEN_FCN (icode) (op[0], op[1], op[2]);
20725         break;
20726
20727       case 4:
20728         pat = GEN_FCN (icode) (op[0], op[1], op[2], op[3]);
20729         break;
20730
20731       case 5:
20732         pat = GEN_FCN (icode) (op[0], op[1], op[2], op[3], op[4]);
20733         break;
20734
20735       default:
20736         gcc_unreachable ();
20737       }
20738
20739   if (!pat)
20740     return 0;
20741
20742   emit_insn (pat);
20743
20744   return target;
20745 }
20746
20747 /* Expand a Neon builtin. These are "special" because they don't have symbolic
20748    constants defined per-instruction or per instruction-variant. Instead, the
20749    required info is looked up in the table neon_builtin_data.  */
20750 static rtx
20751 arm_expand_neon_builtin (int fcode, tree exp, rtx target)
20752 {
20753   neon_builtin_datum *d = &neon_builtin_data[fcode - ARM_BUILTIN_NEON_BASE];
20754   neon_itype itype = d->itype;
20755   enum insn_code icode = d->code;
20756   neon_builtin_type_mode type_mode = d->mode;
20757
20758   switch (itype)
20759     {
20760     case NEON_UNOP:
20761     case NEON_CONVERT:
20762     case NEON_DUPLANE:
20763       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20764         NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT, NEON_ARG_STOP);
20765
20766     case NEON_BINOP:
20767     case NEON_SETLANE:
20768     case NEON_SCALARMUL:
20769     case NEON_SCALARMULL:
20770     case NEON_SCALARMULH:
20771     case NEON_SHIFTINSERT:
20772     case NEON_LOGICBINOP:
20773       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20774         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT,
20775         NEON_ARG_STOP);
20776
20777     case NEON_TERNOP:
20778       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20779         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG,
20780         NEON_ARG_CONSTANT, NEON_ARG_STOP);
20781
20782     case NEON_GETLANE:
20783     case NEON_FIXCONV:
20784     case NEON_SHIFTIMM:
20785       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20786         NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT, NEON_ARG_CONSTANT,
20787         NEON_ARG_STOP);
20788
20789     case NEON_CREATE:
20790       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20791         NEON_ARG_COPY_TO_REG, NEON_ARG_STOP);
20792
20793     case NEON_DUP:
20794     case NEON_SPLIT:
20795     case NEON_REINTERP:
20796       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20797         NEON_ARG_COPY_TO_REG, NEON_ARG_STOP);
20798
20799     case NEON_COMBINE:
20800     case NEON_VTBL:
20801       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20802         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_STOP);
20803
20804     case NEON_RESULTPAIR:
20805       return arm_expand_neon_args (target, icode, 0, type_mode, exp,
20806         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG,
20807         NEON_ARG_STOP);
20808
20809     case NEON_LANEMUL:
20810     case NEON_LANEMULL:
20811     case NEON_LANEMULH:
20812       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20813         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT,
20814         NEON_ARG_CONSTANT, NEON_ARG_STOP);
20815
20816     case NEON_LANEMAC:
20817       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20818         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG,
20819         NEON_ARG_CONSTANT, NEON_ARG_CONSTANT, NEON_ARG_STOP);
20820
20821     case NEON_SHIFTACC:
20822       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20823         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT,
20824         NEON_ARG_CONSTANT, NEON_ARG_STOP);
20825
20826     case NEON_SCALARMAC:
20827       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20828         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG,
20829         NEON_ARG_CONSTANT, NEON_ARG_STOP);
20830
20831     case NEON_SELECT:
20832     case NEON_VTBX:
20833       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20834         NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG, NEON_ARG_COPY_TO_REG,
20835         NEON_ARG_STOP);
20836
20837     case NEON_LOAD1:
20838     case NEON_LOADSTRUCT:
20839       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20840         NEON_ARG_MEMORY, NEON_ARG_STOP);
20841
20842     case NEON_LOAD1LANE:
20843     case NEON_LOADSTRUCTLANE:
20844       return arm_expand_neon_args (target, icode, 1, type_mode, exp,
20845         NEON_ARG_MEMORY, NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT,
20846         NEON_ARG_STOP);
20847
20848     case NEON_STORE1:
20849     case NEON_STORESTRUCT:
20850       return arm_expand_neon_args (target, icode, 0, type_mode, exp,
20851         NEON_ARG_MEMORY, NEON_ARG_COPY_TO_REG, NEON_ARG_STOP);
20852
20853     case NEON_STORE1LANE:
20854     case NEON_STORESTRUCTLANE:
20855       return arm_expand_neon_args (target, icode, 0, type_mode, exp,
20856         NEON_ARG_MEMORY, NEON_ARG_COPY_TO_REG, NEON_ARG_CONSTANT,
20857         NEON_ARG_STOP);
20858     }
20859
20860   gcc_unreachable ();
20861 }
20862
20863 /* Emit code to reinterpret one Neon type as another, without altering bits.  */
20864 void
20865 neon_reinterpret (rtx dest, rtx src)
20866 {
20867   emit_move_insn (dest, gen_lowpart (GET_MODE (dest), src));
20868 }
20869
20870 /* Emit code to place a Neon pair result in memory locations (with equal
20871    registers).  */
20872 void
20873 neon_emit_pair_result_insn (enum machine_mode mode,
20874                             rtx (*intfn) (rtx, rtx, rtx, rtx), rtx destaddr,
20875                             rtx op1, rtx op2)
20876 {
20877   rtx mem = gen_rtx_MEM (mode, destaddr);
20878   rtx tmp1 = gen_reg_rtx (mode);
20879   rtx tmp2 = gen_reg_rtx (mode);
20880
20881   emit_insn (intfn (tmp1, op1, op2, tmp2));
20882
20883   emit_move_insn (mem, tmp1);
20884   mem = adjust_address (mem, mode, GET_MODE_SIZE (mode));
20885   emit_move_insn (mem, tmp2);
20886 }
20887
20888 /* Set up OPERANDS for a register copy from SRC to DEST, taking care
20889    not to early-clobber SRC registers in the process.
20890
20891    We assume that the operands described by SRC and DEST represent a
20892    decomposed copy of OPERANDS[1] into OPERANDS[0].  COUNT is the
20893    number of components into which the copy has been decomposed.  */
20894 void
20895 neon_disambiguate_copy (rtx *operands, rtx *dest, rtx *src, unsigned int count)
20896 {
20897   unsigned int i;
20898
20899   if (!reg_overlap_mentioned_p (operands[0], operands[1])
20900       || REGNO (operands[0]) < REGNO (operands[1]))
20901     {
20902       for (i = 0; i < count; i++)
20903         {
20904           operands[2 * i] = dest[i];
20905           operands[2 * i + 1] = src[i];
20906         }
20907     }
20908   else
20909     {
20910       for (i = 0; i < count; i++)
20911         {
20912           operands[2 * i] = dest[count - i - 1];
20913           operands[2 * i + 1] = src[count - i - 1];
20914         }
20915     }
20916 }
20917
20918 /* Expand an expression EXP that calls a built-in function,
20919    with result going to TARGET if that's convenient
20920    (and in mode MODE if that's convenient).
20921    SUBTARGET may be used as the target for computing one of EXP's operands.
20922    IGNORE is nonzero if the value is to be ignored.  */
20923
20924 static rtx
20925 arm_expand_builtin (tree exp,
20926                     rtx target,
20927                     rtx subtarget ATTRIBUTE_UNUSED,
20928                     enum machine_mode mode ATTRIBUTE_UNUSED,
20929                     int ignore ATTRIBUTE_UNUSED)
20930 {
20931   const struct builtin_description * d;
20932   enum insn_code    icode;
20933   tree              fndecl = TREE_OPERAND (CALL_EXPR_FN (exp), 0);
20934   tree              arg0;
20935   tree              arg1;
20936   tree              arg2;
20937   rtx               op0;
20938   rtx               op1;
20939   rtx               op2;
20940   rtx               pat;
20941   int               fcode = DECL_FUNCTION_CODE (fndecl);
20942   size_t            i;
20943   enum machine_mode tmode;
20944   enum machine_mode mode0;
20945   enum machine_mode mode1;
20946   enum machine_mode mode2;
20947
20948   if (fcode >= ARM_BUILTIN_NEON_BASE)
20949     return arm_expand_neon_builtin (fcode, exp, target);
20950
20951   switch (fcode)
20952     {
20953     case ARM_BUILTIN_TEXTRMSB:
20954     case ARM_BUILTIN_TEXTRMUB:
20955     case ARM_BUILTIN_TEXTRMSH:
20956     case ARM_BUILTIN_TEXTRMUH:
20957     case ARM_BUILTIN_TEXTRMSW:
20958     case ARM_BUILTIN_TEXTRMUW:
20959       icode = (fcode == ARM_BUILTIN_TEXTRMSB ? CODE_FOR_iwmmxt_textrmsb
20960                : fcode == ARM_BUILTIN_TEXTRMUB ? CODE_FOR_iwmmxt_textrmub
20961                : fcode == ARM_BUILTIN_TEXTRMSH ? CODE_FOR_iwmmxt_textrmsh
20962                : fcode == ARM_BUILTIN_TEXTRMUH ? CODE_FOR_iwmmxt_textrmuh
20963                : CODE_FOR_iwmmxt_textrmw);
20964
20965       arg0 = CALL_EXPR_ARG (exp, 0);
20966       arg1 = CALL_EXPR_ARG (exp, 1);
20967       op0 = expand_normal (arg0);
20968       op1 = expand_normal (arg1);
20969       tmode = insn_data[icode].operand[0].mode;
20970       mode0 = insn_data[icode].operand[1].mode;
20971       mode1 = insn_data[icode].operand[2].mode;
20972
20973       if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
20974         op0 = copy_to_mode_reg (mode0, op0);
20975       if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
20976         {
20977           /* @@@ better error message */
20978           error ("selector must be an immediate");
20979           return gen_reg_rtx (tmode);
20980         }
20981       if (target == 0
20982           || GET_MODE (target) != tmode
20983           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
20984         target = gen_reg_rtx (tmode);
20985       pat = GEN_FCN (icode) (target, op0, op1);
20986       if (! pat)
20987         return 0;
20988       emit_insn (pat);
20989       return target;
20990
20991     case ARM_BUILTIN_TINSRB:
20992     case ARM_BUILTIN_TINSRH:
20993     case ARM_BUILTIN_TINSRW:
20994       icode = (fcode == ARM_BUILTIN_TINSRB ? CODE_FOR_iwmmxt_tinsrb
20995                : fcode == ARM_BUILTIN_TINSRH ? CODE_FOR_iwmmxt_tinsrh
20996                : CODE_FOR_iwmmxt_tinsrw);
20997       arg0 = CALL_EXPR_ARG (exp, 0);
20998       arg1 = CALL_EXPR_ARG (exp, 1);
20999       arg2 = CALL_EXPR_ARG (exp, 2);
21000       op0 = expand_normal (arg0);
21001       op1 = expand_normal (arg1);
21002       op2 = expand_normal (arg2);
21003       tmode = insn_data[icode].operand[0].mode;
21004       mode0 = insn_data[icode].operand[1].mode;
21005       mode1 = insn_data[icode].operand[2].mode;
21006       mode2 = insn_data[icode].operand[3].mode;
21007
21008       if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
21009         op0 = copy_to_mode_reg (mode0, op0);
21010       if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
21011         op1 = copy_to_mode_reg (mode1, op1);
21012       if (! (*insn_data[icode].operand[3].predicate) (op2, mode2))
21013         {
21014           /* @@@ better error message */
21015           error ("selector must be an immediate");
21016           return const0_rtx;
21017         }
21018       if (target == 0
21019           || GET_MODE (target) != tmode
21020           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
21021         target = gen_reg_rtx (tmode);
21022       pat = GEN_FCN (icode) (target, op0, op1, op2);
21023       if (! pat)
21024         return 0;
21025       emit_insn (pat);
21026       return target;
21027
21028     case ARM_BUILTIN_SETWCX:
21029       arg0 = CALL_EXPR_ARG (exp, 0);
21030       arg1 = CALL_EXPR_ARG (exp, 1);
21031       op0 = force_reg (SImode, expand_normal (arg0));
21032       op1 = expand_normal (arg1);
21033       emit_insn (gen_iwmmxt_tmcr (op1, op0));
21034       return 0;
21035
21036     case ARM_BUILTIN_GETWCX:
21037       arg0 = CALL_EXPR_ARG (exp, 0);
21038       op0 = expand_normal (arg0);
21039       target = gen_reg_rtx (SImode);
21040       emit_insn (gen_iwmmxt_tmrc (target, op0));
21041       return target;
21042
21043     case ARM_BUILTIN_WSHUFH:
21044       icode = CODE_FOR_iwmmxt_wshufh;
21045       arg0 = CALL_EXPR_ARG (exp, 0);
21046       arg1 = CALL_EXPR_ARG (exp, 1);
21047       op0 = expand_normal (arg0);
21048       op1 = expand_normal (arg1);
21049       tmode = insn_data[icode].operand[0].mode;
21050       mode1 = insn_data[icode].operand[1].mode;
21051       mode2 = insn_data[icode].operand[2].mode;
21052
21053       if (! (*insn_data[icode].operand[1].predicate) (op0, mode1))
21054         op0 = copy_to_mode_reg (mode1, op0);
21055       if (! (*insn_data[icode].operand[2].predicate) (op1, mode2))
21056         {
21057           /* @@@ better error message */
21058           error ("mask must be an immediate");
21059           return const0_rtx;
21060         }
21061       if (target == 0
21062           || GET_MODE (target) != tmode
21063           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
21064         target = gen_reg_rtx (tmode);
21065       pat = GEN_FCN (icode) (target, op0, op1);
21066       if (! pat)
21067         return 0;
21068       emit_insn (pat);
21069       return target;
21070
21071     case ARM_BUILTIN_WSADB:
21072       return arm_expand_binop_builtin (CODE_FOR_iwmmxt_wsadb, exp, target);
21073     case ARM_BUILTIN_WSADH:
21074       return arm_expand_binop_builtin (CODE_FOR_iwmmxt_wsadh, exp, target);
21075     case ARM_BUILTIN_WSADBZ:
21076       return arm_expand_binop_builtin (CODE_FOR_iwmmxt_wsadbz, exp, target);
21077     case ARM_BUILTIN_WSADHZ:
21078       return arm_expand_binop_builtin (CODE_FOR_iwmmxt_wsadhz, exp, target);
21079
21080       /* Several three-argument builtins.  */
21081     case ARM_BUILTIN_WMACS:
21082     case ARM_BUILTIN_WMACU:
21083     case ARM_BUILTIN_WALIGN:
21084     case ARM_BUILTIN_TMIA:
21085     case ARM_BUILTIN_TMIAPH:
21086     case ARM_BUILTIN_TMIATT:
21087     case ARM_BUILTIN_TMIATB:
21088     case ARM_BUILTIN_TMIABT:
21089     case ARM_BUILTIN_TMIABB:
21090       icode = (fcode == ARM_BUILTIN_WMACS ? CODE_FOR_iwmmxt_wmacs
21091                : fcode == ARM_BUILTIN_WMACU ? CODE_FOR_iwmmxt_wmacu
21092                : fcode == ARM_BUILTIN_TMIA ? CODE_FOR_iwmmxt_tmia
21093                : fcode == ARM_BUILTIN_TMIAPH ? CODE_FOR_iwmmxt_tmiaph
21094                : fcode == ARM_BUILTIN_TMIABB ? CODE_FOR_iwmmxt_tmiabb
21095                : fcode == ARM_BUILTIN_TMIABT ? CODE_FOR_iwmmxt_tmiabt
21096                : fcode == ARM_BUILTIN_TMIATB ? CODE_FOR_iwmmxt_tmiatb
21097                : fcode == ARM_BUILTIN_TMIATT ? CODE_FOR_iwmmxt_tmiatt
21098                : CODE_FOR_iwmmxt_walign);
21099       arg0 = CALL_EXPR_ARG (exp, 0);
21100       arg1 = CALL_EXPR_ARG (exp, 1);
21101       arg2 = CALL_EXPR_ARG (exp, 2);
21102       op0 = expand_normal (arg0);
21103       op1 = expand_normal (arg1);
21104       op2 = expand_normal (arg2);
21105       tmode = insn_data[icode].operand[0].mode;
21106       mode0 = insn_data[icode].operand[1].mode;
21107       mode1 = insn_data[icode].operand[2].mode;
21108       mode2 = insn_data[icode].operand[3].mode;
21109
21110       if (! (*insn_data[icode].operand[1].predicate) (op0, mode0))
21111         op0 = copy_to_mode_reg (mode0, op0);
21112       if (! (*insn_data[icode].operand[2].predicate) (op1, mode1))
21113         op1 = copy_to_mode_reg (mode1, op1);
21114       if (! (*insn_data[icode].operand[3].predicate) (op2, mode2))
21115         op2 = copy_to_mode_reg (mode2, op2);
21116       if (target == 0
21117           || GET_MODE (target) != tmode
21118           || ! (*insn_data[icode].operand[0].predicate) (target, tmode))
21119         target = gen_reg_rtx (tmode);
21120       pat = GEN_FCN (icode) (target, op0, op1, op2);
21121       if (! pat)
21122         return 0;
21123       emit_insn (pat);
21124       return target;
21125
21126     case ARM_BUILTIN_WZERO:
21127       target = gen_reg_rtx (DImode);
21128       emit_insn (gen_iwmmxt_clrdi (target));
21129       return target;
21130
21131     case ARM_BUILTIN_THREAD_POINTER:
21132       return arm_load_tp (target);
21133
21134     default:
21135       break;
21136     }
21137
21138   for (i = 0, d = bdesc_2arg; i < ARRAY_SIZE (bdesc_2arg); i++, d++)
21139     if (d->code == (const enum arm_builtins) fcode)
21140       return arm_expand_binop_builtin (d->icode, exp, target);
21141
21142   for (i = 0, d = bdesc_1arg; i < ARRAY_SIZE (bdesc_1arg); i++, d++)
21143     if (d->code == (const enum arm_builtins) fcode)
21144       return arm_expand_unop_builtin (d->icode, exp, target, 0);
21145
21146   /* @@@ Should really do something sensible here.  */
21147   return NULL_RTX;
21148 }
21149 \f
21150 /* Return the number (counting from 0) of
21151    the least significant set bit in MASK.  */
21152
21153 inline static int
21154 number_of_first_bit_set (unsigned mask)
21155 {
21156   return ctz_hwi (mask);
21157 }
21158
21159 /* Like emit_multi_reg_push, but allowing for a different set of
21160    registers to be described as saved.  MASK is the set of registers
21161    to be saved; REAL_REGS is the set of registers to be described as
21162    saved.  If REAL_REGS is 0, only describe the stack adjustment.  */
21163
21164 static rtx
21165 thumb1_emit_multi_reg_push (unsigned long mask, unsigned long real_regs)
21166 {
21167   unsigned long regno;
21168   rtx par[10], tmp, reg, insn;
21169   int i, j;
21170
21171   /* Build the parallel of the registers actually being stored.  */
21172   for (i = 0; mask; ++i, mask &= mask - 1)
21173     {
21174       regno = ctz_hwi (mask);
21175       reg = gen_rtx_REG (SImode, regno);
21176
21177       if (i == 0)
21178         tmp = gen_rtx_UNSPEC (BLKmode, gen_rtvec (1, reg), UNSPEC_PUSH_MULT);
21179       else
21180         tmp = gen_rtx_USE (VOIDmode, reg);
21181
21182       par[i] = tmp;
21183     }
21184
21185   tmp = plus_constant (stack_pointer_rtx, -4 * i);
21186   tmp = gen_rtx_PRE_MODIFY (Pmode, stack_pointer_rtx, tmp);
21187   tmp = gen_frame_mem (BLKmode, tmp);
21188   tmp = gen_rtx_SET (VOIDmode, tmp, par[0]);
21189   par[0] = tmp;
21190
21191   tmp = gen_rtx_PARALLEL (VOIDmode, gen_rtvec_v (i, par));
21192   insn = emit_insn (tmp);
21193
21194   /* Always build the stack adjustment note for unwind info.  */
21195   tmp = plus_constant (stack_pointer_rtx, -4 * i);
21196   tmp = gen_rtx_SET (VOIDmode, stack_pointer_rtx, tmp);
21197   par[0] = tmp;
21198
21199   /* Build the parallel of the registers recorded as saved for unwind.  */
21200   for (j = 0; real_regs; ++j, real_regs &= real_regs - 1)
21201     {
21202       regno = ctz_hwi (real_regs);
21203       reg = gen_rtx_REG (SImode, regno);
21204
21205       tmp = plus_constant (stack_pointer_rtx, j * 4);
21206       tmp = gen_frame_mem (SImode, tmp);
21207       tmp = gen_rtx_SET (VOIDmode, tmp, reg);
21208       RTX_FRAME_RELATED_P (tmp) = 1;
21209       par[j + 1] = tmp;
21210     }
21211
21212   if (j == 0)
21213     tmp = par[0];
21214   else
21215     {
21216       RTX_FRAME_RELATED_P (par[0]) = 1;
21217       tmp = gen_rtx_SEQUENCE (VOIDmode, gen_rtvec_v (j + 1, par));
21218     }
21219
21220   add_reg_note (insn, REG_FRAME_RELATED_EXPR, tmp);
21221
21222   return insn;
21223 }
21224
21225 /* Emit code to push or pop registers to or from the stack.  F is the
21226    assembly file.  MASK is the registers to pop.  */
21227 static void
21228 thumb_pop (FILE *f, unsigned long mask)
21229 {
21230   int regno;
21231   int lo_mask = mask & 0xFF;
21232   int pushed_words = 0;
21233
21234   gcc_assert (mask);
21235
21236   if (lo_mask == 0 && (mask & (1 << PC_REGNUM)))
21237     {
21238       /* Special case.  Do not generate a POP PC statement here, do it in
21239          thumb_exit() */
21240       thumb_exit (f, -1);
21241       return;
21242     }
21243
21244   fprintf (f, "\tpop\t{");
21245
21246   /* Look at the low registers first.  */
21247   for (regno = 0; regno <= LAST_LO_REGNUM; regno++, lo_mask >>= 1)
21248     {
21249       if (lo_mask & 1)
21250         {
21251           asm_fprintf (f, "%r", regno);
21252
21253           if ((lo_mask & ~1) != 0)
21254             fprintf (f, ", ");
21255
21256           pushed_words++;
21257         }
21258     }
21259
21260   if (mask & (1 << PC_REGNUM))
21261     {
21262       /* Catch popping the PC.  */
21263       if (TARGET_INTERWORK || TARGET_BACKTRACE
21264           || crtl->calls_eh_return)
21265         {
21266           /* The PC is never poped directly, instead
21267              it is popped into r3 and then BX is used.  */
21268           fprintf (f, "}\n");
21269
21270           thumb_exit (f, -1);
21271
21272           return;
21273         }
21274       else
21275         {
21276           if (mask & 0xFF)
21277             fprintf (f, ", ");
21278
21279           asm_fprintf (f, "%r", PC_REGNUM);
21280         }
21281     }
21282
21283   fprintf (f, "}\n");
21284 }
21285
21286 /* Generate code to return from a thumb function.
21287    If 'reg_containing_return_addr' is -1, then the return address is
21288    actually on the stack, at the stack pointer.  */
21289 static void
21290 thumb_exit (FILE *f, int reg_containing_return_addr)
21291 {
21292   unsigned regs_available_for_popping;
21293   unsigned regs_to_pop;
21294   int pops_needed;
21295   unsigned available;
21296   unsigned required;
21297   int mode;
21298   int size;
21299   int restore_a4 = FALSE;
21300
21301   /* Compute the registers we need to pop.  */
21302   regs_to_pop = 0;
21303   pops_needed = 0;
21304
21305   if (reg_containing_return_addr == -1)
21306     {
21307       regs_to_pop |= 1 << LR_REGNUM;
21308       ++pops_needed;
21309     }
21310
21311   if (TARGET_BACKTRACE)
21312     {
21313       /* Restore the (ARM) frame pointer and stack pointer.  */
21314       regs_to_pop |= (1 << ARM_HARD_FRAME_POINTER_REGNUM) | (1 << SP_REGNUM);
21315       pops_needed += 2;
21316     }
21317
21318   /* If there is nothing to pop then just emit the BX instruction and
21319      return.  */
21320   if (pops_needed == 0)
21321     {
21322       if (crtl->calls_eh_return)
21323         asm_fprintf (f, "\tadd\t%r, %r\n", SP_REGNUM, ARM_EH_STACKADJ_REGNUM);
21324
21325       asm_fprintf (f, "\tbx\t%r\n", reg_containing_return_addr);
21326       return;
21327     }
21328   /* Otherwise if we are not supporting interworking and we have not created
21329      a backtrace structure and the function was not entered in ARM mode then
21330      just pop the return address straight into the PC.  */
21331   else if (!TARGET_INTERWORK
21332            && !TARGET_BACKTRACE
21333            && !is_called_in_ARM_mode (current_function_decl)
21334            && !crtl->calls_eh_return)
21335     {
21336       asm_fprintf (f, "\tpop\t{%r}\n", PC_REGNUM);
21337       return;
21338     }
21339
21340   /* Find out how many of the (return) argument registers we can corrupt.  */
21341   regs_available_for_popping = 0;
21342
21343   /* If returning via __builtin_eh_return, the bottom three registers
21344      all contain information needed for the return.  */
21345   if (crtl->calls_eh_return)
21346     size = 12;
21347   else
21348     {
21349       /* If we can deduce the registers used from the function's
21350          return value.  This is more reliable that examining
21351          df_regs_ever_live_p () because that will be set if the register is
21352          ever used in the function, not just if the register is used
21353          to hold a return value.  */
21354
21355       if (crtl->return_rtx != 0)
21356         mode = GET_MODE (crtl->return_rtx);
21357       else
21358         mode = DECL_MODE (DECL_RESULT (current_function_decl));
21359
21360       size = GET_MODE_SIZE (mode);
21361
21362       if (size == 0)
21363         {
21364           /* In a void function we can use any argument register.
21365              In a function that returns a structure on the stack
21366              we can use the second and third argument registers.  */
21367           if (mode == VOIDmode)
21368             regs_available_for_popping =
21369               (1 << ARG_REGISTER (1))
21370               | (1 << ARG_REGISTER (2))
21371               | (1 << ARG_REGISTER (3));
21372           else
21373             regs_available_for_popping =
21374               (1 << ARG_REGISTER (2))
21375               | (1 << ARG_REGISTER (3));
21376         }
21377       else if (size <= 4)
21378         regs_available_for_popping =
21379           (1 << ARG_REGISTER (2))
21380           | (1 << ARG_REGISTER (3));
21381       else if (size <= 8)
21382         regs_available_for_popping =
21383           (1 << ARG_REGISTER (3));
21384     }
21385
21386   /* Match registers to be popped with registers into which we pop them.  */
21387   for (available = regs_available_for_popping,
21388        required  = regs_to_pop;
21389        required != 0 && available != 0;
21390        available &= ~(available & - available),
21391        required  &= ~(required  & - required))
21392     -- pops_needed;
21393
21394   /* If we have any popping registers left over, remove them.  */
21395   if (available > 0)
21396     regs_available_for_popping &= ~available;
21397
21398   /* Otherwise if we need another popping register we can use
21399      the fourth argument register.  */
21400   else if (pops_needed)
21401     {
21402       /* If we have not found any free argument registers and
21403          reg a4 contains the return address, we must move it.  */
21404       if (regs_available_for_popping == 0
21405           && reg_containing_return_addr == LAST_ARG_REGNUM)
21406         {
21407           asm_fprintf (f, "\tmov\t%r, %r\n", LR_REGNUM, LAST_ARG_REGNUM);
21408           reg_containing_return_addr = LR_REGNUM;
21409         }
21410       else if (size > 12)
21411         {
21412           /* Register a4 is being used to hold part of the return value,
21413              but we have dire need of a free, low register.  */
21414           restore_a4 = TRUE;
21415
21416           asm_fprintf (f, "\tmov\t%r, %r\n",IP_REGNUM, LAST_ARG_REGNUM);
21417         }
21418
21419       if (reg_containing_return_addr != LAST_ARG_REGNUM)
21420         {
21421           /* The fourth argument register is available.  */
21422           regs_available_for_popping |= 1 << LAST_ARG_REGNUM;
21423
21424           --pops_needed;
21425         }
21426     }
21427
21428   /* Pop as many registers as we can.  */
21429   thumb_pop (f, regs_available_for_popping);
21430
21431   /* Process the registers we popped.  */
21432   if (reg_containing_return_addr == -1)
21433     {
21434       /* The return address was popped into the lowest numbered register.  */
21435       regs_to_pop &= ~(1 << LR_REGNUM);
21436
21437       reg_containing_return_addr =
21438         number_of_first_bit_set (regs_available_for_popping);
21439
21440       /* Remove this register for the mask of available registers, so that
21441          the return address will not be corrupted by further pops.  */
21442       regs_available_for_popping &= ~(1 << reg_containing_return_addr);
21443     }
21444
21445   /* If we popped other registers then handle them here.  */
21446   if (regs_available_for_popping)
21447     {
21448       int frame_pointer;
21449
21450       /* Work out which register currently contains the frame pointer.  */
21451       frame_pointer = number_of_first_bit_set (regs_available_for_popping);
21452
21453       /* Move it into the correct place.  */
21454       asm_fprintf (f, "\tmov\t%r, %r\n",
21455                    ARM_HARD_FRAME_POINTER_REGNUM, frame_pointer);
21456
21457       /* (Temporarily) remove it from the mask of popped registers.  */
21458       regs_available_for_popping &= ~(1 << frame_pointer);
21459       regs_to_pop &= ~(1 << ARM_HARD_FRAME_POINTER_REGNUM);
21460
21461       if (regs_available_for_popping)
21462         {
21463           int stack_pointer;
21464
21465           /* We popped the stack pointer as well,
21466              find the register that contains it.  */
21467           stack_pointer = number_of_first_bit_set (regs_available_for_popping);
21468
21469           /* Move it into the stack register.  */
21470           asm_fprintf (f, "\tmov\t%r, %r\n", SP_REGNUM, stack_pointer);
21471
21472           /* At this point we have popped all necessary registers, so
21473              do not worry about restoring regs_available_for_popping
21474              to its correct value:
21475
21476              assert (pops_needed == 0)
21477              assert (regs_available_for_popping == (1 << frame_pointer))
21478              assert (regs_to_pop == (1 << STACK_POINTER))  */
21479         }
21480       else
21481         {
21482           /* Since we have just move the popped value into the frame
21483              pointer, the popping register is available for reuse, and
21484              we know that we still have the stack pointer left to pop.  */
21485           regs_available_for_popping |= (1 << frame_pointer);
21486         }
21487     }
21488
21489   /* If we still have registers left on the stack, but we no longer have
21490      any registers into which we can pop them, then we must move the return
21491      address into the link register and make available the register that
21492      contained it.  */
21493   if (regs_available_for_popping == 0 && pops_needed > 0)
21494     {
21495       regs_available_for_popping |= 1 << reg_containing_return_addr;
21496
21497       asm_fprintf (f, "\tmov\t%r, %r\n", LR_REGNUM,
21498                    reg_containing_return_addr);
21499
21500       reg_containing_return_addr = LR_REGNUM;
21501     }
21502
21503   /* If we have registers left on the stack then pop some more.
21504      We know that at most we will want to pop FP and SP.  */
21505   if (pops_needed > 0)
21506     {
21507       int  popped_into;
21508       int  move_to;
21509
21510       thumb_pop (f, regs_available_for_popping);
21511
21512       /* We have popped either FP or SP.
21513          Move whichever one it is into the correct register.  */
21514       popped_into = number_of_first_bit_set (regs_available_for_popping);
21515       move_to     = number_of_first_bit_set (regs_to_pop);
21516
21517       asm_fprintf (f, "\tmov\t%r, %r\n", move_to, popped_into);
21518
21519       regs_to_pop &= ~(1 << move_to);
21520
21521       --pops_needed;
21522     }
21523
21524   /* If we still have not popped everything then we must have only
21525      had one register available to us and we are now popping the SP.  */
21526   if (pops_needed > 0)
21527     {
21528       int  popped_into;
21529
21530       thumb_pop (f, regs_available_for_popping);
21531
21532       popped_into = number_of_first_bit_set (regs_available_for_popping);
21533
21534       asm_fprintf (f, "\tmov\t%r, %r\n", SP_REGNUM, popped_into);
21535       /*
21536         assert (regs_to_pop == (1 << STACK_POINTER))
21537         assert (pops_needed == 1)
21538       */
21539     }
21540
21541   /* If necessary restore the a4 register.  */
21542   if (restore_a4)
21543     {
21544       if (reg_containing_return_addr != LR_REGNUM)
21545         {
21546           asm_fprintf (f, "\tmov\t%r, %r\n", LR_REGNUM, LAST_ARG_REGNUM);
21547           reg_containing_return_addr = LR_REGNUM;
21548         }
21549
21550       asm_fprintf (f, "\tmov\t%r, %r\n", LAST_ARG_REGNUM, IP_REGNUM);
21551     }
21552
21553   if (crtl->calls_eh_return)
21554     asm_fprintf (f, "\tadd\t%r, %r\n", SP_REGNUM, ARM_EH_STACKADJ_REGNUM);
21555
21556   /* Return to caller.  */
21557   asm_fprintf (f, "\tbx\t%r\n", reg_containing_return_addr);
21558 }
21559 \f
21560 /* Scan INSN just before assembler is output for it.
21561    For Thumb-1, we track the status of the condition codes; this
21562    information is used in the cbranchsi4_insn pattern.  */
21563 void
21564 thumb1_final_prescan_insn (rtx insn)
21565 {
21566   if (flag_print_asm_name)
21567     asm_fprintf (asm_out_file, "%@ 0x%04x\n",
21568                  INSN_ADDRESSES (INSN_UID (insn)));
21569   /* Don't overwrite the previous setter when we get to a cbranch.  */
21570   if (INSN_CODE (insn) != CODE_FOR_cbranchsi4_insn)
21571     {
21572       enum attr_conds conds;
21573
21574       if (cfun->machine->thumb1_cc_insn)
21575         {
21576           if (modified_in_p (cfun->machine->thumb1_cc_op0, insn)
21577               || modified_in_p (cfun->machine->thumb1_cc_op1, insn))
21578             CC_STATUS_INIT;
21579         }
21580       conds = get_attr_conds (insn);
21581       if (conds == CONDS_SET)
21582         {
21583           rtx set = single_set (insn);
21584           cfun->machine->thumb1_cc_insn = insn;
21585           cfun->machine->thumb1_cc_op0 = SET_DEST (set);
21586           cfun->machine->thumb1_cc_op1 = const0_rtx;
21587           cfun->machine->thumb1_cc_mode = CC_NOOVmode;
21588           if (INSN_CODE (insn) == CODE_FOR_thumb1_subsi3_insn)
21589             {
21590               rtx src1 = XEXP (SET_SRC (set), 1);
21591               if (src1 == const0_rtx)
21592                 cfun->machine->thumb1_cc_mode = CCmode;
21593             }
21594         }
21595       else if (conds != CONDS_NOCOND)
21596         cfun->machine->thumb1_cc_insn = NULL_RTX;
21597     }
21598 }
21599
21600 int
21601 thumb_shiftable_const (unsigned HOST_WIDE_INT val)
21602 {
21603   unsigned HOST_WIDE_INT mask = 0xff;
21604   int i;
21605
21606   val = val & (unsigned HOST_WIDE_INT)0xffffffffu;
21607   if (val == 0) /* XXX */
21608     return 0;
21609
21610   for (i = 0; i < 25; i++)
21611     if ((val & (mask << i)) == val)
21612       return 1;
21613
21614   return 0;
21615 }
21616
21617 /* Returns nonzero if the current function contains,
21618    or might contain a far jump.  */
21619 static int
21620 thumb_far_jump_used_p (void)
21621 {
21622   rtx insn;
21623
21624   /* This test is only important for leaf functions.  */
21625   /* assert (!leaf_function_p ()); */
21626
21627   /* If we have already decided that far jumps may be used,
21628      do not bother checking again, and always return true even if
21629      it turns out that they are not being used.  Once we have made
21630      the decision that far jumps are present (and that hence the link
21631      register will be pushed onto the stack) we cannot go back on it.  */
21632   if (cfun->machine->far_jump_used)
21633     return 1;
21634
21635   /* If this function is not being called from the prologue/epilogue
21636      generation code then it must be being called from the
21637      INITIAL_ELIMINATION_OFFSET macro.  */
21638   if (!(ARM_DOUBLEWORD_ALIGN || reload_completed))
21639     {
21640       /* In this case we know that we are being asked about the elimination
21641          of the arg pointer register.  If that register is not being used,
21642          then there are no arguments on the stack, and we do not have to
21643          worry that a far jump might force the prologue to push the link
21644          register, changing the stack offsets.  In this case we can just
21645          return false, since the presence of far jumps in the function will
21646          not affect stack offsets.
21647
21648          If the arg pointer is live (or if it was live, but has now been
21649          eliminated and so set to dead) then we do have to test to see if
21650          the function might contain a far jump.  This test can lead to some
21651          false negatives, since before reload is completed, then length of
21652          branch instructions is not known, so gcc defaults to returning their
21653          longest length, which in turn sets the far jump attribute to true.
21654
21655          A false negative will not result in bad code being generated, but it
21656          will result in a needless push and pop of the link register.  We
21657          hope that this does not occur too often.
21658
21659          If we need doubleword stack alignment this could affect the other
21660          elimination offsets so we can't risk getting it wrong.  */
21661       if (df_regs_ever_live_p (ARG_POINTER_REGNUM))
21662         cfun->machine->arg_pointer_live = 1;
21663       else if (!cfun->machine->arg_pointer_live)
21664         return 0;
21665     }
21666
21667   /* Check to see if the function contains a branch
21668      insn with the far jump attribute set.  */
21669   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
21670     {
21671       if (GET_CODE (insn) == JUMP_INSN
21672           /* Ignore tablejump patterns.  */
21673           && GET_CODE (PATTERN (insn)) != ADDR_VEC
21674           && GET_CODE (PATTERN (insn)) != ADDR_DIFF_VEC
21675           && get_attr_far_jump (insn) == FAR_JUMP_YES
21676           )
21677         {
21678           /* Record the fact that we have decided that
21679              the function does use far jumps.  */
21680           cfun->machine->far_jump_used = 1;
21681           return 1;
21682         }
21683     }
21684
21685   return 0;
21686 }
21687
21688 /* Return nonzero if FUNC must be entered in ARM mode.  */
21689 int
21690 is_called_in_ARM_mode (tree func)
21691 {
21692   gcc_assert (TREE_CODE (func) == FUNCTION_DECL);
21693
21694   /* Ignore the problem about functions whose address is taken.  */
21695   if (TARGET_CALLEE_INTERWORKING && TREE_PUBLIC (func))
21696     return TRUE;
21697
21698 #ifdef ARM_PE
21699   return lookup_attribute ("interfacearm", DECL_ATTRIBUTES (func)) != NULL_TREE;
21700 #else
21701   return FALSE;
21702 #endif
21703 }
21704
21705 /* Given the stack offsets and register mask in OFFSETS, decide how
21706    many additional registers to push instead of subtracting a constant
21707    from SP.  For epilogues the principle is the same except we use pop.
21708    FOR_PROLOGUE indicates which we're generating.  */
21709 static int
21710 thumb1_extra_regs_pushed (arm_stack_offsets *offsets, bool for_prologue)
21711 {
21712   HOST_WIDE_INT amount;
21713   unsigned long live_regs_mask = offsets->saved_regs_mask;
21714   /* Extract a mask of the ones we can give to the Thumb's push/pop
21715      instruction.  */
21716   unsigned long l_mask = live_regs_mask & (for_prologue ? 0x40ff : 0xff);
21717   /* Then count how many other high registers will need to be pushed.  */
21718   unsigned long high_regs_pushed = bit_count (live_regs_mask & 0x0f00);
21719   int n_free, reg_base;
21720
21721   if (!for_prologue && frame_pointer_needed)
21722     amount = offsets->locals_base - offsets->saved_regs;
21723   else
21724     amount = offsets->outgoing_args - offsets->saved_regs;
21725
21726   /* If the stack frame size is 512 exactly, we can save one load
21727      instruction, which should make this a win even when optimizing
21728      for speed.  */
21729   if (!optimize_size && amount != 512)
21730     return 0;
21731
21732   /* Can't do this if there are high registers to push.  */
21733   if (high_regs_pushed != 0)
21734     return 0;
21735
21736   /* Shouldn't do it in the prologue if no registers would normally
21737      be pushed at all.  In the epilogue, also allow it if we'll have
21738      a pop insn for the PC.  */
21739   if  (l_mask == 0
21740        && (for_prologue
21741            || TARGET_BACKTRACE
21742            || (live_regs_mask & 1 << LR_REGNUM) == 0
21743            || TARGET_INTERWORK
21744            || crtl->args.pretend_args_size != 0))
21745     return 0;
21746
21747   /* Don't do this if thumb_expand_prologue wants to emit instructions
21748      between the push and the stack frame allocation.  */
21749   if (for_prologue
21750       && ((flag_pic && arm_pic_register != INVALID_REGNUM)
21751           || (!frame_pointer_needed && CALLER_INTERWORKING_SLOT_SIZE > 0)))
21752     return 0;
21753
21754   reg_base = 0;
21755   n_free = 0;
21756   if (!for_prologue)
21757     {
21758       reg_base = arm_size_return_regs () / UNITS_PER_WORD;
21759       live_regs_mask >>= reg_base;
21760     }
21761
21762   while (reg_base + n_free < 8 && !(live_regs_mask & 1)
21763          && (for_prologue || call_used_regs[reg_base + n_free]))
21764     {
21765       live_regs_mask >>= 1;
21766       n_free++;
21767     }
21768
21769   if (n_free == 0)
21770     return 0;
21771   gcc_assert (amount / 4 * 4 == amount);
21772
21773   if (amount >= 512 && (amount - n_free * 4) < 512)
21774     return (amount - 508) / 4;
21775   if (amount <= n_free * 4)
21776     return amount / 4;
21777   return 0;
21778 }
21779
21780 /* The bits which aren't usefully expanded as rtl.  */
21781 const char *
21782 thumb_unexpanded_epilogue (void)
21783 {
21784   arm_stack_offsets *offsets;
21785   int regno;
21786   unsigned long live_regs_mask = 0;
21787   int high_regs_pushed = 0;
21788   int extra_pop;
21789   int had_to_push_lr;
21790   int size;
21791
21792   if (cfun->machine->return_used_this_function != 0)
21793     return "";
21794
21795   if (IS_NAKED (arm_current_func_type ()))
21796     return "";
21797
21798   offsets = arm_get_frame_offsets ();
21799   live_regs_mask = offsets->saved_regs_mask;
21800   high_regs_pushed = bit_count (live_regs_mask & 0x0f00);
21801
21802   /* If we can deduce the registers used from the function's return value.
21803      This is more reliable that examining df_regs_ever_live_p () because that
21804      will be set if the register is ever used in the function, not just if
21805      the register is used to hold a return value.  */
21806   size = arm_size_return_regs ();
21807
21808   extra_pop = thumb1_extra_regs_pushed (offsets, false);
21809   if (extra_pop > 0)
21810     {
21811       unsigned long extra_mask = (1 << extra_pop) - 1;
21812       live_regs_mask |= extra_mask << ((size + UNITS_PER_WORD - 1) 
21813                                        / UNITS_PER_WORD);
21814     }
21815
21816   /* The prolog may have pushed some high registers to use as
21817      work registers.  e.g. the testsuite file:
21818      gcc/testsuite/gcc/gcc.c-torture/execute/complex-2.c
21819      compiles to produce:
21820         push    {r4, r5, r6, r7, lr}
21821         mov     r7, r9
21822         mov     r6, r8
21823         push    {r6, r7}
21824      as part of the prolog.  We have to undo that pushing here.  */
21825
21826   if (high_regs_pushed)
21827     {
21828       unsigned long mask = live_regs_mask & 0xff;
21829       int next_hi_reg;
21830
21831       /* The available low registers depend on the size of the value we are
21832          returning.  */
21833       if (size <= 12)
21834         mask |=  1 << 3;
21835       if (size <= 8)
21836         mask |= 1 << 2;
21837
21838       if (mask == 0)
21839         /* Oh dear!  We have no low registers into which we can pop
21840            high registers!  */
21841         internal_error
21842           ("no low registers available for popping high registers");
21843
21844       for (next_hi_reg = 8; next_hi_reg < 13; next_hi_reg++)
21845         if (live_regs_mask & (1 << next_hi_reg))
21846           break;
21847
21848       while (high_regs_pushed)
21849         {
21850           /* Find lo register(s) into which the high register(s) can
21851              be popped.  */
21852           for (regno = 0; regno <= LAST_LO_REGNUM; regno++)
21853             {
21854               if (mask & (1 << regno))
21855                 high_regs_pushed--;
21856               if (high_regs_pushed == 0)
21857                 break;
21858             }
21859
21860           mask &= (2 << regno) - 1;     /* A noop if regno == 8 */
21861
21862           /* Pop the values into the low register(s).  */
21863           thumb_pop (asm_out_file, mask);
21864
21865           /* Move the value(s) into the high registers.  */
21866           for (regno = 0; regno <= LAST_LO_REGNUM; regno++)
21867             {
21868               if (mask & (1 << regno))
21869                 {
21870                   asm_fprintf (asm_out_file, "\tmov\t%r, %r\n", next_hi_reg,
21871                                regno);
21872
21873                   for (next_hi_reg++; next_hi_reg < 13; next_hi_reg++)
21874                     if (live_regs_mask & (1 << next_hi_reg))
21875                       break;
21876                 }
21877             }
21878         }
21879       live_regs_mask &= ~0x0f00;
21880     }
21881
21882   had_to_push_lr = (live_regs_mask & (1 << LR_REGNUM)) != 0;
21883   live_regs_mask &= 0xff;
21884
21885   if (crtl->args.pretend_args_size == 0 || TARGET_BACKTRACE)
21886     {
21887       /* Pop the return address into the PC.  */
21888       if (had_to_push_lr)
21889         live_regs_mask |= 1 << PC_REGNUM;
21890
21891       /* Either no argument registers were pushed or a backtrace
21892          structure was created which includes an adjusted stack
21893          pointer, so just pop everything.  */
21894       if (live_regs_mask)
21895         thumb_pop (asm_out_file, live_regs_mask);
21896
21897       /* We have either just popped the return address into the
21898          PC or it is was kept in LR for the entire function.
21899          Note that thumb_pop has already called thumb_exit if the
21900          PC was in the list.  */
21901       if (!had_to_push_lr)
21902         thumb_exit (asm_out_file, LR_REGNUM);
21903     }
21904   else
21905     {
21906       /* Pop everything but the return address.  */
21907       if (live_regs_mask)
21908         thumb_pop (asm_out_file, live_regs_mask);
21909
21910       if (had_to_push_lr)
21911         {
21912           if (size > 12)
21913             {
21914               /* We have no free low regs, so save one.  */
21915               asm_fprintf (asm_out_file, "\tmov\t%r, %r\n", IP_REGNUM,
21916                            LAST_ARG_REGNUM);
21917             }
21918
21919           /* Get the return address into a temporary register.  */
21920           thumb_pop (asm_out_file, 1 << LAST_ARG_REGNUM);
21921
21922           if (size > 12)
21923             {
21924               /* Move the return address to lr.  */
21925               asm_fprintf (asm_out_file, "\tmov\t%r, %r\n", LR_REGNUM,
21926                            LAST_ARG_REGNUM);
21927               /* Restore the low register.  */
21928               asm_fprintf (asm_out_file, "\tmov\t%r, %r\n", LAST_ARG_REGNUM,
21929                            IP_REGNUM);
21930               regno = LR_REGNUM;
21931             }
21932           else
21933             regno = LAST_ARG_REGNUM;
21934         }
21935       else
21936         regno = LR_REGNUM;
21937
21938       /* Remove the argument registers that were pushed onto the stack.  */
21939       asm_fprintf (asm_out_file, "\tadd\t%r, %r, #%d\n",
21940                    SP_REGNUM, SP_REGNUM,
21941                    crtl->args.pretend_args_size);
21942
21943       thumb_exit (asm_out_file, regno);
21944     }
21945
21946   return "";
21947 }
21948
21949 /* Functions to save and restore machine-specific function data.  */
21950 static struct machine_function *
21951 arm_init_machine_status (void)
21952 {
21953   struct machine_function *machine;
21954   machine = ggc_alloc_cleared_machine_function ();
21955
21956 #if ARM_FT_UNKNOWN != 0
21957   machine->func_type = ARM_FT_UNKNOWN;
21958 #endif
21959   return machine;
21960 }
21961
21962 /* Return an RTX indicating where the return address to the
21963    calling function can be found.  */
21964 rtx
21965 arm_return_addr (int count, rtx frame ATTRIBUTE_UNUSED)
21966 {
21967   if (count != 0)
21968     return NULL_RTX;
21969
21970   return get_hard_reg_initial_val (Pmode, LR_REGNUM);
21971 }
21972
21973 /* Do anything needed before RTL is emitted for each function.  */
21974 void
21975 arm_init_expanders (void)
21976 {
21977   /* Arrange to initialize and mark the machine per-function status.  */
21978   init_machine_status = arm_init_machine_status;
21979
21980   /* This is to stop the combine pass optimizing away the alignment
21981      adjustment of va_arg.  */
21982   /* ??? It is claimed that this should not be necessary.  */
21983   if (cfun)
21984     mark_reg_pointer (arg_pointer_rtx, PARM_BOUNDARY);
21985 }
21986
21987
21988 /* Like arm_compute_initial_elimination offset.  Simpler because there
21989    isn't an ABI specified frame pointer for Thumb.  Instead, we set it
21990    to point at the base of the local variables after static stack
21991    space for a function has been allocated.  */
21992
21993 HOST_WIDE_INT
21994 thumb_compute_initial_elimination_offset (unsigned int from, unsigned int to)
21995 {
21996   arm_stack_offsets *offsets;
21997
21998   offsets = arm_get_frame_offsets ();
21999
22000   switch (from)
22001     {
22002     case ARG_POINTER_REGNUM:
22003       switch (to)
22004         {
22005         case STACK_POINTER_REGNUM:
22006           return offsets->outgoing_args - offsets->saved_args;
22007
22008         case FRAME_POINTER_REGNUM:
22009           return offsets->soft_frame - offsets->saved_args;
22010
22011         case ARM_HARD_FRAME_POINTER_REGNUM:
22012           return offsets->saved_regs - offsets->saved_args;
22013
22014         case THUMB_HARD_FRAME_POINTER_REGNUM:
22015           return offsets->locals_base - offsets->saved_args;
22016
22017         default:
22018           gcc_unreachable ();
22019         }
22020       break;
22021
22022     case FRAME_POINTER_REGNUM:
22023       switch (to)
22024         {
22025         case STACK_POINTER_REGNUM:
22026           return offsets->outgoing_args - offsets->soft_frame;
22027
22028         case ARM_HARD_FRAME_POINTER_REGNUM:
22029           return offsets->saved_regs - offsets->soft_frame;
22030
22031         case THUMB_HARD_FRAME_POINTER_REGNUM:
22032           return offsets->locals_base - offsets->soft_frame;
22033
22034         default:
22035           gcc_unreachable ();
22036         }
22037       break;
22038
22039     default:
22040       gcc_unreachable ();
22041     }
22042 }
22043
22044 /* Generate the function's prologue.  */
22045
22046 void
22047 thumb1_expand_prologue (void)
22048 {
22049   rtx insn;
22050
22051   HOST_WIDE_INT amount;
22052   arm_stack_offsets *offsets;
22053   unsigned long func_type;
22054   int regno;
22055   unsigned long live_regs_mask;
22056   unsigned long l_mask;
22057   unsigned high_regs_pushed = 0;
22058
22059   func_type = arm_current_func_type ();
22060
22061   /* Naked functions don't have prologues.  */
22062   if (IS_NAKED (func_type))
22063     return;
22064
22065   if (IS_INTERRUPT (func_type))
22066     {
22067       error ("interrupt Service Routines cannot be coded in Thumb mode");
22068       return;
22069     }
22070
22071   if (is_called_in_ARM_mode (current_function_decl))
22072     emit_insn (gen_prologue_thumb1_interwork ());
22073
22074   offsets = arm_get_frame_offsets ();
22075   live_regs_mask = offsets->saved_regs_mask;
22076
22077   /* Extract a mask of the ones we can give to the Thumb's push instruction.  */
22078   l_mask = live_regs_mask & 0x40ff;
22079   /* Then count how many other high registers will need to be pushed.  */
22080   high_regs_pushed = bit_count (live_regs_mask & 0x0f00);
22081
22082   if (crtl->args.pretend_args_size)
22083     {
22084       rtx x = GEN_INT (-crtl->args.pretend_args_size);
22085
22086       if (cfun->machine->uses_anonymous_args)
22087         {
22088           int num_pushes = ARM_NUM_INTS (crtl->args.pretend_args_size);
22089           unsigned long mask;
22090
22091           mask = 1ul << (LAST_ARG_REGNUM + 1);
22092           mask -= 1ul << (LAST_ARG_REGNUM + 1 - num_pushes);
22093
22094           insn = thumb1_emit_multi_reg_push (mask, 0);
22095         }
22096       else
22097         {
22098           insn = emit_insn (gen_addsi3 (stack_pointer_rtx,
22099                                         stack_pointer_rtx, x));
22100         }
22101       RTX_FRAME_RELATED_P (insn) = 1;
22102     }
22103
22104   if (TARGET_BACKTRACE)
22105     {
22106       HOST_WIDE_INT offset = 0;
22107       unsigned work_register;
22108       rtx work_reg, x, arm_hfp_rtx;
22109
22110       /* We have been asked to create a stack backtrace structure.
22111          The code looks like this:
22112
22113          0   .align 2
22114          0   func:
22115          0     sub   SP, #16         Reserve space for 4 registers.
22116          2     push  {R7}            Push low registers.
22117          4     add   R7, SP, #20     Get the stack pointer before the push.
22118          6     str   R7, [SP, #8]    Store the stack pointer
22119                                         (before reserving the space).
22120          8     mov   R7, PC          Get hold of the start of this code + 12.
22121         10     str   R7, [SP, #16]   Store it.
22122         12     mov   R7, FP          Get hold of the current frame pointer.
22123         14     str   R7, [SP, #4]    Store it.
22124         16     mov   R7, LR          Get hold of the current return address.
22125         18     str   R7, [SP, #12]   Store it.
22126         20     add   R7, SP, #16     Point at the start of the
22127                                         backtrace structure.
22128         22     mov   FP, R7          Put this value into the frame pointer.  */
22129
22130       work_register = thumb_find_work_register (live_regs_mask);
22131       work_reg = gen_rtx_REG (SImode, work_register);
22132       arm_hfp_rtx = gen_rtx_REG (SImode, ARM_HARD_FRAME_POINTER_REGNUM);
22133
22134       insn = emit_insn (gen_addsi3 (stack_pointer_rtx,
22135                                     stack_pointer_rtx, GEN_INT (-16)));
22136       RTX_FRAME_RELATED_P (insn) = 1;
22137
22138       if (l_mask)
22139         {
22140           insn = thumb1_emit_multi_reg_push (l_mask, l_mask);
22141           RTX_FRAME_RELATED_P (insn) = 1;
22142
22143           offset = bit_count (l_mask) * UNITS_PER_WORD;
22144         }
22145
22146       x = GEN_INT (offset + 16 + crtl->args.pretend_args_size);
22147       emit_insn (gen_addsi3 (work_reg, stack_pointer_rtx, x));
22148
22149       x = plus_constant (stack_pointer_rtx, offset + 4);
22150       x = gen_frame_mem (SImode, x);
22151       emit_move_insn (x, work_reg);
22152
22153       /* Make sure that the instruction fetching the PC is in the right place
22154          to calculate "start of backtrace creation code + 12".  */
22155       /* ??? The stores using the common WORK_REG ought to be enough to
22156          prevent the scheduler from doing anything weird.  Failing that
22157          we could always move all of the following into an UNSPEC_VOLATILE.  */
22158       if (l_mask)
22159         {
22160           x = gen_rtx_REG (SImode, PC_REGNUM);
22161           emit_move_insn (work_reg, x);
22162
22163           x = plus_constant (stack_pointer_rtx, offset + 12);
22164           x = gen_frame_mem (SImode, x);
22165           emit_move_insn (x, work_reg);
22166
22167           emit_move_insn (work_reg, arm_hfp_rtx);
22168
22169           x = plus_constant (stack_pointer_rtx, offset);
22170           x = gen_frame_mem (SImode, x);
22171           emit_move_insn (x, work_reg);
22172         }
22173       else
22174         {
22175           emit_move_insn (work_reg, arm_hfp_rtx);
22176
22177           x = plus_constant (stack_pointer_rtx, offset);
22178           x = gen_frame_mem (SImode, x);
22179           emit_move_insn (x, work_reg);
22180
22181           x = gen_rtx_REG (SImode, PC_REGNUM);
22182           emit_move_insn (work_reg, x);
22183
22184           x = plus_constant (stack_pointer_rtx, offset + 12);
22185           x = gen_frame_mem (SImode, x);
22186           emit_move_insn (x, work_reg);
22187         }
22188
22189       x = gen_rtx_REG (SImode, LR_REGNUM);
22190       emit_move_insn (work_reg, x);
22191
22192       x = plus_constant (stack_pointer_rtx, offset + 8);
22193       x = gen_frame_mem (SImode, x);
22194       emit_move_insn (x, work_reg);
22195
22196       x = GEN_INT (offset + 12);
22197       emit_insn (gen_addsi3 (work_reg, stack_pointer_rtx, x));
22198
22199       emit_move_insn (arm_hfp_rtx, work_reg);
22200     }
22201   /* Optimization:  If we are not pushing any low registers but we are going
22202      to push some high registers then delay our first push.  This will just
22203      be a push of LR and we can combine it with the push of the first high
22204      register.  */
22205   else if ((l_mask & 0xff) != 0
22206            || (high_regs_pushed == 0 && l_mask))
22207     {
22208       unsigned long mask = l_mask;
22209       mask |= (1 << thumb1_extra_regs_pushed (offsets, true)) - 1;
22210       insn = thumb1_emit_multi_reg_push (mask, mask);
22211       RTX_FRAME_RELATED_P (insn) = 1;
22212     }
22213
22214   if (high_regs_pushed)
22215     {
22216       unsigned pushable_regs;
22217       unsigned next_hi_reg;
22218
22219       for (next_hi_reg = 12; next_hi_reg > LAST_LO_REGNUM; next_hi_reg--)
22220         if (live_regs_mask & (1 << next_hi_reg))
22221           break;
22222
22223       pushable_regs = l_mask & 0xff;
22224
22225       if (pushable_regs == 0)
22226         pushable_regs = 1 << thumb_find_work_register (live_regs_mask);
22227
22228       while (high_regs_pushed > 0)
22229         {
22230           unsigned long real_regs_mask = 0;
22231
22232           for (regno = LAST_LO_REGNUM; regno >= 0; regno --)
22233             {
22234               if (pushable_regs & (1 << regno))
22235                 {
22236                   emit_move_insn (gen_rtx_REG (SImode, regno),
22237                                   gen_rtx_REG (SImode, next_hi_reg));
22238
22239                   high_regs_pushed --;
22240                   real_regs_mask |= (1 << next_hi_reg);
22241
22242                   if (high_regs_pushed)
22243                     {
22244                       for (next_hi_reg --; next_hi_reg > LAST_LO_REGNUM;
22245                            next_hi_reg --)
22246                         if (live_regs_mask & (1 << next_hi_reg))
22247                           break;
22248                     }
22249                   else
22250                     {
22251                       pushable_regs &= ~((1 << regno) - 1);
22252                       break;
22253                     }
22254                 }
22255             }
22256
22257           /* If we had to find a work register and we have not yet
22258              saved the LR then add it to the list of regs to push.  */
22259           if (l_mask == (1 << LR_REGNUM))
22260             {
22261               pushable_regs |= l_mask;
22262               real_regs_mask |= l_mask;
22263               l_mask = 0;
22264             }
22265
22266           insn = thumb1_emit_multi_reg_push (pushable_regs, real_regs_mask);
22267           RTX_FRAME_RELATED_P (insn) = 1;
22268         }
22269     }
22270
22271   /* Load the pic register before setting the frame pointer,
22272      so we can use r7 as a temporary work register.  */
22273   if (flag_pic && arm_pic_register != INVALID_REGNUM)
22274     arm_load_pic_register (live_regs_mask);
22275
22276   if (!frame_pointer_needed && CALLER_INTERWORKING_SLOT_SIZE > 0)
22277     emit_move_insn (gen_rtx_REG (Pmode, ARM_HARD_FRAME_POINTER_REGNUM),
22278                     stack_pointer_rtx);
22279
22280   if (flag_stack_usage_info)
22281     current_function_static_stack_size
22282       = offsets->outgoing_args - offsets->saved_args;
22283
22284   amount = offsets->outgoing_args - offsets->saved_regs;
22285   amount -= 4 * thumb1_extra_regs_pushed (offsets, true);
22286   if (amount)
22287     {
22288       if (amount < 512)
22289         {
22290           insn = emit_insn (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx,
22291                                         GEN_INT (- amount)));
22292           RTX_FRAME_RELATED_P (insn) = 1;
22293         }
22294       else
22295         {
22296           rtx reg, dwarf;
22297
22298           /* The stack decrement is too big for an immediate value in a single
22299              insn.  In theory we could issue multiple subtracts, but after
22300              three of them it becomes more space efficient to place the full
22301              value in the constant pool and load into a register.  (Also the
22302              ARM debugger really likes to see only one stack decrement per
22303              function).  So instead we look for a scratch register into which
22304              we can load the decrement, and then we subtract this from the
22305              stack pointer.  Unfortunately on the thumb the only available
22306              scratch registers are the argument registers, and we cannot use
22307              these as they may hold arguments to the function.  Instead we
22308              attempt to locate a call preserved register which is used by this
22309              function.  If we can find one, then we know that it will have
22310              been pushed at the start of the prologue and so we can corrupt
22311              it now.  */
22312           for (regno = LAST_ARG_REGNUM + 1; regno <= LAST_LO_REGNUM; regno++)
22313             if (live_regs_mask & (1 << regno))
22314               break;
22315
22316           gcc_assert(regno <= LAST_LO_REGNUM);
22317
22318           reg = gen_rtx_REG (SImode, regno);
22319
22320           emit_insn (gen_movsi (reg, GEN_INT (- amount)));
22321
22322           insn = emit_insn (gen_addsi3 (stack_pointer_rtx,
22323                                         stack_pointer_rtx, reg));
22324
22325           dwarf = gen_rtx_SET (VOIDmode, stack_pointer_rtx,
22326                                plus_constant (stack_pointer_rtx,
22327                                               -amount));
22328           add_reg_note (insn, REG_FRAME_RELATED_EXPR, dwarf);
22329           RTX_FRAME_RELATED_P (insn) = 1;
22330         }
22331     }
22332
22333   if (frame_pointer_needed)
22334     thumb_set_frame_pointer (offsets);
22335
22336   /* If we are profiling, make sure no instructions are scheduled before
22337      the call to mcount.  Similarly if the user has requested no
22338      scheduling in the prolog.  Similarly if we want non-call exceptions
22339      using the EABI unwinder, to prevent faulting instructions from being
22340      swapped with a stack adjustment.  */
22341   if (crtl->profile || !TARGET_SCHED_PROLOG
22342       || (arm_except_unwind_info (&global_options) == UI_TARGET
22343           && cfun->can_throw_non_call_exceptions))
22344     emit_insn (gen_blockage ());
22345
22346   cfun->machine->lr_save_eliminated = !thumb_force_lr_save ();
22347   if (live_regs_mask & 0xff)
22348     cfun->machine->lr_save_eliminated = 0;
22349 }
22350
22351
22352 void
22353 thumb1_expand_epilogue (void)
22354 {
22355   HOST_WIDE_INT amount;
22356   arm_stack_offsets *offsets;
22357   int regno;
22358
22359   /* Naked functions don't have prologues.  */
22360   if (IS_NAKED (arm_current_func_type ()))
22361     return;
22362
22363   offsets = arm_get_frame_offsets ();
22364   amount = offsets->outgoing_args - offsets->saved_regs;
22365
22366   if (frame_pointer_needed)
22367     {
22368       emit_insn (gen_movsi (stack_pointer_rtx, hard_frame_pointer_rtx));
22369       amount = offsets->locals_base - offsets->saved_regs;
22370     }
22371   amount -= 4 * thumb1_extra_regs_pushed (offsets, false);
22372
22373   gcc_assert (amount >= 0);
22374   if (amount)
22375     {
22376       emit_insn (gen_blockage ());
22377
22378       if (amount < 512)
22379         emit_insn (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx,
22380                                GEN_INT (amount)));
22381       else
22382         {
22383           /* r3 is always free in the epilogue.  */
22384           rtx reg = gen_rtx_REG (SImode, LAST_ARG_REGNUM);
22385
22386           emit_insn (gen_movsi (reg, GEN_INT (amount)));
22387           emit_insn (gen_addsi3 (stack_pointer_rtx, stack_pointer_rtx, reg));
22388         }
22389     }
22390
22391   /* Emit a USE (stack_pointer_rtx), so that
22392      the stack adjustment will not be deleted.  */
22393   emit_insn (gen_prologue_use (stack_pointer_rtx));
22394
22395   if (crtl->profile || !TARGET_SCHED_PROLOG)
22396     emit_insn (gen_blockage ());
22397
22398   /* Emit a clobber for each insn that will be restored in the epilogue,
22399      so that flow2 will get register lifetimes correct.  */
22400   for (regno = 0; regno < 13; regno++)
22401     if (df_regs_ever_live_p (regno) && !call_used_regs[regno])
22402       emit_clobber (gen_rtx_REG (SImode, regno));
22403
22404   if (! df_regs_ever_live_p (LR_REGNUM))
22405     emit_use (gen_rtx_REG (SImode, LR_REGNUM));
22406 }
22407
22408 /* Implementation of insn prologue_thumb1_interwork.  This is the first
22409    "instruction" of a function called in ARM mode.  Swap to thumb mode.  */
22410
22411 const char *
22412 thumb1_output_interwork (void)
22413 {
22414   const char * name;
22415   FILE *f = asm_out_file;
22416
22417   gcc_assert (GET_CODE (DECL_RTL (current_function_decl)) == MEM);
22418   gcc_assert (GET_CODE (XEXP (DECL_RTL (current_function_decl), 0))
22419               == SYMBOL_REF);
22420   name = XSTR (XEXP (DECL_RTL (current_function_decl), 0), 0);
22421
22422   /* Generate code sequence to switch us into Thumb mode.  */
22423   /* The .code 32 directive has already been emitted by
22424      ASM_DECLARE_FUNCTION_NAME.  */
22425   asm_fprintf (f, "\torr\t%r, %r, #1\n", IP_REGNUM, PC_REGNUM);
22426   asm_fprintf (f, "\tbx\t%r\n", IP_REGNUM);
22427
22428   /* Generate a label, so that the debugger will notice the
22429      change in instruction sets.  This label is also used by
22430      the assembler to bypass the ARM code when this function
22431      is called from a Thumb encoded function elsewhere in the
22432      same file.  Hence the definition of STUB_NAME here must
22433      agree with the definition in gas/config/tc-arm.c.  */
22434
22435 #define STUB_NAME ".real_start_of"
22436
22437   fprintf (f, "\t.code\t16\n");
22438 #ifdef ARM_PE
22439   if (arm_dllexport_name_p (name))
22440     name = arm_strip_name_encoding (name);
22441 #endif
22442   asm_fprintf (f, "\t.globl %s%U%s\n", STUB_NAME, name);
22443   fprintf (f, "\t.thumb_func\n");
22444   asm_fprintf (f, "%s%U%s:\n", STUB_NAME, name);
22445
22446   return "";
22447 }
22448
22449 /* Handle the case of a double word load into a low register from
22450    a computed memory address.  The computed address may involve a
22451    register which is overwritten by the load.  */
22452 const char *
22453 thumb_load_double_from_address (rtx *operands)
22454 {
22455   rtx addr;
22456   rtx base;
22457   rtx offset;
22458   rtx arg1;
22459   rtx arg2;
22460
22461   gcc_assert (GET_CODE (operands[0]) == REG);
22462   gcc_assert (GET_CODE (operands[1]) == MEM);
22463
22464   /* Get the memory address.  */
22465   addr = XEXP (operands[1], 0);
22466
22467   /* Work out how the memory address is computed.  */
22468   switch (GET_CODE (addr))
22469     {
22470     case REG:
22471       operands[2] = adjust_address (operands[1], SImode, 4);
22472
22473       if (REGNO (operands[0]) == REGNO (addr))
22474         {
22475           output_asm_insn ("ldr\t%H0, %2", operands);
22476           output_asm_insn ("ldr\t%0, %1", operands);
22477         }
22478       else
22479         {
22480           output_asm_insn ("ldr\t%0, %1", operands);
22481           output_asm_insn ("ldr\t%H0, %2", operands);
22482         }
22483       break;
22484
22485     case CONST:
22486       /* Compute <address> + 4 for the high order load.  */
22487       operands[2] = adjust_address (operands[1], SImode, 4);
22488
22489       output_asm_insn ("ldr\t%0, %1", operands);
22490       output_asm_insn ("ldr\t%H0, %2", operands);
22491       break;
22492
22493     case PLUS:
22494       arg1   = XEXP (addr, 0);
22495       arg2   = XEXP (addr, 1);
22496
22497       if (CONSTANT_P (arg1))
22498         base = arg2, offset = arg1;
22499       else
22500         base = arg1, offset = arg2;
22501
22502       gcc_assert (GET_CODE (base) == REG);
22503
22504       /* Catch the case of <address> = <reg> + <reg> */
22505       if (GET_CODE (offset) == REG)
22506         {
22507           int reg_offset = REGNO (offset);
22508           int reg_base   = REGNO (base);
22509           int reg_dest   = REGNO (operands[0]);
22510
22511           /* Add the base and offset registers together into the
22512              higher destination register.  */
22513           asm_fprintf (asm_out_file, "\tadd\t%r, %r, %r",
22514                        reg_dest + 1, reg_base, reg_offset);
22515
22516           /* Load the lower destination register from the address in
22517              the higher destination register.  */
22518           asm_fprintf (asm_out_file, "\tldr\t%r, [%r, #0]",
22519                        reg_dest, reg_dest + 1);
22520
22521           /* Load the higher destination register from its own address
22522              plus 4.  */
22523           asm_fprintf (asm_out_file, "\tldr\t%r, [%r, #4]",
22524                        reg_dest + 1, reg_dest + 1);
22525         }
22526       else
22527         {
22528           /* Compute <address> + 4 for the high order load.  */
22529           operands[2] = adjust_address (operands[1], SImode, 4);
22530
22531           /* If the computed address is held in the low order register
22532              then load the high order register first, otherwise always
22533              load the low order register first.  */
22534           if (REGNO (operands[0]) == REGNO (base))
22535             {
22536               output_asm_insn ("ldr\t%H0, %2", operands);
22537               output_asm_insn ("ldr\t%0, %1", operands);
22538             }
22539           else
22540             {
22541               output_asm_insn ("ldr\t%0, %1", operands);
22542               output_asm_insn ("ldr\t%H0, %2", operands);
22543             }
22544         }
22545       break;
22546
22547     case LABEL_REF:
22548       /* With no registers to worry about we can just load the value
22549          directly.  */
22550       operands[2] = adjust_address (operands[1], SImode, 4);
22551
22552       output_asm_insn ("ldr\t%H0, %2", operands);
22553       output_asm_insn ("ldr\t%0, %1", operands);
22554       break;
22555
22556     default:
22557       gcc_unreachable ();
22558     }
22559
22560   return "";
22561 }
22562
22563 const char *
22564 thumb_output_move_mem_multiple (int n, rtx *operands)
22565 {
22566   rtx tmp;
22567
22568   switch (n)
22569     {
22570     case 2:
22571       if (REGNO (operands[4]) > REGNO (operands[5]))
22572         {
22573           tmp = operands[4];
22574           operands[4] = operands[5];
22575           operands[5] = tmp;
22576         }
22577       output_asm_insn ("ldmia\t%1!, {%4, %5}", operands);
22578       output_asm_insn ("stmia\t%0!, {%4, %5}", operands);
22579       break;
22580
22581     case 3:
22582       if (REGNO (operands[4]) > REGNO (operands[5]))
22583         {
22584           tmp = operands[4];
22585           operands[4] = operands[5];
22586           operands[5] = tmp;
22587         }
22588       if (REGNO (operands[5]) > REGNO (operands[6]))
22589         {
22590           tmp = operands[5];
22591           operands[5] = operands[6];
22592           operands[6] = tmp;
22593         }
22594       if (REGNO (operands[4]) > REGNO (operands[5]))
22595         {
22596           tmp = operands[4];
22597           operands[4] = operands[5];
22598           operands[5] = tmp;
22599         }
22600
22601       output_asm_insn ("ldmia\t%1!, {%4, %5, %6}", operands);
22602       output_asm_insn ("stmia\t%0!, {%4, %5, %6}", operands);
22603       break;
22604
22605     default:
22606       gcc_unreachable ();
22607     }
22608
22609   return "";
22610 }
22611
22612 /* Output a call-via instruction for thumb state.  */
22613 const char *
22614 thumb_call_via_reg (rtx reg)
22615 {
22616   int regno = REGNO (reg);
22617   rtx *labelp;
22618
22619   gcc_assert (regno < LR_REGNUM);
22620
22621   /* If we are in the normal text section we can use a single instance
22622      per compilation unit.  If we are doing function sections, then we need
22623      an entry per section, since we can't rely on reachability.  */
22624   if (in_section == text_section)
22625     {
22626       thumb_call_reg_needed = 1;
22627
22628       if (thumb_call_via_label[regno] == NULL)
22629         thumb_call_via_label[regno] = gen_label_rtx ();
22630       labelp = thumb_call_via_label + regno;
22631     }
22632   else
22633     {
22634       if (cfun->machine->call_via[regno] == NULL)
22635         cfun->machine->call_via[regno] = gen_label_rtx ();
22636       labelp = cfun->machine->call_via + regno;
22637     }
22638
22639   output_asm_insn ("bl\t%a0", labelp);
22640   return "";
22641 }
22642
22643 /* Routines for generating rtl.  */
22644 void
22645 thumb_expand_movmemqi (rtx *operands)
22646 {
22647   rtx out = copy_to_mode_reg (SImode, XEXP (operands[0], 0));
22648   rtx in  = copy_to_mode_reg (SImode, XEXP (operands[1], 0));
22649   HOST_WIDE_INT len = INTVAL (operands[2]);
22650   HOST_WIDE_INT offset = 0;
22651
22652   while (len >= 12)
22653     {
22654       emit_insn (gen_movmem12b (out, in, out, in));
22655       len -= 12;
22656     }
22657
22658   if (len >= 8)
22659     {
22660       emit_insn (gen_movmem8b (out, in, out, in));
22661       len -= 8;
22662     }
22663
22664   if (len >= 4)
22665     {
22666       rtx reg = gen_reg_rtx (SImode);
22667       emit_insn (gen_movsi (reg, gen_rtx_MEM (SImode, in)));
22668       emit_insn (gen_movsi (gen_rtx_MEM (SImode, out), reg));
22669       len -= 4;
22670       offset += 4;
22671     }
22672
22673   if (len >= 2)
22674     {
22675       rtx reg = gen_reg_rtx (HImode);
22676       emit_insn (gen_movhi (reg, gen_rtx_MEM (HImode,
22677                                               plus_constant (in, offset))));
22678       emit_insn (gen_movhi (gen_rtx_MEM (HImode, plus_constant (out, offset)),
22679                             reg));
22680       len -= 2;
22681       offset += 2;
22682     }
22683
22684   if (len)
22685     {
22686       rtx reg = gen_reg_rtx (QImode);
22687       emit_insn (gen_movqi (reg, gen_rtx_MEM (QImode,
22688                                               plus_constant (in, offset))));
22689       emit_insn (gen_movqi (gen_rtx_MEM (QImode, plus_constant (out, offset)),
22690                             reg));
22691     }
22692 }
22693
22694 void
22695 thumb_reload_out_hi (rtx *operands)
22696 {
22697   emit_insn (gen_thumb_movhi_clobber (operands[0], operands[1], operands[2]));
22698 }
22699
22700 /* Handle reading a half-word from memory during reload.  */
22701 void
22702 thumb_reload_in_hi (rtx *operands ATTRIBUTE_UNUSED)
22703 {
22704   gcc_unreachable ();
22705 }
22706
22707 /* Return the length of a function name prefix
22708     that starts with the character 'c'.  */
22709 static int
22710 arm_get_strip_length (int c)
22711 {
22712   switch (c)
22713     {
22714     ARM_NAME_ENCODING_LENGTHS
22715       default: return 0;
22716     }
22717 }
22718
22719 /* Return a pointer to a function's name with any
22720    and all prefix encodings stripped from it.  */
22721 const char *
22722 arm_strip_name_encoding (const char *name)
22723 {
22724   int skip;
22725
22726   while ((skip = arm_get_strip_length (* name)))
22727     name += skip;
22728
22729   return name;
22730 }
22731
22732 /* If there is a '*' anywhere in the name's prefix, then
22733    emit the stripped name verbatim, otherwise prepend an
22734    underscore if leading underscores are being used.  */
22735 void
22736 arm_asm_output_labelref (FILE *stream, const char *name)
22737 {
22738   int skip;
22739   int verbatim = 0;
22740
22741   while ((skip = arm_get_strip_length (* name)))
22742     {
22743       verbatim |= (*name == '*');
22744       name += skip;
22745     }
22746
22747   if (verbatim)
22748     fputs (name, stream);
22749   else
22750     asm_fprintf (stream, "%U%s", name);
22751 }
22752
22753 static void
22754 arm_file_start (void)
22755 {
22756   int val;
22757
22758   if (TARGET_UNIFIED_ASM)
22759     asm_fprintf (asm_out_file, "\t.syntax unified\n");
22760
22761   if (TARGET_BPABI)
22762     {
22763       const char *fpu_name;
22764       if (arm_selected_arch)
22765         asm_fprintf (asm_out_file, "\t.arch %s\n", arm_selected_arch->name);
22766       else if (strncmp (arm_selected_cpu->name, "generic", 7) == 0)
22767         asm_fprintf (asm_out_file, "\t.arch %s\n", arm_selected_cpu->name + 8);
22768       else
22769         asm_fprintf (asm_out_file, "\t.cpu %s\n", arm_selected_cpu->name);
22770
22771       if (TARGET_SOFT_FLOAT)
22772         {
22773           if (TARGET_VFP)
22774             fpu_name = "softvfp";
22775           else
22776             fpu_name = "softfpa";
22777         }
22778       else
22779         {
22780           fpu_name = arm_fpu_desc->name;
22781           if (arm_fpu_desc->model == ARM_FP_MODEL_VFP)
22782             {
22783               if (TARGET_HARD_FLOAT)
22784                 EMIT_EABI_ATTRIBUTE (Tag_ABI_HardFP_use, 27, 3);
22785               if (TARGET_HARD_FLOAT_ABI)
22786                 EMIT_EABI_ATTRIBUTE (Tag_ABI_VFP_args, 28, 1);
22787             }
22788         }
22789       asm_fprintf (asm_out_file, "\t.fpu %s\n", fpu_name);
22790
22791       /* Some of these attributes only apply when the corresponding features
22792          are used.  However we don't have any easy way of figuring this out.
22793          Conservatively record the setting that would have been used.  */
22794
22795       if (flag_rounding_math)
22796         EMIT_EABI_ATTRIBUTE (Tag_ABI_FP_rounding, 19, 1);
22797
22798       if (!flag_unsafe_math_optimizations)
22799         {
22800           EMIT_EABI_ATTRIBUTE (Tag_ABI_FP_denormal, 20, 1);
22801           EMIT_EABI_ATTRIBUTE (Tag_ABI_FP_exceptions, 21, 1);
22802         }
22803       if (flag_signaling_nans)
22804         EMIT_EABI_ATTRIBUTE (Tag_ABI_FP_user_exceptions, 22, 1);
22805
22806       EMIT_EABI_ATTRIBUTE (Tag_ABI_FP_number_model, 23,
22807                            flag_finite_math_only ? 1 : 3);
22808
22809       EMIT_EABI_ATTRIBUTE (Tag_ABI_align8_needed, 24, 1);
22810       EMIT_EABI_ATTRIBUTE (Tag_ABI_align8_preserved, 25, 1);
22811       EMIT_EABI_ATTRIBUTE (Tag_ABI_enum_size, 26, flag_short_enums ? 1 : 2);
22812
22813       /* Tag_ABI_optimization_goals.  */
22814       if (optimize_size)
22815         val = 4;
22816       else if (optimize >= 2)
22817         val = 2;
22818       else if (optimize)
22819         val = 1;
22820       else
22821         val = 6;
22822       EMIT_EABI_ATTRIBUTE (Tag_ABI_optimization_goals, 30, val);
22823
22824       EMIT_EABI_ATTRIBUTE (Tag_CPU_unaligned_access, 34, unaligned_access);
22825
22826       if (arm_fp16_format)
22827         EMIT_EABI_ATTRIBUTE (Tag_ABI_FP_16bit_format, 38, (int) arm_fp16_format);
22828
22829       if (arm_lang_output_object_attributes_hook)
22830         arm_lang_output_object_attributes_hook();
22831     }
22832
22833   default_file_start ();
22834 }
22835
22836 static void
22837 arm_file_end (void)
22838 {
22839   int regno;
22840
22841   if (NEED_INDICATE_EXEC_STACK)
22842     /* Add .note.GNU-stack.  */
22843     file_end_indicate_exec_stack ();
22844
22845   if (! thumb_call_reg_needed)
22846     return;
22847
22848   switch_to_section (text_section);
22849   asm_fprintf (asm_out_file, "\t.code 16\n");
22850   ASM_OUTPUT_ALIGN (asm_out_file, 1);
22851
22852   for (regno = 0; regno < LR_REGNUM; regno++)
22853     {
22854       rtx label = thumb_call_via_label[regno];
22855
22856       if (label != 0)
22857         {
22858           targetm.asm_out.internal_label (asm_out_file, "L",
22859                                           CODE_LABEL_NUMBER (label));
22860           asm_fprintf (asm_out_file, "\tbx\t%r\n", regno);
22861         }
22862     }
22863 }
22864
22865 #ifndef ARM_PE
22866 /* Symbols in the text segment can be accessed without indirecting via the
22867    constant pool; it may take an extra binary operation, but this is still
22868    faster than indirecting via memory.  Don't do this when not optimizing,
22869    since we won't be calculating al of the offsets necessary to do this
22870    simplification.  */
22871
22872 static void
22873 arm_encode_section_info (tree decl, rtx rtl, int first)
22874 {
22875   if (optimize > 0 && TREE_CONSTANT (decl))
22876     SYMBOL_REF_FLAG (XEXP (rtl, 0)) = 1;
22877
22878   default_encode_section_info (decl, rtl, first);
22879 }
22880 #endif /* !ARM_PE */
22881
22882 static void
22883 arm_internal_label (FILE *stream, const char *prefix, unsigned long labelno)
22884 {
22885   if (arm_ccfsm_state == 3 && (unsigned) arm_target_label == labelno
22886       && !strcmp (prefix, "L"))
22887     {
22888       arm_ccfsm_state = 0;
22889       arm_target_insn = NULL;
22890     }
22891   default_internal_label (stream, prefix, labelno);
22892 }
22893
22894 /* Output code to add DELTA to the first argument, and then jump
22895    to FUNCTION.  Used for C++ multiple inheritance.  */
22896 static void
22897 arm_output_mi_thunk (FILE *file, tree thunk ATTRIBUTE_UNUSED,
22898                      HOST_WIDE_INT delta,
22899                      HOST_WIDE_INT vcall_offset ATTRIBUTE_UNUSED,
22900                      tree function)
22901 {
22902   static int thunk_label = 0;
22903   char label[256];
22904   char labelpc[256];
22905   int mi_delta = delta;
22906   const char *const mi_op = mi_delta < 0 ? "sub" : "add";
22907   int shift = 0;
22908   int this_regno = (aggregate_value_p (TREE_TYPE (TREE_TYPE (function)), function)
22909                     ? 1 : 0);
22910   if (mi_delta < 0)
22911     mi_delta = - mi_delta;
22912
22913   if (TARGET_THUMB1)
22914     {
22915       int labelno = thunk_label++;
22916       ASM_GENERATE_INTERNAL_LABEL (label, "LTHUMBFUNC", labelno);
22917       /* Thunks are entered in arm mode when avaiable.  */
22918       if (TARGET_THUMB1_ONLY)
22919         {
22920           /* push r3 so we can use it as a temporary.  */
22921           /* TODO: Omit this save if r3 is not used.  */
22922           fputs ("\tpush {r3}\n", file);
22923           fputs ("\tldr\tr3, ", file);
22924         }
22925       else
22926         {
22927           fputs ("\tldr\tr12, ", file);
22928         }
22929       assemble_name (file, label);
22930       fputc ('\n', file);
22931       if (flag_pic)
22932         {
22933           /* If we are generating PIC, the ldr instruction below loads
22934              "(target - 7) - .LTHUNKPCn" into r12.  The pc reads as
22935              the address of the add + 8, so we have:
22936
22937              r12 = (target - 7) - .LTHUNKPCn + (.LTHUNKPCn + 8)
22938                  = target + 1.
22939
22940              Note that we have "+ 1" because some versions of GNU ld
22941              don't set the low bit of the result for R_ARM_REL32
22942              relocations against thumb function symbols.
22943              On ARMv6M this is +4, not +8.  */
22944           ASM_GENERATE_INTERNAL_LABEL (labelpc, "LTHUNKPC", labelno);
22945           assemble_name (file, labelpc);
22946           fputs (":\n", file);
22947           if (TARGET_THUMB1_ONLY)
22948             {
22949               /* This is 2 insns after the start of the thunk, so we know it
22950                  is 4-byte aligned.  */
22951               fputs ("\tadd\tr3, pc, r3\n", file);
22952               fputs ("\tmov r12, r3\n", file);
22953             }
22954           else
22955             fputs ("\tadd\tr12, pc, r12\n", file);
22956         }
22957       else if (TARGET_THUMB1_ONLY)
22958         fputs ("\tmov r12, r3\n", file);
22959     }
22960   if (TARGET_THUMB1_ONLY)
22961     {
22962       if (mi_delta > 255)
22963         {
22964           fputs ("\tldr\tr3, ", file);
22965           assemble_name (file, label);
22966           fputs ("+4\n", file);
22967           asm_fprintf (file, "\t%s\t%r, %r, r3\n",
22968                        mi_op, this_regno, this_regno);
22969         }
22970       else if (mi_delta != 0)
22971         {
22972           asm_fprintf (file, "\t%s\t%r, %r, #%d\n",
22973                        mi_op, this_regno, this_regno,
22974                        mi_delta);
22975         }
22976     }
22977   else
22978     {
22979       /* TODO: Use movw/movt for large constants when available.  */
22980       while (mi_delta != 0)
22981         {
22982           if ((mi_delta & (3 << shift)) == 0)
22983             shift += 2;
22984           else
22985             {
22986               asm_fprintf (file, "\t%s\t%r, %r, #%d\n",
22987                            mi_op, this_regno, this_regno,
22988                            mi_delta & (0xff << shift));
22989               mi_delta &= ~(0xff << shift);
22990               shift += 8;
22991             }
22992         }
22993     }
22994   if (TARGET_THUMB1)
22995     {
22996       if (TARGET_THUMB1_ONLY)
22997         fputs ("\tpop\t{r3}\n", file);
22998
22999       fprintf (file, "\tbx\tr12\n");
23000       ASM_OUTPUT_ALIGN (file, 2);
23001       assemble_name (file, label);
23002       fputs (":\n", file);
23003       if (flag_pic)
23004         {
23005           /* Output ".word .LTHUNKn-7-.LTHUNKPCn".  */
23006           rtx tem = XEXP (DECL_RTL (function), 0);
23007           tem = gen_rtx_PLUS (GET_MODE (tem), tem, GEN_INT (-7));
23008           tem = gen_rtx_MINUS (GET_MODE (tem),
23009                                tem,
23010                                gen_rtx_SYMBOL_REF (Pmode,
23011                                                    ggc_strdup (labelpc)));
23012           assemble_integer (tem, 4, BITS_PER_WORD, 1);
23013         }
23014       else
23015         /* Output ".word .LTHUNKn".  */
23016         assemble_integer (XEXP (DECL_RTL (function), 0), 4, BITS_PER_WORD, 1);
23017
23018       if (TARGET_THUMB1_ONLY && mi_delta > 255)
23019         assemble_integer (GEN_INT(mi_delta), 4, BITS_PER_WORD, 1);
23020     }
23021   else
23022     {
23023       fputs ("\tb\t", file);
23024       assemble_name (file, XSTR (XEXP (DECL_RTL (function), 0), 0));
23025       if (NEED_PLT_RELOC)
23026         fputs ("(PLT)", file);
23027       fputc ('\n', file);
23028     }
23029 }
23030
23031 int
23032 arm_emit_vector_const (FILE *file, rtx x)
23033 {
23034   int i;
23035   const char * pattern;
23036
23037   gcc_assert (GET_CODE (x) == CONST_VECTOR);
23038
23039   switch (GET_MODE (x))
23040     {
23041     case V2SImode: pattern = "%08x"; break;
23042     case V4HImode: pattern = "%04x"; break;
23043     case V8QImode: pattern = "%02x"; break;
23044     default:       gcc_unreachable ();
23045     }
23046
23047   fprintf (file, "0x");
23048   for (i = CONST_VECTOR_NUNITS (x); i--;)
23049     {
23050       rtx element;
23051
23052       element = CONST_VECTOR_ELT (x, i);
23053       fprintf (file, pattern, INTVAL (element));
23054     }
23055
23056   return 1;
23057 }
23058
23059 /* Emit a fp16 constant appropriately padded to occupy a 4-byte word.
23060    HFmode constant pool entries are actually loaded with ldr.  */
23061 void
23062 arm_emit_fp16_const (rtx c)
23063 {
23064   REAL_VALUE_TYPE r;
23065   long bits;
23066
23067   REAL_VALUE_FROM_CONST_DOUBLE (r, c);
23068   bits = real_to_target (NULL, &r, HFmode);
23069   if (WORDS_BIG_ENDIAN)
23070     assemble_zeros (2);
23071   assemble_integer (GEN_INT (bits), 2, BITS_PER_WORD, 1);
23072   if (!WORDS_BIG_ENDIAN)
23073     assemble_zeros (2);
23074 }
23075
23076 const char *
23077 arm_output_load_gr (rtx *operands)
23078 {
23079   rtx reg;
23080   rtx offset;
23081   rtx wcgr;
23082   rtx sum;
23083
23084   if (GET_CODE (operands [1]) != MEM
23085       || GET_CODE (sum = XEXP (operands [1], 0)) != PLUS
23086       || GET_CODE (reg = XEXP (sum, 0)) != REG
23087       || GET_CODE (offset = XEXP (sum, 1)) != CONST_INT
23088       || ((INTVAL (offset) < 1024) && (INTVAL (offset) > -1024)))
23089     return "wldrw%?\t%0, %1";
23090
23091   /* Fix up an out-of-range load of a GR register.  */
23092   output_asm_insn ("str%?\t%0, [sp, #-4]!\t@ Start of GR load expansion", & reg);
23093   wcgr = operands[0];
23094   operands[0] = reg;
23095   output_asm_insn ("ldr%?\t%0, %1", operands);
23096
23097   operands[0] = wcgr;
23098   operands[1] = reg;
23099   output_asm_insn ("tmcr%?\t%0, %1", operands);
23100   output_asm_insn ("ldr%?\t%0, [sp], #4\t@ End of GR load expansion", & reg);
23101
23102   return "";
23103 }
23104
23105 /* Worker function for TARGET_SETUP_INCOMING_VARARGS.
23106
23107    On the ARM, PRETEND_SIZE is set in order to have the prologue push the last
23108    named arg and all anonymous args onto the stack.
23109    XXX I know the prologue shouldn't be pushing registers, but it is faster
23110    that way.  */
23111
23112 static void
23113 arm_setup_incoming_varargs (cumulative_args_t pcum_v,
23114                             enum machine_mode mode,
23115                             tree type,
23116                             int *pretend_size,
23117                             int second_time ATTRIBUTE_UNUSED)
23118 {
23119   CUMULATIVE_ARGS *pcum = get_cumulative_args (pcum_v);
23120   int nregs;
23121
23122   cfun->machine->uses_anonymous_args = 1;
23123   if (pcum->pcs_variant <= ARM_PCS_AAPCS_LOCAL)
23124     {
23125       nregs = pcum->aapcs_ncrn;
23126       if ((nregs & 1) && arm_needs_doubleword_align (mode, type))
23127         nregs++;
23128     }
23129   else
23130     nregs = pcum->nregs;
23131
23132   if (nregs < NUM_ARG_REGS)
23133     *pretend_size = (NUM_ARG_REGS - nregs) * UNITS_PER_WORD;
23134 }
23135
23136 /* Return nonzero if the CONSUMER instruction (a store) does not need
23137    PRODUCER's value to calculate the address.  */
23138
23139 int
23140 arm_no_early_store_addr_dep (rtx producer, rtx consumer)
23141 {
23142   rtx value = PATTERN (producer);
23143   rtx addr = PATTERN (consumer);
23144
23145   if (GET_CODE (value) == COND_EXEC)
23146     value = COND_EXEC_CODE (value);
23147   if (GET_CODE (value) == PARALLEL)
23148     value = XVECEXP (value, 0, 0);
23149   value = XEXP (value, 0);
23150   if (GET_CODE (addr) == COND_EXEC)
23151     addr = COND_EXEC_CODE (addr);
23152   if (GET_CODE (addr) == PARALLEL)
23153     addr = XVECEXP (addr, 0, 0);
23154   addr = XEXP (addr, 0);
23155
23156   return !reg_overlap_mentioned_p (value, addr);
23157 }
23158
23159 /* Return nonzero if the CONSUMER instruction (a store) does need
23160    PRODUCER's value to calculate the address.  */
23161
23162 int
23163 arm_early_store_addr_dep (rtx producer, rtx consumer)
23164 {
23165   return !arm_no_early_store_addr_dep (producer, consumer);
23166 }
23167
23168 /* Return nonzero if the CONSUMER instruction (a load) does need
23169    PRODUCER's value to calculate the address.  */
23170
23171 int
23172 arm_early_load_addr_dep (rtx producer, rtx consumer)
23173 {
23174   rtx value = PATTERN (producer);
23175   rtx addr = PATTERN (consumer);
23176
23177   if (GET_CODE (value) == COND_EXEC)
23178     value = COND_EXEC_CODE (value);
23179   if (GET_CODE (value) == PARALLEL)
23180     value = XVECEXP (value, 0, 0);
23181   value = XEXP (value, 0);
23182   if (GET_CODE (addr) == COND_EXEC)
23183     addr = COND_EXEC_CODE (addr);
23184   if (GET_CODE (addr) == PARALLEL)
23185     addr = XVECEXP (addr, 0, 0);
23186   addr = XEXP (addr, 1);
23187
23188   return reg_overlap_mentioned_p (value, addr);
23189 }
23190
23191 /* Return nonzero if the CONSUMER instruction (an ALU op) does not
23192    have an early register shift value or amount dependency on the
23193    result of PRODUCER.  */
23194
23195 int
23196 arm_no_early_alu_shift_dep (rtx producer, rtx consumer)
23197 {
23198   rtx value = PATTERN (producer);
23199   rtx op = PATTERN (consumer);
23200   rtx early_op;
23201
23202   if (GET_CODE (value) == COND_EXEC)
23203     value = COND_EXEC_CODE (value);
23204   if (GET_CODE (value) == PARALLEL)
23205     value = XVECEXP (value, 0, 0);
23206   value = XEXP (value, 0);
23207   if (GET_CODE (op) == COND_EXEC)
23208     op = COND_EXEC_CODE (op);
23209   if (GET_CODE (op) == PARALLEL)
23210     op = XVECEXP (op, 0, 0);
23211   op = XEXP (op, 1);
23212
23213   early_op = XEXP (op, 0);
23214   /* This is either an actual independent shift, or a shift applied to
23215      the first operand of another operation.  We want the whole shift
23216      operation.  */
23217   if (GET_CODE (early_op) == REG)
23218     early_op = op;
23219
23220   return !reg_overlap_mentioned_p (value, early_op);
23221 }
23222
23223 /* Return nonzero if the CONSUMER instruction (an ALU op) does not
23224    have an early register shift value dependency on the result of
23225    PRODUCER.  */
23226
23227 int
23228 arm_no_early_alu_shift_value_dep (rtx producer, rtx consumer)
23229 {
23230   rtx value = PATTERN (producer);
23231   rtx op = PATTERN (consumer);
23232   rtx early_op;
23233
23234   if (GET_CODE (value) == COND_EXEC)
23235     value = COND_EXEC_CODE (value);
23236   if (GET_CODE (value) == PARALLEL)
23237     value = XVECEXP (value, 0, 0);
23238   value = XEXP (value, 0);
23239   if (GET_CODE (op) == COND_EXEC)
23240     op = COND_EXEC_CODE (op);
23241   if (GET_CODE (op) == PARALLEL)
23242     op = XVECEXP (op, 0, 0);
23243   op = XEXP (op, 1);
23244
23245   early_op = XEXP (op, 0);
23246
23247   /* This is either an actual independent shift, or a shift applied to
23248      the first operand of another operation.  We want the value being
23249      shifted, in either case.  */
23250   if (GET_CODE (early_op) != REG)
23251     early_op = XEXP (early_op, 0);
23252
23253   return !reg_overlap_mentioned_p (value, early_op);
23254 }
23255
23256 /* Return nonzero if the CONSUMER (a mul or mac op) does not
23257    have an early register mult dependency on the result of
23258    PRODUCER.  */
23259
23260 int
23261 arm_no_early_mul_dep (rtx producer, rtx consumer)
23262 {
23263   rtx value = PATTERN (producer);
23264   rtx op = PATTERN (consumer);
23265
23266   if (GET_CODE (value) == COND_EXEC)
23267     value = COND_EXEC_CODE (value);
23268   if (GET_CODE (value) == PARALLEL)
23269     value = XVECEXP (value, 0, 0);
23270   value = XEXP (value, 0);
23271   if (GET_CODE (op) == COND_EXEC)
23272     op = COND_EXEC_CODE (op);
23273   if (GET_CODE (op) == PARALLEL)
23274     op = XVECEXP (op, 0, 0);
23275   op = XEXP (op, 1);
23276
23277   if (GET_CODE (op) == PLUS || GET_CODE (op) == MINUS)
23278     {
23279       if (GET_CODE (XEXP (op, 0)) == MULT)
23280         return !reg_overlap_mentioned_p (value, XEXP (op, 0));
23281       else
23282         return !reg_overlap_mentioned_p (value, XEXP (op, 1));
23283     }
23284
23285   return 0;
23286 }
23287
23288 /* We can't rely on the caller doing the proper promotion when
23289    using APCS or ATPCS.  */
23290
23291 static bool
23292 arm_promote_prototypes (const_tree t ATTRIBUTE_UNUSED)
23293 {
23294     return !TARGET_AAPCS_BASED;
23295 }
23296
23297 static enum machine_mode
23298 arm_promote_function_mode (const_tree type ATTRIBUTE_UNUSED,
23299                            enum machine_mode mode,
23300                            int *punsignedp ATTRIBUTE_UNUSED,
23301                            const_tree fntype ATTRIBUTE_UNUSED,
23302                            int for_return ATTRIBUTE_UNUSED)
23303 {
23304   if (GET_MODE_CLASS (mode) == MODE_INT
23305       && GET_MODE_SIZE (mode) < 4)
23306     return SImode;
23307
23308   return mode;
23309 }
23310
23311 /* AAPCS based ABIs use short enums by default.  */
23312
23313 static bool
23314 arm_default_short_enums (void)
23315 {
23316   return TARGET_AAPCS_BASED && arm_abi != ARM_ABI_AAPCS_LINUX;
23317 }
23318
23319
23320 /* AAPCS requires that anonymous bitfields affect structure alignment.  */
23321
23322 static bool
23323 arm_align_anon_bitfield (void)
23324 {
23325   return TARGET_AAPCS_BASED;
23326 }
23327
23328
23329 /* The generic C++ ABI says 64-bit (long long).  The EABI says 32-bit.  */
23330
23331 static tree
23332 arm_cxx_guard_type (void)
23333 {
23334   return TARGET_AAPCS_BASED ? integer_type_node : long_long_integer_type_node;
23335 }
23336
23337 /* Return non-zero if the consumer (a multiply-accumulate instruction)
23338    has an accumulator dependency on the result of the producer (a
23339    multiplication instruction) and no other dependency on that result.  */
23340 int
23341 arm_mac_accumulator_is_mul_result (rtx producer, rtx consumer)
23342 {
23343   rtx mul = PATTERN (producer);
23344   rtx mac = PATTERN (consumer);
23345   rtx mul_result;
23346   rtx mac_op0, mac_op1, mac_acc;
23347
23348   if (GET_CODE (mul) == COND_EXEC)
23349     mul = COND_EXEC_CODE (mul);
23350   if (GET_CODE (mac) == COND_EXEC)
23351     mac = COND_EXEC_CODE (mac);
23352
23353   /* Check that mul is of the form (set (...) (mult ...))
23354      and mla is of the form (set (...) (plus (mult ...) (...))).  */
23355   if ((GET_CODE (mul) != SET || GET_CODE (XEXP (mul, 1)) != MULT)
23356       || (GET_CODE (mac) != SET || GET_CODE (XEXP (mac, 1)) != PLUS
23357           || GET_CODE (XEXP (XEXP (mac, 1), 0)) != MULT))
23358     return 0;
23359
23360   mul_result = XEXP (mul, 0);
23361   mac_op0 = XEXP (XEXP (XEXP (mac, 1), 0), 0);
23362   mac_op1 = XEXP (XEXP (XEXP (mac, 1), 0), 1);
23363   mac_acc = XEXP (XEXP (mac, 1), 1);
23364
23365   return (reg_overlap_mentioned_p (mul_result, mac_acc)
23366           && !reg_overlap_mentioned_p (mul_result, mac_op0)
23367           && !reg_overlap_mentioned_p (mul_result, mac_op1));
23368 }
23369
23370
23371 /* The EABI says test the least significant bit of a guard variable.  */
23372
23373 static bool
23374 arm_cxx_guard_mask_bit (void)
23375 {
23376   return TARGET_AAPCS_BASED;
23377 }
23378
23379
23380 /* The EABI specifies that all array cookies are 8 bytes long.  */
23381
23382 static tree
23383 arm_get_cookie_size (tree type)
23384 {
23385   tree size;
23386
23387   if (!TARGET_AAPCS_BASED)
23388     return default_cxx_get_cookie_size (type);
23389
23390   size = build_int_cst (sizetype, 8);
23391   return size;
23392 }
23393
23394
23395 /* The EABI says that array cookies should also contain the element size.  */
23396
23397 static bool
23398 arm_cookie_has_size (void)
23399 {
23400   return TARGET_AAPCS_BASED;
23401 }
23402
23403
23404 /* The EABI says constructors and destructors should return a pointer to
23405    the object constructed/destroyed.  */
23406
23407 static bool
23408 arm_cxx_cdtor_returns_this (void)
23409 {
23410   return TARGET_AAPCS_BASED;
23411 }
23412
23413 /* The EABI says that an inline function may never be the key
23414    method.  */
23415
23416 static bool
23417 arm_cxx_key_method_may_be_inline (void)
23418 {
23419   return !TARGET_AAPCS_BASED;
23420 }
23421
23422 static void
23423 arm_cxx_determine_class_data_visibility (tree decl)
23424 {
23425   if (!TARGET_AAPCS_BASED
23426       || !TARGET_DLLIMPORT_DECL_ATTRIBUTES)
23427     return;
23428
23429   /* In general, \S 3.2.5.5 of the ARM EABI requires that class data
23430      is exported.  However, on systems without dynamic vague linkage,
23431      \S 3.2.5.6 says that COMDAT class data has hidden linkage.  */
23432   if (!TARGET_ARM_DYNAMIC_VAGUE_LINKAGE_P && DECL_COMDAT (decl))
23433     DECL_VISIBILITY (decl) = VISIBILITY_HIDDEN;
23434   else
23435     DECL_VISIBILITY (decl) = VISIBILITY_DEFAULT;
23436   DECL_VISIBILITY_SPECIFIED (decl) = 1;
23437 }
23438
23439 static bool
23440 arm_cxx_class_data_always_comdat (void)
23441 {
23442   /* \S 3.2.5.4 of the ARM C++ ABI says that class data only have
23443      vague linkage if the class has no key function.  */
23444   return !TARGET_AAPCS_BASED;
23445 }
23446
23447
23448 /* The EABI says __aeabi_atexit should be used to register static
23449    destructors.  */
23450
23451 static bool
23452 arm_cxx_use_aeabi_atexit (void)
23453 {
23454   return TARGET_AAPCS_BASED;
23455 }
23456
23457
23458 void
23459 arm_set_return_address (rtx source, rtx scratch)
23460 {
23461   arm_stack_offsets *offsets;
23462   HOST_WIDE_INT delta;
23463   rtx addr;
23464   unsigned long saved_regs;
23465
23466   offsets = arm_get_frame_offsets ();
23467   saved_regs = offsets->saved_regs_mask;
23468
23469   if ((saved_regs & (1 << LR_REGNUM)) == 0)
23470     emit_move_insn (gen_rtx_REG (Pmode, LR_REGNUM), source);
23471   else
23472     {
23473       if (frame_pointer_needed)
23474         addr = plus_constant(hard_frame_pointer_rtx, -4);
23475       else
23476         {
23477           /* LR will be the first saved register.  */
23478           delta = offsets->outgoing_args - (offsets->frame + 4);
23479
23480
23481           if (delta >= 4096)
23482             {
23483               emit_insn (gen_addsi3 (scratch, stack_pointer_rtx,
23484                                      GEN_INT (delta & ~4095)));
23485               addr = scratch;
23486               delta &= 4095;
23487             }
23488           else
23489             addr = stack_pointer_rtx;
23490
23491           addr = plus_constant (addr, delta);
23492         }
23493       emit_move_insn (gen_frame_mem (Pmode, addr), source);
23494     }
23495 }
23496
23497
23498 void
23499 thumb_set_return_address (rtx source, rtx scratch)
23500 {
23501   arm_stack_offsets *offsets;
23502   HOST_WIDE_INT delta;
23503   HOST_WIDE_INT limit;
23504   int reg;
23505   rtx addr;
23506   unsigned long mask;
23507
23508   emit_use (source);
23509
23510   offsets = arm_get_frame_offsets ();
23511   mask = offsets->saved_regs_mask;
23512   if (mask & (1 << LR_REGNUM))
23513     {
23514       limit = 1024;
23515       /* Find the saved regs.  */
23516       if (frame_pointer_needed)
23517         {
23518           delta = offsets->soft_frame - offsets->saved_args;
23519           reg = THUMB_HARD_FRAME_POINTER_REGNUM;
23520           if (TARGET_THUMB1)
23521             limit = 128;
23522         }
23523       else
23524         {
23525           delta = offsets->outgoing_args - offsets->saved_args;
23526           reg = SP_REGNUM;
23527         }
23528       /* Allow for the stack frame.  */
23529       if (TARGET_THUMB1 && TARGET_BACKTRACE)
23530         delta -= 16;
23531       /* The link register is always the first saved register.  */
23532       delta -= 4;
23533
23534       /* Construct the address.  */
23535       addr = gen_rtx_REG (SImode, reg);
23536       if (delta > limit)
23537         {
23538           emit_insn (gen_movsi (scratch, GEN_INT (delta)));
23539           emit_insn (gen_addsi3 (scratch, scratch, stack_pointer_rtx));
23540           addr = scratch;
23541         }
23542       else
23543         addr = plus_constant (addr, delta);
23544
23545       emit_move_insn (gen_frame_mem (Pmode, addr), source);
23546     }
23547   else
23548     emit_move_insn (gen_rtx_REG (Pmode, LR_REGNUM), source);
23549 }
23550
23551 /* Implements target hook vector_mode_supported_p.  */
23552 bool
23553 arm_vector_mode_supported_p (enum machine_mode mode)
23554 {
23555   /* Neon also supports V2SImode, etc. listed in the clause below.  */
23556   if (TARGET_NEON && (mode == V2SFmode || mode == V4SImode || mode == V8HImode
23557       || mode == V16QImode || mode == V4SFmode || mode == V2DImode))
23558     return true;
23559
23560   if ((TARGET_NEON || TARGET_IWMMXT)
23561       && ((mode == V2SImode)
23562           || (mode == V4HImode)
23563           || (mode == V8QImode)))
23564     return true;
23565
23566   if (TARGET_INT_SIMD && (mode == V4UQQmode || mode == V4QQmode
23567       || mode == V2UHQmode || mode == V2HQmode || mode == V2UHAmode
23568       || mode == V2HAmode))
23569     return true;
23570
23571   return false;
23572 }
23573
23574 /* Implements target hook array_mode_supported_p.  */
23575
23576 static bool
23577 arm_array_mode_supported_p (enum machine_mode mode,
23578                             unsigned HOST_WIDE_INT nelems)
23579 {
23580   if (TARGET_NEON
23581       && (VALID_NEON_DREG_MODE (mode) || VALID_NEON_QREG_MODE (mode))
23582       && (nelems >= 2 && nelems <= 4))
23583     return true;
23584
23585   return false;
23586 }
23587
23588 /* Use the option -mvectorize-with-neon-double to override the use of quardword
23589    registers when autovectorizing for Neon, at least until multiple vector
23590    widths are supported properly by the middle-end.  */
23591
23592 static enum machine_mode
23593 arm_preferred_simd_mode (enum machine_mode mode)
23594 {
23595   if (TARGET_NEON)
23596     switch (mode)
23597       {
23598       case SFmode:
23599         return TARGET_NEON_VECTORIZE_DOUBLE ? V2SFmode : V4SFmode;
23600       case SImode:
23601         return TARGET_NEON_VECTORIZE_DOUBLE ? V2SImode : V4SImode;
23602       case HImode:
23603         return TARGET_NEON_VECTORIZE_DOUBLE ? V4HImode : V8HImode;
23604       case QImode:
23605         return TARGET_NEON_VECTORIZE_DOUBLE ? V8QImode : V16QImode;
23606       case DImode:
23607         if (!TARGET_NEON_VECTORIZE_DOUBLE)
23608           return V2DImode;
23609         break;
23610
23611       default:;
23612       }
23613
23614   if (TARGET_REALLY_IWMMXT)
23615     switch (mode)
23616       {
23617       case SImode:
23618         return V2SImode;
23619       case HImode:
23620         return V4HImode;
23621       case QImode:
23622         return V8QImode;
23623
23624       default:;
23625       }
23626
23627   return word_mode;
23628 }
23629
23630 /* Implement TARGET_CLASS_LIKELY_SPILLED_P.
23631
23632    We need to define this for LO_REGS on Thumb-1.  Otherwise we can end up
23633    using r0-r4 for function arguments, r7 for the stack frame and don't have
23634    enough left over to do doubleword arithmetic.  For Thumb-2 all the
23635    potentially problematic instructions accept high registers so this is not
23636    necessary.  Care needs to be taken to avoid adding new Thumb-2 patterns
23637    that require many low registers.  */
23638 static bool
23639 arm_class_likely_spilled_p (reg_class_t rclass)
23640 {
23641   if ((TARGET_THUMB1 && rclass == LO_REGS)
23642       || rclass  == CC_REG)
23643     return true;
23644
23645   return false;
23646 }
23647
23648 /* Implements target hook small_register_classes_for_mode_p.  */
23649 bool
23650 arm_small_register_classes_for_mode_p (enum machine_mode mode ATTRIBUTE_UNUSED)
23651 {
23652   return TARGET_THUMB1;
23653 }
23654
23655 /* Implement TARGET_SHIFT_TRUNCATION_MASK.  SImode shifts use normal
23656    ARM insns and therefore guarantee that the shift count is modulo 256.
23657    DImode shifts (those implemented by lib1funcs.S or by optabs.c)
23658    guarantee no particular behavior for out-of-range counts.  */
23659
23660 static unsigned HOST_WIDE_INT
23661 arm_shift_truncation_mask (enum machine_mode mode)
23662 {
23663   return mode == SImode ? 255 : 0;
23664 }
23665
23666
23667 /* Map internal gcc register numbers to DWARF2 register numbers.  */
23668
23669 unsigned int
23670 arm_dbx_register_number (unsigned int regno)
23671 {
23672   if (regno < 16)
23673     return regno;
23674
23675   /* TODO: Legacy targets output FPA regs as registers 16-23 for backwards
23676      compatibility.  The EABI defines them as registers 96-103.  */
23677   if (IS_FPA_REGNUM (regno))
23678     return (TARGET_AAPCS_BASED ? 96 : 16) + regno - FIRST_FPA_REGNUM;
23679
23680   if (IS_VFP_REGNUM (regno))
23681     {
23682       /* See comment in arm_dwarf_register_span.  */
23683       if (VFP_REGNO_OK_FOR_SINGLE (regno))
23684         return 64 + regno - FIRST_VFP_REGNUM;
23685       else
23686         return 256 + (regno - FIRST_VFP_REGNUM) / 2;
23687     }
23688
23689   if (IS_IWMMXT_GR_REGNUM (regno))
23690     return 104 + regno - FIRST_IWMMXT_GR_REGNUM;
23691
23692   if (IS_IWMMXT_REGNUM (regno))
23693     return 112 + regno - FIRST_IWMMXT_REGNUM;
23694
23695   gcc_unreachable ();
23696 }
23697
23698 /* Dwarf models VFPv3 registers as 32 64-bit registers.
23699    GCC models tham as 64 32-bit registers, so we need to describe this to
23700    the DWARF generation code.  Other registers can use the default.  */
23701 static rtx
23702 arm_dwarf_register_span (rtx rtl)
23703 {
23704   unsigned regno;
23705   int nregs;
23706   int i;
23707   rtx p;
23708
23709   regno = REGNO (rtl);
23710   if (!IS_VFP_REGNUM (regno))
23711     return NULL_RTX;
23712
23713   /* XXX FIXME: The EABI defines two VFP register ranges:
23714         64-95: Legacy VFPv2 numbering for S0-S31 (obsolescent)
23715         256-287: D0-D31
23716      The recommended encoding for S0-S31 is a DW_OP_bit_piece of the
23717      corresponding D register.  Until GDB supports this, we shall use the
23718      legacy encodings.  We also use these encodings for D0-D15 for
23719      compatibility with older debuggers.  */
23720   if (VFP_REGNO_OK_FOR_SINGLE (regno))
23721     return NULL_RTX;
23722
23723   nregs = GET_MODE_SIZE (GET_MODE (rtl)) / 8;
23724   p = gen_rtx_PARALLEL (VOIDmode, rtvec_alloc (nregs));
23725   regno = (regno - FIRST_VFP_REGNUM) / 2;
23726   for (i = 0; i < nregs; i++)
23727     XVECEXP (p, 0, i) = gen_rtx_REG (DImode, 256 + regno + i);
23728
23729   return p;
23730 }
23731
23732 #if ARM_UNWIND_INFO
23733 /* Emit unwind directives for a store-multiple instruction or stack pointer
23734    push during alignment.
23735    These should only ever be generated by the function prologue code, so
23736    expect them to have a particular form.  */
23737
23738 static void
23739 arm_unwind_emit_sequence (FILE * asm_out_file, rtx p)
23740 {
23741   int i;
23742   HOST_WIDE_INT offset;
23743   HOST_WIDE_INT nregs;
23744   int reg_size;
23745   unsigned reg;
23746   unsigned lastreg;
23747   rtx e;
23748
23749   e = XVECEXP (p, 0, 0);
23750   if (GET_CODE (e) != SET)
23751     abort ();
23752
23753   /* First insn will adjust the stack pointer.  */
23754   if (GET_CODE (e) != SET
23755       || GET_CODE (XEXP (e, 0)) != REG
23756       || REGNO (XEXP (e, 0)) != SP_REGNUM
23757       || GET_CODE (XEXP (e, 1)) != PLUS)
23758     abort ();
23759
23760   offset = -INTVAL (XEXP (XEXP (e, 1), 1));
23761   nregs = XVECLEN (p, 0) - 1;
23762
23763   reg = REGNO (XEXP (XVECEXP (p, 0, 1), 1));
23764   if (reg < 16)
23765     {
23766       /* The function prologue may also push pc, but not annotate it as it is
23767          never restored.  We turn this into a stack pointer adjustment.  */
23768       if (nregs * 4 == offset - 4)
23769         {
23770           fprintf (asm_out_file, "\t.pad #4\n");
23771           offset -= 4;
23772         }
23773       reg_size = 4;
23774       fprintf (asm_out_file, "\t.save {");
23775     }
23776   else if (IS_VFP_REGNUM (reg))
23777     {
23778       reg_size = 8;
23779       fprintf (asm_out_file, "\t.vsave {");
23780     }
23781   else if (reg >= FIRST_FPA_REGNUM && reg <= LAST_FPA_REGNUM)
23782     {
23783       /* FPA registers are done differently.  */
23784       asm_fprintf (asm_out_file, "\t.save %r, %wd\n", reg, nregs);
23785       return;
23786     }
23787   else
23788     /* Unknown register type.  */
23789     abort ();
23790
23791   /* If the stack increment doesn't match the size of the saved registers,
23792      something has gone horribly wrong.  */
23793   if (offset != nregs * reg_size)
23794     abort ();
23795
23796   offset = 0;
23797   lastreg = 0;
23798   /* The remaining insns will describe the stores.  */
23799   for (i = 1; i <= nregs; i++)
23800     {
23801       /* Expect (set (mem <addr>) (reg)).
23802          Where <addr> is (reg:SP) or (plus (reg:SP) (const_int)).  */
23803       e = XVECEXP (p, 0, i);
23804       if (GET_CODE (e) != SET
23805           || GET_CODE (XEXP (e, 0)) != MEM
23806           || GET_CODE (XEXP (e, 1)) != REG)
23807         abort ();
23808
23809       reg = REGNO (XEXP (e, 1));
23810       if (reg < lastreg)
23811         abort ();
23812
23813       if (i != 1)
23814         fprintf (asm_out_file, ", ");
23815       /* We can't use %r for vfp because we need to use the
23816          double precision register names.  */
23817       if (IS_VFP_REGNUM (reg))
23818         asm_fprintf (asm_out_file, "d%d", (reg - FIRST_VFP_REGNUM) / 2);
23819       else
23820         asm_fprintf (asm_out_file, "%r", reg);
23821
23822 #ifdef ENABLE_CHECKING
23823       /* Check that the addresses are consecutive.  */
23824       e = XEXP (XEXP (e, 0), 0);
23825       if (GET_CODE (e) == PLUS)
23826         {
23827           offset += reg_size;
23828           if (GET_CODE (XEXP (e, 0)) != REG
23829               || REGNO (XEXP (e, 0)) != SP_REGNUM
23830               || GET_CODE (XEXP (e, 1)) != CONST_INT
23831               || offset != INTVAL (XEXP (e, 1)))
23832             abort ();
23833         }
23834       else if (i != 1
23835                || GET_CODE (e) != REG
23836                || REGNO (e) != SP_REGNUM)
23837         abort ();
23838 #endif
23839     }
23840   fprintf (asm_out_file, "}\n");
23841 }
23842
23843 /*  Emit unwind directives for a SET.  */
23844
23845 static void
23846 arm_unwind_emit_set (FILE * asm_out_file, rtx p)
23847 {
23848   rtx e0;
23849   rtx e1;
23850   unsigned reg;
23851
23852   e0 = XEXP (p, 0);
23853   e1 = XEXP (p, 1);
23854   switch (GET_CODE (e0))
23855     {
23856     case MEM:
23857       /* Pushing a single register.  */
23858       if (GET_CODE (XEXP (e0, 0)) != PRE_DEC
23859           || GET_CODE (XEXP (XEXP (e0, 0), 0)) != REG
23860           || REGNO (XEXP (XEXP (e0, 0), 0)) != SP_REGNUM)
23861         abort ();
23862
23863       asm_fprintf (asm_out_file, "\t.save ");
23864       if (IS_VFP_REGNUM (REGNO (e1)))
23865         asm_fprintf(asm_out_file, "{d%d}\n",
23866                     (REGNO (e1) - FIRST_VFP_REGNUM) / 2);
23867       else
23868         asm_fprintf(asm_out_file, "{%r}\n", REGNO (e1));
23869       break;
23870
23871     case REG:
23872       if (REGNO (e0) == SP_REGNUM)
23873         {
23874           /* A stack increment.  */
23875           if (GET_CODE (e1) != PLUS
23876               || GET_CODE (XEXP (e1, 0)) != REG
23877               || REGNO (XEXP (e1, 0)) != SP_REGNUM
23878               || GET_CODE (XEXP (e1, 1)) != CONST_INT)
23879             abort ();
23880
23881           asm_fprintf (asm_out_file, "\t.pad #%wd\n",
23882                        -INTVAL (XEXP (e1, 1)));
23883         }
23884       else if (REGNO (e0) == HARD_FRAME_POINTER_REGNUM)
23885         {
23886           HOST_WIDE_INT offset;
23887
23888           if (GET_CODE (e1) == PLUS)
23889             {
23890               if (GET_CODE (XEXP (e1, 0)) != REG
23891                   || GET_CODE (XEXP (e1, 1)) != CONST_INT)
23892                 abort ();
23893               reg = REGNO (XEXP (e1, 0));
23894               offset = INTVAL (XEXP (e1, 1));
23895               asm_fprintf (asm_out_file, "\t.setfp %r, %r, #%wd\n",
23896                            HARD_FRAME_POINTER_REGNUM, reg,
23897                            offset);
23898             }
23899           else if (GET_CODE (e1) == REG)
23900             {
23901               reg = REGNO (e1);
23902               asm_fprintf (asm_out_file, "\t.setfp %r, %r\n",
23903                            HARD_FRAME_POINTER_REGNUM, reg);
23904             }
23905           else
23906             abort ();
23907         }
23908       else if (GET_CODE (e1) == REG && REGNO (e1) == SP_REGNUM)
23909         {
23910           /* Move from sp to reg.  */
23911           asm_fprintf (asm_out_file, "\t.movsp %r\n", REGNO (e0));
23912         }
23913      else if (GET_CODE (e1) == PLUS
23914               && GET_CODE (XEXP (e1, 0)) == REG
23915               && REGNO (XEXP (e1, 0)) == SP_REGNUM
23916               && GET_CODE (XEXP (e1, 1)) == CONST_INT)
23917         {
23918           /* Set reg to offset from sp.  */
23919           asm_fprintf (asm_out_file, "\t.movsp %r, #%d\n",
23920                        REGNO (e0), (int)INTVAL(XEXP (e1, 1)));
23921         }
23922       else
23923         abort ();
23924       break;
23925
23926     default:
23927       abort ();
23928     }
23929 }
23930
23931
23932 /* Emit unwind directives for the given insn.  */
23933
23934 static void
23935 arm_unwind_emit (FILE * asm_out_file, rtx insn)
23936 {
23937   rtx note, pat;
23938   bool handled_one = false;
23939
23940   if (arm_except_unwind_info (&global_options) != UI_TARGET)
23941     return;
23942
23943   if (!(flag_unwind_tables || crtl->uses_eh_lsda)
23944       && (TREE_NOTHROW (current_function_decl)
23945           || crtl->all_throwers_are_sibcalls))
23946     return;
23947
23948   if (NOTE_P (insn) || !RTX_FRAME_RELATED_P (insn))
23949     return;
23950
23951   for (note = REG_NOTES (insn); note ; note = XEXP (note, 1))
23952     {
23953       pat = XEXP (note, 0);
23954       switch (REG_NOTE_KIND (note))
23955         {
23956         case REG_FRAME_RELATED_EXPR:
23957           goto found;
23958
23959         case REG_CFA_REGISTER:
23960           if (pat == NULL)
23961             {
23962               pat = PATTERN (insn);
23963               if (GET_CODE (pat) == PARALLEL)
23964                 pat = XVECEXP (pat, 0, 0);
23965             }
23966
23967           /* Only emitted for IS_STACKALIGN re-alignment.  */
23968           {
23969             rtx dest, src;
23970             unsigned reg;
23971
23972             src = SET_SRC (pat);
23973             dest = SET_DEST (pat);
23974
23975             gcc_assert (src == stack_pointer_rtx);
23976             reg = REGNO (dest);
23977             asm_fprintf (asm_out_file, "\t.unwind_raw 0, 0x%x @ vsp = r%d\n",
23978                          reg + 0x90, reg);
23979           }
23980           handled_one = true;
23981           break;
23982
23983         case REG_CFA_DEF_CFA:
23984         case REG_CFA_EXPRESSION:
23985         case REG_CFA_ADJUST_CFA:
23986         case REG_CFA_OFFSET:
23987           /* ??? Only handling here what we actually emit.  */
23988           gcc_unreachable ();
23989
23990         default:
23991           break;
23992         }
23993     }
23994   if (handled_one)
23995     return;
23996   pat = PATTERN (insn);
23997  found:
23998
23999   switch (GET_CODE (pat))
24000     {
24001     case SET:
24002       arm_unwind_emit_set (asm_out_file, pat);
24003       break;
24004
24005     case SEQUENCE:
24006       /* Store multiple.  */
24007       arm_unwind_emit_sequence (asm_out_file, pat);
24008       break;
24009
24010     default:
24011       abort();
24012     }
24013 }
24014
24015
24016 /* Output a reference from a function exception table to the type_info
24017    object X.  The EABI specifies that the symbol should be relocated by
24018    an R_ARM_TARGET2 relocation.  */
24019
24020 static bool
24021 arm_output_ttype (rtx x)
24022 {
24023   fputs ("\t.word\t", asm_out_file);
24024   output_addr_const (asm_out_file, x);
24025   /* Use special relocations for symbol references.  */
24026   if (GET_CODE (x) != CONST_INT)
24027     fputs ("(TARGET2)", asm_out_file);
24028   fputc ('\n', asm_out_file);
24029
24030   return TRUE;
24031 }
24032
24033 /* Implement TARGET_ASM_EMIT_EXCEPT_PERSONALITY.  */
24034
24035 static void
24036 arm_asm_emit_except_personality (rtx personality)
24037 {
24038   fputs ("\t.personality\t", asm_out_file);
24039   output_addr_const (asm_out_file, personality);
24040   fputc ('\n', asm_out_file);
24041 }
24042
24043 /* Implement TARGET_ASM_INITIALIZE_SECTIONS.  */
24044
24045 static void
24046 arm_asm_init_sections (void)
24047 {
24048   exception_section = get_unnamed_section (0, output_section_asm_op,
24049                                            "\t.handlerdata");
24050 }
24051 #endif /* ARM_UNWIND_INFO */
24052
24053 /* Output unwind directives for the start/end of a function.  */
24054
24055 void
24056 arm_output_fn_unwind (FILE * f, bool prologue)
24057 {
24058   if (arm_except_unwind_info (&global_options) != UI_TARGET)
24059     return;
24060
24061   if (prologue)
24062     fputs ("\t.fnstart\n", f);
24063   else
24064     {
24065       /* If this function will never be unwound, then mark it as such.
24066          The came condition is used in arm_unwind_emit to suppress
24067          the frame annotations.  */
24068       if (!(flag_unwind_tables || crtl->uses_eh_lsda)
24069           && (TREE_NOTHROW (current_function_decl)
24070               || crtl->all_throwers_are_sibcalls))
24071         fputs("\t.cantunwind\n", f);
24072
24073       fputs ("\t.fnend\n", f);
24074     }
24075 }
24076
24077 static bool
24078 arm_emit_tls_decoration (FILE *fp, rtx x)
24079 {
24080   enum tls_reloc reloc;
24081   rtx val;
24082
24083   val = XVECEXP (x, 0, 0);
24084   reloc = (enum tls_reloc) INTVAL (XVECEXP (x, 0, 1));
24085
24086   output_addr_const (fp, val);
24087
24088   switch (reloc)
24089     {
24090     case TLS_GD32:
24091       fputs ("(tlsgd)", fp);
24092       break;
24093     case TLS_LDM32:
24094       fputs ("(tlsldm)", fp);
24095       break;
24096     case TLS_LDO32:
24097       fputs ("(tlsldo)", fp);
24098       break;
24099     case TLS_IE32:
24100       fputs ("(gottpoff)", fp);
24101       break;
24102     case TLS_LE32:
24103       fputs ("(tpoff)", fp);
24104       break;
24105     case TLS_DESCSEQ:
24106       fputs ("(tlsdesc)", fp);
24107       break;
24108     default:
24109       gcc_unreachable ();
24110     }
24111
24112   switch (reloc)
24113     {
24114     case TLS_GD32:
24115     case TLS_LDM32:
24116     case TLS_IE32:
24117     case TLS_DESCSEQ:
24118       fputs (" + (. - ", fp);
24119       output_addr_const (fp, XVECEXP (x, 0, 2));
24120       /* For DESCSEQ the 3rd operand encodes thumbness, and is added */
24121       fputs (reloc == TLS_DESCSEQ ? " + " : " - ", fp);
24122       output_addr_const (fp, XVECEXP (x, 0, 3));
24123       fputc (')', fp);
24124       break;
24125     default:
24126       break;
24127     }
24128
24129   return TRUE;
24130 }
24131
24132 /* ARM implementation of TARGET_ASM_OUTPUT_DWARF_DTPREL.  */
24133
24134 static void
24135 arm_output_dwarf_dtprel (FILE *file, int size, rtx x)
24136 {
24137   gcc_assert (size == 4);
24138   fputs ("\t.word\t", file);
24139   output_addr_const (file, x);
24140   fputs ("(tlsldo)", file);
24141 }
24142
24143 /* Implement TARGET_ASM_OUTPUT_ADDR_CONST_EXTRA.  */
24144
24145 static bool
24146 arm_output_addr_const_extra (FILE *fp, rtx x)
24147 {
24148   if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_TLS)
24149     return arm_emit_tls_decoration (fp, x);
24150   else if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_PIC_LABEL)
24151     {
24152       char label[256];
24153       int labelno = INTVAL (XVECEXP (x, 0, 0));
24154
24155       ASM_GENERATE_INTERNAL_LABEL (label, "LPIC", labelno);
24156       assemble_name_raw (fp, label);
24157
24158       return TRUE;
24159     }
24160   else if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_GOTSYM_OFF)
24161     {
24162       assemble_name (fp, "_GLOBAL_OFFSET_TABLE_");
24163       if (GOT_PCREL)
24164         fputs ("+.", fp);
24165       fputs ("-(", fp);
24166       output_addr_const (fp, XVECEXP (x, 0, 0));
24167       fputc (')', fp);
24168       return TRUE;
24169     }
24170   else if (GET_CODE (x) == UNSPEC && XINT (x, 1) == UNSPEC_SYMBOL_OFFSET)
24171     {
24172       output_addr_const (fp, XVECEXP (x, 0, 0));
24173       if (GOT_PCREL)
24174         fputs ("+.", fp);
24175       fputs ("-(", fp);
24176       output_addr_const (fp, XVECEXP (x, 0, 1));
24177       fputc (')', fp);
24178       return TRUE;
24179     }
24180   else if (GET_CODE (x) == CONST_VECTOR)
24181     return arm_emit_vector_const (fp, x);
24182
24183   return FALSE;
24184 }
24185
24186 /* Output assembly for a shift instruction.
24187    SET_FLAGS determines how the instruction modifies the condition codes.
24188    0 - Do not set condition codes.
24189    1 - Set condition codes.
24190    2 - Use smallest instruction.  */
24191 const char *
24192 arm_output_shift(rtx * operands, int set_flags)
24193 {
24194   char pattern[100];
24195   static const char flag_chars[3] = {'?', '.', '!'};
24196   const char *shift;
24197   HOST_WIDE_INT val;
24198   char c;
24199
24200   c = flag_chars[set_flags];
24201   if (TARGET_UNIFIED_ASM)
24202     {
24203       shift = shift_op(operands[3], &val);
24204       if (shift)
24205         {
24206           if (val != -1)
24207             operands[2] = GEN_INT(val);
24208           sprintf (pattern, "%s%%%c\t%%0, %%1, %%2", shift, c);
24209         }
24210       else
24211         sprintf (pattern, "mov%%%c\t%%0, %%1", c);
24212     }
24213   else
24214     sprintf (pattern, "mov%%%c\t%%0, %%1%%S3", c);
24215   output_asm_insn (pattern, operands);
24216   return "";
24217 }
24218
24219 /* Output a Thumb-1 casesi dispatch sequence.  */
24220 const char *
24221 thumb1_output_casesi (rtx *operands)
24222 {
24223   rtx diff_vec = PATTERN (next_real_insn (operands[0]));
24224
24225   gcc_assert (GET_CODE (diff_vec) == ADDR_DIFF_VEC);
24226
24227   switch (GET_MODE(diff_vec))
24228     {
24229     case QImode:
24230       return (ADDR_DIFF_VEC_FLAGS (diff_vec).offset_unsigned ?
24231               "bl\t%___gnu_thumb1_case_uqi" : "bl\t%___gnu_thumb1_case_sqi");
24232     case HImode:
24233       return (ADDR_DIFF_VEC_FLAGS (diff_vec).offset_unsigned ?
24234               "bl\t%___gnu_thumb1_case_uhi" : "bl\t%___gnu_thumb1_case_shi");
24235     case SImode:
24236       return "bl\t%___gnu_thumb1_case_si";
24237     default:
24238       gcc_unreachable ();
24239     }
24240 }
24241
24242 /* Output a Thumb-2 casesi instruction.  */
24243 const char *
24244 thumb2_output_casesi (rtx *operands)
24245 {
24246   rtx diff_vec = PATTERN (next_real_insn (operands[2]));
24247
24248   gcc_assert (GET_CODE (diff_vec) == ADDR_DIFF_VEC);
24249
24250   output_asm_insn ("cmp\t%0, %1", operands);
24251   output_asm_insn ("bhi\t%l3", operands);
24252   switch (GET_MODE(diff_vec))
24253     {
24254     case QImode:
24255       return "tbb\t[%|pc, %0]";
24256     case HImode:
24257       return "tbh\t[%|pc, %0, lsl #1]";
24258     case SImode:
24259       if (flag_pic)
24260         {
24261           output_asm_insn ("adr\t%4, %l2", operands);
24262           output_asm_insn ("ldr\t%5, [%4, %0, lsl #2]", operands);
24263           output_asm_insn ("add\t%4, %4, %5", operands);
24264           return "bx\t%4";
24265         }
24266       else
24267         {
24268           output_asm_insn ("adr\t%4, %l2", operands);
24269           return "ldr\t%|pc, [%4, %0, lsl #2]";
24270         }
24271     default:
24272       gcc_unreachable ();
24273     }
24274 }
24275
24276 /* Most ARM cores are single issue, but some newer ones can dual issue.
24277    The scheduler descriptions rely on this being correct.  */
24278 static int
24279 arm_issue_rate (void)
24280 {
24281   switch (arm_tune)
24282     {
24283     case cortexa15:
24284       return 3;
24285
24286     case cortexr4:
24287     case cortexr4f:
24288     case cortexr5:
24289     case genericv7a:
24290     case cortexa5:
24291     case cortexa8:
24292     case cortexa9:
24293     case fa726te:
24294       return 2;
24295
24296     default:
24297       return 1;
24298     }
24299 }
24300
24301 /* A table and a function to perform ARM-specific name mangling for
24302    NEON vector types in order to conform to the AAPCS (see "Procedure
24303    Call Standard for the ARM Architecture", Appendix A).  To qualify
24304    for emission with the mangled names defined in that document, a
24305    vector type must not only be of the correct mode but also be
24306    composed of NEON vector element types (e.g. __builtin_neon_qi).  */
24307 typedef struct
24308 {
24309   enum machine_mode mode;
24310   const char *element_type_name;
24311   const char *aapcs_name;
24312 } arm_mangle_map_entry;
24313
24314 static arm_mangle_map_entry arm_mangle_map[] = {
24315   /* 64-bit containerized types.  */
24316   { V8QImode,  "__builtin_neon_qi",     "15__simd64_int8_t" },
24317   { V8QImode,  "__builtin_neon_uqi",    "16__simd64_uint8_t" },
24318   { V4HImode,  "__builtin_neon_hi",     "16__simd64_int16_t" },
24319   { V4HImode,  "__builtin_neon_uhi",    "17__simd64_uint16_t" },
24320   { V2SImode,  "__builtin_neon_si",     "16__simd64_int32_t" },
24321   { V2SImode,  "__builtin_neon_usi",    "17__simd64_uint32_t" },
24322   { V2SFmode,  "__builtin_neon_sf",     "18__simd64_float32_t" },
24323   { V8QImode,  "__builtin_neon_poly8",  "16__simd64_poly8_t" },
24324   { V4HImode,  "__builtin_neon_poly16", "17__simd64_poly16_t" },
24325   /* 128-bit containerized types.  */
24326   { V16QImode, "__builtin_neon_qi",     "16__simd128_int8_t" },
24327   { V16QImode, "__builtin_neon_uqi",    "17__simd128_uint8_t" },
24328   { V8HImode,  "__builtin_neon_hi",     "17__simd128_int16_t" },
24329   { V8HImode,  "__builtin_neon_uhi",    "18__simd128_uint16_t" },
24330   { V4SImode,  "__builtin_neon_si",     "17__simd128_int32_t" },
24331   { V4SImode,  "__builtin_neon_usi",    "18__simd128_uint32_t" },
24332   { V4SFmode,  "__builtin_neon_sf",     "19__simd128_float32_t" },
24333   { V16QImode, "__builtin_neon_poly8",  "17__simd128_poly8_t" },
24334   { V8HImode,  "__builtin_neon_poly16", "18__simd128_poly16_t" },
24335   { VOIDmode, NULL, NULL }
24336 };
24337
24338 const char *
24339 arm_mangle_type (const_tree type)
24340 {
24341   arm_mangle_map_entry *pos = arm_mangle_map;
24342
24343   /* The ARM ABI documents (10th October 2008) say that "__va_list"
24344      has to be managled as if it is in the "std" namespace.  */
24345   if (TARGET_AAPCS_BASED
24346       && lang_hooks.types_compatible_p (CONST_CAST_TREE (type), va_list_type))
24347     {
24348       static bool warned;
24349       if (!warned && warn_psabi && !in_system_header)
24350         {
24351           warned = true;
24352           inform (input_location,
24353                   "the mangling of %<va_list%> has changed in GCC 4.4");
24354         }
24355       return "St9__va_list";
24356     }
24357
24358   /* Half-precision float.  */
24359   if (TREE_CODE (type) == REAL_TYPE && TYPE_PRECISION (type) == 16)
24360     return "Dh";
24361
24362   if (TREE_CODE (type) != VECTOR_TYPE)
24363     return NULL;
24364
24365   /* Check the mode of the vector type, and the name of the vector
24366      element type, against the table.  */
24367   while (pos->mode != VOIDmode)
24368     {
24369       tree elt_type = TREE_TYPE (type);
24370
24371       if (pos->mode == TYPE_MODE (type)
24372           && TREE_CODE (TYPE_NAME (elt_type)) == TYPE_DECL
24373           && !strcmp (IDENTIFIER_POINTER (DECL_NAME (TYPE_NAME (elt_type))),
24374                       pos->element_type_name))
24375         return pos->aapcs_name;
24376
24377       pos++;
24378     }
24379
24380   /* Use the default mangling for unrecognized (possibly user-defined)
24381      vector types.  */
24382   return NULL;
24383 }
24384
24385 /* Order of allocation of core registers for Thumb: this allocation is
24386    written over the corresponding initial entries of the array
24387    initialized with REG_ALLOC_ORDER.  We allocate all low registers
24388    first.  Saving and restoring a low register is usually cheaper than
24389    using a call-clobbered high register.  */
24390
24391 static const int thumb_core_reg_alloc_order[] =
24392 {
24393    3,  2,  1,  0,  4,  5,  6,  7,
24394   14, 12,  8,  9, 10, 11, 13, 15
24395 };
24396
24397 /* Adjust register allocation order when compiling for Thumb.  */
24398
24399 void
24400 arm_order_regs_for_local_alloc (void)
24401 {
24402   const int arm_reg_alloc_order[] = REG_ALLOC_ORDER;
24403   memcpy(reg_alloc_order, arm_reg_alloc_order, sizeof (reg_alloc_order));
24404   if (TARGET_THUMB)
24405     memcpy (reg_alloc_order, thumb_core_reg_alloc_order,
24406             sizeof (thumb_core_reg_alloc_order));
24407 }
24408
24409 /* Implement TARGET_FRAME_POINTER_REQUIRED.  */
24410
24411 bool
24412 arm_frame_pointer_required (void)
24413 {
24414   return (cfun->has_nonlocal_label
24415           || SUBTARGET_FRAME_POINTER_REQUIRED
24416           || (TARGET_ARM && TARGET_APCS_FRAME && ! leaf_function_p ()));
24417 }
24418
24419 /* Only thumb1 can't support conditional execution, so return true if
24420    the target is not thumb1.  */
24421 static bool
24422 arm_have_conditional_execution (void)
24423 {
24424   return !TARGET_THUMB1;
24425 }
24426
24427 static unsigned int
24428 arm_autovectorize_vector_sizes (void)
24429 {
24430   return TARGET_NEON_VECTORIZE_DOUBLE ? 0 : (16 | 8);
24431 }
24432
24433 static bool
24434 arm_vector_alignment_reachable (const_tree type, bool is_packed)
24435 {
24436   /* Vectors which aren't in packed structures will not be less aligned than
24437      the natural alignment of their element type, so this is safe.  */
24438   if (TARGET_NEON && !BYTES_BIG_ENDIAN)
24439     return !is_packed;
24440
24441   return default_builtin_vector_alignment_reachable (type, is_packed);
24442 }
24443
24444 static bool
24445 arm_builtin_support_vector_misalignment (enum machine_mode mode,
24446                                          const_tree type, int misalignment,
24447                                          bool is_packed)
24448 {
24449   if (TARGET_NEON && !BYTES_BIG_ENDIAN)
24450     {
24451       HOST_WIDE_INT align = TYPE_ALIGN_UNIT (type);
24452
24453       if (is_packed)
24454         return align == 1;
24455
24456       /* If the misalignment is unknown, we should be able to handle the access
24457          so long as it is not to a member of a packed data structure.  */
24458       if (misalignment == -1)
24459         return true;
24460
24461       /* Return true if the misalignment is a multiple of the natural alignment
24462          of the vector's element type.  This is probably always going to be
24463          true in practice, since we've already established that this isn't a
24464          packed access.  */
24465       return ((misalignment % align) == 0);
24466     }
24467
24468   return default_builtin_support_vector_misalignment (mode, type, misalignment,
24469                                                       is_packed);
24470 }
24471
24472 static void
24473 arm_conditional_register_usage (void)
24474 {
24475   int regno;
24476
24477   if (TARGET_SOFT_FLOAT || TARGET_THUMB1 || !TARGET_FPA)
24478     {
24479       for (regno = FIRST_FPA_REGNUM;
24480            regno <= LAST_FPA_REGNUM; ++regno)
24481         fixed_regs[regno] = call_used_regs[regno] = 1;
24482     }
24483
24484   if (TARGET_THUMB1 && optimize_size)
24485     {
24486       /* When optimizing for size on Thumb-1, it's better not
24487         to use the HI regs, because of the overhead of
24488         stacking them.  */
24489       for (regno = FIRST_HI_REGNUM;
24490            regno <= LAST_HI_REGNUM; ++regno)
24491         fixed_regs[regno] = call_used_regs[regno] = 1;
24492     }
24493
24494   /* The link register can be clobbered by any branch insn,
24495      but we have no way to track that at present, so mark
24496      it as unavailable.  */
24497   if (TARGET_THUMB1)
24498     fixed_regs[LR_REGNUM] = call_used_regs[LR_REGNUM] = 1;
24499
24500   if (TARGET_32BIT && TARGET_HARD_FLOAT)
24501     {
24502       if (TARGET_MAVERICK)
24503         {
24504           for (regno = FIRST_FPA_REGNUM;
24505                regno <= LAST_FPA_REGNUM; ++ regno)
24506             fixed_regs[regno] = call_used_regs[regno] = 1;
24507           for (regno = FIRST_CIRRUS_FP_REGNUM;
24508                regno <= LAST_CIRRUS_FP_REGNUM; ++ regno)
24509             {
24510               fixed_regs[regno] = 0;
24511               call_used_regs[regno] = regno < FIRST_CIRRUS_FP_REGNUM + 4;
24512             }
24513         }
24514       if (TARGET_VFP)
24515         {
24516           /* VFPv3 registers are disabled when earlier VFP
24517              versions are selected due to the definition of
24518              LAST_VFP_REGNUM.  */
24519           for (regno = FIRST_VFP_REGNUM;
24520                regno <= LAST_VFP_REGNUM; ++ regno)
24521             {
24522               fixed_regs[regno] = 0;
24523               call_used_regs[regno] = regno < FIRST_VFP_REGNUM + 16
24524                 || regno >= FIRST_VFP_REGNUM + 32;
24525             }
24526         }
24527     }
24528
24529   if (TARGET_REALLY_IWMMXT)
24530     {
24531       regno = FIRST_IWMMXT_GR_REGNUM;
24532       /* The 2002/10/09 revision of the XScale ABI has wCG0
24533          and wCG1 as call-preserved registers.  The 2002/11/21
24534          revision changed this so that all wCG registers are
24535          scratch registers.  */
24536       for (regno = FIRST_IWMMXT_GR_REGNUM;
24537            regno <= LAST_IWMMXT_GR_REGNUM; ++ regno)
24538         fixed_regs[regno] = 0;
24539       /* The XScale ABI has wR0 - wR9 as scratch registers,
24540          the rest as call-preserved registers.  */
24541       for (regno = FIRST_IWMMXT_REGNUM;
24542            regno <= LAST_IWMMXT_REGNUM; ++ regno)
24543         {
24544           fixed_regs[regno] = 0;
24545           call_used_regs[regno] = regno < FIRST_IWMMXT_REGNUM + 10;
24546         }
24547     }
24548
24549   if ((unsigned) PIC_OFFSET_TABLE_REGNUM != INVALID_REGNUM)
24550     {
24551       fixed_regs[PIC_OFFSET_TABLE_REGNUM] = 1;
24552       call_used_regs[PIC_OFFSET_TABLE_REGNUM] = 1;
24553     }
24554   else if (TARGET_APCS_STACK)
24555     {
24556       fixed_regs[10]     = 1;
24557       call_used_regs[10] = 1;
24558     }
24559   /* -mcaller-super-interworking reserves r11 for calls to
24560      _interwork_r11_call_via_rN().  Making the register global
24561      is an easy way of ensuring that it remains valid for all
24562      calls.  */
24563   if (TARGET_APCS_FRAME || TARGET_CALLER_INTERWORKING
24564       || TARGET_TPCS_FRAME || TARGET_TPCS_LEAF_FRAME)
24565     {
24566       fixed_regs[ARM_HARD_FRAME_POINTER_REGNUM] = 1;
24567       call_used_regs[ARM_HARD_FRAME_POINTER_REGNUM] = 1;
24568       if (TARGET_CALLER_INTERWORKING)
24569         global_regs[ARM_HARD_FRAME_POINTER_REGNUM] = 1;
24570     }
24571   SUBTARGET_CONDITIONAL_REGISTER_USAGE
24572 }
24573
24574 static reg_class_t
24575 arm_preferred_rename_class (reg_class_t rclass)
24576 {
24577   /* Thumb-2 instructions using LO_REGS may be smaller than instructions
24578      using GENERIC_REGS.  During register rename pass, we prefer LO_REGS,
24579      and code size can be reduced.  */
24580   if (TARGET_THUMB2 && rclass == GENERAL_REGS)
24581     return LO_REGS;
24582   else
24583     return NO_REGS;
24584 }
24585
24586 /* Compute the atrribute "length" of insn "*push_multi".
24587    So this function MUST be kept in sync with that insn pattern.  */
24588 int
24589 arm_attr_length_push_multi(rtx parallel_op, rtx first_op)
24590 {
24591   int i, regno, hi_reg;
24592   int num_saves = XVECLEN (parallel_op, 0);
24593
24594   /* ARM mode.  */
24595   if (TARGET_ARM)
24596     return 4;
24597   /* Thumb1 mode.  */
24598   if (TARGET_THUMB1)
24599     return 2;
24600
24601   /* Thumb2 mode.  */
24602   regno = REGNO (first_op);
24603   hi_reg = (REGNO_REG_CLASS (regno) == HI_REGS) && (regno != LR_REGNUM);
24604   for (i = 1; i < num_saves && !hi_reg; i++)
24605     {
24606       regno = REGNO (XEXP (XVECEXP (parallel_op, 0, i), 0));
24607       hi_reg |= (REGNO_REG_CLASS (regno) == HI_REGS) && (regno != LR_REGNUM);
24608     }
24609
24610   if (!hi_reg)
24611     return 2;
24612   return 4;
24613 }
24614
24615 /* Compute the number of instructions emitted by output_move_double.  */
24616 int
24617 arm_count_output_move_double_insns (rtx *operands)
24618 {
24619   int count;
24620   output_move_double (operands, false, &count);
24621   return count;
24622 }
24623
24624 int
24625 vfp3_const_double_for_fract_bits (rtx operand)
24626 {
24627   REAL_VALUE_TYPE r0;
24628   
24629   if (GET_CODE (operand) != CONST_DOUBLE)
24630     return 0;
24631   
24632   REAL_VALUE_FROM_CONST_DOUBLE (r0, operand);
24633   if (exact_real_inverse (DFmode, &r0))
24634     {
24635       if (exact_real_truncate (DFmode, &r0))
24636         {
24637           HOST_WIDE_INT value = real_to_integer (&r0);
24638           value = value & 0xffffffff;
24639           if ((value != 0) && ( (value & (value - 1)) == 0))
24640             return int_log2 (value);
24641         }
24642     }
24643   return 0;
24644 }
24645
24646 /* Emit a memory barrier around an atomic sequence according to MODEL.  */
24647
24648 static void
24649 arm_pre_atomic_barrier (enum memmodel model)
24650 {
24651   switch (model)
24652     {
24653     case MEMMODEL_RELAXED:
24654     case MEMMODEL_CONSUME:
24655     case MEMMODEL_ACQUIRE:
24656       break;
24657     case MEMMODEL_RELEASE:
24658     case MEMMODEL_ACQ_REL:
24659     case MEMMODEL_SEQ_CST:
24660       emit_insn (gen_memory_barrier ());
24661       break;
24662     default:
24663       gcc_unreachable ();
24664     }
24665 }
24666
24667 static void
24668 arm_post_atomic_barrier (enum memmodel model)
24669 {
24670   switch (model)
24671     {
24672     case MEMMODEL_RELAXED:
24673     case MEMMODEL_CONSUME:
24674     case MEMMODEL_RELEASE:
24675       break;
24676     case MEMMODEL_ACQUIRE:
24677     case MEMMODEL_ACQ_REL:
24678     case MEMMODEL_SEQ_CST:
24679       emit_insn (gen_memory_barrier ());
24680       break;
24681     default:
24682       gcc_unreachable ();
24683     }
24684 }
24685
24686 /* Emit the load-exclusive and store-exclusive instructions.  */
24687
24688 static void
24689 arm_emit_load_exclusive (enum machine_mode mode, rtx rval, rtx mem)
24690 {
24691   rtx (*gen) (rtx, rtx);
24692
24693   switch (mode)
24694     {
24695     case QImode: gen = gen_arm_load_exclusiveqi; break;
24696     case HImode: gen = gen_arm_load_exclusivehi; break;
24697     case SImode: gen = gen_arm_load_exclusivesi; break;
24698     case DImode: gen = gen_arm_load_exclusivedi; break;
24699     default:
24700       gcc_unreachable ();
24701     }
24702
24703   emit_insn (gen (rval, mem));
24704 }
24705
24706 static void
24707 arm_emit_store_exclusive (enum machine_mode mode, rtx bval, rtx rval, rtx mem)
24708 {
24709   rtx (*gen) (rtx, rtx, rtx);
24710
24711   switch (mode)
24712     {
24713     case QImode: gen = gen_arm_store_exclusiveqi; break;
24714     case HImode: gen = gen_arm_store_exclusivehi; break;
24715     case SImode: gen = gen_arm_store_exclusivesi; break;
24716     case DImode: gen = gen_arm_store_exclusivedi; break;
24717     default:
24718       gcc_unreachable ();
24719     }
24720
24721   emit_insn (gen (bval, rval, mem));
24722 }
24723
24724 /* Mark the previous jump instruction as unlikely.  */
24725
24726 static void
24727 emit_unlikely_jump (rtx insn)
24728 {
24729   rtx very_unlikely = GEN_INT (REG_BR_PROB_BASE / 100 - 1);
24730
24731   insn = emit_jump_insn (insn);
24732   add_reg_note (insn, REG_BR_PROB, very_unlikely);
24733 }
24734
24735 /* Expand a compare and swap pattern.  */
24736
24737 void
24738 arm_expand_compare_and_swap (rtx operands[])
24739 {
24740   rtx bval, rval, mem, oldval, newval, is_weak, mod_s, mod_f, x;
24741   enum machine_mode mode;
24742   rtx (*gen) (rtx, rtx, rtx, rtx, rtx, rtx, rtx);
24743
24744   bval = operands[0];
24745   rval = operands[1];
24746   mem = operands[2];
24747   oldval = operands[3];
24748   newval = operands[4];
24749   is_weak = operands[5];
24750   mod_s = operands[6];
24751   mod_f = operands[7];
24752   mode = GET_MODE (mem);
24753
24754   switch (mode)
24755     {
24756     case QImode:
24757     case HImode:
24758       /* For narrow modes, we're going to perform the comparison in SImode,
24759          so do the zero-extension now.  */
24760       rval = gen_reg_rtx (SImode);
24761       oldval = convert_modes (SImode, mode, oldval, true);
24762       /* FALLTHRU */
24763
24764     case SImode:
24765       /* Force the value into a register if needed.  We waited until after
24766          the zero-extension above to do this properly.  */
24767       if (!arm_add_operand (oldval, mode))
24768         oldval = force_reg (mode, oldval);
24769       break;
24770
24771     case DImode:
24772       if (!cmpdi_operand (oldval, mode))
24773         oldval = force_reg (mode, oldval);
24774       break;
24775
24776     default:
24777       gcc_unreachable ();
24778     }
24779
24780   switch (mode)
24781     {
24782     case QImode: gen = gen_atomic_compare_and_swapqi_1; break;
24783     case HImode: gen = gen_atomic_compare_and_swaphi_1; break;
24784     case SImode: gen = gen_atomic_compare_and_swapsi_1; break;
24785     case DImode: gen = gen_atomic_compare_and_swapdi_1; break;
24786     default:
24787       gcc_unreachable ();
24788     }
24789
24790   emit_insn (gen (rval, mem, oldval, newval, is_weak, mod_s, mod_f));
24791
24792   if (mode == QImode || mode == HImode)
24793     emit_move_insn (operands[1], gen_lowpart (mode, rval));
24794
24795   /* In all cases, we arrange for success to be signaled by Z set.
24796      This arrangement allows for the boolean result to be used directly
24797      in a subsequent branch, post optimization.  */
24798   x = gen_rtx_REG (CCmode, CC_REGNUM);
24799   x = gen_rtx_EQ (SImode, x, const0_rtx);
24800   emit_insn (gen_rtx_SET (VOIDmode, bval, x));
24801 }
24802
24803 /* Split a compare and swap pattern.  It is IMPLEMENTATION DEFINED whether
24804    another memory store between the load-exclusive and store-exclusive can
24805    reset the monitor from Exclusive to Open state.  This means we must wait
24806    until after reload to split the pattern, lest we get a register spill in
24807    the middle of the atomic sequence.  */
24808
24809 void
24810 arm_split_compare_and_swap (rtx operands[])
24811 {
24812   rtx rval, mem, oldval, newval, scratch;
24813   enum machine_mode mode;
24814   enum memmodel mod_s, mod_f;
24815   bool is_weak;
24816   rtx label1, label2, x, cond;
24817
24818   rval = operands[0];
24819   mem = operands[1];
24820   oldval = operands[2];
24821   newval = operands[3];
24822   is_weak = (operands[4] != const0_rtx);
24823   mod_s = (enum memmodel) INTVAL (operands[5]);
24824   mod_f = (enum memmodel) INTVAL (operands[6]);
24825   scratch = operands[7];
24826   mode = GET_MODE (mem);
24827
24828   arm_pre_atomic_barrier (mod_s);
24829
24830   label1 = NULL_RTX;
24831   if (!is_weak)
24832     {
24833       label1 = gen_label_rtx ();
24834       emit_label (label1);
24835     }
24836   label2 = gen_label_rtx ();
24837
24838   arm_emit_load_exclusive (mode, rval, mem);
24839
24840   cond = arm_gen_compare_reg (NE, rval, oldval, scratch);
24841   x = gen_rtx_NE (VOIDmode, cond, const0_rtx);
24842   x = gen_rtx_IF_THEN_ELSE (VOIDmode, x,
24843                             gen_rtx_LABEL_REF (Pmode, label2), pc_rtx);
24844   emit_unlikely_jump (gen_rtx_SET (VOIDmode, pc_rtx, x));
24845
24846   arm_emit_store_exclusive (mode, scratch, mem, newval);
24847
24848   /* Weak or strong, we want EQ to be true for success, so that we
24849      match the flags that we got from the compare above.  */
24850   cond = gen_rtx_REG (CCmode, CC_REGNUM);
24851   x = gen_rtx_COMPARE (CCmode, scratch, const0_rtx);
24852   emit_insn (gen_rtx_SET (VOIDmode, cond, x));
24853
24854   if (!is_weak)
24855     {
24856       x = gen_rtx_NE (VOIDmode, cond, const0_rtx);
24857       x = gen_rtx_IF_THEN_ELSE (VOIDmode, x,
24858                                 gen_rtx_LABEL_REF (Pmode, label1), pc_rtx);
24859       emit_unlikely_jump (gen_rtx_SET (VOIDmode, pc_rtx, x));
24860     }
24861
24862   if (mod_f != MEMMODEL_RELAXED)
24863     emit_label (label2);
24864
24865   arm_post_atomic_barrier (mod_s);
24866
24867   if (mod_f == MEMMODEL_RELAXED)
24868     emit_label (label2);
24869 }
24870
24871 void
24872 arm_split_atomic_op (enum rtx_code code, rtx old_out, rtx new_out, rtx mem,
24873                      rtx value, rtx model_rtx, rtx cond)
24874 {
24875   enum memmodel model = (enum memmodel) INTVAL (model_rtx);
24876   enum machine_mode mode = GET_MODE (mem);
24877   enum machine_mode wmode = (mode == DImode ? DImode : SImode);
24878   rtx label, x;
24879
24880   arm_pre_atomic_barrier (model);
24881
24882   label = gen_label_rtx ();
24883   emit_label (label);
24884
24885   if (new_out)
24886     new_out = gen_lowpart (wmode, new_out);
24887   if (old_out)
24888     old_out = gen_lowpart (wmode, old_out);
24889   else
24890     old_out = new_out;
24891   value = simplify_gen_subreg (wmode, value, mode, 0);
24892
24893   arm_emit_load_exclusive (mode, old_out, mem);
24894
24895   switch (code)
24896     {
24897     case SET:
24898       new_out = value;
24899       break;
24900
24901     case NOT:
24902       x = gen_rtx_AND (wmode, old_out, value);
24903       emit_insn (gen_rtx_SET (VOIDmode, new_out, x));
24904       x = gen_rtx_NOT (wmode, new_out);
24905       emit_insn (gen_rtx_SET (VOIDmode, new_out, x));
24906       break;
24907
24908     case MINUS:
24909       if (CONST_INT_P (value))
24910         {
24911           value = GEN_INT (-INTVAL (value));
24912           code = PLUS;
24913         }
24914       /* FALLTHRU */
24915
24916     case PLUS:
24917       if (mode == DImode)
24918         {
24919           /* DImode plus/minus need to clobber flags.  */
24920           /* The adddi3 and subdi3 patterns are incorrectly written so that
24921              they require matching operands, even when we could easily support
24922              three operands.  Thankfully, this can be fixed up post-splitting,
24923              as the individual add+adc patterns do accept three operands and
24924              post-reload cprop can make these moves go away.  */
24925           emit_move_insn (new_out, old_out);
24926           if (code == PLUS)
24927             x = gen_adddi3 (new_out, new_out, value);
24928           else
24929             x = gen_subdi3 (new_out, new_out, value);
24930           emit_insn (x);
24931           break;
24932         }
24933       /* FALLTHRU */
24934
24935     default:
24936       x = gen_rtx_fmt_ee (code, wmode, old_out, value);
24937       emit_insn (gen_rtx_SET (VOIDmode, new_out, x));
24938       break;
24939     }
24940
24941   arm_emit_store_exclusive (mode, cond, mem, gen_lowpart (mode, new_out));
24942
24943   x = gen_rtx_NE (VOIDmode, cond, const0_rtx);
24944   emit_unlikely_jump (gen_cbranchsi4 (x, cond, const0_rtx, label));
24945
24946   arm_post_atomic_barrier (model);
24947 }
24948
24949 #include "gt-arm.h"
24950