make more variables const
[external/binutils.git] / gas / config / tc-xtensa.c
1 /* tc-xtensa.c -- Assemble Xtensa instructions.
2    Copyright (C) 2003-2016 Free Software Foundation, Inc.
3
4    This file is part of GAS, the GNU Assembler.
5
6    GAS is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3, or (at your option)
9    any later version.
10
11    GAS is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with GAS; see the file COPYING.  If not, write to
18    the Free Software Foundation, 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21 #include "as.h"
22 #include <limits.h>
23 #include "sb.h"
24 #include "safe-ctype.h"
25 #include "tc-xtensa.h"
26 #include "subsegs.h"
27 #include "xtensa-relax.h"
28 #include "dwarf2dbg.h"
29 #include "xtensa-istack.h"
30 #include "struc-symbol.h"
31 #include "xtensa-config.h"
32
33 /* Provide default values for new configuration settings.  */
34 #ifndef XSHAL_ABI
35 #define XSHAL_ABI 0
36 #endif
37
38 #ifndef uint32
39 #define uint32 unsigned int
40 #endif
41 #ifndef int32
42 #define int32 signed int
43 #endif
44
45 /* Notes:
46
47    Naming conventions (used somewhat inconsistently):
48       The xtensa_ functions are exported
49       The xg_ functions are internal
50
51    We also have a couple of different extensibility mechanisms.
52    1) The idiom replacement:
53       This is used when a line is first parsed to
54       replace an instruction pattern with another instruction
55       It is currently limited to replacements of instructions
56       with constant operands.
57    2) The xtensa-relax.c mechanism that has stronger instruction
58       replacement patterns.  When an instruction's immediate field
59       does not fit the next instruction sequence is attempted.
60       In addition, "narrow" opcodes are supported this way.  */
61
62
63 /* Define characters with special meanings to GAS.  */
64 const char comment_chars[] = "#";
65 const char line_comment_chars[] = "#";
66 const char line_separator_chars[] = ";";
67 const char EXP_CHARS[] = "eE";
68 const char FLT_CHARS[] = "rRsSfFdDxXpP";
69
70
71 /* Flags to indicate whether the hardware supports the density and
72    absolute literals options.  */
73
74 bfd_boolean density_supported = XCHAL_HAVE_DENSITY;
75 bfd_boolean absolute_literals_supported = XSHAL_USE_ABSOLUTE_LITERALS;
76
77 static vliw_insn cur_vinsn;
78
79 unsigned xtensa_num_pipe_stages;
80 unsigned xtensa_fetch_width = XCHAL_INST_FETCH_WIDTH;
81
82 static enum debug_info_type xt_saved_debug_type = DEBUG_NONE;
83
84 /* Some functions are only valid in the front end.  This variable
85    allows us to assert that we haven't crossed over into the
86    back end.  */
87 static bfd_boolean past_xtensa_end = FALSE;
88
89 /* Flags for properties of the last instruction in a segment.  */
90 #define FLAG_IS_A0_WRITER       0x1
91 #define FLAG_IS_BAD_LOOPEND     0x2
92
93
94 /* We define a special segment names ".literal" to place literals
95    into.  The .fini and .init sections are special because they
96    contain code that is moved together by the linker.  We give them
97    their own special .fini.literal and .init.literal sections.  */
98
99 #define LITERAL_SECTION_NAME            xtensa_section_rename (".literal")
100 #define LIT4_SECTION_NAME               xtensa_section_rename (".lit4")
101 #define INIT_SECTION_NAME               xtensa_section_rename (".init")
102 #define FINI_SECTION_NAME               xtensa_section_rename (".fini")
103
104
105 /* This type is used for the directive_stack to keep track of the
106    state of the literal collection pools.  If lit_prefix is set, it is
107    used to determine the literal section names; otherwise, the literal
108    sections are determined based on the current text section.  The
109    lit_seg and lit4_seg fields cache these literal sections, with the
110    current_text_seg field used a tag to indicate whether the cached
111    values are valid.  */
112
113 typedef struct lit_state_struct
114 {
115   char *lit_prefix;
116   segT current_text_seg;
117   segT lit_seg;
118   segT lit4_seg;
119 } lit_state;
120
121 static lit_state default_lit_sections;
122
123
124 /* We keep a list of literal segments.  The seg_list type is the node
125    for this list.  The literal_head pointer is the head of the list,
126    with the literal_head_h dummy node at the start.  */
127
128 typedef struct seg_list_struct
129 {
130   struct seg_list_struct *next;
131   segT seg;
132 } seg_list;
133
134 static seg_list literal_head_h;
135 static seg_list *literal_head = &literal_head_h;
136
137
138 /* Lists of symbols.  We keep a list of symbols that label the current
139    instruction, so that we can adjust the symbols when inserting alignment
140    for various instructions.  We also keep a list of all the symbols on
141    literals, so that we can fix up those symbols when the literals are
142    later moved into the text sections.  */
143
144 typedef struct sym_list_struct
145 {
146   struct sym_list_struct *next;
147   symbolS *sym;
148 } sym_list;
149
150 static sym_list *insn_labels = NULL;
151 static sym_list *free_insn_labels = NULL;
152 static sym_list *saved_insn_labels = NULL;
153
154 static sym_list *literal_syms;
155
156
157 /* Flags to determine whether to prefer const16 or l32r
158    if both options are available.  */
159 int prefer_const16 = 0;
160 int prefer_l32r = 0;
161
162 /* Global flag to indicate when we are emitting literals.  */
163 int generating_literals = 0;
164
165 /* The following PROPERTY table definitions are copied from
166    <elf/xtensa.h> and must be kept in sync with the code there.  */
167
168 /* Flags in the property tables to specify whether blocks of memory
169    are literals, instructions, data, or unreachable.  For
170    instructions, blocks that begin loop targets and branch targets are
171    designated.  Blocks that do not allow density, instruction
172    reordering or transformation are also specified.  Finally, for
173    branch targets, branch target alignment priority is included.
174    Alignment of the next block is specified in the current block
175    and the size of the current block does not include any fill required
176    to align to the next block.  */
177
178 #define XTENSA_PROP_LITERAL             0x00000001
179 #define XTENSA_PROP_INSN                0x00000002
180 #define XTENSA_PROP_DATA                0x00000004
181 #define XTENSA_PROP_UNREACHABLE         0x00000008
182 /* Instruction only properties at beginning of code.  */
183 #define XTENSA_PROP_INSN_LOOP_TARGET    0x00000010
184 #define XTENSA_PROP_INSN_BRANCH_TARGET  0x00000020
185 /* Instruction only properties about code.  */
186 #define XTENSA_PROP_INSN_NO_DENSITY     0x00000040
187 #define XTENSA_PROP_INSN_NO_REORDER     0x00000080
188 /* Historically, NO_TRANSFORM was a property of instructions,
189    but it should apply to literals under certain circumstances.  */
190 #define XTENSA_PROP_NO_TRANSFORM        0x00000100
191
192 /*  Branch target alignment information.  This transmits information
193     to the linker optimization about the priority of aligning a
194     particular block for branch target alignment: None, low priority,
195     high priority, or required.  These only need to be checked in
196     instruction blocks marked as XTENSA_PROP_INSN_BRANCH_TARGET.
197     Common usage is
198
199     switch (GET_XTENSA_PROP_BT_ALIGN (flags))
200     case XTENSA_PROP_BT_ALIGN_NONE:
201     case XTENSA_PROP_BT_ALIGN_LOW:
202     case XTENSA_PROP_BT_ALIGN_HIGH:
203     case XTENSA_PROP_BT_ALIGN_REQUIRE:
204 */
205 #define XTENSA_PROP_BT_ALIGN_MASK       0x00000600
206
207 /* No branch target alignment.  */
208 #define XTENSA_PROP_BT_ALIGN_NONE       0x0
209 /* Low priority branch target alignment.  */
210 #define XTENSA_PROP_BT_ALIGN_LOW        0x1
211 /* High priority branch target alignment.  */
212 #define XTENSA_PROP_BT_ALIGN_HIGH       0x2
213 /* Required branch target alignment.  */
214 #define XTENSA_PROP_BT_ALIGN_REQUIRE    0x3
215
216 #define GET_XTENSA_PROP_BT_ALIGN(flag) \
217   (((unsigned) ((flag) & (XTENSA_PROP_BT_ALIGN_MASK))) >> 9)
218 #define SET_XTENSA_PROP_BT_ALIGN(flag, align) \
219   (((flag) & (~XTENSA_PROP_BT_ALIGN_MASK)) | \
220     (((align) << 9) & XTENSA_PROP_BT_ALIGN_MASK))
221
222
223 /* Alignment is specified in the block BEFORE the one that needs
224    alignment.  Up to 5 bits.  Use GET_XTENSA_PROP_ALIGNMENT(flags) to
225    get the required alignment specified as a power of 2.  Use
226    SET_XTENSA_PROP_ALIGNMENT(flags, pow2) to set the required
227    alignment.  Be careful of side effects since the SET will evaluate
228    flags twice.  Also, note that the SIZE of a block in the property
229    table does not include the alignment size, so the alignment fill
230    must be calculated to determine if two blocks are contiguous.
231    TEXT_ALIGN is not currently implemented but is a placeholder for a
232    possible future implementation.  */
233
234 #define XTENSA_PROP_ALIGN               0x00000800
235
236 #define XTENSA_PROP_ALIGNMENT_MASK      0x0001f000
237
238 #define GET_XTENSA_PROP_ALIGNMENT(flag) \
239   (((unsigned) ((flag) & (XTENSA_PROP_ALIGNMENT_MASK))) >> 12)
240 #define SET_XTENSA_PROP_ALIGNMENT(flag, align) \
241   (((flag) & (~XTENSA_PROP_ALIGNMENT_MASK)) | \
242     (((align) << 12) & XTENSA_PROP_ALIGNMENT_MASK))
243
244 #define XTENSA_PROP_INSN_ABSLIT 0x00020000
245
246
247 /* Structure for saving instruction and alignment per-fragment data
248    that will be written to the object file.  This structure is
249    equivalent to the actual data that will be written out to the file
250    but is easier to use.   We provide a conversion to file flags
251    in frag_flags_to_number.  */
252
253 typedef struct frag_flags_struct frag_flags;
254
255 struct frag_flags_struct
256 {
257   /* is_literal should only be used after xtensa_move_literals.
258      If you need to check if you are generating a literal fragment,
259      then use the generating_literals global.  */
260
261   unsigned is_literal : 1;
262   unsigned is_insn : 1;
263   unsigned is_data : 1;
264   unsigned is_unreachable : 1;
265
266   /* is_specific_opcode implies no_transform.  */
267   unsigned is_no_transform : 1;
268
269   struct
270   {
271     unsigned is_loop_target : 1;
272     unsigned is_branch_target : 1; /* Branch targets have a priority.  */
273     unsigned bt_align_priority : 2;
274
275     unsigned is_no_density : 1;
276     /* no_longcalls flag does not need to be placed in the object file.  */
277
278     unsigned is_no_reorder : 1;
279
280     /* Uses absolute literal addressing for l32r.  */
281     unsigned is_abslit : 1;
282   } insn;
283   unsigned is_align : 1;
284   unsigned alignment : 5;
285 };
286
287
288 /* Structure for saving information about a block of property data
289    for frags that have the same flags.  */
290 struct xtensa_block_info_struct
291 {
292   segT sec;
293   bfd_vma offset;
294   size_t size;
295   frag_flags flags;
296   struct xtensa_block_info_struct *next;
297 };
298
299
300 /* Structure for saving the current state before emitting literals.  */
301 typedef struct emit_state_struct
302 {
303   const char *name;
304   segT now_seg;
305   subsegT now_subseg;
306   int generating_literals;
307 } emit_state;
308
309
310 /* Opcode placement information */
311
312 typedef unsigned long long bitfield;
313 #define bit_is_set(bit, bf)     ((bf) & (0x01ll << (bit)))
314 #define set_bit(bit, bf)        ((bf) |= (0x01ll << (bit)))
315 #define clear_bit(bit, bf)      ((bf) &= ~(0x01ll << (bit)))
316
317 #define MAX_FORMATS 32
318
319 typedef struct op_placement_info_struct
320 {
321   int num_formats;
322   /* A number describing how restrictive the issue is for this
323      opcode.  For example, an opcode that fits lots of different
324      formats has a high freedom, as does an opcode that fits
325      only one format but many slots in that format.  The most
326      restrictive is the opcode that fits only one slot in one
327      format.  */
328   int issuef;
329   xtensa_format narrowest;
330   char narrowest_size;
331   char narrowest_slot;
332
333   /* formats is a bitfield with the Nth bit set
334      if the opcode fits in the Nth xtensa_format.  */
335   bitfield formats;
336
337   /* slots[N]'s Mth bit is set if the op fits in the
338      Mth slot of the Nth xtensa_format.  */
339   bitfield slots[MAX_FORMATS];
340
341   /* A count of the number of slots in a given format
342      an op can fit (i.e., the bitcount of the slot field above).  */
343   char slots_in_format[MAX_FORMATS];
344
345 } op_placement_info, *op_placement_info_table;
346
347 op_placement_info_table op_placement_table;
348
349
350 /* Extra expression types.  */
351
352 #define O_pltrel        O_md1   /* like O_symbol but use a PLT reloc */
353 #define O_hi16          O_md2   /* use high 16 bits of symbolic value */
354 #define O_lo16          O_md3   /* use low 16 bits of symbolic value */
355 #define O_pcrel         O_md4   /* value is a PC-relative offset */
356 #define O_tlsfunc       O_md5   /* TLS_FUNC/TLSDESC_FN relocation */
357 #define O_tlsarg        O_md6   /* TLS_ARG/TLSDESC_ARG relocation */
358 #define O_tlscall       O_md7   /* TLS_CALL relocation */
359 #define O_tpoff         O_md8   /* TPOFF relocation */
360 #define O_dtpoff        O_md9   /* DTPOFF relocation */
361
362 struct suffix_reloc_map
363 {
364   const char *suffix;
365   int length;
366   bfd_reloc_code_real_type reloc;
367   unsigned char operator;
368 };
369
370 #define SUFFIX_MAP(str, reloc, op) { str, sizeof (str) - 1, reloc, op }
371
372 static struct suffix_reloc_map suffix_relocs[] =
373 {
374   SUFFIX_MAP ("l",      BFD_RELOC_LO16,                 O_lo16),
375   SUFFIX_MAP ("h",      BFD_RELOC_HI16,                 O_hi16),
376   SUFFIX_MAP ("plt",    BFD_RELOC_XTENSA_PLT,           O_pltrel),
377   SUFFIX_MAP ("pcrel",  BFD_RELOC_32_PCREL,             O_pcrel),
378   SUFFIX_MAP ("tlsfunc", BFD_RELOC_XTENSA_TLS_FUNC,     O_tlsfunc),
379   SUFFIX_MAP ("tlsarg", BFD_RELOC_XTENSA_TLS_ARG,       O_tlsarg),
380   SUFFIX_MAP ("tlscall", BFD_RELOC_XTENSA_TLS_CALL,     O_tlscall),
381   SUFFIX_MAP ("tpoff",  BFD_RELOC_XTENSA_TLS_TPOFF,     O_tpoff),
382   SUFFIX_MAP ("dtpoff", BFD_RELOC_XTENSA_TLS_DTPOFF,    O_dtpoff),
383   { (char *) 0, 0,      BFD_RELOC_UNUSED,               0 }
384 };
385
386
387 /* Directives.  */
388
389 typedef enum
390 {
391   directive_none = 0,
392   directive_literal,
393   directive_density,
394   directive_transform,
395   directive_freeregs,
396   directive_longcalls,
397   directive_literal_prefix,
398   directive_schedule,
399   directive_absolute_literals,
400   directive_last_directive
401 } directiveE;
402
403 typedef struct
404 {
405   const char *name;
406   bfd_boolean can_be_negated;
407 } directive_infoS;
408
409 const directive_infoS directive_info[] =
410 {
411   { "none",             FALSE },
412   { "literal",          FALSE },
413   { "density",          TRUE },
414   { "transform",        TRUE },
415   { "freeregs",         FALSE },
416   { "longcalls",        TRUE },
417   { "literal_prefix",   FALSE },
418   { "schedule",         TRUE },
419   { "absolute-literals", TRUE }
420 };
421
422 bfd_boolean directive_state[] =
423 {
424   FALSE,                        /* none */
425   FALSE,                        /* literal */
426 #if !XCHAL_HAVE_DENSITY
427   FALSE,                        /* density */
428 #else
429   TRUE,                         /* density */
430 #endif
431   TRUE,                         /* transform */
432   FALSE,                        /* freeregs */
433   FALSE,                        /* longcalls */
434   FALSE,                        /* literal_prefix */
435   FALSE,                        /* schedule */
436 #if XSHAL_USE_ABSOLUTE_LITERALS
437   TRUE                          /* absolute_literals */
438 #else
439   FALSE                         /* absolute_literals */
440 #endif
441 };
442
443 /* A circular list of all potential and actual literal pool locations
444    in a segment.  */
445 struct litpool_frag
446 {
447   struct litpool_frag *next;
448   struct litpool_frag *prev;
449   fragS *fragP;
450   addressT addr;
451   short priority; /* 1, 2, or 3 -- 1 is highest  */
452   short original_priority;
453 };
454
455 /* Map a segment to its litpool_frag list.  */
456 struct litpool_seg
457 {
458   struct litpool_seg *next;
459   asection *seg;
460   struct litpool_frag frag_list;
461   int frag_count; /* since last litpool location  */
462 };
463
464 static struct litpool_seg litpool_seg_list;
465
466
467 /* Directive functions.  */
468
469 static void xtensa_begin_directive (int);
470 static void xtensa_end_directive (int);
471 static void xtensa_literal_prefix (void);
472 static void xtensa_literal_position (int);
473 static void xtensa_literal_pseudo (int);
474 static void xtensa_frequency_pseudo (int);
475 static void xtensa_elf_cons (int);
476 static void xtensa_leb128 (int);
477
478 /* Parsing and Idiom Translation.  */
479
480 static bfd_reloc_code_real_type xtensa_elf_suffix (char **, expressionS *);
481
482 /* Various Other Internal Functions.  */
483
484 extern bfd_boolean xg_is_single_relaxable_insn (TInsn *, TInsn *, bfd_boolean);
485 static bfd_boolean xg_build_to_insn (TInsn *, TInsn *, BuildInstr *);
486 static void xtensa_mark_literal_pool_location (void);
487 static addressT get_expanded_loop_offset (xtensa_opcode);
488 static fragS *get_literal_pool_location (segT);
489 static void set_literal_pool_location (segT, fragS *);
490 static void xtensa_set_frag_assembly_state (fragS *);
491 static void finish_vinsn (vliw_insn *);
492 static bfd_boolean emit_single_op (TInsn *);
493 static int total_frag_text_expansion (fragS *);
494 static bfd_boolean use_trampolines = TRUE;
495 static void xtensa_check_frag_count (void);
496 static void xtensa_create_trampoline_frag (bfd_boolean);
497 static void xtensa_maybe_create_trampoline_frag (void);
498 struct trampoline_frag;
499 static int init_trampoline_frag (struct trampoline_frag *);
500 static void xtensa_maybe_create_literal_pool_frag (bfd_boolean, bfd_boolean);
501 static bfd_boolean auto_litpools = FALSE;
502 static int auto_litpool_limit = 10000;
503
504 /* Alignment Functions.  */
505
506 static int get_text_align_power (unsigned);
507 static int get_text_align_max_fill_size (int, bfd_boolean, bfd_boolean);
508 static int branch_align_power (segT);
509
510 /* Helpers for xtensa_relax_frag().  */
511
512 static long relax_frag_add_nop (fragS *);
513
514 /* Accessors for additional per-subsegment information.  */
515
516 static unsigned get_last_insn_flags (segT, subsegT);
517 static void set_last_insn_flags (segT, subsegT, unsigned, bfd_boolean);
518 static float get_subseg_total_freq (segT, subsegT);
519 static float get_subseg_target_freq (segT, subsegT);
520 static void set_subseg_freq (segT, subsegT, float, float);
521
522 /* Segment list functions.  */
523
524 static void xtensa_move_literals (void);
525 static void xtensa_reorder_segments (void);
526 static void xtensa_switch_to_literal_fragment (emit_state *);
527 static void xtensa_switch_to_non_abs_literal_fragment (emit_state *);
528 static void xtensa_switch_section_emit_state (emit_state *, segT, subsegT);
529 static void xtensa_restore_emit_state (emit_state *);
530 static segT cache_literal_section (bfd_boolean);
531
532 /* Import from elf32-xtensa.c in BFD library.  */
533
534 extern asection *xtensa_make_property_section (asection *, const char *);
535
536 /* op_placement_info functions.  */
537
538 static void init_op_placement_info_table (void);
539 extern bfd_boolean opcode_fits_format_slot (xtensa_opcode, xtensa_format, int);
540 static int xg_get_single_size (xtensa_opcode);
541 static xtensa_format xg_get_single_format (xtensa_opcode);
542 static int xg_get_single_slot (xtensa_opcode);
543
544 /* TInsn and IStack functions.  */
545
546 static bfd_boolean tinsn_has_symbolic_operands (const TInsn *);
547 static bfd_boolean tinsn_has_invalid_symbolic_operands (const TInsn *);
548 static bfd_boolean tinsn_has_complex_operands (const TInsn *);
549 static bfd_boolean tinsn_to_insnbuf (TInsn *, xtensa_insnbuf);
550 static bfd_boolean tinsn_check_arguments (const TInsn *);
551 static void tinsn_from_chars (TInsn *, char *, int);
552 static void tinsn_immed_from_frag (TInsn *, fragS *, int);
553 static int get_num_stack_text_bytes (IStack *);
554 static int get_num_stack_literal_bytes (IStack *);
555 static bfd_boolean tinsn_to_slotbuf (xtensa_format, int, TInsn *, xtensa_insnbuf);
556
557 /* vliw_insn functions.  */
558
559 static void xg_init_vinsn (vliw_insn *);
560 static void xg_copy_vinsn (vliw_insn *, vliw_insn *);
561 static void xg_clear_vinsn (vliw_insn *);
562 static bfd_boolean vinsn_has_specific_opcodes (vliw_insn *);
563 static void xg_free_vinsn (vliw_insn *);
564 static bfd_boolean vinsn_to_insnbuf
565   (vliw_insn *, char *, fragS *, bfd_boolean);
566 static void vinsn_from_chars (vliw_insn *, char *);
567
568 /* Expression Utilities.  */
569
570 bfd_boolean expr_is_const (const expressionS *);
571 offsetT get_expr_const (const expressionS *);
572 void set_expr_const (expressionS *, offsetT);
573 bfd_boolean expr_is_register (const expressionS *);
574 offsetT get_expr_register (const expressionS *);
575 void set_expr_symbol_offset (expressionS *, symbolS *, offsetT);
576 bfd_boolean expr_is_equal (expressionS *, expressionS *);
577 static void copy_expr (expressionS *, const expressionS *);
578
579 /* Section renaming.  */
580
581 static void build_section_rename (const char *);
582
583
584 /* ISA imported from bfd.  */
585 extern xtensa_isa xtensa_default_isa;
586
587 extern int target_big_endian;
588
589 static xtensa_opcode xtensa_addi_opcode;
590 static xtensa_opcode xtensa_addmi_opcode;
591 static xtensa_opcode xtensa_call0_opcode;
592 static xtensa_opcode xtensa_call4_opcode;
593 static xtensa_opcode xtensa_call8_opcode;
594 static xtensa_opcode xtensa_call12_opcode;
595 static xtensa_opcode xtensa_callx0_opcode;
596 static xtensa_opcode xtensa_callx4_opcode;
597 static xtensa_opcode xtensa_callx8_opcode;
598 static xtensa_opcode xtensa_callx12_opcode;
599 static xtensa_opcode xtensa_const16_opcode;
600 static xtensa_opcode xtensa_entry_opcode;
601 static xtensa_opcode xtensa_extui_opcode;
602 static xtensa_opcode xtensa_movi_opcode;
603 static xtensa_opcode xtensa_movi_n_opcode;
604 static xtensa_opcode xtensa_isync_opcode;
605 static xtensa_opcode xtensa_j_opcode;
606 static xtensa_opcode xtensa_jx_opcode;
607 static xtensa_opcode xtensa_l32r_opcode;
608 static xtensa_opcode xtensa_loop_opcode;
609 static xtensa_opcode xtensa_loopnez_opcode;
610 static xtensa_opcode xtensa_loopgtz_opcode;
611 static xtensa_opcode xtensa_nop_opcode;
612 static xtensa_opcode xtensa_nop_n_opcode;
613 static xtensa_opcode xtensa_or_opcode;
614 static xtensa_opcode xtensa_ret_opcode;
615 static xtensa_opcode xtensa_ret_n_opcode;
616 static xtensa_opcode xtensa_retw_opcode;
617 static xtensa_opcode xtensa_retw_n_opcode;
618 static xtensa_opcode xtensa_rsr_lcount_opcode;
619 static xtensa_opcode xtensa_waiti_opcode;
620 static int config_max_slots = 0;
621
622 \f
623 /* Command-line Options.  */
624
625 bfd_boolean use_literal_section = TRUE;
626 enum flix_level produce_flix = FLIX_ALL;
627 static bfd_boolean align_targets = TRUE;
628 static bfd_boolean warn_unaligned_branch_targets = FALSE;
629 static bfd_boolean has_a0_b_retw = FALSE;
630 static bfd_boolean workaround_a0_b_retw = FALSE;
631 static bfd_boolean workaround_b_j_loop_end = FALSE;
632 static bfd_boolean workaround_short_loop = FALSE;
633 static bfd_boolean maybe_has_short_loop = FALSE;
634 static bfd_boolean workaround_close_loop_end = FALSE;
635 static bfd_boolean maybe_has_close_loop_end = FALSE;
636 static bfd_boolean enforce_three_byte_loop_align = FALSE;
637
638 /* When workaround_short_loops is TRUE, all loops with early exits must
639    have at least 3 instructions.  workaround_all_short_loops is a modifier
640    to the workaround_short_loop flag.  In addition to the
641    workaround_short_loop actions, all straightline loopgtz and loopnez
642    must have at least 3 instructions.  */
643
644 static bfd_boolean workaround_all_short_loops = FALSE;
645
646
647 static void
648 xtensa_setup_hw_workarounds (int earliest, int latest)
649 {
650   if (earliest > latest)
651     as_fatal (_("illegal range of target hardware versions"));
652
653   /* Enable all workarounds for pre-T1050.0 hardware.  */
654   if (earliest < 105000 || latest < 105000)
655     {
656       workaround_a0_b_retw |= TRUE;
657       workaround_b_j_loop_end |= TRUE;
658       workaround_short_loop |= TRUE;
659       workaround_close_loop_end |= TRUE;
660       workaround_all_short_loops |= TRUE;
661       enforce_three_byte_loop_align = TRUE;
662     }
663 }
664
665
666 enum
667 {
668   option_density = OPTION_MD_BASE,
669   option_no_density,
670
671   option_flix,
672   option_no_generate_flix,
673   option_no_flix,
674
675   option_relax,
676   option_no_relax,
677
678   option_link_relax,
679   option_no_link_relax,
680
681   option_generics,
682   option_no_generics,
683
684   option_transform,
685   option_no_transform,
686
687   option_text_section_literals,
688   option_no_text_section_literals,
689
690   option_absolute_literals,
691   option_no_absolute_literals,
692
693   option_align_targets,
694   option_no_align_targets,
695
696   option_warn_unaligned_targets,
697
698   option_longcalls,
699   option_no_longcalls,
700
701   option_workaround_a0_b_retw,
702   option_no_workaround_a0_b_retw,
703
704   option_workaround_b_j_loop_end,
705   option_no_workaround_b_j_loop_end,
706
707   option_workaround_short_loop,
708   option_no_workaround_short_loop,
709
710   option_workaround_all_short_loops,
711   option_no_workaround_all_short_loops,
712
713   option_workaround_close_loop_end,
714   option_no_workaround_close_loop_end,
715
716   option_no_workarounds,
717
718   option_rename_section_name,
719
720   option_prefer_l32r,
721   option_prefer_const16,
722
723   option_target_hardware,
724
725   option_trampolines,
726   option_no_trampolines,
727
728   option_auto_litpools,
729   option_no_auto_litpools,
730   option_auto_litpool_limit,
731 };
732
733 const char *md_shortopts = "";
734
735 struct option md_longopts[] =
736 {
737   { "density", no_argument, NULL, option_density },
738   { "no-density", no_argument, NULL, option_no_density },
739
740   { "flix", no_argument, NULL, option_flix },
741   { "no-generate-flix", no_argument, NULL, option_no_generate_flix },
742   { "no-allow-flix", no_argument, NULL, option_no_flix },
743
744   /* Both "relax" and "generics" are deprecated and treated as equivalent
745      to the "transform" option.  */
746   { "relax", no_argument, NULL, option_relax },
747   { "no-relax", no_argument, NULL, option_no_relax },
748   { "generics", no_argument, NULL, option_generics },
749   { "no-generics", no_argument, NULL, option_no_generics },
750
751   { "transform", no_argument, NULL, option_transform },
752   { "no-transform", no_argument, NULL, option_no_transform },
753   { "text-section-literals", no_argument, NULL, option_text_section_literals },
754   { "no-text-section-literals", no_argument, NULL,
755     option_no_text_section_literals },
756   { "absolute-literals", no_argument, NULL, option_absolute_literals },
757   { "no-absolute-literals", no_argument, NULL, option_no_absolute_literals },
758   /* This option was changed from -align-target to -target-align
759      because it conflicted with the "-al" option.  */
760   { "target-align", no_argument, NULL, option_align_targets },
761   { "no-target-align", no_argument, NULL, option_no_align_targets },
762   { "warn-unaligned-targets", no_argument, NULL,
763     option_warn_unaligned_targets },
764   { "longcalls", no_argument, NULL, option_longcalls },
765   { "no-longcalls", no_argument, NULL, option_no_longcalls },
766
767   { "no-workaround-a0-b-retw", no_argument, NULL,
768     option_no_workaround_a0_b_retw },
769   { "workaround-a0-b-retw", no_argument, NULL, option_workaround_a0_b_retw },
770
771   { "no-workaround-b-j-loop-end", no_argument, NULL,
772     option_no_workaround_b_j_loop_end },
773   { "workaround-b-j-loop-end", no_argument, NULL,
774     option_workaround_b_j_loop_end },
775
776   { "no-workaround-short-loops", no_argument, NULL,
777     option_no_workaround_short_loop },
778   { "workaround-short-loops", no_argument, NULL,
779     option_workaround_short_loop },
780
781   { "no-workaround-all-short-loops", no_argument, NULL,
782     option_no_workaround_all_short_loops },
783   { "workaround-all-short-loop", no_argument, NULL,
784     option_workaround_all_short_loops },
785
786   { "prefer-l32r", no_argument, NULL, option_prefer_l32r },
787   { "prefer-const16", no_argument, NULL, option_prefer_const16 },
788
789   { "no-workarounds", no_argument, NULL, option_no_workarounds },
790
791   { "no-workaround-close-loop-end", no_argument, NULL,
792     option_no_workaround_close_loop_end },
793   { "workaround-close-loop-end", no_argument, NULL,
794     option_workaround_close_loop_end },
795
796   { "rename-section", required_argument, NULL, option_rename_section_name },
797
798   { "link-relax", no_argument, NULL, option_link_relax },
799   { "no-link-relax", no_argument, NULL, option_no_link_relax },
800
801   { "target-hardware", required_argument, NULL, option_target_hardware },
802
803   { "trampolines", no_argument, NULL, option_trampolines },
804   { "no-trampolines", no_argument, NULL, option_no_trampolines },
805
806   { "auto-litpools", no_argument, NULL, option_auto_litpools },
807   { "no-auto-litpools", no_argument, NULL, option_no_auto_litpools },
808   { "auto-litpool-limit", required_argument, NULL, option_auto_litpool_limit },
809
810   { NULL, no_argument, NULL, 0 }
811 };
812
813 size_t md_longopts_size = sizeof md_longopts;
814
815
816 int
817 md_parse_option (int c, char *arg)
818 {
819   switch (c)
820     {
821     case option_density:
822       as_warn (_("--density option is ignored"));
823       return 1;
824     case option_no_density:
825       as_warn (_("--no-density option is ignored"));
826       return 1;
827     case option_link_relax:
828       linkrelax = 1;
829       return 1;
830     case option_no_link_relax:
831       linkrelax = 0;
832       return 1;
833     case option_flix:
834       produce_flix = FLIX_ALL;
835       return 1;
836     case option_no_generate_flix:
837       produce_flix = FLIX_NO_GENERATE;
838       return 1;
839     case option_no_flix:
840       produce_flix = FLIX_NONE;
841       return 1;
842     case option_generics:
843       as_warn (_("--generics is deprecated; use --transform instead"));
844       return md_parse_option (option_transform, arg);
845     case option_no_generics:
846       as_warn (_("--no-generics is deprecated; use --no-transform instead"));
847       return md_parse_option (option_no_transform, arg);
848     case option_relax:
849       as_warn (_("--relax is deprecated; use --transform instead"));
850       return md_parse_option (option_transform, arg);
851     case option_no_relax:
852       as_warn (_("--no-relax is deprecated; use --no-transform instead"));
853       return md_parse_option (option_no_transform, arg);
854     case option_longcalls:
855       directive_state[directive_longcalls] = TRUE;
856       return 1;
857     case option_no_longcalls:
858       directive_state[directive_longcalls] = FALSE;
859       return 1;
860     case option_text_section_literals:
861       use_literal_section = FALSE;
862       return 1;
863     case option_no_text_section_literals:
864       use_literal_section = TRUE;
865       return 1;
866     case option_absolute_literals:
867       if (!absolute_literals_supported)
868         {
869           as_fatal (_("--absolute-literals option not supported in this Xtensa configuration"));
870           return 0;
871         }
872       directive_state[directive_absolute_literals] = TRUE;
873       return 1;
874     case option_no_absolute_literals:
875       directive_state[directive_absolute_literals] = FALSE;
876       return 1;
877
878     case option_workaround_a0_b_retw:
879       workaround_a0_b_retw = TRUE;
880       return 1;
881     case option_no_workaround_a0_b_retw:
882       workaround_a0_b_retw = FALSE;
883       return 1;
884     case option_workaround_b_j_loop_end:
885       workaround_b_j_loop_end = TRUE;
886       return 1;
887     case option_no_workaround_b_j_loop_end:
888       workaround_b_j_loop_end = FALSE;
889       return 1;
890
891     case option_workaround_short_loop:
892       workaround_short_loop = TRUE;
893       return 1;
894     case option_no_workaround_short_loop:
895       workaround_short_loop = FALSE;
896       return 1;
897
898     case option_workaround_all_short_loops:
899       workaround_all_short_loops = TRUE;
900       return 1;
901     case option_no_workaround_all_short_loops:
902       workaround_all_short_loops = FALSE;
903       return 1;
904
905     case option_workaround_close_loop_end:
906       workaround_close_loop_end = TRUE;
907       return 1;
908     case option_no_workaround_close_loop_end:
909       workaround_close_loop_end = FALSE;
910       return 1;
911
912     case option_no_workarounds:
913       workaround_a0_b_retw = FALSE;
914       workaround_b_j_loop_end = FALSE;
915       workaround_short_loop = FALSE;
916       workaround_all_short_loops = FALSE;
917       workaround_close_loop_end = FALSE;
918       return 1;
919
920     case option_align_targets:
921       align_targets = TRUE;
922       return 1;
923     case option_no_align_targets:
924       align_targets = FALSE;
925       return 1;
926
927     case option_warn_unaligned_targets:
928       warn_unaligned_branch_targets = TRUE;
929       return 1;
930
931     case option_rename_section_name:
932       build_section_rename (arg);
933       return 1;
934
935     case 'Q':
936       /* -Qy, -Qn: SVR4 arguments controlling whether a .comment section
937          should be emitted or not.  FIXME: Not implemented.  */
938       return 1;
939
940     case option_prefer_l32r:
941       if (prefer_const16)
942         as_fatal (_("prefer-l32r conflicts with prefer-const16"));
943       prefer_l32r = 1;
944       return 1;
945
946     case option_prefer_const16:
947       if (prefer_l32r)
948         as_fatal (_("prefer-const16 conflicts with prefer-l32r"));
949       prefer_const16 = 1;
950       return 1;
951
952     case option_target_hardware:
953       {
954         int earliest, latest = 0;
955         if (*arg == 0 || *arg == '-')
956           as_fatal (_("invalid target hardware version"));
957
958         earliest = strtol (arg, &arg, 0);
959
960         if (*arg == 0)
961           latest = earliest;
962         else if (*arg == '-')
963           {
964             if (*++arg == 0)
965               as_fatal (_("invalid target hardware version"));
966             latest = strtol (arg, &arg, 0);
967           }
968         if (*arg != 0)
969           as_fatal (_("invalid target hardware version"));
970
971         xtensa_setup_hw_workarounds (earliest, latest);
972         return 1;
973       }
974
975     case option_transform:
976       /* This option has no affect other than to use the defaults,
977          which are already set.  */
978       return 1;
979
980     case option_no_transform:
981       /* This option turns off all transformations of any kind.
982          However, because we want to preserve the state of other
983          directives, we only change its own field.  Thus, before
984          you perform any transformation, always check if transform
985          is available.  If you use the functions we provide for this
986          purpose, you will be ok.  */
987       directive_state[directive_transform] = FALSE;
988       return 1;
989
990     case option_trampolines:
991       use_trampolines = TRUE;
992       return 1;
993
994     case option_no_trampolines:
995       use_trampolines = FALSE;
996       return 1;
997
998     case option_auto_litpools:
999       auto_litpools = TRUE;
1000       use_literal_section = FALSE;
1001       return 1;
1002
1003     case option_no_auto_litpools:
1004       auto_litpools = FALSE;
1005       auto_litpool_limit = -1;
1006       return 1;
1007
1008     case option_auto_litpool_limit:
1009       {
1010         int value = 0;
1011         if (auto_litpool_limit < 0)
1012           as_fatal (_("no-auto-litpools is incompatible with auto-litpool-limit"));
1013         if (*arg == 0 || *arg == '-')
1014           as_fatal (_("invalid auto-litpool-limit argument"));
1015         value = strtol (arg, &arg, 10);
1016         if (*arg != 0)
1017           as_fatal (_("invalid auto-litpool-limit argument"));
1018         if (value < 100 || value > 10000)
1019           as_fatal (_("invalid auto-litpool-limit argument (range is 100-10000)"));
1020         auto_litpool_limit = value;
1021         auto_litpools = TRUE;
1022         use_literal_section = FALSE;
1023         return 1;
1024       }
1025
1026     default:
1027       return 0;
1028     }
1029 }
1030
1031
1032 void
1033 md_show_usage (FILE *stream)
1034 {
1035   fputs ("\n\
1036 Xtensa options:\n\
1037   --[no-]text-section-literals\n\
1038                           [Do not] put literals in the text section\n\
1039   --[no-]absolute-literals\n\
1040                           [Do not] default to use non-PC-relative literals\n\
1041   --[no-]target-align     [Do not] try to align branch targets\n\
1042   --[no-]longcalls        [Do not] emit 32-bit call sequences\n\
1043   --[no-]transform        [Do not] transform instructions\n\
1044   --flix                  both allow hand-written and generate flix bundles\n\
1045   --no-generate-flix      allow hand-written but do not generate\n\
1046                           flix bundles\n\
1047   --no-allow-flix         neither allow hand-written nor generate\n\
1048                           flix bundles\n\
1049   --rename-section old=new Rename section 'old' to 'new'\n\
1050   --[no-]trampolines      [Do not] generate trampolines (jumps to jumps)\n\
1051                           when jumps do not reach their targets\n\
1052   --[no-]auto-litpools    [Do not] automatically create literal pools\n\
1053   --auto-litpool-limit=<value>\n\
1054                           (range 100-10000) Maximum number of blocks of\n\
1055                           instructions to emit between literal pool\n\
1056                           locations; implies --auto-litpools flag\n", stream);
1057 }
1058
1059 \f
1060 /* Functions related to the list of current label symbols.  */
1061
1062 static void
1063 xtensa_add_insn_label (symbolS *sym)
1064 {
1065   sym_list *l;
1066
1067   if (!free_insn_labels)
1068     l = (sym_list *) xmalloc (sizeof (sym_list));
1069   else
1070     {
1071       l = free_insn_labels;
1072       free_insn_labels = l->next;
1073     }
1074
1075   l->sym = sym;
1076   l->next = insn_labels;
1077   insn_labels = l;
1078 }
1079
1080
1081 static void
1082 xtensa_clear_insn_labels (void)
1083 {
1084   sym_list **pl;
1085
1086   for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
1087     ;
1088   *pl = insn_labels;
1089   insn_labels = NULL;
1090 }
1091
1092
1093 static void
1094 xtensa_move_labels (fragS *new_frag, valueT new_offset)
1095 {
1096   sym_list *lit;
1097
1098   for (lit = insn_labels; lit; lit = lit->next)
1099     {
1100       symbolS *lit_sym = lit->sym;
1101       S_SET_VALUE (lit_sym, new_offset);
1102       symbol_set_frag (lit_sym, new_frag);
1103     }
1104 }
1105
1106 \f
1107 /* Directive data and functions.  */
1108
1109 typedef struct state_stackS_struct
1110 {
1111   directiveE directive;
1112   bfd_boolean negated;
1113   bfd_boolean old_state;
1114   const char *file;
1115   unsigned int line;
1116   const void *datum;
1117   struct state_stackS_struct *prev;
1118 } state_stackS;
1119
1120 state_stackS *directive_state_stack;
1121
1122 const pseudo_typeS md_pseudo_table[] =
1123 {
1124   { "align", s_align_bytes, 0 }, /* Defaulting is invalid (0).  */
1125   { "literal_position", xtensa_literal_position, 0 },
1126   { "frame", s_ignore, 0 },     /* Formerly used for STABS debugging.  */
1127   { "long", xtensa_elf_cons, 4 },
1128   { "word", xtensa_elf_cons, 4 },
1129   { "4byte", xtensa_elf_cons, 4 },
1130   { "short", xtensa_elf_cons, 2 },
1131   { "2byte", xtensa_elf_cons, 2 },
1132   { "sleb128", xtensa_leb128, 1},
1133   { "uleb128", xtensa_leb128, 0},
1134   { "begin", xtensa_begin_directive, 0 },
1135   { "end", xtensa_end_directive, 0 },
1136   { "literal", xtensa_literal_pseudo, 0 },
1137   { "frequency", xtensa_frequency_pseudo, 0 },
1138   { NULL, 0, 0 },
1139 };
1140
1141
1142 static bfd_boolean
1143 use_transform (void)
1144 {
1145   /* After md_end, you should be checking frag by frag, rather
1146      than state directives.  */
1147   gas_assert (!past_xtensa_end);
1148   return directive_state[directive_transform];
1149 }
1150
1151
1152 static bfd_boolean
1153 do_align_targets (void)
1154 {
1155   /* Do not use this function after md_end; just look at align_targets
1156      instead.  There is no target-align directive, so alignment is either
1157      enabled for all frags or not done at all.  */
1158   gas_assert (!past_xtensa_end);
1159   return align_targets && use_transform ();
1160 }
1161
1162
1163 static void
1164 directive_push (directiveE directive, bfd_boolean negated, const void *datum)
1165 {
1166   const char *file;
1167   unsigned int line;
1168   state_stackS *stack = (state_stackS *) xmalloc (sizeof (state_stackS));
1169
1170   file = as_where (&line);
1171
1172   stack->directive = directive;
1173   stack->negated = negated;
1174   stack->old_state = directive_state[directive];
1175   stack->file = file;
1176   stack->line = line;
1177   stack->datum = datum;
1178   stack->prev = directive_state_stack;
1179   directive_state_stack = stack;
1180
1181   directive_state[directive] = !negated;
1182 }
1183
1184
1185 static void
1186 directive_pop (directiveE *directive,
1187                bfd_boolean *negated,
1188                const char **file,
1189                unsigned int *line,
1190                const void **datum)
1191 {
1192   state_stackS *top = directive_state_stack;
1193
1194   if (!directive_state_stack)
1195     {
1196       as_bad (_("unmatched end directive"));
1197       *directive = directive_none;
1198       return;
1199     }
1200
1201   directive_state[directive_state_stack->directive] = top->old_state;
1202   *directive = top->directive;
1203   *negated = top->negated;
1204   *file = top->file;
1205   *line = top->line;
1206   *datum = top->datum;
1207   directive_state_stack = top->prev;
1208   free (top);
1209 }
1210
1211
1212 static void
1213 directive_balance (void)
1214 {
1215   while (directive_state_stack)
1216     {
1217       directiveE directive;
1218       bfd_boolean negated;
1219       const char *file;
1220       unsigned int line;
1221       const void *datum;
1222
1223       directive_pop (&directive, &negated, &file, &line, &datum);
1224       as_warn_where ((char *) file, line,
1225                      _(".begin directive with no matching .end directive"));
1226     }
1227 }
1228
1229
1230 static bfd_boolean
1231 inside_directive (directiveE dir)
1232 {
1233   state_stackS *top = directive_state_stack;
1234
1235   while (top && top->directive != dir)
1236     top = top->prev;
1237
1238   return (top != NULL);
1239 }
1240
1241
1242 static void
1243 get_directive (directiveE *directive, bfd_boolean *negated)
1244 {
1245   int len;
1246   unsigned i;
1247   const char *directive_string;
1248
1249   if (strncmp (input_line_pointer, "no-", 3) != 0)
1250     *negated = FALSE;
1251   else
1252     {
1253       *negated = TRUE;
1254       input_line_pointer += 3;
1255     }
1256
1257   len = strspn (input_line_pointer,
1258                 "abcdefghijklmnopqrstuvwxyz_-/0123456789.");
1259
1260   /* This code is a hack to make .begin [no-][generics|relax] exactly
1261      equivalent to .begin [no-]transform.  We should remove it when
1262      we stop accepting those options.  */
1263
1264   if (strncmp (input_line_pointer, "generics", strlen ("generics")) == 0)
1265     {
1266       as_warn (_("[no-]generics is deprecated; use [no-]transform instead"));
1267       directive_string = "transform";
1268     }
1269   else if (strncmp (input_line_pointer, "relax", strlen ("relax")) == 0)
1270     {
1271       as_warn (_("[no-]relax is deprecated; use [no-]transform instead"));
1272       directive_string = "transform";
1273     }
1274   else
1275     directive_string = input_line_pointer;
1276
1277   for (i = 0; i < sizeof (directive_info) / sizeof (*directive_info); ++i)
1278     {
1279       if (strncmp (directive_string, directive_info[i].name, len) == 0)
1280         {
1281           input_line_pointer += len;
1282           *directive = (directiveE) i;
1283           if (*negated && !directive_info[i].can_be_negated)
1284             as_bad (_("directive %s cannot be negated"),
1285                     directive_info[i].name);
1286           return;
1287         }
1288     }
1289
1290   as_bad (_("unknown directive"));
1291   *directive = (directiveE) XTENSA_UNDEFINED;
1292 }
1293
1294
1295 static void
1296 xtensa_begin_directive (int ignore ATTRIBUTE_UNUSED)
1297 {
1298   directiveE directive;
1299   bfd_boolean negated;
1300   emit_state *state;
1301   lit_state *ls;
1302
1303   get_directive (&directive, &negated);
1304   if (directive == (directiveE) XTENSA_UNDEFINED)
1305     {
1306       discard_rest_of_line ();
1307       return;
1308     }
1309
1310   if (cur_vinsn.inside_bundle)
1311     as_bad (_("directives are not valid inside bundles"));
1312
1313   switch (directive)
1314     {
1315     case directive_literal:
1316       if (!inside_directive (directive_literal))
1317         {
1318           /* Previous labels go with whatever follows this directive, not with
1319              the literal, so save them now.  */
1320           saved_insn_labels = insn_labels;
1321           insn_labels = NULL;
1322         }
1323       as_warn (_(".begin literal is deprecated; use .literal instead"));
1324       state = (emit_state *) xmalloc (sizeof (emit_state));
1325       xtensa_switch_to_literal_fragment (state);
1326       directive_push (directive_literal, negated, state);
1327       break;
1328
1329     case directive_literal_prefix:
1330       /* Have to flush pending output because a movi relaxed to an l32r
1331          might produce a literal.  */
1332       md_flush_pending_output ();
1333       /* Check to see if the current fragment is a literal
1334          fragment.  If it is, then this operation is not allowed.  */
1335       if (generating_literals)
1336         {
1337           as_bad (_("cannot set literal_prefix inside literal fragment"));
1338           return;
1339         }
1340
1341       /* Allocate the literal state for this section and push
1342          onto the directive stack.  */
1343       ls = xmalloc (sizeof (lit_state));
1344       gas_assert (ls);
1345
1346       *ls = default_lit_sections;
1347       directive_push (directive_literal_prefix, negated, ls);
1348
1349       /* Process the new prefix.  */
1350       xtensa_literal_prefix ();
1351       break;
1352
1353     case directive_freeregs:
1354       /* This information is currently unused, but we'll accept the statement
1355          and just discard the rest of the line.  This won't check the syntax,
1356          but it will accept every correct freeregs directive.  */
1357       input_line_pointer += strcspn (input_line_pointer, "\n");
1358       directive_push (directive_freeregs, negated, 0);
1359       break;
1360
1361     case directive_schedule:
1362       md_flush_pending_output ();
1363       frag_var (rs_fill, 0, 0, frag_now->fr_subtype,
1364                 frag_now->fr_symbol, frag_now->fr_offset, NULL);
1365       directive_push (directive_schedule, negated, 0);
1366       xtensa_set_frag_assembly_state (frag_now);
1367       break;
1368
1369     case directive_density:
1370       as_warn (_(".begin [no-]density is ignored"));
1371       break;
1372
1373     case directive_absolute_literals:
1374       md_flush_pending_output ();
1375       if (!absolute_literals_supported && !negated)
1376         {
1377           as_warn (_("Xtensa absolute literals option not supported; ignored"));
1378           break;
1379         }
1380       xtensa_set_frag_assembly_state (frag_now);
1381       directive_push (directive, negated, 0);
1382       break;
1383
1384     default:
1385       md_flush_pending_output ();
1386       xtensa_set_frag_assembly_state (frag_now);
1387       directive_push (directive, negated, 0);
1388       break;
1389     }
1390
1391   demand_empty_rest_of_line ();
1392 }
1393
1394
1395 static void
1396 xtensa_end_directive (int ignore ATTRIBUTE_UNUSED)
1397 {
1398   directiveE begin_directive, end_directive;
1399   bfd_boolean begin_negated, end_negated;
1400   const char *file;
1401   unsigned int line;
1402   emit_state *state;
1403   emit_state **state_ptr;
1404   lit_state *s;
1405
1406   if (cur_vinsn.inside_bundle)
1407     as_bad (_("directives are not valid inside bundles"));
1408
1409   get_directive (&end_directive, &end_negated);
1410
1411   md_flush_pending_output ();
1412
1413   switch ((int) end_directive)
1414     {
1415     case XTENSA_UNDEFINED:
1416       discard_rest_of_line ();
1417       return;
1418
1419     case (int) directive_density:
1420       as_warn (_(".end [no-]density is ignored"));
1421       demand_empty_rest_of_line ();
1422       break;
1423
1424     case (int) directive_absolute_literals:
1425       if (!absolute_literals_supported && !end_negated)
1426         {
1427           as_warn (_("Xtensa absolute literals option not supported; ignored"));
1428           demand_empty_rest_of_line ();
1429           return;
1430         }
1431       break;
1432
1433     default:
1434       break;
1435     }
1436
1437   state_ptr = &state; /* use state_ptr to avoid type-punning warning */
1438   directive_pop (&begin_directive, &begin_negated, &file, &line,
1439                  (const void **) state_ptr);
1440
1441   if (begin_directive != directive_none)
1442     {
1443       if (begin_directive != end_directive || begin_negated != end_negated)
1444         {
1445           as_bad (_("does not match begin %s%s at %s:%d"),
1446                   begin_negated ? "no-" : "",
1447                   directive_info[begin_directive].name, file, line);
1448         }
1449       else
1450         {
1451           switch (end_directive)
1452             {
1453             case directive_literal:
1454               frag_var (rs_fill, 0, 0, 0, NULL, 0, NULL);
1455               xtensa_restore_emit_state (state);
1456               xtensa_set_frag_assembly_state (frag_now);
1457               free (state);
1458               if (!inside_directive (directive_literal))
1459                 {
1460                   /* Restore the list of current labels.  */
1461                   xtensa_clear_insn_labels ();
1462                   insn_labels = saved_insn_labels;
1463                 }
1464               break;
1465
1466             case directive_literal_prefix:
1467               /* Restore the default collection sections from saved state.  */
1468               s = (lit_state *) state;
1469               gas_assert (s);
1470               default_lit_sections = *s;
1471
1472               /* Free the state storage.  */
1473               free (s->lit_prefix);
1474               free (s);
1475               break;
1476
1477             case directive_schedule:
1478             case directive_freeregs:
1479               break;
1480
1481             default:
1482               xtensa_set_frag_assembly_state (frag_now);
1483               break;
1484             }
1485         }
1486     }
1487
1488   demand_empty_rest_of_line ();
1489 }
1490
1491
1492 /* Place an aligned literal fragment at the current location.  */
1493
1494 static void
1495 xtensa_literal_position (int ignore ATTRIBUTE_UNUSED)
1496 {
1497   md_flush_pending_output ();
1498
1499   if (inside_directive (directive_literal))
1500     as_warn (_(".literal_position inside literal directive; ignoring"));
1501   xtensa_mark_literal_pool_location ();
1502
1503   demand_empty_rest_of_line ();
1504   xtensa_clear_insn_labels ();
1505 }
1506
1507
1508 /* Support .literal label, expr, ...  */
1509
1510 static void
1511 xtensa_literal_pseudo (int ignored ATTRIBUTE_UNUSED)
1512 {
1513   emit_state state;
1514   char *p, *base_name;
1515   char c;
1516   segT dest_seg;
1517
1518   if (inside_directive (directive_literal))
1519     {
1520       as_bad (_(".literal not allowed inside .begin literal region"));
1521       ignore_rest_of_line ();
1522       return;
1523     }
1524
1525   md_flush_pending_output ();
1526
1527   /* Previous labels go with whatever follows this directive, not with
1528      the literal, so save them now.  */
1529   saved_insn_labels = insn_labels;
1530   insn_labels = NULL;
1531
1532   /* If we are using text-section literals, then this is the right value... */
1533   dest_seg = now_seg;
1534
1535   base_name = input_line_pointer;
1536
1537   xtensa_switch_to_literal_fragment (&state);
1538
1539   /* ...but if we aren't using text-section-literals, then we
1540      need to put them in the section we just switched to.  */
1541   if (use_literal_section || directive_state[directive_absolute_literals])
1542     dest_seg = now_seg;
1543
1544   /* FIXME, despite the previous comments, dest_seg is unused...  */
1545   (void) dest_seg;
1546
1547   /* All literals are aligned to four-byte boundaries.  */
1548   frag_align (2, 0, 0);
1549   record_alignment (now_seg, 2);
1550
1551   c = get_symbol_name (&base_name);
1552   /* Just after name is now '\0'.  */
1553   p = input_line_pointer;
1554   *p = c;
1555   SKIP_WHITESPACE_AFTER_NAME ();
1556
1557   if (*input_line_pointer != ',' && *input_line_pointer != ':')
1558     {
1559       as_bad (_("expected comma or colon after symbol name; "
1560                 "rest of line ignored"));
1561       ignore_rest_of_line ();
1562       xtensa_restore_emit_state (&state);
1563       return;
1564     }
1565
1566   *p = 0;
1567   colon (base_name);
1568   *p = c;
1569
1570   input_line_pointer++;         /* skip ',' or ':' */
1571
1572   xtensa_elf_cons (4);
1573
1574   xtensa_restore_emit_state (&state);
1575
1576   /* Restore the list of current labels.  */
1577   xtensa_clear_insn_labels ();
1578   insn_labels = saved_insn_labels;
1579 }
1580
1581
1582 static void
1583 xtensa_literal_prefix (void)
1584 {
1585   char *name;
1586   int len;
1587
1588   /* Parse the new prefix from the input_line_pointer.  */
1589   SKIP_WHITESPACE ();
1590   len = strspn (input_line_pointer,
1591                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1592                 "abcdefghijklmnopqrstuvwxyz_/0123456789.$");
1593
1594   /* Get a null-terminated copy of the name.  */
1595   name = xmalloc (len + 1);
1596   gas_assert (name);
1597   strncpy (name, input_line_pointer, len);
1598   name[len] = 0;
1599
1600   /* Skip the name in the input line.  */
1601   input_line_pointer += len;
1602
1603   default_lit_sections.lit_prefix = name;
1604
1605   /* Clear cached literal sections, since the prefix has changed.  */
1606   default_lit_sections.lit_seg = NULL;
1607   default_lit_sections.lit4_seg = NULL;
1608 }
1609
1610
1611 /* Support ".frequency branch_target_frequency fall_through_frequency".  */
1612
1613 static void
1614 xtensa_frequency_pseudo (int ignored ATTRIBUTE_UNUSED)
1615 {
1616   float fall_through_f, target_f;
1617
1618   fall_through_f = (float) strtod (input_line_pointer, &input_line_pointer);
1619   if (fall_through_f < 0)
1620     {
1621       as_bad (_("fall through frequency must be greater than 0"));
1622       ignore_rest_of_line ();
1623       return;
1624     }
1625
1626   target_f = (float) strtod (input_line_pointer, &input_line_pointer);
1627   if (target_f < 0)
1628     {
1629       as_bad (_("branch target frequency must be greater than 0"));
1630       ignore_rest_of_line ();
1631       return;
1632     }
1633
1634   set_subseg_freq (now_seg, now_subseg, target_f + fall_through_f, target_f);
1635
1636   demand_empty_rest_of_line ();
1637 }
1638
1639
1640 /* Like normal .long/.short/.word, except support @plt, etc.
1641    Clobbers input_line_pointer, checks end-of-line.  */
1642
1643 static void
1644 xtensa_elf_cons (int nbytes)
1645 {
1646   expressionS exp;
1647   bfd_reloc_code_real_type reloc;
1648
1649   md_flush_pending_output ();
1650
1651   if (cur_vinsn.inside_bundle)
1652     as_bad (_("directives are not valid inside bundles"));
1653
1654   if (is_it_end_of_statement ())
1655     {
1656       demand_empty_rest_of_line ();
1657       return;
1658     }
1659
1660   do
1661     {
1662       expression (&exp);
1663       if (exp.X_op == O_symbol
1664           && *input_line_pointer == '@'
1665           && ((reloc = xtensa_elf_suffix (&input_line_pointer, &exp))
1666               != BFD_RELOC_NONE))
1667         {
1668           reloc_howto_type *reloc_howto =
1669             bfd_reloc_type_lookup (stdoutput, reloc);
1670
1671           if (reloc == BFD_RELOC_UNUSED || !reloc_howto)
1672             as_bad (_("unsupported relocation"));
1673           else if ((reloc >= BFD_RELOC_XTENSA_SLOT0_OP
1674                     && reloc <= BFD_RELOC_XTENSA_SLOT14_OP)
1675                    || (reloc >= BFD_RELOC_XTENSA_SLOT0_ALT
1676                        && reloc <= BFD_RELOC_XTENSA_SLOT14_ALT))
1677             as_bad (_("opcode-specific %s relocation used outside "
1678                       "an instruction"), reloc_howto->name);
1679           else if (nbytes != (int) bfd_get_reloc_size (reloc_howto))
1680             as_bad (_("%s relocations do not fit in %d bytes"),
1681                     reloc_howto->name, nbytes);
1682           else if (reloc == BFD_RELOC_XTENSA_TLS_FUNC
1683                    || reloc == BFD_RELOC_XTENSA_TLS_ARG
1684                    || reloc == BFD_RELOC_XTENSA_TLS_CALL)
1685             as_bad (_("invalid use of %s relocation"), reloc_howto->name);
1686           else
1687             {
1688               char *p = frag_more ((int) nbytes);
1689               xtensa_set_frag_assembly_state (frag_now);
1690               fix_new_exp (frag_now, p - frag_now->fr_literal,
1691                            nbytes, &exp, reloc_howto->pc_relative, reloc);
1692             }
1693         }
1694       else
1695         {
1696           xtensa_set_frag_assembly_state (frag_now);
1697           emit_expr (&exp, (unsigned int) nbytes);
1698         }
1699     }
1700   while (*input_line_pointer++ == ',');
1701
1702   input_line_pointer--;         /* Put terminator back into stream.  */
1703   demand_empty_rest_of_line ();
1704 }
1705
1706 static bfd_boolean is_leb128_expr;
1707
1708 static void
1709 xtensa_leb128 (int sign)
1710 {
1711   is_leb128_expr = TRUE;
1712   s_leb128 (sign);
1713   is_leb128_expr = FALSE;
1714 }
1715
1716 \f
1717 /* Parsing and Idiom Translation.  */
1718
1719 /* Parse @plt, etc. and return the desired relocation.  */
1720 static bfd_reloc_code_real_type
1721 xtensa_elf_suffix (char **str_p, expressionS *exp_p)
1722 {
1723   char ident[20];
1724   char *str = *str_p;
1725   char *str2;
1726   int ch;
1727   int len;
1728   struct suffix_reloc_map *ptr;
1729
1730   if (*str++ != '@')
1731     return BFD_RELOC_NONE;
1732
1733   for (ch = *str, str2 = ident;
1734        (str2 < ident + sizeof (ident) - 1
1735         && (ISALNUM (ch) || ch == '@'));
1736        ch = *++str)
1737     {
1738       *str2++ = (ISLOWER (ch)) ? ch : TOLOWER (ch);
1739     }
1740
1741   *str2 = '\0';
1742   len = str2 - ident;
1743
1744   ch = ident[0];
1745   for (ptr = &suffix_relocs[0]; ptr->length > 0; ptr++)
1746     if (ch == ptr->suffix[0]
1747         && len == ptr->length
1748         && memcmp (ident, ptr->suffix, ptr->length) == 0)
1749       {
1750         /* Now check for "identifier@suffix+constant".  */
1751         if (*str == '-' || *str == '+')
1752           {
1753             char *orig_line = input_line_pointer;
1754             expressionS new_exp;
1755
1756             input_line_pointer = str;
1757             expression (&new_exp);
1758             if (new_exp.X_op == O_constant)
1759               {
1760                 exp_p->X_add_number += new_exp.X_add_number;
1761                 str = input_line_pointer;
1762               }
1763
1764             if (&input_line_pointer != str_p)
1765               input_line_pointer = orig_line;
1766           }
1767
1768         *str_p = str;
1769         return ptr->reloc;
1770       }
1771
1772   return BFD_RELOC_UNUSED;
1773 }
1774
1775
1776 /* Find the matching operator type.  */
1777 static unsigned char
1778 map_suffix_reloc_to_operator (bfd_reloc_code_real_type reloc)
1779 {
1780   struct suffix_reloc_map *sfx;
1781   unsigned char operator = (unsigned char) -1;
1782
1783   for (sfx = &suffix_relocs[0]; sfx->suffix; sfx++)
1784     {
1785       if (sfx->reloc == reloc)
1786         {
1787           operator = sfx->operator;
1788           break;
1789         }
1790     }
1791   gas_assert (operator != (unsigned char) -1);
1792   return operator;
1793 }
1794
1795
1796 /* Find the matching reloc type.  */
1797 static bfd_reloc_code_real_type
1798 map_operator_to_reloc (unsigned char operator, bfd_boolean is_literal)
1799 {
1800   struct suffix_reloc_map *sfx;
1801   bfd_reloc_code_real_type reloc = BFD_RELOC_UNUSED;
1802
1803   for (sfx = &suffix_relocs[0]; sfx->suffix; sfx++)
1804     {
1805       if (sfx->operator == operator)
1806         {
1807           reloc = sfx->reloc;
1808           break;
1809         }
1810     }
1811
1812   if (is_literal)
1813     {
1814       if (reloc == BFD_RELOC_XTENSA_TLS_FUNC)
1815         return BFD_RELOC_XTENSA_TLSDESC_FN;
1816       else if (reloc == BFD_RELOC_XTENSA_TLS_ARG)
1817         return BFD_RELOC_XTENSA_TLSDESC_ARG;
1818     }
1819
1820   if (reloc == BFD_RELOC_UNUSED)
1821     return BFD_RELOC_32;
1822
1823   return reloc;
1824 }
1825
1826
1827 static const char *
1828 expression_end (const char *name)
1829 {
1830   while (1)
1831     {
1832       switch (*name)
1833         {
1834         case '}':
1835         case ';':
1836         case '\0':
1837         case ',':
1838         case ':':
1839           return name;
1840         case ' ':
1841         case '\t':
1842           ++name;
1843           continue;
1844         default:
1845           return 0;
1846         }
1847     }
1848 }
1849
1850
1851 #define ERROR_REG_NUM ((unsigned) -1)
1852
1853 static unsigned
1854 tc_get_register (const char *prefix)
1855 {
1856   unsigned reg;
1857   const char *next_expr;
1858   const char *old_line_pointer;
1859
1860   SKIP_WHITESPACE ();
1861   old_line_pointer = input_line_pointer;
1862
1863   if (*input_line_pointer == '$')
1864     ++input_line_pointer;
1865
1866   /* Accept "sp" as a synonym for "a1".  */
1867   if (input_line_pointer[0] == 's' && input_line_pointer[1] == 'p'
1868       && expression_end (input_line_pointer + 2))
1869     {
1870       input_line_pointer += 2;
1871       return 1;  /* AR[1] */
1872     }
1873
1874   while (*input_line_pointer++ == *prefix++)
1875     ;
1876   --input_line_pointer;
1877   --prefix;
1878
1879   if (*prefix)
1880     {
1881       as_bad (_("bad register name: %s"), old_line_pointer);
1882       return ERROR_REG_NUM;
1883     }
1884
1885   if (!ISDIGIT ((unsigned char) *input_line_pointer))
1886     {
1887       as_bad (_("bad register number: %s"), input_line_pointer);
1888       return ERROR_REG_NUM;
1889     }
1890
1891   reg = 0;
1892
1893   while (ISDIGIT ((int) *input_line_pointer))
1894     reg = reg * 10 + *input_line_pointer++ - '0';
1895
1896   if (!(next_expr = expression_end (input_line_pointer)))
1897     {
1898       as_bad (_("bad register name: %s"), old_line_pointer);
1899       return ERROR_REG_NUM;
1900     }
1901
1902   input_line_pointer = (char *) next_expr;
1903
1904   return reg;
1905 }
1906
1907
1908 static void
1909 expression_maybe_register (xtensa_opcode opc, int opnd, expressionS *tok)
1910 {
1911   xtensa_isa isa = xtensa_default_isa;
1912
1913   /* Check if this is an immediate operand.  */
1914   if (xtensa_operand_is_register (isa, opc, opnd) == 0)
1915     {
1916       bfd_reloc_code_real_type reloc;
1917       segT t = expression (tok);
1918
1919       if (t == absolute_section
1920           && xtensa_operand_is_PCrelative (isa, opc, opnd) == 1)
1921         {
1922           gas_assert (tok->X_op == O_constant);
1923           tok->X_op = O_symbol;
1924           tok->X_add_symbol = &abs_symbol;
1925         }
1926
1927       if ((tok->X_op == O_constant || tok->X_op == O_symbol)
1928           && ((reloc = xtensa_elf_suffix (&input_line_pointer, tok))
1929               != BFD_RELOC_NONE))
1930         {
1931           switch (reloc)
1932             {
1933             case BFD_RELOC_LO16:
1934               if (tok->X_op == O_constant)
1935                 {
1936                   tok->X_add_number &= 0xffff;
1937                   return;
1938                 }
1939               break;
1940             case BFD_RELOC_HI16:
1941               if (tok->X_op == O_constant)
1942                 {
1943                   tok->X_add_number = ((unsigned) tok->X_add_number) >> 16;
1944                   return;
1945                 }
1946               break;
1947             case BFD_RELOC_UNUSED:
1948               as_bad (_("unsupported relocation"));
1949               return;
1950             case BFD_RELOC_32_PCREL:
1951               as_bad (_("pcrel relocation not allowed in an instruction"));
1952               return;
1953             default:
1954               break;
1955             }
1956           tok->X_op = map_suffix_reloc_to_operator (reloc);
1957         }
1958     }
1959   else
1960     {
1961       xtensa_regfile opnd_rf = xtensa_operand_regfile (isa, opc, opnd);
1962       unsigned reg = tc_get_register (xtensa_regfile_shortname (isa, opnd_rf));
1963
1964       if (reg != ERROR_REG_NUM) /* Already errored */
1965         {
1966           uint32 buf = reg;
1967           if (xtensa_operand_encode (isa, opc, opnd, &buf))
1968             as_bad (_("register number out of range"));
1969         }
1970
1971       tok->X_op = O_register;
1972       tok->X_add_symbol = 0;
1973       tok->X_add_number = reg;
1974     }
1975 }
1976
1977
1978 /* Split up the arguments for an opcode or pseudo-op.  */
1979
1980 static int
1981 tokenize_arguments (char **args, char *str)
1982 {
1983   char *old_input_line_pointer;
1984   bfd_boolean saw_comma = FALSE;
1985   bfd_boolean saw_arg = FALSE;
1986   bfd_boolean saw_colon = FALSE;
1987   int num_args = 0;
1988   char *arg_end, *arg;
1989   int arg_len;
1990
1991   /* Save and restore input_line_pointer around this function.  */
1992   old_input_line_pointer = input_line_pointer;
1993   input_line_pointer = str;
1994
1995   while (*input_line_pointer)
1996     {
1997       SKIP_WHITESPACE ();
1998       switch (*input_line_pointer)
1999         {
2000         case '\0':
2001         case '}':
2002           goto fini;
2003
2004         case ':':
2005           input_line_pointer++;
2006           if (saw_comma || saw_colon || !saw_arg)
2007             goto err;
2008           saw_colon = TRUE;
2009           break;
2010
2011         case ',':
2012           input_line_pointer++;
2013           if (saw_comma || saw_colon || !saw_arg)
2014             goto err;
2015           saw_comma = TRUE;
2016           break;
2017
2018         default:
2019           if (!saw_comma && !saw_colon && saw_arg)
2020             goto err;
2021
2022           arg_end = input_line_pointer + 1;
2023           while (!expression_end (arg_end))
2024             arg_end += 1;
2025
2026           arg_len = arg_end - input_line_pointer;
2027           arg = (char *) xmalloc ((saw_colon ? 1 : 0) + arg_len + 1);
2028           args[num_args] = arg;
2029
2030           if (saw_colon)
2031             *arg++ = ':';
2032           strncpy (arg, input_line_pointer, arg_len);
2033           arg[arg_len] = '\0';
2034
2035           input_line_pointer = arg_end;
2036           num_args += 1;
2037           saw_comma = FALSE;
2038           saw_colon = FALSE;
2039           saw_arg = TRUE;
2040           break;
2041         }
2042     }
2043
2044 fini:
2045   if (saw_comma || saw_colon)
2046     goto err;
2047   input_line_pointer = old_input_line_pointer;
2048   return num_args;
2049
2050 err:
2051   if (saw_comma)
2052     as_bad (_("extra comma"));
2053   else if (saw_colon)
2054     as_bad (_("extra colon"));
2055   else if (!saw_arg)
2056     as_bad (_("missing argument"));
2057   else
2058     as_bad (_("missing comma or colon"));
2059   input_line_pointer = old_input_line_pointer;
2060   return -1;
2061 }
2062
2063
2064 /* Parse the arguments to an opcode.  Return TRUE on error.  */
2065
2066 static bfd_boolean
2067 parse_arguments (TInsn *insn, int num_args, char **arg_strings)
2068 {
2069   expressionS *tok, *last_tok;
2070   xtensa_opcode opcode = insn->opcode;
2071   bfd_boolean had_error = TRUE;
2072   xtensa_isa isa = xtensa_default_isa;
2073   int n, num_regs = 0;
2074   int opcode_operand_count;
2075   int opnd_cnt, last_opnd_cnt;
2076   unsigned int next_reg = 0;
2077   char *old_input_line_pointer;
2078
2079   if (insn->insn_type == ITYPE_LITERAL)
2080     opcode_operand_count = 1;
2081   else
2082     opcode_operand_count = xtensa_opcode_num_operands (isa, opcode);
2083
2084   tok = insn->tok;
2085   memset (tok, 0, sizeof (*tok) * MAX_INSN_ARGS);
2086
2087   /* Save and restore input_line_pointer around this function.  */
2088   old_input_line_pointer = input_line_pointer;
2089
2090   last_tok = 0;
2091   last_opnd_cnt = -1;
2092   opnd_cnt = 0;
2093
2094   /* Skip invisible operands.  */
2095   while (xtensa_operand_is_visible (isa, opcode, opnd_cnt) == 0)
2096     {
2097       opnd_cnt += 1;
2098       tok++;
2099     }
2100
2101   for (n = 0; n < num_args; n++)
2102     {
2103       input_line_pointer = arg_strings[n];
2104       if (*input_line_pointer == ':')
2105         {
2106           xtensa_regfile opnd_rf;
2107           input_line_pointer++;
2108           if (num_regs == 0)
2109             goto err;
2110           gas_assert (opnd_cnt > 0);
2111           num_regs--;
2112           opnd_rf = xtensa_operand_regfile (isa, opcode, last_opnd_cnt);
2113           if (next_reg
2114               != tc_get_register (xtensa_regfile_shortname (isa, opnd_rf)))
2115             as_warn (_("incorrect register number, ignoring"));
2116           next_reg++;
2117         }
2118       else
2119         {
2120           if (opnd_cnt >= opcode_operand_count)
2121             {
2122               as_warn (_("too many arguments"));
2123               goto err;
2124             }
2125           gas_assert (opnd_cnt < MAX_INSN_ARGS);
2126
2127           expression_maybe_register (opcode, opnd_cnt, tok);
2128           next_reg = tok->X_add_number + 1;
2129
2130           if (tok->X_op == O_illegal || tok->X_op == O_absent)
2131             goto err;
2132           if (xtensa_operand_is_register (isa, opcode, opnd_cnt) == 1)
2133             {
2134               num_regs = xtensa_operand_num_regs (isa, opcode, opnd_cnt) - 1;
2135               /* minus 1 because we are seeing one right now */
2136             }
2137           else
2138             num_regs = 0;
2139
2140           last_tok = tok;
2141           last_opnd_cnt = opnd_cnt;
2142           demand_empty_rest_of_line ();
2143
2144           do
2145             {
2146               opnd_cnt += 1;
2147               tok++;
2148             }
2149           while (xtensa_operand_is_visible (isa, opcode, opnd_cnt) == 0);
2150         }
2151     }
2152
2153   if (num_regs > 0 && ((int) next_reg != last_tok->X_add_number + 1))
2154     goto err;
2155
2156   insn->ntok = tok - insn->tok;
2157   had_error = FALSE;
2158
2159  err:
2160   input_line_pointer = old_input_line_pointer;
2161   return had_error;
2162 }
2163
2164
2165 static int
2166 get_invisible_operands (TInsn *insn)
2167 {
2168   xtensa_isa isa = xtensa_default_isa;
2169   static xtensa_insnbuf slotbuf = NULL;
2170   xtensa_format fmt;
2171   xtensa_opcode opc = insn->opcode;
2172   int slot, opnd, fmt_found;
2173   unsigned val;
2174
2175   if (!slotbuf)
2176     slotbuf = xtensa_insnbuf_alloc (isa);
2177
2178   /* Find format/slot where this can be encoded.  */
2179   fmt_found = 0;
2180   slot = 0;
2181   for (fmt = 0; fmt < xtensa_isa_num_formats (isa); fmt++)
2182     {
2183       for (slot = 0; slot < xtensa_format_num_slots (isa, fmt); slot++)
2184         {
2185           if (xtensa_opcode_encode (isa, fmt, slot, slotbuf, opc) == 0)
2186             {
2187               fmt_found = 1;
2188               break;
2189             }
2190         }
2191       if (fmt_found) break;
2192     }
2193
2194   if (!fmt_found)
2195     {
2196       as_bad (_("cannot encode opcode \"%s\""), xtensa_opcode_name (isa, opc));
2197       return -1;
2198     }
2199
2200   /* First encode all the visible operands
2201      (to deal with shared field operands).  */
2202   for (opnd = 0; opnd < insn->ntok; opnd++)
2203     {
2204       if (xtensa_operand_is_visible (isa, opc, opnd) == 1
2205           && (insn->tok[opnd].X_op == O_register
2206               || insn->tok[opnd].X_op == O_constant))
2207         {
2208           val = insn->tok[opnd].X_add_number;
2209           xtensa_operand_encode (isa, opc, opnd, &val);
2210           xtensa_operand_set_field (isa, opc, opnd, fmt, slot, slotbuf, val);
2211         }
2212     }
2213
2214   /* Then pull out the values for the invisible ones.  */
2215   for (opnd = 0; opnd < insn->ntok; opnd++)
2216     {
2217       if (xtensa_operand_is_visible (isa, opc, opnd) == 0)
2218         {
2219           xtensa_operand_get_field (isa, opc, opnd, fmt, slot, slotbuf, &val);
2220           xtensa_operand_decode (isa, opc, opnd, &val);
2221           insn->tok[opnd].X_add_number = val;
2222           if (xtensa_operand_is_register (isa, opc, opnd) == 1)
2223             insn->tok[opnd].X_op = O_register;
2224           else
2225             insn->tok[opnd].X_op = O_constant;
2226         }
2227     }
2228
2229   return 0;
2230 }
2231
2232
2233 static void
2234 xg_reverse_shift_count (char **cnt_argp)
2235 {
2236   char *cnt_arg, *new_arg;
2237   cnt_arg = *cnt_argp;
2238
2239   /* replace the argument with "31-(argument)" */
2240   new_arg = (char *) xmalloc (strlen (cnt_arg) + 6);
2241   sprintf (new_arg, "31-(%s)", cnt_arg);
2242
2243   free (cnt_arg);
2244   *cnt_argp = new_arg;
2245 }
2246
2247
2248 /* If "arg" is a constant expression, return non-zero with the value
2249    in *valp.  */
2250
2251 static int
2252 xg_arg_is_constant (char *arg, offsetT *valp)
2253 {
2254   expressionS exp;
2255   char *save_ptr = input_line_pointer;
2256
2257   input_line_pointer = arg;
2258   expression (&exp);
2259   input_line_pointer = save_ptr;
2260
2261   if (exp.X_op == O_constant)
2262     {
2263       *valp = exp.X_add_number;
2264       return 1;
2265     }
2266
2267   return 0;
2268 }
2269
2270
2271 static void
2272 xg_replace_opname (char **popname, const char *newop)
2273 {
2274   free (*popname);
2275   *popname = (char *) xmalloc (strlen (newop) + 1);
2276   strcpy (*popname, newop);
2277 }
2278
2279
2280 static int
2281 xg_check_num_args (int *pnum_args,
2282                    int expected_num,
2283                    char *opname,
2284                    char **arg_strings)
2285 {
2286   int num_args = *pnum_args;
2287
2288   if (num_args < expected_num)
2289     {
2290       as_bad (_("not enough operands (%d) for '%s'; expected %d"),
2291               num_args, opname, expected_num);
2292       return -1;
2293     }
2294
2295   if (num_args > expected_num)
2296     {
2297       as_warn (_("too many operands (%d) for '%s'; expected %d"),
2298                num_args, opname, expected_num);
2299       while (num_args-- > expected_num)
2300         {
2301           free (arg_strings[num_args]);
2302           arg_strings[num_args] = 0;
2303         }
2304       *pnum_args = expected_num;
2305       return -1;
2306     }
2307
2308   return 0;
2309 }
2310
2311
2312 /* If the register is not specified as part of the opcode,
2313    then get it from the operand and move it to the opcode.  */
2314
2315 static int
2316 xg_translate_sysreg_op (char **popname, int *pnum_args, char **arg_strings)
2317 {
2318   xtensa_isa isa = xtensa_default_isa;
2319   xtensa_sysreg sr;
2320   char *opname, *new_opname;
2321   const char *sr_name;
2322   int is_user, is_write;
2323
2324   opname = *popname;
2325   if (*opname == '_')
2326     opname += 1;
2327   is_user = (opname[1] == 'u');
2328   is_write = (opname[0] == 'w');
2329
2330   /* Opname == [rw]ur or [rwx]sr... */
2331
2332   if (xg_check_num_args (pnum_args, 2, opname, arg_strings))
2333     return -1;
2334
2335   /* Check if the argument is a symbolic register name.  */
2336   sr = xtensa_sysreg_lookup_name (isa, arg_strings[1]);
2337   /* Handle WSR to "INTSET" as a special case.  */
2338   if (sr == XTENSA_UNDEFINED && is_write && !is_user
2339       && !strcasecmp (arg_strings[1], "intset"))
2340     sr = xtensa_sysreg_lookup_name (isa, "interrupt");
2341   if (sr == XTENSA_UNDEFINED
2342       || (xtensa_sysreg_is_user (isa, sr) == 1) != is_user)
2343     {
2344       /* Maybe it's a register number.... */
2345       offsetT val;
2346       if (!xg_arg_is_constant (arg_strings[1], &val))
2347         {
2348           as_bad (_("invalid register '%s' for '%s' instruction"),
2349                   arg_strings[1], opname);
2350           return -1;
2351         }
2352       sr = xtensa_sysreg_lookup (isa, val, is_user);
2353       if (sr == XTENSA_UNDEFINED)
2354         {
2355           as_bad (_("invalid register number (%ld) for '%s' instruction"),
2356                   (long) val, opname);
2357           return -1;
2358         }
2359     }
2360
2361   /* Remove the last argument, which is now part of the opcode.  */
2362   free (arg_strings[1]);
2363   arg_strings[1] = 0;
2364   *pnum_args = 1;
2365
2366   /* Translate the opcode.  */
2367   sr_name = xtensa_sysreg_name (isa, sr);
2368   /* Another special case for "WSR.INTSET"....  */
2369   if (is_write && !is_user && !strcasecmp ("interrupt", sr_name))
2370     sr_name = "intset";
2371   new_opname = (char *) xmalloc (strlen (sr_name) + 6);
2372   sprintf (new_opname, "%s.%s", *popname, sr_name);
2373   free (*popname);
2374   *popname = new_opname;
2375
2376   return 0;
2377 }
2378
2379
2380 static int
2381 xtensa_translate_old_userreg_ops (char **popname)
2382 {
2383   xtensa_isa isa = xtensa_default_isa;
2384   xtensa_sysreg sr;
2385   char *opname, *new_opname;
2386   const char *sr_name;
2387   bfd_boolean has_underbar = FALSE;
2388
2389   opname = *popname;
2390   if (opname[0] == '_')
2391     {
2392       has_underbar = TRUE;
2393       opname += 1;
2394     }
2395
2396   sr = xtensa_sysreg_lookup_name (isa, opname + 1);
2397   if (sr != XTENSA_UNDEFINED)
2398     {
2399       /* The new default name ("nnn") is different from the old default
2400          name ("URnnn").  The old default is handled below, and we don't
2401          want to recognize [RW]nnn, so do nothing if the name is the (new)
2402          default.  */
2403       static char namebuf[10];
2404       sprintf (namebuf, "%d", xtensa_sysreg_number (isa, sr));
2405       if (strcmp (namebuf, opname + 1) == 0)
2406         return 0;
2407     }
2408   else
2409     {
2410       offsetT val;
2411       char *end;
2412
2413       /* Only continue if the reg name is "URnnn".  */
2414       if (opname[1] != 'u' || opname[2] != 'r')
2415         return 0;
2416       val = strtoul (opname + 3, &end, 10);
2417       if (*end != '\0')
2418         return 0;
2419
2420       sr = xtensa_sysreg_lookup (isa, val, 1);
2421       if (sr == XTENSA_UNDEFINED)
2422         {
2423           as_bad (_("invalid register number (%ld) for '%s'"),
2424                   (long) val, opname);
2425           return -1;
2426         }
2427     }
2428
2429   /* Translate the opcode.  */
2430   sr_name = xtensa_sysreg_name (isa, sr);
2431   new_opname = (char *) xmalloc (strlen (sr_name) + 6);
2432   sprintf (new_opname, "%s%cur.%s", (has_underbar ? "_" : ""),
2433            opname[0], sr_name);
2434   free (*popname);
2435   *popname = new_opname;
2436
2437   return 0;
2438 }
2439
2440
2441 static int
2442 xtensa_translate_zero_immed (const char *old_op,
2443                              const char *new_op,
2444                              char **popname,
2445                              int *pnum_args,
2446                              char **arg_strings)
2447 {
2448   char *opname;
2449   offsetT val;
2450
2451   opname = *popname;
2452   gas_assert (opname[0] != '_');
2453
2454   if (strcmp (opname, old_op) != 0)
2455     return 0;
2456
2457   if (xg_check_num_args (pnum_args, 3, opname, arg_strings))
2458     return -1;
2459   if (xg_arg_is_constant (arg_strings[1], &val) && val == 0)
2460     {
2461       xg_replace_opname (popname, new_op);
2462       free (arg_strings[1]);
2463       arg_strings[1] = arg_strings[2];
2464       arg_strings[2] = 0;
2465       *pnum_args = 2;
2466     }
2467
2468   return 0;
2469 }
2470
2471
2472 /* If the instruction is an idiom (i.e., a built-in macro), translate it.
2473    Returns non-zero if an error was found.  */
2474
2475 static int
2476 xg_translate_idioms (char **popname, int *pnum_args, char **arg_strings)
2477 {
2478   char *opname = *popname;
2479   bfd_boolean has_underbar = FALSE;
2480
2481   if (*opname == '_')
2482     {
2483       has_underbar = TRUE;
2484       opname += 1;
2485     }
2486
2487   if (strcmp (opname, "mov") == 0)
2488     {
2489       if (use_transform () && !has_underbar && density_supported)
2490         xg_replace_opname (popname, "mov.n");
2491       else
2492         {
2493           if (xg_check_num_args (pnum_args, 2, opname, arg_strings))
2494             return -1;
2495           xg_replace_opname (popname, (has_underbar ? "_or" : "or"));
2496           arg_strings[2] = (char *) xmalloc (strlen (arg_strings[1]) + 1);
2497           strcpy (arg_strings[2], arg_strings[1]);
2498           *pnum_args = 3;
2499         }
2500       return 0;
2501     }
2502
2503   if (strcmp (opname, "bbsi.l") == 0)
2504     {
2505       if (xg_check_num_args (pnum_args, 3, opname, arg_strings))
2506         return -1;
2507       xg_replace_opname (popname, (has_underbar ? "_bbsi" : "bbsi"));
2508       if (target_big_endian)
2509         xg_reverse_shift_count (&arg_strings[1]);
2510       return 0;
2511     }
2512
2513   if (strcmp (opname, "bbci.l") == 0)
2514     {
2515       if (xg_check_num_args (pnum_args, 3, opname, arg_strings))
2516         return -1;
2517       xg_replace_opname (popname, (has_underbar ? "_bbci" : "bbci"));
2518       if (target_big_endian)
2519         xg_reverse_shift_count (&arg_strings[1]);
2520       return 0;
2521     }
2522
2523   /* Don't do anything special with NOPs inside FLIX instructions.  They
2524      are handled elsewhere.  Real NOP instructions are always available
2525      in configurations with FLIX, so this should never be an issue but
2526      check for it anyway.  */
2527   if (!cur_vinsn.inside_bundle && xtensa_nop_opcode == XTENSA_UNDEFINED
2528       && strcmp (opname, "nop") == 0)
2529     {
2530       if (use_transform () && !has_underbar && density_supported)
2531         xg_replace_opname (popname, "nop.n");
2532       else
2533         {
2534           if (xg_check_num_args (pnum_args, 0, opname, arg_strings))
2535             return -1;
2536           xg_replace_opname (popname, (has_underbar ? "_or" : "or"));
2537           arg_strings[0] = (char *) xmalloc (3);
2538           arg_strings[1] = (char *) xmalloc (3);
2539           arg_strings[2] = (char *) xmalloc (3);
2540           strcpy (arg_strings[0], "a1");
2541           strcpy (arg_strings[1], "a1");
2542           strcpy (arg_strings[2], "a1");
2543           *pnum_args = 3;
2544         }
2545       return 0;
2546     }
2547
2548   /* Recognize [RW]UR and [RWX]SR.  */
2549   if ((((opname[0] == 'r' || opname[0] == 'w')
2550         && (opname[1] == 'u' || opname[1] == 's'))
2551        || (opname[0] == 'x' && opname[1] == 's'))
2552       && opname[2] == 'r'
2553       && opname[3] == '\0')
2554     return xg_translate_sysreg_op (popname, pnum_args, arg_strings);
2555
2556   /* Backward compatibility for RUR and WUR: Recognize [RW]UR<nnn> and
2557      [RW]<name> if <name> is the non-default name of a user register.  */
2558   if ((opname[0] == 'r' || opname[0] == 'w')
2559       && xtensa_opcode_lookup (xtensa_default_isa, opname) == XTENSA_UNDEFINED)
2560     return xtensa_translate_old_userreg_ops (popname);
2561
2562   /* Relax branches that don't allow comparisons against an immediate value
2563      of zero to the corresponding branches with implicit zero immediates.  */
2564   if (!has_underbar && use_transform ())
2565     {
2566       if (xtensa_translate_zero_immed ("bnei", "bnez", popname,
2567                                        pnum_args, arg_strings))
2568         return -1;
2569
2570       if (xtensa_translate_zero_immed ("beqi", "beqz", popname,
2571                                        pnum_args, arg_strings))
2572         return -1;
2573
2574       if (xtensa_translate_zero_immed ("bgei", "bgez", popname,
2575                                        pnum_args, arg_strings))
2576         return -1;
2577
2578       if (xtensa_translate_zero_immed ("blti", "bltz", popname,
2579                                        pnum_args, arg_strings))
2580         return -1;
2581     }
2582
2583   return 0;
2584 }
2585
2586 \f
2587 /* Functions for dealing with the Xtensa ISA.  */
2588
2589 /* Currently the assembler only allows us to use a single target per
2590    fragment.  Because of this, only one operand for a given
2591    instruction may be symbolic.  If there is a PC-relative operand,
2592    the last one is chosen.  Otherwise, the result is the number of the
2593    last immediate operand, and if there are none of those, we fail and
2594    return -1.  */
2595
2596 static int
2597 get_relaxable_immed (xtensa_opcode opcode)
2598 {
2599   int last_immed = -1;
2600   int noperands, opi;
2601
2602   if (opcode == XTENSA_UNDEFINED)
2603     return -1;
2604
2605   noperands = xtensa_opcode_num_operands (xtensa_default_isa, opcode);
2606   for (opi = noperands - 1; opi >= 0; opi--)
2607     {
2608       if (xtensa_operand_is_visible (xtensa_default_isa, opcode, opi) == 0)
2609         continue;
2610       if (xtensa_operand_is_PCrelative (xtensa_default_isa, opcode, opi) == 1)
2611         return opi;
2612       if (last_immed == -1
2613           && xtensa_operand_is_register (xtensa_default_isa, opcode, opi) == 0)
2614         last_immed = opi;
2615     }
2616   return last_immed;
2617 }
2618
2619
2620 static xtensa_opcode
2621 get_opcode_from_buf (const char *buf, int slot)
2622 {
2623   static xtensa_insnbuf insnbuf = NULL;
2624   static xtensa_insnbuf slotbuf = NULL;
2625   xtensa_isa isa = xtensa_default_isa;
2626   xtensa_format fmt;
2627
2628   if (!insnbuf)
2629     {
2630       insnbuf = xtensa_insnbuf_alloc (isa);
2631       slotbuf = xtensa_insnbuf_alloc (isa);
2632     }
2633
2634   xtensa_insnbuf_from_chars (isa, insnbuf, (const unsigned char *) buf, 0);
2635   fmt = xtensa_format_decode (isa, insnbuf);
2636   if (fmt == XTENSA_UNDEFINED)
2637     return XTENSA_UNDEFINED;
2638
2639   if (slot >= xtensa_format_num_slots (isa, fmt))
2640     return XTENSA_UNDEFINED;
2641
2642   xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
2643   return xtensa_opcode_decode (isa, fmt, slot, slotbuf);
2644 }
2645
2646
2647 #ifdef TENSILICA_DEBUG
2648
2649 /* For debugging, print out the mapping of opcode numbers to opcodes.  */
2650
2651 static void
2652 xtensa_print_insn_table (void)
2653 {
2654   int num_opcodes, num_operands;
2655   xtensa_opcode opcode;
2656   xtensa_isa isa = xtensa_default_isa;
2657
2658   num_opcodes = xtensa_isa_num_opcodes (xtensa_default_isa);
2659   for (opcode = 0; opcode < num_opcodes; opcode++)
2660     {
2661       int opn;
2662       fprintf (stderr, "%d: %s: ", opcode, xtensa_opcode_name (isa, opcode));
2663       num_operands = xtensa_opcode_num_operands (isa, opcode);
2664       for (opn = 0; opn < num_operands; opn++)
2665         {
2666           if (xtensa_operand_is_visible (isa, opcode, opn) == 0)
2667             continue;
2668           if (xtensa_operand_is_register (isa, opcode, opn) == 1)
2669             {
2670               xtensa_regfile opnd_rf =
2671                 xtensa_operand_regfile (isa, opcode, opn);
2672               fprintf (stderr, "%s ", xtensa_regfile_shortname (isa, opnd_rf));
2673             }
2674           else if (xtensa_operand_is_PCrelative (isa, opcode, opn) == 1)
2675             fputs ("[lLr] ", stderr);
2676           else
2677             fputs ("i ", stderr);
2678         }
2679       fprintf (stderr, "\n");
2680     }
2681 }
2682
2683
2684 static void
2685 print_vliw_insn (xtensa_insnbuf vbuf)
2686 {
2687   xtensa_isa isa = xtensa_default_isa;
2688   xtensa_format f = xtensa_format_decode (isa, vbuf);
2689   xtensa_insnbuf sbuf = xtensa_insnbuf_alloc (isa);
2690   int op;
2691
2692   fprintf (stderr, "format = %d\n", f);
2693
2694   for (op = 0; op < xtensa_format_num_slots (isa, f); op++)
2695     {
2696       xtensa_opcode opcode;
2697       const char *opname;
2698       int operands;
2699
2700       xtensa_format_get_slot (isa, f, op, vbuf, sbuf);
2701       opcode = xtensa_opcode_decode (isa, f, op, sbuf);
2702       opname = xtensa_opcode_name (isa, opcode);
2703
2704       fprintf (stderr, "op in slot %i is %s;\n", op, opname);
2705       fprintf (stderr, "   operands = ");
2706       for (operands = 0;
2707            operands < xtensa_opcode_num_operands (isa, opcode);
2708            operands++)
2709         {
2710           unsigned int val;
2711           if (xtensa_operand_is_visible (isa, opcode, operands) == 0)
2712             continue;
2713           xtensa_operand_get_field (isa, opcode, operands, f, op, sbuf, &val);
2714           xtensa_operand_decode (isa, opcode, operands, &val);
2715           fprintf (stderr, "%d ", val);
2716         }
2717       fprintf (stderr, "\n");
2718     }
2719   xtensa_insnbuf_free (isa, sbuf);
2720 }
2721
2722 #endif /* TENSILICA_DEBUG */
2723
2724
2725 static bfd_boolean
2726 is_direct_call_opcode (xtensa_opcode opcode)
2727 {
2728   xtensa_isa isa = xtensa_default_isa;
2729   int n, num_operands;
2730
2731   if (xtensa_opcode_is_call (isa, opcode) != 1)
2732     return FALSE;
2733
2734   num_operands = xtensa_opcode_num_operands (isa, opcode);
2735   for (n = 0; n < num_operands; n++)
2736     {
2737       if (xtensa_operand_is_register (isa, opcode, n) == 0
2738           && xtensa_operand_is_PCrelative (isa, opcode, n) == 1)
2739         return TRUE;
2740     }
2741   return FALSE;
2742 }
2743
2744
2745 /* Convert from BFD relocation type code to slot and operand number.
2746    Returns non-zero on failure.  */
2747
2748 static int
2749 decode_reloc (bfd_reloc_code_real_type reloc, int *slot, bfd_boolean *is_alt)
2750 {
2751   if (reloc >= BFD_RELOC_XTENSA_SLOT0_OP
2752       && reloc <= BFD_RELOC_XTENSA_SLOT14_OP)
2753     {
2754       *slot = reloc - BFD_RELOC_XTENSA_SLOT0_OP;
2755       *is_alt = FALSE;
2756     }
2757   else if (reloc >= BFD_RELOC_XTENSA_SLOT0_ALT
2758       && reloc <= BFD_RELOC_XTENSA_SLOT14_ALT)
2759     {
2760       *slot = reloc - BFD_RELOC_XTENSA_SLOT0_ALT;
2761       *is_alt = TRUE;
2762     }
2763   else
2764     return -1;
2765
2766   return 0;
2767 }
2768
2769
2770 /* Convert from slot number to BFD relocation type code for the
2771    standard PC-relative relocations.  Return BFD_RELOC_NONE on
2772    failure.  */
2773
2774 static bfd_reloc_code_real_type
2775 encode_reloc (int slot)
2776 {
2777   if (slot < 0 || slot > 14)
2778     return BFD_RELOC_NONE;
2779
2780   return BFD_RELOC_XTENSA_SLOT0_OP + slot;
2781 }
2782
2783
2784 /* Convert from slot numbers to BFD relocation type code for the
2785    "alternate" relocations.  Return BFD_RELOC_NONE on failure.  */
2786
2787 static bfd_reloc_code_real_type
2788 encode_alt_reloc (int slot)
2789 {
2790   if (slot < 0 || slot > 14)
2791     return BFD_RELOC_NONE;
2792
2793   return BFD_RELOC_XTENSA_SLOT0_ALT + slot;
2794 }
2795
2796
2797 static void
2798 xtensa_insnbuf_set_operand (xtensa_insnbuf slotbuf,
2799                             xtensa_format fmt,
2800                             int slot,
2801                             xtensa_opcode opcode,
2802                             int operand,
2803                             uint32 value,
2804                             const char *file,
2805                             unsigned int line)
2806 {
2807   uint32 valbuf = value;
2808
2809   if (xtensa_operand_encode (xtensa_default_isa, opcode, operand, &valbuf))
2810     {
2811       if (xtensa_operand_is_PCrelative (xtensa_default_isa, opcode, operand)
2812           == 1)
2813         as_bad_where ((char *) file, line,
2814                       _("operand %d of '%s' has out of range value '%u'"),
2815                       operand + 1,
2816                       xtensa_opcode_name (xtensa_default_isa, opcode),
2817                       value);
2818       else
2819         as_bad_where ((char *) file, line,
2820                       _("operand %d of '%s' has invalid value '%u'"),
2821                       operand + 1,
2822                       xtensa_opcode_name (xtensa_default_isa, opcode),
2823                       value);
2824       return;
2825     }
2826
2827   xtensa_operand_set_field (xtensa_default_isa, opcode, operand, fmt, slot,
2828                             slotbuf, valbuf);
2829 }
2830
2831
2832 static uint32
2833 xtensa_insnbuf_get_operand (xtensa_insnbuf slotbuf,
2834                             xtensa_format fmt,
2835                             int slot,
2836                             xtensa_opcode opcode,
2837                             int opnum)
2838 {
2839   uint32 val = 0;
2840   (void) xtensa_operand_get_field (xtensa_default_isa, opcode, opnum,
2841                                    fmt, slot, slotbuf, &val);
2842   (void) xtensa_operand_decode (xtensa_default_isa, opcode, opnum, &val);
2843   return val;
2844 }
2845
2846 \f
2847 /* Checks for rules from xtensa-relax tables.  */
2848
2849 /* The routine xg_instruction_matches_option_term must return TRUE
2850    when a given option term is true.  The meaning of all of the option
2851    terms is given interpretation by this function.  */
2852
2853 static bfd_boolean
2854 xg_instruction_matches_option_term (TInsn *insn, const ReqOrOption *option)
2855 {
2856   if (strcmp (option->option_name, "realnop") == 0
2857       || strncmp (option->option_name, "IsaUse", 6) == 0)
2858     {
2859       /* These conditions were evaluated statically when building the
2860          relaxation table.  There's no need to reevaluate them now.  */
2861       return TRUE;
2862     }
2863   else if (strcmp (option->option_name, "FREEREG") == 0)
2864     return insn->extra_arg.X_op == O_register;
2865   else
2866     {
2867       as_fatal (_("internal error: unknown option name '%s'"),
2868                 option->option_name);
2869     }
2870 }
2871
2872
2873 static bfd_boolean
2874 xg_instruction_matches_or_options (TInsn *insn,
2875                                    const ReqOrOptionList *or_option)
2876 {
2877   const ReqOrOption *option;
2878   /* Must match each of the AND terms.  */
2879   for (option = or_option; option != NULL; option = option->next)
2880     {
2881       if (xg_instruction_matches_option_term (insn, option))
2882         return TRUE;
2883     }
2884   return FALSE;
2885 }
2886
2887
2888 static bfd_boolean
2889 xg_instruction_matches_options (TInsn *insn, const ReqOptionList *options)
2890 {
2891   const ReqOption *req_options;
2892   /* Must match each of the AND terms.  */
2893   for (req_options = options;
2894        req_options != NULL;
2895        req_options = req_options->next)
2896     {
2897       /* Must match one of the OR clauses.  */
2898       if (!xg_instruction_matches_or_options (insn,
2899                                               req_options->or_option_terms))
2900         return FALSE;
2901     }
2902   return TRUE;
2903 }
2904
2905
2906 /* Return the transition rule that matches or NULL if none matches.  */
2907
2908 static bfd_boolean
2909 xg_instruction_matches_rule (TInsn *insn, TransitionRule *rule)
2910 {
2911   PreconditionList *condition_l;
2912
2913   if (rule->opcode != insn->opcode)
2914     return FALSE;
2915
2916   for (condition_l = rule->conditions;
2917        condition_l != NULL;
2918        condition_l = condition_l->next)
2919     {
2920       expressionS *exp1;
2921       expressionS *exp2;
2922       Precondition *cond = condition_l->precond;
2923
2924       switch (cond->typ)
2925         {
2926         case OP_CONSTANT:
2927           /* The expression must be the constant.  */
2928           gas_assert (cond->op_num < insn->ntok);
2929           exp1 = &insn->tok[cond->op_num];
2930           if (expr_is_const (exp1))
2931             {
2932               switch (cond->cmp)
2933                 {
2934                 case OP_EQUAL:
2935                   if (get_expr_const (exp1) != cond->op_data)
2936                     return FALSE;
2937                   break;
2938                 case OP_NOTEQUAL:
2939                   if (get_expr_const (exp1) == cond->op_data)
2940                     return FALSE;
2941                   break;
2942                 default:
2943                   return FALSE;
2944                 }
2945             }
2946           else if (expr_is_register (exp1))
2947             {
2948               switch (cond->cmp)
2949                 {
2950                 case OP_EQUAL:
2951                   if (get_expr_register (exp1) != cond->op_data)
2952                     return FALSE;
2953                   break;
2954                 case OP_NOTEQUAL:
2955                   if (get_expr_register (exp1) == cond->op_data)
2956                     return FALSE;
2957                   break;
2958                 default:
2959                   return FALSE;
2960                 }
2961             }
2962           else
2963             return FALSE;
2964           break;
2965
2966         case OP_OPERAND:
2967           gas_assert (cond->op_num < insn->ntok);
2968           gas_assert (cond->op_data < insn->ntok);
2969           exp1 = &insn->tok[cond->op_num];
2970           exp2 = &insn->tok[cond->op_data];
2971
2972           switch (cond->cmp)
2973             {
2974             case OP_EQUAL:
2975               if (!expr_is_equal (exp1, exp2))
2976                 return FALSE;
2977               break;
2978             case OP_NOTEQUAL:
2979               if (expr_is_equal (exp1, exp2))
2980                 return FALSE;
2981               break;
2982             }
2983           break;
2984
2985         case OP_LITERAL:
2986         case OP_LABEL:
2987         default:
2988           return FALSE;
2989         }
2990     }
2991   if (!xg_instruction_matches_options (insn, rule->options))
2992     return FALSE;
2993
2994   return TRUE;
2995 }
2996
2997
2998 static int
2999 transition_rule_cmp (const TransitionRule *a, const TransitionRule *b)
3000 {
3001   bfd_boolean a_greater = FALSE;
3002   bfd_boolean b_greater = FALSE;
3003
3004   ReqOptionList *l_a = a->options;
3005   ReqOptionList *l_b = b->options;
3006
3007   /* We only care if they both are the same except for
3008      a const16 vs. an l32r.  */
3009
3010   while (l_a && l_b && ((l_a->next == NULL) == (l_b->next == NULL)))
3011     {
3012       ReqOrOptionList *l_or_a = l_a->or_option_terms;
3013       ReqOrOptionList *l_or_b = l_b->or_option_terms;
3014       while (l_or_a && l_or_b && ((l_a->next == NULL) == (l_b->next == NULL)))
3015         {
3016           if (l_or_a->is_true != l_or_b->is_true)
3017             return 0;
3018           if (strcmp (l_or_a->option_name, l_or_b->option_name) != 0)
3019             {
3020               /* This is the case we care about.  */
3021               if (strcmp (l_or_a->option_name, "IsaUseConst16") == 0
3022                   && strcmp (l_or_b->option_name, "IsaUseL32R") == 0)
3023                 {
3024                   if (prefer_const16)
3025                     a_greater = TRUE;
3026                   else
3027                     b_greater = TRUE;
3028                 }
3029               else if (strcmp (l_or_a->option_name, "IsaUseL32R") == 0
3030                        && strcmp (l_or_b->option_name, "IsaUseConst16") == 0)
3031                 {
3032                   if (prefer_const16)
3033                     b_greater = TRUE;
3034                   else
3035                     a_greater = TRUE;
3036                 }
3037               else
3038                 return 0;
3039             }
3040           l_or_a = l_or_a->next;
3041           l_or_b = l_or_b->next;
3042         }
3043       if (l_or_a || l_or_b)
3044         return 0;
3045
3046       l_a = l_a->next;
3047       l_b = l_b->next;
3048     }
3049   if (l_a || l_b)
3050     return 0;
3051
3052   /* Incomparable if the substitution was used differently in two cases.  */
3053   if (a_greater && b_greater)
3054     return 0;
3055
3056   if (b_greater)
3057     return 1;
3058   if (a_greater)
3059     return -1;
3060
3061   return 0;
3062 }
3063
3064
3065 static TransitionRule *
3066 xg_instruction_match (TInsn *insn)
3067 {
3068   TransitionTable *table = xg_build_simplify_table (&transition_rule_cmp);
3069   TransitionList *l;
3070   gas_assert (insn->opcode < table->num_opcodes);
3071
3072   /* Walk through all of the possible transitions.  */
3073   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
3074     {
3075       TransitionRule *rule = l->rule;
3076       if (xg_instruction_matches_rule (insn, rule))
3077         return rule;
3078     }
3079   return NULL;
3080 }
3081
3082 \f
3083 /* Various Other Internal Functions.  */
3084
3085 static bfd_boolean
3086 is_unique_insn_expansion (TransitionRule *r)
3087 {
3088   if (!r->to_instr || r->to_instr->next != NULL)
3089     return FALSE;
3090   if (r->to_instr->typ != INSTR_INSTR)
3091     return FALSE;
3092   return TRUE;
3093 }
3094
3095
3096 /* Check if there is exactly one relaxation for INSN that converts it to
3097    another instruction of equal or larger size.  If so, and if TARG is
3098    non-null, go ahead and generate the relaxed instruction into TARG.  If
3099    NARROW_ONLY is true, then only consider relaxations that widen a narrow
3100    instruction, i.e., ignore relaxations that convert to an instruction of
3101    equal size.  In some contexts where this function is used, only
3102    a single widening is allowed and the NARROW_ONLY argument is used to
3103    exclude cases like ADDI being "widened" to an ADDMI, which may
3104    later be relaxed to an ADDMI/ADDI pair.  */
3105
3106 bfd_boolean
3107 xg_is_single_relaxable_insn (TInsn *insn, TInsn *targ, bfd_boolean narrow_only)
3108 {
3109   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
3110   TransitionList *l;
3111   TransitionRule *match = 0;
3112
3113   gas_assert (insn->insn_type == ITYPE_INSN);
3114   gas_assert (insn->opcode < table->num_opcodes);
3115
3116   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
3117     {
3118       TransitionRule *rule = l->rule;
3119
3120       if (xg_instruction_matches_rule (insn, rule)
3121           && is_unique_insn_expansion (rule)
3122           && (xg_get_single_size (insn->opcode) + (narrow_only ? 1 : 0)
3123               <= xg_get_single_size (rule->to_instr->opcode)))
3124         {
3125           if (match)
3126             return FALSE;
3127           match = rule;
3128         }
3129     }
3130   if (!match)
3131     return FALSE;
3132
3133   if (targ)
3134     xg_build_to_insn (targ, insn, match->to_instr);
3135   return TRUE;
3136 }
3137
3138
3139 /* Return the maximum number of bytes this opcode can expand to.  */
3140
3141 static int
3142 xg_get_max_insn_widen_size (xtensa_opcode opcode)
3143 {
3144   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
3145   TransitionList *l;
3146   int max_size = xg_get_single_size (opcode);
3147
3148   gas_assert (opcode < table->num_opcodes);
3149
3150   for (l = table->table[opcode]; l != NULL; l = l->next)
3151     {
3152       TransitionRule *rule = l->rule;
3153       BuildInstr *build_list;
3154       int this_size = 0;
3155
3156       if (!rule)
3157         continue;
3158       build_list = rule->to_instr;
3159       if (is_unique_insn_expansion (rule))
3160         {
3161           gas_assert (build_list->typ == INSTR_INSTR);
3162           this_size = xg_get_max_insn_widen_size (build_list->opcode);
3163         }
3164       else
3165         for (; build_list != NULL; build_list = build_list->next)
3166           {
3167             switch (build_list->typ)
3168               {
3169               case INSTR_INSTR:
3170                 this_size += xg_get_single_size (build_list->opcode);
3171                 break;
3172               case INSTR_LITERAL_DEF:
3173               case INSTR_LABEL_DEF:
3174               default:
3175                 break;
3176               }
3177           }
3178       if (this_size > max_size)
3179         max_size = this_size;
3180     }
3181   return max_size;
3182 }
3183
3184
3185 /* Return the maximum number of literal bytes this opcode can generate.  */
3186
3187 static int
3188 xg_get_max_insn_widen_literal_size (xtensa_opcode opcode)
3189 {
3190   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
3191   TransitionList *l;
3192   int max_size = 0;
3193
3194   gas_assert (opcode < table->num_opcodes);
3195
3196   for (l = table->table[opcode]; l != NULL; l = l->next)
3197     {
3198       TransitionRule *rule = l->rule;
3199       BuildInstr *build_list;
3200       int this_size = 0;
3201
3202       if (!rule)
3203         continue;
3204       build_list = rule->to_instr;
3205       if (is_unique_insn_expansion (rule))
3206         {
3207           gas_assert (build_list->typ == INSTR_INSTR);
3208           this_size = xg_get_max_insn_widen_literal_size (build_list->opcode);
3209         }
3210       else
3211         for (; build_list != NULL; build_list = build_list->next)
3212           {
3213             switch (build_list->typ)
3214               {
3215               case INSTR_LITERAL_DEF:
3216                 /* Hard-coded 4-byte literal.  */
3217                 this_size += 4;
3218                 break;
3219               case INSTR_INSTR:
3220               case INSTR_LABEL_DEF:
3221               default:
3222                 break;
3223               }
3224           }
3225       if (this_size > max_size)
3226         max_size = this_size;
3227     }
3228   return max_size;
3229 }
3230
3231
3232 static bfd_boolean
3233 xg_is_relaxable_insn (TInsn *insn, int lateral_steps)
3234 {
3235   int steps_taken = 0;
3236   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
3237   TransitionList *l;
3238
3239   gas_assert (insn->insn_type == ITYPE_INSN);
3240   gas_assert (insn->opcode < table->num_opcodes);
3241
3242   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
3243     {
3244       TransitionRule *rule = l->rule;
3245
3246       if (xg_instruction_matches_rule (insn, rule))
3247         {
3248           if (steps_taken == lateral_steps)
3249             return TRUE;
3250           steps_taken++;
3251         }
3252     }
3253   return FALSE;
3254 }
3255
3256
3257 static symbolS *
3258 get_special_literal_symbol (void)
3259 {
3260   static symbolS *sym = NULL;
3261
3262   if (sym == NULL)
3263     sym = symbol_find_or_make ("SPECIAL_LITERAL0\001");
3264   return sym;
3265 }
3266
3267
3268 static symbolS *
3269 get_special_label_symbol (void)
3270 {
3271   static symbolS *sym = NULL;
3272
3273   if (sym == NULL)
3274     sym = symbol_find_or_make ("SPECIAL_LABEL0\001");
3275   return sym;
3276 }
3277
3278
3279 static bfd_boolean
3280 xg_valid_literal_expression (const expressionS *exp)
3281 {
3282   switch (exp->X_op)
3283     {
3284     case O_constant:
3285     case O_symbol:
3286     case O_big:
3287     case O_uminus:
3288     case O_subtract:
3289     case O_pltrel:
3290     case O_pcrel:
3291     case O_tlsfunc:
3292     case O_tlsarg:
3293     case O_tpoff:
3294     case O_dtpoff:
3295       return TRUE;
3296     default:
3297       return FALSE;
3298     }
3299 }
3300
3301
3302 /* This will check to see if the value can be converted into the
3303    operand type.  It will return TRUE if it does not fit.  */
3304
3305 static bfd_boolean
3306 xg_check_operand (int32 value, xtensa_opcode opcode, int operand)
3307 {
3308   uint32 valbuf = value;
3309   if (xtensa_operand_encode (xtensa_default_isa, opcode, operand, &valbuf))
3310     return TRUE;
3311   return FALSE;
3312 }
3313
3314
3315 /* Assumes: All immeds are constants.  Check that all constants fit
3316    into their immeds; return FALSE if not.  */
3317
3318 static bfd_boolean
3319 xg_immeds_fit (const TInsn *insn)
3320 {
3321   xtensa_isa isa = xtensa_default_isa;
3322   int i;
3323
3324   int n = insn->ntok;
3325   gas_assert (insn->insn_type == ITYPE_INSN);
3326   for (i = 0; i < n; ++i)
3327     {
3328       const expressionS *exp = &insn->tok[i];
3329
3330       if (xtensa_operand_is_register (isa, insn->opcode, i) == 1)
3331         continue;
3332
3333       switch (exp->X_op)
3334         {
3335         case O_register:
3336         case O_constant:
3337           if (xg_check_operand (exp->X_add_number, insn->opcode, i))
3338             return FALSE;
3339           break;
3340
3341         default:
3342           /* The symbol should have a fixup associated with it.  */
3343           gas_assert (FALSE);
3344           break;
3345         }
3346     }
3347   return TRUE;
3348 }
3349
3350
3351 /* This should only be called after we have an initial
3352    estimate of the addresses.  */
3353
3354 static bfd_boolean
3355 xg_symbolic_immeds_fit (const TInsn *insn,
3356                         segT pc_seg,
3357                         fragS *pc_frag,
3358                         offsetT pc_offset,
3359                         long stretch)
3360 {
3361   xtensa_isa isa = xtensa_default_isa;
3362   symbolS *symbolP;
3363   fragS *sym_frag;
3364   offsetT target, pc;
3365   uint32 new_offset;
3366   int i;
3367   int n = insn->ntok;
3368
3369   gas_assert (insn->insn_type == ITYPE_INSN);
3370
3371   for (i = 0; i < n; ++i)
3372     {
3373       const expressionS *exp = &insn->tok[i];
3374
3375       if (xtensa_operand_is_register (isa, insn->opcode, i) == 1)
3376         continue;
3377
3378       switch (exp->X_op)
3379         {
3380         case O_register:
3381         case O_constant:
3382           if (xg_check_operand (exp->X_add_number, insn->opcode, i))
3383             return FALSE;
3384           break;
3385
3386         case O_lo16:
3387         case O_hi16:
3388           /* Check for the worst case.  */
3389           if (xg_check_operand (0xffff, insn->opcode, i))
3390             return FALSE;
3391           break;
3392
3393         case O_symbol:
3394           /* We only allow symbols for PC-relative references.
3395              If pc_frag == 0, then we don't have frag locations yet.  */
3396           if (pc_frag == 0
3397               || xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 0)
3398             return FALSE;
3399
3400           /* If it is a weak symbol or a symbol in a different section,
3401              it cannot be known to fit at assembly time.  */
3402           if (S_IS_WEAK (exp->X_add_symbol)
3403               || S_GET_SEGMENT (exp->X_add_symbol) != pc_seg)
3404             {
3405               /* For a direct call with --no-longcalls, be optimistic and
3406                  assume it will be in range.  If the symbol is weak and
3407                  undefined, it may remain undefined at link-time, in which
3408                  case it will have a zero value and almost certainly be out
3409                  of range for a direct call; thus, relax for undefined weak
3410                  symbols even if longcalls is not enabled.  */
3411               if (is_direct_call_opcode (insn->opcode)
3412                   && ! pc_frag->tc_frag_data.use_longcalls
3413                   && (! S_IS_WEAK (exp->X_add_symbol)
3414                       || S_IS_DEFINED (exp->X_add_symbol)))
3415                 return TRUE;
3416
3417               return FALSE;
3418             }
3419
3420           symbolP = exp->X_add_symbol;
3421           sym_frag = symbol_get_frag (symbolP);
3422           target = S_GET_VALUE (symbolP) + exp->X_add_number;
3423           pc = pc_frag->fr_address + pc_offset;
3424
3425           /* If frag has yet to be reached on this pass, assume it
3426              will move by STRETCH just as we did.  If this is not so,
3427              it will be because some frag between grows, and that will
3428              force another pass.  Beware zero-length frags.  There
3429              should be a faster way to do this.  */
3430
3431           if (stretch != 0
3432               && sym_frag->relax_marker != pc_frag->relax_marker
3433               && S_GET_SEGMENT (symbolP) == pc_seg)
3434             {
3435               target += stretch;
3436             }
3437
3438           new_offset = target;
3439           xtensa_operand_do_reloc (isa, insn->opcode, i, &new_offset, pc);
3440           if (xg_check_operand (new_offset, insn->opcode, i))
3441             return FALSE;
3442           break;
3443
3444         default:
3445           /* The symbol should have a fixup associated with it.  */
3446           return FALSE;
3447         }
3448     }
3449
3450   return TRUE;
3451 }
3452
3453
3454 /* Return TRUE on success.  */
3455
3456 static bfd_boolean
3457 xg_build_to_insn (TInsn *targ, TInsn *insn, BuildInstr *bi)
3458 {
3459   BuildOp *op;
3460   symbolS *sym;
3461
3462   tinsn_init (targ);
3463   targ->debug_line = insn->debug_line;
3464   targ->loc_directive_seen = insn->loc_directive_seen;
3465   switch (bi->typ)
3466     {
3467     case INSTR_INSTR:
3468       op = bi->ops;
3469       targ->opcode = bi->opcode;
3470       targ->insn_type = ITYPE_INSN;
3471       targ->is_specific_opcode = FALSE;
3472
3473       for (; op != NULL; op = op->next)
3474         {
3475           int op_num = op->op_num;
3476           int op_data = op->op_data;
3477
3478           gas_assert (op->op_num < MAX_INSN_ARGS);
3479
3480           if (targ->ntok <= op_num)
3481             targ->ntok = op_num + 1;
3482
3483           switch (op->typ)
3484             {
3485             case OP_CONSTANT:
3486               set_expr_const (&targ->tok[op_num], op_data);
3487               break;
3488             case OP_OPERAND:
3489               gas_assert (op_data < insn->ntok);
3490               copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
3491               break;
3492             case OP_FREEREG:
3493               if (insn->extra_arg.X_op != O_register)
3494                 return FALSE;
3495               copy_expr (&targ->tok[op_num], &insn->extra_arg);
3496               break;
3497             case OP_LITERAL:
3498               sym = get_special_literal_symbol ();
3499               set_expr_symbol_offset (&targ->tok[op_num], sym, 0);
3500               if (insn->tok[op_data].X_op == O_tlsfunc
3501                   || insn->tok[op_data].X_op == O_tlsarg)
3502                 copy_expr (&targ->extra_arg, &insn->tok[op_data]);
3503               break;
3504             case OP_LABEL:
3505               sym = get_special_label_symbol ();
3506               set_expr_symbol_offset (&targ->tok[op_num], sym, 0);
3507               break;
3508             case OP_OPERAND_HI16U:
3509             case OP_OPERAND_LOW16U:
3510               gas_assert (op_data < insn->ntok);
3511               if (expr_is_const (&insn->tok[op_data]))
3512                 {
3513                   long val;
3514                   copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
3515                   val = xg_apply_userdef_op_fn (op->typ,
3516                                                 targ->tok[op_num].
3517                                                 X_add_number);
3518                   targ->tok[op_num].X_add_number = val;
3519                 }
3520               else
3521                 {
3522                   /* For const16 we can create relocations for these.  */
3523                   if (targ->opcode == XTENSA_UNDEFINED
3524                       || (targ->opcode != xtensa_const16_opcode))
3525                     return FALSE;
3526                   gas_assert (op_data < insn->ntok);
3527                   /* Need to build a O_lo16 or O_hi16.  */
3528                   copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
3529                   if (targ->tok[op_num].X_op == O_symbol)
3530                     {
3531                       if (op->typ == OP_OPERAND_HI16U)
3532                         targ->tok[op_num].X_op = O_hi16;
3533                       else if (op->typ == OP_OPERAND_LOW16U)
3534                         targ->tok[op_num].X_op = O_lo16;
3535                       else
3536                         return FALSE;
3537                     }
3538                 }
3539               break;
3540             default:
3541               /* currently handles:
3542                  OP_OPERAND_LOW8
3543                  OP_OPERAND_HI24S
3544                  OP_OPERAND_F32MINUS */
3545               if (xg_has_userdef_op_fn (op->typ))
3546                 {
3547                   gas_assert (op_data < insn->ntok);
3548                   if (expr_is_const (&insn->tok[op_data]))
3549                     {
3550                       long val;
3551                       copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
3552                       val = xg_apply_userdef_op_fn (op->typ,
3553                                                     targ->tok[op_num].
3554                                                     X_add_number);
3555                       targ->tok[op_num].X_add_number = val;
3556                     }
3557                   else
3558                     return FALSE; /* We cannot use a relocation for this.  */
3559                   break;
3560                 }
3561               gas_assert (0);
3562               break;
3563             }
3564         }
3565       break;
3566
3567     case INSTR_LITERAL_DEF:
3568       op = bi->ops;
3569       targ->opcode = XTENSA_UNDEFINED;
3570       targ->insn_type = ITYPE_LITERAL;
3571       targ->is_specific_opcode = FALSE;
3572       for (; op != NULL; op = op->next)
3573         {
3574           int op_num = op->op_num;
3575           int op_data = op->op_data;
3576           gas_assert (op->op_num < MAX_INSN_ARGS);
3577
3578           if (targ->ntok <= op_num)
3579             targ->ntok = op_num + 1;
3580
3581           switch (op->typ)
3582             {
3583             case OP_OPERAND:
3584               gas_assert (op_data < insn->ntok);
3585               /* We can only pass resolvable literals through.  */
3586               if (!xg_valid_literal_expression (&insn->tok[op_data]))
3587                 return FALSE;
3588               copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
3589               break;
3590             case OP_LITERAL:
3591             case OP_CONSTANT:
3592             case OP_LABEL:
3593             default:
3594               gas_assert (0);
3595               break;
3596             }
3597         }
3598       break;
3599
3600     case INSTR_LABEL_DEF:
3601       op = bi->ops;
3602       targ->opcode = XTENSA_UNDEFINED;
3603       targ->insn_type = ITYPE_LABEL;
3604       targ->is_specific_opcode = FALSE;
3605       /* Literal with no ops is a label?  */
3606       gas_assert (op == NULL);
3607       break;
3608
3609     default:
3610       gas_assert (0);
3611     }
3612
3613   return TRUE;
3614 }
3615
3616
3617 /* Return TRUE on success.  */
3618
3619 static bfd_boolean
3620 xg_build_to_stack (IStack *istack, TInsn *insn, BuildInstr *bi)
3621 {
3622   for (; bi != NULL; bi = bi->next)
3623     {
3624       TInsn *next_insn = istack_push_space (istack);
3625
3626       if (!xg_build_to_insn (next_insn, insn, bi))
3627         return FALSE;
3628     }
3629   return TRUE;
3630 }
3631
3632
3633 /* Return TRUE on valid expansion.  */
3634
3635 static bfd_boolean
3636 xg_expand_to_stack (IStack *istack, TInsn *insn, int lateral_steps)
3637 {
3638   int stack_size = istack->ninsn;
3639   int steps_taken = 0;
3640   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
3641   TransitionList *l;
3642
3643   gas_assert (insn->insn_type == ITYPE_INSN);
3644   gas_assert (insn->opcode < table->num_opcodes);
3645
3646   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
3647     {
3648       TransitionRule *rule = l->rule;
3649
3650       if (xg_instruction_matches_rule (insn, rule))
3651         {
3652           if (lateral_steps == steps_taken)
3653             {
3654               int i;
3655
3656               /* This is it.  Expand the rule to the stack.  */
3657               if (!xg_build_to_stack (istack, insn, rule->to_instr))
3658                 return FALSE;
3659
3660               /* Check to see if it fits.  */
3661               for (i = stack_size; i < istack->ninsn; i++)
3662                 {
3663                   TInsn *tinsn = &istack->insn[i];
3664
3665                   if (tinsn->insn_type == ITYPE_INSN
3666                       && !tinsn_has_symbolic_operands (tinsn)
3667                       && !xg_immeds_fit (tinsn))
3668                     {
3669                       istack->ninsn = stack_size;
3670                       return FALSE;
3671                     }
3672                 }
3673               return TRUE;
3674             }
3675           steps_taken++;
3676         }
3677     }
3678   return FALSE;
3679 }
3680
3681 \f
3682 /* Relax the assembly instruction at least "min_steps".
3683    Return the number of steps taken.
3684
3685    For relaxation to correctly terminate, every relaxation chain must
3686    terminate in one of two ways:
3687
3688    1.  If the chain from one instruction to the next consists entirely of
3689        single instructions, then the chain *must* handle all possible
3690        immediates without failing.  It must not ever fail because an
3691        immediate is out of range.  The MOVI.N -> MOVI -> L32R relaxation
3692        chain is one example.  L32R loads 32 bits, and there cannot be an
3693        immediate larger than 32 bits, so it satisfies this condition.
3694        Single instruction relaxation chains are as defined by
3695        xg_is_single_relaxable_instruction.
3696
3697    2.  Otherwise, the chain must end in a multi-instruction expansion: e.g.,
3698        BNEZ.N -> BNEZ -> BNEZ.W15 -> BENZ.N/J
3699
3700    Strictly speaking, in most cases you can violate condition 1 and be OK
3701    -- in particular when the last two instructions have the same single
3702    size.  But nevertheless, you should guarantee the above two conditions.
3703
3704    We could fix this so that single-instruction expansions correctly
3705    terminate when they can't handle the range, but the error messages are
3706    worse, and it actually turns out that in every case but one (18-bit wide
3707    branches), you need a multi-instruction expansion to get the full range
3708    anyway.  And because 18-bit branches are handled identically to 15-bit
3709    branches, there isn't any point in changing it.  */
3710
3711 static int
3712 xg_assembly_relax (IStack *istack,
3713                    TInsn *insn,
3714                    segT pc_seg,
3715                    fragS *pc_frag,      /* if pc_frag == 0, not pc-relative */
3716                    offsetT pc_offset,   /* offset in fragment */
3717                    int min_steps,       /* minimum conversion steps */
3718                    long stretch)        /* number of bytes stretched so far */
3719 {
3720   int steps_taken = 0;
3721
3722   /* Some of its immeds don't fit.  Try to build a relaxed version.
3723      This may go through a couple of stages of single instruction
3724      transformations before we get there.  */
3725
3726   TInsn single_target;
3727   TInsn current_insn;
3728   int lateral_steps = 0;
3729   int istack_size = istack->ninsn;
3730
3731   if (xg_symbolic_immeds_fit (insn, pc_seg, pc_frag, pc_offset, stretch)
3732       && steps_taken >= min_steps)
3733     {
3734       istack_push (istack, insn);
3735       return steps_taken;
3736     }
3737   current_insn = *insn;
3738
3739   /* Walk through all of the single instruction expansions.  */
3740   while (xg_is_single_relaxable_insn (&current_insn, &single_target, FALSE))
3741     {
3742       steps_taken++;
3743       if (xg_symbolic_immeds_fit (&single_target, pc_seg, pc_frag, pc_offset,
3744                                   stretch))
3745         {
3746           if (steps_taken >= min_steps)
3747             {
3748               istack_push (istack, &single_target);
3749               return steps_taken;
3750             }
3751         }
3752       current_insn = single_target;
3753     }
3754
3755   /* Now check for a multi-instruction expansion.  */
3756   while (xg_is_relaxable_insn (&current_insn, lateral_steps))
3757     {
3758       if (xg_symbolic_immeds_fit (&current_insn, pc_seg, pc_frag, pc_offset,
3759                                   stretch))
3760         {
3761           if (steps_taken >= min_steps)
3762             {
3763               istack_push (istack, &current_insn);
3764               return steps_taken;
3765             }
3766         }
3767       steps_taken++;
3768       if (xg_expand_to_stack (istack, &current_insn, lateral_steps))
3769         {
3770           if (steps_taken >= min_steps)
3771             return steps_taken;
3772         }
3773       lateral_steps++;
3774       istack->ninsn = istack_size;
3775     }
3776
3777   /* It's not going to work -- use the original.  */
3778   istack_push (istack, insn);
3779   return steps_taken;
3780 }
3781
3782
3783 static void
3784 xg_finish_frag (char *last_insn,
3785                 enum xtensa_relax_statesE frag_state,
3786                 enum xtensa_relax_statesE slot0_state,
3787                 int max_growth,
3788                 bfd_boolean is_insn)
3789 {
3790   /* Finish off this fragment so that it has at LEAST the desired
3791      max_growth.  If it doesn't fit in this fragment, close this one
3792      and start a new one.  In either case, return a pointer to the
3793      beginning of the growth area.  */
3794
3795   fragS *old_frag;
3796
3797   frag_grow (max_growth);
3798   old_frag = frag_now;
3799
3800   frag_now->fr_opcode = last_insn;
3801   if (is_insn)
3802     frag_now->tc_frag_data.is_insn = TRUE;
3803
3804   frag_var (rs_machine_dependent, max_growth, max_growth,
3805             frag_state, frag_now->fr_symbol, frag_now->fr_offset, last_insn);
3806
3807   old_frag->tc_frag_data.slot_subtypes[0] = slot0_state;
3808   xtensa_set_frag_assembly_state (frag_now);
3809
3810   /* Just to make sure that we did not split it up.  */
3811   gas_assert (old_frag->fr_next == frag_now);
3812 }
3813
3814
3815 /* Return TRUE if the target frag is one of the next non-empty frags.  */
3816
3817 static bfd_boolean
3818 is_next_frag_target (const fragS *fragP, const fragS *target)
3819 {
3820   if (fragP == NULL)
3821     return FALSE;
3822
3823   for (; fragP; fragP = fragP->fr_next)
3824     {
3825       if (fragP == target)
3826         return TRUE;
3827       if (fragP->fr_fix != 0)
3828         return FALSE;
3829       if (fragP->fr_type == rs_fill && fragP->fr_offset != 0)
3830         return FALSE;
3831       if ((fragP->fr_type == rs_align || fragP->fr_type == rs_align_code)
3832           && ((fragP->fr_address % (1 << fragP->fr_offset)) != 0))
3833         return FALSE;
3834       if (fragP->fr_type == rs_space)
3835         return FALSE;
3836     }
3837   return FALSE;
3838 }
3839
3840
3841 static bfd_boolean
3842 is_branch_jmp_to_next (TInsn *insn, fragS *fragP)
3843 {
3844   xtensa_isa isa = xtensa_default_isa;
3845   int i;
3846   int num_ops = xtensa_opcode_num_operands (isa, insn->opcode);
3847   int target_op = -1;
3848   symbolS *sym;
3849   fragS *target_frag;
3850
3851   if (xtensa_opcode_is_branch (isa, insn->opcode) != 1
3852       && xtensa_opcode_is_jump (isa, insn->opcode) != 1)
3853     return FALSE;
3854
3855   for (i = 0; i < num_ops; i++)
3856     {
3857       if (xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 1)
3858         {
3859           target_op = i;
3860           break;
3861         }
3862     }
3863   if (target_op == -1)
3864     return FALSE;
3865
3866   if (insn->ntok <= target_op)
3867     return FALSE;
3868
3869   if (insn->tok[target_op].X_op != O_symbol)
3870     return FALSE;
3871
3872   sym = insn->tok[target_op].X_add_symbol;
3873   if (sym == NULL)
3874     return FALSE;
3875
3876   if (insn->tok[target_op].X_add_number != 0)
3877     return FALSE;
3878
3879   target_frag = symbol_get_frag (sym);
3880   if (target_frag == NULL)
3881     return FALSE;
3882
3883   if (is_next_frag_target (fragP->fr_next, target_frag)
3884       && S_GET_VALUE (sym) == target_frag->fr_address)
3885     return TRUE;
3886
3887   return FALSE;
3888 }
3889
3890
3891 static void
3892 xg_add_branch_and_loop_targets (TInsn *insn)
3893 {
3894   xtensa_isa isa = xtensa_default_isa;
3895   int num_ops = xtensa_opcode_num_operands (isa, insn->opcode);
3896
3897   if (xtensa_opcode_is_loop (isa, insn->opcode) == 1)
3898     {
3899       int i = 1;
3900       if (xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 1
3901           && insn->tok[i].X_op == O_symbol)
3902         symbol_get_tc (insn->tok[i].X_add_symbol)->is_loop_target = TRUE;
3903       return;
3904     }
3905
3906   if (xtensa_opcode_is_branch (isa, insn->opcode) == 1
3907       || xtensa_opcode_is_loop (isa, insn->opcode) == 1)
3908     {
3909       int i;
3910
3911       for (i = 0; i < insn->ntok && i < num_ops; i++)
3912         {
3913           if (xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 1
3914               && insn->tok[i].X_op == O_symbol)
3915             {
3916               symbolS *sym = insn->tok[i].X_add_symbol;
3917               symbol_get_tc (sym)->is_branch_target = TRUE;
3918               if (S_IS_DEFINED (sym))
3919                 symbol_get_frag (sym)->tc_frag_data.is_branch_target = TRUE;
3920             }
3921         }
3922     }
3923 }
3924
3925
3926 /* Return FALSE if no error.  */
3927
3928 static bfd_boolean
3929 xg_build_token_insn (BuildInstr *instr_spec, TInsn *old_insn, TInsn *new_insn)
3930 {
3931   int num_ops = 0;
3932   BuildOp *b_op;
3933
3934   switch (instr_spec->typ)
3935     {
3936     case INSTR_INSTR:
3937       new_insn->insn_type = ITYPE_INSN;
3938       new_insn->opcode = instr_spec->opcode;
3939       break;
3940     case INSTR_LITERAL_DEF:
3941       new_insn->insn_type = ITYPE_LITERAL;
3942       new_insn->opcode = XTENSA_UNDEFINED;
3943       break;
3944     case INSTR_LABEL_DEF:
3945       abort ();
3946     }
3947   new_insn->is_specific_opcode = FALSE;
3948   new_insn->debug_line = old_insn->debug_line;
3949   new_insn->loc_directive_seen = old_insn->loc_directive_seen;
3950
3951   for (b_op = instr_spec->ops; b_op != NULL; b_op = b_op->next)
3952     {
3953       expressionS *exp;
3954       const expressionS *src_exp;
3955
3956       num_ops++;
3957       switch (b_op->typ)
3958         {
3959         case OP_CONSTANT:
3960           /* The expression must be the constant.  */
3961           gas_assert (b_op->op_num < MAX_INSN_ARGS);
3962           exp = &new_insn->tok[b_op->op_num];
3963           set_expr_const (exp, b_op->op_data);
3964           break;
3965
3966         case OP_OPERAND:
3967           gas_assert (b_op->op_num < MAX_INSN_ARGS);
3968           gas_assert (b_op->op_data < (unsigned) old_insn->ntok);
3969           src_exp = &old_insn->tok[b_op->op_data];
3970           exp = &new_insn->tok[b_op->op_num];
3971           copy_expr (exp, src_exp);
3972           break;
3973
3974         case OP_LITERAL:
3975         case OP_LABEL:
3976           as_bad (_("can't handle generation of literal/labels yet"));
3977           gas_assert (0);
3978
3979         default:
3980           as_bad (_("can't handle undefined OP TYPE"));
3981           gas_assert (0);
3982         }
3983     }
3984
3985   new_insn->ntok = num_ops;
3986   return FALSE;
3987 }
3988
3989
3990 /* Return TRUE if it was simplified.  */
3991
3992 static bfd_boolean
3993 xg_simplify_insn (TInsn *old_insn, TInsn *new_insn)
3994 {
3995   TransitionRule *rule;
3996   BuildInstr *insn_spec;
3997
3998   if (old_insn->is_specific_opcode || !density_supported)
3999     return FALSE;
4000
4001   rule = xg_instruction_match (old_insn);
4002   if (rule == NULL)
4003     return FALSE;
4004
4005   insn_spec = rule->to_instr;
4006   /* There should only be one.  */
4007   gas_assert (insn_spec != NULL);
4008   gas_assert (insn_spec->next == NULL);
4009   if (insn_spec->next != NULL)
4010     return FALSE;
4011
4012   xg_build_token_insn (insn_spec, old_insn, new_insn);
4013
4014   return TRUE;
4015 }
4016
4017
4018 /* xg_expand_assembly_insn: (1) Simplify the instruction, i.e., l32i ->
4019    l32i.n. (2) Check the number of operands.  (3) Place the instruction
4020    tokens into the stack or relax it and place multiple
4021    instructions/literals onto the stack.  Return FALSE if no error.  */
4022
4023 static bfd_boolean
4024 xg_expand_assembly_insn (IStack *istack, TInsn *orig_insn)
4025 {
4026   int noperands;
4027   TInsn new_insn;
4028   bfd_boolean do_expand;
4029
4030   tinsn_init (&new_insn);
4031
4032   /* Narrow it if we can.  xg_simplify_insn now does all the
4033      appropriate checking (e.g., for the density option).  */
4034   if (xg_simplify_insn (orig_insn, &new_insn))
4035     orig_insn = &new_insn;
4036
4037   noperands = xtensa_opcode_num_operands (xtensa_default_isa,
4038                                           orig_insn->opcode);
4039   if (orig_insn->ntok < noperands)
4040     {
4041       as_bad (_("found %d operands for '%s':  Expected %d"),
4042               orig_insn->ntok,
4043               xtensa_opcode_name (xtensa_default_isa, orig_insn->opcode),
4044               noperands);
4045       return TRUE;
4046     }
4047   if (orig_insn->ntok > noperands)
4048     as_warn (_("found too many (%d) operands for '%s':  Expected %d"),
4049              orig_insn->ntok,
4050              xtensa_opcode_name (xtensa_default_isa, orig_insn->opcode),
4051              noperands);
4052
4053   /* If there are not enough operands, we will assert above.  If there
4054      are too many, just cut out the extras here.  */
4055   orig_insn->ntok = noperands;
4056
4057   if (tinsn_has_invalid_symbolic_operands (orig_insn))
4058     return TRUE;
4059
4060   /* Special case for extui opcode which has constraints not handled
4061      by the ordinary operand encoding checks.  The number of operands
4062      and related syntax issues have already been checked.  */
4063   if (orig_insn->opcode == xtensa_extui_opcode)
4064     {
4065       int shiftimm = orig_insn->tok[2].X_add_number;
4066       int maskimm = orig_insn->tok[3].X_add_number;
4067       if (shiftimm + maskimm > 32)
4068         {
4069           as_bad (_("immediate operands sum to greater than 32"));
4070           return TRUE;
4071         }
4072     }
4073
4074   /* If the instruction will definitely need to be relaxed, it is better
4075      to expand it now for better scheduling.  Decide whether to expand
4076      now....  */
4077   do_expand = (!orig_insn->is_specific_opcode && use_transform ());
4078
4079   /* Calls should be expanded to longcalls only in the backend relaxation
4080      so that the assembly scheduler will keep the L32R/CALLX instructions
4081      adjacent.  */
4082   if (is_direct_call_opcode (orig_insn->opcode))
4083     do_expand = FALSE;
4084
4085   if (tinsn_has_symbolic_operands (orig_insn))
4086     {
4087       /* The values of symbolic operands are not known yet, so only expand
4088          now if an operand is "complex" (e.g., difference of symbols) and
4089          will have to be stored as a literal regardless of the value.  */
4090       if (!tinsn_has_complex_operands (orig_insn))
4091         do_expand = FALSE;
4092     }
4093   else if (xg_immeds_fit (orig_insn))
4094     do_expand = FALSE;
4095
4096   if (do_expand)
4097     xg_assembly_relax (istack, orig_insn, 0, 0, 0, 0, 0);
4098   else
4099     istack_push (istack, orig_insn);
4100
4101   return FALSE;
4102 }
4103
4104
4105 /* Return TRUE if the section flags are marked linkonce
4106    or the name is .gnu.linkonce.*.  */
4107
4108 static int linkonce_len = sizeof (".gnu.linkonce.") - 1;
4109
4110 static bfd_boolean
4111 get_is_linkonce_section (bfd *abfd ATTRIBUTE_UNUSED, segT sec)
4112 {
4113   flagword flags, link_once_flags;
4114
4115   flags = bfd_get_section_flags (abfd, sec);
4116   link_once_flags = (flags & SEC_LINK_ONCE);
4117
4118   /* Flags might not be set yet.  */
4119   if (!link_once_flags
4120       && strncmp (segment_name (sec), ".gnu.linkonce.", linkonce_len) == 0)
4121     link_once_flags = SEC_LINK_ONCE;
4122
4123   return (link_once_flags != 0);
4124 }
4125
4126
4127 static void
4128 xtensa_add_literal_sym (symbolS *sym)
4129 {
4130   sym_list *l;
4131
4132   l = (sym_list *) xmalloc (sizeof (sym_list));
4133   l->sym = sym;
4134   l->next = literal_syms;
4135   literal_syms = l;
4136 }
4137
4138
4139 static symbolS *
4140 xtensa_create_literal_symbol (segT sec, fragS *frag)
4141 {
4142   static int lit_num = 0;
4143   static char name[256];
4144   symbolS *symbolP;
4145
4146   sprintf (name, ".L_lit_sym%d", lit_num);
4147
4148   /* Create a local symbol.  If it is in a linkonce section, we have to
4149      be careful to make sure that if it is used in a relocation that the
4150      symbol will be in the output file.  */
4151   if (get_is_linkonce_section (stdoutput, sec))
4152     {
4153       symbolP = symbol_new (name, sec, 0, frag);
4154       S_CLEAR_EXTERNAL (symbolP);
4155       /* symbolP->local = 1; */
4156     }
4157   else
4158     symbolP = symbol_new (name, sec, 0, frag);
4159
4160   xtensa_add_literal_sym (symbolP);
4161
4162   lit_num++;
4163   return symbolP;
4164 }
4165
4166
4167 /* Currently all literals that are generated here are 32-bit L32R targets.  */
4168
4169 static symbolS *
4170 xg_assemble_literal (/* const */ TInsn *insn)
4171 {
4172   emit_state state;
4173   symbolS *lit_sym = NULL;
4174   bfd_reloc_code_real_type reloc;
4175   bfd_boolean pcrel = FALSE;
4176   char *p;
4177
4178   /* size = 4 for L32R.  It could easily be larger when we move to
4179      larger constants.  Add a parameter later.  */
4180   offsetT litsize = 4;
4181   offsetT litalign = 2;         /* 2^2 = 4 */
4182   expressionS saved_loc;
4183   expressionS * emit_val;
4184
4185   set_expr_symbol_offset (&saved_loc, frag_now->fr_symbol, frag_now_fix ());
4186
4187   gas_assert (insn->insn_type == ITYPE_LITERAL);
4188   gas_assert (insn->ntok == 1); /* must be only one token here */
4189
4190   xtensa_switch_to_literal_fragment (&state);
4191
4192   emit_val = &insn->tok[0];
4193   if (emit_val->X_op == O_big)
4194     {
4195       int size = emit_val->X_add_number * CHARS_PER_LITTLENUM;
4196       if (size > litsize)
4197         {
4198           /* This happens when someone writes a "movi a2, big_number".  */
4199           as_bad_where (frag_now->fr_file, frag_now->fr_line,
4200                         _("invalid immediate"));
4201           xtensa_restore_emit_state (&state);
4202           return NULL;
4203         }
4204     }
4205
4206   /* Force a 4-byte align here.  Note that this opens a new frag, so all
4207      literals done with this function have a frag to themselves.  That's
4208      important for the way text section literals work.  */
4209   frag_align (litalign, 0, 0);
4210   record_alignment (now_seg, litalign);
4211
4212   switch (emit_val->X_op)
4213     {
4214     case O_pcrel:
4215       pcrel = TRUE;
4216       /* fall through */
4217     case O_pltrel:
4218     case O_tlsfunc:
4219     case O_tlsarg:
4220     case O_tpoff:
4221     case O_dtpoff:
4222       p = frag_more (litsize);
4223       xtensa_set_frag_assembly_state (frag_now);
4224       reloc = map_operator_to_reloc (emit_val->X_op, TRUE);
4225       if (emit_val->X_add_symbol)
4226         emit_val->X_op = O_symbol;
4227       else
4228         emit_val->X_op = O_constant;
4229       fix_new_exp (frag_now, p - frag_now->fr_literal,
4230                    litsize, emit_val, pcrel, reloc);
4231       break;
4232
4233     default:
4234       emit_expr (emit_val, litsize);
4235       break;
4236     }
4237
4238   gas_assert (frag_now->tc_frag_data.literal_frag == NULL);
4239   frag_now->tc_frag_data.literal_frag = get_literal_pool_location (now_seg);
4240   frag_now->fr_symbol = xtensa_create_literal_symbol (now_seg, frag_now);
4241   lit_sym = frag_now->fr_symbol;
4242
4243   /* Go back.  */
4244   xtensa_restore_emit_state (&state);
4245   return lit_sym;
4246 }
4247
4248
4249 static void
4250 xg_assemble_literal_space (/* const */ int size, int slot)
4251 {
4252   emit_state state;
4253   /* We might have to do something about this alignment.  It only
4254      takes effect if something is placed here.  */
4255   offsetT litalign = 2;         /* 2^2 = 4 */
4256   fragS *lit_saved_frag;
4257
4258   gas_assert (size % 4 == 0);
4259
4260   xtensa_switch_to_literal_fragment (&state);
4261
4262   /* Force a 4-byte align here.  */
4263   frag_align (litalign, 0, 0);
4264   record_alignment (now_seg, litalign);
4265
4266   frag_grow (size);
4267
4268   lit_saved_frag = frag_now;
4269   frag_now->tc_frag_data.literal_frag = get_literal_pool_location (now_seg);
4270   frag_now->fr_symbol = xtensa_create_literal_symbol (now_seg, frag_now);
4271   xg_finish_frag (0, RELAX_LITERAL, 0, size, FALSE);
4272
4273   /* Go back.  */
4274   xtensa_restore_emit_state (&state);
4275   frag_now->tc_frag_data.literal_frags[slot] = lit_saved_frag;
4276 }
4277
4278
4279 /* Put in a fixup record based on the opcode.
4280    Return TRUE on success.  */
4281
4282 static bfd_boolean
4283 xg_add_opcode_fix (TInsn *tinsn,
4284                    int opnum,
4285                    xtensa_format fmt,
4286                    int slot,
4287                    expressionS *exp,
4288                    fragS *fragP,
4289                    offsetT offset)
4290 {
4291   xtensa_opcode opcode = tinsn->opcode;
4292   bfd_reloc_code_real_type reloc;
4293   reloc_howto_type *howto;
4294   int fmt_length;
4295   fixS *the_fix;
4296
4297   reloc = BFD_RELOC_NONE;
4298
4299   /* First try the special cases for "alternate" relocs.  */
4300   if (opcode == xtensa_l32r_opcode)
4301     {
4302       if (fragP->tc_frag_data.use_absolute_literals)
4303         reloc = encode_alt_reloc (slot);
4304     }
4305   else if (opcode == xtensa_const16_opcode)
4306     {
4307       if (exp->X_op == O_lo16)
4308         {
4309           reloc = encode_reloc (slot);
4310           exp->X_op = O_symbol;
4311         }
4312       else if (exp->X_op == O_hi16)
4313         {
4314           reloc = encode_alt_reloc (slot);
4315           exp->X_op = O_symbol;
4316         }
4317     }
4318
4319   if (opnum != get_relaxable_immed (opcode))
4320     {
4321       as_bad (_("invalid relocation for operand %i of '%s'"),
4322               opnum + 1, xtensa_opcode_name (xtensa_default_isa, opcode));
4323       return FALSE;
4324     }
4325
4326   /* Handle erroneous "@h" and "@l" expressions here before they propagate
4327      into the symbol table where the generic portions of the assembler
4328      won't know what to do with them.  */
4329   if (exp->X_op == O_lo16 || exp->X_op == O_hi16)
4330     {
4331       as_bad (_("invalid expression for operand %i of '%s'"),
4332               opnum + 1, xtensa_opcode_name (xtensa_default_isa, opcode));
4333       return FALSE;
4334     }
4335
4336   /* Next try the generic relocs.  */
4337   if (reloc == BFD_RELOC_NONE)
4338     reloc = encode_reloc (slot);
4339   if (reloc == BFD_RELOC_NONE)
4340     {
4341       as_bad (_("invalid relocation in instruction slot %i"), slot);
4342       return FALSE;
4343     }
4344
4345   howto = bfd_reloc_type_lookup (stdoutput, reloc);
4346   if (!howto)
4347     {
4348       as_bad (_("undefined symbol for opcode \"%s\""),
4349               xtensa_opcode_name (xtensa_default_isa, opcode));
4350       return FALSE;
4351     }
4352
4353   fmt_length = xtensa_format_length (xtensa_default_isa, fmt);
4354   the_fix = fix_new_exp (fragP, offset, fmt_length, exp,
4355                          howto->pc_relative, reloc);
4356   the_fix->fx_no_overflow = 1;
4357   the_fix->tc_fix_data.X_add_symbol = exp->X_add_symbol;
4358   the_fix->tc_fix_data.X_add_number = exp->X_add_number;
4359   the_fix->tc_fix_data.slot = slot;
4360
4361   return TRUE;
4362 }
4363
4364
4365 static bfd_boolean
4366 xg_emit_insn_to_buf (TInsn *tinsn,
4367                      char *buf,
4368                      fragS *fragP,
4369                      offsetT offset,
4370                      bfd_boolean build_fix)
4371 {
4372   static xtensa_insnbuf insnbuf = NULL;
4373   bfd_boolean has_symbolic_immed = FALSE;
4374   bfd_boolean ok = TRUE;
4375
4376   if (!insnbuf)
4377     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
4378
4379   has_symbolic_immed = tinsn_to_insnbuf (tinsn, insnbuf);
4380   if (has_symbolic_immed && build_fix)
4381     {
4382       /* Add a fixup.  */
4383       xtensa_format fmt = xg_get_single_format (tinsn->opcode);
4384       int slot = xg_get_single_slot (tinsn->opcode);
4385       int opnum = get_relaxable_immed (tinsn->opcode);
4386       expressionS *exp = &tinsn->tok[opnum];
4387
4388       if (!xg_add_opcode_fix (tinsn, opnum, fmt, slot, exp, fragP, offset))
4389         ok = FALSE;
4390     }
4391   fragP->tc_frag_data.is_insn = TRUE;
4392   xtensa_insnbuf_to_chars (xtensa_default_isa, insnbuf,
4393                            (unsigned char *) buf, 0);
4394   return ok;
4395 }
4396
4397
4398 static void
4399 xg_resolve_literals (TInsn *insn, symbolS *lit_sym)
4400 {
4401   symbolS *sym = get_special_literal_symbol ();
4402   int i;
4403   if (lit_sym == 0)
4404     return;
4405   gas_assert (insn->insn_type == ITYPE_INSN);
4406   for (i = 0; i < insn->ntok; i++)
4407     if (insn->tok[i].X_add_symbol == sym)
4408       insn->tok[i].X_add_symbol = lit_sym;
4409
4410 }
4411
4412
4413 static void
4414 xg_resolve_labels (TInsn *insn, symbolS *label_sym)
4415 {
4416   symbolS *sym = get_special_label_symbol ();
4417   int i;
4418   for (i = 0; i < insn->ntok; i++)
4419     if (insn->tok[i].X_add_symbol == sym)
4420       insn->tok[i].X_add_symbol = label_sym;
4421
4422 }
4423
4424
4425 /* Return TRUE if the instruction can write to the specified
4426    integer register.  */
4427
4428 static bfd_boolean
4429 is_register_writer (const TInsn *insn, const char *regset, int regnum)
4430 {
4431   int i;
4432   int num_ops;
4433   xtensa_isa isa = xtensa_default_isa;
4434
4435   num_ops = xtensa_opcode_num_operands (isa, insn->opcode);
4436
4437   for (i = 0; i < num_ops; i++)
4438     {
4439       char inout;
4440       inout = xtensa_operand_inout (isa, insn->opcode, i);
4441       if ((inout == 'o' || inout == 'm')
4442           && xtensa_operand_is_register (isa, insn->opcode, i) == 1)
4443         {
4444           xtensa_regfile opnd_rf =
4445             xtensa_operand_regfile (isa, insn->opcode, i);
4446           if (!strcmp (xtensa_regfile_shortname (isa, opnd_rf), regset))
4447             {
4448               if ((insn->tok[i].X_op == O_register)
4449                   && (insn->tok[i].X_add_number == regnum))
4450                 return TRUE;
4451             }
4452         }
4453     }
4454   return FALSE;
4455 }
4456
4457
4458 static bfd_boolean
4459 is_bad_loopend_opcode (const TInsn *tinsn)
4460 {
4461   xtensa_opcode opcode = tinsn->opcode;
4462
4463   if (opcode == XTENSA_UNDEFINED)
4464     return FALSE;
4465
4466   if (opcode == xtensa_call0_opcode
4467       || opcode == xtensa_callx0_opcode
4468       || opcode == xtensa_call4_opcode
4469       || opcode == xtensa_callx4_opcode
4470       || opcode == xtensa_call8_opcode
4471       || opcode == xtensa_callx8_opcode
4472       || opcode == xtensa_call12_opcode
4473       || opcode == xtensa_callx12_opcode
4474       || opcode == xtensa_isync_opcode
4475       || opcode == xtensa_ret_opcode
4476       || opcode == xtensa_ret_n_opcode
4477       || opcode == xtensa_retw_opcode
4478       || opcode == xtensa_retw_n_opcode
4479       || opcode == xtensa_waiti_opcode
4480       || opcode == xtensa_rsr_lcount_opcode)
4481     return TRUE;
4482
4483   return FALSE;
4484 }
4485
4486
4487 /* Labels that begin with ".Ln" or ".LM"  are unaligned.
4488    This allows the debugger to add unaligned labels.
4489    Also, the assembler generates stabs labels that need
4490    not be aligned:  FAKE_LABEL_NAME . {"F", "L", "endfunc"}.  */
4491
4492 static bfd_boolean
4493 is_unaligned_label (symbolS *sym)
4494 {
4495   const char *name = S_GET_NAME (sym);
4496   static size_t fake_size = 0;
4497
4498   if (name
4499       && name[0] == '.'
4500       && name[1] == 'L' && (name[2] == 'n' || name[2] == 'M'))
4501     return TRUE;
4502
4503   /* FAKE_LABEL_NAME followed by "F", "L" or "endfunc" */
4504   if (fake_size == 0)
4505     fake_size = strlen (FAKE_LABEL_NAME);
4506
4507   if (name
4508       && strncmp (FAKE_LABEL_NAME, name, fake_size) == 0
4509       && (name[fake_size] == 'F'
4510           || name[fake_size] == 'L'
4511           || (name[fake_size] == 'e'
4512               && strncmp ("endfunc", name+fake_size, 7) == 0)))
4513     return TRUE;
4514
4515   return FALSE;
4516 }
4517
4518
4519 static fragS *
4520 next_non_empty_frag (const fragS *fragP)
4521 {
4522   fragS *next_fragP = fragP->fr_next;
4523
4524   /* Sometimes an empty will end up here due storage allocation issues.
4525      So we have to skip until we find something legit.  */
4526   while (next_fragP && next_fragP->fr_fix == 0)
4527     next_fragP = next_fragP->fr_next;
4528
4529   if (next_fragP == NULL || next_fragP->fr_fix == 0)
4530     return NULL;
4531
4532   return next_fragP;
4533 }
4534
4535
4536 static bfd_boolean
4537 next_frag_opcode_is_loop (const fragS *fragP, xtensa_opcode *opcode)
4538 {
4539   xtensa_opcode out_opcode;
4540   const fragS *next_fragP = next_non_empty_frag (fragP);
4541
4542   if (next_fragP == NULL)
4543     return FALSE;
4544
4545   out_opcode = get_opcode_from_buf (next_fragP->fr_literal, 0);
4546   if (xtensa_opcode_is_loop (xtensa_default_isa, out_opcode) == 1)
4547     {
4548       *opcode = out_opcode;
4549       return TRUE;
4550     }
4551   return FALSE;
4552 }
4553
4554
4555 static int
4556 frag_format_size (const fragS *fragP)
4557 {
4558   static xtensa_insnbuf insnbuf = NULL;
4559   xtensa_isa isa = xtensa_default_isa;
4560   xtensa_format fmt;
4561   int fmt_size;
4562
4563   if (!insnbuf)
4564     insnbuf = xtensa_insnbuf_alloc (isa);
4565
4566   if (fragP == NULL)
4567     return XTENSA_UNDEFINED;
4568
4569   xtensa_insnbuf_from_chars (isa, insnbuf,
4570                              (unsigned char *) fragP->fr_literal, 0);
4571
4572   fmt = xtensa_format_decode (isa, insnbuf);
4573   if (fmt == XTENSA_UNDEFINED)
4574     return XTENSA_UNDEFINED;
4575   fmt_size = xtensa_format_length (isa, fmt);
4576
4577   /* If the next format won't be changing due to relaxation, just
4578      return the length of the first format.  */
4579   if (fragP->fr_opcode != fragP->fr_literal)
4580     return fmt_size;
4581
4582   /* If during relaxation we have to pull an instruction out of a
4583      multi-slot instruction, we will return the more conservative
4584      number.  This works because alignment on bigger instructions
4585      is more restrictive than alignment on smaller instructions.
4586      This is more conservative than we would like, but it happens
4587      infrequently.  */
4588
4589   if (xtensa_format_num_slots (xtensa_default_isa, fmt) > 1)
4590     return fmt_size;
4591
4592   /* If we aren't doing one of our own relaxations or it isn't
4593      slot-based, then the insn size won't change.  */
4594   if (fragP->fr_type != rs_machine_dependent)
4595     return fmt_size;
4596   if (fragP->fr_subtype != RELAX_SLOTS)
4597     return fmt_size;
4598
4599   /* If an instruction is about to grow, return the longer size.  */
4600   if (fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED_STEP1
4601       || fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED_STEP2
4602       || fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED_STEP3)
4603     {
4604       /* For most frags at RELAX_IMMED_STEPX, with X > 0, the first
4605          instruction in the relaxed version is of length 3.  (The case
4606          where we have to pull the instruction out of a FLIX bundle
4607          is handled conservatively above.)  However, frags with opcodes
4608          that are expanding to wide branches end up having formats that
4609          are not determinable by the RELAX_IMMED_STEPX enumeration, and
4610          we can't tell directly what format the relaxer picked.  This
4611          is a wart in the design of the relaxer that should someday be
4612          fixed, but would require major changes, or at least should
4613          be accompanied by major changes to make use of that data.
4614
4615          In any event, we can tell that we are expanding from a single-slot
4616          format to a wider one with the logic below.  */
4617
4618       int i;
4619       int relaxed_size = fmt_size + fragP->tc_frag_data.text_expansion[0];
4620
4621       for (i = 0; i < xtensa_isa_num_formats (isa); i++)
4622         {
4623           if (relaxed_size == xtensa_format_length (isa, i))
4624             return relaxed_size;
4625         }
4626
4627       return 3;
4628     }
4629
4630   if (fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
4631     return 2 + fragP->tc_frag_data.text_expansion[0];
4632
4633   return fmt_size;
4634 }
4635
4636
4637 static int
4638 next_frag_format_size (const fragS *fragP)
4639 {
4640   const fragS *next_fragP = next_non_empty_frag (fragP);
4641   return frag_format_size (next_fragP);
4642 }
4643
4644
4645 /* In early Xtensa Processors, for reasons that are unclear, the ISA
4646    required two-byte instructions to be treated as three-byte instructions
4647    for loop instruction alignment.  This restriction was removed beginning
4648    with Xtensa LX.  Now the only requirement on loop instruction alignment
4649    is that the first instruction of the loop must appear at an address that
4650    does not cross a fetch boundary.  */
4651
4652 static int
4653 get_loop_align_size (int insn_size)
4654 {
4655   if (insn_size == XTENSA_UNDEFINED)
4656     return xtensa_fetch_width;
4657
4658   if (enforce_three_byte_loop_align && insn_size == 2)
4659     return 3;
4660
4661   return insn_size;
4662 }
4663
4664
4665 /* If the next legit fragment is an end-of-loop marker,
4666    switch its state so it will instantiate a NOP.  */
4667
4668 static void
4669 update_next_frag_state (fragS *fragP)
4670 {
4671   fragS *next_fragP = fragP->fr_next;
4672   fragS *new_target = NULL;
4673
4674   if (align_targets)
4675     {
4676       /* We are guaranteed there will be one of these...   */
4677       while (!(next_fragP->fr_type == rs_machine_dependent
4678                && (next_fragP->fr_subtype == RELAX_MAYBE_UNREACHABLE
4679                    || next_fragP->fr_subtype == RELAX_UNREACHABLE)))
4680         next_fragP = next_fragP->fr_next;
4681
4682       gas_assert (next_fragP->fr_type == rs_machine_dependent
4683               && (next_fragP->fr_subtype == RELAX_MAYBE_UNREACHABLE
4684                   || next_fragP->fr_subtype == RELAX_UNREACHABLE));
4685
4686       /* ...and one of these.  */
4687       new_target = next_fragP->fr_next;
4688       while (!(new_target->fr_type == rs_machine_dependent
4689                && (new_target->fr_subtype == RELAX_MAYBE_DESIRE_ALIGN
4690                    || new_target->fr_subtype == RELAX_DESIRE_ALIGN)))
4691         new_target = new_target->fr_next;
4692
4693       gas_assert (new_target->fr_type == rs_machine_dependent
4694               && (new_target->fr_subtype == RELAX_MAYBE_DESIRE_ALIGN
4695                   || new_target->fr_subtype == RELAX_DESIRE_ALIGN));
4696     }
4697
4698   while (next_fragP && next_fragP->fr_fix == 0)
4699     {
4700       if (next_fragP->fr_type == rs_machine_dependent
4701           && next_fragP->fr_subtype == RELAX_LOOP_END)
4702         {
4703           next_fragP->fr_subtype = RELAX_LOOP_END_ADD_NOP;
4704           return;
4705         }
4706
4707       next_fragP = next_fragP->fr_next;
4708     }
4709 }
4710
4711
4712 static bfd_boolean
4713 next_frag_is_branch_target (const fragS *fragP)
4714 {
4715   /* Sometimes an empty will end up here due to storage allocation issues,
4716      so we have to skip until we find something legit.  */
4717   for (fragP = fragP->fr_next; fragP; fragP = fragP->fr_next)
4718     {
4719       if (fragP->tc_frag_data.is_branch_target)
4720         return TRUE;
4721       if (fragP->fr_fix != 0)
4722         break;
4723     }
4724   return FALSE;
4725 }
4726
4727
4728 static bfd_boolean
4729 next_frag_is_loop_target (const fragS *fragP)
4730 {
4731   /* Sometimes an empty will end up here due storage allocation issues.
4732      So we have to skip until we find something legit. */
4733   for (fragP = fragP->fr_next; fragP; fragP = fragP->fr_next)
4734     {
4735       if (fragP->tc_frag_data.is_loop_target)
4736         return TRUE;
4737       if (fragP->fr_fix != 0)
4738         break;
4739     }
4740   return FALSE;
4741 }
4742
4743
4744 /* As specified in the relaxation table, when a loop instruction is
4745    relaxed, there are 24 bytes between the loop instruction itself and
4746    the first instruction in the loop.  */
4747
4748 #define RELAXED_LOOP_INSN_BYTES 24
4749
4750 static addressT
4751 next_frag_pre_opcode_bytes (const fragS *fragp)
4752 {
4753   const fragS *next_fragp = fragp->fr_next;
4754   xtensa_opcode next_opcode;
4755
4756   if (!next_frag_opcode_is_loop (fragp, &next_opcode))
4757     return 0;
4758
4759   /* Sometimes an empty will end up here due to storage allocation issues,
4760      so we have to skip until we find something legit.  */
4761   while (next_fragp->fr_fix == 0)
4762     next_fragp = next_fragp->fr_next;
4763
4764   if (next_fragp->fr_type != rs_machine_dependent)
4765     return 0;
4766
4767   /* There is some implicit knowledge encoded in here.
4768      The LOOP instructions that are NOT RELAX_IMMED have
4769      been relaxed.  Note that we can assume that the LOOP
4770      instruction is in slot 0 because loops aren't bundleable.  */
4771   if (next_fragp->tc_frag_data.slot_subtypes[0] > RELAX_IMMED)
4772       return get_expanded_loop_offset (next_opcode) + RELAXED_LOOP_INSN_BYTES;
4773
4774   return 0;
4775 }
4776
4777
4778 /* Mark a location where we can later insert literal frags.  Update
4779    the section's literal_pool_loc, so subsequent literals can be
4780    placed nearest to their use.  */
4781
4782 static void
4783 xtensa_mark_literal_pool_location (void)
4784 {
4785   /* Any labels pointing to the current location need
4786      to be adjusted to after the literal pool.  */
4787   emit_state s;
4788   fragS *pool_location;
4789
4790   if (use_literal_section)
4791     return;
4792
4793   /* We stash info in these frags so we can later move the literal's
4794      fixes into this frchain's fix list.  */
4795   pool_location = frag_now;
4796   frag_now->tc_frag_data.lit_frchain = frchain_now;
4797   frag_now->tc_frag_data.literal_frag = frag_now;
4798   /* Just record this frag.  */
4799   xtensa_maybe_create_literal_pool_frag (FALSE, FALSE);
4800   frag_variant (rs_machine_dependent, 0, 0,
4801                 RELAX_LITERAL_POOL_BEGIN, NULL, 0, NULL);
4802   xtensa_set_frag_assembly_state (frag_now);
4803   frag_now->tc_frag_data.lit_seg = now_seg;
4804   frag_variant (rs_machine_dependent, 0, 0,
4805                 RELAX_LITERAL_POOL_END, NULL, 0, NULL);
4806   xtensa_set_frag_assembly_state (frag_now);
4807
4808   /* Now put a frag into the literal pool that points to this location.  */
4809   set_literal_pool_location (now_seg, pool_location);
4810   xtensa_switch_to_non_abs_literal_fragment (&s);
4811   frag_align (2, 0, 0);
4812   record_alignment (now_seg, 2);
4813
4814   /* Close whatever frag is there.  */
4815   frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
4816   xtensa_set_frag_assembly_state (frag_now);
4817   frag_now->tc_frag_data.literal_frag = pool_location;
4818   frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
4819   xtensa_restore_emit_state (&s);
4820   xtensa_set_frag_assembly_state (frag_now);
4821 }
4822
4823
4824 /* Build a nop of the correct size into tinsn.  */
4825
4826 static void
4827 build_nop (TInsn *tinsn, int size)
4828 {
4829   tinsn_init (tinsn);
4830   switch (size)
4831     {
4832     case 2:
4833       tinsn->opcode = xtensa_nop_n_opcode;
4834       tinsn->ntok = 0;
4835       if (tinsn->opcode == XTENSA_UNDEFINED)
4836         as_fatal (_("opcode 'NOP.N' unavailable in this configuration"));
4837       break;
4838
4839     case 3:
4840       if (xtensa_nop_opcode == XTENSA_UNDEFINED)
4841         {
4842           tinsn->opcode = xtensa_or_opcode;
4843           set_expr_const (&tinsn->tok[0], 1);
4844           set_expr_const (&tinsn->tok[1], 1);
4845           set_expr_const (&tinsn->tok[2], 1);
4846           tinsn->ntok = 3;
4847         }
4848       else
4849         tinsn->opcode = xtensa_nop_opcode;
4850
4851       gas_assert (tinsn->opcode != XTENSA_UNDEFINED);
4852     }
4853 }
4854
4855
4856 /* Assemble a NOP of the requested size in the buffer.  User must have
4857    allocated "buf" with at least "size" bytes.  */
4858
4859 static void
4860 assemble_nop (int size, char *buf)
4861 {
4862   static xtensa_insnbuf insnbuf = NULL;
4863   TInsn tinsn;
4864
4865   build_nop (&tinsn, size);
4866
4867   if (!insnbuf)
4868     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
4869
4870   tinsn_to_insnbuf (&tinsn, insnbuf);
4871   xtensa_insnbuf_to_chars (xtensa_default_isa, insnbuf,
4872                            (unsigned char *) buf, 0);
4873 }
4874
4875
4876 /* Return the number of bytes for the offset of the expanded loop
4877    instruction.  This should be incorporated into the relaxation
4878    specification but is hard-coded here.  This is used to auto-align
4879    the loop instruction.  It is invalid to call this function if the
4880    configuration does not have loops or if the opcode is not a loop
4881    opcode.  */
4882
4883 static addressT
4884 get_expanded_loop_offset (xtensa_opcode opcode)
4885 {
4886   /* This is the OFFSET of the loop instruction in the expanded loop.
4887      This MUST correspond directly to the specification of the loop
4888      expansion.  It will be validated on fragment conversion.  */
4889   gas_assert (opcode != XTENSA_UNDEFINED);
4890   if (opcode == xtensa_loop_opcode)
4891     return 0;
4892   if (opcode == xtensa_loopnez_opcode)
4893     return 3;
4894   if (opcode == xtensa_loopgtz_opcode)
4895     return 6;
4896   as_fatal (_("get_expanded_loop_offset: invalid opcode"));
4897   return 0;
4898 }
4899
4900
4901 static fragS *
4902 get_literal_pool_location (segT seg)
4903 {
4904   struct litpool_seg *lps = litpool_seg_list.next;
4905   struct litpool_frag *lpf;
4906   for ( ; lps && lps->seg->id != seg->id; lps = lps->next)
4907     ;
4908   if (lps)
4909     {
4910       for (lpf = lps->frag_list.prev; lpf->fragP; lpf = lpf->prev)
4911         { /* Skip "candidates" for now.  */
4912           if (lpf->fragP->fr_subtype == RELAX_LITERAL_POOL_BEGIN &&
4913               lpf->priority == 1)
4914             return lpf->fragP;
4915         }
4916       /* Must convert a lower-priority pool.  */
4917       for (lpf = lps->frag_list.prev; lpf->fragP; lpf = lpf->prev)
4918         {
4919           if (lpf->fragP->fr_subtype == RELAX_LITERAL_POOL_BEGIN)
4920             return lpf->fragP;
4921         }
4922       /* Still no match -- try for a low priority pool.  */
4923       for (lpf = lps->frag_list.prev; lpf->fragP; lpf = lpf->prev)
4924         {
4925           if (lpf->fragP->fr_subtype == RELAX_LITERAL_POOL_CANDIDATE_BEGIN)
4926             return lpf->fragP;
4927         }
4928     }
4929   return seg_info (seg)->tc_segment_info_data.literal_pool_loc;
4930 }
4931
4932
4933 static void
4934 set_literal_pool_location (segT seg, fragS *literal_pool_loc)
4935 {
4936   seg_info (seg)->tc_segment_info_data.literal_pool_loc = literal_pool_loc;
4937 }
4938
4939
4940 /* Set frag assembly state should be called when a new frag is
4941    opened and after a frag has been closed.  */
4942
4943 static void
4944 xtensa_set_frag_assembly_state (fragS *fragP)
4945 {
4946   if (!density_supported)
4947     fragP->tc_frag_data.is_no_density = TRUE;
4948
4949   /* This function is called from subsegs_finish, which is called
4950      after xtensa_end, so we can't use "use_transform" or
4951      "use_schedule" here.  */
4952   if (!directive_state[directive_transform])
4953     fragP->tc_frag_data.is_no_transform = TRUE;
4954   if (directive_state[directive_longcalls])
4955     fragP->tc_frag_data.use_longcalls = TRUE;
4956   fragP->tc_frag_data.use_absolute_literals =
4957     directive_state[directive_absolute_literals];
4958   fragP->tc_frag_data.is_assembly_state_set = TRUE;
4959 }
4960
4961
4962 static bfd_boolean
4963 relaxable_section (asection *sec)
4964 {
4965   return ((sec->flags & SEC_DEBUGGING) == 0
4966           && strcmp (sec->name, ".eh_frame") != 0);
4967 }
4968
4969
4970 static void
4971 xtensa_mark_frags_for_org (void)
4972 {
4973   segT *seclist;
4974
4975   /* Walk over each fragment of all of the current segments.  If we find
4976      a .org frag in any of the segments, mark all frags prior to it as
4977      "no transform", which will prevent linker optimizations from messing
4978      up the .org distance.  This should be done after
4979      xtensa_find_unmarked_state_frags, because we don't want to worry here
4980      about that function trashing the data we save here.  */
4981
4982   for (seclist = &stdoutput->sections;
4983        seclist && *seclist;
4984        seclist = &(*seclist)->next)
4985     {
4986       segT sec = *seclist;
4987       segment_info_type *seginfo;
4988       fragS *fragP;
4989       flagword flags;
4990       flags = bfd_get_section_flags (stdoutput, sec);
4991       if (flags & SEC_DEBUGGING)
4992         continue;
4993       if (!(flags & SEC_ALLOC))
4994         continue;
4995
4996       seginfo = seg_info (sec);
4997       if (seginfo && seginfo->frchainP)
4998         {
4999           fragS *last_fragP = seginfo->frchainP->frch_root;
5000           for (fragP = seginfo->frchainP->frch_root; fragP;
5001                fragP = fragP->fr_next)
5002             {
5003               /* cvt_frag_to_fill has changed the fr_type of org frags to
5004                  rs_fill, so use the value as cached in rs_subtype here.  */
5005               if (fragP->fr_subtype == RELAX_ORG)
5006                 {
5007                   while (last_fragP != fragP->fr_next)
5008                     {
5009                       last_fragP->tc_frag_data.is_no_transform = TRUE;
5010                       last_fragP = last_fragP->fr_next;
5011                     }
5012                 }
5013             }
5014         }
5015     }
5016 }
5017
5018
5019 static void
5020 xtensa_find_unmarked_state_frags (void)
5021 {
5022   segT *seclist;
5023
5024   /* Walk over each fragment of all of the current segments.  For each
5025      unmarked fragment, mark it with the same info as the previous
5026      fragment.  */
5027   for (seclist = &stdoutput->sections;
5028        seclist && *seclist;
5029        seclist = &(*seclist)->next)
5030     {
5031       segT sec = *seclist;
5032       segment_info_type *seginfo;
5033       fragS *fragP;
5034       flagword flags;
5035       flags = bfd_get_section_flags (stdoutput, sec);
5036       if (flags & SEC_DEBUGGING)
5037         continue;
5038       if (!(flags & SEC_ALLOC))
5039         continue;
5040
5041       seginfo = seg_info (sec);
5042       if (seginfo && seginfo->frchainP)
5043         {
5044           fragS *last_fragP = 0;
5045           for (fragP = seginfo->frchainP->frch_root; fragP;
5046                fragP = fragP->fr_next)
5047             {
5048               if (fragP->fr_fix != 0
5049                   && !fragP->tc_frag_data.is_assembly_state_set)
5050                 {
5051                   if (last_fragP == 0)
5052                     {
5053                       as_warn_where (fragP->fr_file, fragP->fr_line,
5054                                      _("assembly state not set for first frag in section %s"),
5055                                      sec->name);
5056                     }
5057                   else
5058                     {
5059                       fragP->tc_frag_data.is_assembly_state_set = TRUE;
5060                       fragP->tc_frag_data.is_no_density =
5061                         last_fragP->tc_frag_data.is_no_density;
5062                       fragP->tc_frag_data.is_no_transform =
5063                         last_fragP->tc_frag_data.is_no_transform;
5064                       fragP->tc_frag_data.use_longcalls =
5065                         last_fragP->tc_frag_data.use_longcalls;
5066                       fragP->tc_frag_data.use_absolute_literals =
5067                         last_fragP->tc_frag_data.use_absolute_literals;
5068                     }
5069                 }
5070               if (fragP->tc_frag_data.is_assembly_state_set)
5071                 last_fragP = fragP;
5072             }
5073         }
5074     }
5075 }
5076
5077
5078 static void
5079 xtensa_find_unaligned_branch_targets (bfd *abfd ATTRIBUTE_UNUSED,
5080                                       asection *sec,
5081                                       void *unused ATTRIBUTE_UNUSED)
5082 {
5083   flagword flags = bfd_get_section_flags (abfd, sec);
5084   segment_info_type *seginfo = seg_info (sec);
5085   fragS *frag = seginfo->frchainP->frch_root;
5086
5087   if (flags & SEC_CODE)
5088     {
5089       xtensa_isa isa = xtensa_default_isa;
5090       xtensa_insnbuf insnbuf = xtensa_insnbuf_alloc (isa);
5091       while (frag != NULL)
5092         {
5093           if (frag->tc_frag_data.is_branch_target)
5094             {
5095               int op_size;
5096               addressT branch_align, frag_addr;
5097               xtensa_format fmt;
5098
5099               xtensa_insnbuf_from_chars
5100                 (isa, insnbuf, (unsigned char *) frag->fr_literal, 0);
5101               fmt = xtensa_format_decode (isa, insnbuf);
5102               op_size = xtensa_format_length (isa, fmt);
5103               branch_align = 1 << branch_align_power (sec);
5104               frag_addr = frag->fr_address % branch_align;
5105               if (frag_addr + op_size > branch_align)
5106                 as_warn_where (frag->fr_file, frag->fr_line,
5107                                _("unaligned branch target: %d bytes at 0x%lx"),
5108                                op_size, (long) frag->fr_address);
5109             }
5110           frag = frag->fr_next;
5111         }
5112       xtensa_insnbuf_free (isa, insnbuf);
5113     }
5114 }
5115
5116
5117 static void
5118 xtensa_find_unaligned_loops (bfd *abfd ATTRIBUTE_UNUSED,
5119                              asection *sec,
5120                              void *unused ATTRIBUTE_UNUSED)
5121 {
5122   flagword flags = bfd_get_section_flags (abfd, sec);
5123   segment_info_type *seginfo = seg_info (sec);
5124   fragS *frag = seginfo->frchainP->frch_root;
5125   xtensa_isa isa = xtensa_default_isa;
5126
5127   if (flags & SEC_CODE)
5128     {
5129       xtensa_insnbuf insnbuf = xtensa_insnbuf_alloc (isa);
5130       while (frag != NULL)
5131         {
5132           if (frag->tc_frag_data.is_first_loop_insn)
5133             {
5134               int op_size;
5135               addressT frag_addr;
5136               xtensa_format fmt;
5137
5138               if (frag->fr_fix == 0)
5139                 frag = next_non_empty_frag (frag);
5140
5141               if (frag)
5142                 {
5143                   xtensa_insnbuf_from_chars
5144                     (isa, insnbuf, (unsigned char *) frag->fr_literal, 0);
5145                   fmt = xtensa_format_decode (isa, insnbuf);
5146                   op_size = xtensa_format_length (isa, fmt);
5147                   frag_addr = frag->fr_address % xtensa_fetch_width;
5148
5149                   if (frag_addr + op_size > xtensa_fetch_width)
5150                     as_warn_where (frag->fr_file, frag->fr_line,
5151                                    _("unaligned loop: %d bytes at 0x%lx"),
5152                                    op_size, (long) frag->fr_address);
5153                 }
5154             }
5155           frag = frag->fr_next;
5156         }
5157       xtensa_insnbuf_free (isa, insnbuf);
5158     }
5159 }
5160
5161
5162 static int
5163 xg_apply_fix_value (fixS *fixP, valueT val)
5164 {
5165   xtensa_isa isa = xtensa_default_isa;
5166   static xtensa_insnbuf insnbuf = NULL;
5167   static xtensa_insnbuf slotbuf = NULL;
5168   xtensa_format fmt;
5169   int slot;
5170   bfd_boolean alt_reloc;
5171   xtensa_opcode opcode;
5172   char *const fixpos = fixP->fx_frag->fr_literal + fixP->fx_where;
5173
5174   if (decode_reloc (fixP->fx_r_type, &slot, &alt_reloc)
5175       || alt_reloc)
5176     as_fatal (_("unexpected fix"));
5177
5178   if (!insnbuf)
5179     {
5180       insnbuf = xtensa_insnbuf_alloc (isa);
5181       slotbuf = xtensa_insnbuf_alloc (isa);
5182     }
5183
5184   xtensa_insnbuf_from_chars (isa, insnbuf, (unsigned char *) fixpos, 0);
5185   fmt = xtensa_format_decode (isa, insnbuf);
5186   if (fmt == XTENSA_UNDEFINED)
5187     as_fatal (_("undecodable fix"));
5188   xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
5189   opcode = xtensa_opcode_decode (isa, fmt, slot, slotbuf);
5190   if (opcode == XTENSA_UNDEFINED)
5191     as_fatal (_("undecodable fix"));
5192
5193   /* CONST16 immediates are not PC-relative, despite the fact that we
5194      reuse the normal PC-relative operand relocations for the low part
5195      of a CONST16 operand.  */
5196   if (opcode == xtensa_const16_opcode)
5197     return 0;
5198
5199   xtensa_insnbuf_set_operand (slotbuf, fmt, slot, opcode,
5200                               get_relaxable_immed (opcode), val,
5201                               fixP->fx_file, fixP->fx_line);
5202
5203   xtensa_format_set_slot (isa, fmt, slot, insnbuf, slotbuf);
5204   xtensa_insnbuf_to_chars (isa, insnbuf, (unsigned char *) fixpos, 0);
5205
5206   return 1;
5207 }
5208
5209 \f
5210 /* External Functions and Other GAS Hooks.  */
5211
5212 const char *
5213 xtensa_target_format (void)
5214 {
5215   return (target_big_endian ? "elf32-xtensa-be" : "elf32-xtensa-le");
5216 }
5217
5218
5219 void
5220 xtensa_file_arch_init (bfd *abfd)
5221 {
5222   bfd_set_private_flags (abfd, 0x100 | 0x200);
5223 }
5224
5225
5226 void
5227 md_number_to_chars (char *buf, valueT val, int n)
5228 {
5229   if (target_big_endian)
5230     number_to_chars_bigendian (buf, val, n);
5231   else
5232     number_to_chars_littleendian (buf, val, n);
5233 }
5234
5235
5236 /* This function is called once, at assembler startup time.  It should
5237    set up all the tables, etc. that the MD part of the assembler will
5238    need.  */
5239
5240 void
5241 md_begin (void)
5242 {
5243   segT current_section = now_seg;
5244   int current_subsec = now_subseg;
5245   xtensa_isa isa;
5246   int i;
5247
5248   xtensa_default_isa = xtensa_isa_init (0, 0);
5249   isa = xtensa_default_isa;
5250
5251   linkrelax = 1;
5252
5253   /* Set up the literal sections.  */
5254   memset (&default_lit_sections, 0, sizeof (default_lit_sections));
5255
5256   subseg_set (current_section, current_subsec);
5257
5258   xtensa_addi_opcode = xtensa_opcode_lookup (isa, "addi");
5259   xtensa_addmi_opcode = xtensa_opcode_lookup (isa, "addmi");
5260   xtensa_call0_opcode = xtensa_opcode_lookup (isa, "call0");
5261   xtensa_call4_opcode = xtensa_opcode_lookup (isa, "call4");
5262   xtensa_call8_opcode = xtensa_opcode_lookup (isa, "call8");
5263   xtensa_call12_opcode = xtensa_opcode_lookup (isa, "call12");
5264   xtensa_callx0_opcode = xtensa_opcode_lookup (isa, "callx0");
5265   xtensa_callx4_opcode = xtensa_opcode_lookup (isa, "callx4");
5266   xtensa_callx8_opcode = xtensa_opcode_lookup (isa, "callx8");
5267   xtensa_callx12_opcode = xtensa_opcode_lookup (isa, "callx12");
5268   xtensa_const16_opcode = xtensa_opcode_lookup (isa, "const16");
5269   xtensa_entry_opcode = xtensa_opcode_lookup (isa, "entry");
5270   xtensa_extui_opcode = xtensa_opcode_lookup (isa, "extui");
5271   xtensa_movi_opcode = xtensa_opcode_lookup (isa, "movi");
5272   xtensa_movi_n_opcode = xtensa_opcode_lookup (isa, "movi.n");
5273   xtensa_isync_opcode = xtensa_opcode_lookup (isa, "isync");
5274   xtensa_j_opcode = xtensa_opcode_lookup (isa, "j");
5275   xtensa_jx_opcode = xtensa_opcode_lookup (isa, "jx");
5276   xtensa_l32r_opcode = xtensa_opcode_lookup (isa, "l32r");
5277   xtensa_loop_opcode = xtensa_opcode_lookup (isa, "loop");
5278   xtensa_loopnez_opcode = xtensa_opcode_lookup (isa, "loopnez");
5279   xtensa_loopgtz_opcode = xtensa_opcode_lookup (isa, "loopgtz");
5280   xtensa_nop_opcode = xtensa_opcode_lookup (isa, "nop");
5281   xtensa_nop_n_opcode = xtensa_opcode_lookup (isa, "nop.n");
5282   xtensa_or_opcode = xtensa_opcode_lookup (isa, "or");
5283   xtensa_ret_opcode = xtensa_opcode_lookup (isa, "ret");
5284   xtensa_ret_n_opcode = xtensa_opcode_lookup (isa, "ret.n");
5285   xtensa_retw_opcode = xtensa_opcode_lookup (isa, "retw");
5286   xtensa_retw_n_opcode = xtensa_opcode_lookup (isa, "retw.n");
5287   xtensa_rsr_lcount_opcode = xtensa_opcode_lookup (isa, "rsr.lcount");
5288   xtensa_waiti_opcode = xtensa_opcode_lookup (isa, "waiti");
5289
5290   for (i = 0; i < xtensa_isa_num_formats (isa); i++)
5291     {
5292       int format_slots = xtensa_format_num_slots (isa, i);
5293       if (format_slots > config_max_slots)
5294         config_max_slots = format_slots;
5295     }
5296
5297   xg_init_vinsn (&cur_vinsn);
5298
5299   xtensa_num_pipe_stages = xtensa_isa_num_pipe_stages (isa);
5300
5301   init_op_placement_info_table ();
5302
5303   /* Set up the assembly state.  */
5304   if (!frag_now->tc_frag_data.is_assembly_state_set)
5305     xtensa_set_frag_assembly_state (frag_now);
5306 }
5307
5308
5309 /* TC_INIT_FIX_DATA hook */
5310
5311 void
5312 xtensa_init_fix_data (fixS *x)
5313 {
5314   x->tc_fix_data.slot = 0;
5315   x->tc_fix_data.X_add_symbol = NULL;
5316   x->tc_fix_data.X_add_number = 0;
5317 }
5318
5319
5320 /* tc_frob_label hook */
5321
5322 void
5323 xtensa_frob_label (symbolS *sym)
5324 {
5325   float freq;
5326
5327   if (cur_vinsn.inside_bundle)
5328     {
5329       as_bad (_("labels are not valid inside bundles"));
5330       return;
5331     }
5332
5333   freq = get_subseg_target_freq (now_seg, now_subseg);
5334
5335   /* Since the label was already attached to a frag associated with the
5336      previous basic block, it now needs to be reset to the current frag.  */
5337   symbol_set_frag (sym, frag_now);
5338   S_SET_VALUE (sym, (valueT) frag_now_fix ());
5339
5340   if (generating_literals)
5341     xtensa_add_literal_sym (sym);
5342   else
5343     xtensa_add_insn_label (sym);
5344
5345   if (symbol_get_tc (sym)->is_loop_target)
5346     {
5347       if ((get_last_insn_flags (now_seg, now_subseg)
5348           & FLAG_IS_BAD_LOOPEND) != 0)
5349         as_bad (_("invalid last instruction for a zero-overhead loop"));
5350
5351       xtensa_set_frag_assembly_state (frag_now);
5352       frag_var (rs_machine_dependent, 4, 4, RELAX_LOOP_END,
5353                 frag_now->fr_symbol, frag_now->fr_offset, NULL);
5354
5355       xtensa_set_frag_assembly_state (frag_now);
5356       xtensa_move_labels (frag_now, 0);
5357     }
5358
5359   /* No target aligning in the absolute section.  */
5360   if (now_seg != absolute_section
5361       && !is_unaligned_label (sym)
5362       && !generating_literals)
5363     {
5364       xtensa_set_frag_assembly_state (frag_now);
5365
5366       if (do_align_targets ())
5367         frag_var (rs_machine_dependent, 0, (int) freq,
5368                   RELAX_DESIRE_ALIGN_IF_TARGET, frag_now->fr_symbol,
5369                   frag_now->fr_offset, NULL);
5370       else
5371         frag_var (rs_fill, 0, 0, frag_now->fr_subtype,
5372                   frag_now->fr_symbol, frag_now->fr_offset, NULL);
5373       xtensa_set_frag_assembly_state (frag_now);
5374       xtensa_move_labels (frag_now, 0);
5375     }
5376
5377   /* We need to mark the following properties even if we aren't aligning.  */
5378
5379   /* If the label is already known to be a branch target, i.e., a
5380      forward branch, mark the frag accordingly.  Backward branches
5381      are handled by xg_add_branch_and_loop_targets.  */
5382   if (symbol_get_tc (sym)->is_branch_target)
5383     symbol_get_frag (sym)->tc_frag_data.is_branch_target = TRUE;
5384
5385   /* Loops only go forward, so they can be identified here.  */
5386   if (symbol_get_tc (sym)->is_loop_target)
5387     symbol_get_frag (sym)->tc_frag_data.is_loop_target = TRUE;
5388
5389   dwarf2_emit_label (sym);
5390 }
5391
5392
5393 /* tc_unrecognized_line hook */
5394
5395 int
5396 xtensa_unrecognized_line (int ch)
5397 {
5398   switch (ch)
5399     {
5400     case '{' :
5401       if (cur_vinsn.inside_bundle == 0)
5402         {
5403           /* PR8110: Cannot emit line number info inside a FLIX bundle
5404              when using --gstabs.  Temporarily disable debug info.  */
5405           generate_lineno_debug ();
5406           if (debug_type == DEBUG_STABS)
5407             {
5408               xt_saved_debug_type = debug_type;
5409               debug_type = DEBUG_NONE;
5410             }
5411
5412           cur_vinsn.inside_bundle = 1;
5413         }
5414       else
5415         {
5416           as_bad (_("extra opening brace"));
5417           return 0;
5418         }
5419       break;
5420
5421     case '}' :
5422       if (cur_vinsn.inside_bundle)
5423         finish_vinsn (&cur_vinsn);
5424       else
5425         {
5426           as_bad (_("extra closing brace"));
5427           return 0;
5428         }
5429       break;
5430     default:
5431       as_bad (_("syntax error"));
5432       return 0;
5433     }
5434   return 1;
5435 }
5436
5437
5438 /* md_flush_pending_output hook */
5439
5440 void
5441 xtensa_flush_pending_output (void)
5442 {
5443   /* This line fixes a bug where automatically generated gstabs info
5444      separates a function label from its entry instruction, ending up
5445      with the literal position between the function label and the entry
5446      instruction and crashing code.  It only happens with --gstabs and
5447      --text-section-literals, and when several other obscure relaxation
5448      conditions are met.  */
5449   if (outputting_stabs_line_debug)
5450     return;
5451
5452   if (cur_vinsn.inside_bundle)
5453     as_bad (_("missing closing brace"));
5454
5455   /* If there is a non-zero instruction fragment, close it.  */
5456   if (frag_now_fix () != 0 && frag_now->tc_frag_data.is_insn)
5457     {
5458       frag_wane (frag_now);
5459       frag_new (0);
5460       xtensa_set_frag_assembly_state (frag_now);
5461     }
5462   frag_now->tc_frag_data.is_insn = FALSE;
5463
5464   xtensa_clear_insn_labels ();
5465 }
5466
5467
5468 /* We had an error while parsing an instruction.  The string might look
5469    like this: "insn arg1, arg2 }".  If so, we need to see the closing
5470    brace and reset some fields.  Otherwise, the vinsn never gets closed
5471    and the num_slots field will grow past the end of the array of slots,
5472    and bad things happen.  */
5473
5474 static void
5475 error_reset_cur_vinsn (void)
5476 {
5477   if (cur_vinsn.inside_bundle)
5478     {
5479       if (*input_line_pointer == '}'
5480           || *(input_line_pointer - 1) == '}'
5481           || *(input_line_pointer - 2) == '}')
5482         xg_clear_vinsn (&cur_vinsn);
5483     }
5484 }
5485
5486
5487 void
5488 md_assemble (char *str)
5489 {
5490   xtensa_isa isa = xtensa_default_isa;
5491   char *opname;
5492   unsigned opnamelen;
5493   bfd_boolean has_underbar = FALSE;
5494   char *arg_strings[MAX_INSN_ARGS];
5495   int num_args;
5496   TInsn orig_insn;              /* Original instruction from the input.  */
5497
5498   tinsn_init (&orig_insn);
5499
5500   /* Split off the opcode.  */
5501   opnamelen = strspn (str, "abcdefghijklmnopqrstuvwxyz_/0123456789.");
5502   opname = xmalloc (opnamelen + 1);
5503   memcpy (opname, str, opnamelen);
5504   opname[opnamelen] = '\0';
5505
5506   num_args = tokenize_arguments (arg_strings, str + opnamelen);
5507   if (num_args == -1)
5508     {
5509       as_bad (_("syntax error"));
5510       return;
5511     }
5512
5513   if (xg_translate_idioms (&opname, &num_args, arg_strings))
5514     return;
5515
5516   /* Check for an underbar prefix.  */
5517   if (*opname == '_')
5518     {
5519       has_underbar = TRUE;
5520       opname += 1;
5521     }
5522
5523   orig_insn.insn_type = ITYPE_INSN;
5524   orig_insn.ntok = 0;
5525   orig_insn.is_specific_opcode = (has_underbar || !use_transform ());
5526   orig_insn.opcode = xtensa_opcode_lookup (isa, opname);
5527
5528   /* Special case: Check for "CALLXn.TLS" psuedo op.  If found, grab its
5529      extra argument and set the opcode to "CALLXn".  */
5530   if (orig_insn.opcode == XTENSA_UNDEFINED
5531       && strncasecmp (opname, "callx", 5) == 0)
5532     {
5533       unsigned long window_size;
5534       char *suffix;
5535
5536       window_size = strtoul (opname + 5, &suffix, 10);
5537       if (suffix != opname + 5
5538           && (window_size == 0
5539               || window_size == 4
5540               || window_size == 8
5541               || window_size == 12)
5542           && strcasecmp (suffix, ".tls") == 0)
5543         {
5544           switch (window_size)
5545             {
5546             case 0: orig_insn.opcode = xtensa_callx0_opcode; break;
5547             case 4: orig_insn.opcode = xtensa_callx4_opcode; break;
5548             case 8: orig_insn.opcode = xtensa_callx8_opcode; break;
5549             case 12: orig_insn.opcode = xtensa_callx12_opcode; break;
5550             }
5551
5552           if (num_args != 2)
5553             as_bad (_("wrong number of operands for '%s'"), opname);
5554           else
5555             {
5556               bfd_reloc_code_real_type reloc;
5557               char *old_input_line_pointer;
5558               expressionS *tok = &orig_insn.extra_arg;
5559
5560               old_input_line_pointer = input_line_pointer;
5561               input_line_pointer = arg_strings[num_args - 1];
5562
5563               expression (tok);
5564               if (tok->X_op == O_symbol
5565                   && ((reloc = xtensa_elf_suffix (&input_line_pointer, tok))
5566                       == BFD_RELOC_XTENSA_TLS_CALL))
5567                 tok->X_op = map_suffix_reloc_to_operator (reloc);
5568               else
5569                 as_bad (_("bad relocation expression for '%s'"), opname);
5570
5571               input_line_pointer = old_input_line_pointer;
5572               num_args -= 1;
5573             }
5574         }
5575     }
5576
5577   /* Special case: Check for "j.l" psuedo op.  */
5578   if (orig_insn.opcode == XTENSA_UNDEFINED
5579       && strncasecmp (opname, "j.l", 3) == 0)
5580     {
5581       if (num_args != 2)
5582         as_bad (_("wrong number of operands for '%s'"), opname);
5583       else
5584         {
5585           char *old_input_line_pointer;
5586           expressionS *tok = &orig_insn.extra_arg;
5587
5588           old_input_line_pointer = input_line_pointer;
5589           input_line_pointer = arg_strings[num_args - 1];
5590
5591           expression_maybe_register (xtensa_jx_opcode, 0, tok);
5592           input_line_pointer = old_input_line_pointer;
5593
5594           num_args -= 1;
5595           orig_insn.opcode = xtensa_j_opcode;
5596         }
5597     }
5598
5599   if (orig_insn.opcode == XTENSA_UNDEFINED)
5600     {
5601       xtensa_format fmt = xtensa_format_lookup (isa, opname);
5602       if (fmt == XTENSA_UNDEFINED)
5603         {
5604           as_bad (_("unknown opcode or format name '%s'"), opname);
5605           error_reset_cur_vinsn ();
5606           return;
5607         }
5608       if (!cur_vinsn.inside_bundle)
5609         {
5610           as_bad (_("format names only valid inside bundles"));
5611           error_reset_cur_vinsn ();
5612           return;
5613         }
5614       if (cur_vinsn.format != XTENSA_UNDEFINED)
5615         as_warn (_("multiple formats specified for one bundle; using '%s'"),
5616                  opname);
5617       cur_vinsn.format = fmt;
5618       free (has_underbar ? opname - 1 : opname);
5619       error_reset_cur_vinsn ();
5620       return;
5621     }
5622
5623   /* Parse the arguments.  */
5624   if (parse_arguments (&orig_insn, num_args, arg_strings))
5625     {
5626       as_bad (_("syntax error"));
5627       error_reset_cur_vinsn ();
5628       return;
5629     }
5630
5631   /* Free the opcode and argument strings, now that they've been parsed.  */
5632   free (has_underbar ? opname - 1 : opname);
5633   opname = 0;
5634   while (num_args-- > 0)
5635     free (arg_strings[num_args]);
5636
5637   /* Get expressions for invisible operands.  */
5638   if (get_invisible_operands (&orig_insn))
5639     {
5640       error_reset_cur_vinsn ();
5641       return;
5642     }
5643
5644   /* Check for the right number and type of arguments.  */
5645   if (tinsn_check_arguments (&orig_insn))
5646     {
5647       error_reset_cur_vinsn ();
5648       return;
5649     }
5650
5651   /* Record the line number for each TInsn, because a FLIX bundle may be
5652      spread across multiple input lines and individual instructions may be
5653      moved around in some cases.  */
5654   orig_insn.loc_directive_seen = dwarf2_loc_directive_seen;
5655   dwarf2_where (&orig_insn.debug_line);
5656   dwarf2_consume_line_info ();
5657
5658   xg_add_branch_and_loop_targets (&orig_insn);
5659
5660   /* Check that immediate value for ENTRY is >= 16.  */
5661   if (orig_insn.opcode == xtensa_entry_opcode && orig_insn.ntok >= 3)
5662     {
5663       expressionS *exp = &orig_insn.tok[2];
5664       if (exp->X_op == O_constant && exp->X_add_number < 16)
5665         as_warn (_("entry instruction with stack decrement < 16"));
5666     }
5667
5668   /* Finish it off:
5669      assemble_tokens (opcode, tok, ntok);
5670      expand the tokens from the orig_insn into the
5671      stack of instructions that will not expand
5672      unless required at relaxation time.  */
5673
5674   if (!cur_vinsn.inside_bundle)
5675     emit_single_op (&orig_insn);
5676   else /* We are inside a bundle.  */
5677     {
5678       cur_vinsn.slots[cur_vinsn.num_slots] = orig_insn;
5679       cur_vinsn.num_slots++;
5680       if (*input_line_pointer == '}'
5681           || *(input_line_pointer - 1) == '}'
5682           || *(input_line_pointer - 2) == '}')
5683         finish_vinsn (&cur_vinsn);
5684     }
5685
5686   /* We've just emitted a new instruction so clear the list of labels.  */
5687   xtensa_clear_insn_labels ();
5688
5689   xtensa_check_frag_count ();
5690 }
5691
5692
5693 /* HANDLE_ALIGN hook */
5694
5695 /* For a .align directive, we mark the previous block with the alignment
5696    information.  This will be placed in the object file in the
5697    property section corresponding to this section.  */
5698
5699 void
5700 xtensa_handle_align (fragS *fragP)
5701 {
5702   if (linkrelax
5703       && ! fragP->tc_frag_data.is_literal
5704       && (fragP->fr_type == rs_align
5705           || fragP->fr_type == rs_align_code)
5706       && fragP->fr_offset > 0
5707       && now_seg != bss_section)
5708     {
5709       fragP->tc_frag_data.is_align = TRUE;
5710       fragP->tc_frag_data.alignment = fragP->fr_offset;
5711     }
5712
5713   if (fragP->fr_type == rs_align_test)
5714     {
5715       int count;
5716       count = fragP->fr_next->fr_address - fragP->fr_address - fragP->fr_fix;
5717       if (count != 0)
5718         as_bad_where (fragP->fr_file, fragP->fr_line,
5719                       _("unaligned entry instruction"));
5720     }
5721
5722   if (linkrelax && fragP->fr_type == rs_org)
5723     fragP->fr_subtype = RELAX_ORG;
5724 }
5725
5726
5727 /* TC_FRAG_INIT hook */
5728
5729 void
5730 xtensa_frag_init (fragS *frag)
5731 {
5732   xtensa_set_frag_assembly_state (frag);
5733 }
5734
5735
5736 symbolS *
5737 md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
5738 {
5739   return NULL;
5740 }
5741
5742
5743 /* Round up a section size to the appropriate boundary.  */
5744
5745 valueT
5746 md_section_align (segT segment ATTRIBUTE_UNUSED, valueT size)
5747 {
5748   return size;                  /* Byte alignment is fine.  */
5749 }
5750
5751
5752 long
5753 md_pcrel_from (fixS *fixP)
5754 {
5755   char *insn_p;
5756   static xtensa_insnbuf insnbuf = NULL;
5757   static xtensa_insnbuf slotbuf = NULL;
5758   int opnum;
5759   uint32 opnd_value;
5760   xtensa_opcode opcode;
5761   xtensa_format fmt;
5762   int slot;
5763   xtensa_isa isa = xtensa_default_isa;
5764   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
5765   bfd_boolean alt_reloc;
5766
5767   if (fixP->fx_r_type == BFD_RELOC_XTENSA_ASM_EXPAND)
5768     return 0;
5769
5770   if (fixP->fx_r_type == BFD_RELOC_32_PCREL)
5771     return addr;
5772
5773   if (!insnbuf)
5774     {
5775       insnbuf = xtensa_insnbuf_alloc (isa);
5776       slotbuf = xtensa_insnbuf_alloc (isa);
5777     }
5778
5779   insn_p = &fixP->fx_frag->fr_literal[fixP->fx_where];
5780   xtensa_insnbuf_from_chars (isa, insnbuf, (unsigned char *) insn_p, 0);
5781   fmt = xtensa_format_decode (isa, insnbuf);
5782
5783   if (fmt == XTENSA_UNDEFINED)
5784     as_fatal (_("bad instruction format"));
5785
5786   if (decode_reloc (fixP->fx_r_type, &slot, &alt_reloc) != 0)
5787     as_fatal (_("invalid relocation"));
5788
5789   xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
5790   opcode = xtensa_opcode_decode (isa, fmt, slot, slotbuf);
5791
5792   /* Check for "alternate" relocations (operand not specified).  None
5793      of the current uses for these are really PC-relative.  */
5794   if (alt_reloc || opcode == xtensa_const16_opcode)
5795     {
5796       if (opcode != xtensa_l32r_opcode
5797           && opcode != xtensa_const16_opcode)
5798         as_fatal (_("invalid relocation for '%s' instruction"),
5799                   xtensa_opcode_name (isa, opcode));
5800       return 0;
5801     }
5802
5803   opnum = get_relaxable_immed (opcode);
5804   opnd_value = 0;
5805   if (xtensa_operand_is_PCrelative (isa, opcode, opnum) != 1
5806       || xtensa_operand_do_reloc (isa, opcode, opnum, &opnd_value, addr))
5807     {
5808       as_bad_where (fixP->fx_file,
5809                     fixP->fx_line,
5810                     _("invalid relocation for operand %d of '%s'"),
5811                     opnum, xtensa_opcode_name (isa, opcode));
5812       return 0;
5813     }
5814   return 0 - opnd_value;
5815 }
5816
5817
5818 /* TC_FORCE_RELOCATION hook */
5819
5820 int
5821 xtensa_force_relocation (fixS *fix)
5822 {
5823   switch (fix->fx_r_type)
5824     {
5825     case BFD_RELOC_XTENSA_ASM_EXPAND:
5826     case BFD_RELOC_XTENSA_SLOT0_ALT:
5827     case BFD_RELOC_XTENSA_SLOT1_ALT:
5828     case BFD_RELOC_XTENSA_SLOT2_ALT:
5829     case BFD_RELOC_XTENSA_SLOT3_ALT:
5830     case BFD_RELOC_XTENSA_SLOT4_ALT:
5831     case BFD_RELOC_XTENSA_SLOT5_ALT:
5832     case BFD_RELOC_XTENSA_SLOT6_ALT:
5833     case BFD_RELOC_XTENSA_SLOT7_ALT:
5834     case BFD_RELOC_XTENSA_SLOT8_ALT:
5835     case BFD_RELOC_XTENSA_SLOT9_ALT:
5836     case BFD_RELOC_XTENSA_SLOT10_ALT:
5837     case BFD_RELOC_XTENSA_SLOT11_ALT:
5838     case BFD_RELOC_XTENSA_SLOT12_ALT:
5839     case BFD_RELOC_XTENSA_SLOT13_ALT:
5840     case BFD_RELOC_XTENSA_SLOT14_ALT:
5841       return 1;
5842     default:
5843       break;
5844     }
5845
5846   if (linkrelax && fix->fx_addsy
5847       && relaxable_section (S_GET_SEGMENT (fix->fx_addsy)))
5848     return 1;
5849
5850   return generic_force_reloc (fix);
5851 }
5852
5853
5854 /* TC_VALIDATE_FIX_SUB hook */
5855
5856 int
5857 xtensa_validate_fix_sub (fixS *fix)
5858 {
5859   segT add_symbol_segment, sub_symbol_segment;
5860
5861   /* The difference of two symbols should be resolved by the assembler when
5862      linkrelax is not set.  If the linker may relax the section containing
5863      the symbols, then an Xtensa DIFF relocation must be generated so that
5864      the linker knows to adjust the difference value.  */
5865   if (!linkrelax || fix->fx_addsy == NULL)
5866     return 0;
5867
5868   /* Make sure both symbols are in the same segment, and that segment is
5869      "normal" and relaxable.  If the segment is not "normal", then the
5870      fix is not valid.  If the segment is not "relaxable", then the fix
5871      should have been handled earlier.  */
5872   add_symbol_segment = S_GET_SEGMENT (fix->fx_addsy);
5873   if (! SEG_NORMAL (add_symbol_segment) ||
5874       ! relaxable_section (add_symbol_segment))
5875     return 0;
5876   sub_symbol_segment = S_GET_SEGMENT (fix->fx_subsy);
5877   return (sub_symbol_segment == add_symbol_segment);
5878 }
5879
5880
5881 /* NO_PSEUDO_DOT hook */
5882
5883 /* This function has nothing to do with pseudo dots, but this is the
5884    nearest macro to where the check needs to take place.  FIXME: This
5885    seems wrong.  */
5886
5887 bfd_boolean
5888 xtensa_check_inside_bundle (void)
5889 {
5890   if (cur_vinsn.inside_bundle && input_line_pointer[-1] == '.')
5891     as_bad (_("directives are not valid inside bundles"));
5892
5893   /* This function must always return FALSE because it is called via a
5894      macro that has nothing to do with bundling.  */
5895   return FALSE;
5896 }
5897
5898
5899 /* md_elf_section_change_hook */
5900
5901 void
5902 xtensa_elf_section_change_hook (void)
5903 {
5904   /* Set up the assembly state.  */
5905   if (!frag_now->tc_frag_data.is_assembly_state_set)
5906     xtensa_set_frag_assembly_state (frag_now);
5907 }
5908
5909
5910 /* tc_fix_adjustable hook */
5911
5912 bfd_boolean
5913 xtensa_fix_adjustable (fixS *fixP)
5914 {
5915   /* We need the symbol name for the VTABLE entries.  */
5916   if (fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
5917       || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
5918     return 0;
5919
5920   return 1;
5921 }
5922
5923
5924 /* tc_symbol_new_hook */
5925
5926 symbolS *expr_symbols = NULL;
5927
5928 void
5929 xtensa_symbol_new_hook (symbolS *sym)
5930 {
5931   if (is_leb128_expr && S_GET_SEGMENT (sym) == expr_section)
5932     {
5933       symbol_get_tc (sym)->next_expr_symbol = expr_symbols;
5934       expr_symbols = sym;
5935     }
5936 }
5937
5938
5939 void
5940 md_apply_fix (fixS *fixP, valueT *valP, segT seg)
5941 {
5942   char *const fixpos = fixP->fx_frag->fr_literal + fixP->fx_where;
5943   valueT val = 0;
5944
5945   /* Subtracted symbols are only allowed for a few relocation types, and
5946      unless linkrelax is enabled, they should not make it to this point.  */
5947   if (fixP->fx_subsy && !(linkrelax && (fixP->fx_r_type == BFD_RELOC_32
5948                                         || fixP->fx_r_type == BFD_RELOC_16
5949                                         || fixP->fx_r_type == BFD_RELOC_8)))
5950     as_bad_where (fixP->fx_file, fixP->fx_line, _("expression too complex"));
5951
5952   switch (fixP->fx_r_type)
5953     {
5954     case BFD_RELOC_32_PCREL:
5955     case BFD_RELOC_32:
5956     case BFD_RELOC_16:
5957     case BFD_RELOC_8:
5958       if (fixP->fx_subsy)
5959         {
5960           switch (fixP->fx_r_type)
5961             {
5962             case BFD_RELOC_8:
5963               fixP->fx_r_type = BFD_RELOC_XTENSA_DIFF8;
5964               fixP->fx_signed = 0;
5965               break;
5966             case BFD_RELOC_16:
5967               fixP->fx_r_type = BFD_RELOC_XTENSA_DIFF16;
5968               fixP->fx_signed = 0;
5969               break;
5970             case BFD_RELOC_32:
5971               fixP->fx_r_type = BFD_RELOC_XTENSA_DIFF32;
5972               fixP->fx_signed = 0;
5973               break;
5974             default:
5975               break;
5976             }
5977
5978           val = (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset
5979                  - S_GET_VALUE (fixP->fx_subsy));
5980
5981           /* The difference value gets written out, and the DIFF reloc
5982              identifies the address of the subtracted symbol (i.e., the one
5983              with the lowest address).  */
5984           *valP = val;
5985           fixP->fx_offset -= val;
5986           fixP->fx_subsy = NULL;
5987         }
5988       else if (! fixP->fx_addsy)
5989         {
5990           val = *valP;
5991           fixP->fx_done = 1;
5992         }
5993       /* fall through */
5994
5995     case BFD_RELOC_XTENSA_PLT:
5996       md_number_to_chars (fixpos, val, fixP->fx_size);
5997       fixP->fx_no_overflow = 0; /* Use the standard overflow check.  */
5998       break;
5999
6000     case BFD_RELOC_XTENSA_TLSDESC_FN:
6001     case BFD_RELOC_XTENSA_TLSDESC_ARG:
6002     case BFD_RELOC_XTENSA_TLS_TPOFF:
6003     case BFD_RELOC_XTENSA_TLS_DTPOFF:
6004       S_SET_THREAD_LOCAL (fixP->fx_addsy);
6005       md_number_to_chars (fixpos, 0, fixP->fx_size);
6006       fixP->fx_no_overflow = 0; /* Use the standard overflow check.  */
6007       break;
6008
6009     case BFD_RELOC_XTENSA_SLOT0_OP:
6010     case BFD_RELOC_XTENSA_SLOT1_OP:
6011     case BFD_RELOC_XTENSA_SLOT2_OP:
6012     case BFD_RELOC_XTENSA_SLOT3_OP:
6013     case BFD_RELOC_XTENSA_SLOT4_OP:
6014     case BFD_RELOC_XTENSA_SLOT5_OP:
6015     case BFD_RELOC_XTENSA_SLOT6_OP:
6016     case BFD_RELOC_XTENSA_SLOT7_OP:
6017     case BFD_RELOC_XTENSA_SLOT8_OP:
6018     case BFD_RELOC_XTENSA_SLOT9_OP:
6019     case BFD_RELOC_XTENSA_SLOT10_OP:
6020     case BFD_RELOC_XTENSA_SLOT11_OP:
6021     case BFD_RELOC_XTENSA_SLOT12_OP:
6022     case BFD_RELOC_XTENSA_SLOT13_OP:
6023     case BFD_RELOC_XTENSA_SLOT14_OP:
6024       if (linkrelax)
6025         {
6026           /* Write the tentative value of a PC-relative relocation to a
6027              local symbol into the instruction.  The value will be ignored
6028              by the linker, and it makes the object file disassembly
6029              readable when all branch targets are encoded in relocations.  */
6030
6031           gas_assert (fixP->fx_addsy);
6032           if (S_GET_SEGMENT (fixP->fx_addsy) == seg
6033               && !S_FORCE_RELOC (fixP->fx_addsy, 1))
6034             {
6035               val = (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset
6036                      - md_pcrel_from (fixP));
6037               (void) xg_apply_fix_value (fixP, val);
6038             }
6039         }
6040       else if (! fixP->fx_addsy)
6041         {
6042           val = *valP;
6043           if (xg_apply_fix_value (fixP, val))
6044             fixP->fx_done = 1;
6045         }
6046       break;
6047
6048     case BFD_RELOC_XTENSA_ASM_EXPAND:
6049     case BFD_RELOC_XTENSA_TLS_FUNC:
6050     case BFD_RELOC_XTENSA_TLS_ARG:
6051     case BFD_RELOC_XTENSA_TLS_CALL:
6052     case BFD_RELOC_XTENSA_SLOT0_ALT:
6053     case BFD_RELOC_XTENSA_SLOT1_ALT:
6054     case BFD_RELOC_XTENSA_SLOT2_ALT:
6055     case BFD_RELOC_XTENSA_SLOT3_ALT:
6056     case BFD_RELOC_XTENSA_SLOT4_ALT:
6057     case BFD_RELOC_XTENSA_SLOT5_ALT:
6058     case BFD_RELOC_XTENSA_SLOT6_ALT:
6059     case BFD_RELOC_XTENSA_SLOT7_ALT:
6060     case BFD_RELOC_XTENSA_SLOT8_ALT:
6061     case BFD_RELOC_XTENSA_SLOT9_ALT:
6062     case BFD_RELOC_XTENSA_SLOT10_ALT:
6063     case BFD_RELOC_XTENSA_SLOT11_ALT:
6064     case BFD_RELOC_XTENSA_SLOT12_ALT:
6065     case BFD_RELOC_XTENSA_SLOT13_ALT:
6066     case BFD_RELOC_XTENSA_SLOT14_ALT:
6067       /* These all need to be resolved at link-time.  Do nothing now.  */
6068       break;
6069
6070     case BFD_RELOC_VTABLE_INHERIT:
6071     case BFD_RELOC_VTABLE_ENTRY:
6072       fixP->fx_done = 0;
6073       break;
6074
6075     default:
6076       as_bad (_("unhandled local relocation fix %s"),
6077               bfd_get_reloc_code_name (fixP->fx_r_type));
6078     }
6079 }
6080
6081
6082 char *
6083 md_atof (int type, char *litP, int *sizeP)
6084 {
6085   return ieee_md_atof (type, litP, sizeP, target_big_endian);
6086 }
6087
6088
6089 int
6090 md_estimate_size_before_relax (fragS *fragP, segT seg ATTRIBUTE_UNUSED)
6091 {
6092   return total_frag_text_expansion (fragP);
6093 }
6094
6095
6096 /* Translate internal representation of relocation info to BFD target
6097    format.  */
6098
6099 arelent *
6100 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
6101 {
6102   arelent *reloc;
6103
6104   reloc = (arelent *) xmalloc (sizeof (arelent));
6105   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
6106   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
6107   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
6108
6109   /* Make sure none of our internal relocations make it this far.
6110      They'd better have been fully resolved by this point.  */
6111   gas_assert ((int) fixp->fx_r_type > 0);
6112
6113   reloc->addend = fixp->fx_offset;
6114
6115   reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
6116   if (reloc->howto == NULL)
6117     {
6118       as_bad_where (fixp->fx_file, fixp->fx_line,
6119                     _("cannot represent `%s' relocation in object file"),
6120                     bfd_get_reloc_code_name (fixp->fx_r_type));
6121       free (reloc->sym_ptr_ptr);
6122       free (reloc);
6123       return NULL;
6124     }
6125
6126   if (!fixp->fx_pcrel != !reloc->howto->pc_relative)
6127     as_fatal (_("internal error; cannot generate `%s' relocation"),
6128               bfd_get_reloc_code_name (fixp->fx_r_type));
6129
6130   return reloc;
6131 }
6132
6133 \f
6134 /* Checks for resource conflicts between instructions.  */
6135
6136 /* The func unit stuff could be implemented as bit-vectors rather
6137    than the iterative approach here.  If it ends up being too
6138    slow, we will switch it.  */
6139
6140 resource_table *
6141 new_resource_table (void *data,
6142                     int cycles,
6143                     int nu,
6144                     unit_num_copies_func uncf,
6145                     opcode_num_units_func onuf,
6146                     opcode_funcUnit_use_unit_func ouuf,
6147                     opcode_funcUnit_use_stage_func ousf)
6148 {
6149   int i;
6150   resource_table *rt = (resource_table *) xmalloc (sizeof (resource_table));
6151   rt->data = data;
6152   rt->cycles = cycles;
6153   rt->allocated_cycles = cycles;
6154   rt->num_units = nu;
6155   rt->unit_num_copies = uncf;
6156   rt->opcode_num_units = onuf;
6157   rt->opcode_unit_use = ouuf;
6158   rt->opcode_unit_stage = ousf;
6159
6160   rt->units = (unsigned char **) xcalloc (cycles, sizeof (unsigned char *));
6161   for (i = 0; i < cycles; i++)
6162     rt->units[i] = (unsigned char *) xcalloc (nu, sizeof (unsigned char));
6163
6164   return rt;
6165 }
6166
6167
6168 void
6169 clear_resource_table (resource_table *rt)
6170 {
6171   int i, j;
6172   for (i = 0; i < rt->allocated_cycles; i++)
6173     for (j = 0; j < rt->num_units; j++)
6174       rt->units[i][j] = 0;
6175 }
6176
6177
6178 /* We never shrink it, just fake it into thinking so.  */
6179
6180 void
6181 resize_resource_table (resource_table *rt, int cycles)
6182 {
6183   int i, old_cycles;
6184
6185   rt->cycles = cycles;
6186   if (cycles <= rt->allocated_cycles)
6187     return;
6188
6189   old_cycles = rt->allocated_cycles;
6190   rt->allocated_cycles = cycles;
6191
6192   rt->units = xrealloc (rt->units,
6193                         rt->allocated_cycles * sizeof (unsigned char *));
6194   for (i = 0; i < old_cycles; i++)
6195     rt->units[i] = xrealloc (rt->units[i],
6196                              rt->num_units * sizeof (unsigned char));
6197   for (i = old_cycles; i < cycles; i++)
6198     rt->units[i] = xcalloc (rt->num_units, sizeof (unsigned char));
6199 }
6200
6201
6202 bfd_boolean
6203 resources_available (resource_table *rt, xtensa_opcode opcode, int cycle)
6204 {
6205   int i;
6206   int uses = (rt->opcode_num_units) (rt->data, opcode);
6207
6208   for (i = 0; i < uses; i++)
6209     {
6210       xtensa_funcUnit unit = (rt->opcode_unit_use) (rt->data, opcode, i);
6211       int stage = (rt->opcode_unit_stage) (rt->data, opcode, i);
6212       int copies_in_use = rt->units[stage + cycle][unit];
6213       int copies = (rt->unit_num_copies) (rt->data, unit);
6214       if (copies_in_use >= copies)
6215         return FALSE;
6216     }
6217   return TRUE;
6218 }
6219
6220
6221 void
6222 reserve_resources (resource_table *rt, xtensa_opcode opcode, int cycle)
6223 {
6224   int i;
6225   int uses = (rt->opcode_num_units) (rt->data, opcode);
6226
6227   for (i = 0; i < uses; i++)
6228     {
6229       xtensa_funcUnit unit = (rt->opcode_unit_use) (rt->data, opcode, i);
6230       int stage = (rt->opcode_unit_stage) (rt->data, opcode, i);
6231       /* Note that this allows resources to be oversubscribed.  That's
6232          essential to the way the optional scheduler works.
6233          resources_available reports when a resource is over-subscribed,
6234          so it's easy to tell.  */
6235       rt->units[stage + cycle][unit]++;
6236     }
6237 }
6238
6239
6240 void
6241 release_resources (resource_table *rt, xtensa_opcode opcode, int cycle)
6242 {
6243   int i;
6244   int uses = (rt->opcode_num_units) (rt->data, opcode);
6245
6246   for (i = 0; i < uses; i++)
6247     {
6248       xtensa_funcUnit unit = (rt->opcode_unit_use) (rt->data, opcode, i);
6249       int stage = (rt->opcode_unit_stage) (rt->data, opcode, i);
6250       gas_assert (rt->units[stage + cycle][unit] > 0);
6251       rt->units[stage + cycle][unit]--;
6252     }
6253 }
6254
6255
6256 /* Wrapper functions make parameterized resource reservation
6257    more convenient.  */
6258
6259 int
6260 opcode_funcUnit_use_unit (void *data, xtensa_opcode opcode, int idx)
6261 {
6262   xtensa_funcUnit_use *use = xtensa_opcode_funcUnit_use (data, opcode, idx);
6263   return use->unit;
6264 }
6265
6266
6267 int
6268 opcode_funcUnit_use_stage (void *data, xtensa_opcode opcode, int idx)
6269 {
6270   xtensa_funcUnit_use *use = xtensa_opcode_funcUnit_use (data, opcode, idx);
6271   return use->stage;
6272 }
6273
6274
6275 /* Note that this function does not check issue constraints, but
6276    solely whether the hardware is available to execute the given
6277    instructions together.  It also doesn't check if the tinsns
6278    write the same state, or access the same tieports.  That is
6279    checked by check_t1_t2_reads_and_writes.  */
6280
6281 static bfd_boolean
6282 resources_conflict (vliw_insn *vinsn)
6283 {
6284   int i;
6285   static resource_table *rt = NULL;
6286
6287   /* This is the most common case by far.  Optimize it.  */
6288   if (vinsn->num_slots == 1)
6289     return FALSE;
6290
6291   if (rt == NULL)
6292     {
6293       xtensa_isa isa = xtensa_default_isa;
6294       rt = new_resource_table
6295         (isa, xtensa_num_pipe_stages,
6296          xtensa_isa_num_funcUnits (isa),
6297          (unit_num_copies_func) xtensa_funcUnit_num_copies,
6298          (opcode_num_units_func) xtensa_opcode_num_funcUnit_uses,
6299          opcode_funcUnit_use_unit,
6300          opcode_funcUnit_use_stage);
6301     }
6302
6303   clear_resource_table (rt);
6304
6305   for (i = 0; i < vinsn->num_slots; i++)
6306     {
6307       if (!resources_available (rt, vinsn->slots[i].opcode, 0))
6308         return TRUE;
6309       reserve_resources (rt, vinsn->slots[i].opcode, 0);
6310     }
6311
6312   return FALSE;
6313 }
6314
6315 \f
6316 /* finish_vinsn, emit_single_op and helper functions.  */
6317
6318 static bfd_boolean find_vinsn_conflicts (vliw_insn *);
6319 static xtensa_format xg_find_narrowest_format (vliw_insn *);
6320 static void xg_assemble_vliw_tokens (vliw_insn *);
6321
6322
6323 /* We have reached the end of a bundle; emit into the frag.  */
6324
6325 static void
6326 finish_vinsn (vliw_insn *vinsn)
6327 {
6328   IStack slotstack;
6329   int i;
6330
6331   if (find_vinsn_conflicts (vinsn))
6332     {
6333       xg_clear_vinsn (vinsn);
6334       return;
6335     }
6336
6337   /* First, find a format that works.  */
6338   if (vinsn->format == XTENSA_UNDEFINED)
6339     vinsn->format = xg_find_narrowest_format (vinsn);
6340
6341   if (xtensa_format_num_slots (xtensa_default_isa, vinsn->format) > 1
6342       && produce_flix == FLIX_NONE)
6343     {
6344       as_bad (_("The option \"--no-allow-flix\" prohibits multi-slot flix."));
6345       xg_clear_vinsn (vinsn);
6346       return;
6347     }
6348
6349   if (vinsn->format == XTENSA_UNDEFINED)
6350     {
6351       as_bad (_("couldn't find a valid instruction format"));
6352       fprintf (stderr, _("    ops were: "));
6353       for (i = 0; i < vinsn->num_slots; i++)
6354         fprintf (stderr, _(" %s;"),
6355                  xtensa_opcode_name (xtensa_default_isa,
6356                                      vinsn->slots[i].opcode));
6357       fprintf (stderr, _("\n"));
6358       xg_clear_vinsn (vinsn);
6359       return;
6360     }
6361
6362   if (vinsn->num_slots
6363       != xtensa_format_num_slots (xtensa_default_isa, vinsn->format))
6364     {
6365       as_bad (_("format '%s' allows %d slots, but there are %d opcodes"),
6366               xtensa_format_name (xtensa_default_isa, vinsn->format),
6367               xtensa_format_num_slots (xtensa_default_isa, vinsn->format),
6368               vinsn->num_slots);
6369       xg_clear_vinsn (vinsn);
6370       return;
6371     }
6372
6373   if (resources_conflict (vinsn))
6374     {
6375       as_bad (_("illegal resource usage in bundle"));
6376       fprintf (stderr, "    ops were: ");
6377       for (i = 0; i < vinsn->num_slots; i++)
6378         fprintf (stderr, " %s;",
6379                  xtensa_opcode_name (xtensa_default_isa,
6380                                      vinsn->slots[i].opcode));
6381       fprintf (stderr, "\n");
6382       xg_clear_vinsn (vinsn);
6383       return;
6384     }
6385
6386   for (i = 0; i < vinsn->num_slots; i++)
6387     {
6388       if (vinsn->slots[i].opcode != XTENSA_UNDEFINED)
6389         {
6390           symbolS *lit_sym = NULL;
6391           int j;
6392           bfd_boolean e = FALSE;
6393           bfd_boolean saved_density = density_supported;
6394
6395           /* We don't want to narrow ops inside multi-slot bundles.  */
6396           if (vinsn->num_slots > 1)
6397             density_supported = FALSE;
6398
6399           istack_init (&slotstack);
6400           if (vinsn->slots[i].opcode == xtensa_nop_opcode)
6401             {
6402               vinsn->slots[i].opcode =
6403                 xtensa_format_slot_nop_opcode (xtensa_default_isa,
6404                                                vinsn->format, i);
6405               vinsn->slots[i].ntok = 0;
6406             }
6407
6408           if (xg_expand_assembly_insn (&slotstack, &vinsn->slots[i]))
6409             {
6410               e = TRUE;
6411               continue;
6412             }
6413
6414           density_supported = saved_density;
6415
6416           if (e)
6417             {
6418               xg_clear_vinsn (vinsn);
6419               return;
6420             }
6421
6422           for (j = 0; j < slotstack.ninsn; j++)
6423             {
6424               TInsn *insn = &slotstack.insn[j];
6425               if (insn->insn_type == ITYPE_LITERAL)
6426                 {
6427                   gas_assert (lit_sym == NULL);
6428                   lit_sym = xg_assemble_literal (insn);
6429                 }
6430               else
6431                 {
6432                   gas_assert (insn->insn_type == ITYPE_INSN);
6433                   if (lit_sym)
6434                     xg_resolve_literals (insn, lit_sym);
6435                   if (j != slotstack.ninsn - 1)
6436                     emit_single_op (insn);
6437                 }
6438             }
6439
6440           if (vinsn->num_slots > 1)
6441             {
6442               if (opcode_fits_format_slot
6443                   (slotstack.insn[slotstack.ninsn - 1].opcode,
6444                    vinsn->format, i))
6445                 {
6446                   vinsn->slots[i] = slotstack.insn[slotstack.ninsn - 1];
6447                 }
6448               else
6449                 {
6450                   emit_single_op (&slotstack.insn[slotstack.ninsn - 1]);
6451                   if (vinsn->format == XTENSA_UNDEFINED)
6452                     vinsn->slots[i].opcode = xtensa_nop_opcode;
6453                   else
6454                     vinsn->slots[i].opcode
6455                       = xtensa_format_slot_nop_opcode (xtensa_default_isa,
6456                                                        vinsn->format, i);
6457
6458                   vinsn->slots[i].ntok = 0;
6459                 }
6460             }
6461           else
6462             {
6463               vinsn->slots[0] = slotstack.insn[slotstack.ninsn - 1];
6464               vinsn->format = XTENSA_UNDEFINED;
6465             }
6466         }
6467     }
6468
6469   /* Now check resource conflicts on the modified bundle.  */
6470   if (resources_conflict (vinsn))
6471     {
6472       as_bad (_("illegal resource usage in bundle"));
6473       fprintf (stderr, "    ops were: ");
6474       for (i = 0; i < vinsn->num_slots; i++)
6475         fprintf (stderr, " %s;",
6476                  xtensa_opcode_name (xtensa_default_isa,
6477                                      vinsn->slots[i].opcode));
6478       fprintf (stderr, "\n");
6479       xg_clear_vinsn (vinsn);
6480       return;
6481     }
6482
6483   /* First, find a format that works.  */
6484   if (vinsn->format == XTENSA_UNDEFINED)
6485       vinsn->format = xg_find_narrowest_format (vinsn);
6486
6487   xg_assemble_vliw_tokens (vinsn);
6488
6489   xg_clear_vinsn (vinsn);
6490
6491   xtensa_check_frag_count ();
6492 }
6493
6494
6495 /* Given an vliw instruction, what conflicts are there in register
6496    usage and in writes to states and queues?
6497
6498    This function does two things:
6499    1. Reports an error when a vinsn contains illegal combinations
6500       of writes to registers states or queues.
6501    2. Marks individual tinsns as not relaxable if the combination
6502       contains antidependencies.
6503
6504    Job 2 handles things like swap semantics in instructions that need
6505    to be relaxed.  For example,
6506
6507         addi a0, a1, 100000
6508
6509    normally would be relaxed to
6510
6511         l32r a0, some_label
6512         add a0, a1, a0
6513
6514    _but_, if the above instruction is bundled with an a0 reader, e.g.,
6515
6516         { addi a0, a1, 10000 ; add a2, a0, a4 ; }
6517
6518    then we can't relax it into
6519
6520         l32r a0, some_label
6521         { add a0, a1, a0 ; add a2, a0, a4 ; }
6522
6523    because the value of a0 is trashed before the second add can read it.  */
6524
6525 static char check_t1_t2_reads_and_writes (TInsn *, TInsn *);
6526
6527 static bfd_boolean
6528 find_vinsn_conflicts (vliw_insn *vinsn)
6529 {
6530   int i, j;
6531   int branches = 0;
6532   xtensa_isa isa = xtensa_default_isa;
6533
6534   gas_assert (!past_xtensa_end);
6535
6536   for (i = 0 ; i < vinsn->num_slots; i++)
6537     {
6538       TInsn *op1 = &vinsn->slots[i];
6539       if (op1->is_specific_opcode)
6540         op1->keep_wide = TRUE;
6541       else
6542         op1->keep_wide = FALSE;
6543     }
6544
6545   for (i = 0 ; i < vinsn->num_slots; i++)
6546     {
6547       TInsn *op1 = &vinsn->slots[i];
6548
6549       if (xtensa_opcode_is_branch (isa, op1->opcode) == 1)
6550         branches++;
6551
6552       for (j = 0; j < vinsn->num_slots; j++)
6553         {
6554           if (i != j)
6555             {
6556               TInsn *op2 = &vinsn->slots[j];
6557               char conflict_type = check_t1_t2_reads_and_writes (op1, op2);
6558               switch (conflict_type)
6559                 {
6560                 case 'c':
6561                   as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) write the same register"),
6562                           xtensa_opcode_name (isa, op1->opcode), i,
6563                           xtensa_opcode_name (isa, op2->opcode), j);
6564                   return TRUE;
6565                 case 'd':
6566                   as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) write the same state"),
6567                           xtensa_opcode_name (isa, op1->opcode), i,
6568                           xtensa_opcode_name (isa, op2->opcode), j);
6569                   return TRUE;
6570                 case 'e':
6571                   as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) write the same port"),
6572                           xtensa_opcode_name (isa, op1->opcode), i,
6573                           xtensa_opcode_name (isa, op2->opcode), j);
6574                   return TRUE;
6575                 case 'f':
6576                   as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) both have volatile port accesses"),
6577                           xtensa_opcode_name (isa, op1->opcode), i,
6578                           xtensa_opcode_name (isa, op2->opcode), j);
6579                   return TRUE;
6580                 default:
6581                   /* Everything is OK.  */
6582                   break;
6583                 }
6584               op2->is_specific_opcode = (op2->is_specific_opcode
6585                                          || conflict_type == 'a');
6586             }
6587         }
6588     }
6589
6590   if (branches > 1)
6591     {
6592       as_bad (_("multiple branches or jumps in the same bundle"));
6593       return TRUE;
6594     }
6595
6596   return FALSE;
6597 }
6598
6599
6600 /* Check how the state used by t1 and t2 relate.
6601    Cases found are:
6602
6603    case A: t1 reads a register t2 writes (an antidependency within a bundle)
6604    case B: no relationship between what is read and written (both could
6605            read the same reg though)
6606    case C: t1 writes a register t2 writes (a register conflict within a
6607            bundle)
6608    case D: t1 writes a state that t2 also writes
6609    case E: t1 writes a tie queue that t2 also writes
6610    case F: two volatile queue accesses
6611 */
6612
6613 static char
6614 check_t1_t2_reads_and_writes (TInsn *t1, TInsn *t2)
6615 {
6616   xtensa_isa isa = xtensa_default_isa;
6617   xtensa_regfile t1_regfile, t2_regfile;
6618   int t1_reg, t2_reg;
6619   int t1_base_reg, t1_last_reg;
6620   int t2_base_reg, t2_last_reg;
6621   char t1_inout, t2_inout;
6622   int i, j;
6623   char conflict = 'b';
6624   int t1_states;
6625   int t2_states;
6626   int t1_interfaces;
6627   int t2_interfaces;
6628   bfd_boolean t1_volatile = FALSE;
6629   bfd_boolean t2_volatile = FALSE;
6630
6631   /* Check registers.  */
6632   for (j = 0; j < t2->ntok; j++)
6633     {
6634       if (xtensa_operand_is_register (isa, t2->opcode, j) != 1)
6635         continue;
6636
6637       t2_regfile = xtensa_operand_regfile (isa, t2->opcode, j);
6638       t2_base_reg = t2->tok[j].X_add_number;
6639       t2_last_reg = t2_base_reg + xtensa_operand_num_regs (isa, t2->opcode, j);
6640
6641       for (i = 0; i < t1->ntok; i++)
6642         {
6643           if (xtensa_operand_is_register (isa, t1->opcode, i) != 1)
6644             continue;
6645
6646           t1_regfile = xtensa_operand_regfile (isa, t1->opcode, i);
6647
6648           if (t1_regfile != t2_regfile)
6649             continue;
6650
6651           t1_inout = xtensa_operand_inout (isa, t1->opcode, i);
6652           t2_inout = xtensa_operand_inout (isa, t2->opcode, j);
6653
6654           if (xtensa_operand_is_known_reg (isa, t1->opcode, i) == 0
6655               || xtensa_operand_is_known_reg (isa, t2->opcode, j) == 0)
6656             {
6657               if (t1_inout == 'm' || t1_inout == 'o'
6658                   || t2_inout == 'm' || t2_inout == 'o')
6659                 {
6660                   conflict = 'a';
6661                   continue;
6662                 }
6663             }
6664
6665           t1_base_reg = t1->tok[i].X_add_number;
6666           t1_last_reg = (t1_base_reg
6667                          + xtensa_operand_num_regs (isa, t1->opcode, i));
6668
6669           for (t1_reg = t1_base_reg; t1_reg < t1_last_reg; t1_reg++)
6670             {
6671               for (t2_reg = t2_base_reg; t2_reg < t2_last_reg; t2_reg++)
6672                 {
6673                   if (t1_reg != t2_reg)
6674                     continue;
6675
6676                   if (t2_inout == 'i' && (t1_inout == 'm' || t1_inout == 'o'))
6677                     {
6678                       conflict = 'a';
6679                       continue;
6680                     }
6681
6682                   if (t1_inout == 'i' && (t2_inout == 'm' || t2_inout == 'o'))
6683                     {
6684                       conflict = 'a';
6685                       continue;
6686                     }
6687
6688                   if (t1_inout != 'i' && t2_inout != 'i')
6689                     return 'c';
6690                 }
6691             }
6692         }
6693     }
6694
6695   /* Check states.  */
6696   t1_states = xtensa_opcode_num_stateOperands (isa, t1->opcode);
6697   t2_states = xtensa_opcode_num_stateOperands (isa, t2->opcode);
6698   for (j = 0; j < t2_states; j++)
6699     {
6700       xtensa_state t2_so = xtensa_stateOperand_state (isa, t2->opcode, j);
6701       t2_inout = xtensa_stateOperand_inout (isa, t2->opcode, j);
6702       for (i = 0; i < t1_states; i++)
6703         {
6704           xtensa_state t1_so = xtensa_stateOperand_state (isa, t1->opcode, i);
6705           t1_inout = xtensa_stateOperand_inout (isa, t1->opcode, i);
6706           if (t1_so != t2_so || xtensa_state_is_shared_or (isa, t1_so) == 1)
6707             continue;
6708
6709           if (t2_inout == 'i' && (t1_inout == 'm' || t1_inout == 'o'))
6710             {
6711               conflict = 'a';
6712               continue;
6713             }
6714
6715           if (t1_inout == 'i' && (t2_inout == 'm' || t2_inout == 'o'))
6716             {
6717               conflict = 'a';
6718               continue;
6719             }
6720
6721           if (t1_inout != 'i' && t2_inout != 'i')
6722             return 'd';
6723         }
6724     }
6725
6726   /* Check tieports.  */
6727   t1_interfaces = xtensa_opcode_num_interfaceOperands (isa, t1->opcode);
6728   t2_interfaces = xtensa_opcode_num_interfaceOperands (isa, t2->opcode);
6729   for (j = 0; j < t2_interfaces; j++)
6730     {
6731       xtensa_interface t2_int
6732         = xtensa_interfaceOperand_interface (isa, t2->opcode, j);
6733       int t2_class = xtensa_interface_class_id (isa, t2_int);
6734
6735       t2_inout = xtensa_interface_inout (isa, t2_int);
6736       if (xtensa_interface_has_side_effect (isa, t2_int) == 1)
6737         t2_volatile = TRUE;
6738
6739       for (i = 0; i < t1_interfaces; i++)
6740         {
6741           xtensa_interface t1_int
6742             = xtensa_interfaceOperand_interface (isa, t1->opcode, j);
6743           int t1_class = xtensa_interface_class_id (isa, t1_int);
6744
6745           t1_inout = xtensa_interface_inout (isa, t1_int);
6746           if (xtensa_interface_has_side_effect (isa, t1_int) == 1)
6747             t1_volatile = TRUE;
6748
6749           if (t1_volatile && t2_volatile && (t1_class == t2_class))
6750             return 'f';
6751
6752           if (t1_int != t2_int)
6753             continue;
6754
6755           if (t2_inout == 'i' && t1_inout == 'o')
6756             {
6757               conflict = 'a';
6758               continue;
6759             }
6760
6761           if (t1_inout == 'i' && t2_inout == 'o')
6762             {
6763               conflict = 'a';
6764               continue;
6765             }
6766
6767           if (t1_inout != 'i' && t2_inout != 'i')
6768             return 'e';
6769         }
6770     }
6771
6772   return conflict;
6773 }
6774
6775
6776 static xtensa_format
6777 xg_find_narrowest_format (vliw_insn *vinsn)
6778 {
6779   /* Right now we assume that the ops within the vinsn are properly
6780      ordered for the slots that the programmer wanted them in.  In
6781      other words, we don't rearrange the ops in hopes of finding a
6782      better format.  The scheduler handles that.  */
6783
6784   xtensa_isa isa = xtensa_default_isa;
6785   xtensa_format format;
6786   xtensa_opcode nop_opcode = xtensa_nop_opcode;
6787
6788   if (vinsn->num_slots == 1)
6789     return xg_get_single_format (vinsn->slots[0].opcode);
6790
6791   for (format = 0; format < xtensa_isa_num_formats (isa); format++)
6792     {
6793       vliw_insn v_copy;
6794       xg_copy_vinsn (&v_copy, vinsn);
6795       if (xtensa_format_num_slots (isa, format) == v_copy.num_slots)
6796         {
6797           int slot;
6798           int fit = 0;
6799           for (slot = 0; slot < v_copy.num_slots; slot++)
6800             {
6801               if (v_copy.slots[slot].opcode == nop_opcode)
6802                 {
6803                   v_copy.slots[slot].opcode =
6804                     xtensa_format_slot_nop_opcode (isa, format, slot);
6805                   v_copy.slots[slot].ntok = 0;
6806                 }
6807
6808               if (opcode_fits_format_slot (v_copy.slots[slot].opcode,
6809                                            format, slot))
6810                 fit++;
6811               else if (v_copy.num_slots > 1)
6812                 {
6813                   TInsn widened;
6814                   /* Try the widened version.  */
6815                   if (!v_copy.slots[slot].keep_wide
6816                       && !v_copy.slots[slot].is_specific_opcode
6817                       && xg_is_single_relaxable_insn (&v_copy.slots[slot],
6818                                                       &widened, TRUE)
6819                       && opcode_fits_format_slot (widened.opcode,
6820                                                   format, slot))
6821                     {
6822                       v_copy.slots[slot] = widened;
6823                       fit++;
6824                     }
6825                 }
6826             }
6827           if (fit == v_copy.num_slots)
6828             {
6829               xg_copy_vinsn (vinsn, &v_copy);
6830               xtensa_format_encode (isa, format, vinsn->insnbuf);
6831               vinsn->format = format;
6832               break;
6833             }
6834         }
6835     }
6836
6837   if (format == xtensa_isa_num_formats (isa))
6838     return XTENSA_UNDEFINED;
6839
6840   return format;
6841 }
6842
6843
6844 /* Return the additional space needed in a frag
6845    for possible relaxations of any ops in a VLIW insn.
6846    Also fill out the relaxations that might be required of
6847    each tinsn in the vinsn.  */
6848
6849 static int
6850 relaxation_requirements (vliw_insn *vinsn, bfd_boolean *pfinish_frag)
6851 {
6852   bfd_boolean finish_frag = FALSE;
6853   int extra_space = 0;
6854   int slot;
6855
6856   for (slot = 0; slot < vinsn->num_slots; slot++)
6857     {
6858       TInsn *tinsn = &vinsn->slots[slot];
6859       if (!tinsn_has_symbolic_operands (tinsn))
6860         {
6861           /* A narrow instruction could be widened later to help
6862              alignment issues.  */
6863           if (xg_is_single_relaxable_insn (tinsn, 0, TRUE)
6864               && !tinsn->is_specific_opcode
6865               && vinsn->num_slots == 1)
6866             {
6867               /* Difference in bytes between narrow and wide insns...  */
6868               extra_space += 1;
6869               tinsn->subtype = RELAX_NARROW;
6870             }
6871         }
6872       else
6873         {
6874           if (workaround_b_j_loop_end
6875               && tinsn->opcode == xtensa_jx_opcode
6876               && use_transform ())
6877             {
6878               /* Add 2 of these.  */
6879               extra_space += 3; /* for the nop size */
6880               tinsn->subtype = RELAX_ADD_NOP_IF_PRE_LOOP_END;
6881             }
6882
6883           /* Need to assemble it with space for the relocation.  */
6884           if (xg_is_relaxable_insn (tinsn, 0)
6885               && !tinsn->is_specific_opcode)
6886             {
6887               int max_size = xg_get_max_insn_widen_size (tinsn->opcode);
6888               int max_literal_size =
6889                 xg_get_max_insn_widen_literal_size (tinsn->opcode);
6890
6891               tinsn->literal_space = max_literal_size;
6892
6893               tinsn->subtype = RELAX_IMMED;
6894               extra_space += max_size;
6895             }
6896           else
6897             {
6898               /* A fix record will be added for this instruction prior
6899                  to relaxation, so make it end the frag.  */
6900               finish_frag = TRUE;
6901             }
6902         }
6903     }
6904   *pfinish_frag = finish_frag;
6905   return extra_space;
6906 }
6907
6908
6909 static void
6910 bundle_tinsn (TInsn *tinsn, vliw_insn *vinsn)
6911 {
6912   xtensa_isa isa = xtensa_default_isa;
6913   int slot, chosen_slot;
6914
6915   vinsn->format = xg_get_single_format (tinsn->opcode);
6916   gas_assert (vinsn->format != XTENSA_UNDEFINED);
6917   vinsn->num_slots = xtensa_format_num_slots (isa, vinsn->format);
6918
6919   chosen_slot = xg_get_single_slot (tinsn->opcode);
6920   for (slot = 0; slot < vinsn->num_slots; slot++)
6921     {
6922       if (slot == chosen_slot)
6923         vinsn->slots[slot] = *tinsn;
6924       else
6925         {
6926           vinsn->slots[slot].opcode =
6927             xtensa_format_slot_nop_opcode (isa, vinsn->format, slot);
6928           vinsn->slots[slot].ntok = 0;
6929           vinsn->slots[slot].insn_type = ITYPE_INSN;
6930         }
6931     }
6932 }
6933
6934
6935 static bfd_boolean
6936 emit_single_op (TInsn *orig_insn)
6937 {
6938   int i;
6939   IStack istack;                /* put instructions into here */
6940   symbolS *lit_sym = NULL;
6941   symbolS *label_sym = NULL;
6942
6943   istack_init (&istack);
6944
6945   /* Special-case for "movi aX, foo" which is guaranteed to need relaxing.
6946      Because the scheduling and bundling characteristics of movi and
6947      l32r or const16 are so different, we can do much better if we relax
6948      it prior to scheduling and bundling, rather than after.  */
6949   if ((orig_insn->opcode == xtensa_movi_opcode
6950        || orig_insn->opcode == xtensa_movi_n_opcode)
6951       && !cur_vinsn.inside_bundle
6952       && (orig_insn->tok[1].X_op == O_symbol
6953           || orig_insn->tok[1].X_op == O_pltrel
6954           || orig_insn->tok[1].X_op == O_tlsfunc
6955           || orig_insn->tok[1].X_op == O_tlsarg
6956           || orig_insn->tok[1].X_op == O_tpoff
6957           || orig_insn->tok[1].X_op == O_dtpoff)
6958       && !orig_insn->is_specific_opcode && use_transform ())
6959     xg_assembly_relax (&istack, orig_insn, now_seg, frag_now, 0, 1, 0);
6960   else
6961     if (xg_expand_assembly_insn (&istack, orig_insn))
6962       return TRUE;
6963
6964   for (i = 0; i < istack.ninsn; i++)
6965     {
6966       TInsn *insn = &istack.insn[i];
6967       switch (insn->insn_type)
6968         {
6969         case ITYPE_LITERAL:
6970           gas_assert (lit_sym == NULL);
6971           lit_sym = xg_assemble_literal (insn);
6972           break;
6973         case ITYPE_LABEL:
6974           {
6975             static int relaxed_sym_idx = 0;
6976             char *label = xmalloc (strlen (FAKE_LABEL_NAME) + 12);
6977             sprintf (label, "%s_rl_%x", FAKE_LABEL_NAME, relaxed_sym_idx++);
6978             colon (label);
6979             gas_assert (label_sym == NULL);
6980             label_sym = symbol_find_or_make (label);
6981             gas_assert (label_sym);
6982             free (label);
6983           }
6984           break;
6985         case ITYPE_INSN:
6986           {
6987             vliw_insn v;
6988             if (lit_sym)
6989               xg_resolve_literals (insn, lit_sym);
6990             if (label_sym)
6991               xg_resolve_labels (insn, label_sym);
6992             xg_init_vinsn (&v);
6993             bundle_tinsn (insn, &v);
6994             finish_vinsn (&v);
6995             xg_free_vinsn (&v);
6996           }
6997           break;
6998         default:
6999           gas_assert (0);
7000           break;
7001         }
7002     }
7003   return FALSE;
7004 }
7005
7006
7007 static int
7008 total_frag_text_expansion (fragS *fragP)
7009 {
7010   int slot;
7011   int total_expansion = 0;
7012
7013   for (slot = 0; slot < config_max_slots; slot++)
7014     total_expansion += fragP->tc_frag_data.text_expansion[slot];
7015
7016   return total_expansion;
7017 }
7018
7019
7020 /* Emit a vliw instruction to the current fragment.  */
7021
7022 static void
7023 xg_assemble_vliw_tokens (vliw_insn *vinsn)
7024 {
7025   bfd_boolean finish_frag;
7026   bfd_boolean is_jump = FALSE;
7027   bfd_boolean is_branch = FALSE;
7028   xtensa_isa isa = xtensa_default_isa;
7029   int insn_size;
7030   int extra_space;
7031   char *f = NULL;
7032   int slot;
7033   struct dwarf2_line_info debug_line;
7034   bfd_boolean loc_directive_seen = FALSE;
7035   TInsn *tinsn;
7036
7037   memset (&debug_line, 0, sizeof (struct dwarf2_line_info));
7038
7039   if (generating_literals)
7040     {
7041       static int reported = 0;
7042       if (reported < 4)
7043         as_bad_where (frag_now->fr_file, frag_now->fr_line,
7044                       _("cannot assemble into a literal fragment"));
7045       if (reported == 3)
7046         as_bad (_("..."));
7047       reported++;
7048       return;
7049     }
7050
7051   if (frag_now_fix () != 0
7052       && (! frag_now->tc_frag_data.is_insn
7053           || (vinsn_has_specific_opcodes (vinsn) && use_transform ())
7054           || (!use_transform ()) != frag_now->tc_frag_data.is_no_transform
7055           || (directive_state[directive_longcalls]
7056               != frag_now->tc_frag_data.use_longcalls)
7057           || (directive_state[directive_absolute_literals]
7058               != frag_now->tc_frag_data.use_absolute_literals)))
7059     {
7060       frag_wane (frag_now);
7061       frag_new (0);
7062       xtensa_set_frag_assembly_state (frag_now);
7063     }
7064
7065   if (workaround_a0_b_retw
7066       && vinsn->num_slots == 1
7067       && (get_last_insn_flags (now_seg, now_subseg) & FLAG_IS_A0_WRITER) != 0
7068       && xtensa_opcode_is_branch (isa, vinsn->slots[0].opcode) == 1
7069       && use_transform ())
7070     {
7071       has_a0_b_retw = TRUE;
7072
7073       /* Mark this fragment with the special RELAX_ADD_NOP_IF_A0_B_RETW.
7074          After the first assembly pass we will check all of them and
7075          add a nop if needed.  */
7076       frag_now->tc_frag_data.is_insn = TRUE;
7077       frag_var (rs_machine_dependent, 4, 4,
7078                 RELAX_ADD_NOP_IF_A0_B_RETW,
7079                 frag_now->fr_symbol,
7080                 frag_now->fr_offset,
7081                 NULL);
7082       xtensa_set_frag_assembly_state (frag_now);
7083       frag_now->tc_frag_data.is_insn = TRUE;
7084       frag_var (rs_machine_dependent, 4, 4,
7085                 RELAX_ADD_NOP_IF_A0_B_RETW,
7086                 frag_now->fr_symbol,
7087                 frag_now->fr_offset,
7088                 NULL);
7089       xtensa_set_frag_assembly_state (frag_now);
7090     }
7091
7092   for (slot = 0; slot < vinsn->num_slots; slot++)
7093     {
7094       tinsn = &vinsn->slots[slot];
7095
7096       /* See if the instruction implies an aligned section.  */
7097       if (xtensa_opcode_is_loop (isa, tinsn->opcode) == 1)
7098         record_alignment (now_seg, 2);
7099
7100       /* Determine the best line number for debug info.  */
7101       if ((tinsn->loc_directive_seen || !loc_directive_seen)
7102           && (tinsn->debug_line.filenum != debug_line.filenum
7103               || tinsn->debug_line.line < debug_line.line
7104               || tinsn->debug_line.column < debug_line.column))
7105         debug_line = tinsn->debug_line;
7106       if (tinsn->loc_directive_seen)
7107         loc_directive_seen = TRUE;
7108     }
7109
7110   /* Special cases for instructions that force an alignment... */
7111   /* None of these opcodes are bundle-able.  */
7112   if (xtensa_opcode_is_loop (isa, vinsn->slots[0].opcode) == 1)
7113     {
7114       int max_fill;
7115
7116       /* Remember the symbol that marks the end of the loop in the frag
7117          that marks the start of the loop.  This way we can easily find
7118          the end of the loop at the beginning, without adding special code
7119          to mark the loop instructions themselves.  */
7120       symbolS *target_sym = NULL;
7121       if (vinsn->slots[0].tok[1].X_op == O_symbol)
7122         target_sym = vinsn->slots[0].tok[1].X_add_symbol;
7123
7124       xtensa_set_frag_assembly_state (frag_now);
7125       frag_now->tc_frag_data.is_insn = TRUE;
7126
7127       max_fill = get_text_align_max_fill_size
7128         (get_text_align_power (xtensa_fetch_width),
7129          TRUE, frag_now->tc_frag_data.is_no_density);
7130
7131       if (use_transform ())
7132         frag_var (rs_machine_dependent, max_fill, max_fill,
7133                   RELAX_ALIGN_NEXT_OPCODE, target_sym, 0, NULL);
7134       else
7135         frag_var (rs_machine_dependent, 0, 0,
7136                   RELAX_CHECK_ALIGN_NEXT_OPCODE, target_sym, 0, NULL);
7137       xtensa_set_frag_assembly_state (frag_now);
7138     }
7139
7140   if (vinsn->slots[0].opcode == xtensa_entry_opcode
7141       && !vinsn->slots[0].is_specific_opcode)
7142     {
7143       xtensa_mark_literal_pool_location ();
7144       xtensa_move_labels (frag_now, 0);
7145       frag_var (rs_align_test, 1, 1, 0, NULL, 2, NULL);
7146     }
7147
7148   if (vinsn->num_slots == 1)
7149     {
7150       if (workaround_a0_b_retw && use_transform ())
7151         set_last_insn_flags (now_seg, now_subseg, FLAG_IS_A0_WRITER,
7152                              is_register_writer (&vinsn->slots[0], "a", 0));
7153
7154       set_last_insn_flags (now_seg, now_subseg, FLAG_IS_BAD_LOOPEND,
7155                            is_bad_loopend_opcode (&vinsn->slots[0]));
7156     }
7157   else
7158     set_last_insn_flags (now_seg, now_subseg, FLAG_IS_BAD_LOOPEND, FALSE);
7159
7160   insn_size = xtensa_format_length (isa, vinsn->format);
7161
7162   extra_space = relaxation_requirements (vinsn, &finish_frag);
7163
7164   /* vinsn_to_insnbuf will produce the error.  */
7165   if (vinsn->format != XTENSA_UNDEFINED)
7166     {
7167       f = frag_more (insn_size + extra_space);
7168       xtensa_set_frag_assembly_state (frag_now);
7169       frag_now->tc_frag_data.is_insn = TRUE;
7170     }
7171
7172   vinsn_to_insnbuf (vinsn, f, frag_now, FALSE);
7173   if (vinsn->format == XTENSA_UNDEFINED)
7174     return;
7175
7176   xtensa_insnbuf_to_chars (isa, vinsn->insnbuf, (unsigned char *) f, 0);
7177
7178   if (debug_type == DEBUG_DWARF2 || loc_directive_seen)
7179     dwarf2_gen_line_info (frag_now_fix () - (insn_size + extra_space),
7180                           &debug_line);
7181
7182   for (slot = 0; slot < vinsn->num_slots; slot++)
7183     {
7184       tinsn = &vinsn->slots[slot];
7185       frag_now->tc_frag_data.slot_subtypes[slot] = tinsn->subtype;
7186       frag_now->tc_frag_data.slot_symbols[slot] = tinsn->symbol;
7187       frag_now->tc_frag_data.slot_offsets[slot] = tinsn->offset;
7188       frag_now->tc_frag_data.literal_frags[slot] = tinsn->literal_frag;
7189       if (tinsn->opcode == xtensa_l32r_opcode)
7190         {
7191           frag_now->tc_frag_data.literal_frags[slot] =
7192                   tinsn->tok[1].X_add_symbol->sy_frag;
7193         }
7194       if (tinsn->literal_space != 0)
7195         xg_assemble_literal_space (tinsn->literal_space, slot);
7196       frag_now->tc_frag_data.free_reg[slot] = tinsn->extra_arg;
7197
7198       if (tinsn->subtype == RELAX_NARROW)
7199         gas_assert (vinsn->num_slots == 1);
7200       if (xtensa_opcode_is_jump (isa, tinsn->opcode) == 1)
7201         is_jump = TRUE;
7202       if (xtensa_opcode_is_branch (isa, tinsn->opcode) == 1)
7203         is_branch = TRUE;
7204
7205       if (tinsn->subtype || tinsn->symbol || tinsn->offset
7206           || tinsn->literal_frag || is_jump || is_branch)
7207         finish_frag = TRUE;
7208     }
7209
7210   if (vinsn_has_specific_opcodes (vinsn) && use_transform ())
7211     frag_now->tc_frag_data.is_specific_opcode = TRUE;
7212
7213   if (finish_frag)
7214     {
7215       frag_variant (rs_machine_dependent,
7216                     extra_space, extra_space, RELAX_SLOTS,
7217                     frag_now->fr_symbol, frag_now->fr_offset, f);
7218       xtensa_set_frag_assembly_state (frag_now);
7219     }
7220
7221   /* Special cases for loops:
7222      close_loop_end should be inserted AFTER short_loop.
7223      Make sure that CLOSE loops are processed BEFORE short_loops
7224      when converting them.  */
7225
7226   /* "short_loop": Add a NOP if the loop is < 4 bytes.  */
7227   if (xtensa_opcode_is_loop (isa, vinsn->slots[0].opcode) == 1
7228       && !vinsn->slots[0].is_specific_opcode)
7229     {
7230       if (workaround_short_loop && use_transform ())
7231         {
7232           maybe_has_short_loop = TRUE;
7233           frag_now->tc_frag_data.is_insn = TRUE;
7234           frag_var (rs_machine_dependent, 4, 4,
7235                     RELAX_ADD_NOP_IF_SHORT_LOOP,
7236                     frag_now->fr_symbol, frag_now->fr_offset, NULL);
7237           frag_now->tc_frag_data.is_insn = TRUE;
7238           frag_var (rs_machine_dependent, 4, 4,
7239                     RELAX_ADD_NOP_IF_SHORT_LOOP,
7240                     frag_now->fr_symbol, frag_now->fr_offset, NULL);
7241         }
7242
7243       /* "close_loop_end": Add up to 12 bytes of NOPs to keep a
7244          loop at least 12 bytes away from another loop's end.  */
7245       if (workaround_close_loop_end && use_transform ())
7246         {
7247           maybe_has_close_loop_end = TRUE;
7248           frag_now->tc_frag_data.is_insn = TRUE;
7249           frag_var (rs_machine_dependent, 12, 12,
7250                     RELAX_ADD_NOP_IF_CLOSE_LOOP_END,
7251                     frag_now->fr_symbol, frag_now->fr_offset, NULL);
7252         }
7253     }
7254
7255   if (use_transform ())
7256     {
7257       if (is_jump)
7258         {
7259           gas_assert (finish_frag);
7260           frag_var (rs_machine_dependent,
7261                     xtensa_fetch_width, xtensa_fetch_width,
7262                     RELAX_UNREACHABLE,
7263                     frag_now->fr_symbol, frag_now->fr_offset, NULL);
7264           xtensa_set_frag_assembly_state (frag_now);
7265           xtensa_maybe_create_trampoline_frag ();
7266           /* Always create one here.  */
7267           xtensa_maybe_create_literal_pool_frag (TRUE, FALSE);
7268         }
7269       else if (is_branch && do_align_targets ())
7270         {
7271           gas_assert (finish_frag);
7272           frag_var (rs_machine_dependent,
7273                     xtensa_fetch_width, xtensa_fetch_width,
7274                     RELAX_MAYBE_UNREACHABLE,
7275                     frag_now->fr_symbol, frag_now->fr_offset, NULL);
7276           xtensa_set_frag_assembly_state (frag_now);
7277           frag_var (rs_machine_dependent,
7278                     0, 0,
7279                     RELAX_MAYBE_DESIRE_ALIGN,
7280                     frag_now->fr_symbol, frag_now->fr_offset, NULL);
7281           xtensa_set_frag_assembly_state (frag_now);
7282         }
7283     }
7284
7285   /* Now, if the original opcode was a call...  */
7286   if (do_align_targets ()
7287       && xtensa_opcode_is_call (isa, vinsn->slots[0].opcode) == 1)
7288     {
7289       float freq = get_subseg_total_freq (now_seg, now_subseg);
7290       frag_now->tc_frag_data.is_insn = TRUE;
7291       frag_var (rs_machine_dependent, 4, (int) freq, RELAX_DESIRE_ALIGN,
7292                 frag_now->fr_symbol, frag_now->fr_offset, NULL);
7293       xtensa_set_frag_assembly_state (frag_now);
7294     }
7295
7296   if (vinsn_has_specific_opcodes (vinsn) && use_transform ())
7297     {
7298       frag_wane (frag_now);
7299       frag_new (0);
7300       xtensa_set_frag_assembly_state (frag_now);
7301     }
7302 }
7303
7304 \f
7305 /* xtensa_end and helper functions.  */
7306
7307 static void xtensa_cleanup_align_frags (void);
7308 static void xtensa_fix_target_frags (void);
7309 static void xtensa_mark_narrow_branches (void);
7310 static void xtensa_mark_zcl_first_insns (void);
7311 static void xtensa_mark_difference_of_two_symbols (void);
7312 static void xtensa_fix_a0_b_retw_frags (void);
7313 static void xtensa_fix_b_j_loop_end_frags (void);
7314 static void xtensa_fix_close_loop_end_frags (void);
7315 static void xtensa_fix_short_loop_frags (void);
7316 static void xtensa_sanity_check (void);
7317 static void xtensa_add_config_info (void);
7318
7319 void
7320 xtensa_end (void)
7321 {
7322   directive_balance ();
7323   xtensa_flush_pending_output ();
7324
7325   past_xtensa_end = TRUE;
7326
7327   xtensa_move_literals ();
7328
7329   xtensa_reorder_segments ();
7330   xtensa_cleanup_align_frags ();
7331   xtensa_fix_target_frags ();
7332   if (workaround_a0_b_retw && has_a0_b_retw)
7333     xtensa_fix_a0_b_retw_frags ();
7334   if (workaround_b_j_loop_end)
7335     xtensa_fix_b_j_loop_end_frags ();
7336
7337   /* "close_loop_end" should be processed BEFORE "short_loop".  */
7338   if (workaround_close_loop_end && maybe_has_close_loop_end)
7339     xtensa_fix_close_loop_end_frags ();
7340
7341   if (workaround_short_loop && maybe_has_short_loop)
7342     xtensa_fix_short_loop_frags ();
7343   if (align_targets)
7344     xtensa_mark_narrow_branches ();
7345   xtensa_mark_zcl_first_insns ();
7346
7347   xtensa_sanity_check ();
7348
7349   xtensa_add_config_info ();
7350
7351   xtensa_check_frag_count ();
7352 }
7353
7354
7355 struct trampoline_frag
7356 {
7357   struct trampoline_frag *next;
7358   bfd_boolean needs_jump_around;
7359   fragS *fragP;
7360   fixS *fixP;
7361 };
7362
7363 struct trampoline_seg
7364 {
7365   struct trampoline_seg *next;
7366   asection *seg;
7367   struct trampoline_frag trampoline_list;
7368 };
7369
7370 static struct trampoline_seg trampoline_seg_list;
7371 #define J_RANGE (128 * 1024)
7372
7373 static int unreachable_count = 0;
7374
7375
7376 static void
7377 xtensa_maybe_create_trampoline_frag (void)
7378 {
7379   if (!use_trampolines)
7380     return;
7381
7382   /* We create an area for possible trampolines every 10 unreachable frags.
7383      These are preferred over the ones not preceded by an unreachable frag,
7384      because we don't have to jump around them. This function is called after
7385      each RELAX_UNREACHABLE frag is created.  */
7386
7387   if (++unreachable_count > 10)
7388     {
7389       xtensa_create_trampoline_frag (FALSE);
7390       clear_frag_count ();
7391       unreachable_count = 0;
7392     }
7393 }
7394
7395 static void
7396 xtensa_check_frag_count (void)
7397 {
7398   if (!use_trampolines || frag_now->tc_frag_data.is_no_transform)
7399     return;
7400
7401   /* We create an area for possible trampolines every 8000 frags or so. This
7402      is an estimate based on the max range of a "j" insn (+/-128K) divided
7403      by a typical frag byte count (16), minus a few for safety. This function
7404      is called after each source line is processed.  */
7405
7406   if (get_frag_count () > 8000)
7407     {
7408       xtensa_create_trampoline_frag (TRUE);
7409       clear_frag_count ();
7410       unreachable_count = 0;
7411     }
7412
7413   /* We create an area for a possible literal pool every N (default 5000)
7414      frags or so.  */
7415   xtensa_maybe_create_literal_pool_frag (TRUE, TRUE);
7416 }
7417
7418 static xtensa_insnbuf trampoline_buf = NULL;
7419 static xtensa_insnbuf trampoline_slotbuf = NULL;
7420
7421 static xtensa_insnbuf litpool_buf = NULL;
7422 static xtensa_insnbuf litpool_slotbuf = NULL;
7423
7424 #define TRAMPOLINE_FRAG_SIZE 3000
7425
7426 static void
7427 xtensa_create_trampoline_frag (bfd_boolean needs_jump_around)
7428 {
7429   /* Emit a frag where we can place intermediate jump instructions,
7430      in case we need to jump farther than 128K bytes.
7431      Each jump instruction takes three bytes.
7432      We allocate enough for 1000 trampolines in each frag.
7433      If that's not enough, oh well.  */
7434
7435   struct trampoline_seg *ts = trampoline_seg_list.next;
7436   struct trampoline_frag *tf;
7437   char *varP;
7438   fragS *fragP;
7439   int size = TRAMPOLINE_FRAG_SIZE;
7440
7441   for ( ; ts; ts = ts->next)
7442     {
7443       if (ts->seg == now_seg)
7444         break;
7445     }
7446
7447   if (ts == NULL)
7448     {
7449       ts = (struct trampoline_seg *)xcalloc(sizeof (struct trampoline_seg), 1);
7450       ts->next = trampoline_seg_list.next;
7451       trampoline_seg_list.next = ts;
7452       ts->seg = now_seg;
7453     }
7454
7455   frag_wane (frag_now);
7456   frag_new (0);
7457   xtensa_set_frag_assembly_state (frag_now);
7458   varP = frag_var (rs_machine_dependent, size, size, RELAX_TRAMPOLINE, NULL, 0, NULL);
7459   fragP = (fragS *)(varP - SIZEOF_STRUCT_FRAG);
7460   if (trampoline_buf == NULL)
7461     {
7462       trampoline_buf = xtensa_insnbuf_alloc (xtensa_default_isa);
7463       trampoline_slotbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
7464     }
7465   tf = (struct trampoline_frag *)xmalloc(sizeof (struct trampoline_frag));
7466   tf->next = ts->trampoline_list.next;
7467   ts->trampoline_list.next = tf;
7468   tf->needs_jump_around = needs_jump_around;
7469   tf->fragP = fragP;
7470   tf->fixP = NULL;
7471 }
7472
7473
7474 static struct trampoline_seg *
7475 find_trampoline_seg (asection *seg)
7476 {
7477   struct trampoline_seg *ts = trampoline_seg_list.next;
7478
7479   for ( ; ts; ts = ts->next)
7480     {
7481       if (ts->seg == seg)
7482         return ts;
7483     }
7484
7485   return NULL;
7486 }
7487
7488
7489 void dump_trampolines (void);
7490
7491 void
7492 dump_trampolines (void)
7493 {
7494   struct trampoline_seg *ts = trampoline_seg_list.next;
7495
7496   for ( ; ts; ts = ts->next)
7497     {
7498       asection *seg = ts->seg;
7499
7500       if (seg == NULL)
7501         continue;
7502       fprintf(stderr, "SECTION %s\n", seg->name);
7503       struct trampoline_frag *tf = ts->trampoline_list.next;
7504       for ( ; tf; tf = tf->next)
7505         {
7506           if (tf->fragP == NULL)
7507             continue;
7508           fprintf(stderr, "   0x%08x: fix=%d, jump_around=%s\n",
7509                   (int)tf->fragP->fr_address, (int)tf->fragP->fr_fix,
7510                   tf->needs_jump_around ? "T" : "F");
7511         }
7512     }
7513 }
7514
7515 static void dump_litpools (void) __attribute__ ((unused));
7516
7517 static void
7518 dump_litpools (void)
7519 {
7520   struct litpool_seg *lps = litpool_seg_list.next;
7521   struct litpool_frag *lpf;
7522
7523   for ( ; lps ; lps = lps->next )
7524     {
7525       printf("litpool seg %s\n", lps->seg->name);
7526       for ( lpf = lps->frag_list.next; lpf->fragP; lpf = lpf->next )
7527         {
7528           fragS *litfrag = lpf->fragP->fr_next;
7529           int count = 0;
7530           while (litfrag && litfrag->fr_subtype != RELAX_LITERAL_POOL_END)
7531             {
7532               if (litfrag->fr_fix == 4)
7533                 count++;
7534               litfrag = litfrag->fr_next;
7535             }
7536           printf("   %ld <%d:%d> (%d) [%d]: ",
7537                  lpf->addr, lpf->priority, lpf->original_priority,
7538                  lpf->fragP->fr_line, count);
7539           //dump_frag(lpf->fragP);
7540         }
7541     }
7542 }
7543
7544 static void
7545 xtensa_maybe_create_literal_pool_frag (bfd_boolean create,
7546                                        bfd_boolean only_if_needed)
7547 {
7548   struct litpool_seg *lps = litpool_seg_list.next;
7549   fragS *fragP;
7550   struct litpool_frag *lpf;
7551   bfd_boolean needed = FALSE;
7552
7553   if (use_literal_section || !auto_litpools)
7554     return;
7555
7556   for ( ; lps ; lps = lps->next )
7557     {
7558       if (lps->seg == now_seg)
7559         break;
7560     }
7561
7562   if (lps == NULL)
7563     {
7564       lps = (struct litpool_seg *)xcalloc (sizeof (struct litpool_seg), 1);
7565       lps->next = litpool_seg_list.next;
7566       litpool_seg_list.next = lps;
7567       lps->seg = now_seg;
7568       lps->frag_list.next = &lps->frag_list;
7569       lps->frag_list.prev = &lps->frag_list;
7570     }
7571
7572   lps->frag_count++;
7573
7574   if (create)
7575     {
7576       if (only_if_needed)
7577         {
7578           if (past_xtensa_end || !use_transform() ||
7579               frag_now->tc_frag_data.is_no_transform)
7580             {
7581               return;
7582             }
7583           if (auto_litpool_limit <= 0)
7584             {
7585               /* Don't create a litpool based only on frag count.  */
7586               return;
7587             }
7588           else if (lps->frag_count > auto_litpool_limit)
7589             {
7590               needed = TRUE;
7591             }
7592           else
7593             {
7594               return;
7595             }
7596         }
7597       else
7598         {
7599           needed = TRUE;
7600         }
7601     }
7602
7603   if (needed)
7604     {
7605       int size = (only_if_needed) ? 3 : 0; /* Space for a "j" insn.  */
7606       /* Create a potential site for a literal pool.  */
7607       frag_wane (frag_now);
7608       frag_new (0);
7609       xtensa_set_frag_assembly_state (frag_now);
7610       fragP = frag_now;
7611       fragP->tc_frag_data.lit_frchain = frchain_now;
7612       fragP->tc_frag_data.literal_frag = fragP;
7613       frag_var (rs_machine_dependent, size, size,
7614                     (only_if_needed) ?
7615                         RELAX_LITERAL_POOL_CANDIDATE_BEGIN :
7616                         RELAX_LITERAL_POOL_BEGIN,
7617                     NULL, 0, NULL);
7618       frag_now->tc_frag_data.lit_seg = now_seg;
7619       frag_variant (rs_machine_dependent, 0, 0,
7620                     RELAX_LITERAL_POOL_END, NULL, 0, NULL);
7621       xtensa_set_frag_assembly_state (frag_now);
7622     }
7623   else
7624     {
7625       /* RELAX_LITERAL_POOL_BEGIN frag is being created;
7626          just record it here.  */
7627       fragP = frag_now;
7628     }
7629
7630   lpf = (struct litpool_frag *)xmalloc(sizeof (struct litpool_frag));
7631   /* Insert at tail of circular list.  */
7632   lpf->addr = 0;
7633   lps->frag_list.prev->next = lpf;
7634   lpf->next = &lps->frag_list;
7635   lpf->prev = lps->frag_list.prev;
7636   lps->frag_list.prev = lpf;
7637   lpf->fragP = fragP;
7638   lpf->priority = (needed) ? (only_if_needed) ? 3 : 2 : 1;
7639   lpf->original_priority = lpf->priority;
7640
7641   lps->frag_count = 0;
7642 }
7643
7644 static void
7645 xtensa_cleanup_align_frags (void)
7646 {
7647   frchainS *frchP;
7648   asection *s;
7649
7650   for (s = stdoutput->sections; s; s = s->next)
7651     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
7652       {
7653         fragS *fragP;
7654         /* Walk over all of the fragments in a subsection.  */
7655         for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
7656           {
7657             if ((fragP->fr_type == rs_align
7658                  || fragP->fr_type == rs_align_code
7659                  || (fragP->fr_type == rs_machine_dependent
7660                      && (fragP->fr_subtype == RELAX_DESIRE_ALIGN
7661                          || fragP->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET)))
7662                 && fragP->fr_fix == 0)
7663               {
7664                 fragS *next = fragP->fr_next;
7665
7666                 while (next
7667                        && next->fr_fix == 0
7668                        && next->fr_type == rs_machine_dependent
7669                        && next->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET)
7670                   {
7671                     frag_wane (next);
7672                     next = next->fr_next;
7673                   }
7674               }
7675             /* If we don't widen branch targets, then they
7676                will be easier to align.  */
7677             if (fragP->tc_frag_data.is_branch_target
7678                 && fragP->fr_opcode == fragP->fr_literal
7679                 && fragP->fr_type == rs_machine_dependent
7680                 && fragP->fr_subtype == RELAX_SLOTS
7681                 && fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
7682               frag_wane (fragP);
7683             if (fragP->fr_type == rs_machine_dependent
7684                 && fragP->fr_subtype == RELAX_UNREACHABLE)
7685               fragP->tc_frag_data.is_unreachable = TRUE;
7686           }
7687       }
7688 }
7689
7690
7691 /* Re-process all of the fragments looking to convert all of the
7692    RELAX_DESIRE_ALIGN_IF_TARGET fragments.  If there is a branch
7693    target in the next fragment, convert this to RELAX_DESIRE_ALIGN.
7694    Otherwise, convert to a .fill 0.  */
7695
7696 static void
7697 xtensa_fix_target_frags (void)
7698 {
7699   frchainS *frchP;
7700   asection *s;
7701
7702   /* When this routine is called, all of the subsections are still intact
7703      so we walk over subsections instead of sections.  */
7704   for (s = stdoutput->sections; s; s = s->next)
7705     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
7706       {
7707         fragS *fragP;
7708
7709         /* Walk over all of the fragments in a subsection.  */
7710         for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
7711           {
7712             if (fragP->fr_type == rs_machine_dependent
7713                 && fragP->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET)
7714               {
7715                 if (next_frag_is_branch_target (fragP))
7716                   fragP->fr_subtype = RELAX_DESIRE_ALIGN;
7717                 else
7718                   frag_wane (fragP);
7719               }
7720           }
7721       }
7722 }
7723
7724
7725 static bfd_boolean is_narrow_branch_guaranteed_in_range (fragS *, TInsn *);
7726
7727 static void
7728 xtensa_mark_narrow_branches (void)
7729 {
7730   frchainS *frchP;
7731   asection *s;
7732
7733   for (s = stdoutput->sections; s; s = s->next)
7734     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
7735       {
7736         fragS *fragP;
7737         /* Walk over all of the fragments in a subsection.  */
7738         for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
7739           {
7740             if (fragP->fr_type == rs_machine_dependent
7741                 && fragP->fr_subtype == RELAX_SLOTS
7742                 && fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED)
7743               {
7744                 vliw_insn vinsn;
7745
7746                 vinsn_from_chars (&vinsn, fragP->fr_opcode);
7747                 tinsn_immed_from_frag (&vinsn.slots[0], fragP, 0);
7748
7749                 if (vinsn.num_slots == 1
7750                     && xtensa_opcode_is_branch (xtensa_default_isa,
7751                                                 vinsn.slots[0].opcode) == 1
7752                     && xg_get_single_size (vinsn.slots[0].opcode) == 2
7753                     && is_narrow_branch_guaranteed_in_range (fragP,
7754                                                              &vinsn.slots[0]))
7755                   {
7756                     fragP->fr_subtype = RELAX_SLOTS;
7757                     fragP->tc_frag_data.slot_subtypes[0] = RELAX_NARROW;
7758                     fragP->tc_frag_data.is_aligning_branch = 1;
7759                   }
7760               }
7761           }
7762       }
7763 }
7764
7765
7766 /* A branch is typically widened only when its target is out of
7767    range.  However, we would like to widen them to align a subsequent
7768    branch target when possible.
7769
7770    Because the branch relaxation code is so convoluted, the optimal solution
7771    (combining the two cases) is difficult to get right in all circumstances.
7772    We therefore go with an "almost as good" solution, where we only
7773    use for alignment narrow branches that definitely will not expand to a
7774    jump and a branch.  These functions find and mark these cases.  */
7775
7776 /* The range in bytes of BNEZ.N and BEQZ.N.  The target operand is encoded
7777    as PC + 4 + imm6, where imm6 is a 6-bit immediate ranging from 0 to 63.
7778    We start counting beginning with the frag after the 2-byte branch, so the
7779    maximum offset is (4 - 2) + 63 = 65.  */
7780 #define MAX_IMMED6 65
7781
7782 static offsetT unrelaxed_frag_max_size (fragS *);
7783
7784 static bfd_boolean
7785 is_narrow_branch_guaranteed_in_range (fragS *fragP, TInsn *tinsn)
7786 {
7787   const expressionS *exp = &tinsn->tok[1];
7788   symbolS *symbolP = exp->X_add_symbol;
7789   offsetT max_distance = exp->X_add_number;
7790   fragS *target_frag;
7791
7792   if (exp->X_op != O_symbol)
7793     return FALSE;
7794
7795   target_frag = symbol_get_frag (symbolP);
7796
7797   max_distance += (S_GET_VALUE (symbolP) - target_frag->fr_address);
7798   if (is_branch_jmp_to_next (tinsn, fragP))
7799     return FALSE;
7800
7801   /* The branch doesn't branch over it's own frag,
7802      but over the subsequent ones.  */
7803   fragP = fragP->fr_next;
7804   while (fragP != NULL && fragP != target_frag && max_distance <= MAX_IMMED6)
7805     {
7806       max_distance += unrelaxed_frag_max_size (fragP);
7807       fragP = fragP->fr_next;
7808     }
7809   if (max_distance <= MAX_IMMED6 && fragP == target_frag)
7810     return TRUE;
7811   return FALSE;
7812 }
7813
7814
7815 static void
7816 xtensa_mark_zcl_first_insns (void)
7817 {
7818   frchainS *frchP;
7819   asection *s;
7820
7821   for (s = stdoutput->sections; s; s = s->next)
7822     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
7823       {
7824         fragS *fragP;
7825         /* Walk over all of the fragments in a subsection.  */
7826         for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
7827           {
7828             if (fragP->fr_type == rs_machine_dependent
7829                 && (fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE
7830                     || fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE))
7831               {
7832                 /* Find the loop frag.  */
7833                 fragS *loop_frag = next_non_empty_frag (fragP);
7834                 /* Find the first insn frag.  */
7835                 fragS *targ_frag = next_non_empty_frag (loop_frag);
7836
7837               /* Handle a corner case that comes up in hardware
7838                  diagnostics.  The original assembly looks like this:
7839
7840                  loop aX, LabelA
7841                  <empty_frag>--not found by next_non_empty_frag
7842                  loop aY, LabelB
7843
7844                  Depending on the start address, the assembler may or
7845                  may not change it to look something like this:
7846
7847                  loop aX, LabelA
7848                  nop--frag isn't empty anymore
7849                  loop aY, LabelB
7850
7851                  So set up to check the alignment of the nop if it
7852                  exists  */
7853                 while (loop_frag != targ_frag)
7854                   {
7855                     if (loop_frag->fr_type == rs_machine_dependent
7856                         && (loop_frag->fr_subtype == RELAX_ALIGN_NEXT_OPCODE
7857                             || loop_frag->fr_subtype
7858                             == RELAX_CHECK_ALIGN_NEXT_OPCODE))
7859                       targ_frag = loop_frag;
7860                     else
7861                       loop_frag = loop_frag->fr_next;
7862                   }
7863
7864                 /* Of course, sometimes (mostly for toy test cases) a
7865                    zero-cost loop instruction is the last in a section.  */
7866                 if (targ_frag)
7867                   {
7868                     targ_frag->tc_frag_data.is_first_loop_insn = TRUE;
7869                     /* Do not widen a frag that is the first instruction of a
7870                        zero-cost loop.  It makes that loop harder to align.  */
7871                     if (targ_frag->fr_type == rs_machine_dependent
7872                         && targ_frag->fr_subtype == RELAX_SLOTS
7873                         && (targ_frag->tc_frag_data.slot_subtypes[0]
7874                             == RELAX_NARROW))
7875                       {
7876                         if (targ_frag->tc_frag_data.is_aligning_branch)
7877                           targ_frag->tc_frag_data.slot_subtypes[0] = RELAX_IMMED;
7878                         else
7879                           {
7880                             frag_wane (targ_frag);
7881                             targ_frag->tc_frag_data.slot_subtypes[0] = 0;
7882                           }
7883                       }
7884                   }
7885                 if (fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE)
7886                   frag_wane (fragP);
7887               }
7888           }
7889       }
7890 }
7891
7892
7893 /* When a difference-of-symbols expression is encoded as a uleb128 or
7894    sleb128 value, the linker is unable to adjust that value to account for
7895    link-time relaxation.  Mark all the code between such symbols so that
7896    its size cannot be changed by linker relaxation.  */
7897
7898 static void
7899 xtensa_mark_difference_of_two_symbols (void)
7900 {
7901   symbolS *expr_sym;
7902
7903   for (expr_sym = expr_symbols; expr_sym;
7904        expr_sym = symbol_get_tc (expr_sym)->next_expr_symbol)
7905     {
7906       expressionS *exp = symbol_get_value_expression (expr_sym);
7907
7908       if (exp->X_op == O_subtract)
7909         {
7910           symbolS *left = exp->X_add_symbol;
7911           symbolS *right = exp->X_op_symbol;
7912
7913           /* Difference of two symbols not in the same section
7914              are handled with relocations in the linker.  */
7915           if (S_GET_SEGMENT (left) == S_GET_SEGMENT (right))
7916             {
7917               fragS *start;
7918               fragS *end;
7919               fragS *walk;
7920
7921               if (symbol_get_frag (left)->fr_address
7922                   <= symbol_get_frag (right)->fr_address)
7923                 {
7924                   start = symbol_get_frag (left);
7925                   end = symbol_get_frag (right);
7926                 }
7927               else
7928                 {
7929                   start = symbol_get_frag (right);
7930                   end = symbol_get_frag (left);
7931                 }
7932
7933               if (start->tc_frag_data.no_transform_end != NULL)
7934                 walk = start->tc_frag_data.no_transform_end;
7935               else
7936                 walk = start;
7937               do
7938                 {
7939                   walk->tc_frag_data.is_no_transform = 1;
7940                   walk = walk->fr_next;
7941                 }
7942               while (walk && walk->fr_address < end->fr_address);
7943
7944               start->tc_frag_data.no_transform_end = walk;
7945             }
7946         }
7947     }
7948 }
7949
7950
7951 /* Re-process all of the fragments looking to convert all of the
7952    RELAX_ADD_NOP_IF_A0_B_RETW.  If the next instruction is a
7953    conditional branch or a retw/retw.n, convert this frag to one that
7954    will generate a NOP.  In any case close it off with a .fill 0.  */
7955
7956 static bfd_boolean next_instrs_are_b_retw (fragS *);
7957
7958 static void
7959 xtensa_fix_a0_b_retw_frags (void)
7960 {
7961   frchainS *frchP;
7962   asection *s;
7963
7964   /* When this routine is called, all of the subsections are still intact
7965      so we walk over subsections instead of sections.  */
7966   for (s = stdoutput->sections; s; s = s->next)
7967     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
7968       {
7969         fragS *fragP;
7970
7971         /* Walk over all of the fragments in a subsection.  */
7972         for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
7973           {
7974             if (fragP->fr_type == rs_machine_dependent
7975                 && fragP->fr_subtype == RELAX_ADD_NOP_IF_A0_B_RETW)
7976               {
7977                 if (next_instrs_are_b_retw (fragP))
7978                   {
7979                     if (fragP->tc_frag_data.is_no_transform)
7980                       as_bad (_("instruction sequence (write a0, branch, retw) may trigger hardware errata"));
7981                     else
7982                       relax_frag_add_nop (fragP);
7983                   }
7984                 frag_wane (fragP);
7985               }
7986           }
7987       }
7988 }
7989
7990
7991 static bfd_boolean
7992 next_instrs_are_b_retw (fragS *fragP)
7993 {
7994   xtensa_opcode opcode;
7995   xtensa_format fmt;
7996   const fragS *next_fragP = next_non_empty_frag (fragP);
7997   static xtensa_insnbuf insnbuf = NULL;
7998   static xtensa_insnbuf slotbuf = NULL;
7999   xtensa_isa isa = xtensa_default_isa;
8000   int offset = 0;
8001   int slot;
8002   bfd_boolean branch_seen = FALSE;
8003
8004   if (!insnbuf)
8005     {
8006       insnbuf = xtensa_insnbuf_alloc (isa);
8007       slotbuf = xtensa_insnbuf_alloc (isa);
8008     }
8009
8010   if (next_fragP == NULL)
8011     return FALSE;
8012
8013   /* Check for the conditional branch.  */
8014   xtensa_insnbuf_from_chars
8015     (isa, insnbuf, (unsigned char *) &next_fragP->fr_literal[offset], 0);
8016   fmt = xtensa_format_decode (isa, insnbuf);
8017   if (fmt == XTENSA_UNDEFINED)
8018     return FALSE;
8019
8020   for (slot = 0; slot < xtensa_format_num_slots (isa, fmt); slot++)
8021     {
8022       xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
8023       opcode = xtensa_opcode_decode (isa, fmt, slot, slotbuf);
8024
8025       branch_seen = (branch_seen
8026                      || xtensa_opcode_is_branch (isa, opcode) == 1);
8027     }
8028
8029   if (!branch_seen)
8030     return FALSE;
8031
8032   offset += xtensa_format_length (isa, fmt);
8033   if (offset == next_fragP->fr_fix)
8034     {
8035       next_fragP = next_non_empty_frag (next_fragP);
8036       offset = 0;
8037     }
8038
8039   if (next_fragP == NULL)
8040     return FALSE;
8041
8042   /* Check for the retw/retw.n.  */
8043   xtensa_insnbuf_from_chars
8044     (isa, insnbuf, (unsigned char *) &next_fragP->fr_literal[offset], 0);
8045   fmt = xtensa_format_decode (isa, insnbuf);
8046
8047   /* Because RETW[.N] is not bundleable, a VLIW bundle here means that we
8048      have no problems.  */
8049   if (fmt == XTENSA_UNDEFINED
8050       || xtensa_format_num_slots (isa, fmt) != 1)
8051     return FALSE;
8052
8053   xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf);
8054   opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
8055
8056   if (opcode == xtensa_retw_opcode || opcode == xtensa_retw_n_opcode)
8057     return TRUE;
8058
8059   return FALSE;
8060 }
8061
8062
8063 /* Re-process all of the fragments looking to convert all of the
8064    RELAX_ADD_NOP_IF_PRE_LOOP_END.  If there is one instruction and a
8065    loop end label, convert this frag to one that will generate a NOP.
8066    In any case close it off with a .fill 0.  */
8067
8068 static bfd_boolean next_instr_is_loop_end (fragS *);
8069
8070 static void
8071 xtensa_fix_b_j_loop_end_frags (void)
8072 {
8073   frchainS *frchP;
8074   asection *s;
8075
8076   /* When this routine is called, all of the subsections are still intact
8077      so we walk over subsections instead of sections.  */
8078   for (s = stdoutput->sections; s; s = s->next)
8079     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
8080       {
8081         fragS *fragP;
8082
8083         /* Walk over all of the fragments in a subsection.  */
8084         for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
8085           {
8086             if (fragP->fr_type == rs_machine_dependent
8087                 && fragP->fr_subtype == RELAX_ADD_NOP_IF_PRE_LOOP_END)
8088               {
8089                 if (next_instr_is_loop_end (fragP))
8090                   {
8091                     if (fragP->tc_frag_data.is_no_transform)
8092                       as_bad (_("branching or jumping to a loop end may trigger hardware errata"));
8093                     else
8094                       relax_frag_add_nop (fragP);
8095                   }
8096                 frag_wane (fragP);
8097               }
8098           }
8099       }
8100 }
8101
8102
8103 static bfd_boolean
8104 next_instr_is_loop_end (fragS *fragP)
8105 {
8106   const fragS *next_fragP;
8107
8108   if (next_frag_is_loop_target (fragP))
8109     return FALSE;
8110
8111   next_fragP = next_non_empty_frag (fragP);
8112   if (next_fragP == NULL)
8113     return FALSE;
8114
8115   if (!next_frag_is_loop_target (next_fragP))
8116     return FALSE;
8117
8118   /* If the size is >= 3 then there is more than one instruction here.
8119      The hardware bug will not fire.  */
8120   if (next_fragP->fr_fix > 3)
8121     return FALSE;
8122
8123   return TRUE;
8124 }
8125
8126
8127 /* Re-process all of the fragments looking to convert all of the
8128    RELAX_ADD_NOP_IF_CLOSE_LOOP_END.  If there is an loop end that is
8129    not MY loop's loop end within 12 bytes, add enough nops here to
8130    make it at least 12 bytes away.  In any case close it off with a
8131    .fill 0.  */
8132
8133 static offsetT min_bytes_to_other_loop_end
8134   (fragS *, fragS *, offsetT);
8135
8136 static void
8137 xtensa_fix_close_loop_end_frags (void)
8138 {
8139   frchainS *frchP;
8140   asection *s;
8141
8142   /* When this routine is called, all of the subsections are still intact
8143      so we walk over subsections instead of sections.  */
8144   for (s = stdoutput->sections; s; s = s->next)
8145     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
8146       {
8147         fragS *fragP;
8148
8149         fragS *current_target = NULL;
8150
8151         /* Walk over all of the fragments in a subsection.  */
8152         for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
8153           {
8154             if (fragP->fr_type == rs_machine_dependent
8155                 && ((fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE)
8156                     || (fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE)))
8157               current_target = symbol_get_frag (fragP->fr_symbol);
8158
8159             if (current_target
8160                 && fragP->fr_type == rs_machine_dependent
8161                 && fragP->fr_subtype == RELAX_ADD_NOP_IF_CLOSE_LOOP_END)
8162               {
8163                 offsetT min_bytes;
8164                 int bytes_added = 0;
8165
8166 #define REQUIRED_LOOP_DIVIDING_BYTES 12
8167                 /* Max out at 12.  */
8168                 min_bytes = min_bytes_to_other_loop_end
8169                   (fragP->fr_next, current_target, REQUIRED_LOOP_DIVIDING_BYTES);
8170
8171                 if (min_bytes < REQUIRED_LOOP_DIVIDING_BYTES)
8172                   {
8173                     if (fragP->tc_frag_data.is_no_transform)
8174                       as_bad (_("loop end too close to another loop end may trigger hardware errata"));
8175                     else
8176                       {
8177                         while (min_bytes + bytes_added
8178                                < REQUIRED_LOOP_DIVIDING_BYTES)
8179                           {
8180                             int length = 3;
8181
8182                             if (fragP->fr_var < length)
8183                               as_fatal (_("fr_var %lu < length %d"),
8184                                         (long) fragP->fr_var, length);
8185                             else
8186                               {
8187                                 assemble_nop (length,
8188                                               fragP->fr_literal + fragP->fr_fix);
8189                                 fragP->fr_fix += length;
8190                                 fragP->fr_var -= length;
8191                               }
8192                             bytes_added += length;
8193                           }
8194                       }
8195                   }
8196                 frag_wane (fragP);
8197               }
8198             gas_assert (fragP->fr_type != rs_machine_dependent
8199                     || fragP->fr_subtype != RELAX_ADD_NOP_IF_CLOSE_LOOP_END);
8200           }
8201       }
8202 }
8203
8204
8205 static offsetT unrelaxed_frag_min_size (fragS *);
8206
8207 static offsetT
8208 min_bytes_to_other_loop_end (fragS *fragP,
8209                              fragS *current_target,
8210                              offsetT max_size)
8211 {
8212   offsetT offset = 0;
8213   fragS *current_fragP;
8214
8215   for (current_fragP = fragP;
8216        current_fragP;
8217        current_fragP = current_fragP->fr_next)
8218     {
8219       if (current_fragP->tc_frag_data.is_loop_target
8220           && current_fragP != current_target)
8221         return offset;
8222
8223       offset += unrelaxed_frag_min_size (current_fragP);
8224
8225       if (offset >= max_size)
8226         return max_size;
8227     }
8228   return max_size;
8229 }
8230
8231
8232 static offsetT
8233 unrelaxed_frag_min_size (fragS *fragP)
8234 {
8235   offsetT size = fragP->fr_fix;
8236
8237   /* Add fill size.  */
8238   if (fragP->fr_type == rs_fill)
8239     size += fragP->fr_offset;
8240
8241   return size;
8242 }
8243
8244
8245 static offsetT
8246 unrelaxed_frag_max_size (fragS *fragP)
8247 {
8248   offsetT size = fragP->fr_fix;
8249   switch (fragP->fr_type)
8250     {
8251     case 0:
8252       /* Empty frags created by the obstack allocation scheme
8253          end up with type 0.  */
8254       break;
8255     case rs_fill:
8256     case rs_org:
8257     case rs_space:
8258       size += fragP->fr_offset;
8259       break;
8260     case rs_align:
8261     case rs_align_code:
8262     case rs_align_test:
8263     case rs_leb128:
8264     case rs_cfa:
8265     case rs_dwarf2dbg:
8266       /* No further adjustments needed.  */
8267       break;
8268     case rs_machine_dependent:
8269       if (fragP->fr_subtype != RELAX_DESIRE_ALIGN)
8270         size += fragP->fr_var;
8271       break;
8272     default:
8273       /* We had darn well better know how big it is.  */
8274       gas_assert (0);
8275       break;
8276     }
8277
8278   return size;
8279 }
8280
8281
8282 /* Re-process all of the fragments looking to convert all
8283    of the RELAX_ADD_NOP_IF_SHORT_LOOP.  If:
8284
8285    A)
8286      1) the instruction size count to the loop end label
8287         is too short (<= 2 instructions),
8288      2) loop has a jump or branch in it
8289
8290    or B)
8291      1) workaround_all_short_loops is TRUE
8292      2) The generating loop was a  'loopgtz' or 'loopnez'
8293      3) the instruction size count to the loop end label is too short
8294         (<= 2 instructions)
8295    then convert this frag (and maybe the next one) to generate a NOP.
8296    In any case close it off with a .fill 0.  */
8297
8298 static int count_insns_to_loop_end (fragS *, bfd_boolean, int);
8299 static bfd_boolean branch_before_loop_end (fragS *);
8300
8301 static void
8302 xtensa_fix_short_loop_frags (void)
8303 {
8304   frchainS *frchP;
8305   asection *s;
8306
8307   /* When this routine is called, all of the subsections are still intact
8308      so we walk over subsections instead of sections.  */
8309   for (s = stdoutput->sections; s; s = s->next)
8310     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
8311       {
8312         fragS *fragP;
8313         xtensa_opcode current_opcode = XTENSA_UNDEFINED;
8314
8315         /* Walk over all of the fragments in a subsection.  */
8316         for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
8317           {
8318             if (fragP->fr_type == rs_machine_dependent
8319                 && ((fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE)
8320                     || (fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE)))
8321               {
8322                 TInsn t_insn;
8323                 fragS *loop_frag = next_non_empty_frag (fragP);
8324                 tinsn_from_chars (&t_insn, loop_frag->fr_opcode, 0);
8325                 current_opcode = t_insn.opcode;
8326                 gas_assert (xtensa_opcode_is_loop (xtensa_default_isa,
8327                                                current_opcode) == 1);
8328               }
8329
8330             if (fragP->fr_type == rs_machine_dependent
8331                 && fragP->fr_subtype == RELAX_ADD_NOP_IF_SHORT_LOOP)
8332               {
8333                 if (count_insns_to_loop_end (fragP->fr_next, TRUE, 3) < 3
8334                     && (branch_before_loop_end (fragP->fr_next)
8335                         || (workaround_all_short_loops
8336                             && current_opcode != XTENSA_UNDEFINED
8337                             && current_opcode != xtensa_loop_opcode)))
8338                   {
8339                     if (fragP->tc_frag_data.is_no_transform)
8340                       as_bad (_("loop containing less than three instructions may trigger hardware errata"));
8341                     else
8342                       relax_frag_add_nop (fragP);
8343                   }
8344                 frag_wane (fragP);
8345               }
8346           }
8347       }
8348 }
8349
8350
8351 static int unrelaxed_frag_min_insn_count (fragS *);
8352
8353 static int
8354 count_insns_to_loop_end (fragS *base_fragP,
8355                          bfd_boolean count_relax_add,
8356                          int max_count)
8357 {
8358   fragS *fragP = NULL;
8359   int insn_count = 0;
8360
8361   fragP = base_fragP;
8362
8363   for (; fragP && !fragP->tc_frag_data.is_loop_target; fragP = fragP->fr_next)
8364     {
8365       insn_count += unrelaxed_frag_min_insn_count (fragP);
8366       if (insn_count >= max_count)
8367         return max_count;
8368
8369       if (count_relax_add)
8370         {
8371           if (fragP->fr_type == rs_machine_dependent
8372               && fragP->fr_subtype == RELAX_ADD_NOP_IF_SHORT_LOOP)
8373             {
8374               /* In order to add the appropriate number of
8375                  NOPs, we count an instruction for downstream
8376                  occurrences.  */
8377               insn_count++;
8378               if (insn_count >= max_count)
8379                 return max_count;
8380             }
8381         }
8382     }
8383   return insn_count;
8384 }
8385
8386
8387 static int
8388 unrelaxed_frag_min_insn_count (fragS *fragP)
8389 {
8390   xtensa_isa isa = xtensa_default_isa;
8391   static xtensa_insnbuf insnbuf = NULL;
8392   int insn_count = 0;
8393   int offset = 0;
8394
8395   if (!fragP->tc_frag_data.is_insn)
8396     return insn_count;
8397
8398   if (!insnbuf)
8399     insnbuf = xtensa_insnbuf_alloc (isa);
8400
8401   /* Decode the fixed instructions.  */
8402   while (offset < fragP->fr_fix)
8403     {
8404       xtensa_format fmt;
8405
8406       xtensa_insnbuf_from_chars
8407         (isa, insnbuf, (unsigned char *) fragP->fr_literal + offset, 0);
8408       fmt = xtensa_format_decode (isa, insnbuf);
8409
8410       if (fmt == XTENSA_UNDEFINED)
8411         {
8412           as_fatal (_("undecodable instruction in instruction frag"));
8413           return insn_count;
8414         }
8415       offset += xtensa_format_length (isa, fmt);
8416       insn_count++;
8417     }
8418
8419   return insn_count;
8420 }
8421
8422
8423 static bfd_boolean unrelaxed_frag_has_b_j (fragS *);
8424
8425 static bfd_boolean
8426 branch_before_loop_end (fragS *base_fragP)
8427 {
8428   fragS *fragP;
8429
8430   for (fragP = base_fragP;
8431        fragP && !fragP->tc_frag_data.is_loop_target;
8432        fragP = fragP->fr_next)
8433     {
8434       if (unrelaxed_frag_has_b_j (fragP))
8435         return TRUE;
8436     }
8437   return FALSE;
8438 }
8439
8440
8441 static bfd_boolean
8442 unrelaxed_frag_has_b_j (fragS *fragP)
8443 {
8444   static xtensa_insnbuf insnbuf = NULL;
8445   xtensa_isa isa = xtensa_default_isa;
8446   int offset = 0;
8447
8448   if (!fragP->tc_frag_data.is_insn)
8449     return FALSE;
8450
8451   if (!insnbuf)
8452     insnbuf = xtensa_insnbuf_alloc (isa);
8453
8454   /* Decode the fixed instructions.  */
8455   while (offset < fragP->fr_fix)
8456     {
8457       xtensa_format fmt;
8458       int slot;
8459
8460       xtensa_insnbuf_from_chars
8461         (isa, insnbuf, (unsigned char *) fragP->fr_literal + offset, 0);
8462       fmt = xtensa_format_decode (isa, insnbuf);
8463       if (fmt == XTENSA_UNDEFINED)
8464         return FALSE;
8465
8466       for (slot = 0; slot < xtensa_format_num_slots (isa, fmt); slot++)
8467         {
8468           xtensa_opcode opcode =
8469             get_opcode_from_buf (fragP->fr_literal + offset, slot);
8470           if (xtensa_opcode_is_branch (isa, opcode) == 1
8471               || xtensa_opcode_is_jump (isa, opcode) == 1)
8472             return TRUE;
8473         }
8474       offset += xtensa_format_length (isa, fmt);
8475     }
8476   return FALSE;
8477 }
8478
8479
8480 /* Checks to be made after initial assembly but before relaxation.  */
8481
8482 static bfd_boolean is_empty_loop (const TInsn *, fragS *);
8483 static bfd_boolean is_local_forward_loop (const TInsn *, fragS *);
8484
8485 static void
8486 xtensa_sanity_check (void)
8487 {
8488   const char *file_name;
8489   unsigned line;
8490   frchainS *frchP;
8491   asection *s;
8492
8493   file_name = as_where (&line);
8494   for (s = stdoutput->sections; s; s = s->next)
8495     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
8496       {
8497         fragS *fragP;
8498
8499         /* Walk over all of the fragments in a subsection.  */
8500         for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
8501           {
8502             if (fragP->fr_type == rs_machine_dependent
8503                 && fragP->fr_subtype == RELAX_SLOTS
8504                 && fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED)
8505               {
8506                 static xtensa_insnbuf insnbuf = NULL;
8507                 TInsn t_insn;
8508
8509                 if (fragP->fr_opcode != NULL)
8510                   {
8511                     if (!insnbuf)
8512                       insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
8513                     tinsn_from_chars (&t_insn, fragP->fr_opcode, 0);
8514                     tinsn_immed_from_frag (&t_insn, fragP, 0);
8515
8516                     if (xtensa_opcode_is_loop (xtensa_default_isa,
8517                                                t_insn.opcode) == 1)
8518                       {
8519                         if (is_empty_loop (&t_insn, fragP))
8520                           {
8521                             new_logical_line (fragP->fr_file, fragP->fr_line);
8522                             as_bad (_("invalid empty loop"));
8523                           }
8524                         if (!is_local_forward_loop (&t_insn, fragP))
8525                           {
8526                             new_logical_line (fragP->fr_file, fragP->fr_line);
8527                             as_bad (_("loop target does not follow "
8528                                       "loop instruction in section"));
8529                           }
8530                       }
8531                   }
8532               }
8533           }
8534       }
8535   new_logical_line (file_name, line);
8536 }
8537
8538
8539 #define LOOP_IMMED_OPN 1
8540
8541 /* Return TRUE if the loop target is the next non-zero fragment.  */
8542
8543 static bfd_boolean
8544 is_empty_loop (const TInsn *insn, fragS *fragP)
8545 {
8546   const expressionS *exp;
8547   symbolS *symbolP;
8548   fragS *next_fragP;
8549
8550   if (insn->insn_type != ITYPE_INSN)
8551     return FALSE;
8552
8553   if (xtensa_opcode_is_loop (xtensa_default_isa, insn->opcode) != 1)
8554     return FALSE;
8555
8556   if (insn->ntok <= LOOP_IMMED_OPN)
8557     return FALSE;
8558
8559   exp = &insn->tok[LOOP_IMMED_OPN];
8560
8561   if (exp->X_op != O_symbol)
8562     return FALSE;
8563
8564   symbolP = exp->X_add_symbol;
8565   if (!symbolP)
8566     return FALSE;
8567
8568   if (symbol_get_frag (symbolP) == NULL)
8569     return FALSE;
8570
8571   if (S_GET_VALUE (symbolP) != 0)
8572     return FALSE;
8573
8574   /* Walk through the zero-size fragments from this one.  If we find
8575      the target fragment, then this is a zero-size loop.  */
8576
8577   for (next_fragP = fragP->fr_next;
8578        next_fragP != NULL;
8579        next_fragP = next_fragP->fr_next)
8580     {
8581       if (next_fragP == symbol_get_frag (symbolP))
8582         return TRUE;
8583       if (next_fragP->fr_fix != 0)
8584         return FALSE;
8585     }
8586   return FALSE;
8587 }
8588
8589
8590 static bfd_boolean
8591 is_local_forward_loop (const TInsn *insn, fragS *fragP)
8592 {
8593   const expressionS *exp;
8594   symbolS *symbolP;
8595   fragS *next_fragP;
8596
8597   if (insn->insn_type != ITYPE_INSN)
8598     return FALSE;
8599
8600   if (xtensa_opcode_is_loop (xtensa_default_isa, insn->opcode) != 1)
8601     return FALSE;
8602
8603   if (insn->ntok <= LOOP_IMMED_OPN)
8604     return FALSE;
8605
8606   exp = &insn->tok[LOOP_IMMED_OPN];
8607
8608   if (exp->X_op != O_symbol)
8609     return FALSE;
8610
8611   symbolP = exp->X_add_symbol;
8612   if (!symbolP)
8613     return FALSE;
8614
8615   if (symbol_get_frag (symbolP) == NULL)
8616     return FALSE;
8617
8618   /* Walk through fragments until we find the target.
8619      If we do not find the target, then this is an invalid loop.  */
8620
8621   for (next_fragP = fragP->fr_next;
8622        next_fragP != NULL;
8623        next_fragP = next_fragP->fr_next)
8624     {
8625       if (next_fragP == symbol_get_frag (symbolP))
8626         return TRUE;
8627     }
8628
8629   return FALSE;
8630 }
8631
8632
8633 #define XTINFO_NAME "Xtensa_Info"
8634 #define XTINFO_NAMESZ 12
8635 #define XTINFO_TYPE 1
8636
8637 static void
8638 xtensa_add_config_info (void)
8639 {
8640   asection *info_sec;
8641   char *data, *p;
8642   int sz;
8643
8644   info_sec = subseg_new (".xtensa.info", 0);
8645   bfd_set_section_flags (stdoutput, info_sec, SEC_HAS_CONTENTS | SEC_READONLY);
8646
8647   data = xmalloc (100);
8648   sprintf (data, "USE_ABSOLUTE_LITERALS=%d\nABI=%d\n",
8649            XSHAL_USE_ABSOLUTE_LITERALS, XSHAL_ABI);
8650   sz = strlen (data) + 1;
8651
8652   /* Add enough null terminators to pad to a word boundary.  */
8653   do
8654     data[sz++] = 0;
8655   while ((sz & 3) != 0);
8656
8657   /* Follow the standard note section layout:
8658      First write the length of the name string.  */
8659   p = frag_more (4);
8660   md_number_to_chars (p, (valueT) XTINFO_NAMESZ, 4);
8661
8662   /* Next comes the length of the "descriptor", i.e., the actual data.  */
8663   p = frag_more (4);
8664   md_number_to_chars (p, (valueT) sz, 4);
8665
8666   /* Write the note type.  */
8667   p = frag_more (4);
8668   md_number_to_chars (p, (valueT) XTINFO_TYPE, 4);
8669
8670   /* Write the name field.  */
8671   p = frag_more (XTINFO_NAMESZ);
8672   memcpy (p, XTINFO_NAME, XTINFO_NAMESZ);
8673
8674   /* Finally, write the descriptor.  */
8675   p = frag_more (sz);
8676   memcpy (p, data, sz);
8677
8678   free (data);
8679 }
8680
8681 \f
8682 /* Alignment Functions.  */
8683
8684 static int
8685 get_text_align_power (unsigned target_size)
8686 {
8687   if (target_size <= 4)
8688     return 2;
8689
8690   if (target_size <= 8)
8691     return 3;
8692
8693   if (target_size <= 16)
8694     return 4;
8695
8696   if (target_size <= 32)
8697     return 5;
8698
8699   if (target_size <= 64)
8700     return 6;
8701
8702   if (target_size <= 128)
8703     return 7;
8704
8705   if (target_size <= 256)
8706     return 8;
8707
8708   if (target_size <= 512)
8709     return 9;
8710
8711   if (target_size <= 1024)
8712     return 10;
8713
8714   gas_assert (0);
8715   return 0;
8716 }
8717
8718
8719 static int
8720 get_text_align_max_fill_size (int align_pow,
8721                               bfd_boolean use_nops,
8722                               bfd_boolean use_no_density)
8723 {
8724   if (!use_nops)
8725     return (1 << align_pow);
8726   if (use_no_density)
8727     return 3 * (1 << align_pow);
8728
8729   return 1 + (1 << align_pow);
8730 }
8731
8732
8733 /* Calculate the minimum bytes of fill needed at "address" to align a
8734    target instruction of size "target_size" so that it does not cross a
8735    power-of-two boundary specified by "align_pow".  If "use_nops" is FALSE,
8736    the fill can be an arbitrary number of bytes.  Otherwise, the space must
8737    be filled by NOP instructions.  */
8738
8739 static int
8740 get_text_align_fill_size (addressT address,
8741                           int align_pow,
8742                           int target_size,
8743                           bfd_boolean use_nops,
8744                           bfd_boolean use_no_density)
8745 {
8746   addressT alignment, fill, fill_limit, fill_step;
8747   bfd_boolean skip_one = FALSE;
8748
8749   alignment = (1 << align_pow);
8750   gas_assert (target_size > 0 && alignment >= (addressT) target_size);
8751
8752   if (!use_nops)
8753     {
8754       fill_limit = alignment;
8755       fill_step = 1;
8756     }
8757   else if (!use_no_density)
8758     {
8759       /* Combine 2- and 3-byte NOPs to fill anything larger than one.  */
8760       fill_limit = alignment * 2;
8761       fill_step = 1;
8762       skip_one = TRUE;
8763     }
8764   else
8765     {
8766       /* Fill with 3-byte NOPs -- can only fill multiples of 3.  */
8767       fill_limit = alignment * 3;
8768       fill_step = 3;
8769     }
8770
8771   /* Try all fill sizes until finding one that works.  */
8772   for (fill = 0; fill < fill_limit; fill += fill_step)
8773     {
8774       if (skip_one && fill == 1)
8775         continue;
8776       if ((address + fill) >> align_pow
8777           == (address + fill + target_size - 1) >> align_pow)
8778         return fill;
8779     }
8780   gas_assert (0);
8781   return 0;
8782 }
8783
8784
8785 static int
8786 branch_align_power (segT sec)
8787 {
8788   /* If the Xtensa processor has a fetch width of X, and
8789      the section is aligned to at least that boundary, then a branch
8790      target need only fit within that aligned block of memory to avoid
8791      a stall.  Otherwise, try to fit branch targets within 4-byte
8792      aligned blocks (which may be insufficient, e.g., if the section
8793      has no alignment, but it's good enough).  */
8794   int fetch_align = get_text_align_power(xtensa_fetch_width);
8795   int sec_align = get_recorded_alignment (sec);
8796
8797   if (sec_align >= fetch_align)
8798     return fetch_align;
8799
8800   return 2;
8801 }
8802
8803
8804 /* This will assert if it is not possible.  */
8805
8806 static int
8807 get_text_align_nop_count (offsetT fill_size, bfd_boolean use_no_density)
8808 {
8809   int count = 0;
8810
8811   if (use_no_density)
8812     {
8813       gas_assert (fill_size % 3 == 0);
8814       return (fill_size / 3);
8815     }
8816
8817   gas_assert (fill_size != 1);  /* Bad argument.  */
8818
8819   while (fill_size > 1)
8820     {
8821       int insn_size = 3;
8822       if (fill_size == 2 || fill_size == 4)
8823         insn_size = 2;
8824       fill_size -= insn_size;
8825       count++;
8826     }
8827   gas_assert (fill_size != 1);  /* Bad algorithm.  */
8828   return count;
8829 }
8830
8831
8832 static int
8833 get_text_align_nth_nop_size (offsetT fill_size,
8834                              int n,
8835                              bfd_boolean use_no_density)
8836 {
8837   int count = 0;
8838
8839   if (use_no_density)
8840     return 3;
8841
8842   gas_assert (fill_size != 1);  /* Bad argument.  */
8843
8844   while (fill_size > 1)
8845     {
8846       int insn_size = 3;
8847       if (fill_size == 2 || fill_size == 4)
8848         insn_size = 2;
8849       fill_size -= insn_size;
8850       count++;
8851       if (n + 1 == count)
8852         return insn_size;
8853     }
8854   gas_assert (0);
8855   return 0;
8856 }
8857
8858
8859 /* For the given fragment, find the appropriate address
8860    for it to begin at if we are using NOPs to align it.  */
8861
8862 static addressT
8863 get_noop_aligned_address (fragS *fragP, addressT address)
8864 {
8865   /* The rule is: get next fragment's FIRST instruction.  Find
8866      the smallest number of bytes that need to be added to
8867      ensure that the next fragment's FIRST instruction will fit
8868      in a single word.
8869
8870      E.G.,   2 bytes : 0, 1, 2 mod 4
8871              3 bytes: 0, 1 mod 4
8872
8873      If the FIRST instruction MIGHT be relaxed,
8874      assume that it will become a 3-byte instruction.
8875
8876      Note again here that LOOP instructions are not bundleable,
8877      and this relaxation only applies to LOOP opcodes.  */
8878
8879   int fill_size = 0;
8880   int first_insn_size;
8881   int loop_insn_size;
8882   addressT pre_opcode_bytes;
8883   int align_power;
8884   fragS *first_insn;
8885   xtensa_opcode opcode;
8886   bfd_boolean is_loop;
8887
8888   gas_assert (fragP->fr_type == rs_machine_dependent);
8889   gas_assert (fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE);
8890
8891   /* Find the loop frag.  */
8892   first_insn = next_non_empty_frag (fragP);
8893   /* Now find the first insn frag.  */
8894   first_insn = next_non_empty_frag (first_insn);
8895
8896   is_loop = next_frag_opcode_is_loop (fragP, &opcode);
8897   gas_assert (is_loop);
8898   loop_insn_size = xg_get_single_size (opcode);
8899
8900   pre_opcode_bytes = next_frag_pre_opcode_bytes (fragP);
8901   pre_opcode_bytes += loop_insn_size;
8902
8903   /* For loops, the alignment depends on the size of the
8904      instruction following the loop, not the LOOP instruction.  */
8905
8906   if (first_insn == NULL)
8907     first_insn_size = xtensa_fetch_width;
8908   else
8909     first_insn_size = get_loop_align_size (frag_format_size (first_insn));
8910
8911   /* If it was 8, then we'll need a larger alignment for the section.  */
8912   align_power = get_text_align_power (first_insn_size);
8913   record_alignment (now_seg, align_power);
8914
8915   fill_size = get_text_align_fill_size
8916     (address + pre_opcode_bytes, align_power, first_insn_size, TRUE,
8917      fragP->tc_frag_data.is_no_density);
8918
8919   return address + fill_size;
8920 }
8921
8922
8923 /* 3 mechanisms for relaxing an alignment:
8924
8925    Align to a power of 2.
8926    Align so the next fragment's instruction does not cross a word boundary.
8927    Align the current instruction so that if the next instruction
8928        were 3 bytes, it would not cross a word boundary.
8929
8930    We can align with:
8931
8932    zeros    - This is easy; always insert zeros.
8933    nops     - 3-byte and 2-byte instructions
8934               2 - 2-byte nop
8935               3 - 3-byte nop
8936               4 - 2 2-byte nops
8937               >=5 : 3-byte instruction + fn (n-3)
8938    widening - widen previous instructions.  */
8939
8940 static offsetT
8941 get_aligned_diff (fragS *fragP, addressT address, offsetT *max_diff)
8942 {
8943   addressT target_address, loop_insn_offset;
8944   int target_size;
8945   xtensa_opcode loop_opcode;
8946   bfd_boolean is_loop;
8947   int align_power;
8948   offsetT opt_diff;
8949   offsetT branch_align;
8950   fragS *loop_frag;
8951
8952   gas_assert (fragP->fr_type == rs_machine_dependent);
8953   switch (fragP->fr_subtype)
8954     {
8955     case RELAX_DESIRE_ALIGN:
8956       target_size = next_frag_format_size (fragP);
8957       if (target_size == XTENSA_UNDEFINED)
8958         target_size = 3;
8959       align_power = branch_align_power (now_seg);
8960       branch_align = 1 << align_power;
8961       /* Don't count on the section alignment being as large as the target.  */
8962       if (target_size > branch_align)
8963         target_size = branch_align;
8964       opt_diff = get_text_align_fill_size (address, align_power,
8965                                            target_size, FALSE, FALSE);
8966
8967       *max_diff = (opt_diff + branch_align
8968                    - (target_size + ((address + opt_diff) % branch_align)));
8969       gas_assert (*max_diff >= opt_diff);
8970       return opt_diff;
8971
8972     case RELAX_ALIGN_NEXT_OPCODE:
8973       /* The next non-empty frag after this one holds the LOOP instruction
8974          that needs to be aligned.  The required alignment depends on the
8975          size of the next non-empty frag after the loop frag, i.e., the
8976          first instruction in the loop.  */
8977       loop_frag = next_non_empty_frag (fragP);
8978       target_size = get_loop_align_size (next_frag_format_size (loop_frag));
8979       loop_insn_offset = 0;
8980       is_loop = next_frag_opcode_is_loop (fragP, &loop_opcode);
8981       gas_assert (is_loop);
8982
8983       /* If the loop has been expanded then the LOOP instruction
8984          could be at an offset from this fragment.  */
8985       if (loop_frag->tc_frag_data.slot_subtypes[0] != RELAX_IMMED)
8986         loop_insn_offset = get_expanded_loop_offset (loop_opcode);
8987
8988       /* In an ideal world, which is what we are shooting for here,
8989          we wouldn't need to use any NOPs immediately prior to the
8990          LOOP instruction.  If this approach fails, relax_frag_loop_align
8991          will call get_noop_aligned_address.  */
8992       target_address =
8993         address + loop_insn_offset + xg_get_single_size (loop_opcode);
8994       align_power = get_text_align_power (target_size);
8995       opt_diff = get_text_align_fill_size (target_address, align_power,
8996                                            target_size, FALSE, FALSE);
8997
8998       *max_diff = xtensa_fetch_width
8999         - ((target_address + opt_diff) % xtensa_fetch_width)
9000         - target_size + opt_diff;
9001       gas_assert (*max_diff >= opt_diff);
9002       return opt_diff;
9003
9004     default:
9005       break;
9006     }
9007   gas_assert (0);
9008   return 0;
9009 }
9010
9011 \f
9012 /* md_relax_frag Hook and Helper Functions.  */
9013
9014 static long relax_frag_loop_align (fragS *, long);
9015 static long relax_frag_for_align (fragS *, long);
9016 static long relax_frag_immed
9017   (segT, fragS *, long, int, xtensa_format, int, int *, bfd_boolean);
9018
9019 typedef struct cached_fixup cached_fixupS;
9020 struct cached_fixup
9021 {
9022   int addr;
9023   int target;
9024   int delta;
9025   fixS *fixP;
9026 };
9027
9028 typedef struct fixup_cache fixup_cacheS;
9029 struct fixup_cache
9030 {
9031   cached_fixupS *fixups;
9032   unsigned n_fixups;
9033   unsigned n_max;
9034
9035   segT seg;
9036   fragS *first_frag;
9037 };
9038
9039 static int fixup_order (const void *a, const void *b)
9040 {
9041   const cached_fixupS *pa = a;
9042   const cached_fixupS *pb = b;
9043
9044   if (pa->addr == pb->addr)
9045     {
9046       if (pa->target == pb->target)
9047         {
9048           if (pa->fixP->fx_r_type == pb->fixP->fx_r_type)
9049             return 0;
9050           return pa->fixP->fx_r_type < pb->fixP->fx_r_type ?  -1 : 1;
9051         }
9052       return pa->target - pb->target;
9053     }
9054   return pa->addr - pb->addr;
9055 }
9056
9057 static bfd_boolean xtensa_make_cached_fixup (cached_fixupS *o, fixS *fixP)
9058 {
9059   xtensa_isa isa = xtensa_default_isa;
9060   int addr = fixP->fx_frag->fr_address;
9061   int target;
9062   int delta;
9063   symbolS *s = fixP->fx_addsy;
9064   int slot;
9065   xtensa_format fmt;
9066   xtensa_opcode opcode;
9067
9068   if (fixP->fx_r_type < BFD_RELOC_XTENSA_SLOT0_OP ||
9069       fixP->fx_r_type > BFD_RELOC_XTENSA_SLOT14_OP)
9070     return FALSE;
9071   target = S_GET_VALUE (s);
9072   delta = target - addr;
9073
9074   if (abs(delta) < J_RANGE / 2)
9075     return FALSE;
9076
9077   xtensa_insnbuf_from_chars (isa, trampoline_buf,
9078                              (unsigned char *) fixP->fx_frag->fr_literal +
9079                              fixP->fx_where, 0);
9080   fmt = xtensa_format_decode (isa, trampoline_buf);
9081   gas_assert (fmt != XTENSA_UNDEFINED);
9082   slot = fixP->tc_fix_data.slot;
9083   xtensa_format_get_slot (isa, fmt, slot, trampoline_buf, trampoline_slotbuf);
9084   opcode = xtensa_opcode_decode (isa, fmt, slot, trampoline_slotbuf);
9085   if (opcode != xtensa_j_opcode)
9086     return FALSE;
9087
9088   o->addr = addr;
9089   o->target = target;
9090   o->delta = delta;
9091   o->fixP = fixP;
9092
9093   return TRUE;
9094 }
9095
9096 static void xtensa_realloc_fixup_cache (fixup_cacheS *cache, unsigned add)
9097 {
9098   if (cache->n_fixups + add > cache->n_max)
9099     {
9100       cache->n_max = (cache->n_fixups + add) * 2;
9101       cache->fixups = xrealloc (cache->fixups,
9102                                 sizeof (*cache->fixups) * cache->n_max);
9103     }
9104 }
9105
9106 static void xtensa_cache_relaxable_fixups (fixup_cacheS *cache,
9107                                            segment_info_type *seginfo)
9108 {
9109   fixS *fixP;
9110
9111   cache->n_fixups = 0;
9112
9113   for (fixP = seginfo->fix_root; fixP ; fixP = fixP->fx_next)
9114     {
9115       xtensa_realloc_fixup_cache (cache, 1);
9116
9117       if (xtensa_make_cached_fixup (cache->fixups + cache->n_fixups, fixP))
9118         ++cache->n_fixups;
9119     }
9120   qsort (cache->fixups, cache->n_fixups, sizeof (*cache->fixups), fixup_order);
9121 }
9122
9123 static unsigned xtensa_find_first_cached_fixup (const fixup_cacheS *cache,
9124                                                 int addr)
9125 {
9126   unsigned a = 0;
9127   unsigned b = cache->n_fixups;
9128
9129   while (b - a > 1)
9130     {
9131       unsigned c = (a + b) / 2;
9132
9133       if (cache->fixups[c].addr < addr)
9134         a = c;
9135       else
9136         b = c;
9137     }
9138   return a;
9139 }
9140
9141 static void xtensa_delete_cached_fixup (fixup_cacheS *cache, unsigned i)
9142 {
9143   memmove (cache->fixups + i, cache->fixups + i + 1,
9144            (cache->n_fixups - i - 1) * sizeof (*cache->fixups));
9145   --cache->n_fixups;
9146 }
9147
9148 static bfd_boolean xtensa_add_cached_fixup (fixup_cacheS *cache, fixS *fixP)
9149 {
9150   cached_fixupS o;
9151   unsigned i;
9152
9153   if (!xtensa_make_cached_fixup (&o, fixP))
9154     return FALSE;
9155   xtensa_realloc_fixup_cache (cache, 1);
9156   i = xtensa_find_first_cached_fixup (cache, o.addr);
9157   if (i < cache->n_fixups)
9158     {
9159       ++i;
9160       memmove (cache->fixups + i + 1, cache->fixups + i,
9161                (cache->n_fixups - i) * sizeof (*cache->fixups));
9162     }
9163   cache->fixups[i] = o;
9164   ++cache->n_fixups;
9165   return TRUE;
9166 }
9167
9168 /* Return the number of bytes added to this fragment, given that the
9169    input has been stretched already by "stretch".  */
9170
9171 long
9172 xtensa_relax_frag (fragS *fragP, long stretch, int *stretched_p)
9173 {
9174   xtensa_isa isa = xtensa_default_isa;
9175   int unreported = fragP->tc_frag_data.unreported_expansion;
9176   long new_stretch = 0;
9177   const char *file_name;
9178   unsigned line;
9179   int lit_size;
9180   static xtensa_insnbuf vbuf = NULL;
9181   int slot, num_slots;
9182   xtensa_format fmt;
9183
9184   file_name = as_where (&line);
9185   new_logical_line (fragP->fr_file, fragP->fr_line);
9186
9187   fragP->tc_frag_data.unreported_expansion = 0;
9188
9189   switch (fragP->fr_subtype)
9190     {
9191     case RELAX_ALIGN_NEXT_OPCODE:
9192       /* Always convert.  */
9193       if (fragP->tc_frag_data.relax_seen)
9194         new_stretch = relax_frag_loop_align (fragP, stretch);
9195       break;
9196
9197     case RELAX_LOOP_END:
9198       /* Do nothing.  */
9199       break;
9200
9201     case RELAX_LOOP_END_ADD_NOP:
9202       /* Add a NOP and switch to .fill 0.  */
9203       new_stretch = relax_frag_add_nop (fragP);
9204       frag_wane (fragP);
9205       break;
9206
9207     case RELAX_DESIRE_ALIGN:
9208       /* Do nothing. The narrowing before this frag will either align
9209          it or not.  */
9210       break;
9211
9212     case RELAX_LITERAL:
9213     case RELAX_LITERAL_FINAL:
9214       return 0;
9215
9216     case RELAX_LITERAL_NR:
9217       lit_size = 4;
9218       fragP->fr_subtype = RELAX_LITERAL_FINAL;
9219       gas_assert (unreported == lit_size);
9220       memset (&fragP->fr_literal[fragP->fr_fix], 0, 4);
9221       fragP->fr_var -= lit_size;
9222       fragP->fr_fix += lit_size;
9223       new_stretch = 4;
9224       break;
9225
9226     case RELAX_SLOTS:
9227       if (vbuf == NULL)
9228         vbuf = xtensa_insnbuf_alloc (isa);
9229
9230       xtensa_insnbuf_from_chars
9231         (isa, vbuf, (unsigned char *) fragP->fr_opcode, 0);
9232       fmt = xtensa_format_decode (isa, vbuf);
9233       num_slots = xtensa_format_num_slots (isa, fmt);
9234
9235       for (slot = 0; slot < num_slots; slot++)
9236         {
9237           switch (fragP->tc_frag_data.slot_subtypes[slot])
9238             {
9239             case RELAX_NARROW:
9240               if (fragP->tc_frag_data.relax_seen)
9241                 new_stretch += relax_frag_for_align (fragP, stretch);
9242               break;
9243
9244             case RELAX_IMMED:
9245             case RELAX_IMMED_STEP1:
9246             case RELAX_IMMED_STEP2:
9247             case RELAX_IMMED_STEP3:
9248               /* Place the immediate.  */
9249               new_stretch += relax_frag_immed
9250                 (now_seg, fragP, stretch,
9251                  fragP->tc_frag_data.slot_subtypes[slot] - RELAX_IMMED,
9252                  fmt, slot, stretched_p, FALSE);
9253               break;
9254
9255             default:
9256               /* This is OK; see the note in xg_assemble_vliw_tokens.  */
9257               break;
9258             }
9259         }
9260       break;
9261
9262     case RELAX_LITERAL_POOL_BEGIN:
9263       if (fragP->fr_var != 0)
9264         {
9265           /* We have a converted "candidate" literal pool;
9266              assemble a jump around it.  */
9267           TInsn insn;
9268           if (!litpool_slotbuf)
9269             {
9270               litpool_buf = xtensa_insnbuf_alloc (isa);
9271               litpool_slotbuf = xtensa_insnbuf_alloc (isa);
9272             }
9273           new_stretch += 3;
9274           fragP->tc_frag_data.relax_seen = FALSE; /* Need another pass.  */
9275           fragP->tc_frag_data.is_insn = TRUE;
9276           tinsn_init (&insn);
9277           insn.insn_type = ITYPE_INSN;
9278           insn.opcode = xtensa_j_opcode;
9279           insn.ntok = 1;
9280           set_expr_symbol_offset (&insn.tok[0], fragP->fr_symbol,
9281                                   fragP->fr_fix);
9282           fmt = xg_get_single_format (xtensa_j_opcode);
9283           tinsn_to_slotbuf (fmt, 0, &insn, litpool_slotbuf);
9284           xtensa_format_set_slot (isa, fmt, 0, litpool_buf, litpool_slotbuf);
9285           xtensa_insnbuf_to_chars (isa, litpool_buf,
9286                                    (unsigned char *)fragP->fr_literal +
9287                                    fragP->fr_fix, 3);
9288           fragP->fr_fix += 3;
9289           fragP->fr_var -= 3;
9290           /* Add a fix-up.  */
9291           fix_new (fragP, 0, 3, fragP->fr_symbol, 0, TRUE,
9292                    BFD_RELOC_XTENSA_SLOT0_OP);
9293         }
9294       break;
9295
9296     case RELAX_LITERAL_POOL_END:
9297     case RELAX_LITERAL_POOL_CANDIDATE_BEGIN:
9298     case RELAX_MAYBE_UNREACHABLE:
9299     case RELAX_MAYBE_DESIRE_ALIGN:
9300       /* No relaxation required.  */
9301       break;
9302
9303     case RELAX_FILL_NOP:
9304     case RELAX_UNREACHABLE:
9305       if (fragP->tc_frag_data.relax_seen)
9306         new_stretch += relax_frag_for_align (fragP, stretch);
9307       break;
9308
9309     case RELAX_TRAMPOLINE:
9310       if (fragP->tc_frag_data.relax_seen)
9311         {
9312           static fixup_cacheS fixup_cache;
9313           segment_info_type *seginfo = seg_info (now_seg);
9314           int trampaddr = fragP->fr_address + fragP->fr_fix;
9315           int searchaddr = trampaddr < J_RANGE ? 0 : trampaddr - J_RANGE;
9316           unsigned i;
9317
9318           if (now_seg != fixup_cache.seg ||
9319               fragP == fixup_cache.first_frag ||
9320               fixup_cache.first_frag == NULL)
9321             {
9322               xtensa_cache_relaxable_fixups (&fixup_cache, seginfo);
9323               fixup_cache.seg = now_seg;
9324               fixup_cache.first_frag = fragP;
9325             }
9326
9327           /* Scan for jumps that will not reach.  */
9328           for (i = xtensa_find_first_cached_fixup (&fixup_cache, searchaddr);
9329                i < fixup_cache.n_fixups; ++i)
9330
9331             {
9332               fixS *fixP = fixup_cache.fixups[i].fixP;
9333               int target = fixup_cache.fixups[i].target;
9334               int addr = fixup_cache.fixups[i].addr;
9335               int delta = fixup_cache.fixups[i].delta + stretch;
9336
9337               trampaddr = fragP->fr_address + fragP->fr_fix;
9338
9339               if (addr + J_RANGE < trampaddr)
9340                 continue;
9341               if (addr > trampaddr + J_RANGE)
9342                 break;
9343               if (abs (delta) < J_RANGE)
9344                 continue;
9345
9346               slot = fixP->tc_fix_data.slot;
9347
9348               if (delta > J_RANGE  || delta < -1 * J_RANGE)
9349                 { /* Found an out-of-range jump; scan the list of trampolines for the best match.  */
9350                   struct trampoline_seg *ts = find_trampoline_seg (now_seg);
9351                   struct trampoline_frag *tf = ts->trampoline_list.next;
9352                   struct trampoline_frag *prev = &ts->trampoline_list;
9353                   int lower = (target < addr) ? target : addr;
9354                   int upper = (target > addr) ? target : addr;
9355                   int midpoint = lower + (upper - lower) / 2;
9356
9357                   if ((upper - lower) > 2 * J_RANGE)
9358                     {
9359                       /* One trampoline won't suffice; we need multiple jumps.
9360                          Jump to the trampoline that's farthest, but still in
9361                          range relative to the original "j" instruction.  */
9362                       for ( ; tf; prev = tf, tf = tf->next )
9363                         {
9364                           int this_addr = tf->fragP->fr_address + tf->fragP->fr_fix;
9365                           int next_addr = (tf->next) ? tf->next->fragP->fr_address + tf->next->fragP->fr_fix : 0 ;
9366
9367                           if (addr == lower)
9368                             {
9369                               /* Forward jump.  */
9370                               if (this_addr - addr < J_RANGE)
9371                                 break;
9372                             }
9373                           else
9374                             {
9375                               /* Backward jump.  */
9376                               if (next_addr == 0 || addr - next_addr > J_RANGE)
9377                                 break;
9378                             }
9379                         }
9380                     }
9381                   else
9382                     {
9383                       struct trampoline_frag *best_tf = NULL;
9384                       int best_delta = 0;
9385
9386                       for ( ; tf; prev = tf, tf = tf->next )
9387                         {
9388                           int this_addr = tf->fragP->fr_address + tf->fragP->fr_fix;
9389                           int this_delta = abs (this_addr - midpoint);
9390
9391                           if (!best_tf || this_delta < best_delta)
9392                             {
9393                                best_tf = tf;
9394                                best_delta = this_delta;
9395                             }
9396                         }
9397                       tf = best_tf;
9398                     }
9399                   if (tf->fragP == fragP)
9400                     {
9401                       if (abs (addr - trampaddr) < J_RANGE)
9402                         { /* The trampoline is in range of original; fix it!  */
9403                           fixS *newfixP;
9404                           int offset;
9405                           TInsn insn;
9406                           symbolS *lsym;
9407                           fragS *fP; /* The out-of-range jump.  */
9408
9409                           new_stretch += init_trampoline_frag (tf);
9410                           offset = fragP->fr_fix; /* Where to assemble the j insn.  */
9411                           lsym = fragP->fr_symbol;
9412                           fP = fixP->fx_frag;
9413                           /* Assemble a jump to the target label here.  */
9414                           tinsn_init (&insn);
9415                           insn.insn_type = ITYPE_INSN;
9416                           insn.opcode = xtensa_j_opcode;
9417                           insn.ntok = 1;
9418                           set_expr_symbol_offset (&insn.tok[0], lsym, offset);
9419                           fmt = xg_get_single_format (xtensa_j_opcode);
9420                           tinsn_to_slotbuf (fmt, 0, &insn, trampoline_slotbuf);
9421                           xtensa_format_set_slot (isa, fmt, 0, trampoline_buf, trampoline_slotbuf);
9422                           xtensa_insnbuf_to_chars (isa, trampoline_buf, (unsigned char *)fragP->fr_literal + offset, 3);
9423                           fragP->fr_fix += 3;
9424                           fragP->fr_var -= 3;
9425                           /* Add a fix-up for the original j insn.  */
9426                           newfixP = fix_new (fP, fixP->fx_where, fixP->fx_size, lsym, fragP->fr_fix - 3, TRUE, fixP->fx_r_type);
9427                           newfixP->fx_no_overflow = 1;
9428                           newfixP->tc_fix_data.X_add_symbol = lsym;
9429                           newfixP->tc_fix_data.X_add_number = offset;
9430                           newfixP->tc_fix_data.slot = slot;
9431
9432                           xtensa_delete_cached_fixup (&fixup_cache, i);
9433                           xtensa_add_cached_fixup (&fixup_cache, newfixP);
9434
9435                           /* Move the fix-up from the original j insn to this one.  */
9436                           fixP->fx_frag = fragP;
9437                           fixP->fx_where = fragP->fr_fix - 3;
9438                           fixP->tc_fix_data.slot = 0;
9439
9440                           xtensa_add_cached_fixup (&fixup_cache, fixP);
9441
9442                           /* re-do current fixup */
9443                           --i;
9444
9445                           /* Adjust the jump around this trampoline (if present).  */
9446                           if (tf->fixP != NULL)
9447                             {
9448                               tf->fixP->fx_offset += 3;
9449                             }
9450                           new_stretch += 3;
9451                           fragP->tc_frag_data.relax_seen = FALSE; /* Need another pass.  */
9452                           /* Do we have room for more?  */
9453                           if (fragP->fr_var < 3)
9454                             { /* No, convert to fill.  */
9455                               frag_wane (fragP);
9456                               fragP->fr_subtype = 0;
9457                               /* Remove from the trampoline_list.  */
9458                               prev->next = tf->next;
9459                               if (fragP == fixup_cache.first_frag)
9460                                 fixup_cache.first_frag = NULL;
9461                               break;
9462                             }
9463                         }
9464                     }
9465                 }
9466             }
9467         }
9468       break;
9469
9470     default:
9471       as_bad (_("bad relaxation state"));
9472     }
9473
9474   /* Tell gas we need another relaxation pass.  */
9475   if (! fragP->tc_frag_data.relax_seen)
9476     {
9477       fragP->tc_frag_data.relax_seen = TRUE;
9478       *stretched_p = 1;
9479     }
9480
9481   new_logical_line (file_name, line);
9482   return new_stretch;
9483 }
9484
9485
9486 static long
9487 relax_frag_loop_align (fragS *fragP, long stretch)
9488 {
9489   addressT old_address, old_next_address, old_size;
9490   addressT new_address, new_next_address, new_size;
9491   addressT growth;
9492
9493   /* All the frags with relax_frag_for_alignment prior to this one in the
9494      section have been done, hopefully eliminating the need for a NOP here.
9495      But, this will put it in if necessary.  */
9496
9497   /* Calculate the old address of this fragment and the next fragment.  */
9498   old_address = fragP->fr_address - stretch;
9499   old_next_address = (fragP->fr_address - stretch + fragP->fr_fix +
9500                       fragP->tc_frag_data.text_expansion[0]);
9501   old_size = old_next_address - old_address;
9502
9503   /* Calculate the new address of this fragment and the next fragment.  */
9504   new_address = fragP->fr_address;
9505   new_next_address =
9506     get_noop_aligned_address (fragP, fragP->fr_address + fragP->fr_fix);
9507   new_size = new_next_address - new_address;
9508
9509   growth = new_size - old_size;
9510
9511   /* Fix up the text_expansion field and return the new growth.  */
9512   fragP->tc_frag_data.text_expansion[0] += growth;
9513   return growth;
9514 }
9515
9516
9517 /* Add a NOP instruction.  */
9518
9519 static long
9520 relax_frag_add_nop (fragS *fragP)
9521 {
9522   char *nop_buf = fragP->fr_literal + fragP->fr_fix;
9523   int length = fragP->tc_frag_data.is_no_density ? 3 : 2;
9524   assemble_nop (length, nop_buf);
9525   fragP->tc_frag_data.is_insn = TRUE;
9526
9527   if (fragP->fr_var < length)
9528     {
9529       as_fatal (_("fr_var (%ld) < length (%d)"), (long) fragP->fr_var, length);
9530       return 0;
9531     }
9532
9533   fragP->fr_fix += length;
9534   fragP->fr_var -= length;
9535   return length;
9536 }
9537
9538
9539 static long future_alignment_required (fragS *, long);
9540
9541 static long
9542 relax_frag_for_align (fragS *fragP, long stretch)
9543 {
9544   /* Overview of the relaxation procedure for alignment:
9545      We can widen with NOPs or by widening instructions or by filling
9546      bytes after jump instructions.  Find the opportune places and widen
9547      them if necessary.  */
9548
9549   long stretch_me;
9550   long diff;
9551
9552   gas_assert (fragP->fr_subtype == RELAX_FILL_NOP
9553           || fragP->fr_subtype == RELAX_UNREACHABLE
9554           || (fragP->fr_subtype == RELAX_SLOTS
9555               && fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW));
9556
9557   stretch_me = future_alignment_required (fragP, stretch);
9558   diff = stretch_me - fragP->tc_frag_data.text_expansion[0];
9559   if (diff == 0)
9560     return 0;
9561
9562   if (diff < 0)
9563     {
9564       /* We expanded on a previous pass.  Can we shrink now?  */
9565       long shrink = fragP->tc_frag_data.text_expansion[0] - stretch_me;
9566       if (shrink <= stretch && stretch > 0)
9567         {
9568           fragP->tc_frag_data.text_expansion[0] = stretch_me;
9569           return -shrink;
9570         }
9571       return 0;
9572     }
9573
9574   /* Below here, diff > 0.  */
9575   fragP->tc_frag_data.text_expansion[0] = stretch_me;
9576
9577   return diff;
9578 }
9579
9580
9581 /* Return the address of the next frag that should be aligned.
9582
9583    By "address" we mean the address it _would_ be at if there
9584    is no action taken to align it between here and the target frag.
9585    In other words, if no narrows and no fill nops are used between
9586    here and the frag to align, _even_if_ some of the frags we use
9587    to align targets have already expanded on a previous relaxation
9588    pass.
9589
9590    Also, count each frag that may be used to help align the target.
9591
9592    Return 0 if there are no frags left in the chain that need to be
9593    aligned.  */
9594
9595 static addressT
9596 find_address_of_next_align_frag (fragS **fragPP,
9597                                  int *wide_nops,
9598                                  int *narrow_nops,
9599                                  int *widens,
9600                                  bfd_boolean *paddable)
9601 {
9602   fragS *fragP = *fragPP;
9603   addressT address = fragP->fr_address;
9604
9605   /* Do not reset the counts to 0.  */
9606
9607   while (fragP)
9608     {
9609       /* Limit this to a small search.  */
9610       if (*widens >= (int) xtensa_fetch_width)
9611         {
9612           *fragPP = fragP;
9613           return 0;
9614         }
9615       address += fragP->fr_fix;
9616
9617       if (fragP->fr_type == rs_fill)
9618         address += fragP->fr_offset * fragP->fr_var;
9619       else if (fragP->fr_type == rs_machine_dependent)
9620         {
9621           switch (fragP->fr_subtype)
9622             {
9623             case RELAX_UNREACHABLE:
9624               *paddable = TRUE;
9625               break;
9626
9627             case RELAX_FILL_NOP:
9628               (*wide_nops)++;
9629               if (!fragP->tc_frag_data.is_no_density)
9630                 (*narrow_nops)++;
9631               break;
9632
9633             case RELAX_SLOTS:
9634               if (fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
9635                 {
9636                   (*widens)++;
9637                   break;
9638                 }
9639               address += total_frag_text_expansion (fragP);
9640               break;
9641
9642             case RELAX_IMMED:
9643               address += fragP->tc_frag_data.text_expansion[0];
9644               break;
9645
9646             case RELAX_ALIGN_NEXT_OPCODE:
9647             case RELAX_DESIRE_ALIGN:
9648               *fragPP = fragP;
9649               return address;
9650
9651             case RELAX_MAYBE_UNREACHABLE:
9652             case RELAX_MAYBE_DESIRE_ALIGN:
9653               /* Do nothing.  */
9654               break;
9655
9656             default:
9657               /* Just punt if we don't know the type.  */
9658               *fragPP = fragP;
9659               return 0;
9660             }
9661         }
9662       else
9663         {
9664           /* Just punt if we don't know the type.  */
9665           *fragPP = fragP;
9666           return 0;
9667         }
9668       fragP = fragP->fr_next;
9669     }
9670
9671   *fragPP = fragP;
9672   return 0;
9673 }
9674
9675
9676 static long bytes_to_stretch (fragS *, int, int, int, int);
9677
9678 static long
9679 future_alignment_required (fragS *fragP, long stretch ATTRIBUTE_UNUSED)
9680 {
9681   fragS *this_frag = fragP;
9682   long address;
9683   int num_widens = 0;
9684   int wide_nops = 0;
9685   int narrow_nops = 0;
9686   bfd_boolean paddable = FALSE;
9687   offsetT local_opt_diff;
9688   offsetT opt_diff;
9689   offsetT max_diff;
9690   int stretch_amount = 0;
9691   int local_stretch_amount;
9692   int global_stretch_amount;
9693
9694   address = find_address_of_next_align_frag
9695     (&fragP, &wide_nops, &narrow_nops, &num_widens, &paddable);
9696
9697   if (!address)
9698     {
9699       if (this_frag->tc_frag_data.is_aligning_branch)
9700         this_frag->tc_frag_data.slot_subtypes[0] = RELAX_IMMED;
9701       else
9702         frag_wane (this_frag);
9703     }
9704   else
9705     {
9706       local_opt_diff = get_aligned_diff (fragP, address, &max_diff);
9707       opt_diff = local_opt_diff;
9708       gas_assert (opt_diff >= 0);
9709       gas_assert (max_diff >= opt_diff);
9710       if (max_diff == 0)
9711         return 0;
9712
9713       if (fragP)
9714         fragP = fragP->fr_next;
9715
9716       while (fragP && opt_diff < max_diff && address)
9717         {
9718           /* We only use these to determine if we can exit early
9719              because there will be plenty of ways to align future
9720              align frags.  */
9721           int glob_widens = 0;
9722           int dnn = 0;
9723           int dw = 0;
9724           bfd_boolean glob_pad = 0;
9725           address = find_address_of_next_align_frag
9726             (&fragP, &glob_widens, &dnn, &dw, &glob_pad);
9727           /* If there is a padable portion, then skip.  */
9728           if (glob_pad || glob_widens >= (1 << branch_align_power (now_seg)))
9729             address = 0;
9730
9731           if (address)
9732             {
9733               offsetT next_m_diff;
9734               offsetT next_o_diff;
9735
9736               /* Downrange frags haven't had stretch added to them yet.  */
9737               address += stretch;
9738
9739               /* The address also includes any text expansion from this
9740                  frag in a previous pass, but we don't want that.  */
9741               address -= this_frag->tc_frag_data.text_expansion[0];
9742
9743               /* Assume we are going to move at least opt_diff.  In
9744                  reality, we might not be able to, but assuming that
9745                  we will helps catch cases where moving opt_diff pushes
9746                  the next target from aligned to unaligned.  */
9747               address += opt_diff;
9748
9749               next_o_diff = get_aligned_diff (fragP, address, &next_m_diff);
9750
9751               /* Now cleanup for the adjustments to address.  */
9752               next_o_diff += opt_diff;
9753               next_m_diff += opt_diff;
9754               if (next_o_diff <= max_diff && next_o_diff > opt_diff)
9755                 opt_diff = next_o_diff;
9756               if (next_m_diff < max_diff)
9757                 max_diff = next_m_diff;
9758               fragP = fragP->fr_next;
9759             }
9760         }
9761
9762       /* If there are enough wideners in between, do it.  */
9763       if (paddable)
9764         {
9765           if (this_frag->fr_subtype == RELAX_UNREACHABLE)
9766             {
9767               gas_assert (opt_diff <= (signed) xtensa_fetch_width);
9768               return opt_diff;
9769             }
9770           return 0;
9771         }
9772       local_stretch_amount
9773         = bytes_to_stretch (this_frag, wide_nops, narrow_nops,
9774                             num_widens, local_opt_diff);
9775       global_stretch_amount
9776         = bytes_to_stretch (this_frag, wide_nops, narrow_nops,
9777                             num_widens, opt_diff);
9778       /* If the condition below is true, then the frag couldn't
9779          stretch the correct amount for the global case, so we just
9780          optimize locally.  We'll rely on the subsequent frags to get
9781          the correct alignment in the global case.  */
9782       if (global_stretch_amount < local_stretch_amount)
9783         stretch_amount = local_stretch_amount;
9784       else
9785         stretch_amount = global_stretch_amount;
9786
9787       if (this_frag->fr_subtype == RELAX_SLOTS
9788           && this_frag->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
9789         gas_assert (stretch_amount <= 1);
9790       else if (this_frag->fr_subtype == RELAX_FILL_NOP)
9791         {
9792           if (this_frag->tc_frag_data.is_no_density)
9793             gas_assert (stretch_amount == 3 || stretch_amount == 0);
9794           else
9795             gas_assert (stretch_amount <= 3);
9796         }
9797     }
9798   return stretch_amount;
9799 }
9800
9801
9802 /* The idea: widen everything you can to get a target or loop aligned,
9803    then start using NOPs.
9804
9805    wide_nops   = the number of wide NOPs available for aligning
9806    narrow_nops = the number of narrow NOPs available for aligning
9807                  (a subset of wide_nops)
9808    widens      = the number of narrow instructions that should be widened
9809
9810 */
9811
9812 static long
9813 bytes_to_stretch (fragS *this_frag,
9814                   int wide_nops,
9815                   int narrow_nops,
9816                   int num_widens,
9817                   int desired_diff)
9818 {
9819   int nops_needed;
9820   int nop_bytes;
9821   int extra_bytes;
9822   int bytes_short = desired_diff - num_widens;
9823
9824   gas_assert (desired_diff >= 0
9825               && desired_diff < (signed) xtensa_fetch_width);
9826   if (desired_diff == 0)
9827     return 0;
9828
9829   gas_assert (wide_nops > 0 || num_widens > 0);
9830
9831   /* Always prefer widening to NOP-filling.  */
9832   if (bytes_short < 0)
9833     {
9834       /* There are enough RELAX_NARROW frags after this one
9835          to align the target without widening this frag in any way.  */
9836       return 0;
9837     }
9838
9839   if (bytes_short == 0)
9840     {
9841       /* Widen every narrow between here and the align target
9842          and the align target will be properly aligned.  */
9843       if (this_frag->fr_subtype == RELAX_FILL_NOP)
9844         return 0;
9845       else
9846         return 1;
9847     }
9848
9849   /* From here we will need at least one NOP to get an alignment.
9850      However, we may not be able to align at all, in which case,
9851      don't widen.  */
9852   nops_needed = desired_diff / 3;
9853
9854   /* If there aren't enough nops, don't widen.  */
9855   if (nops_needed > wide_nops)
9856     return 0;
9857
9858   /* First try it with all wide nops.  */
9859   nop_bytes = nops_needed * 3;
9860   extra_bytes = desired_diff - nop_bytes;
9861
9862   if (nop_bytes + num_widens >= desired_diff)
9863     {
9864       if (this_frag->fr_subtype == RELAX_FILL_NOP)
9865         return 3;
9866       else if (num_widens == extra_bytes)
9867         return 1;
9868       return 0;
9869     }
9870
9871   /* Add a narrow nop.  */
9872   nops_needed++;
9873   nop_bytes += 2;
9874   extra_bytes -= 2;
9875   if (narrow_nops == 0 || nops_needed > wide_nops)
9876     return 0;
9877
9878   if (nop_bytes + num_widens >= desired_diff && extra_bytes >= 0)
9879     {
9880       if (this_frag->fr_subtype == RELAX_FILL_NOP)
9881         return !this_frag->tc_frag_data.is_no_density ? 2 : 3;
9882       else if (num_widens == extra_bytes)
9883         return 1;
9884       return 0;
9885     }
9886
9887   /* Replace a wide nop with a narrow nop--we can get here if
9888      extra_bytes was negative in the previous conditional.  */
9889   if (narrow_nops == 1)
9890     return 0;
9891   nop_bytes--;
9892   extra_bytes++;
9893   if (nop_bytes + num_widens >= desired_diff)
9894     {
9895       if (this_frag->fr_subtype == RELAX_FILL_NOP)
9896         return !this_frag->tc_frag_data.is_no_density ? 2 : 3;
9897       else if (num_widens == extra_bytes)
9898         return 1;
9899       return 0;
9900     }
9901
9902   /* If we can't satisfy any of the above cases, then we can't align
9903      using padding or fill nops.  */
9904   return 0;
9905 }
9906
9907
9908 static struct trampoline_frag *
9909 search_trampolines (TInsn *tinsn, fragS *fragP, bfd_boolean unreachable_only)
9910 {
9911   struct trampoline_seg *ts = find_trampoline_seg (now_seg);
9912   struct trampoline_frag *tf = (ts) ? ts->trampoline_list.next : NULL;
9913   struct trampoline_frag *best_tf = NULL;
9914   int best_delta = 0;
9915   int best_addr = 0;
9916   symbolS *sym = tinsn->tok[0].X_add_symbol;
9917   offsetT target = S_GET_VALUE (sym) + tinsn->tok[0].X_add_number;
9918   offsetT addr = fragP->fr_address;
9919   offsetT lower = (addr < target) ? addr : target;
9920   offsetT upper = (addr > target) ? addr : target;
9921   int delta = upper - lower;
9922   offsetT midpoint = lower + delta / 2;
9923   int this_delta = -1;
9924   int this_addr = -1;
9925
9926   if (delta > 2 * J_RANGE)
9927     {
9928       /* One trampoline won't do; we need multiple.
9929          Choose the farthest trampoline that's still in range of the original
9930          and let a later pass finish the job.  */
9931       for ( ; tf; tf = tf->next)
9932         {
9933           int next_addr = (tf->next) ? tf->next->fragP->fr_address + tf->next->fragP->fr_fix : 0;
9934
9935           this_addr = tf->fragP->fr_address + tf->fragP->fr_fix;
9936           if (lower == addr)
9937             {
9938               /* Forward jump.  */
9939               if (this_addr - addr < J_RANGE)
9940                 break;
9941             }
9942           else
9943             {
9944               /* Backward jump.  */
9945               if (next_addr == 0 || addr - next_addr > J_RANGE)
9946                 break;
9947             }
9948         }
9949       if (abs (addr - this_addr) < J_RANGE)
9950         return tf;
9951
9952       return NULL;
9953     }
9954   for ( ; tf; tf = tf->next)
9955     {
9956       this_addr = tf->fragP->fr_address + tf->fragP->fr_fix;
9957       this_delta = abs (this_addr - midpoint);
9958       if (unreachable_only && tf->needs_jump_around)
9959         continue;
9960       if (!best_tf || this_delta < best_delta)
9961         {
9962           best_tf = tf;
9963           best_delta = this_delta;
9964           best_addr = this_addr;
9965         }
9966     }
9967
9968   if (best_tf &&
9969       best_delta < J_RANGE &&
9970       abs(best_addr - lower) < J_RANGE &&
9971       abs(best_addr - upper) < J_RANGE)
9972     return best_tf;
9973
9974   return NULL; /* No suitable trampoline found.  */
9975 }
9976
9977
9978 static struct trampoline_frag *
9979 get_best_trampoline (TInsn *tinsn, fragS *fragP)
9980 {
9981   struct trampoline_frag *tf = NULL;
9982
9983   tf = search_trampolines (tinsn, fragP, TRUE); /* Try unreachable first.  */
9984
9985   if (tf == NULL)
9986     tf = search_trampolines (tinsn, fragP, FALSE); /* Try ones needing a jump-around, too.  */
9987
9988   return tf;
9989 }
9990
9991
9992 static void
9993 check_and_update_trampolines (void)
9994 {
9995   struct trampoline_seg *ts = find_trampoline_seg (now_seg);
9996   struct trampoline_frag *tf = ts->trampoline_list.next;
9997   struct trampoline_frag *prev = &ts->trampoline_list;
9998
9999   for ( ; tf; prev = tf, tf = tf->next)
10000     {
10001       if (tf->fragP->fr_var < 3)
10002         {
10003           frag_wane (tf->fragP);
10004           prev->next = tf->next;
10005           tf->fragP = NULL;
10006         }
10007     }
10008 }
10009
10010
10011 static int
10012 init_trampoline_frag (struct trampoline_frag *trampP)
10013 {
10014   fragS *fp = trampP->fragP;
10015   int growth = 0;
10016
10017   if (fp->fr_fix == 0)
10018     {
10019       symbolS *lsym;
10020       char label[10 + 2 * sizeof(fp)];
10021       sprintf (label, ".L0_TR_%p", fp);
10022
10023       lsym = (symbolS *)local_symbol_make (label, now_seg, 0, fp);
10024       fp->fr_symbol = lsym;
10025       if (trampP->needs_jump_around)
10026         {
10027           /* Add a jump around this block of jumps, in case
10028              control flows into this block.  */
10029           fixS *fixP;
10030           TInsn insn;
10031           xtensa_format fmt;
10032           xtensa_isa isa = xtensa_default_isa;
10033
10034           fp->tc_frag_data.is_insn = 1;
10035           /* Assemble a jump insn.  */
10036           tinsn_init (&insn);
10037           insn.insn_type = ITYPE_INSN;
10038           insn.opcode = xtensa_j_opcode;
10039           insn.ntok = 1;
10040           set_expr_symbol_offset (&insn.tok[0], lsym, 3);
10041           fmt = xg_get_single_format (xtensa_j_opcode);
10042           tinsn_to_slotbuf (fmt, 0, &insn, trampoline_slotbuf);
10043           xtensa_format_set_slot (isa, fmt, 0, trampoline_buf, trampoline_slotbuf);
10044           xtensa_insnbuf_to_chars (isa, trampoline_buf, (unsigned char *)fp->fr_literal, 3);
10045           fp->fr_fix += 3;
10046           fp->fr_var -= 3;
10047           growth = 3;
10048           fixP = fix_new (fp, 0, 3, lsym, 3, TRUE, BFD_RELOC_XTENSA_SLOT0_OP);
10049           trampP->fixP = fixP;
10050         }
10051     }
10052   return growth;
10053 }
10054
10055
10056 static int
10057 add_jump_to_trampoline (struct trampoline_frag *trampP, fragS *origfrag)
10058 {
10059   fragS *tramp = trampP->fragP;
10060   fixS *fixP;
10061   int offset = tramp->fr_fix; /* Where to assemble the j insn.  */
10062   TInsn insn;
10063   symbolS *lsym;
10064   symbolS *tsym;
10065   int toffset;
10066   xtensa_format fmt;
10067   xtensa_isa isa = xtensa_default_isa;
10068   int growth = 0;
10069
10070   lsym = tramp->fr_symbol;
10071   /* Assemble a jump to the target label in the trampoline frag.  */
10072   tsym = origfrag->tc_frag_data.slot_symbols[0];
10073   toffset = origfrag-> tc_frag_data.slot_offsets[0];
10074   tinsn_init (&insn);
10075   insn.insn_type = ITYPE_INSN;
10076   insn.opcode = xtensa_j_opcode;
10077   insn.ntok = 1;
10078   set_expr_symbol_offset (&insn.tok[0], tsym, toffset);
10079   fmt = xg_get_single_format (xtensa_j_opcode);
10080   tinsn_to_slotbuf (fmt, 0, &insn, trampoline_slotbuf);
10081   xtensa_format_set_slot (isa, fmt, 0, trampoline_buf, trampoline_slotbuf);
10082   xtensa_insnbuf_to_chars (isa, trampoline_buf, (unsigned char *)tramp->fr_literal + offset, 3);
10083   tramp->fr_fix += 3;
10084   tramp->fr_var -= 3;
10085   growth = 3;
10086   /* add a fix-up for the trampoline jump.  */
10087   fixP = fix_new (tramp, tramp->fr_fix - 3, 3, tsym, toffset, TRUE, BFD_RELOC_XTENSA_SLOT0_OP);
10088   /* Modify the jump at the start of this trampoline to point past the newly-added jump.  */
10089   fixP = trampP->fixP;
10090   if (fixP)
10091     fixP->fx_offset += 3;
10092   /* Modify the original j to point here.  */
10093   origfrag->tc_frag_data.slot_symbols[0] = lsym;
10094   origfrag->tc_frag_data.slot_offsets[0] = tramp->fr_fix - 3;
10095   /* If trampoline is full, remove it from the list.  */
10096   check_and_update_trampolines ();
10097
10098   return growth;
10099 }
10100
10101
10102 static long
10103 relax_frag_immed (segT segP,
10104                   fragS *fragP,
10105                   long stretch,
10106                   int min_steps,
10107                   xtensa_format fmt,
10108                   int slot,
10109                   int *stretched_p,
10110                   bfd_boolean estimate_only)
10111 {
10112   TInsn tinsn;
10113   int old_size;
10114   bfd_boolean negatable_branch = FALSE;
10115   bfd_boolean branch_jmp_to_next = FALSE;
10116   bfd_boolean from_wide_insn = FALSE;
10117   xtensa_isa isa = xtensa_default_isa;
10118   IStack istack;
10119   offsetT frag_offset;
10120   int num_steps;
10121   int num_text_bytes, num_literal_bytes;
10122   int literal_diff, total_text_diff, this_text_diff;
10123
10124   gas_assert (fragP->fr_opcode != NULL);
10125
10126   xg_clear_vinsn (&cur_vinsn);
10127   vinsn_from_chars (&cur_vinsn, fragP->fr_opcode);
10128   if (cur_vinsn.num_slots > 1)
10129     from_wide_insn = TRUE;
10130
10131   tinsn = cur_vinsn.slots[slot];
10132   tinsn_immed_from_frag (&tinsn, fragP, slot);
10133
10134   if (estimate_only && xtensa_opcode_is_loop (isa, tinsn.opcode) == 1)
10135     return 0;
10136
10137   if (workaround_b_j_loop_end && ! fragP->tc_frag_data.is_no_transform)
10138     branch_jmp_to_next = is_branch_jmp_to_next (&tinsn, fragP);
10139
10140   negatable_branch = (xtensa_opcode_is_branch (isa, tinsn.opcode) == 1);
10141
10142   old_size = xtensa_format_length (isa, fmt);
10143
10144   /* Special case: replace a branch to the next instruction with a NOP.
10145      This is required to work around a hardware bug in T1040.0 and also
10146      serves as an optimization.  */
10147
10148   if (branch_jmp_to_next
10149       && ((old_size == 2) || (old_size == 3))
10150       && !next_frag_is_loop_target (fragP))
10151     return 0;
10152
10153   /* Here is the fun stuff: Get the immediate field from this
10154      instruction.  If it fits, we are done.  If not, find the next
10155      instruction sequence that fits.  */
10156
10157   frag_offset = fragP->fr_opcode - fragP->fr_literal;
10158   istack_init (&istack);
10159   num_steps = xg_assembly_relax (&istack, &tinsn, segP, fragP, frag_offset,
10160                                  min_steps, stretch);
10161   gas_assert (num_steps >= min_steps && num_steps <= RELAX_IMMED_MAXSTEPS);
10162
10163   fragP->tc_frag_data.slot_subtypes[slot] = (int) RELAX_IMMED + num_steps;
10164
10165   /* Figure out the number of bytes needed.  */
10166   num_literal_bytes = get_num_stack_literal_bytes (&istack);
10167   literal_diff
10168     = num_literal_bytes - fragP->tc_frag_data.literal_expansion[slot];
10169   num_text_bytes = get_num_stack_text_bytes (&istack);
10170
10171   if (from_wide_insn)
10172     {
10173       int first = 0;
10174       while (istack.insn[first].opcode == XTENSA_UNDEFINED)
10175         first++;
10176
10177       num_text_bytes += old_size;
10178       if (opcode_fits_format_slot (istack.insn[first].opcode, fmt, slot))
10179         num_text_bytes -= xg_get_single_size (istack.insn[first].opcode);
10180       else
10181         {
10182           /* The first instruction in the relaxed sequence will go after
10183              the current wide instruction, and thus its symbolic immediates
10184              might not fit.  */
10185
10186           istack_init (&istack);
10187           num_steps = xg_assembly_relax (&istack, &tinsn, segP, fragP,
10188                                          frag_offset + old_size,
10189                                          min_steps, stretch + old_size);
10190           gas_assert (num_steps >= min_steps && num_steps <= RELAX_IMMED_MAXSTEPS);
10191
10192           fragP->tc_frag_data.slot_subtypes[slot]
10193             = (int) RELAX_IMMED + num_steps;
10194
10195           num_literal_bytes = get_num_stack_literal_bytes (&istack);
10196           literal_diff
10197             = num_literal_bytes - fragP->tc_frag_data.literal_expansion[slot];
10198
10199           num_text_bytes = get_num_stack_text_bytes (&istack) + old_size;
10200         }
10201     }
10202
10203   total_text_diff = num_text_bytes - old_size;
10204   this_text_diff = total_text_diff - fragP->tc_frag_data.text_expansion[slot];
10205
10206   /* It MUST get larger.  If not, we could get an infinite loop.  */
10207   gas_assert (num_text_bytes >= 0);
10208   gas_assert (literal_diff >= 0);
10209   gas_assert (total_text_diff >= 0);
10210
10211   fragP->tc_frag_data.text_expansion[slot] = total_text_diff;
10212   fragP->tc_frag_data.literal_expansion[slot] = num_literal_bytes;
10213   gas_assert (fragP->tc_frag_data.text_expansion[slot] >= 0);
10214   gas_assert (fragP->tc_frag_data.literal_expansion[slot] >= 0);
10215
10216   /* Find the associated expandable literal for this.  */
10217   if (literal_diff != 0)
10218     {
10219       fragS *lit_fragP = fragP->tc_frag_data.literal_frags[slot];
10220       if (lit_fragP)
10221         {
10222           gas_assert (literal_diff == 4);
10223           lit_fragP->tc_frag_data.unreported_expansion += literal_diff;
10224
10225           /* We expect that the literal section state has NOT been
10226              modified yet.  */
10227           gas_assert (lit_fragP->fr_type == rs_machine_dependent
10228                   && lit_fragP->fr_subtype == RELAX_LITERAL);
10229           lit_fragP->fr_subtype = RELAX_LITERAL_NR;
10230
10231           /* We need to mark this section for another iteration
10232              of relaxation.  */
10233           (*stretched_p)++;
10234         }
10235     }
10236
10237   if (negatable_branch && istack.ninsn > 1)
10238     update_next_frag_state (fragP);
10239
10240   /* If last insn is a jump, and it cannot reach its target, try to find a trampoline.  */
10241   if (istack.ninsn > 2 &&
10242       istack.insn[istack.ninsn - 1].insn_type == ITYPE_LABEL &&
10243       istack.insn[istack.ninsn - 2].insn_type == ITYPE_INSN &&
10244       istack.insn[istack.ninsn - 2].opcode == xtensa_j_opcode)
10245     {
10246       TInsn *jinsn = &istack.insn[istack.ninsn - 2];
10247
10248       if (!xg_symbolic_immeds_fit (jinsn, segP, fragP, fragP->fr_offset, total_text_diff))
10249         {
10250           struct trampoline_frag *tf = get_best_trampoline (jinsn, fragP);
10251
10252           if (tf)
10253             {
10254               this_text_diff += init_trampoline_frag (tf);
10255               this_text_diff += add_jump_to_trampoline (tf, fragP);
10256             }
10257           else
10258             {
10259               /* If target symbol is undefined, assume it will reach once linked.  */
10260               expressionS *exp = &istack.insn[istack.ninsn - 2].tok[0];
10261
10262               if (exp->X_op == O_symbol && S_IS_DEFINED (exp->X_add_symbol))
10263                 {
10264                   as_bad_where (fragP->fr_file, fragP->fr_line,
10265                     _("jump target out of range; no usable trampoline found"));
10266                 }
10267             }
10268         }
10269     }
10270
10271   return this_text_diff;
10272 }
10273
10274 \f
10275 /* md_convert_frag Hook and Helper Functions.  */
10276
10277 static void convert_frag_align_next_opcode (fragS *);
10278 static void convert_frag_narrow (segT, fragS *, xtensa_format, int);
10279 static void convert_frag_fill_nop (fragS *);
10280 static void convert_frag_immed (segT, fragS *, int, xtensa_format, int);
10281
10282 void
10283 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT sec, fragS *fragp)
10284 {
10285   static xtensa_insnbuf vbuf = NULL;
10286   xtensa_isa isa = xtensa_default_isa;
10287   int slot;
10288   int num_slots;
10289   xtensa_format fmt;
10290   const char *file_name;
10291   unsigned line;
10292
10293   file_name = as_where (&line);
10294   new_logical_line (fragp->fr_file, fragp->fr_line);
10295
10296   switch (fragp->fr_subtype)
10297     {
10298     case RELAX_ALIGN_NEXT_OPCODE:
10299       /* Always convert.  */
10300       convert_frag_align_next_opcode (fragp);
10301       break;
10302
10303     case RELAX_DESIRE_ALIGN:
10304       /* Do nothing.  If not aligned already, too bad.  */
10305       break;
10306
10307     case RELAX_LITERAL:
10308     case RELAX_LITERAL_FINAL:
10309       break;
10310
10311     case RELAX_SLOTS:
10312       if (vbuf == NULL)
10313         vbuf = xtensa_insnbuf_alloc (isa);
10314
10315       xtensa_insnbuf_from_chars
10316         (isa, vbuf, (unsigned char *) fragp->fr_opcode, 0);
10317       fmt = xtensa_format_decode (isa, vbuf);
10318       num_slots = xtensa_format_num_slots (isa, fmt);
10319
10320       for (slot = 0; slot < num_slots; slot++)
10321         {
10322           switch (fragp->tc_frag_data.slot_subtypes[slot])
10323             {
10324             case RELAX_NARROW:
10325               convert_frag_narrow (sec, fragp, fmt, slot);
10326               break;
10327
10328             case RELAX_IMMED:
10329             case RELAX_IMMED_STEP1:
10330             case RELAX_IMMED_STEP2:
10331             case RELAX_IMMED_STEP3:
10332               /* Place the immediate.  */
10333               convert_frag_immed
10334                 (sec, fragp,
10335                  fragp->tc_frag_data.slot_subtypes[slot] - RELAX_IMMED,
10336                  fmt, slot);
10337               break;
10338
10339             default:
10340               /* This is OK because some slots could have
10341                  relaxations and others have none.  */
10342               break;
10343             }
10344         }
10345       break;
10346
10347     case RELAX_UNREACHABLE:
10348       memset (&fragp->fr_literal[fragp->fr_fix], 0, fragp->fr_var);
10349       fragp->fr_fix += fragp->tc_frag_data.text_expansion[0];
10350       fragp->fr_var -= fragp->tc_frag_data.text_expansion[0];
10351       frag_wane (fragp);
10352       break;
10353
10354     case RELAX_MAYBE_UNREACHABLE:
10355     case RELAX_MAYBE_DESIRE_ALIGN:
10356       frag_wane (fragp);
10357       break;
10358
10359     case RELAX_FILL_NOP:
10360       convert_frag_fill_nop (fragp);
10361       break;
10362
10363     case RELAX_LITERAL_NR:
10364       if (use_literal_section)
10365         {
10366           /* This should have been handled during relaxation.  When
10367              relaxing a code segment, literals sometimes need to be
10368              added to the corresponding literal segment.  If that
10369              literal segment has already been relaxed, then we end up
10370              in this situation.  Marking the literal segments as data
10371              would make this happen less often (since GAS always relaxes
10372              code before data), but we could still get into trouble if
10373              there are instructions in a segment that is not marked as
10374              containing code.  Until we can implement a better solution,
10375              cheat and adjust the addresses of all the following frags.
10376              This could break subsequent alignments, but the linker's
10377              literal coalescing will do that anyway.  */
10378
10379           fragS *f;
10380           fragp->fr_subtype = RELAX_LITERAL_FINAL;
10381           gas_assert (fragp->tc_frag_data.unreported_expansion == 4);
10382           memset (&fragp->fr_literal[fragp->fr_fix], 0, 4);
10383           fragp->fr_var -= 4;
10384           fragp->fr_fix += 4;
10385           for (f = fragp->fr_next; f; f = f->fr_next)
10386             f->fr_address += 4;
10387         }
10388       else
10389         as_bad (_("invalid relaxation fragment result"));
10390       break;
10391
10392     case RELAX_TRAMPOLINE:
10393       break;
10394     }
10395
10396   fragp->fr_var = 0;
10397   new_logical_line (file_name, line);
10398 }
10399
10400
10401 static void
10402 convert_frag_align_next_opcode (fragS *fragp)
10403 {
10404   char *nop_buf;                /* Location for Writing.  */
10405   bfd_boolean use_no_density = fragp->tc_frag_data.is_no_density;
10406   addressT aligned_address;
10407   offsetT fill_size;
10408   int nop, nop_count;
10409
10410   aligned_address = get_noop_aligned_address (fragp, fragp->fr_address +
10411                                               fragp->fr_fix);
10412   fill_size = aligned_address - (fragp->fr_address + fragp->fr_fix);
10413   nop_count = get_text_align_nop_count (fill_size, use_no_density);
10414   nop_buf = fragp->fr_literal + fragp->fr_fix;
10415
10416   for (nop = 0; nop < nop_count; nop++)
10417     {
10418       int nop_size;
10419       nop_size = get_text_align_nth_nop_size (fill_size, nop, use_no_density);
10420
10421       assemble_nop (nop_size, nop_buf);
10422       nop_buf += nop_size;
10423     }
10424
10425   fragp->fr_fix += fill_size;
10426   fragp->fr_var -= fill_size;
10427 }
10428
10429
10430 static void
10431 convert_frag_narrow (segT segP, fragS *fragP, xtensa_format fmt, int slot)
10432 {
10433   TInsn tinsn, single_target;
10434   int size, old_size, diff;
10435   offsetT frag_offset;
10436
10437   gas_assert (slot == 0);
10438   tinsn_from_chars (&tinsn, fragP->fr_opcode, 0);
10439
10440   if (fragP->tc_frag_data.is_aligning_branch == 1)
10441     {
10442       gas_assert (fragP->tc_frag_data.text_expansion[0] == 1
10443               || fragP->tc_frag_data.text_expansion[0] == 0);
10444       convert_frag_immed (segP, fragP, fragP->tc_frag_data.text_expansion[0],
10445                           fmt, slot);
10446       return;
10447     }
10448
10449   if (fragP->tc_frag_data.text_expansion[0] == 0)
10450     {
10451       /* No conversion.  */
10452       fragP->fr_var = 0;
10453       return;
10454     }
10455
10456   gas_assert (fragP->fr_opcode != NULL);
10457
10458   /* Frags in this relaxation state should only contain
10459      single instruction bundles.  */
10460   tinsn_immed_from_frag (&tinsn, fragP, 0);
10461
10462   /* Just convert it to a wide form....  */
10463   size = 0;
10464   old_size = xg_get_single_size (tinsn.opcode);
10465
10466   tinsn_init (&single_target);
10467   frag_offset = fragP->fr_opcode - fragP->fr_literal;
10468
10469   if (! xg_is_single_relaxable_insn (&tinsn, &single_target, FALSE))
10470     {
10471       as_bad (_("unable to widen instruction"));
10472       return;
10473     }
10474
10475   size = xg_get_single_size (single_target.opcode);
10476   xg_emit_insn_to_buf (&single_target, fragP->fr_opcode, fragP,
10477                        frag_offset, TRUE);
10478
10479   diff = size - old_size;
10480   gas_assert (diff >= 0);
10481   gas_assert (diff <= fragP->fr_var);
10482   fragP->fr_var -= diff;
10483   fragP->fr_fix += diff;
10484
10485   /* clean it up */
10486   fragP->fr_var = 0;
10487 }
10488
10489
10490 static void
10491 convert_frag_fill_nop (fragS *fragP)
10492 {
10493   char *loc = &fragP->fr_literal[fragP->fr_fix];
10494   int size = fragP->tc_frag_data.text_expansion[0];
10495   gas_assert ((unsigned) size == (fragP->fr_next->fr_address
10496                               - fragP->fr_address - fragP->fr_fix));
10497   if (size == 0)
10498     {
10499       /* No conversion.  */
10500       fragP->fr_var = 0;
10501       return;
10502     }
10503   assemble_nop (size, loc);
10504   fragP->tc_frag_data.is_insn = TRUE;
10505   fragP->fr_var -= size;
10506   fragP->fr_fix += size;
10507   frag_wane (fragP);
10508 }
10509
10510
10511 static fixS *fix_new_exp_in_seg
10512   (segT, subsegT, fragS *, int, int, expressionS *, int,
10513    bfd_reloc_code_real_type);
10514 static void convert_frag_immed_finish_loop (segT, fragS *, TInsn *);
10515
10516 static void
10517 convert_frag_immed (segT segP,
10518                     fragS *fragP,
10519                     int min_steps,
10520                     xtensa_format fmt,
10521                     int slot)
10522 {
10523   char *immed_instr = fragP->fr_opcode;
10524   TInsn orig_tinsn;
10525   bfd_boolean expanded = FALSE;
10526   bfd_boolean branch_jmp_to_next = FALSE;
10527   char *fr_opcode = fragP->fr_opcode;
10528   xtensa_isa isa = xtensa_default_isa;
10529   bfd_boolean from_wide_insn = FALSE;
10530   int bytes;
10531   bfd_boolean is_loop;
10532
10533   gas_assert (fr_opcode != NULL);
10534
10535   xg_clear_vinsn (&cur_vinsn);
10536
10537   vinsn_from_chars (&cur_vinsn, fr_opcode);
10538   if (cur_vinsn.num_slots > 1)
10539     from_wide_insn = TRUE;
10540
10541   orig_tinsn = cur_vinsn.slots[slot];
10542   tinsn_immed_from_frag (&orig_tinsn, fragP, slot);
10543
10544   is_loop = xtensa_opcode_is_loop (xtensa_default_isa, orig_tinsn.opcode) == 1;
10545
10546   if (workaround_b_j_loop_end && ! fragP->tc_frag_data.is_no_transform)
10547     branch_jmp_to_next = is_branch_jmp_to_next (&orig_tinsn, fragP);
10548
10549   if (branch_jmp_to_next && !next_frag_is_loop_target (fragP))
10550     {
10551       /* Conversion just inserts a NOP and marks the fix as completed.  */
10552       bytes = xtensa_format_length (isa, fmt);
10553       if (bytes >= 4)
10554         {
10555           cur_vinsn.slots[slot].opcode =
10556             xtensa_format_slot_nop_opcode (isa, cur_vinsn.format, slot);
10557           cur_vinsn.slots[slot].ntok = 0;
10558         }
10559       else
10560         {
10561           bytes += fragP->tc_frag_data.text_expansion[0];
10562           gas_assert (bytes == 2 || bytes == 3);
10563           build_nop (&cur_vinsn.slots[0], bytes);
10564           fragP->fr_fix += fragP->tc_frag_data.text_expansion[0];
10565         }
10566       vinsn_to_insnbuf (&cur_vinsn, fr_opcode, frag_now, TRUE);
10567       xtensa_insnbuf_to_chars
10568         (isa, cur_vinsn.insnbuf, (unsigned char *) fr_opcode, 0);
10569       fragP->fr_var = 0;
10570     }
10571   else
10572     {
10573       /* Here is the fun stuff:  Get the immediate field from this
10574          instruction.  If it fits, we're done.  If not, find the next
10575          instruction sequence that fits.  */
10576
10577       IStack istack;
10578       int i;
10579       symbolS *lit_sym = NULL;
10580       int total_size = 0;
10581       int target_offset = 0;
10582       int old_size;
10583       int diff;
10584       symbolS *gen_label = NULL;
10585       offsetT frag_offset;
10586       bfd_boolean first = TRUE;
10587
10588       /* It does not fit.  Find something that does and
10589          convert immediately.  */
10590       frag_offset = fr_opcode - fragP->fr_literal;
10591       istack_init (&istack);
10592       xg_assembly_relax (&istack, &orig_tinsn,
10593                          segP, fragP, frag_offset, min_steps, 0);
10594
10595       old_size = xtensa_format_length (isa, fmt);
10596
10597       /* Assemble this right inline.  */
10598
10599       /* First, create the mapping from a label name to the REAL label.  */
10600       target_offset = 0;
10601       for (i = 0; i < istack.ninsn; i++)
10602         {
10603           TInsn *tinsn = &istack.insn[i];
10604           fragS *lit_frag;
10605
10606           switch (tinsn->insn_type)
10607             {
10608             case ITYPE_LITERAL:
10609               if (lit_sym != NULL)
10610                 as_bad (_("multiple literals in expansion"));
10611               /* First find the appropriate space in the literal pool.  */
10612               lit_frag = fragP->tc_frag_data.literal_frags[slot];
10613               if (lit_frag == NULL)
10614                 as_bad (_("no registered fragment for literal"));
10615               if (tinsn->ntok != 1)
10616                 as_bad (_("number of literal tokens != 1"));
10617
10618               /* Set the literal symbol and add a fixup.  */
10619               lit_sym = lit_frag->fr_symbol;
10620               break;
10621
10622             case ITYPE_LABEL:
10623               if (align_targets && !is_loop)
10624                 {
10625                   fragS *unreach = fragP->fr_next;
10626                   while (!(unreach->fr_type == rs_machine_dependent
10627                            && (unreach->fr_subtype == RELAX_MAYBE_UNREACHABLE
10628                                || unreach->fr_subtype == RELAX_UNREACHABLE)))
10629                     {
10630                       unreach = unreach->fr_next;
10631                     }
10632
10633                   gas_assert (unreach->fr_type == rs_machine_dependent
10634                           && (unreach->fr_subtype == RELAX_MAYBE_UNREACHABLE
10635                               || unreach->fr_subtype == RELAX_UNREACHABLE));
10636
10637                   target_offset += unreach->tc_frag_data.text_expansion[0];
10638                 }
10639               gas_assert (gen_label == NULL);
10640               gen_label = symbol_new (FAKE_LABEL_NAME, now_seg,
10641                                       fr_opcode - fragP->fr_literal
10642                                       + target_offset, fragP);
10643               break;
10644
10645             case ITYPE_INSN:
10646               if (first && from_wide_insn)
10647                 {
10648                   target_offset += xtensa_format_length (isa, fmt);
10649                   first = FALSE;
10650                   if (!opcode_fits_format_slot (tinsn->opcode, fmt, slot))
10651                     target_offset += xg_get_single_size (tinsn->opcode);
10652                 }
10653               else
10654                 target_offset += xg_get_single_size (tinsn->opcode);
10655               break;
10656             }
10657         }
10658
10659       total_size = 0;
10660       first = TRUE;
10661       for (i = 0; i < istack.ninsn; i++)
10662         {
10663           TInsn *tinsn = &istack.insn[i];
10664           fragS *lit_frag;
10665           int size;
10666           segT target_seg;
10667           bfd_reloc_code_real_type reloc_type;
10668
10669           switch (tinsn->insn_type)
10670             {
10671             case ITYPE_LITERAL:
10672               lit_frag = fragP->tc_frag_data.literal_frags[slot];
10673               /* Already checked.  */
10674               gas_assert (lit_frag != NULL);
10675               gas_assert (lit_sym != NULL);
10676               gas_assert (tinsn->ntok == 1);
10677               /* Add a fixup.  */
10678               target_seg = S_GET_SEGMENT (lit_sym);
10679               gas_assert (target_seg);
10680               reloc_type = map_operator_to_reloc (tinsn->tok[0].X_op, TRUE);
10681               fix_new_exp_in_seg (target_seg, 0, lit_frag, 0, 4,
10682                                   &tinsn->tok[0], FALSE, reloc_type);
10683               break;
10684
10685             case ITYPE_LABEL:
10686               break;
10687
10688             case ITYPE_INSN:
10689               xg_resolve_labels (tinsn, gen_label);
10690               xg_resolve_literals (tinsn, lit_sym);
10691               if (from_wide_insn && first)
10692                 {
10693                   first = FALSE;
10694                   if (opcode_fits_format_slot (tinsn->opcode, fmt, slot))
10695                     {
10696                       cur_vinsn.slots[slot] = *tinsn;
10697                     }
10698                   else
10699                     {
10700                       cur_vinsn.slots[slot].opcode =
10701                         xtensa_format_slot_nop_opcode (isa, fmt, slot);
10702                       cur_vinsn.slots[slot].ntok = 0;
10703                     }
10704                   vinsn_to_insnbuf (&cur_vinsn, immed_instr, fragP, TRUE);
10705                   xtensa_insnbuf_to_chars (isa, cur_vinsn.insnbuf,
10706                                            (unsigned char *) immed_instr, 0);
10707                   fragP->tc_frag_data.is_insn = TRUE;
10708                   size = xtensa_format_length (isa, fmt);
10709                   if (!opcode_fits_format_slot (tinsn->opcode, fmt, slot))
10710                     {
10711                       xg_emit_insn_to_buf
10712                         (tinsn, immed_instr + size, fragP,
10713                          immed_instr - fragP->fr_literal + size, TRUE);
10714                       size += xg_get_single_size (tinsn->opcode);
10715                     }
10716                 }
10717               else
10718                 {
10719                   size = xg_get_single_size (tinsn->opcode);
10720                   xg_emit_insn_to_buf (tinsn, immed_instr, fragP,
10721                                        immed_instr - fragP->fr_literal, TRUE);
10722                 }
10723               immed_instr += size;
10724               total_size += size;
10725               break;
10726             }
10727         }
10728
10729       diff = total_size - old_size;
10730       gas_assert (diff >= 0);
10731       if (diff != 0)
10732         expanded = TRUE;
10733       gas_assert (diff <= fragP->fr_var);
10734       fragP->fr_var -= diff;
10735       fragP->fr_fix += diff;
10736     }
10737
10738   /* Check for undefined immediates in LOOP instructions.  */
10739   if (is_loop)
10740     {
10741       symbolS *sym;
10742       sym = orig_tinsn.tok[1].X_add_symbol;
10743       if (sym != NULL && !S_IS_DEFINED (sym))
10744         {
10745           as_bad (_("unresolved loop target symbol: %s"), S_GET_NAME (sym));
10746           return;
10747         }
10748       sym = orig_tinsn.tok[1].X_op_symbol;
10749       if (sym != NULL && !S_IS_DEFINED (sym))
10750         {
10751           as_bad (_("unresolved loop target symbol: %s"), S_GET_NAME (sym));
10752           return;
10753         }
10754     }
10755
10756   if (expanded && xtensa_opcode_is_loop (isa, orig_tinsn.opcode) == 1)
10757     convert_frag_immed_finish_loop (segP, fragP, &orig_tinsn);
10758
10759   if (expanded && is_direct_call_opcode (orig_tinsn.opcode))
10760     {
10761       /* Add an expansion note on the expanded instruction.  */
10762       fix_new_exp_in_seg (now_seg, 0, fragP, fr_opcode - fragP->fr_literal, 4,
10763                           &orig_tinsn.tok[0], TRUE,
10764                           BFD_RELOC_XTENSA_ASM_EXPAND);
10765     }
10766 }
10767
10768
10769 /* Add a new fix expression into the desired segment.  We have to
10770    switch to that segment to do this.  */
10771
10772 static fixS *
10773 fix_new_exp_in_seg (segT new_seg,
10774                     subsegT new_subseg,
10775                     fragS *frag,
10776                     int where,
10777                     int size,
10778                     expressionS *exp,
10779                     int pcrel,
10780                     bfd_reloc_code_real_type r_type)
10781 {
10782   fixS *new_fix;
10783   segT seg = now_seg;
10784   subsegT subseg = now_subseg;
10785
10786   gas_assert (new_seg != 0);
10787   subseg_set (new_seg, new_subseg);
10788
10789   new_fix = fix_new_exp (frag, where, size, exp, pcrel, r_type);
10790   subseg_set (seg, subseg);
10791   return new_fix;
10792 }
10793
10794
10795 /* Relax a loop instruction so that it can span loop >256 bytes.
10796
10797                   loop    as, .L1
10798           .L0:
10799                   rsr     as, LEND
10800                   wsr     as, LBEG
10801                   addi    as, as, lo8 (label-.L1)
10802                   addmi   as, as, mid8 (label-.L1)
10803                   wsr     as, LEND
10804                   isync
10805                   rsr     as, LCOUNT
10806                   addi    as, as, 1
10807           .L1:
10808                   <<body>>
10809           label:
10810 */
10811
10812 static void
10813 convert_frag_immed_finish_loop (segT segP, fragS *fragP, TInsn *tinsn)
10814 {
10815   TInsn loop_insn;
10816   TInsn addi_insn;
10817   TInsn addmi_insn;
10818   unsigned long target;
10819   static xtensa_insnbuf insnbuf = NULL;
10820   unsigned int loop_length, loop_length_hi, loop_length_lo;
10821   xtensa_isa isa = xtensa_default_isa;
10822   addressT loop_offset;
10823   addressT addi_offset = 9;
10824   addressT addmi_offset = 12;
10825   fragS *next_fragP;
10826   int target_count;
10827
10828   if (!insnbuf)
10829     insnbuf = xtensa_insnbuf_alloc (isa);
10830
10831   /* Get the loop offset.  */
10832   loop_offset = get_expanded_loop_offset (tinsn->opcode);
10833
10834   /* Validate that there really is a LOOP at the loop_offset.  Because
10835      loops are not bundleable, we can assume that the instruction will be
10836      in slot 0.  */
10837   tinsn_from_chars (&loop_insn, fragP->fr_opcode + loop_offset, 0);
10838   tinsn_immed_from_frag (&loop_insn, fragP, 0);
10839
10840   gas_assert (xtensa_opcode_is_loop (isa, loop_insn.opcode) == 1);
10841   addi_offset += loop_offset;
10842   addmi_offset += loop_offset;
10843
10844   gas_assert (tinsn->ntok == 2);
10845   if (tinsn->tok[1].X_op == O_constant)
10846     target = tinsn->tok[1].X_add_number;
10847   else if (tinsn->tok[1].X_op == O_symbol)
10848     {
10849       /* Find the fragment.  */
10850       symbolS *sym = tinsn->tok[1].X_add_symbol;
10851       gas_assert (S_GET_SEGMENT (sym) == segP
10852               || S_GET_SEGMENT (sym) == absolute_section);
10853       target = (S_GET_VALUE (sym) + tinsn->tok[1].X_add_number);
10854     }
10855   else
10856     {
10857       as_bad (_("invalid expression evaluation type %d"), tinsn->tok[1].X_op);
10858       target = 0;
10859     }
10860
10861   loop_length = target - (fragP->fr_address + fragP->fr_fix);
10862   loop_length_hi = loop_length & ~0x0ff;
10863   loop_length_lo = loop_length & 0x0ff;
10864   if (loop_length_lo >= 128)
10865     {
10866       loop_length_lo -= 256;
10867       loop_length_hi += 256;
10868     }
10869
10870   /* Because addmi sign-extends the immediate, 'loop_length_hi' can be at most
10871      32512.  If the loop is larger than that, then we just fail.  */
10872   if (loop_length_hi > 32512)
10873     as_bad_where (fragP->fr_file, fragP->fr_line,
10874                   _("loop too long for LOOP instruction"));
10875
10876   tinsn_from_chars (&addi_insn, fragP->fr_opcode + addi_offset, 0);
10877   gas_assert (addi_insn.opcode == xtensa_addi_opcode);
10878
10879   tinsn_from_chars (&addmi_insn, fragP->fr_opcode + addmi_offset, 0);
10880   gas_assert (addmi_insn.opcode == xtensa_addmi_opcode);
10881
10882   set_expr_const (&addi_insn.tok[2], loop_length_lo);
10883   tinsn_to_insnbuf (&addi_insn, insnbuf);
10884
10885   fragP->tc_frag_data.is_insn = TRUE;
10886   xtensa_insnbuf_to_chars
10887     (isa, insnbuf, (unsigned char *) fragP->fr_opcode + addi_offset, 0);
10888
10889   set_expr_const (&addmi_insn.tok[2], loop_length_hi);
10890   tinsn_to_insnbuf (&addmi_insn, insnbuf);
10891   xtensa_insnbuf_to_chars
10892     (isa, insnbuf, (unsigned char *) fragP->fr_opcode + addmi_offset, 0);
10893
10894   /* Walk through all of the frags from here to the loop end
10895      and mark them as no_transform to keep them from being modified
10896      by the linker.  If we ever have a relocation for the
10897      addi/addmi of the difference of two symbols we can remove this.  */
10898
10899   target_count = 0;
10900   for (next_fragP = fragP; next_fragP != NULL;
10901        next_fragP = next_fragP->fr_next)
10902     {
10903       next_fragP->tc_frag_data.is_no_transform = TRUE;
10904       if (next_fragP->tc_frag_data.is_loop_target)
10905         target_count++;
10906       if (target_count == 2)
10907         break;
10908     }
10909 }
10910
10911 \f
10912 /* A map that keeps information on a per-subsegment basis.  This is
10913    maintained during initial assembly, but is invalid once the
10914    subsegments are smashed together.  I.E., it cannot be used during
10915    the relaxation.  */
10916
10917 typedef struct subseg_map_struct
10918 {
10919   /* the key */
10920   segT seg;
10921   subsegT subseg;
10922
10923   /* the data */
10924   unsigned flags;
10925   float total_freq;     /* fall-through + branch target frequency */
10926   float target_freq;    /* branch target frequency alone */
10927
10928   struct subseg_map_struct *next;
10929 } subseg_map;
10930
10931
10932 static subseg_map *sseg_map = NULL;
10933
10934 static subseg_map *
10935 get_subseg_info (segT seg, subsegT subseg)
10936 {
10937   subseg_map *subseg_e;
10938
10939   for (subseg_e = sseg_map; subseg_e; subseg_e = subseg_e->next)
10940     {
10941       if (seg == subseg_e->seg && subseg == subseg_e->subseg)
10942         break;
10943     }
10944   return subseg_e;
10945 }
10946
10947
10948 static subseg_map *
10949 add_subseg_info (segT seg, subsegT subseg)
10950 {
10951   subseg_map *subseg_e = (subseg_map *) xmalloc (sizeof (subseg_map));
10952   memset (subseg_e, 0, sizeof (subseg_map));
10953   subseg_e->seg = seg;
10954   subseg_e->subseg = subseg;
10955   subseg_e->flags = 0;
10956   /* Start off considering every branch target very important.  */
10957   subseg_e->target_freq = 1.0;
10958   subseg_e->total_freq = 1.0;
10959   subseg_e->next = sseg_map;
10960   sseg_map = subseg_e;
10961   return subseg_e;
10962 }
10963
10964
10965 static unsigned
10966 get_last_insn_flags (segT seg, subsegT subseg)
10967 {
10968   subseg_map *subseg_e = get_subseg_info (seg, subseg);
10969   if (subseg_e)
10970     return subseg_e->flags;
10971   return 0;
10972 }
10973
10974
10975 static void
10976 set_last_insn_flags (segT seg,
10977                      subsegT subseg,
10978                      unsigned fl,
10979                      bfd_boolean val)
10980 {
10981   subseg_map *subseg_e = get_subseg_info (seg, subseg);
10982   if (! subseg_e)
10983     subseg_e = add_subseg_info (seg, subseg);
10984   if (val)
10985     subseg_e->flags |= fl;
10986   else
10987     subseg_e->flags &= ~fl;
10988 }
10989
10990
10991 static float
10992 get_subseg_total_freq (segT seg, subsegT subseg)
10993 {
10994   subseg_map *subseg_e = get_subseg_info (seg, subseg);
10995   if (subseg_e)
10996     return subseg_e->total_freq;
10997   return 1.0;
10998 }
10999
11000
11001 static float
11002 get_subseg_target_freq (segT seg, subsegT subseg)
11003 {
11004   subseg_map *subseg_e = get_subseg_info (seg, subseg);
11005   if (subseg_e)
11006     return subseg_e->target_freq;
11007   return 1.0;
11008 }
11009
11010
11011 static void
11012 set_subseg_freq (segT seg, subsegT subseg, float total_f, float target_f)
11013 {
11014   subseg_map *subseg_e = get_subseg_info (seg, subseg);
11015   if (! subseg_e)
11016     subseg_e = add_subseg_info (seg, subseg);
11017   subseg_e->total_freq = total_f;
11018   subseg_e->target_freq = target_f;
11019 }
11020
11021 \f
11022 /* Segment Lists and emit_state Stuff.  */
11023
11024 static void
11025 xtensa_move_seg_list_to_beginning (seg_list *head)
11026 {
11027   head = head->next;
11028   while (head)
11029     {
11030       segT literal_section = head->seg;
11031
11032       /* Move the literal section to the front of the section list.  */
11033       gas_assert (literal_section);
11034       if (literal_section != stdoutput->sections)
11035         {
11036           bfd_section_list_remove (stdoutput, literal_section);
11037           bfd_section_list_prepend (stdoutput, literal_section);
11038         }
11039       head = head->next;
11040     }
11041 }
11042
11043
11044 static void mark_literal_frags (seg_list *);
11045
11046 static void
11047 xtensa_move_literals (void)
11048 {
11049   seg_list *segment;
11050   frchainS *frchain_from, *frchain_to;
11051   fragS *search_frag, *next_frag, *literal_pool, *insert_after;
11052   fragS **frag_splice;
11053   emit_state state;
11054   segT dest_seg;
11055   fixS *fix, *next_fix, **fix_splice;
11056   sym_list *lit;
11057   struct litpool_seg *lps;
11058   const char *init_name = INIT_SECTION_NAME;
11059   const char *fini_name = FINI_SECTION_NAME;
11060   int init_name_len = strlen(init_name);
11061   int fini_name_len = strlen(fini_name);
11062
11063   mark_literal_frags (literal_head->next);
11064
11065   if (use_literal_section)
11066     return;
11067
11068   /* Assign addresses (rough estimates) to the potential literal pool locations
11069      and create new ones if the gaps are too large.  */
11070
11071   for (lps = litpool_seg_list.next; lps; lps = lps->next)
11072     {
11073       frchainS *frchP = seg_info (lps->seg)->frchainP;
11074       struct litpool_frag *lpf = lps->frag_list.next;
11075       addressT addr = 0;
11076
11077       for ( ; frchP; frchP = frchP->frch_next)
11078         {
11079           fragS *fragP;
11080           for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
11081             {
11082               if (lpf && fragP == lpf->fragP)
11083                 {
11084                   gas_assert(fragP->fr_type == rs_machine_dependent &&
11085                              (fragP->fr_subtype == RELAX_LITERAL_POOL_BEGIN ||
11086                               fragP->fr_subtype == RELAX_LITERAL_POOL_CANDIDATE_BEGIN));
11087                   /* Found a litpool location.  */
11088                   lpf->addr = addr;
11089                   lpf = lpf->next;
11090                 }
11091               if (fragP->fr_type == rs_machine_dependent &&
11092                   fragP->fr_subtype == RELAX_SLOTS)
11093                 {
11094                   int slot;
11095                   for (slot = 0; slot < MAX_SLOTS; slot++)
11096                     {
11097                       if (fragP->tc_frag_data.literal_frags[slot])
11098                         {
11099                           /* L32R; point its literal to the nearest litpool
11100                              preferring non-"candidate" positions to avoid
11101                              the jump-around.  */
11102                           fragS *litfrag = fragP->tc_frag_data.literal_frags[slot];
11103                           struct litpool_frag *lp = lpf->prev;
11104                           if (!lp->fragP)
11105                             {
11106                               break;
11107                             }
11108                           while (lp->fragP->fr_subtype ==
11109                                  RELAX_LITERAL_POOL_CANDIDATE_BEGIN)
11110                             {
11111                               lp = lp->prev;
11112                               if (lp->fragP == NULL)
11113                                 {
11114                                   /* End of list; have to bite the bullet.
11115                                      Take the nearest.  */
11116                                   lp = lpf->prev;
11117                                   break;
11118                                 }
11119                               /* Does it (conservatively) reach?  */
11120                               if (addr - lp->addr <= 128 * 1024)
11121                                 {
11122                                   if (lp->fragP->fr_subtype == RELAX_LITERAL_POOL_BEGIN)
11123                                     {
11124                                       /* Found a good one.  */
11125                                       break;
11126                                     }
11127                                   else if (lp->prev->fragP &&
11128                                            addr - lp->prev->addr > 128 * 1024)
11129                                     {
11130                                       /* This is still a "candidate" but the next one
11131                                          will be too far away, so revert to the nearest
11132                                          one, convert it and add the jump around.  */
11133                                       fragS *poolbeg;
11134                                       fragS *poolend;
11135                                       symbolS *lsym;
11136                                       char label[10 + 2 * sizeof (fragS *)];
11137                                       lp = lpf->prev;
11138                                       poolbeg = lp->fragP;
11139                                       lp->priority = 1;
11140                                       poolbeg->fr_subtype = RELAX_LITERAL_POOL_BEGIN;
11141                                       poolend = poolbeg->fr_next;
11142                                       gas_assert (poolend->fr_type == rs_machine_dependent &&
11143                                                   poolend->fr_subtype == RELAX_LITERAL_POOL_END);
11144                                       /* Create a local symbol pointing to the
11145                                          end of the pool.  */
11146                                       sprintf (label, ".L0_LT_%p", poolbeg);
11147                                       lsym = (symbolS *)local_symbol_make (label, lps->seg,
11148                                                                            0, poolend);
11149                                       poolbeg->fr_symbol = lsym;
11150                                       /* Rest is done in xtensa_relax_frag.  */
11151                                     }
11152                                 }
11153                             }
11154                           if (! litfrag->tc_frag_data.literal_frag)
11155                             {
11156                               /* Take earliest use of this literal to avoid
11157                                  forward refs.  */
11158                               litfrag->tc_frag_data.literal_frag = lp->fragP;
11159                             }
11160                         }
11161                     }
11162                 }
11163               addr += fragP->fr_fix;
11164               if (fragP->fr_type == rs_fill)
11165                 addr += fragP->fr_offset;
11166             }
11167         }
11168     }
11169
11170   for (segment = literal_head->next; segment; segment = segment->next)
11171     {
11172       const char *seg_name = segment_name (segment->seg);
11173
11174       /* Keep the literals for .init and .fini in separate sections.  */
11175       if ((!memcmp (seg_name, init_name, init_name_len) &&
11176            !strcmp (seg_name + init_name_len, ".literal")) ||
11177           (!memcmp (seg_name, fini_name, fini_name_len) &&
11178            !strcmp (seg_name + fini_name_len, ".literal")))
11179         continue;
11180
11181       frchain_from = seg_info (segment->seg)->frchainP;
11182       search_frag = frchain_from->frch_root;
11183       literal_pool = NULL;
11184       frchain_to = NULL;
11185       frag_splice = &(frchain_from->frch_root);
11186
11187       while (search_frag && !search_frag->tc_frag_data.literal_frag)
11188         {
11189           gas_assert (search_frag->fr_fix == 0
11190                   || search_frag->fr_type == rs_align);
11191           search_frag = search_frag->fr_next;
11192         }
11193
11194       if (!search_frag)
11195         {
11196           search_frag = frchain_from->frch_root;
11197           as_bad_where (search_frag->fr_file, search_frag->fr_line,
11198                         _("literal pool location required for text-section-literals; specify with .literal_position"));
11199           continue;
11200         }
11201
11202       gas_assert (search_frag->tc_frag_data.literal_frag->fr_subtype
11203               == RELAX_LITERAL_POOL_BEGIN);
11204       xtensa_switch_section_emit_state (&state, segment->seg, 0);
11205
11206       /* Make sure that all the frags in this series are closed, and
11207          that there is at least one left over of zero-size.  This
11208          prevents us from making a segment with an frchain without any
11209          frags in it.  */
11210       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
11211       xtensa_set_frag_assembly_state (frag_now);
11212       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
11213       xtensa_set_frag_assembly_state (frag_now);
11214
11215       while (search_frag != frag_now)
11216         {
11217           next_frag = search_frag->fr_next;
11218           if (search_frag->tc_frag_data.literal_frag)
11219             {
11220               literal_pool = search_frag->tc_frag_data.literal_frag;
11221               gas_assert (literal_pool->fr_subtype == RELAX_LITERAL_POOL_BEGIN);
11222               frchain_to = literal_pool->tc_frag_data.lit_frchain;
11223               gas_assert (frchain_to);
11224             }
11225
11226           if (search_frag->fr_type == rs_fill && search_frag->fr_fix == 0)
11227             {
11228               /* Skip empty fill frags.  */
11229               *frag_splice = next_frag;
11230               search_frag = next_frag;
11231               continue;
11232             }
11233
11234           if (search_frag->fr_type == rs_align)
11235             {
11236               /* Skip alignment frags, because the pool as a whole will be
11237                  aligned if used, and we don't want to force alignment if the
11238                  pool is unused.  */
11239               *frag_splice = next_frag;
11240               search_frag = next_frag;
11241               continue;
11242             }
11243
11244           /* First, move the frag out of the literal section and
11245              to the appropriate place.  */
11246
11247           /* Insert an aligmnent frag at start of pool.  */
11248           if (literal_pool->fr_next->fr_type == rs_machine_dependent &&
11249               literal_pool->fr_next->fr_subtype == RELAX_LITERAL_POOL_END)
11250             {
11251               segT pool_seg = literal_pool->fr_next->tc_frag_data.lit_seg;
11252               emit_state prev_state;
11253               fragS *prev_frag;
11254               fragS *align_frag;
11255               xtensa_switch_section_emit_state (&prev_state, pool_seg, 0);
11256               prev_frag = frag_now;
11257               frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
11258               align_frag = frag_now;
11259               frag_align (2, 0, 0);
11260               /* Splice it into the right place.  */
11261               prev_frag->fr_next = align_frag->fr_next;
11262               align_frag->fr_next = literal_pool->fr_next;
11263               literal_pool->fr_next = align_frag;
11264               /* Insert after this one.  */
11265               literal_pool->tc_frag_data.literal_frag = align_frag;
11266               xtensa_restore_emit_state (&prev_state);
11267             }
11268           insert_after = literal_pool->tc_frag_data.literal_frag;
11269           dest_seg = insert_after->fr_next->tc_frag_data.lit_seg;
11270           /* Skip align frag.  */
11271           if (insert_after->fr_next->fr_type == rs_align)
11272             {
11273               insert_after = insert_after->fr_next;
11274             }
11275
11276           *frag_splice = next_frag;
11277           search_frag->fr_next = insert_after->fr_next;
11278           insert_after->fr_next = search_frag;
11279           search_frag->tc_frag_data.lit_seg = dest_seg;
11280           literal_pool->tc_frag_data.literal_frag = search_frag;
11281
11282           /* Now move any fixups associated with this frag to the
11283              right section.  */
11284           fix = frchain_from->fix_root;
11285           fix_splice = &(frchain_from->fix_root);
11286           while (fix)
11287             {
11288               next_fix = fix->fx_next;
11289               if (fix->fx_frag == search_frag)
11290                 {
11291                   *fix_splice = next_fix;
11292                   fix->fx_next = frchain_to->fix_root;
11293                   frchain_to->fix_root = fix;
11294                   if (frchain_to->fix_tail == NULL)
11295                     frchain_to->fix_tail = fix;
11296                 }
11297               else
11298                 fix_splice = &(fix->fx_next);
11299               fix = next_fix;
11300             }
11301           search_frag = next_frag;
11302         }
11303
11304       if (frchain_from->fix_root != NULL)
11305         {
11306           frchain_from = seg_info (segment->seg)->frchainP;
11307           as_warn (_("fixes not all moved from %s"), segment->seg->name);
11308
11309           gas_assert (frchain_from->fix_root == NULL);
11310         }
11311       frchain_from->fix_tail = NULL;
11312       xtensa_restore_emit_state (&state);
11313     }
11314
11315   /* Now fix up the SEGMENT value for all the literal symbols.  */
11316   for (lit = literal_syms; lit; lit = lit->next)
11317     {
11318       symbolS *lit_sym = lit->sym;
11319       segT dseg = symbol_get_frag (lit_sym)->tc_frag_data.lit_seg;
11320       if (dseg)
11321         S_SET_SEGMENT (lit_sym, dseg);
11322     }
11323 }
11324
11325
11326 /* Walk over all the frags for segments in a list and mark them as
11327    containing literals.  As clunky as this is, we can't rely on frag_var
11328    and frag_variant to get called in all situations.  */
11329
11330 static void
11331 mark_literal_frags (seg_list *segment)
11332 {
11333   frchainS *frchain_from;
11334   fragS *search_frag;
11335
11336   while (segment)
11337     {
11338       frchain_from = seg_info (segment->seg)->frchainP;
11339       search_frag = frchain_from->frch_root;
11340       while (search_frag)
11341         {
11342           search_frag->tc_frag_data.is_literal = TRUE;
11343           search_frag = search_frag->fr_next;
11344         }
11345       segment = segment->next;
11346     }
11347 }
11348
11349
11350 static void
11351 xtensa_reorder_seg_list (seg_list *head, segT after)
11352 {
11353   /* Move all of the sections in the section list to come
11354      after "after" in the gnu segment list.  */
11355
11356   head = head->next;
11357   while (head)
11358     {
11359       segT literal_section = head->seg;
11360
11361       /* Move the literal section after "after".  */
11362       gas_assert (literal_section);
11363       if (literal_section != after)
11364         {
11365           bfd_section_list_remove (stdoutput, literal_section);
11366           bfd_section_list_insert_after (stdoutput, after, literal_section);
11367         }
11368
11369       head = head->next;
11370     }
11371 }
11372
11373
11374 /* Push all the literal segments to the end of the gnu list.  */
11375
11376 static void
11377 xtensa_reorder_segments (void)
11378 {
11379   segT sec;
11380   segT last_sec = 0;
11381   int old_count = 0;
11382   int new_count = 0;
11383
11384   for (sec = stdoutput->sections; sec != NULL; sec = sec->next)
11385     {
11386       last_sec = sec;
11387       old_count++;
11388     }
11389
11390   /* Now that we have the last section, push all the literal
11391      sections to the end.  */
11392   xtensa_reorder_seg_list (literal_head, last_sec);
11393
11394   /* Now perform the final error check.  */
11395   for (sec = stdoutput->sections; sec != NULL; sec = sec->next)
11396     new_count++;
11397   gas_assert (new_count == old_count);
11398 }
11399
11400
11401 /* Change the emit state (seg, subseg, and frag related stuff) to the
11402    correct location.  Return a emit_state which can be passed to
11403    xtensa_restore_emit_state to return to current fragment.  */
11404
11405 static void
11406 xtensa_switch_to_literal_fragment (emit_state *result)
11407 {
11408   if (directive_state[directive_absolute_literals])
11409     {
11410       segT lit4_seg = cache_literal_section (TRUE);
11411       xtensa_switch_section_emit_state (result, lit4_seg, 0);
11412     }
11413   else
11414     xtensa_switch_to_non_abs_literal_fragment (result);
11415
11416   /* Do a 4-byte align here.  */
11417   frag_align (2, 0, 0);
11418   record_alignment (now_seg, 2);
11419 }
11420
11421
11422 static void
11423 xtensa_switch_to_non_abs_literal_fragment (emit_state *result)
11424 {
11425   static bfd_boolean recursive = FALSE;
11426   fragS *pool_location = get_literal_pool_location (now_seg);
11427   segT lit_seg;
11428   bfd_boolean is_init =
11429     (now_seg && !strcmp (segment_name (now_seg), INIT_SECTION_NAME));
11430   bfd_boolean is_fini =
11431     (now_seg && !strcmp (segment_name (now_seg), FINI_SECTION_NAME));
11432
11433   if (pool_location == NULL
11434       && !use_literal_section
11435       && !recursive
11436       && !is_init && ! is_fini)
11437     {
11438       if (!auto_litpools)
11439         {
11440           as_bad (_("literal pool location required for text-section-literals; specify with .literal_position"));
11441         }
11442
11443       /* When we mark a literal pool location, we want to put a frag in
11444          the literal pool that points to it.  But to do that, we want to
11445          switch_to_literal_fragment.  But literal sections don't have
11446          literal pools, so their location is always null, so we would
11447          recurse forever.  This is kind of hacky, but it works.  */
11448
11449       recursive = TRUE;
11450       xtensa_mark_literal_pool_location ();
11451       recursive = FALSE;
11452     }
11453
11454   lit_seg = cache_literal_section (FALSE);
11455   xtensa_switch_section_emit_state (result, lit_seg, 0);
11456
11457   if (!use_literal_section
11458       && !is_init && !is_fini
11459       && get_literal_pool_location (now_seg) != pool_location)
11460     {
11461       /* Close whatever frag is there.  */
11462       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
11463       xtensa_set_frag_assembly_state (frag_now);
11464       frag_now->tc_frag_data.literal_frag = pool_location;
11465       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
11466       xtensa_set_frag_assembly_state (frag_now);
11467     }
11468 }
11469
11470
11471 /* Call this function before emitting data into the literal section.
11472    This is a helper function for xtensa_switch_to_literal_fragment.
11473    This is similar to a .section new_now_seg subseg. */
11474
11475 static void
11476 xtensa_switch_section_emit_state (emit_state *state,
11477                                   segT new_now_seg,
11478                                   subsegT new_now_subseg)
11479 {
11480   state->name = now_seg->name;
11481   state->now_seg = now_seg;
11482   state->now_subseg = now_subseg;
11483   state->generating_literals = generating_literals;
11484   generating_literals++;
11485   subseg_set (new_now_seg, new_now_subseg);
11486 }
11487
11488
11489 /* Use to restore the emitting into the normal place.  */
11490
11491 static void
11492 xtensa_restore_emit_state (emit_state *state)
11493 {
11494   generating_literals = state->generating_literals;
11495   subseg_set (state->now_seg, state->now_subseg);
11496 }
11497
11498
11499 /* Predicate function used to look up a section in a particular group.  */
11500
11501 static bfd_boolean
11502 match_section_group (bfd *abfd ATTRIBUTE_UNUSED, asection *sec, void *inf)
11503 {
11504   const char *gname = inf;
11505   const char *group_name = elf_group_name (sec);
11506
11507   return (group_name == gname
11508           || (group_name != NULL
11509               && gname != NULL
11510               && strcmp (group_name, gname) == 0));
11511 }
11512
11513
11514 /* Get the literal section to be used for the current text section.
11515    The result may be cached in the default_lit_sections structure.  */
11516
11517 static segT
11518 cache_literal_section (bfd_boolean use_abs_literals)
11519 {
11520   const char *text_name, *group_name = 0;
11521   const char *base_name, *suffix;
11522   char *name;
11523   segT *pcached;
11524   segT seg, current_section;
11525   int current_subsec;
11526   bfd_boolean linkonce = FALSE;
11527
11528   /* Save the current section/subsection.  */
11529   current_section = now_seg;
11530   current_subsec = now_subseg;
11531
11532   /* Clear the cached values if they are no longer valid.  */
11533   if (now_seg != default_lit_sections.current_text_seg)
11534     {
11535       default_lit_sections.current_text_seg = now_seg;
11536       default_lit_sections.lit_seg = NULL;
11537       default_lit_sections.lit4_seg = NULL;
11538     }
11539
11540   /* Check if the literal section is already cached.  */
11541   if (use_abs_literals)
11542     pcached = &default_lit_sections.lit4_seg;
11543   else
11544     pcached = &default_lit_sections.lit_seg;
11545
11546   if (*pcached)
11547     return *pcached;
11548
11549   text_name = default_lit_sections.lit_prefix;
11550   if (! text_name || ! *text_name)
11551     {
11552       text_name = segment_name (current_section);
11553       group_name = elf_group_name (current_section);
11554       linkonce = (current_section->flags & SEC_LINK_ONCE) != 0;
11555     }
11556
11557   base_name = use_abs_literals ? ".lit4" : ".literal";
11558   if (group_name)
11559     {
11560       name = xmalloc (strlen (base_name) + strlen (group_name) + 2);
11561       sprintf (name, "%s.%s", base_name, group_name);
11562     }
11563   else if (strncmp (text_name, ".gnu.linkonce.", linkonce_len) == 0)
11564     {
11565       suffix = strchr (text_name + linkonce_len, '.');
11566
11567       name = xmalloc (linkonce_len + strlen (base_name) + 1
11568                       + (suffix ? strlen (suffix) : 0));
11569       strcpy (name, ".gnu.linkonce");
11570       strcat (name, base_name);
11571       if (suffix)
11572         strcat (name, suffix);
11573       linkonce = TRUE;
11574     }
11575   else
11576     {
11577       /* If the section name begins or ends with ".text", then replace
11578          that portion instead of appending an additional suffix.  */
11579       size_t len = strlen (text_name);
11580       if (len >= 5
11581           && (strcmp (text_name + len - 5, ".text") == 0
11582               || strncmp (text_name, ".text", 5) == 0))
11583         len -= 5;
11584
11585       name = xmalloc (len + strlen (base_name) + 1);
11586       if (strncmp (text_name, ".text", 5) == 0)
11587         {
11588           strcpy (name, base_name);
11589           strcat (name, text_name + 5);
11590         }
11591       else
11592         {
11593           strcpy (name, text_name);
11594           strcpy (name + len, base_name);
11595         }
11596     }
11597
11598   /* Canonicalize section names to allow renaming literal sections.
11599      The group name, if any, came from the current text section and
11600      has already been canonicalized.  */
11601   name = tc_canonicalize_symbol_name (name);
11602
11603   seg = bfd_get_section_by_name_if (stdoutput, name, match_section_group,
11604                                     (void *) group_name);
11605   if (! seg)
11606     {
11607       flagword flags;
11608
11609       seg = subseg_force_new (name, 0);
11610
11611       if (! use_abs_literals)
11612         {
11613           /* Add the newly created literal segment to the list.  */
11614           seg_list *n = (seg_list *) xmalloc (sizeof (seg_list));
11615           n->seg = seg;
11616           n->next = literal_head->next;
11617           literal_head->next = n;
11618         }
11619
11620       flags = (SEC_HAS_CONTENTS | SEC_READONLY | SEC_ALLOC | SEC_LOAD
11621                | (linkonce ? (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD) : 0)
11622                | (use_abs_literals ? SEC_DATA : SEC_CODE));
11623
11624       elf_group_name (seg) = group_name;
11625
11626       bfd_set_section_flags (stdoutput, seg, flags);
11627       bfd_set_section_alignment (stdoutput, seg, 2);
11628     }
11629
11630   *pcached = seg;
11631   subseg_set (current_section, current_subsec);
11632   return seg;
11633 }
11634
11635 \f
11636 /* Property Tables Stuff.  */
11637
11638 #define XTENSA_INSN_SEC_NAME ".xt.insn"
11639 #define XTENSA_LIT_SEC_NAME ".xt.lit"
11640 #define XTENSA_PROP_SEC_NAME ".xt.prop"
11641
11642 typedef bfd_boolean (*frag_predicate) (const fragS *);
11643 typedef void (*frag_flags_fn) (const fragS *, frag_flags *);
11644
11645 static bfd_boolean get_frag_is_literal (const fragS *);
11646 static void xtensa_create_property_segments
11647   (frag_predicate, frag_predicate, const char *, xt_section_type);
11648 static void xtensa_create_xproperty_segments
11649   (frag_flags_fn, const char *, xt_section_type);
11650 static bfd_boolean exclude_section_from_property_tables (segT);
11651 static bfd_boolean section_has_property (segT, frag_predicate);
11652 static bfd_boolean section_has_xproperty (segT, frag_flags_fn);
11653 static void add_xt_block_frags
11654   (segT, xtensa_block_info **, frag_predicate, frag_predicate);
11655 static bfd_boolean xtensa_frag_flags_is_empty (const frag_flags *);
11656 static void xtensa_frag_flags_init (frag_flags *);
11657 static void get_frag_property_flags (const fragS *, frag_flags *);
11658 static flagword frag_flags_to_number (const frag_flags *);
11659 static void add_xt_prop_frags (segT, xtensa_block_info **, frag_flags_fn);
11660
11661 /* Set up property tables after relaxation.  */
11662
11663 void
11664 xtensa_post_relax_hook (void)
11665 {
11666   xtensa_move_seg_list_to_beginning (literal_head);
11667
11668   xtensa_find_unmarked_state_frags ();
11669   xtensa_mark_frags_for_org ();
11670   xtensa_mark_difference_of_two_symbols ();
11671
11672   xtensa_create_property_segments (get_frag_is_literal,
11673                                    NULL,
11674                                    XTENSA_LIT_SEC_NAME,
11675                                    xt_literal_sec);
11676   xtensa_create_xproperty_segments (get_frag_property_flags,
11677                                     XTENSA_PROP_SEC_NAME,
11678                                     xt_prop_sec);
11679
11680   if (warn_unaligned_branch_targets)
11681     bfd_map_over_sections (stdoutput, xtensa_find_unaligned_branch_targets, 0);
11682   bfd_map_over_sections (stdoutput, xtensa_find_unaligned_loops, 0);
11683 }
11684
11685
11686 /* This function is only meaningful after xtensa_move_literals.  */
11687
11688 static bfd_boolean
11689 get_frag_is_literal (const fragS *fragP)
11690 {
11691   gas_assert (fragP != NULL);
11692   return fragP->tc_frag_data.is_literal;
11693 }
11694
11695
11696 static void
11697 xtensa_create_property_segments (frag_predicate property_function,
11698                                  frag_predicate end_property_function,
11699                                  const char *section_name_base,
11700                                  xt_section_type sec_type)
11701 {
11702   segT *seclist;
11703
11704   /* Walk over all of the current segments.
11705      Walk over each fragment
11706      For each non-empty fragment,
11707      Build a property record (append where possible).  */
11708
11709   for (seclist = &stdoutput->sections;
11710        seclist && *seclist;
11711        seclist = &(*seclist)->next)
11712     {
11713       segT sec = *seclist;
11714
11715       if (exclude_section_from_property_tables (sec))
11716         continue;
11717
11718       if (section_has_property (sec, property_function))
11719         {
11720           segment_info_type *xt_seg_info;
11721           xtensa_block_info **xt_blocks;
11722           segT prop_sec = xtensa_make_property_section (sec, section_name_base);
11723
11724           prop_sec->output_section = prop_sec;
11725           subseg_set (prop_sec, 0);
11726           xt_seg_info = seg_info (prop_sec);
11727           xt_blocks = &xt_seg_info->tc_segment_info_data.blocks[sec_type];
11728
11729           /* Walk over all of the frchains here and add new sections.  */
11730           add_xt_block_frags (sec, xt_blocks, property_function,
11731                               end_property_function);
11732         }
11733     }
11734
11735   /* Now we fill them out....  */
11736
11737   for (seclist = &stdoutput->sections;
11738        seclist && *seclist;
11739        seclist = &(*seclist)->next)
11740     {
11741       segment_info_type *seginfo;
11742       xtensa_block_info *block;
11743       segT sec = *seclist;
11744
11745       seginfo = seg_info (sec);
11746       block = seginfo->tc_segment_info_data.blocks[sec_type];
11747
11748       if (block)
11749         {
11750           xtensa_block_info *cur_block;
11751           int num_recs = 0;
11752           bfd_size_type rec_size;
11753
11754           for (cur_block = block; cur_block; cur_block = cur_block->next)
11755             num_recs++;
11756
11757           rec_size = num_recs * 8;
11758           bfd_set_section_size (stdoutput, sec, rec_size);
11759
11760           if (num_recs)
11761             {
11762               char *frag_data;
11763               int i;
11764
11765               subseg_set (sec, 0);
11766               frag_data = frag_more (rec_size);
11767               cur_block = block;
11768               for (i = 0; i < num_recs; i++)
11769                 {
11770                   fixS *fix;
11771
11772                   /* Write the fixup.  */
11773                   gas_assert (cur_block);
11774                   fix = fix_new (frag_now, i * 8, 4,
11775                                  section_symbol (cur_block->sec),
11776                                  cur_block->offset,
11777                                  FALSE, BFD_RELOC_32);
11778                   fix->fx_file = "<internal>";
11779                   fix->fx_line = 0;
11780
11781                   /* Write the length.  */
11782                   md_number_to_chars (&frag_data[4 + i * 8],
11783                                       cur_block->size, 4);
11784                   cur_block = cur_block->next;
11785                 }
11786               frag_wane (frag_now);
11787               frag_new (0);
11788               frag_wane (frag_now);
11789             }
11790         }
11791     }
11792 }
11793
11794
11795 static void
11796 xtensa_create_xproperty_segments (frag_flags_fn flag_fn,
11797                                   const char *section_name_base,
11798                                   xt_section_type sec_type)
11799 {
11800   segT *seclist;
11801
11802   /* Walk over all of the current segments.
11803      Walk over each fragment.
11804      For each fragment that has instructions,
11805      build an instruction record (append where possible).  */
11806
11807   for (seclist = &stdoutput->sections;
11808        seclist && *seclist;
11809        seclist = &(*seclist)->next)
11810     {
11811       segT sec = *seclist;
11812
11813       if (exclude_section_from_property_tables (sec))
11814         continue;
11815
11816       if (section_has_xproperty (sec, flag_fn))
11817         {
11818           segment_info_type *xt_seg_info;
11819           xtensa_block_info **xt_blocks;
11820           segT prop_sec = xtensa_make_property_section (sec, section_name_base);
11821
11822           prop_sec->output_section = prop_sec;
11823           subseg_set (prop_sec, 0);
11824           xt_seg_info = seg_info (prop_sec);
11825           xt_blocks = &xt_seg_info->tc_segment_info_data.blocks[sec_type];
11826
11827           /* Walk over all of the frchains here and add new sections.  */
11828           add_xt_prop_frags (sec, xt_blocks, flag_fn);
11829         }
11830     }
11831
11832   /* Now we fill them out....  */
11833
11834   for (seclist = &stdoutput->sections;
11835        seclist && *seclist;
11836        seclist = &(*seclist)->next)
11837     {
11838       segment_info_type *seginfo;
11839       xtensa_block_info *block;
11840       segT sec = *seclist;
11841
11842       seginfo = seg_info (sec);
11843       block = seginfo->tc_segment_info_data.blocks[sec_type];
11844
11845       if (block)
11846         {
11847           xtensa_block_info *cur_block;
11848           int num_recs = 0;
11849           bfd_size_type rec_size;
11850
11851           for (cur_block = block; cur_block; cur_block = cur_block->next)
11852             num_recs++;
11853
11854           rec_size = num_recs * (8 + 4);
11855           bfd_set_section_size (stdoutput, sec, rec_size);
11856           /* elf_section_data (sec)->this_hdr.sh_entsize = 12; */
11857
11858           if (num_recs)
11859             {
11860               char *frag_data;
11861               int i;
11862
11863               subseg_set (sec, 0);
11864               frag_data = frag_more (rec_size);
11865               cur_block = block;
11866               for (i = 0; i < num_recs; i++)
11867                 {
11868                   fixS *fix;
11869
11870                   /* Write the fixup.  */
11871                   gas_assert (cur_block);
11872                   fix = fix_new (frag_now, i * 12, 4,
11873                                  section_symbol (cur_block->sec),
11874                                  cur_block->offset,
11875                                  FALSE, BFD_RELOC_32);
11876                   fix->fx_file = "<internal>";
11877                   fix->fx_line = 0;
11878
11879                   /* Write the length.  */
11880                   md_number_to_chars (&frag_data[4 + i * 12],
11881                                       cur_block->size, 4);
11882                   md_number_to_chars (&frag_data[8 + i * 12],
11883                                       frag_flags_to_number (&cur_block->flags),
11884                                       sizeof (flagword));
11885                   cur_block = cur_block->next;
11886                 }
11887               frag_wane (frag_now);
11888               frag_new (0);
11889               frag_wane (frag_now);
11890             }
11891         }
11892     }
11893 }
11894
11895
11896 static bfd_boolean
11897 exclude_section_from_property_tables (segT sec)
11898 {
11899   flagword flags = bfd_get_section_flags (stdoutput, sec);
11900
11901   /* Sections that don't contribute to the memory footprint are excluded.  */
11902   if ((flags & SEC_DEBUGGING)
11903       || !(flags & SEC_ALLOC)
11904       || (flags & SEC_MERGE))
11905     return TRUE;
11906
11907   /* Linker cie and fde optimizations mess up property entries for
11908      eh_frame sections, but there is nothing inside them relevant to
11909      property tables anyway.  */
11910   if (strcmp (sec->name, ".eh_frame") == 0)
11911     return TRUE;
11912
11913   return FALSE;
11914 }
11915
11916
11917 static bfd_boolean
11918 section_has_property (segT sec, frag_predicate property_function)
11919 {
11920   segment_info_type *seginfo = seg_info (sec);
11921   fragS *fragP;
11922
11923   if (seginfo && seginfo->frchainP)
11924     {
11925       for (fragP = seginfo->frchainP->frch_root; fragP; fragP = fragP->fr_next)
11926         {
11927           if (property_function (fragP)
11928               && (fragP->fr_type != rs_fill || fragP->fr_fix != 0))
11929             return TRUE;
11930         }
11931     }
11932   return FALSE;
11933 }
11934
11935
11936 static bfd_boolean
11937 section_has_xproperty (segT sec, frag_flags_fn property_function)
11938 {
11939   segment_info_type *seginfo = seg_info (sec);
11940   fragS *fragP;
11941
11942   if (seginfo && seginfo->frchainP)
11943     {
11944       for (fragP = seginfo->frchainP->frch_root; fragP; fragP = fragP->fr_next)
11945         {
11946           frag_flags prop_flags;
11947           property_function (fragP, &prop_flags);
11948           if (!xtensa_frag_flags_is_empty (&prop_flags))
11949             return TRUE;
11950         }
11951     }
11952   return FALSE;
11953 }
11954
11955
11956 /* Two types of block sections exist right now: literal and insns.  */
11957
11958 static void
11959 add_xt_block_frags (segT sec,
11960                     xtensa_block_info **xt_block,
11961                     frag_predicate property_function,
11962                     frag_predicate end_property_function)
11963 {
11964   fragS *fragP;
11965
11966   /* Build it if needed.  */
11967   while (*xt_block != NULL)
11968     xt_block = &(*xt_block)->next;
11969   /* We are either at NULL at the beginning or at the end.  */
11970
11971   /* Walk through the frags.  */
11972   if (seg_info (sec)->frchainP)
11973     {
11974       for (fragP = seg_info (sec)->frchainP->frch_root;
11975            fragP;
11976            fragP = fragP->fr_next)
11977         {
11978           if (property_function (fragP)
11979               && (fragP->fr_type != rs_fill || fragP->fr_fix != 0))
11980             {
11981               if (*xt_block != NULL)
11982                 {
11983                   if ((*xt_block)->offset + (*xt_block)->size
11984                       == fragP->fr_address)
11985                     (*xt_block)->size += fragP->fr_fix;
11986                   else
11987                     xt_block = &((*xt_block)->next);
11988                 }
11989               if (*xt_block == NULL)
11990                 {
11991                   xtensa_block_info *new_block = (xtensa_block_info *)
11992                     xmalloc (sizeof (xtensa_block_info));
11993                   new_block->sec = sec;
11994                   new_block->offset = fragP->fr_address;
11995                   new_block->size = fragP->fr_fix;
11996                   new_block->next = NULL;
11997                   xtensa_frag_flags_init (&new_block->flags);
11998                   *xt_block = new_block;
11999                 }
12000               if (end_property_function
12001                   && end_property_function (fragP))
12002                 {
12003                   xt_block = &((*xt_block)->next);
12004                 }
12005             }
12006         }
12007     }
12008 }
12009
12010
12011 /* Break the encapsulation of add_xt_prop_frags here.  */
12012
12013 static bfd_boolean
12014 xtensa_frag_flags_is_empty (const frag_flags *prop_flags)
12015 {
12016   if (prop_flags->is_literal
12017       || prop_flags->is_insn
12018       || prop_flags->is_data
12019       || prop_flags->is_unreachable)
12020     return FALSE;
12021   return TRUE;
12022 }
12023
12024
12025 static void
12026 xtensa_frag_flags_init (frag_flags *prop_flags)
12027 {
12028   memset (prop_flags, 0, sizeof (frag_flags));
12029 }
12030
12031
12032 static void
12033 get_frag_property_flags (const fragS *fragP, frag_flags *prop_flags)
12034 {
12035   xtensa_frag_flags_init (prop_flags);
12036   if (fragP->tc_frag_data.is_literal)
12037     prop_flags->is_literal = TRUE;
12038   if (fragP->tc_frag_data.is_specific_opcode
12039       || fragP->tc_frag_data.is_no_transform)
12040     {
12041       prop_flags->is_no_transform = TRUE;
12042       if (xtensa_frag_flags_is_empty (prop_flags))
12043         prop_flags->is_data = TRUE;
12044     }
12045   if (fragP->tc_frag_data.is_unreachable)
12046     prop_flags->is_unreachable = TRUE;
12047   else if (fragP->tc_frag_data.is_insn)
12048     {
12049       prop_flags->is_insn = TRUE;
12050       if (fragP->tc_frag_data.is_loop_target)
12051         prop_flags->insn.is_loop_target = TRUE;
12052       if (fragP->tc_frag_data.is_branch_target)
12053         prop_flags->insn.is_branch_target = TRUE;
12054       if (fragP->tc_frag_data.is_no_density)
12055         prop_flags->insn.is_no_density = TRUE;
12056       if (fragP->tc_frag_data.use_absolute_literals)
12057         prop_flags->insn.is_abslit = TRUE;
12058     }
12059   if (fragP->tc_frag_data.is_align)
12060     {
12061       prop_flags->is_align = TRUE;
12062       prop_flags->alignment = fragP->tc_frag_data.alignment;
12063       if (xtensa_frag_flags_is_empty (prop_flags))
12064         prop_flags->is_data = TRUE;
12065     }
12066 }
12067
12068
12069 static flagword
12070 frag_flags_to_number (const frag_flags *prop_flags)
12071 {
12072   flagword num = 0;
12073   if (prop_flags->is_literal)
12074     num |= XTENSA_PROP_LITERAL;
12075   if (prop_flags->is_insn)
12076     num |= XTENSA_PROP_INSN;
12077   if (prop_flags->is_data)
12078     num |= XTENSA_PROP_DATA;
12079   if (prop_flags->is_unreachable)
12080     num |= XTENSA_PROP_UNREACHABLE;
12081   if (prop_flags->insn.is_loop_target)
12082     num |= XTENSA_PROP_INSN_LOOP_TARGET;
12083   if (prop_flags->insn.is_branch_target)
12084     {
12085       num |= XTENSA_PROP_INSN_BRANCH_TARGET;
12086       num = SET_XTENSA_PROP_BT_ALIGN (num, prop_flags->insn.bt_align_priority);
12087     }
12088
12089   if (prop_flags->insn.is_no_density)
12090     num |= XTENSA_PROP_INSN_NO_DENSITY;
12091   if (prop_flags->is_no_transform)
12092     num |= XTENSA_PROP_NO_TRANSFORM;
12093   if (prop_flags->insn.is_no_reorder)
12094     num |= XTENSA_PROP_INSN_NO_REORDER;
12095   if (prop_flags->insn.is_abslit)
12096     num |= XTENSA_PROP_INSN_ABSLIT;
12097
12098   if (prop_flags->is_align)
12099     {
12100       num |= XTENSA_PROP_ALIGN;
12101       num = SET_XTENSA_PROP_ALIGNMENT (num, prop_flags->alignment);
12102     }
12103
12104   return num;
12105 }
12106
12107
12108 static bfd_boolean
12109 xtensa_frag_flags_combinable (const frag_flags *prop_flags_1,
12110                               const frag_flags *prop_flags_2)
12111 {
12112   /* Cannot combine with an end marker.  */
12113
12114   if (prop_flags_1->is_literal != prop_flags_2->is_literal)
12115     return FALSE;
12116   if (prop_flags_1->is_insn != prop_flags_2->is_insn)
12117     return FALSE;
12118   if (prop_flags_1->is_data != prop_flags_2->is_data)
12119     return FALSE;
12120
12121   if (prop_flags_1->is_insn)
12122     {
12123       /* Properties of the beginning of the frag.  */
12124       if (prop_flags_2->insn.is_loop_target)
12125         return FALSE;
12126       if (prop_flags_2->insn.is_branch_target)
12127         return FALSE;
12128       if (prop_flags_1->insn.is_no_density !=
12129           prop_flags_2->insn.is_no_density)
12130         return FALSE;
12131       if (prop_flags_1->is_no_transform !=
12132           prop_flags_2->is_no_transform)
12133         return FALSE;
12134       if (prop_flags_1->insn.is_no_reorder !=
12135           prop_flags_2->insn.is_no_reorder)
12136         return FALSE;
12137       if (prop_flags_1->insn.is_abslit !=
12138           prop_flags_2->insn.is_abslit)
12139         return FALSE;
12140     }
12141
12142   if (prop_flags_1->is_align)
12143     return FALSE;
12144
12145   return TRUE;
12146 }
12147
12148
12149 static bfd_vma
12150 xt_block_aligned_size (const xtensa_block_info *xt_block)
12151 {
12152   bfd_vma end_addr;
12153   unsigned align_bits;
12154
12155   if (!xt_block->flags.is_align)
12156     return xt_block->size;
12157
12158   end_addr = xt_block->offset + xt_block->size;
12159   align_bits = xt_block->flags.alignment;
12160   end_addr = ((end_addr + ((1 << align_bits) -1)) >> align_bits) << align_bits;
12161   return end_addr - xt_block->offset;
12162 }
12163
12164
12165 static bfd_boolean
12166 xtensa_xt_block_combine (xtensa_block_info *xt_block,
12167                          const xtensa_block_info *xt_block_2)
12168 {
12169   if (xt_block->sec != xt_block_2->sec)
12170     return FALSE;
12171   if (xt_block->offset + xt_block_aligned_size (xt_block)
12172       != xt_block_2->offset)
12173     return FALSE;
12174
12175   if (xt_block_2->size == 0
12176       && (!xt_block_2->flags.is_unreachable
12177           || xt_block->flags.is_unreachable))
12178     {
12179       if (xt_block_2->flags.is_align
12180           && xt_block->flags.is_align)
12181         {
12182           /* Nothing needed.  */
12183           if (xt_block->flags.alignment >= xt_block_2->flags.alignment)
12184             return TRUE;
12185         }
12186       else
12187         {
12188           if (xt_block_2->flags.is_align)
12189             {
12190               /* Push alignment to previous entry.  */
12191               xt_block->flags.is_align = xt_block_2->flags.is_align;
12192               xt_block->flags.alignment = xt_block_2->flags.alignment;
12193             }
12194           return TRUE;
12195         }
12196     }
12197   if (!xtensa_frag_flags_combinable (&xt_block->flags,
12198                                      &xt_block_2->flags))
12199     return FALSE;
12200
12201   xt_block->size += xt_block_2->size;
12202
12203   if (xt_block_2->flags.is_align)
12204     {
12205       xt_block->flags.is_align = TRUE;
12206       xt_block->flags.alignment = xt_block_2->flags.alignment;
12207     }
12208
12209   return TRUE;
12210 }
12211
12212
12213 static void
12214 add_xt_prop_frags (segT sec,
12215                    xtensa_block_info **xt_block,
12216                    frag_flags_fn property_function)
12217 {
12218   fragS *fragP;
12219
12220   /* Build it if needed.  */
12221   while (*xt_block != NULL)
12222     {
12223       xt_block = &(*xt_block)->next;
12224     }
12225   /* We are either at NULL at the beginning or at the end.  */
12226
12227   /* Walk through the frags.  */
12228   if (seg_info (sec)->frchainP)
12229     {
12230       for (fragP = seg_info (sec)->frchainP->frch_root; fragP;
12231            fragP = fragP->fr_next)
12232         {
12233           xtensa_block_info tmp_block;
12234           tmp_block.sec = sec;
12235           tmp_block.offset = fragP->fr_address;
12236           tmp_block.size = fragP->fr_fix;
12237           tmp_block.next = NULL;
12238           property_function (fragP, &tmp_block.flags);
12239
12240           if (!xtensa_frag_flags_is_empty (&tmp_block.flags))
12241             /* && fragP->fr_fix != 0) */
12242             {
12243               if ((*xt_block) == NULL
12244                   || !xtensa_xt_block_combine (*xt_block, &tmp_block))
12245                 {
12246                   xtensa_block_info *new_block;
12247                   if ((*xt_block) != NULL)
12248                     xt_block = &(*xt_block)->next;
12249                   new_block = (xtensa_block_info *)
12250                     xmalloc (sizeof (xtensa_block_info));
12251                   *new_block = tmp_block;
12252                   *xt_block = new_block;
12253                 }
12254             }
12255         }
12256     }
12257 }
12258
12259 \f
12260 /* op_placement_info_table */
12261
12262 /* op_placement_info makes it easier to determine which
12263    ops can go in which slots.  */
12264
12265 static void
12266 init_op_placement_info_table (void)
12267 {
12268   xtensa_isa isa = xtensa_default_isa;
12269   xtensa_insnbuf ibuf = xtensa_insnbuf_alloc (isa);
12270   xtensa_opcode opcode;
12271   xtensa_format fmt;
12272   int slot;
12273   int num_opcodes = xtensa_isa_num_opcodes (isa);
12274
12275   op_placement_table = (op_placement_info_table)
12276     xmalloc (sizeof (op_placement_info) * num_opcodes);
12277   gas_assert (xtensa_isa_num_formats (isa) < MAX_FORMATS);
12278
12279   for (opcode = 0; opcode < num_opcodes; opcode++)
12280     {
12281       op_placement_info *opi = &op_placement_table[opcode];
12282       /* FIXME: Make tinsn allocation dynamic.  */
12283       if (xtensa_opcode_num_operands (isa, opcode) > MAX_INSN_ARGS)
12284         as_fatal (_("too many operands in instruction"));
12285       opi->narrowest = XTENSA_UNDEFINED;
12286       opi->narrowest_size = 0x7F;
12287       opi->narrowest_slot = 0;
12288       opi->formats = 0;
12289       opi->num_formats = 0;
12290       opi->issuef = 0;
12291       for (fmt = 0; fmt < xtensa_isa_num_formats (isa); fmt++)
12292         {
12293           opi->slots[fmt] = 0;
12294           for (slot = 0; slot < xtensa_format_num_slots (isa, fmt); slot++)
12295             {
12296               if (xtensa_opcode_encode (isa, fmt, slot, ibuf, opcode) == 0)
12297                 {
12298                   int fmt_length = xtensa_format_length (isa, fmt);
12299                   opi->issuef++;
12300                   set_bit (fmt, opi->formats);
12301                   set_bit (slot, opi->slots[fmt]);
12302                   if (fmt_length < opi->narrowest_size
12303                       || (fmt_length == opi->narrowest_size
12304                           && (xtensa_format_num_slots (isa, fmt)
12305                               < xtensa_format_num_slots (isa,
12306                                                          opi->narrowest))))
12307                     {
12308                       opi->narrowest = fmt;
12309                       opi->narrowest_size = fmt_length;
12310                       opi->narrowest_slot = slot;
12311                     }
12312                 }
12313             }
12314           if (opi->formats)
12315             opi->num_formats++;
12316         }
12317     }
12318   xtensa_insnbuf_free (isa, ibuf);
12319 }
12320
12321
12322 bfd_boolean
12323 opcode_fits_format_slot (xtensa_opcode opcode, xtensa_format fmt, int slot)
12324 {
12325   return bit_is_set (slot, op_placement_table[opcode].slots[fmt]);
12326 }
12327
12328
12329 /* If the opcode is available in a single slot format, return its size.  */
12330
12331 static int
12332 xg_get_single_size (xtensa_opcode opcode)
12333 {
12334   return op_placement_table[opcode].narrowest_size;
12335 }
12336
12337
12338 static xtensa_format
12339 xg_get_single_format (xtensa_opcode opcode)
12340 {
12341   return op_placement_table[opcode].narrowest;
12342 }
12343
12344
12345 static int
12346 xg_get_single_slot (xtensa_opcode opcode)
12347 {
12348   return op_placement_table[opcode].narrowest_slot;
12349 }
12350
12351 \f
12352 /* Instruction Stack Functions (from "xtensa-istack.h").  */
12353
12354 void
12355 istack_init (IStack *stack)
12356 {
12357   stack->ninsn = 0;
12358 }
12359
12360
12361 bfd_boolean
12362 istack_empty (IStack *stack)
12363 {
12364   return (stack->ninsn == 0);
12365 }
12366
12367
12368 bfd_boolean
12369 istack_full (IStack *stack)
12370 {
12371   return (stack->ninsn == MAX_ISTACK);
12372 }
12373
12374
12375 /* Return a pointer to the top IStack entry.
12376    It is an error to call this if istack_empty () is TRUE. */
12377
12378 TInsn *
12379 istack_top (IStack *stack)
12380 {
12381   int rec = stack->ninsn - 1;
12382   gas_assert (!istack_empty (stack));
12383   return &stack->insn[rec];
12384 }
12385
12386
12387 /* Add a new TInsn to an IStack.
12388    It is an error to call this if istack_full () is TRUE.  */
12389
12390 void
12391 istack_push (IStack *stack, TInsn *insn)
12392 {
12393   int rec = stack->ninsn;
12394   gas_assert (!istack_full (stack));
12395   stack->insn[rec] = *insn;
12396   stack->ninsn++;
12397 }
12398
12399
12400 /* Clear space for the next TInsn on the IStack and return a pointer
12401    to it.  It is an error to call this if istack_full () is TRUE.  */
12402
12403 TInsn *
12404 istack_push_space (IStack *stack)
12405 {
12406   int rec = stack->ninsn;
12407   TInsn *insn;
12408   gas_assert (!istack_full (stack));
12409   insn = &stack->insn[rec];
12410   tinsn_init (insn);
12411   stack->ninsn++;
12412   return insn;
12413 }
12414
12415
12416 /* Remove the last pushed instruction.  It is an error to call this if
12417    istack_empty () returns TRUE.  */
12418
12419 void
12420 istack_pop (IStack *stack)
12421 {
12422   int rec = stack->ninsn - 1;
12423   gas_assert (!istack_empty (stack));
12424   stack->ninsn--;
12425   tinsn_init (&stack->insn[rec]);
12426 }
12427
12428 \f
12429 /* TInsn functions.  */
12430
12431 void
12432 tinsn_init (TInsn *dst)
12433 {
12434   memset (dst, 0, sizeof (TInsn));
12435 }
12436
12437
12438 /* Return TRUE if ANY of the operands in the insn are symbolic.  */
12439
12440 static bfd_boolean
12441 tinsn_has_symbolic_operands (const TInsn *insn)
12442 {
12443   int i;
12444   int n = insn->ntok;
12445
12446   gas_assert (insn->insn_type == ITYPE_INSN);
12447
12448   for (i = 0; i < n; ++i)
12449     {
12450       switch (insn->tok[i].X_op)
12451         {
12452         case O_register:
12453         case O_constant:
12454           break;
12455         default:
12456           return TRUE;
12457         }
12458     }
12459   return FALSE;
12460 }
12461
12462
12463 bfd_boolean
12464 tinsn_has_invalid_symbolic_operands (const TInsn *insn)
12465 {
12466   xtensa_isa isa = xtensa_default_isa;
12467   int i;
12468   int n = insn->ntok;
12469
12470   gas_assert (insn->insn_type == ITYPE_INSN);
12471
12472   for (i = 0; i < n; ++i)
12473     {
12474       switch (insn->tok[i].X_op)
12475         {
12476         case O_register:
12477         case O_constant:
12478           break;
12479         case O_big:
12480         case O_illegal:
12481         case O_absent:
12482           /* Errors for these types are caught later.  */
12483           break;
12484         case O_hi16:
12485         case O_lo16:
12486         default:
12487           /* Symbolic immediates are only allowed on the last immediate
12488              operand.  At this time, CONST16 is the only opcode where we
12489              support non-PC-relative relocations.  */
12490           if (i != get_relaxable_immed (insn->opcode)
12491               || (xtensa_operand_is_PCrelative (isa, insn->opcode, i) != 1
12492                   && insn->opcode != xtensa_const16_opcode))
12493             {
12494               as_bad (_("invalid symbolic operand"));
12495               return TRUE;
12496             }
12497         }
12498     }
12499   return FALSE;
12500 }
12501
12502
12503 /* For assembly code with complex expressions (e.g. subtraction),
12504    we have to build them in the literal pool so that
12505    their results are calculated correctly after relaxation.
12506    The relaxation only handles expressions that
12507    boil down to SYMBOL + OFFSET.  */
12508
12509 static bfd_boolean
12510 tinsn_has_complex_operands (const TInsn *insn)
12511 {
12512   int i;
12513   int n = insn->ntok;
12514   gas_assert (insn->insn_type == ITYPE_INSN);
12515   for (i = 0; i < n; ++i)
12516     {
12517       switch (insn->tok[i].X_op)
12518         {
12519         case O_register:
12520         case O_constant:
12521         case O_symbol:
12522         case O_lo16:
12523         case O_hi16:
12524           break;
12525         default:
12526           return TRUE;
12527         }
12528     }
12529   return FALSE;
12530 }
12531
12532
12533 /* Encode a TInsn opcode and its constant operands into slotbuf.
12534    Return TRUE if there is a symbol in the immediate field.  This
12535    function assumes that:
12536    1) The number of operands are correct.
12537    2) The insn_type is ITYPE_INSN.
12538    3) The opcode can be encoded in the specified format and slot.
12539    4) Operands are either O_constant or O_symbol, and all constants fit.  */
12540
12541 static bfd_boolean
12542 tinsn_to_slotbuf (xtensa_format fmt,
12543                   int slot,
12544                   TInsn *tinsn,
12545                   xtensa_insnbuf slotbuf)
12546 {
12547   xtensa_isa isa = xtensa_default_isa;
12548   xtensa_opcode opcode = tinsn->opcode;
12549   bfd_boolean has_fixup = FALSE;
12550   int noperands = xtensa_opcode_num_operands (isa, opcode);
12551   int i;
12552
12553   gas_assert (tinsn->insn_type == ITYPE_INSN);
12554   if (noperands != tinsn->ntok)
12555     as_fatal (_("operand number mismatch"));
12556
12557   if (xtensa_opcode_encode (isa, fmt, slot, slotbuf, opcode))
12558     {
12559       as_bad (_("cannot encode opcode \"%s\" in the given format \"%s\""),
12560               xtensa_opcode_name (isa, opcode), xtensa_format_name (isa, fmt));
12561       return FALSE;
12562     }
12563
12564   for (i = 0; i < noperands; i++)
12565     {
12566       expressionS *exp = &tinsn->tok[i];
12567       int rc;
12568       unsigned line;
12569       const char *file_name;
12570       uint32 opnd_value;
12571
12572       switch (exp->X_op)
12573         {
12574         case O_register:
12575           if (xtensa_operand_is_visible (isa, opcode, i) == 0)
12576             break;
12577           /* The register number has already been checked in
12578              expression_maybe_register, so we don't need to check here.  */
12579           opnd_value = exp->X_add_number;
12580           (void) xtensa_operand_encode (isa, opcode, i, &opnd_value);
12581           rc = xtensa_operand_set_field (isa, opcode, i, fmt, slot, slotbuf,
12582                                          opnd_value);
12583           if (rc != 0)
12584             as_warn (_("xtensa-isa failure: %s"), xtensa_isa_error_msg (isa));
12585           break;
12586
12587         case O_constant:
12588           if (xtensa_operand_is_visible (isa, opcode, i) == 0)
12589             break;
12590           file_name = as_where (&line);
12591           /* It is a constant and we called this function
12592              then we have to try to fit it.  */
12593           xtensa_insnbuf_set_operand (slotbuf, fmt, slot, opcode, i,
12594                                       exp->X_add_number, file_name, line);
12595           break;
12596
12597         default:
12598           has_fixup = TRUE;
12599           break;
12600         }
12601     }
12602
12603   return has_fixup;
12604 }
12605
12606
12607 /* Encode a single TInsn into an insnbuf.  If the opcode can only be encoded
12608    into a multi-slot instruction, fill the other slots with NOPs.
12609    Return TRUE if there is a symbol in the immediate field.  See also the
12610    assumptions listed for tinsn_to_slotbuf.  */
12611
12612 static bfd_boolean
12613 tinsn_to_insnbuf (TInsn *tinsn, xtensa_insnbuf insnbuf)
12614 {
12615   static xtensa_insnbuf slotbuf = 0;
12616   static vliw_insn vinsn;
12617   xtensa_isa isa = xtensa_default_isa;
12618   bfd_boolean has_fixup = FALSE;
12619   int i;
12620
12621   if (!slotbuf)
12622     {
12623       slotbuf = xtensa_insnbuf_alloc (isa);
12624       xg_init_vinsn (&vinsn);
12625     }
12626
12627   xg_clear_vinsn (&vinsn);
12628
12629   bundle_tinsn (tinsn, &vinsn);
12630
12631   xtensa_format_encode (isa, vinsn.format, insnbuf);
12632
12633   for (i = 0; i < vinsn.num_slots; i++)
12634     {
12635       /* Only one slot may have a fix-up because the rest contains NOPs.  */
12636       has_fixup |=
12637         tinsn_to_slotbuf (vinsn.format, i, &vinsn.slots[i], vinsn.slotbuf[i]);
12638       xtensa_format_set_slot (isa, vinsn.format, i, insnbuf, vinsn.slotbuf[i]);
12639     }
12640
12641   return has_fixup;
12642 }
12643
12644
12645 /* Check the instruction arguments.  Return TRUE on failure.  */
12646
12647 static bfd_boolean
12648 tinsn_check_arguments (const TInsn *insn)
12649 {
12650   xtensa_isa isa = xtensa_default_isa;
12651   xtensa_opcode opcode = insn->opcode;
12652   xtensa_regfile t1_regfile, t2_regfile;
12653   int t1_reg, t2_reg;
12654   int t1_base_reg, t1_last_reg;
12655   int t2_base_reg, t2_last_reg;
12656   char t1_inout, t2_inout;
12657   int i, j;
12658
12659   if (opcode == XTENSA_UNDEFINED)
12660     {
12661       as_bad (_("invalid opcode"));
12662       return TRUE;
12663     }
12664
12665   if (xtensa_opcode_num_operands (isa, opcode) > insn->ntok)
12666     {
12667       as_bad (_("too few operands"));
12668       return TRUE;
12669     }
12670
12671   if (xtensa_opcode_num_operands (isa, opcode) < insn->ntok)
12672     {
12673       as_bad (_("too many operands"));
12674       return TRUE;
12675     }
12676
12677   /* Check registers.  */
12678   for (j = 0; j < insn->ntok; j++)
12679     {
12680       if (xtensa_operand_is_register (isa, insn->opcode, j) != 1)
12681         continue;
12682
12683       t2_regfile = xtensa_operand_regfile (isa, insn->opcode, j);
12684       t2_base_reg = insn->tok[j].X_add_number;
12685       t2_last_reg
12686         = t2_base_reg + xtensa_operand_num_regs (isa, insn->opcode, j);
12687
12688       for (i = 0; i < insn->ntok; i++)
12689         {
12690           if (i == j)
12691             continue;
12692
12693           if (xtensa_operand_is_register (isa, insn->opcode, i) != 1)
12694             continue;
12695
12696           t1_regfile = xtensa_operand_regfile (isa, insn->opcode, i);
12697
12698           if (t1_regfile != t2_regfile)
12699             continue;
12700
12701           t1_inout = xtensa_operand_inout (isa, insn->opcode, i);
12702           t2_inout = xtensa_operand_inout (isa, insn->opcode, j);
12703
12704           t1_base_reg = insn->tok[i].X_add_number;
12705           t1_last_reg = (t1_base_reg
12706                          + xtensa_operand_num_regs (isa, insn->opcode, i));
12707
12708           for (t1_reg = t1_base_reg; t1_reg < t1_last_reg; t1_reg++)
12709             {
12710               for (t2_reg = t2_base_reg; t2_reg < t2_last_reg; t2_reg++)
12711                 {
12712                   if (t1_reg != t2_reg)
12713                     continue;
12714
12715                   if (t1_inout != 'i' && t2_inout != 'i')
12716                     {
12717                       as_bad (_("multiple writes to the same register"));
12718                       return TRUE;
12719                     }
12720                 }
12721             }
12722         }
12723     }
12724   return FALSE;
12725 }
12726
12727
12728 /* Load an instruction from its encoded form.  */
12729
12730 static void
12731 tinsn_from_chars (TInsn *tinsn, char *f, int slot)
12732 {
12733   vliw_insn vinsn;
12734
12735   xg_init_vinsn (&vinsn);
12736   vinsn_from_chars (&vinsn, f);
12737
12738   *tinsn = vinsn.slots[slot];
12739   xg_free_vinsn (&vinsn);
12740 }
12741
12742
12743 static void
12744 tinsn_from_insnbuf (TInsn *tinsn,
12745                     xtensa_insnbuf slotbuf,
12746                     xtensa_format fmt,
12747                     int slot)
12748 {
12749   int i;
12750   xtensa_isa isa = xtensa_default_isa;
12751
12752   /* Find the immed.  */
12753   tinsn_init (tinsn);
12754   tinsn->insn_type = ITYPE_INSN;
12755   tinsn->is_specific_opcode = FALSE;    /* must not be specific */
12756   tinsn->opcode = xtensa_opcode_decode (isa, fmt, slot, slotbuf);
12757   tinsn->ntok = xtensa_opcode_num_operands (isa, tinsn->opcode);
12758   for (i = 0; i < tinsn->ntok; i++)
12759     {
12760       set_expr_const (&tinsn->tok[i],
12761                       xtensa_insnbuf_get_operand (slotbuf, fmt, slot,
12762                                                   tinsn->opcode, i));
12763     }
12764 }
12765
12766
12767 /* Read the value of the relaxable immed from the fr_symbol and fr_offset.  */
12768
12769 static void
12770 tinsn_immed_from_frag (TInsn *tinsn, fragS *fragP, int slot)
12771 {
12772   xtensa_opcode opcode = tinsn->opcode;
12773   int opnum;
12774
12775   if (fragP->tc_frag_data.slot_symbols[slot])
12776     {
12777       opnum = get_relaxable_immed (opcode);
12778       gas_assert (opnum >= 0);
12779       set_expr_symbol_offset (&tinsn->tok[opnum],
12780                               fragP->tc_frag_data.slot_symbols[slot],
12781                               fragP->tc_frag_data.slot_offsets[slot]);
12782     }
12783   tinsn->extra_arg = fragP->tc_frag_data.free_reg[slot];
12784 }
12785
12786
12787 static int
12788 get_num_stack_text_bytes (IStack *istack)
12789 {
12790   int i;
12791   int text_bytes = 0;
12792
12793   for (i = 0; i < istack->ninsn; i++)
12794     {
12795       TInsn *tinsn = &istack->insn[i];
12796       if (tinsn->insn_type == ITYPE_INSN)
12797         text_bytes += xg_get_single_size (tinsn->opcode);
12798     }
12799   return text_bytes;
12800 }
12801
12802
12803 static int
12804 get_num_stack_literal_bytes (IStack *istack)
12805 {
12806   int i;
12807   int lit_bytes = 0;
12808
12809   for (i = 0; i < istack->ninsn; i++)
12810     {
12811       TInsn *tinsn = &istack->insn[i];
12812       if (tinsn->insn_type == ITYPE_LITERAL && tinsn->ntok == 1)
12813         lit_bytes += 4;
12814     }
12815   return lit_bytes;
12816 }
12817
12818 \f
12819 /* vliw_insn functions.  */
12820
12821 static void
12822 xg_init_vinsn (vliw_insn *v)
12823 {
12824   int i;
12825   xtensa_isa isa = xtensa_default_isa;
12826
12827   xg_clear_vinsn (v);
12828
12829   v->insnbuf = xtensa_insnbuf_alloc (isa);
12830   if (v->insnbuf == NULL)
12831     as_fatal (_("out of memory"));
12832
12833   for (i = 0; i < config_max_slots; i++)
12834     {
12835       v->slotbuf[i] = xtensa_insnbuf_alloc (isa);
12836       if (v->slotbuf[i] == NULL)
12837         as_fatal (_("out of memory"));
12838     }
12839 }
12840
12841
12842 static void
12843 xg_clear_vinsn (vliw_insn *v)
12844 {
12845   int i;
12846
12847   memset (v, 0, offsetof (vliw_insn, slots)
12848                 + sizeof(TInsn) * config_max_slots);
12849
12850   v->format = XTENSA_UNDEFINED;
12851   v->num_slots = 0;
12852   v->inside_bundle = FALSE;
12853
12854   if (xt_saved_debug_type != DEBUG_NONE)
12855     debug_type = xt_saved_debug_type;
12856
12857   for (i = 0; i < config_max_slots; i++)
12858     v->slots[i].opcode = XTENSA_UNDEFINED;
12859 }
12860
12861
12862 static void
12863 xg_copy_vinsn (vliw_insn *dst, vliw_insn *src)
12864 {
12865   memcpy (dst, src,
12866           offsetof(vliw_insn, slots) + src->num_slots * sizeof(TInsn));
12867   dst->insnbuf = src->insnbuf;
12868   memcpy (dst->slotbuf, src->slotbuf, src->num_slots * sizeof(xtensa_insnbuf));
12869 }
12870
12871
12872 static bfd_boolean
12873 vinsn_has_specific_opcodes (vliw_insn *v)
12874 {
12875   int i;
12876
12877   for (i = 0; i < v->num_slots; i++)
12878     {
12879       if (v->slots[i].is_specific_opcode)
12880         return TRUE;
12881     }
12882   return FALSE;
12883 }
12884
12885
12886 static void
12887 xg_free_vinsn (vliw_insn *v)
12888 {
12889   int i;
12890   xtensa_insnbuf_free (xtensa_default_isa, v->insnbuf);
12891   for (i = 0; i < config_max_slots; i++)
12892     xtensa_insnbuf_free (xtensa_default_isa, v->slotbuf[i]);
12893 }
12894
12895
12896 /* Encode a vliw_insn into an insnbuf.  Return TRUE if there are any symbolic
12897    operands.  See also the assumptions listed for tinsn_to_slotbuf.  */
12898
12899 static bfd_boolean
12900 vinsn_to_insnbuf (vliw_insn *vinsn,
12901                   char *frag_offset,
12902                   fragS *fragP,
12903                   bfd_boolean record_fixup)
12904 {
12905   xtensa_isa isa = xtensa_default_isa;
12906   xtensa_format fmt = vinsn->format;
12907   xtensa_insnbuf insnbuf = vinsn->insnbuf;
12908   int slot;
12909   bfd_boolean has_fixup = FALSE;
12910
12911   xtensa_format_encode (isa, fmt, insnbuf);
12912
12913   for (slot = 0; slot < vinsn->num_slots; slot++)
12914     {
12915       TInsn *tinsn = &vinsn->slots[slot];
12916       expressionS *extra_arg = &tinsn->extra_arg;
12917       bfd_boolean tinsn_has_fixup =
12918         tinsn_to_slotbuf (vinsn->format, slot, tinsn,
12919                           vinsn->slotbuf[slot]);
12920
12921       xtensa_format_set_slot (isa, fmt, slot,
12922                               insnbuf, vinsn->slotbuf[slot]);
12923       if (extra_arg->X_op != O_illegal && extra_arg->X_op != O_register)
12924         {
12925           if (vinsn->num_slots != 1)
12926             as_bad (_("TLS relocation not allowed in FLIX bundle"));
12927           else if (record_fixup)
12928             /* Instructions that generate TLS relocations should always be
12929                relaxed in the front-end.  If "record_fixup" is set, then this
12930                function is being called during back-end relaxation, so flag
12931                the unexpected behavior as an error.  */
12932             as_bad (_("unexpected TLS relocation"));
12933           else
12934             fix_new (fragP, frag_offset - fragP->fr_literal,
12935                      xtensa_format_length (isa, fmt),
12936                      extra_arg->X_add_symbol, extra_arg->X_add_number,
12937                      FALSE, map_operator_to_reloc (extra_arg->X_op, FALSE));
12938         }
12939       if (tinsn_has_fixup)
12940         {
12941           int i;
12942           xtensa_opcode opcode = tinsn->opcode;
12943           int noperands = xtensa_opcode_num_operands (isa, opcode);
12944           has_fixup = TRUE;
12945
12946           for (i = 0; i < noperands; i++)
12947             {
12948               expressionS* exp = &tinsn->tok[i];
12949               switch (exp->X_op)
12950                 {
12951                 case O_symbol:
12952                 case O_lo16:
12953                 case O_hi16:
12954                   if (get_relaxable_immed (opcode) == i)
12955                     {
12956                       /* Add a fix record for the instruction, except if this
12957                          function is being called prior to relaxation, i.e.,
12958                          if record_fixup is false, and the instruction might
12959                          be relaxed later.  */
12960                       if (record_fixup
12961                           || tinsn->is_specific_opcode
12962                           || !xg_is_relaxable_insn (tinsn, 0))
12963                         {
12964                           xg_add_opcode_fix (tinsn, i, fmt, slot, exp, fragP,
12965                                              frag_offset - fragP->fr_literal);
12966                         }
12967                       else
12968                         {
12969                           if (exp->X_op != O_symbol)
12970                             as_bad (_("invalid operand"));
12971                           tinsn->symbol = exp->X_add_symbol;
12972                           tinsn->offset = exp->X_add_number;
12973                         }
12974                     }
12975                   else
12976                     as_bad (_("symbolic operand not allowed"));
12977                   break;
12978
12979                 case O_constant:
12980                 case O_register:
12981                   break;
12982
12983                 default:
12984                   as_bad (_("expression too complex"));
12985                   break;
12986                 }
12987             }
12988         }
12989     }
12990
12991   return has_fixup;
12992 }
12993
12994
12995 static void
12996 vinsn_from_chars (vliw_insn *vinsn, char *f)
12997 {
12998   static xtensa_insnbuf insnbuf = NULL;
12999   static xtensa_insnbuf slotbuf = NULL;
13000   int i;
13001   xtensa_format fmt;
13002   xtensa_isa isa = xtensa_default_isa;
13003
13004   if (!insnbuf)
13005     {
13006       insnbuf = xtensa_insnbuf_alloc (isa);
13007       slotbuf = xtensa_insnbuf_alloc (isa);
13008     }
13009
13010   xtensa_insnbuf_from_chars (isa, insnbuf, (unsigned char *) f, 0);
13011   fmt = xtensa_format_decode (isa, insnbuf);
13012   if (fmt == XTENSA_UNDEFINED)
13013     as_fatal (_("cannot decode instruction format"));
13014   vinsn->format = fmt;
13015   vinsn->num_slots = xtensa_format_num_slots (isa, fmt);
13016
13017   for (i = 0; i < vinsn->num_slots; i++)
13018     {
13019       TInsn *tinsn = &vinsn->slots[i];
13020       xtensa_format_get_slot (isa, fmt, i, insnbuf, slotbuf);
13021       tinsn_from_insnbuf (tinsn, slotbuf, fmt, i);
13022     }
13023 }
13024
13025 \f
13026 /* Expression utilities.  */
13027
13028 /* Return TRUE if the expression is an integer constant.  */
13029
13030 bfd_boolean
13031 expr_is_const (const expressionS *s)
13032 {
13033   return (s->X_op == O_constant);
13034 }
13035
13036
13037 /* Get the expression constant.
13038    Calling this is illegal if expr_is_const () returns TRUE.  */
13039
13040 offsetT
13041 get_expr_const (const expressionS *s)
13042 {
13043   gas_assert (expr_is_const (s));
13044   return s->X_add_number;
13045 }
13046
13047
13048 /* Set the expression to a constant value.  */
13049
13050 void
13051 set_expr_const (expressionS *s, offsetT val)
13052 {
13053   s->X_op = O_constant;
13054   s->X_add_number = val;
13055   s->X_add_symbol = NULL;
13056   s->X_op_symbol = NULL;
13057 }
13058
13059
13060 bfd_boolean
13061 expr_is_register (const expressionS *s)
13062 {
13063   return (s->X_op == O_register);
13064 }
13065
13066
13067 /* Get the expression constant.
13068    Calling this is illegal if expr_is_const () returns TRUE.  */
13069
13070 offsetT
13071 get_expr_register (const expressionS *s)
13072 {
13073   gas_assert (expr_is_register (s));
13074   return s->X_add_number;
13075 }
13076
13077
13078 /* Set the expression to a symbol + constant offset.  */
13079
13080 void
13081 set_expr_symbol_offset (expressionS *s, symbolS *sym, offsetT offset)
13082 {
13083   s->X_op = O_symbol;
13084   s->X_add_symbol = sym;
13085   s->X_op_symbol = NULL;        /* unused */
13086   s->X_add_number = offset;
13087 }
13088
13089
13090 /* Return TRUE if the two expressions are equal.  */
13091
13092 bfd_boolean
13093 expr_is_equal (expressionS *s1, expressionS *s2)
13094 {
13095   if (s1->X_op != s2->X_op)
13096     return FALSE;
13097   if (s1->X_add_symbol != s2->X_add_symbol)
13098     return FALSE;
13099   if (s1->X_op_symbol != s2->X_op_symbol)
13100     return FALSE;
13101   if (s1->X_add_number != s2->X_add_number)
13102     return FALSE;
13103   return TRUE;
13104 }
13105
13106
13107 static void
13108 copy_expr (expressionS *dst, const expressionS *src)
13109 {
13110   memcpy (dst, src, sizeof (expressionS));
13111 }
13112
13113 \f
13114 /* Support for the "--rename-section" option.  */
13115
13116 struct rename_section_struct
13117 {
13118   char *old_name;
13119   char *new_name;
13120   struct rename_section_struct *next;
13121 };
13122
13123 static struct rename_section_struct *section_rename;
13124
13125
13126 /* Parse the string "oldname=new_name(:oldname2=new_name2)*" and add
13127    entries to the section_rename list.  Note: Specifying multiple
13128    renamings separated by colons is not documented and is retained only
13129    for backward compatibility.  */
13130
13131 static void
13132 build_section_rename (const char *arg)
13133 {
13134   struct rename_section_struct *r;
13135   char *this_arg = NULL;
13136   char *next_arg = NULL;
13137
13138   for (this_arg = xstrdup (arg); this_arg != NULL; this_arg = next_arg)
13139     {
13140       char *old_name, *new_name;
13141
13142       if (this_arg)
13143         {
13144           next_arg = strchr (this_arg, ':');
13145           if (next_arg)
13146             {
13147               *next_arg = '\0';
13148               next_arg++;
13149             }
13150         }
13151
13152       old_name = this_arg;
13153       new_name = strchr (this_arg, '=');
13154
13155       if (*old_name == '\0')
13156         {
13157           as_warn (_("ignoring extra '-rename-section' delimiter ':'"));
13158           continue;
13159         }
13160       if (!new_name || new_name[1] == '\0')
13161         {
13162           as_warn (_("ignoring invalid '-rename-section' specification: '%s'"),
13163                    old_name);
13164           continue;
13165         }
13166       *new_name = '\0';
13167       new_name++;
13168
13169       /* Check for invalid section renaming.  */
13170       for (r = section_rename; r != NULL; r = r->next)
13171         {
13172           if (strcmp (r->old_name, old_name) == 0)
13173             as_bad (_("section %s renamed multiple times"), old_name);
13174           if (strcmp (r->new_name, new_name) == 0)
13175             as_bad (_("multiple sections remapped to output section %s"),
13176                     new_name);
13177         }
13178
13179       /* Now add it.  */
13180       r = (struct rename_section_struct *)
13181         xmalloc (sizeof (struct rename_section_struct));
13182       r->old_name = xstrdup (old_name);
13183       r->new_name = xstrdup (new_name);
13184       r->next = section_rename;
13185       section_rename = r;
13186     }
13187 }
13188
13189
13190 char *
13191 xtensa_section_rename (char *name)
13192 {
13193   struct rename_section_struct *r = section_rename;
13194
13195   for (r = section_rename; r != NULL; r = r->next)
13196     {
13197       if (strcmp (r->old_name, name) == 0)
13198         return r->new_name;
13199     }
13200
13201   return name;
13202 }