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