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