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