Back to index

cell-binutils  2.17cvs20070401
tc-xtensa.c
Go to the documentation of this file.
00001 /* tc-xtensa.c -- Assemble Xtensa instructions.
00002    Copyright 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
00003 
00004    This file is part of GAS, the GNU Assembler.
00005 
00006    GAS is free software; you can redistribute it and/or modify
00007    it under the terms of the GNU General Public License as published by
00008    the Free Software Foundation; either version 2, or (at your option)
00009    any later version.
00010 
00011    GAS is distributed in the hope that it will be useful,
00012    but WITHOUT ANY WARRANTY; without even the implied warranty of
00013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014    GNU General Public License for more details.
00015 
00016    You should have received a copy of the GNU General Public License
00017    along with GAS; see the file COPYING.  If not, write to
00018    the Free Software Foundation, 51 Franklin Street - Fifth Floor, Boston,
00019    MA 02110-1301, USA.  */
00020 
00021 #include <limits.h>
00022 #include "as.h"
00023 #include "sb.h"
00024 #include "safe-ctype.h"
00025 #include "tc-xtensa.h"
00026 #include "subsegs.h"
00027 #include "xtensa-relax.h"
00028 #include "xtensa-istack.h"
00029 #include "dwarf2dbg.h"
00030 #include "struc-symbol.h"
00031 #include "xtensa-config.h"
00032 
00033 /* Provide default values for new configuration settings.  */
00034 #ifndef XSHAL_ABI
00035 #define XSHAL_ABI 0
00036 #endif
00037 
00038 #ifndef uint32
00039 #define uint32 unsigned int
00040 #endif
00041 #ifndef int32
00042 #define int32 signed int
00043 #endif
00044 
00045 /* Notes:
00046 
00047    Naming conventions (used somewhat inconsistently):
00048       The xtensa_ functions are exported
00049       The xg_ functions are internal
00050 
00051    We also have a couple of different extensibility mechanisms.
00052    1) The idiom replacement:
00053       This is used when a line is first parsed to
00054       replace an instruction pattern with another instruction
00055       It is currently limited to replacements of instructions
00056       with constant operands.
00057    2) The xtensa-relax.c mechanism that has stronger instruction
00058       replacement patterns.  When an instruction's immediate field
00059       does not fit the next instruction sequence is attempted.
00060       In addition, "narrow" opcodes are supported this way.  */
00061 
00062 
00063 /* Define characters with special meanings to GAS.  */
00064 const char comment_chars[] = "#";
00065 const char line_comment_chars[] = "#";
00066 const char line_separator_chars[] = ";";
00067 const char EXP_CHARS[] = "eE";
00068 const char FLT_CHARS[] = "rRsSfFdDxXpP";
00069 
00070 
00071 /* Flags to indicate whether the hardware supports the density and
00072    absolute literals options.  */
00073 
00074 bfd_boolean density_supported = XCHAL_HAVE_DENSITY;
00075 bfd_boolean absolute_literals_supported = XSHAL_USE_ABSOLUTE_LITERALS;
00076 
00077 /* Maximum width we would pad an unreachable frag to get alignment.  */
00078 #define UNREACHABLE_MAX_WIDTH  8
00079 
00080 static vliw_insn cur_vinsn;
00081 
00082 unsigned xtensa_fetch_width = XCHAL_INST_FETCH_WIDTH;
00083 
00084 static enum debug_info_type xt_saved_debug_type = DEBUG_NONE;
00085 
00086 /* Some functions are only valid in the front end.  This variable
00087    allows us to assert that we haven't crossed over into the
00088    back end.  */
00089 static bfd_boolean past_xtensa_end = FALSE;
00090 
00091 /* Flags for properties of the last instruction in a segment.  */
00092 #define FLAG_IS_A0_WRITER   0x1
00093 #define FLAG_IS_BAD_LOOPEND 0x2
00094 
00095 
00096 /* We define a special segment names ".literal" to place literals
00097    into.  The .fini and .init sections are special because they
00098    contain code that is moved together by the linker.  We give them
00099    their own special .fini.literal and .init.literal sections.  */
00100 
00101 #define LITERAL_SECTION_NAME              xtensa_section_rename (".literal")
00102 #define LIT4_SECTION_NAME          xtensa_section_rename (".lit4")
00103 #define INIT_SECTION_NAME          xtensa_section_rename (".init")
00104 #define FINI_SECTION_NAME          xtensa_section_rename (".fini")
00105 
00106 
00107 /* This type is used for the directive_stack to keep track of the
00108    state of the literal collection pools.  If lit_prefix is set, it is
00109    used to determine the literal section names; otherwise, the literal
00110    sections are determined based on the current text section.  The
00111    lit_seg and lit4_seg fields cache these literal sections, with the
00112    current_text_seg field used a tag to indicate whether the cached
00113    values are valid.  */
00114 
00115 typedef struct lit_state_struct
00116 {
00117   char *lit_prefix;
00118   segT current_text_seg;
00119   segT lit_seg;
00120   segT lit4_seg;
00121 } lit_state;
00122 
00123 static lit_state default_lit_sections;
00124 
00125 
00126 /* We keep a list of literal segments.  The seg_list type is the node
00127    for this list.  The literal_head pointer is the head of the list,
00128    with the literal_head_h dummy node at the start.  */
00129 
00130 typedef struct seg_list_struct
00131 {
00132   struct seg_list_struct *next;
00133   segT seg;
00134 } seg_list;
00135 
00136 static seg_list literal_head_h;
00137 static seg_list *literal_head = &literal_head_h;
00138 
00139 
00140 /* Lists of symbols.  We keep a list of symbols that label the current
00141    instruction, so that we can adjust the symbols when inserting alignment
00142    for various instructions.  We also keep a list of all the symbols on
00143    literals, so that we can fix up those symbols when the literals are
00144    later moved into the text sections.  */
00145 
00146 typedef struct sym_list_struct
00147 {
00148   struct sym_list_struct *next;
00149   symbolS *sym;
00150 } sym_list;
00151 
00152 static sym_list *insn_labels = NULL;
00153 static sym_list *free_insn_labels = NULL;
00154 static sym_list *saved_insn_labels = NULL;
00155 
00156 static sym_list *literal_syms;
00157 
00158 
00159 /* Flags to determine whether to prefer const16 or l32r
00160    if both options are available.  */
00161 int prefer_const16 = 0;
00162 int prefer_l32r = 0;
00163 
00164 /* Global flag to indicate when we are emitting literals.  */
00165 int generating_literals = 0;
00166 
00167 /* The following PROPERTY table definitions are copied from
00168    <elf/xtensa.h> and must be kept in sync with the code there.  */
00169 
00170 /* Flags in the property tables to specify whether blocks of memory
00171    are literals, instructions, data, or unreachable.  For
00172    instructions, blocks that begin loop targets and branch targets are
00173    designated.  Blocks that do not allow density, instruction
00174    reordering or transformation are also specified.  Finally, for
00175    branch targets, branch target alignment priority is included.
00176    Alignment of the next block is specified in the current block
00177    and the size of the current block does not include any fill required
00178    to align to the next block.  */
00179 
00180 #define XTENSA_PROP_LITERAL        0x00000001
00181 #define XTENSA_PROP_INSN           0x00000002
00182 #define XTENSA_PROP_DATA           0x00000004
00183 #define XTENSA_PROP_UNREACHABLE           0x00000008
00184 /* Instruction only properties at beginning of code.  */
00185 #define XTENSA_PROP_INSN_LOOP_TARGET      0x00000010
00186 #define XTENSA_PROP_INSN_BRANCH_TARGET    0x00000020
00187 /* Instruction only properties about code.  */
00188 #define XTENSA_PROP_INSN_NO_DENSITY       0x00000040
00189 #define XTENSA_PROP_INSN_NO_REORDER       0x00000080
00190 #define XTENSA_PROP_INSN_NO_TRANSFORM     0x00000100
00191 
00192 /*  Branch target alignment information.  This transmits information
00193     to the linker optimization about the priority of aligning a
00194     particular block for branch target alignment: None, low priority,
00195     high priority, or required.  These only need to be checked in
00196     instruction blocks marked as XTENSA_PROP_INSN_BRANCH_TARGET.
00197     Common usage is
00198 
00199     switch (GET_XTENSA_PROP_BT_ALIGN (flags))
00200     case XTENSA_PROP_BT_ALIGN_NONE:
00201     case XTENSA_PROP_BT_ALIGN_LOW:
00202     case XTENSA_PROP_BT_ALIGN_HIGH:
00203     case XTENSA_PROP_BT_ALIGN_REQUIRE:
00204 */
00205 #define XTENSA_PROP_BT_ALIGN_MASK       0x00000600
00206 
00207 /* No branch target alignment.  */
00208 #define XTENSA_PROP_BT_ALIGN_NONE       0x0
00209 /* Low priority branch target alignment.  */
00210 #define XTENSA_PROP_BT_ALIGN_LOW        0x1
00211 /* High priority branch target alignment.  */
00212 #define XTENSA_PROP_BT_ALIGN_HIGH       0x2
00213 /* Required branch target alignment.  */
00214 #define XTENSA_PROP_BT_ALIGN_REQUIRE    0x3
00215 
00216 #define GET_XTENSA_PROP_BT_ALIGN(flag) \
00217   (((unsigned) ((flag) & (XTENSA_PROP_BT_ALIGN_MASK))) >> 9)
00218 #define SET_XTENSA_PROP_BT_ALIGN(flag, align) \
00219   (((flag) & (~XTENSA_PROP_BT_ALIGN_MASK)) | \
00220     (((align) << 9) & XTENSA_PROP_BT_ALIGN_MASK))
00221 
00222 
00223 /* Alignment is specified in the block BEFORE the one that needs
00224    alignment.  Up to 5 bits.  Use GET_XTENSA_PROP_ALIGNMENT(flags) to
00225    get the required alignment specified as a power of 2.  Use
00226    SET_XTENSA_PROP_ALIGNMENT(flags, pow2) to set the required
00227    alignment.  Be careful of side effects since the SET will evaluate
00228    flags twice.  Also, note that the SIZE of a block in the property
00229    table does not include the alignment size, so the alignment fill
00230    must be calculated to determine if two blocks are contiguous.
00231    TEXT_ALIGN is not currently implemented but is a placeholder for a
00232    possible future implementation.  */
00233 
00234 #define XTENSA_PROP_ALIGN          0x00000800
00235 
00236 #define XTENSA_PROP_ALIGNMENT_MASK      0x0001f000
00237 
00238 #define GET_XTENSA_PROP_ALIGNMENT(flag) \
00239   (((unsigned) ((flag) & (XTENSA_PROP_ALIGNMENT_MASK))) >> 12)
00240 #define SET_XTENSA_PROP_ALIGNMENT(flag, align) \
00241   (((flag) & (~XTENSA_PROP_ALIGNMENT_MASK)) | \
00242     (((align) << 12) & XTENSA_PROP_ALIGNMENT_MASK))
00243 
00244 #define XTENSA_PROP_INSN_ABSLIT 0x00020000
00245 
00246 
00247 /* Structure for saving instruction and alignment per-fragment data
00248    that will be written to the object file.  This structure is
00249    equivalent to the actual data that will be written out to the file
00250    but is easier to use.   We provide a conversion to file flags
00251    in frag_flags_to_number.  */
00252 
00253 typedef struct frag_flags_struct frag_flags;
00254 
00255 struct frag_flags_struct
00256 {
00257   /* is_literal should only be used after xtensa_move_literals.
00258      If you need to check if you are generating a literal fragment,
00259      then use the generating_literals global.  */
00260 
00261   unsigned is_literal : 1;
00262   unsigned is_insn : 1;
00263   unsigned is_data : 1;
00264   unsigned is_unreachable : 1;
00265 
00266   struct
00267   {
00268     unsigned is_loop_target : 1;
00269     unsigned is_branch_target : 1; /* Branch targets have a priority.  */
00270     unsigned bt_align_priority : 2;
00271 
00272     unsigned is_no_density : 1;
00273     /* no_longcalls flag does not need to be placed in the object file.  */
00274     /* is_specific_opcode implies no_transform.  */
00275     unsigned is_no_transform : 1;
00276 
00277     unsigned is_no_reorder : 1;
00278 
00279     /* Uses absolute literal addressing for l32r.  */
00280     unsigned is_abslit : 1;
00281   } insn;
00282   unsigned is_align : 1;
00283   unsigned alignment : 5;
00284 };
00285 
00286 
00287 /* Structure for saving information about a block of property data
00288    for frags that have the same flags.  */
00289 struct xtensa_block_info_struct
00290 {
00291   segT sec;
00292   bfd_vma offset;
00293   size_t size;
00294   frag_flags flags;
00295   struct xtensa_block_info_struct *next;
00296 };
00297 
00298 
00299 /* Structure for saving the current state before emitting literals.  */
00300 typedef struct emit_state_struct
00301 {
00302   const char *name;
00303   segT now_seg;
00304   subsegT now_subseg;
00305   int generating_literals;
00306 } emit_state;
00307 
00308 
00309 /* Opcode placement information */
00310 
00311 typedef unsigned long long bitfield;
00312 #define bit_is_set(bit, bf) ((bf) & (0x01ll << (bit)))
00313 #define set_bit(bit, bf)    ((bf) |= (0x01ll << (bit)))
00314 #define clear_bit(bit, bf)  ((bf) &= ~(0x01ll << (bit)))
00315 
00316 #define MAX_FORMATS 32
00317 
00318 typedef struct op_placement_info_struct
00319 {
00320   int num_formats;
00321   /* A number describing how restrictive the issue is for this
00322      opcode.  For example, an opcode that fits lots of different
00323      formats has a high freedom, as does an opcode that fits
00324      only one format but many slots in that format.  The most
00325      restrictive is the opcode that fits only one slot in one
00326      format.  */
00327   int issuef;
00328   xtensa_format narrowest;
00329   char narrowest_size;
00330   char narrowest_slot;
00331 
00332   /* formats is a bitfield with the Nth bit set
00333      if the opcode fits in the Nth xtensa_format.  */
00334   bitfield formats;
00335 
00336   /* slots[N]'s Mth bit is set if the op fits in the
00337      Mth slot of the Nth xtensa_format.  */
00338   bitfield slots[MAX_FORMATS];
00339 
00340   /* A count of the number of slots in a given format
00341      an op can fit (i.e., the bitcount of the slot field above).  */
00342   char slots_in_format[MAX_FORMATS];
00343 
00344 } op_placement_info, *op_placement_info_table;
00345 
00346 op_placement_info_table op_placement_table;
00347 
00348 
00349 /* Extra expression types.  */
00350 
00351 #define O_pltrel     O_md1  /* like O_symbol but use a PLT reloc */
00352 #define O_hi16              O_md2  /* use high 16 bits of symbolic value */
00353 #define O_lo16              O_md3  /* use low 16 bits of symbolic value */
00354 
00355 struct suffix_reloc_map
00356 {
00357   char *suffix;
00358   int length;
00359   bfd_reloc_code_real_type reloc;
00360   unsigned char operator;
00361 };
00362 
00363 #define SUFFIX_MAP(str, reloc, op) { str, sizeof (str) - 1, reloc, op }
00364 
00365 static struct suffix_reloc_map suffix_relocs[] =
00366 {
00367   SUFFIX_MAP ("l",   BFD_RELOC_LO16,                    O_lo16),
00368   SUFFIX_MAP ("h",   BFD_RELOC_HI16,                    O_hi16),
00369   SUFFIX_MAP ("plt", BFD_RELOC_XTENSA_PLT,              O_pltrel),
00370   { (char *) 0, 0,   BFD_RELOC_UNUSED,           0 }
00371 };
00372 
00373 
00374 /* Directives.  */
00375 
00376 typedef enum
00377 {
00378   directive_none = 0,
00379   directive_literal,
00380   directive_density,
00381   directive_transform,
00382   directive_freeregs,
00383   directive_longcalls,
00384   directive_literal_prefix,
00385   directive_schedule,
00386   directive_absolute_literals,
00387   directive_last_directive
00388 } directiveE;
00389 
00390 typedef struct
00391 {
00392   const char *name;
00393   bfd_boolean can_be_negated;
00394 } directive_infoS;
00395 
00396 const directive_infoS directive_info[] =
00397 {
00398   { "none",          FALSE },
00399   { "literal",              FALSE },
00400   { "density",              TRUE },
00401   { "transform",     TRUE },
00402   { "freeregs",             FALSE },
00403   { "longcalls",     TRUE },
00404   { "literal_prefix",       FALSE },
00405   { "schedule",             TRUE },
00406   { "absolute-literals", TRUE }
00407 };
00408 
00409 bfd_boolean directive_state[] =
00410 {
00411   FALSE,                    /* none */
00412   FALSE,                    /* literal */
00413 #if !XCHAL_HAVE_DENSITY
00414   FALSE,                    /* density */
00415 #else
00416   TRUE,                            /* density */
00417 #endif
00418   TRUE,                            /* transform */
00419   FALSE,                    /* freeregs */
00420   FALSE,                    /* longcalls */
00421   FALSE,                    /* literal_prefix */
00422   FALSE,                    /* schedule */
00423 #if XSHAL_USE_ABSOLUTE_LITERALS
00424   TRUE                      /* absolute_literals */
00425 #else
00426   FALSE                            /* absolute_literals */
00427 #endif
00428 };
00429 
00430 
00431 /* Directive functions.  */
00432 
00433 static void xtensa_begin_directive (int);
00434 static void xtensa_end_directive (int);
00435 static void xtensa_literal_prefix (void);
00436 static void xtensa_literal_position (int);
00437 static void xtensa_literal_pseudo (int);
00438 static void xtensa_frequency_pseudo (int);
00439 static void xtensa_elf_cons (int);
00440 
00441 /* Parsing and Idiom Translation.  */
00442 
00443 static bfd_reloc_code_real_type xtensa_elf_suffix (char **, expressionS *);
00444 
00445 /* Various Other Internal Functions.  */
00446 
00447 extern bfd_boolean xg_is_single_relaxable_insn (TInsn *, TInsn *, bfd_boolean);
00448 static bfd_boolean xg_build_to_insn (TInsn *, TInsn *, BuildInstr *);
00449 static void xtensa_mark_literal_pool_location (void);
00450 static addressT get_expanded_loop_offset (xtensa_opcode);
00451 static fragS *get_literal_pool_location (segT);
00452 static void set_literal_pool_location (segT, fragS *);
00453 static void xtensa_set_frag_assembly_state (fragS *);
00454 static void finish_vinsn (vliw_insn *);
00455 static bfd_boolean emit_single_op (TInsn *);
00456 static int total_frag_text_expansion (fragS *);
00457 
00458 /* Alignment Functions.  */
00459 
00460 static int get_text_align_power (unsigned);
00461 static int get_text_align_max_fill_size (int, bfd_boolean, bfd_boolean);
00462 static int branch_align_power (segT);
00463 
00464 /* Helpers for xtensa_relax_frag().  */
00465 
00466 static long relax_frag_add_nop (fragS *);
00467 
00468 /* Accessors for additional per-subsegment information.  */
00469 
00470 static unsigned get_last_insn_flags (segT, subsegT);
00471 static void set_last_insn_flags (segT, subsegT, unsigned, bfd_boolean);
00472 static float get_subseg_total_freq (segT, subsegT);
00473 static float get_subseg_target_freq (segT, subsegT);
00474 static void set_subseg_freq (segT, subsegT, float, float);
00475 
00476 /* Segment list functions.  */
00477 
00478 static void xtensa_move_literals (void);
00479 static void xtensa_reorder_segments (void);
00480 static void xtensa_switch_to_literal_fragment (emit_state *);
00481 static void xtensa_switch_to_non_abs_literal_fragment (emit_state *);
00482 static void xtensa_switch_section_emit_state (emit_state *, segT, subsegT);
00483 static void xtensa_restore_emit_state (emit_state *);
00484 static segT cache_literal_section (bfd_boolean);
00485 
00486 /* Import from elf32-xtensa.c in BFD library.  */
00487 
00488 extern asection *xtensa_get_property_section (asection *, const char *);
00489 
00490 /* op_placement_info functions.  */
00491 
00492 static void init_op_placement_info_table (void);
00493 extern bfd_boolean opcode_fits_format_slot (xtensa_opcode, xtensa_format, int);
00494 static int xg_get_single_size (xtensa_opcode);
00495 static xtensa_format xg_get_single_format (xtensa_opcode);
00496 static int xg_get_single_slot (xtensa_opcode);
00497 
00498 /* TInsn and IStack functions.  */
00499 
00500 static bfd_boolean tinsn_has_symbolic_operands (const TInsn *);
00501 static bfd_boolean tinsn_has_invalid_symbolic_operands (const TInsn *);
00502 static bfd_boolean tinsn_has_complex_operands (const TInsn *);
00503 static bfd_boolean tinsn_to_insnbuf (TInsn *, xtensa_insnbuf);
00504 static bfd_boolean tinsn_check_arguments (const TInsn *);
00505 static void tinsn_from_chars (TInsn *, char *, int);
00506 static void tinsn_immed_from_frag (TInsn *, fragS *, int);
00507 static int get_num_stack_text_bytes (IStack *);
00508 static int get_num_stack_literal_bytes (IStack *);
00509 
00510 /* vliw_insn functions.  */
00511 
00512 static void xg_init_vinsn (vliw_insn *);
00513 static void xg_clear_vinsn (vliw_insn *);
00514 static bfd_boolean vinsn_has_specific_opcodes (vliw_insn *);
00515 static void xg_free_vinsn (vliw_insn *);
00516 static bfd_boolean vinsn_to_insnbuf
00517   (vliw_insn *, char *, fragS *, bfd_boolean);
00518 static void vinsn_from_chars (vliw_insn *, char *);
00519 
00520 /* Expression Utilities.  */
00521 
00522 bfd_boolean expr_is_const (const expressionS *);
00523 offsetT get_expr_const (const expressionS *);
00524 void set_expr_const (expressionS *, offsetT);
00525 bfd_boolean expr_is_register (const expressionS *);
00526 offsetT get_expr_register (const expressionS *);
00527 void set_expr_symbol_offset (expressionS *, symbolS *, offsetT);
00528 bfd_boolean expr_is_equal (expressionS *, expressionS *);
00529 static void copy_expr (expressionS *, const expressionS *);
00530 
00531 /* Section renaming.  */
00532 
00533 static void build_section_rename (const char *);
00534 
00535 
00536 /* ISA imported from bfd.  */
00537 extern xtensa_isa xtensa_default_isa;
00538 
00539 extern int target_big_endian;
00540 
00541 static xtensa_opcode xtensa_addi_opcode;
00542 static xtensa_opcode xtensa_addmi_opcode;
00543 static xtensa_opcode xtensa_call0_opcode;
00544 static xtensa_opcode xtensa_call4_opcode;
00545 static xtensa_opcode xtensa_call8_opcode;
00546 static xtensa_opcode xtensa_call12_opcode;
00547 static xtensa_opcode xtensa_callx0_opcode;
00548 static xtensa_opcode xtensa_callx4_opcode;
00549 static xtensa_opcode xtensa_callx8_opcode;
00550 static xtensa_opcode xtensa_callx12_opcode;
00551 static xtensa_opcode xtensa_const16_opcode;
00552 static xtensa_opcode xtensa_entry_opcode;
00553 static xtensa_opcode xtensa_movi_opcode;
00554 static xtensa_opcode xtensa_movi_n_opcode;
00555 static xtensa_opcode xtensa_isync_opcode;
00556 static xtensa_opcode xtensa_jx_opcode;
00557 static xtensa_opcode xtensa_l32r_opcode;
00558 static xtensa_opcode xtensa_loop_opcode;
00559 static xtensa_opcode xtensa_loopnez_opcode;
00560 static xtensa_opcode xtensa_loopgtz_opcode;
00561 static xtensa_opcode xtensa_nop_opcode;
00562 static xtensa_opcode xtensa_nop_n_opcode;
00563 static xtensa_opcode xtensa_or_opcode;
00564 static xtensa_opcode xtensa_ret_opcode;
00565 static xtensa_opcode xtensa_ret_n_opcode;
00566 static xtensa_opcode xtensa_retw_opcode;
00567 static xtensa_opcode xtensa_retw_n_opcode;
00568 static xtensa_opcode xtensa_rsr_lcount_opcode;
00569 static xtensa_opcode xtensa_waiti_opcode;
00570 
00571 
00572 /* Command-line Options.  */
00573 
00574 bfd_boolean use_literal_section = TRUE;
00575 static bfd_boolean align_targets = TRUE;
00576 static bfd_boolean warn_unaligned_branch_targets = FALSE;
00577 static bfd_boolean has_a0_b_retw = FALSE;
00578 static bfd_boolean workaround_a0_b_retw = FALSE;
00579 static bfd_boolean workaround_b_j_loop_end = FALSE;
00580 static bfd_boolean workaround_short_loop = FALSE;
00581 static bfd_boolean maybe_has_short_loop = FALSE;
00582 static bfd_boolean workaround_close_loop_end = FALSE;
00583 static bfd_boolean maybe_has_close_loop_end = FALSE;
00584 static bfd_boolean enforce_three_byte_loop_align = FALSE;
00585 
00586 /* When workaround_short_loops is TRUE, all loops with early exits must
00587    have at least 3 instructions.  workaround_all_short_loops is a modifier
00588    to the workaround_short_loop flag.  In addition to the
00589    workaround_short_loop actions, all straightline loopgtz and loopnez
00590    must have at least 3 instructions.  */
00591 
00592 static bfd_boolean workaround_all_short_loops = FALSE;
00593 
00594 
00595 static void
00596 xtensa_setup_hw_workarounds (int earliest, int latest)
00597 {
00598   if (earliest > latest)
00599     as_fatal (_("illegal range of target hardware versions"));
00600 
00601   /* Enable all workarounds for pre-T1050.0 hardware.  */
00602   if (earliest < 105000 || latest < 105000)
00603     {
00604       workaround_a0_b_retw |= TRUE;
00605       workaround_b_j_loop_end |= TRUE;
00606       workaround_short_loop |= TRUE;
00607       workaround_close_loop_end |= TRUE;
00608       workaround_all_short_loops |= TRUE;
00609       enforce_three_byte_loop_align = TRUE;
00610     }
00611 }
00612 
00613 
00614 enum
00615 {
00616   option_density = OPTION_MD_BASE,
00617   option_no_density,
00618 
00619   option_relax,
00620   option_no_relax,
00621 
00622   option_link_relax,
00623   option_no_link_relax,
00624 
00625   option_generics,
00626   option_no_generics,
00627 
00628   option_transform,
00629   option_no_transform,
00630 
00631   option_text_section_literals,
00632   option_no_text_section_literals,
00633 
00634   option_absolute_literals,
00635   option_no_absolute_literals,
00636 
00637   option_align_targets,
00638   option_no_align_targets,
00639 
00640   option_warn_unaligned_targets,
00641 
00642   option_longcalls,
00643   option_no_longcalls,
00644 
00645   option_workaround_a0_b_retw,
00646   option_no_workaround_a0_b_retw,
00647 
00648   option_workaround_b_j_loop_end,
00649   option_no_workaround_b_j_loop_end,
00650 
00651   option_workaround_short_loop,
00652   option_no_workaround_short_loop,
00653 
00654   option_workaround_all_short_loops,
00655   option_no_workaround_all_short_loops,
00656 
00657   option_workaround_close_loop_end,
00658   option_no_workaround_close_loop_end,
00659 
00660   option_no_workarounds,
00661 
00662   option_rename_section_name,
00663 
00664   option_prefer_l32r,
00665   option_prefer_const16,
00666 
00667   option_target_hardware
00668 };
00669 
00670 const char *md_shortopts = "";
00671 
00672 struct option md_longopts[] =
00673 {
00674   { "density", no_argument, NULL, option_density },
00675   { "no-density", no_argument, NULL, option_no_density },
00676 
00677   /* Both "relax" and "generics" are deprecated and treated as equivalent
00678      to the "transform" option.  */
00679   { "relax", no_argument, NULL, option_relax },
00680   { "no-relax", no_argument, NULL, option_no_relax },
00681   { "generics", no_argument, NULL, option_generics },
00682   { "no-generics", no_argument, NULL, option_no_generics },
00683 
00684   { "transform", no_argument, NULL, option_transform },
00685   { "no-transform", no_argument, NULL, option_no_transform },
00686   { "text-section-literals", no_argument, NULL, option_text_section_literals },
00687   { "no-text-section-literals", no_argument, NULL,
00688     option_no_text_section_literals },
00689   { "absolute-literals", no_argument, NULL, option_absolute_literals },
00690   { "no-absolute-literals", no_argument, NULL, option_no_absolute_literals },
00691   /* This option was changed from -align-target to -target-align
00692      because it conflicted with the "-al" option.  */
00693   { "target-align", no_argument, NULL, option_align_targets },
00694   { "no-target-align", no_argument, NULL, option_no_align_targets },
00695   { "warn-unaligned-targets", no_argument, NULL,
00696     option_warn_unaligned_targets },
00697   { "longcalls", no_argument, NULL, option_longcalls },
00698   { "no-longcalls", no_argument, NULL, option_no_longcalls },
00699 
00700   { "no-workaround-a0-b-retw", no_argument, NULL,
00701     option_no_workaround_a0_b_retw },
00702   { "workaround-a0-b-retw", no_argument, NULL, option_workaround_a0_b_retw },
00703 
00704   { "no-workaround-b-j-loop-end", no_argument, NULL,
00705     option_no_workaround_b_j_loop_end },
00706   { "workaround-b-j-loop-end", no_argument, NULL,
00707     option_workaround_b_j_loop_end },
00708 
00709   { "no-workaround-short-loops", no_argument, NULL,
00710     option_no_workaround_short_loop },
00711   { "workaround-short-loops", no_argument, NULL,
00712     option_workaround_short_loop },
00713 
00714   { "no-workaround-all-short-loops", no_argument, NULL,
00715     option_no_workaround_all_short_loops },
00716   { "workaround-all-short-loop", no_argument, NULL,
00717     option_workaround_all_short_loops },
00718 
00719   { "prefer-l32r", no_argument, NULL, option_prefer_l32r },
00720   { "prefer-const16", no_argument, NULL, option_prefer_const16 },
00721 
00722   { "no-workarounds", no_argument, NULL, option_no_workarounds },
00723 
00724   { "no-workaround-close-loop-end", no_argument, NULL,
00725     option_no_workaround_close_loop_end },
00726   { "workaround-close-loop-end", no_argument, NULL,
00727     option_workaround_close_loop_end },
00728 
00729   { "rename-section", required_argument, NULL, option_rename_section_name },
00730 
00731   { "link-relax", no_argument, NULL, option_link_relax },
00732   { "no-link-relax", no_argument, NULL, option_no_link_relax },
00733 
00734   { "target-hardware", required_argument, NULL, option_target_hardware },
00735 
00736   { NULL, no_argument, NULL, 0 }
00737 };
00738 
00739 size_t md_longopts_size = sizeof md_longopts;
00740 
00741 
00742 int
00743 md_parse_option (int c, char *arg)
00744 {
00745   switch (c)
00746     {
00747     case option_density:
00748       as_warn (_("--density option is ignored"));
00749       return 1;
00750     case option_no_density:
00751       as_warn (_("--no-density option is ignored"));
00752       return 1;
00753     case option_link_relax:
00754       linkrelax = 1;
00755       return 1;
00756     case option_no_link_relax:
00757       linkrelax = 0;
00758       return 1;
00759     case option_generics:
00760       as_warn (_("--generics is deprecated; use --transform instead"));
00761       return md_parse_option (option_transform, arg);
00762     case option_no_generics:
00763       as_warn (_("--no-generics is deprecated; use --no-transform instead"));
00764       return md_parse_option (option_no_transform, arg);
00765     case option_relax:
00766       as_warn (_("--relax is deprecated; use --transform instead"));
00767       return md_parse_option (option_transform, arg);
00768     case option_no_relax:
00769       as_warn (_("--no-relax is deprecated; use --no-transform instead"));
00770       return md_parse_option (option_no_transform, arg);
00771     case option_longcalls:
00772       directive_state[directive_longcalls] = TRUE;
00773       return 1;
00774     case option_no_longcalls:
00775       directive_state[directive_longcalls] = FALSE;
00776       return 1;
00777     case option_text_section_literals:
00778       use_literal_section = FALSE;
00779       return 1;
00780     case option_no_text_section_literals:
00781       use_literal_section = TRUE;
00782       return 1;
00783     case option_absolute_literals:
00784       if (!absolute_literals_supported)
00785        {
00786          as_fatal (_("--absolute-literals option not supported in this Xtensa configuration"));
00787          return 0;
00788        }
00789       directive_state[directive_absolute_literals] = TRUE;
00790       return 1;
00791     case option_no_absolute_literals:
00792       directive_state[directive_absolute_literals] = FALSE;
00793       return 1;
00794 
00795     case option_workaround_a0_b_retw:
00796       workaround_a0_b_retw = TRUE;
00797       return 1;
00798     case option_no_workaround_a0_b_retw:
00799       workaround_a0_b_retw = FALSE;
00800       return 1;
00801     case option_workaround_b_j_loop_end:
00802       workaround_b_j_loop_end = TRUE;
00803       return 1;
00804     case option_no_workaround_b_j_loop_end:
00805       workaround_b_j_loop_end = FALSE;
00806       return 1;
00807 
00808     case option_workaround_short_loop:
00809       workaround_short_loop = TRUE;
00810       return 1;
00811     case option_no_workaround_short_loop:
00812       workaround_short_loop = FALSE;
00813       return 1;
00814 
00815     case option_workaround_all_short_loops:
00816       workaround_all_short_loops = TRUE;
00817       return 1;
00818     case option_no_workaround_all_short_loops:
00819       workaround_all_short_loops = FALSE;
00820       return 1;
00821 
00822     case option_workaround_close_loop_end:
00823       workaround_close_loop_end = TRUE;
00824       return 1;
00825     case option_no_workaround_close_loop_end:
00826       workaround_close_loop_end = FALSE;
00827       return 1;
00828 
00829     case option_no_workarounds:
00830       workaround_a0_b_retw = FALSE;
00831       workaround_b_j_loop_end = FALSE;
00832       workaround_short_loop = FALSE;
00833       workaround_all_short_loops = FALSE;
00834       workaround_close_loop_end = FALSE;
00835       return 1;
00836 
00837     case option_align_targets:
00838       align_targets = TRUE;
00839       return 1;
00840     case option_no_align_targets:
00841       align_targets = FALSE;
00842       return 1;
00843 
00844     case option_warn_unaligned_targets:
00845       warn_unaligned_branch_targets = TRUE;
00846       return 1;
00847 
00848     case option_rename_section_name:
00849       build_section_rename (arg);
00850       return 1;
00851 
00852     case 'Q':
00853       /* -Qy, -Qn: SVR4 arguments controlling whether a .comment section
00854          should be emitted or not.  FIXME: Not implemented.  */
00855       return 1;
00856 
00857     case option_prefer_l32r:
00858       if (prefer_const16)
00859        as_fatal (_("prefer-l32r conflicts with prefer-const16"));
00860       prefer_l32r = 1;
00861       return 1;
00862 
00863     case option_prefer_const16:
00864       if (prefer_l32r)
00865        as_fatal (_("prefer-const16 conflicts with prefer-l32r"));
00866       prefer_const16 = 1;
00867       return 1;
00868 
00869     case option_target_hardware:
00870       {
00871        int earliest, latest = 0;
00872        if (*arg == 0 || *arg == '-')
00873          as_fatal (_("invalid target hardware version"));
00874 
00875        earliest = strtol (arg, &arg, 0);
00876 
00877        if (*arg == 0)
00878          latest = earliest;
00879        else if (*arg == '-')
00880          {
00881            if (*++arg == 0)
00882              as_fatal (_("invalid target hardware version"));
00883            latest = strtol (arg, &arg, 0);
00884          }
00885        if (*arg != 0)
00886          as_fatal (_("invalid target hardware version"));
00887 
00888        xtensa_setup_hw_workarounds (earliest, latest);
00889        return 1;
00890       }
00891 
00892     case option_transform:
00893       /* This option has no affect other than to use the defaults,
00894         which are already set.  */
00895       return 1;
00896 
00897     case option_no_transform:
00898       /* This option turns off all transformations of any kind.
00899         However, because we want to preserve the state of other
00900         directives, we only change its own field.  Thus, before
00901         you perform any transformation, always check if transform
00902         is available.  If you use the functions we provide for this
00903         purpose, you will be ok.  */
00904       directive_state[directive_transform] = FALSE;
00905       return 1;
00906 
00907     default:
00908       return 0;
00909     }
00910 }
00911 
00912 
00913 void
00914 md_show_usage (FILE *stream)
00915 {
00916   fputs ("\n\
00917 Xtensa options:\n\
00918   --[no-]text-section-literals\n\
00919                           [Do not] put literals in the text section\n\
00920   --[no-]absolute-literals\n\
00921                           [Do not] default to use non-PC-relative literals\n\
00922   --[no-]target-align     [Do not] try to align branch targets\n\
00923   --[no-]longcalls        [Do not] emit 32-bit call sequences\n\
00924   --[no-]transform        [Do not] transform instructions\n\
00925   --rename-section old=new Rename section 'old' to 'new'\n", stream);
00926 }
00927 
00928 
00929 /* Functions related to the list of current label symbols.  */
00930 
00931 static void
00932 xtensa_add_insn_label (symbolS *sym)
00933 {
00934   sym_list *l;
00935 
00936   if (!free_insn_labels)
00937     l = (sym_list *) xmalloc (sizeof (sym_list));
00938   else
00939     {
00940       l = free_insn_labels;
00941       free_insn_labels = l->next;
00942     }
00943 
00944   l->sym = sym;
00945   l->next = insn_labels;
00946   insn_labels = l;
00947 }
00948 
00949 
00950 static void
00951 xtensa_clear_insn_labels (void)
00952 {
00953   sym_list **pl;
00954 
00955   for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
00956     ;
00957   *pl = insn_labels;
00958   insn_labels = NULL;
00959 }
00960 
00961 
00962 static void
00963 xtensa_move_labels (fragS *new_frag, valueT new_offset)
00964 {
00965   sym_list *lit;
00966 
00967   for (lit = insn_labels; lit; lit = lit->next)
00968     {
00969       symbolS *lit_sym = lit->sym;
00970       S_SET_VALUE (lit_sym, new_offset);
00971       symbol_set_frag (lit_sym, new_frag);
00972     }
00973 }
00974 
00975 
00976 /* Directive data and functions.  */
00977 
00978 typedef struct state_stackS_struct
00979 {
00980   directiveE directive;
00981   bfd_boolean negated;
00982   bfd_boolean old_state;
00983   const char *file;
00984   unsigned int line;
00985   const void *datum;
00986   struct state_stackS_struct *prev;
00987 } state_stackS;
00988 
00989 state_stackS *directive_state_stack;
00990 
00991 const pseudo_typeS md_pseudo_table[] =
00992 {
00993   { "align", s_align_bytes, 0 }, /* Defaulting is invalid (0).  */
00994   { "literal_position", xtensa_literal_position, 0 },
00995   { "frame", s_ignore, 0 }, /* Formerly used for STABS debugging.  */
00996   { "long", xtensa_elf_cons, 4 },
00997   { "word", xtensa_elf_cons, 4 },
00998   { "short", xtensa_elf_cons, 2 },
00999   { "begin", xtensa_begin_directive, 0 },
01000   { "end", xtensa_end_directive, 0 },
01001   { "literal", xtensa_literal_pseudo, 0 },
01002   { "frequency", xtensa_frequency_pseudo, 0 },
01003   { NULL, 0, 0 },
01004 };
01005 
01006 
01007 static bfd_boolean
01008 use_transform (void)
01009 {
01010   /* After md_end, you should be checking frag by frag, rather
01011      than state directives.  */
01012   assert (!past_xtensa_end);
01013   return directive_state[directive_transform];
01014 }
01015 
01016 
01017 static bfd_boolean
01018 do_align_targets (void)
01019 {
01020   /* Do not use this function after md_end; just look at align_targets
01021      instead.  There is no target-align directive, so alignment is either
01022      enabled for all frags or not done at all.  */
01023   assert (!past_xtensa_end);
01024   return align_targets && use_transform ();
01025 }
01026 
01027 
01028 static void
01029 directive_push (directiveE directive, bfd_boolean negated, const void *datum)
01030 {
01031   char *file;
01032   unsigned int line;
01033   state_stackS *stack = (state_stackS *) xmalloc (sizeof (state_stackS));
01034 
01035   as_where (&file, &line);
01036 
01037   stack->directive = directive;
01038   stack->negated = negated;
01039   stack->old_state = directive_state[directive];
01040   stack->file = file;
01041   stack->line = line;
01042   stack->datum = datum;
01043   stack->prev = directive_state_stack;
01044   directive_state_stack = stack;
01045 
01046   directive_state[directive] = !negated;
01047 }
01048 
01049 
01050 static void
01051 directive_pop (directiveE *directive,
01052               bfd_boolean *negated,
01053               const char **file,
01054               unsigned int *line,
01055               const void **datum)
01056 {
01057   state_stackS *top = directive_state_stack;
01058 
01059   if (!directive_state_stack)
01060     {
01061       as_bad (_("unmatched end directive"));
01062       *directive = directive_none;
01063       return;
01064     }
01065 
01066   directive_state[directive_state_stack->directive] = top->old_state;
01067   *directive = top->directive;
01068   *negated = top->negated;
01069   *file = top->file;
01070   *line = top->line;
01071   *datum = top->datum;
01072   directive_state_stack = top->prev;
01073   free (top);
01074 }
01075 
01076 
01077 static void
01078 directive_balance (void)
01079 {
01080   while (directive_state_stack)
01081     {
01082       directiveE directive;
01083       bfd_boolean negated;
01084       const char *file;
01085       unsigned int line;
01086       const void *datum;
01087 
01088       directive_pop (&directive, &negated, &file, &line, &datum);
01089       as_warn_where ((char *) file, line,
01090                    _(".begin directive with no matching .end directive"));
01091     }
01092 }
01093 
01094 
01095 static bfd_boolean
01096 inside_directive (directiveE dir)
01097 {
01098   state_stackS *top = directive_state_stack;
01099 
01100   while (top && top->directive != dir)
01101     top = top->prev;
01102 
01103   return (top != NULL);
01104 }
01105 
01106 
01107 static void
01108 get_directive (directiveE *directive, bfd_boolean *negated)
01109 {
01110   int len;
01111   unsigned i;
01112   char *directive_string;
01113 
01114   if (strncmp (input_line_pointer, "no-", 3) != 0)
01115     *negated = FALSE;
01116   else
01117     {
01118       *negated = TRUE;
01119       input_line_pointer += 3;
01120     }
01121 
01122   len = strspn (input_line_pointer,
01123               "abcdefghijklmnopqrstuvwxyz_-/0123456789.");
01124 
01125   /* This code is a hack to make .begin [no-][generics|relax] exactly
01126      equivalent to .begin [no-]transform.  We should remove it when
01127      we stop accepting those options.  */
01128 
01129   if (strncmp (input_line_pointer, "generics", strlen ("generics")) == 0)
01130     {
01131       as_warn (_("[no-]generics is deprecated; use [no-]transform instead"));
01132       directive_string = "transform";
01133     }
01134   else if (strncmp (input_line_pointer, "relax", strlen ("relax")) == 0)
01135     {
01136       as_warn (_("[no-]relax is deprecated; use [no-]transform instead"));
01137       directive_string = "transform";
01138     }
01139   else
01140     directive_string = input_line_pointer;
01141 
01142   for (i = 0; i < sizeof (directive_info) / sizeof (*directive_info); ++i)
01143     {
01144       if (strncmp (directive_string, directive_info[i].name, len) == 0)
01145        {
01146          input_line_pointer += len;
01147          *directive = (directiveE) i;
01148          if (*negated && !directive_info[i].can_be_negated)
01149            as_bad (_("directive %s cannot be negated"),
01150                   directive_info[i].name);
01151          return;
01152        }
01153     }
01154 
01155   as_bad (_("unknown directive"));
01156   *directive = (directiveE) XTENSA_UNDEFINED;
01157 }
01158 
01159 
01160 static void
01161 xtensa_begin_directive (int ignore ATTRIBUTE_UNUSED)
01162 {
01163   directiveE directive;
01164   bfd_boolean negated;
01165   emit_state *state;
01166   lit_state *ls;
01167 
01168   get_directive (&directive, &negated);
01169   if (directive == (directiveE) XTENSA_UNDEFINED)
01170     {
01171       discard_rest_of_line ();
01172       return;
01173     }
01174 
01175   if (cur_vinsn.inside_bundle)
01176     as_bad (_("directives are not valid inside bundles"));
01177 
01178   switch (directive)
01179     {
01180     case directive_literal:
01181       if (!inside_directive (directive_literal))
01182        {
01183          /* Previous labels go with whatever follows this directive, not with
01184             the literal, so save them now.  */
01185          saved_insn_labels = insn_labels;
01186          insn_labels = NULL;
01187        }
01188       as_warn (_(".begin literal is deprecated; use .literal instead"));
01189       state = (emit_state *) xmalloc (sizeof (emit_state));
01190       xtensa_switch_to_literal_fragment (state);
01191       directive_push (directive_literal, negated, state);
01192       break;
01193 
01194     case directive_literal_prefix:
01195       /* Have to flush pending output because a movi relaxed to an l32r
01196         might produce a literal.  */
01197       md_flush_pending_output ();
01198       /* Check to see if the current fragment is a literal
01199         fragment.  If it is, then this operation is not allowed.  */
01200       if (generating_literals)
01201        {
01202          as_bad (_("cannot set literal_prefix inside literal fragment"));
01203          return;
01204        }
01205 
01206       /* Allocate the literal state for this section and push
01207         onto the directive stack.  */
01208       ls = xmalloc (sizeof (lit_state));
01209       assert (ls);
01210 
01211       *ls = default_lit_sections;
01212       directive_push (directive_literal_prefix, negated, ls);
01213 
01214       /* Process the new prefix.  */
01215       xtensa_literal_prefix ();
01216       break;
01217 
01218     case directive_freeregs:
01219       /* This information is currently unused, but we'll accept the statement
01220          and just discard the rest of the line.  This won't check the syntax,
01221          but it will accept every correct freeregs directive.  */
01222       input_line_pointer += strcspn (input_line_pointer, "\n");
01223       directive_push (directive_freeregs, negated, 0);
01224       break;
01225 
01226     case directive_schedule:
01227       md_flush_pending_output ();
01228       frag_var (rs_fill, 0, 0, frag_now->fr_subtype,
01229               frag_now->fr_symbol, frag_now->fr_offset, NULL);
01230       directive_push (directive_schedule, negated, 0);
01231       xtensa_set_frag_assembly_state (frag_now);
01232       break;
01233 
01234     case directive_density:
01235       as_warn (_(".begin [no-]density is ignored"));
01236       break;
01237 
01238     case directive_absolute_literals:
01239       md_flush_pending_output ();
01240       if (!absolute_literals_supported && !negated)
01241        {
01242          as_warn (_("Xtensa absolute literals option not supported; ignored"));
01243          break;
01244        }
01245       xtensa_set_frag_assembly_state (frag_now);
01246       directive_push (directive, negated, 0);
01247       break;
01248 
01249     default:
01250       md_flush_pending_output ();
01251       xtensa_set_frag_assembly_state (frag_now);
01252       directive_push (directive, negated, 0);
01253       break;
01254     }
01255 
01256   demand_empty_rest_of_line ();
01257 }
01258 
01259 
01260 static void
01261 xtensa_end_directive (int ignore ATTRIBUTE_UNUSED)
01262 {
01263   directiveE begin_directive, end_directive;
01264   bfd_boolean begin_negated, end_negated;
01265   const char *file;
01266   unsigned int line;
01267   emit_state *state;
01268   emit_state **state_ptr;
01269   lit_state *s;
01270 
01271   if (cur_vinsn.inside_bundle)
01272     as_bad (_("directives are not valid inside bundles"));
01273 
01274   get_directive (&end_directive, &end_negated);
01275 
01276   md_flush_pending_output ();
01277 
01278   switch (end_directive)
01279     {
01280     case (directiveE) XTENSA_UNDEFINED:
01281       discard_rest_of_line ();
01282       return;
01283 
01284     case directive_density:
01285       as_warn (_(".end [no-]density is ignored"));
01286       demand_empty_rest_of_line ();
01287       break;
01288 
01289     case directive_absolute_literals:
01290       if (!absolute_literals_supported && !end_negated)
01291        {
01292          as_warn (_("Xtensa absolute literals option not supported; ignored"));
01293          demand_empty_rest_of_line ();
01294          return;
01295        }
01296       break;
01297 
01298     default:
01299       break;
01300     }
01301 
01302   state_ptr = &state; /* use state_ptr to avoid type-punning warning */
01303   directive_pop (&begin_directive, &begin_negated, &file, &line,
01304                (const void **) state_ptr);
01305 
01306   if (begin_directive != directive_none)
01307     {
01308       if (begin_directive != end_directive || begin_negated != end_negated)
01309        {
01310          as_bad (_("does not match begin %s%s at %s:%d"),
01311                 begin_negated ? "no-" : "",
01312                 directive_info[begin_directive].name, file, line);
01313        }
01314       else
01315        {
01316          switch (end_directive)
01317            {
01318            case directive_literal:
01319              frag_var (rs_fill, 0, 0, 0, NULL, 0, NULL);
01320              xtensa_restore_emit_state (state);
01321              xtensa_set_frag_assembly_state (frag_now);
01322              free (state);
01323              if (!inside_directive (directive_literal))
01324               {
01325                 /* Restore the list of current labels.  */
01326                 xtensa_clear_insn_labels ();
01327                 insn_labels = saved_insn_labels;
01328               }
01329              break;
01330 
01331            case directive_literal_prefix:
01332              /* Restore the default collection sections from saved state.  */
01333              s = (lit_state *) state;
01334              assert (s);
01335              default_lit_sections = *s;
01336 
01337              /* Free the state storage.  */
01338              free (s->lit_prefix);
01339              free (s);
01340              break;
01341 
01342            case directive_schedule:
01343            case directive_freeregs:
01344              break;
01345 
01346            default:
01347              xtensa_set_frag_assembly_state (frag_now);
01348              break;
01349            }
01350        }
01351     }
01352 
01353   demand_empty_rest_of_line ();
01354 }
01355 
01356 
01357 /* Place an aligned literal fragment at the current location.  */
01358 
01359 static void
01360 xtensa_literal_position (int ignore ATTRIBUTE_UNUSED)
01361 {
01362   md_flush_pending_output ();
01363 
01364   if (inside_directive (directive_literal))
01365     as_warn (_(".literal_position inside literal directive; ignoring"));
01366   xtensa_mark_literal_pool_location ();
01367 
01368   demand_empty_rest_of_line ();
01369   xtensa_clear_insn_labels ();
01370 }
01371 
01372 
01373 /* Support .literal label, expr, ...  */
01374 
01375 static void
01376 xtensa_literal_pseudo (int ignored ATTRIBUTE_UNUSED)
01377 {
01378   emit_state state;
01379   char *p, *base_name;
01380   char c;
01381   segT dest_seg;
01382 
01383   if (inside_directive (directive_literal))
01384     {
01385       as_bad (_(".literal not allowed inside .begin literal region"));
01386       ignore_rest_of_line ();
01387       return;
01388     }
01389 
01390   md_flush_pending_output ();
01391 
01392   /* Previous labels go with whatever follows this directive, not with
01393      the literal, so save them now.  */
01394   saved_insn_labels = insn_labels;
01395   insn_labels = NULL;
01396 
01397   /* If we are using text-section literals, then this is the right value... */
01398   dest_seg = now_seg;
01399 
01400   base_name = input_line_pointer;
01401 
01402   xtensa_switch_to_literal_fragment (&state);
01403 
01404   /* ...but if we aren't using text-section-literals, then we
01405      need to put them in the section we just switched to.  */
01406   if (use_literal_section || directive_state[directive_absolute_literals])
01407     dest_seg = now_seg;
01408 
01409   /* All literals are aligned to four-byte boundaries.  */
01410   frag_align (2, 0, 0);
01411   record_alignment (now_seg, 2);
01412 
01413   c = get_symbol_end ();
01414   /* Just after name is now '\0'.  */
01415   p = input_line_pointer;
01416   *p = c;
01417   SKIP_WHITESPACE ();
01418 
01419   if (*input_line_pointer != ',' && *input_line_pointer != ':')
01420     {
01421       as_bad (_("expected comma or colon after symbol name; "
01422               "rest of line ignored"));
01423       ignore_rest_of_line ();
01424       xtensa_restore_emit_state (&state);
01425       return;
01426     }
01427   *p = 0;
01428 
01429   colon (base_name);
01430 
01431   *p = c;
01432   input_line_pointer++;            /* skip ',' or ':' */
01433 
01434   xtensa_elf_cons (4);
01435 
01436   xtensa_restore_emit_state (&state);
01437 
01438   /* Restore the list of current labels.  */
01439   xtensa_clear_insn_labels ();
01440   insn_labels = saved_insn_labels;
01441 }
01442 
01443 
01444 static void
01445 xtensa_literal_prefix (void)
01446 {
01447   char *name;
01448   int len;
01449 
01450   /* Parse the new prefix from the input_line_pointer.  */
01451   SKIP_WHITESPACE ();
01452   len = strspn (input_line_pointer,
01453               "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
01454               "abcdefghijklmnopqrstuvwxyz_/0123456789.$");
01455 
01456   /* Get a null-terminated copy of the name.  */
01457   name = xmalloc (len + 1);
01458   assert (name);
01459   strncpy (name, input_line_pointer, len);
01460   name[len] = 0;
01461 
01462   /* Skip the name in the input line.  */
01463   input_line_pointer += len;
01464 
01465   default_lit_sections.lit_prefix = name;
01466 
01467   /* Clear cached literal sections, since the prefix has changed.  */
01468   default_lit_sections.lit_seg = NULL;
01469   default_lit_sections.lit4_seg = NULL;
01470 }
01471 
01472 
01473 /* Support ".frequency branch_target_frequency fall_through_frequency".  */
01474 
01475 static void
01476 xtensa_frequency_pseudo (int ignored ATTRIBUTE_UNUSED)
01477 {
01478   float fall_through_f, target_f;
01479 
01480   fall_through_f = (float) strtod (input_line_pointer, &input_line_pointer);
01481   if (fall_through_f < 0)
01482     {
01483       as_bad (_("fall through frequency must be greater than 0"));
01484       ignore_rest_of_line ();
01485       return;
01486     }
01487 
01488   target_f = (float) strtod (input_line_pointer, &input_line_pointer);
01489   if (target_f < 0)
01490     {
01491       as_bad (_("branch target frequency must be greater than 0"));
01492       ignore_rest_of_line ();
01493       return;
01494     }
01495 
01496   set_subseg_freq (now_seg, now_subseg, target_f + fall_through_f, target_f);
01497 
01498   demand_empty_rest_of_line ();
01499 }
01500 
01501 
01502 /* Like normal .long/.short/.word, except support @plt, etc.
01503    Clobbers input_line_pointer, checks end-of-line.  */
01504 
01505 static void
01506 xtensa_elf_cons (int nbytes)
01507 {
01508   expressionS exp;
01509   bfd_reloc_code_real_type reloc;
01510 
01511   md_flush_pending_output ();
01512 
01513   if (cur_vinsn.inside_bundle)
01514     as_bad (_("directives are not valid inside bundles"));
01515 
01516   if (is_it_end_of_statement ())
01517     {
01518       demand_empty_rest_of_line ();
01519       return;
01520     }
01521 
01522   do
01523     {
01524       expression (&exp);
01525       if (exp.X_op == O_symbol
01526          && *input_line_pointer == '@'
01527          && ((reloc = xtensa_elf_suffix (&input_line_pointer, &exp))
01528              != BFD_RELOC_NONE))
01529        {
01530          reloc_howto_type *reloc_howto =
01531            bfd_reloc_type_lookup (stdoutput, reloc);
01532 
01533          if (reloc == BFD_RELOC_UNUSED || !reloc_howto)
01534            as_bad (_("unsupported relocation"));
01535          else if ((reloc >= BFD_RELOC_XTENSA_SLOT0_OP
01536                   && reloc <= BFD_RELOC_XTENSA_SLOT14_OP)
01537                  || (reloc >= BFD_RELOC_XTENSA_SLOT0_ALT
01538                      && reloc <= BFD_RELOC_XTENSA_SLOT14_ALT))
01539            as_bad (_("opcode-specific %s relocation used outside "
01540                     "an instruction"), reloc_howto->name);
01541          else if (nbytes != (int) bfd_get_reloc_size (reloc_howto))
01542            as_bad (_("%s relocations do not fit in %d bytes"),
01543                   reloc_howto->name, nbytes);
01544          else
01545            {
01546              char *p = frag_more ((int) nbytes);
01547              xtensa_set_frag_assembly_state (frag_now);
01548              fix_new_exp (frag_now, p - frag_now->fr_literal,
01549                         nbytes, &exp, 0, reloc);
01550            }
01551        }
01552       else
01553        emit_expr (&exp, (unsigned int) nbytes);
01554     }
01555   while (*input_line_pointer++ == ',');
01556 
01557   input_line_pointer--;            /* Put terminator back into stream.  */
01558   demand_empty_rest_of_line ();
01559 }
01560 
01561 
01562 /* Parsing and Idiom Translation.  */
01563 
01564 /* Parse @plt, etc. and return the desired relocation.  */
01565 static bfd_reloc_code_real_type
01566 xtensa_elf_suffix (char **str_p, expressionS *exp_p)
01567 {
01568   char ident[20];
01569   char *str = *str_p;
01570   char *str2;
01571   int ch;
01572   int len;
01573   struct suffix_reloc_map *ptr;
01574 
01575   if (*str++ != '@')
01576     return BFD_RELOC_NONE;
01577 
01578   for (ch = *str, str2 = ident;
01579        (str2 < ident + sizeof (ident) - 1
01580        && (ISALNUM (ch) || ch == '@'));
01581        ch = *++str)
01582     {
01583       *str2++ = (ISLOWER (ch)) ? ch : TOLOWER (ch);
01584     }
01585 
01586   *str2 = '\0';
01587   len = str2 - ident;
01588 
01589   ch = ident[0];
01590   for (ptr = &suffix_relocs[0]; ptr->length > 0; ptr++)
01591     if (ch == ptr->suffix[0]
01592        && len == ptr->length
01593        && memcmp (ident, ptr->suffix, ptr->length) == 0)
01594       {
01595        /* Now check for "identifier@suffix+constant".  */
01596        if (*str == '-' || *str == '+')
01597          {
01598            char *orig_line = input_line_pointer;
01599            expressionS new_exp;
01600 
01601            input_line_pointer = str;
01602            expression (&new_exp);
01603            if (new_exp.X_op == O_constant)
01604              {
01605               exp_p->X_add_number += new_exp.X_add_number;
01606               str = input_line_pointer;
01607              }
01608 
01609            if (&input_line_pointer != str_p)
01610              input_line_pointer = orig_line;
01611          }
01612 
01613        *str_p = str;
01614        return ptr->reloc;
01615       }
01616 
01617   return BFD_RELOC_UNUSED;
01618 }
01619 
01620 
01621 /* Find the matching operator type.  */
01622 static unsigned char
01623 map_suffix_reloc_to_operator (bfd_reloc_code_real_type reloc)
01624 {
01625   struct suffix_reloc_map *sfx;
01626   unsigned char operator = (unsigned char) -1;
01627   
01628   for (sfx = &suffix_relocs[0]; sfx->suffix; sfx++)
01629     {
01630       if (sfx->reloc == reloc)
01631        {
01632          operator = sfx->operator;
01633          break;
01634        }
01635     }
01636   assert (operator != (unsigned char) -1);
01637   return operator;
01638 }
01639 
01640 
01641 /* Find the matching reloc type.  */
01642 static bfd_reloc_code_real_type
01643 map_operator_to_reloc (unsigned char operator)
01644 {
01645   struct suffix_reloc_map *sfx;
01646   bfd_reloc_code_real_type reloc = BFD_RELOC_UNUSED;
01647 
01648   for (sfx = &suffix_relocs[0]; sfx->suffix; sfx++)
01649     {
01650       if (sfx->operator == operator)
01651        {
01652          reloc = sfx->reloc;
01653          break;
01654        }
01655     }
01656 
01657   if (reloc == BFD_RELOC_UNUSED)
01658     return BFD_RELOC_32;
01659 
01660   return reloc;
01661 }
01662 
01663 
01664 static const char *
01665 expression_end (const char *name)
01666 {
01667   while (1)
01668     {
01669       switch (*name)
01670        {
01671        case '}':
01672        case ';':
01673        case '\0':
01674        case ',':
01675        case ':':
01676          return name;
01677        case ' ':
01678        case '\t':
01679          ++name;
01680          continue;
01681        default:
01682          return 0;
01683        }
01684     }
01685 }
01686 
01687 
01688 #define ERROR_REG_NUM ((unsigned) -1)
01689 
01690 static unsigned
01691 tc_get_register (const char *prefix)
01692 {
01693   unsigned reg;
01694   const char *next_expr;
01695   const char *old_line_pointer;
01696 
01697   SKIP_WHITESPACE ();
01698   old_line_pointer = input_line_pointer;
01699 
01700   if (*input_line_pointer == '$')
01701     ++input_line_pointer;
01702 
01703   /* Accept "sp" as a synonym for "a1".  */
01704   if (input_line_pointer[0] == 's' && input_line_pointer[1] == 'p'
01705       && expression_end (input_line_pointer + 2))
01706     {
01707       input_line_pointer += 2;
01708       return 1;  /* AR[1] */
01709     }
01710 
01711   while (*input_line_pointer++ == *prefix++)
01712     ;
01713   --input_line_pointer;
01714   --prefix;
01715 
01716   if (*prefix)
01717     {
01718       as_bad (_("bad register name: %s"), old_line_pointer);
01719       return ERROR_REG_NUM;
01720     }
01721 
01722   if (!ISDIGIT ((unsigned char) *input_line_pointer))
01723     {
01724       as_bad (_("bad register number: %s"), input_line_pointer);
01725       return ERROR_REG_NUM;
01726     }
01727 
01728   reg = 0;
01729 
01730   while (ISDIGIT ((int) *input_line_pointer))
01731     reg = reg * 10 + *input_line_pointer++ - '0';
01732 
01733   if (!(next_expr = expression_end (input_line_pointer)))
01734     {
01735       as_bad (_("bad register name: %s"), old_line_pointer);
01736       return ERROR_REG_NUM;
01737     }
01738 
01739   input_line_pointer = (char *) next_expr;
01740 
01741   return reg;
01742 }
01743 
01744 
01745 static void
01746 expression_maybe_register (xtensa_opcode opc, int opnd, expressionS *tok)
01747 {
01748   xtensa_isa isa = xtensa_default_isa;
01749 
01750   /* Check if this is an immediate operand.  */
01751   if (xtensa_operand_is_register (isa, opc, opnd) == 0)
01752     {
01753       bfd_reloc_code_real_type reloc;
01754       segT t = expression (tok);
01755       if (t == absolute_section
01756          && xtensa_operand_is_PCrelative (isa, opc, opnd) == 1)
01757        {
01758          assert (tok->X_op == O_constant);
01759          tok->X_op = O_symbol;
01760          tok->X_add_symbol = &abs_symbol;
01761        }
01762 
01763       if ((tok->X_op == O_constant || tok->X_op == O_symbol)
01764          && ((reloc = xtensa_elf_suffix (&input_line_pointer, tok))
01765              != BFD_RELOC_NONE))
01766        {
01767          if (reloc == BFD_RELOC_UNUSED)
01768            {
01769              as_bad (_("unsupported relocation"));
01770              return;
01771            }
01772 
01773          if (tok->X_op == O_constant)
01774            {
01775              switch (reloc)
01776               {
01777               case BFD_RELOC_LO16:
01778                 tok->X_add_number &= 0xffff;
01779                 return;
01780 
01781               case BFD_RELOC_HI16:
01782                 tok->X_add_number = ((unsigned) tok->X_add_number) >> 16;
01783                 return;
01784 
01785               default:
01786                 break;
01787               }
01788            }
01789          tok->X_op = map_suffix_reloc_to_operator (reloc);
01790        }
01791     }
01792   else
01793     {
01794       xtensa_regfile opnd_rf = xtensa_operand_regfile (isa, opc, opnd);
01795       unsigned reg = tc_get_register (xtensa_regfile_shortname (isa, opnd_rf));
01796 
01797       if (reg != ERROR_REG_NUM)    /* Already errored */
01798        {
01799          uint32 buf = reg;
01800          if (xtensa_operand_encode (isa, opc, opnd, &buf))
01801            as_bad (_("register number out of range"));
01802        }
01803 
01804       tok->X_op = O_register;
01805       tok->X_add_symbol = 0;
01806       tok->X_add_number = reg;
01807     }
01808 }
01809 
01810 
01811 /* Split up the arguments for an opcode or pseudo-op.  */
01812 
01813 static int
01814 tokenize_arguments (char **args, char *str)
01815 {
01816   char *old_input_line_pointer;
01817   bfd_boolean saw_comma = FALSE;
01818   bfd_boolean saw_arg = FALSE;
01819   bfd_boolean saw_colon = FALSE;
01820   int num_args = 0;
01821   char *arg_end, *arg;
01822   int arg_len;
01823 
01824   /* Save and restore input_line_pointer around this function.  */
01825   old_input_line_pointer = input_line_pointer;
01826   input_line_pointer = str;
01827 
01828   while (*input_line_pointer)
01829     {
01830       SKIP_WHITESPACE ();
01831       switch (*input_line_pointer)
01832        {
01833        case '\0':
01834        case '}':
01835          goto fini;
01836 
01837        case ':':
01838          input_line_pointer++;
01839          if (saw_comma || saw_colon || !saw_arg)
01840            goto err;
01841          saw_colon = TRUE;
01842          break;
01843 
01844        case ',':
01845          input_line_pointer++;
01846          if (saw_comma || saw_colon || !saw_arg)
01847            goto err;
01848          saw_comma = TRUE;
01849          break;
01850 
01851        default:
01852          if (!saw_comma && !saw_colon && saw_arg)
01853            goto err;
01854 
01855          arg_end = input_line_pointer + 1;
01856          while (!expression_end (arg_end))
01857            arg_end += 1;
01858 
01859          arg_len = arg_end - input_line_pointer;
01860          arg = (char *) xmalloc ((saw_colon ? 1 : 0) + arg_len + 1);
01861          args[num_args] = arg;
01862 
01863          if (saw_colon)
01864            *arg++ = ':';
01865          strncpy (arg, input_line_pointer, arg_len);
01866          arg[arg_len] = '\0';
01867 
01868          input_line_pointer = arg_end;
01869          num_args += 1;
01870          saw_comma = FALSE;
01871          saw_colon = FALSE;
01872          saw_arg = TRUE;
01873          break;
01874        }
01875     }
01876 
01877 fini:
01878   if (saw_comma || saw_colon)
01879     goto err;
01880   input_line_pointer = old_input_line_pointer;
01881   return num_args;
01882 
01883 err:
01884   if (saw_comma)
01885     as_bad (_("extra comma"));
01886   else if (saw_colon)
01887     as_bad (_("extra colon"));
01888   else if (!saw_arg)
01889     as_bad (_("missing argument"));
01890   else
01891     as_bad (_("missing comma or colon"));
01892   input_line_pointer = old_input_line_pointer;
01893   return -1;
01894 }
01895 
01896 
01897 /* Parse the arguments to an opcode.  Return TRUE on error.  */
01898 
01899 static bfd_boolean
01900 parse_arguments (TInsn *insn, int num_args, char **arg_strings)
01901 {
01902   expressionS *tok, *last_tok;
01903   xtensa_opcode opcode = insn->opcode;
01904   bfd_boolean had_error = TRUE;
01905   xtensa_isa isa = xtensa_default_isa;
01906   int n, num_regs = 0;
01907   int opcode_operand_count;
01908   int opnd_cnt, last_opnd_cnt;
01909   unsigned int next_reg = 0;
01910   char *old_input_line_pointer;
01911 
01912   if (insn->insn_type == ITYPE_LITERAL)
01913     opcode_operand_count = 1;
01914   else
01915     opcode_operand_count = xtensa_opcode_num_operands (isa, opcode);
01916 
01917   tok = insn->tok;
01918   memset (tok, 0, sizeof (*tok) * MAX_INSN_ARGS);
01919 
01920   /* Save and restore input_line_pointer around this function.  */
01921   old_input_line_pointer = input_line_pointer;
01922 
01923   last_tok = 0;
01924   last_opnd_cnt = -1;
01925   opnd_cnt = 0;
01926 
01927   /* Skip invisible operands.  */
01928   while (xtensa_operand_is_visible (isa, opcode, opnd_cnt) == 0)
01929     {
01930       opnd_cnt += 1;
01931       tok++;
01932     }
01933 
01934   for (n = 0; n < num_args; n++)
01935     {
01936       input_line_pointer = arg_strings[n];
01937       if (*input_line_pointer == ':')
01938        {
01939          xtensa_regfile opnd_rf;
01940          input_line_pointer++;
01941          if (num_regs == 0)
01942            goto err;
01943          assert (opnd_cnt > 0);
01944          num_regs--;
01945          opnd_rf = xtensa_operand_regfile (isa, opcode, last_opnd_cnt);
01946          if (next_reg
01947              != tc_get_register (xtensa_regfile_shortname (isa, opnd_rf)))
01948            as_warn (_("incorrect register number, ignoring"));
01949          next_reg++;
01950        }
01951       else
01952        {
01953          if (opnd_cnt >= opcode_operand_count)
01954            {
01955              as_warn (_("too many arguments"));
01956              goto err;
01957            }
01958          assert (opnd_cnt < MAX_INSN_ARGS);
01959 
01960          expression_maybe_register (opcode, opnd_cnt, tok);
01961          next_reg = tok->X_add_number + 1;
01962 
01963          if (tok->X_op == O_illegal || tok->X_op == O_absent)
01964            goto err;
01965          if (xtensa_operand_is_register (isa, opcode, opnd_cnt) == 1)
01966            {
01967              num_regs = xtensa_operand_num_regs (isa, opcode, opnd_cnt) - 1;
01968              /* minus 1 because we are seeing one right now */
01969            }
01970          else
01971            num_regs = 0;
01972 
01973          last_tok = tok;
01974          last_opnd_cnt = opnd_cnt;
01975 
01976          do
01977            {
01978              opnd_cnt += 1;
01979              tok++;
01980            }
01981          while (xtensa_operand_is_visible (isa, opcode, opnd_cnt) == 0);
01982        }
01983     }
01984 
01985   if (num_regs > 0 && ((int) next_reg != last_tok->X_add_number + 1))
01986     goto err;
01987 
01988   insn->ntok = tok - insn->tok;
01989   had_error = FALSE;
01990 
01991  err:
01992   input_line_pointer = old_input_line_pointer;
01993   return had_error;
01994 }
01995 
01996 
01997 static int
01998 get_invisible_operands (TInsn *insn)
01999 {
02000   xtensa_isa isa = xtensa_default_isa;
02001   static xtensa_insnbuf slotbuf = NULL;
02002   xtensa_format fmt;
02003   xtensa_opcode opc = insn->opcode;
02004   int slot, opnd, fmt_found;
02005   unsigned val;
02006 
02007   if (!slotbuf)
02008     slotbuf = xtensa_insnbuf_alloc (isa);
02009 
02010   /* Find format/slot where this can be encoded.  */
02011   fmt_found = 0;
02012   slot = 0;
02013   for (fmt = 0; fmt < xtensa_isa_num_formats (isa); fmt++)
02014     {
02015       for (slot = 0; slot < xtensa_format_num_slots (isa, fmt); slot++)
02016        {
02017          if (xtensa_opcode_encode (isa, fmt, slot, slotbuf, opc) == 0)
02018            {
02019              fmt_found = 1;
02020              break;
02021            }
02022        }
02023       if (fmt_found) break;
02024     }
02025 
02026   if (!fmt_found)
02027     {
02028       as_bad (_("cannot encode opcode \"%s\""), xtensa_opcode_name (isa, opc));
02029       return -1;
02030     }
02031 
02032   /* First encode all the visible operands
02033      (to deal with shared field operands).  */
02034   for (opnd = 0; opnd < insn->ntok; opnd++)
02035     {
02036       if (xtensa_operand_is_visible (isa, opc, opnd) == 1
02037          && (insn->tok[opnd].X_op == O_register
02038              || insn->tok[opnd].X_op == O_constant))
02039        {
02040          val = insn->tok[opnd].X_add_number;
02041          xtensa_operand_encode (isa, opc, opnd, &val);
02042          xtensa_operand_set_field (isa, opc, opnd, fmt, slot, slotbuf, val);
02043        }
02044     }
02045 
02046   /* Then pull out the values for the invisible ones.  */
02047   for (opnd = 0; opnd < insn->ntok; opnd++)
02048     {
02049       if (xtensa_operand_is_visible (isa, opc, opnd) == 0)
02050        {
02051          xtensa_operand_get_field (isa, opc, opnd, fmt, slot, slotbuf, &val);
02052          xtensa_operand_decode (isa, opc, opnd, &val);
02053          insn->tok[opnd].X_add_number = val;
02054          if (xtensa_operand_is_register (isa, opc, opnd) == 1)
02055            insn->tok[opnd].X_op = O_register;
02056          else
02057            insn->tok[opnd].X_op = O_constant;
02058        }
02059     }
02060 
02061   return 0;
02062 }
02063 
02064 
02065 static void
02066 xg_reverse_shift_count (char **cnt_argp)
02067 {
02068   char *cnt_arg, *new_arg;
02069   cnt_arg = *cnt_argp;
02070 
02071   /* replace the argument with "31-(argument)" */
02072   new_arg = (char *) xmalloc (strlen (cnt_arg) + 6);
02073   sprintf (new_arg, "31-(%s)", cnt_arg);
02074 
02075   free (cnt_arg);
02076   *cnt_argp = new_arg;
02077 }
02078 
02079 
02080 /* If "arg" is a constant expression, return non-zero with the value
02081    in *valp.  */
02082 
02083 static int
02084 xg_arg_is_constant (char *arg, offsetT *valp)
02085 {
02086   expressionS exp;
02087   char *save_ptr = input_line_pointer;
02088 
02089   input_line_pointer = arg;
02090   expression (&exp);
02091   input_line_pointer = save_ptr;
02092 
02093   if (exp.X_op == O_constant)
02094     {
02095       *valp = exp.X_add_number;
02096       return 1;
02097     }
02098 
02099   return 0;
02100 }
02101 
02102 
02103 static void
02104 xg_replace_opname (char **popname, char *newop)
02105 {
02106   free (*popname);
02107   *popname = (char *) xmalloc (strlen (newop) + 1);
02108   strcpy (*popname, newop);
02109 }
02110 
02111 
02112 static int
02113 xg_check_num_args (int *pnum_args,
02114                  int expected_num,
02115                  char *opname,
02116                  char **arg_strings)
02117 {
02118   int num_args = *pnum_args;
02119 
02120   if (num_args < expected_num)
02121     {
02122       as_bad (_("not enough operands (%d) for '%s'; expected %d"),
02123              num_args, opname, expected_num);
02124       return -1;
02125     }
02126 
02127   if (num_args > expected_num)
02128     {
02129       as_warn (_("too many operands (%d) for '%s'; expected %d"),
02130               num_args, opname, expected_num);
02131       while (num_args-- > expected_num)
02132        {
02133          free (arg_strings[num_args]);
02134          arg_strings[num_args] = 0;
02135        }
02136       *pnum_args = expected_num;
02137       return -1;
02138     }
02139 
02140   return 0;
02141 }
02142 
02143 
02144 /* If the register is not specified as part of the opcode,
02145    then get it from the operand and move it to the opcode.  */
02146 
02147 static int
02148 xg_translate_sysreg_op (char **popname, int *pnum_args, char **arg_strings)
02149 {
02150   xtensa_isa isa = xtensa_default_isa;
02151   xtensa_sysreg sr;
02152   char *opname, *new_opname;
02153   const char *sr_name;
02154   int is_user, is_write;
02155 
02156   opname = *popname;
02157   if (*opname == '_')
02158     opname += 1;
02159   is_user = (opname[1] == 'u');
02160   is_write = (opname[0] == 'w');
02161 
02162   /* Opname == [rw]ur or [rwx]sr... */
02163 
02164   if (xg_check_num_args (pnum_args, 2, opname, arg_strings))
02165     return -1;
02166 
02167   /* Check if the argument is a symbolic register name.  */
02168   sr = xtensa_sysreg_lookup_name (isa, arg_strings[1]);
02169   /* Handle WSR to "INTSET" as a special case.  */
02170   if (sr == XTENSA_UNDEFINED && is_write && !is_user
02171       && !strcasecmp (arg_strings[1], "intset"))
02172     sr = xtensa_sysreg_lookup_name (isa, "interrupt");
02173   if (sr == XTENSA_UNDEFINED
02174       || (xtensa_sysreg_is_user (isa, sr) == 1) != is_user)
02175     {
02176       /* Maybe it's a register number.... */
02177       offsetT val;
02178       if (!xg_arg_is_constant (arg_strings[1], &val))
02179        {
02180          as_bad (_("invalid register '%s' for '%s' instruction"),
02181                 arg_strings[1], opname);
02182          return -1;
02183        }
02184       sr = xtensa_sysreg_lookup (isa, val, is_user);
02185       if (sr == XTENSA_UNDEFINED)
02186        {
02187          as_bad (_("invalid register number (%ld) for '%s' instruction"),
02188                 (long) val, opname);
02189          return -1;
02190        }
02191     }
02192 
02193   /* Remove the last argument, which is now part of the opcode.  */
02194   free (arg_strings[1]);
02195   arg_strings[1] = 0;
02196   *pnum_args = 1;
02197 
02198   /* Translate the opcode.  */
02199   sr_name = xtensa_sysreg_name (isa, sr);
02200   /* Another special case for "WSR.INTSET"....  */
02201   if (is_write && !is_user && !strcasecmp ("interrupt", sr_name))
02202     sr_name = "intset";
02203   new_opname = (char *) xmalloc (strlen (sr_name) + 6);
02204   sprintf (new_opname, "%s.%s", *popname, sr_name);
02205   free (*popname);
02206   *popname = new_opname;
02207 
02208   return 0;
02209 }
02210 
02211 
02212 static int
02213 xtensa_translate_old_userreg_ops (char **popname)
02214 {
02215   xtensa_isa isa = xtensa_default_isa;
02216   xtensa_sysreg sr;
02217   char *opname, *new_opname;
02218   const char *sr_name;
02219   bfd_boolean has_underbar = FALSE;
02220 
02221   opname = *popname;
02222   if (opname[0] == '_')
02223     {
02224       has_underbar = TRUE;
02225       opname += 1;
02226     }
02227 
02228   sr = xtensa_sysreg_lookup_name (isa, opname + 1);
02229   if (sr != XTENSA_UNDEFINED)
02230     {
02231       /* The new default name ("nnn") is different from the old default
02232         name ("URnnn").  The old default is handled below, and we don't
02233         want to recognize [RW]nnn, so do nothing if the name is the (new)
02234         default.  */
02235       static char namebuf[10];
02236       sprintf (namebuf, "%d", xtensa_sysreg_number (isa, sr));
02237       if (strcmp (namebuf, opname + 1) == 0)
02238        return 0;
02239     }
02240   else
02241     {
02242       offsetT val;
02243       char *end;
02244 
02245       /* Only continue if the reg name is "URnnn".  */
02246       if (opname[1] != 'u' || opname[2] != 'r')
02247        return 0;
02248       val = strtoul (opname + 3, &end, 10);
02249       if (*end != '\0')
02250        return 0;
02251 
02252       sr = xtensa_sysreg_lookup (isa, val, 1);
02253       if (sr == XTENSA_UNDEFINED)
02254        {
02255          as_bad (_("invalid register number (%ld) for '%s'"),
02256                 (long) val, opname);
02257          return -1;
02258        }
02259     }
02260 
02261   /* Translate the opcode.  */
02262   sr_name = xtensa_sysreg_name (isa, sr);
02263   new_opname = (char *) xmalloc (strlen (sr_name) + 6);
02264   sprintf (new_opname, "%s%cur.%s", (has_underbar ? "_" : ""),
02265           opname[0], sr_name);
02266   free (*popname);
02267   *popname = new_opname;
02268 
02269   return 0;
02270 }
02271 
02272 
02273 static int
02274 xtensa_translate_zero_immed (char *old_op,
02275                           char *new_op,
02276                           char **popname,
02277                           int *pnum_args,
02278                           char **arg_strings)
02279 {
02280   char *opname;
02281   offsetT val;
02282 
02283   opname = *popname;
02284   assert (opname[0] != '_');
02285 
02286   if (strcmp (opname, old_op) != 0)
02287     return 0;
02288 
02289   if (xg_check_num_args (pnum_args, 3, opname, arg_strings))
02290     return -1;
02291   if (xg_arg_is_constant (arg_strings[1], &val) && val == 0)
02292     {
02293       xg_replace_opname (popname, new_op);
02294       free (arg_strings[1]);
02295       arg_strings[1] = arg_strings[2];
02296       arg_strings[2] = 0;
02297       *pnum_args = 2;
02298     }
02299 
02300   return 0;
02301 }
02302 
02303 
02304 /* If the instruction is an idiom (i.e., a built-in macro), translate it.
02305    Returns non-zero if an error was found.  */
02306 
02307 static int
02308 xg_translate_idioms (char **popname, int *pnum_args, char **arg_strings)
02309 {
02310   char *opname = *popname;
02311   bfd_boolean has_underbar = FALSE;
02312 
02313   if (*opname == '_')
02314     {
02315       has_underbar = TRUE;
02316       opname += 1;
02317     }
02318 
02319   if (strcmp (opname, "mov") == 0)
02320     {
02321       if (use_transform () && !has_underbar && density_supported)
02322        xg_replace_opname (popname, "mov.n");
02323       else
02324        {
02325          if (xg_check_num_args (pnum_args, 2, opname, arg_strings))
02326            return -1;
02327          xg_replace_opname (popname, (has_underbar ? "_or" : "or"));
02328          arg_strings[2] = (char *) xmalloc (strlen (arg_strings[1]) + 1);
02329          strcpy (arg_strings[2], arg_strings[1]);
02330          *pnum_args = 3;
02331        }
02332       return 0;
02333     }
02334 
02335   if (strcmp (opname, "bbsi.l") == 0)
02336     {
02337       if (xg_check_num_args (pnum_args, 3, opname, arg_strings))
02338        return -1;
02339       xg_replace_opname (popname, (has_underbar ? "_bbsi" : "bbsi"));
02340       if (target_big_endian)
02341        xg_reverse_shift_count (&arg_strings[1]);
02342       return 0;
02343     }
02344 
02345   if (strcmp (opname, "bbci.l") == 0)
02346     {
02347       if (xg_check_num_args (pnum_args, 3, opname, arg_strings))
02348        return -1;
02349       xg_replace_opname (popname, (has_underbar ? "_bbci" : "bbci"));
02350       if (target_big_endian)
02351        xg_reverse_shift_count (&arg_strings[1]);
02352       return 0;
02353     }
02354 
02355   /* Don't do anything special with NOPs inside FLIX instructions.  They
02356      are handled elsewhere.  Real NOP instructions are always available 
02357      in configurations with FLIX, so this should never be an issue but
02358      check for it anyway.  */
02359   if (!cur_vinsn.inside_bundle && xtensa_nop_opcode == XTENSA_UNDEFINED
02360       && strcmp (opname, "nop") == 0)
02361     {
02362       if (use_transform () && !has_underbar && density_supported)
02363        xg_replace_opname (popname, "nop.n");
02364       else
02365        {
02366          if (xg_check_num_args (pnum_args, 0, opname, arg_strings))
02367            return -1;
02368          xg_replace_opname (popname, (has_underbar ? "_or" : "or"));
02369          arg_strings[0] = (char *) xmalloc (3);
02370          arg_strings[1] = (char *) xmalloc (3);
02371          arg_strings[2] = (char *) xmalloc (3);
02372          strcpy (arg_strings[0], "a1");
02373          strcpy (arg_strings[1], "a1");
02374          strcpy (arg_strings[2], "a1");
02375          *pnum_args = 3;
02376        }
02377       return 0;
02378     }
02379 
02380   /* Recognize [RW]UR and [RWX]SR.  */
02381   if ((((opname[0] == 'r' || opname[0] == 'w')
02382        && (opname[1] == 'u' || opname[1] == 's'))
02383        || (opname[0] == 'x' && opname[1] == 's'))
02384       && opname[2] == 'r'
02385       && opname[3] == '\0')
02386     return xg_translate_sysreg_op (popname, pnum_args, arg_strings);
02387 
02388   /* Backward compatibility for RUR and WUR: Recognize [RW]UR<nnn> and
02389      [RW]<name> if <name> is the non-default name of a user register.  */
02390   if ((opname[0] == 'r' || opname[0] == 'w')
02391       && xtensa_opcode_lookup (xtensa_default_isa, opname) == XTENSA_UNDEFINED)
02392     return xtensa_translate_old_userreg_ops (popname);
02393 
02394   /* Relax branches that don't allow comparisons against an immediate value
02395      of zero to the corresponding branches with implicit zero immediates.  */
02396   if (!has_underbar && use_transform ())
02397     {
02398       if (xtensa_translate_zero_immed ("bnei", "bnez", popname,
02399                                    pnum_args, arg_strings))
02400        return -1;
02401 
02402       if (xtensa_translate_zero_immed ("beqi", "beqz", popname,
02403                                    pnum_args, arg_strings))
02404        return -1;
02405 
02406       if (xtensa_translate_zero_immed ("bgei", "bgez", popname,
02407                                    pnum_args, arg_strings))
02408        return -1;
02409 
02410       if (xtensa_translate_zero_immed ("blti", "bltz", popname,
02411                                    pnum_args, arg_strings))
02412        return -1;
02413     }
02414 
02415   return 0;
02416 }
02417 
02418 
02419 /* Functions for dealing with the Xtensa ISA.  */
02420 
02421 /* Currently the assembler only allows us to use a single target per
02422    fragment.  Because of this, only one operand for a given
02423    instruction may be symbolic.  If there is a PC-relative operand,
02424    the last one is chosen.  Otherwise, the result is the number of the
02425    last immediate operand, and if there are none of those, we fail and
02426    return -1.  */
02427 
02428 static int
02429 get_relaxable_immed (xtensa_opcode opcode)
02430 {
02431   int last_immed = -1;
02432   int noperands, opi;
02433 
02434   if (opcode == XTENSA_UNDEFINED)
02435     return -1;
02436 
02437   noperands = xtensa_opcode_num_operands (xtensa_default_isa, opcode);
02438   for (opi = noperands - 1; opi >= 0; opi--)
02439     {
02440       if (xtensa_operand_is_visible (xtensa_default_isa, opcode, opi) == 0)
02441        continue;
02442       if (xtensa_operand_is_PCrelative (xtensa_default_isa, opcode, opi) == 1)
02443        return opi;
02444       if (last_immed == -1
02445          && xtensa_operand_is_register (xtensa_default_isa, opcode, opi) == 0)
02446        last_immed = opi;
02447     }
02448   return last_immed;
02449 }
02450 
02451 
02452 static xtensa_opcode
02453 get_opcode_from_buf (const char *buf, int slot)
02454 {
02455   static xtensa_insnbuf insnbuf = NULL;
02456   static xtensa_insnbuf slotbuf = NULL;
02457   xtensa_isa isa = xtensa_default_isa;
02458   xtensa_format fmt;
02459 
02460   if (!insnbuf)
02461     {
02462       insnbuf = xtensa_insnbuf_alloc (isa);
02463       slotbuf = xtensa_insnbuf_alloc (isa);
02464     }
02465 
02466   xtensa_insnbuf_from_chars (isa, insnbuf, (const unsigned char *) buf, 0);
02467   fmt = xtensa_format_decode (isa, insnbuf);
02468   if (fmt == XTENSA_UNDEFINED)
02469     return XTENSA_UNDEFINED;
02470 
02471   if (slot >= xtensa_format_num_slots (isa, fmt))
02472     return XTENSA_UNDEFINED;
02473 
02474   xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
02475   return xtensa_opcode_decode (isa, fmt, slot, slotbuf);
02476 }
02477 
02478 
02479 #ifdef TENSILICA_DEBUG
02480 
02481 /* For debugging, print out the mapping of opcode numbers to opcodes.  */
02482 
02483 static void
02484 xtensa_print_insn_table (void)
02485 {
02486   int num_opcodes, num_operands;
02487   xtensa_opcode opcode;
02488   xtensa_isa isa = xtensa_default_isa;
02489 
02490   num_opcodes = xtensa_isa_num_opcodes (xtensa_default_isa);
02491   for (opcode = 0; opcode < num_opcodes; opcode++)
02492     {
02493       int opn;
02494       fprintf (stderr, "%d: %s: ", opcode, xtensa_opcode_name (isa, opcode));
02495       num_operands = xtensa_opcode_num_operands (isa, opcode);
02496       for (opn = 0; opn < num_operands; opn++)
02497        {
02498          if (xtensa_operand_is_visible (isa, opcode, opn) == 0)
02499            continue;
02500          if (xtensa_operand_is_register (isa, opcode, opn) == 1)
02501            {
02502              xtensa_regfile opnd_rf =
02503               xtensa_operand_regfile (isa, opcode, opn);
02504              fprintf (stderr, "%s ", xtensa_regfile_shortname (isa, opnd_rf));
02505            }
02506          else if (xtensa_operand_is_PCrelative (isa, opcode, opn) == 1)
02507            fputs ("[lLr] ", stderr);
02508          else
02509            fputs ("i ", stderr);
02510        }
02511       fprintf (stderr, "\n");
02512     }
02513 }
02514 
02515 
02516 static void
02517 print_vliw_insn (xtensa_insnbuf vbuf)
02518 {
02519   xtensa_isa isa = xtensa_default_isa;
02520   xtensa_format f = xtensa_format_decode (isa, vbuf);
02521   xtensa_insnbuf sbuf = xtensa_insnbuf_alloc (isa);
02522   int op;
02523 
02524   fprintf (stderr, "format = %d\n", f);
02525 
02526   for (op = 0; op < xtensa_format_num_slots (isa, f); op++)
02527     {
02528       xtensa_opcode opcode;
02529       const char *opname;
02530       int operands;
02531 
02532       xtensa_format_get_slot (isa, f, op, vbuf, sbuf);
02533       opcode = xtensa_opcode_decode (isa, f, op, sbuf);
02534       opname = xtensa_opcode_name (isa, opcode);
02535 
02536       fprintf (stderr, "op in slot %i is %s;\n", op, opname);
02537       fprintf (stderr, "   operands = ");
02538       for (operands = 0;
02539           operands < xtensa_opcode_num_operands (isa, opcode);
02540           operands++)
02541        {
02542          unsigned int val;
02543          if (xtensa_operand_is_visible (isa, opcode, operands) == 0)
02544            continue;
02545          xtensa_operand_get_field (isa, opcode, operands, f, op, sbuf, &val);
02546          xtensa_operand_decode (isa, opcode, operands, &val);
02547          fprintf (stderr, "%d ", val);
02548        }
02549       fprintf (stderr, "\n");
02550     }
02551   xtensa_insnbuf_free (isa, sbuf);
02552 }
02553 
02554 #endif /* TENSILICA_DEBUG */
02555 
02556 
02557 static bfd_boolean
02558 is_direct_call_opcode (xtensa_opcode opcode)
02559 {
02560   xtensa_isa isa = xtensa_default_isa;
02561   int n, num_operands;
02562 
02563   if (xtensa_opcode_is_call (isa, opcode) != 1)
02564     return FALSE;
02565 
02566   num_operands = xtensa_opcode_num_operands (isa, opcode);
02567   for (n = 0; n < num_operands; n++)
02568     {
02569       if (xtensa_operand_is_register (isa, opcode, n) == 0
02570          && xtensa_operand_is_PCrelative (isa, opcode, n) == 1)
02571        return TRUE;
02572     }
02573   return FALSE;
02574 }
02575 
02576 
02577 /* Convert from BFD relocation type code to slot and operand number.
02578    Returns non-zero on failure.  */
02579 
02580 static int
02581 decode_reloc (bfd_reloc_code_real_type reloc, int *slot, bfd_boolean *is_alt)
02582 {
02583   if (reloc >= BFD_RELOC_XTENSA_SLOT0_OP
02584       && reloc <= BFD_RELOC_XTENSA_SLOT14_OP)
02585     {
02586       *slot = reloc - BFD_RELOC_XTENSA_SLOT0_OP;
02587       *is_alt = FALSE;
02588     }
02589   else if (reloc >= BFD_RELOC_XTENSA_SLOT0_ALT
02590       && reloc <= BFD_RELOC_XTENSA_SLOT14_ALT)
02591     {
02592       *slot = reloc - BFD_RELOC_XTENSA_SLOT0_ALT;
02593       *is_alt = TRUE;
02594     }
02595   else
02596     return -1;
02597 
02598   return 0;
02599 }
02600 
02601 
02602 /* Convert from slot number to BFD relocation type code for the
02603    standard PC-relative relocations.  Return BFD_RELOC_NONE on
02604    failure.  */
02605 
02606 static bfd_reloc_code_real_type
02607 encode_reloc (int slot)
02608 {
02609   if (slot < 0 || slot > 14)
02610     return BFD_RELOC_NONE;
02611 
02612   return BFD_RELOC_XTENSA_SLOT0_OP + slot;
02613 }
02614 
02615 
02616 /* Convert from slot numbers to BFD relocation type code for the
02617    "alternate" relocations.  Return BFD_RELOC_NONE on failure.  */
02618 
02619 static bfd_reloc_code_real_type
02620 encode_alt_reloc (int slot)
02621 {
02622   if (slot < 0 || slot > 14)
02623     return BFD_RELOC_NONE;
02624 
02625   return BFD_RELOC_XTENSA_SLOT0_ALT + slot;
02626 }
02627 
02628 
02629 static void
02630 xtensa_insnbuf_set_operand (xtensa_insnbuf slotbuf,
02631                          xtensa_format fmt,
02632                          int slot,
02633                          xtensa_opcode opcode,
02634                          int operand,
02635                          uint32 value,
02636                          const char *file,
02637                          unsigned int line)
02638 {
02639   uint32 valbuf = value;
02640 
02641   if (xtensa_operand_encode (xtensa_default_isa, opcode, operand, &valbuf))
02642     {
02643       if (xtensa_operand_is_PCrelative (xtensa_default_isa, opcode, operand)
02644          == 1)
02645        as_bad_where ((char *) file, line,
02646                     _("operand %d of '%s' has out of range value '%u'"), 
02647                     operand + 1,
02648                     xtensa_opcode_name (xtensa_default_isa, opcode),
02649                     value);
02650       else
02651        as_bad_where ((char *) file, line,
02652                     _("operand %d of '%s' has invalid value '%u'"),
02653                     operand + 1,
02654                     xtensa_opcode_name (xtensa_default_isa, opcode),
02655                     value);
02656       return;
02657     }
02658 
02659   xtensa_operand_set_field (xtensa_default_isa, opcode, operand, fmt, slot,
02660                          slotbuf, valbuf);
02661 }
02662 
02663 
02664 static uint32
02665 xtensa_insnbuf_get_operand (xtensa_insnbuf slotbuf,
02666                          xtensa_format fmt,
02667                          int slot,
02668                          xtensa_opcode opcode,
02669                          int opnum)
02670 {
02671   uint32 val = 0;
02672   (void) xtensa_operand_get_field (xtensa_default_isa, opcode, opnum,
02673                                fmt, slot, slotbuf, &val);
02674   (void) xtensa_operand_decode (xtensa_default_isa, opcode, opnum, &val);
02675   return val;
02676 }
02677 
02678 
02679 /* Checks for rules from xtensa-relax tables.  */
02680 
02681 /* The routine xg_instruction_matches_option_term must return TRUE
02682    when a given option term is true.  The meaning of all of the option
02683    terms is given interpretation by this function.  This is needed when
02684    an option depends on the state of a directive, but there are no such
02685    options in use right now.  */
02686 
02687 static bfd_boolean
02688 xg_instruction_matches_option_term (TInsn *insn ATTRIBUTE_UNUSED,
02689                                 const ReqOrOption *option)
02690 {
02691   if (strcmp (option->option_name, "realnop") == 0
02692       || strncmp (option->option_name, "IsaUse", 6) == 0)
02693     {
02694       /* These conditions were evaluated statically when building the
02695         relaxation table.  There's no need to reevaluate them now.  */
02696       return TRUE;
02697     }
02698   else
02699     {
02700       as_fatal (_("internal error: unknown option name '%s'"),
02701               option->option_name);
02702     }
02703 }
02704 
02705 
02706 static bfd_boolean
02707 xg_instruction_matches_or_options (TInsn *insn,
02708                                const ReqOrOptionList *or_option)
02709 {
02710   const ReqOrOption *option;
02711   /* Must match each of the AND terms.  */
02712   for (option = or_option; option != NULL; option = option->next)
02713     {
02714       if (xg_instruction_matches_option_term (insn, option))
02715        return TRUE;
02716     }
02717   return FALSE;
02718 }
02719 
02720 
02721 static bfd_boolean
02722 xg_instruction_matches_options (TInsn *insn, const ReqOptionList *options)
02723 {
02724   const ReqOption *req_options;
02725   /* Must match each of the AND terms.  */
02726   for (req_options = options;
02727        req_options != NULL;
02728        req_options = req_options->next)
02729     {
02730       /* Must match one of the OR clauses.  */
02731       if (!xg_instruction_matches_or_options (insn,
02732                                          req_options->or_option_terms))
02733        return FALSE;
02734     }
02735   return TRUE;
02736 }
02737 
02738 
02739 /* Return the transition rule that matches or NULL if none matches.  */
02740 
02741 static bfd_boolean
02742 xg_instruction_matches_rule (TInsn *insn, TransitionRule *rule)
02743 {
02744   PreconditionList *condition_l;
02745 
02746   if (rule->opcode != insn->opcode)
02747     return FALSE;
02748 
02749   for (condition_l = rule->conditions;
02750        condition_l != NULL;
02751        condition_l = condition_l->next)
02752     {
02753       expressionS *exp1;
02754       expressionS *exp2;
02755       Precondition *cond = condition_l->precond;
02756 
02757       switch (cond->typ)
02758        {
02759        case OP_CONSTANT:
02760          /* The expression must be the constant.  */
02761          assert (cond->op_num < insn->ntok);
02762          exp1 = &insn->tok[cond->op_num];
02763          if (expr_is_const (exp1))
02764            {
02765              switch (cond->cmp)
02766               {
02767               case OP_EQUAL:
02768                 if (get_expr_const (exp1) != cond->op_data)
02769                   return FALSE;
02770                 break;
02771               case OP_NOTEQUAL:
02772                 if (get_expr_const (exp1) == cond->op_data)
02773                   return FALSE;
02774                 break;
02775               default:
02776                 return FALSE;
02777               }
02778            }
02779          else if (expr_is_register (exp1))
02780            {
02781              switch (cond->cmp)
02782               {
02783               case OP_EQUAL:
02784                 if (get_expr_register (exp1) != cond->op_data)
02785                   return FALSE;
02786                 break;
02787               case OP_NOTEQUAL:
02788                 if (get_expr_register (exp1) == cond->op_data)
02789                   return FALSE;
02790                 break;
02791               default:
02792                 return FALSE;
02793               }
02794            }
02795          else
02796            return FALSE;
02797          break;
02798 
02799        case OP_OPERAND:
02800          assert (cond->op_num < insn->ntok);
02801          assert (cond->op_data < insn->ntok);
02802          exp1 = &insn->tok[cond->op_num];
02803          exp2 = &insn->tok[cond->op_data];
02804 
02805          switch (cond->cmp)
02806            {
02807            case OP_EQUAL:
02808              if (!expr_is_equal (exp1, exp2))
02809               return FALSE;
02810              break;
02811            case OP_NOTEQUAL:
02812              if (expr_is_equal (exp1, exp2))
02813               return FALSE;
02814              break;
02815            }
02816          break;
02817 
02818        case OP_LITERAL:
02819        case OP_LABEL:
02820        default:
02821          return FALSE;
02822        }
02823     }
02824   if (!xg_instruction_matches_options (insn, rule->options))
02825     return FALSE;
02826 
02827   return TRUE;
02828 }
02829 
02830 
02831 static int
02832 transition_rule_cmp (const TransitionRule *a, const TransitionRule *b)
02833 {
02834   bfd_boolean a_greater = FALSE;
02835   bfd_boolean b_greater = FALSE;
02836 
02837   ReqOptionList *l_a = a->options;
02838   ReqOptionList *l_b = b->options;
02839 
02840   /* We only care if they both are the same except for
02841      a const16 vs. an l32r.  */
02842 
02843   while (l_a && l_b && ((l_a->next == NULL) == (l_b->next == NULL)))
02844     {
02845       ReqOrOptionList *l_or_a = l_a->or_option_terms;
02846       ReqOrOptionList *l_or_b = l_b->or_option_terms;
02847       while (l_or_a && l_or_b && ((l_a->next == NULL) == (l_b->next == NULL)))
02848        {
02849          if (l_or_a->is_true != l_or_b->is_true)
02850            return 0;
02851          if (strcmp (l_or_a->option_name, l_or_b->option_name) != 0)
02852            {
02853              /* This is the case we care about.  */
02854              if (strcmp (l_or_a->option_name, "IsaUseConst16") == 0
02855                 && strcmp (l_or_b->option_name, "IsaUseL32R") == 0)
02856               {
02857                 if (prefer_const16)
02858                   a_greater = TRUE;
02859                 else
02860                   b_greater = TRUE;
02861               }
02862              else if (strcmp (l_or_a->option_name, "IsaUseL32R") == 0
02863                      && strcmp (l_or_b->option_name, "IsaUseConst16") == 0)
02864               {
02865                 if (prefer_const16)
02866                   b_greater = TRUE;
02867                 else
02868                   a_greater = TRUE;
02869               }
02870              else
02871               return 0;
02872            }
02873          l_or_a = l_or_a->next;
02874          l_or_b = l_or_b->next;
02875        }
02876       if (l_or_a || l_or_b)
02877        return 0;
02878 
02879       l_a = l_a->next;
02880       l_b = l_b->next;
02881     }
02882   if (l_a || l_b)
02883     return 0;
02884 
02885   /* Incomparable if the substitution was used differently in two cases.  */
02886   if (a_greater && b_greater)
02887     return 0;
02888 
02889   if (b_greater)
02890     return 1;
02891   if (a_greater)
02892     return -1;
02893 
02894   return 0;
02895 }
02896 
02897 
02898 static TransitionRule *
02899 xg_instruction_match (TInsn *insn)
02900 {
02901   TransitionTable *table = xg_build_simplify_table (&transition_rule_cmp);
02902   TransitionList *l;
02903   assert (insn->opcode < table->num_opcodes);
02904 
02905   /* Walk through all of the possible transitions.  */
02906   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
02907     {
02908       TransitionRule *rule = l->rule;
02909       if (xg_instruction_matches_rule (insn, rule))
02910        return rule;
02911     }
02912   return NULL;
02913 }
02914 
02915 
02916 /* Various Other Internal Functions.  */
02917 
02918 static bfd_boolean
02919 is_unique_insn_expansion (TransitionRule *r)
02920 {
02921   if (!r->to_instr || r->to_instr->next != NULL)
02922     return FALSE;
02923   if (r->to_instr->typ != INSTR_INSTR)
02924     return FALSE;
02925   return TRUE;
02926 }
02927 
02928 
02929 /* Check if there is exactly one relaxation for INSN that converts it to
02930    another instruction of equal or larger size.  If so, and if TARG is
02931    non-null, go ahead and generate the relaxed instruction into TARG.  If
02932    NARROW_ONLY is true, then only consider relaxations that widen a narrow
02933    instruction, i.e., ignore relaxations that convert to an instruction of
02934    equal size.  In some contexts where this function is used, only
02935    a single widening is allowed and the NARROW_ONLY argument is used to
02936    exclude cases like ADDI being "widened" to an ADDMI, which may
02937    later be relaxed to an ADDMI/ADDI pair.  */
02938 
02939 bfd_boolean
02940 xg_is_single_relaxable_insn (TInsn *insn, TInsn *targ, bfd_boolean narrow_only)
02941 {
02942   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
02943   TransitionList *l;
02944   TransitionRule *match = 0;
02945 
02946   assert (insn->insn_type == ITYPE_INSN);
02947   assert (insn->opcode < table->num_opcodes);
02948 
02949   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
02950     {
02951       TransitionRule *rule = l->rule;
02952 
02953       if (xg_instruction_matches_rule (insn, rule)
02954          && is_unique_insn_expansion (rule)
02955          && (xg_get_single_size (insn->opcode) + (narrow_only ? 1 : 0)
02956              <= xg_get_single_size (rule->to_instr->opcode)))
02957        {
02958          if (match)
02959            return FALSE;
02960          match = rule;
02961        }
02962     }
02963   if (!match)
02964     return FALSE;
02965 
02966   if (targ)
02967     xg_build_to_insn (targ, insn, match->to_instr);
02968   return TRUE;
02969 }
02970 
02971 
02972 /* Return the maximum number of bytes this opcode can expand to.  */
02973 
02974 static int
02975 xg_get_max_insn_widen_size (xtensa_opcode opcode)
02976 {
02977   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
02978   TransitionList *l;
02979   int max_size = xg_get_single_size (opcode);
02980 
02981   assert (opcode < table->num_opcodes);
02982 
02983   for (l = table->table[opcode]; l != NULL; l = l->next)
02984     {
02985       TransitionRule *rule = l->rule;
02986       BuildInstr *build_list;
02987       int this_size = 0;
02988 
02989       if (!rule)
02990        continue;
02991       build_list = rule->to_instr;
02992       if (is_unique_insn_expansion (rule))
02993        {
02994          assert (build_list->typ == INSTR_INSTR);
02995          this_size = xg_get_max_insn_widen_size (build_list->opcode);
02996        }
02997       else
02998        for (; build_list != NULL; build_list = build_list->next)
02999          {
03000            switch (build_list->typ)
03001              {
03002              case INSTR_INSTR:
03003               this_size += xg_get_single_size (build_list->opcode);
03004               break;
03005              case INSTR_LITERAL_DEF:
03006              case INSTR_LABEL_DEF:
03007              default:
03008               break;
03009              }
03010          }
03011       if (this_size > max_size)
03012        max_size = this_size;
03013     }
03014   return max_size;
03015 }
03016 
03017 
03018 /* Return the maximum number of literal bytes this opcode can generate.  */
03019 
03020 static int
03021 xg_get_max_insn_widen_literal_size (xtensa_opcode opcode)
03022 {
03023   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
03024   TransitionList *l;
03025   int max_size = 0;
03026 
03027   assert (opcode < table->num_opcodes);
03028 
03029   for (l = table->table[opcode]; l != NULL; l = l->next)
03030     {
03031       TransitionRule *rule = l->rule;
03032       BuildInstr *build_list;
03033       int this_size = 0;
03034 
03035       if (!rule)
03036        continue;
03037       build_list = rule->to_instr;
03038       if (is_unique_insn_expansion (rule))
03039        {
03040          assert (build_list->typ == INSTR_INSTR);
03041          this_size = xg_get_max_insn_widen_literal_size (build_list->opcode);
03042        }
03043       else
03044        for (; build_list != NULL; build_list = build_list->next)
03045          {
03046            switch (build_list->typ)
03047              {
03048              case INSTR_LITERAL_DEF:
03049               /* Hard-coded 4-byte literal.  */
03050               this_size += 4;
03051               break;
03052              case INSTR_INSTR:
03053              case INSTR_LABEL_DEF:
03054              default:
03055               break;
03056              }
03057          }
03058       if (this_size > max_size)
03059        max_size = this_size;
03060     }
03061   return max_size;
03062 }
03063 
03064 
03065 static bfd_boolean
03066 xg_is_relaxable_insn (TInsn *insn, int lateral_steps)
03067 {
03068   int steps_taken = 0;
03069   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
03070   TransitionList *l;
03071 
03072   assert (insn->insn_type == ITYPE_INSN);
03073   assert (insn->opcode < table->num_opcodes);
03074 
03075   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
03076     {
03077       TransitionRule *rule = l->rule;
03078 
03079       if (xg_instruction_matches_rule (insn, rule))
03080        {
03081          if (steps_taken == lateral_steps)
03082            return TRUE;
03083          steps_taken++;
03084        }
03085     }
03086   return FALSE;
03087 }
03088 
03089 
03090 static symbolS *
03091 get_special_literal_symbol (void)
03092 {
03093   static symbolS *sym = NULL;
03094 
03095   if (sym == NULL)
03096     sym = symbol_find_or_make ("SPECIAL_LITERAL0\001");
03097   return sym;
03098 }
03099 
03100 
03101 static symbolS *
03102 get_special_label_symbol (void)
03103 {
03104   static symbolS *sym = NULL;
03105 
03106   if (sym == NULL)
03107     sym = symbol_find_or_make ("SPECIAL_LABEL0\001");
03108   return sym;
03109 }
03110 
03111 
03112 static bfd_boolean
03113 xg_valid_literal_expression (const expressionS *exp)
03114 {
03115   switch (exp->X_op)
03116     {
03117     case O_constant:
03118     case O_symbol:
03119     case O_big:
03120     case O_uminus:
03121     case O_subtract:
03122     case O_pltrel:
03123       return TRUE;
03124     default:
03125       return FALSE;
03126     }
03127 }
03128 
03129 
03130 /* This will check to see if the value can be converted into the
03131    operand type.  It will return TRUE if it does not fit.  */
03132 
03133 static bfd_boolean
03134 xg_check_operand (int32 value, xtensa_opcode opcode, int operand)
03135 {
03136   uint32 valbuf = value;
03137   if (xtensa_operand_encode (xtensa_default_isa, opcode, operand, &valbuf))
03138     return TRUE;
03139   return FALSE;
03140 }
03141 
03142 
03143 /* Assumes: All immeds are constants.  Check that all constants fit
03144    into their immeds; return FALSE if not.  */
03145 
03146 static bfd_boolean
03147 xg_immeds_fit (const TInsn *insn)
03148 {
03149   xtensa_isa isa = xtensa_default_isa;
03150   int i;
03151 
03152   int n = insn->ntok;
03153   assert (insn->insn_type == ITYPE_INSN);
03154   for (i = 0; i < n; ++i)
03155     {
03156       const expressionS *expr = &insn->tok[i];
03157       if (xtensa_operand_is_register (isa, insn->opcode, i) == 1)
03158        continue;
03159 
03160       switch (expr->X_op)
03161        {
03162        case O_register:
03163        case O_constant:
03164          if (xg_check_operand (expr->X_add_number, insn->opcode, i))
03165            return FALSE;
03166          break;
03167 
03168        default:
03169          /* The symbol should have a fixup associated with it.  */
03170          assert (FALSE);
03171          break;
03172        }
03173     }
03174   return TRUE;
03175 }
03176 
03177 
03178 /* This should only be called after we have an initial
03179    estimate of the addresses.  */
03180 
03181 static bfd_boolean
03182 xg_symbolic_immeds_fit (const TInsn *insn,
03183                      segT pc_seg,
03184                      fragS *pc_frag,
03185                      offsetT pc_offset,
03186                      long stretch)
03187 {
03188   xtensa_isa isa = xtensa_default_isa;
03189   symbolS *symbolP;
03190   fragS *sym_frag;
03191   offsetT target, pc;
03192   uint32 new_offset;
03193   int i;
03194   int n = insn->ntok;
03195 
03196   assert (insn->insn_type == ITYPE_INSN);
03197 
03198   for (i = 0; i < n; ++i)
03199     {
03200       const expressionS *expr = &insn->tok[i];
03201       if (xtensa_operand_is_register (isa, insn->opcode, i) == 1)
03202        continue;
03203 
03204       switch (expr->X_op)
03205        {
03206        case O_register:
03207        case O_constant:
03208          if (xg_check_operand (expr->X_add_number, insn->opcode, i))
03209            return FALSE;
03210          break;
03211 
03212        case O_lo16:
03213        case O_hi16:
03214          /* Check for the worst case.  */
03215          if (xg_check_operand (0xffff, insn->opcode, i))
03216            return FALSE;
03217          break;
03218 
03219        case O_symbol:
03220          /* We only allow symbols for PC-relative references.
03221             If pc_frag == 0, then we don't have frag locations yet.  */
03222          if (pc_frag == 0
03223              || xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 0)
03224            return FALSE;
03225 
03226          /* If it is a weak symbol, then assume it won't reach.  */
03227          if (S_IS_WEAK (expr->X_add_symbol))
03228            return FALSE;
03229 
03230          if (is_direct_call_opcode (insn->opcode)
03231              && ! pc_frag->tc_frag_data.use_longcalls)
03232            {
03233              /* If callee is undefined or in a different segment, be
03234                optimistic and assume it will be in range.  */
03235              if (S_GET_SEGMENT (expr->X_add_symbol) != pc_seg)
03236               return TRUE;
03237            }
03238 
03239          /* Only references within a segment can be known to fit in the
03240             operands at assembly time.  */
03241          if (S_GET_SEGMENT (expr->X_add_symbol) != pc_seg)
03242            return FALSE;
03243 
03244          symbolP = expr->X_add_symbol;
03245          sym_frag = symbol_get_frag (symbolP);
03246          target = S_GET_VALUE (symbolP) + expr->X_add_number;
03247          pc = pc_frag->fr_address + pc_offset;
03248 
03249          /* If frag has yet to be reached on this pass, assume it
03250             will move by STRETCH just as we did.  If this is not so,
03251             it will be because some frag between grows, and that will
03252             force another pass.  Beware zero-length frags.  There
03253             should be a faster way to do this.  */
03254 
03255          if (stretch != 0
03256              && sym_frag->relax_marker != pc_frag->relax_marker
03257              && S_GET_SEGMENT (symbolP) == pc_seg)
03258            {
03259              target += stretch;
03260            }
03261 
03262          new_offset = target;
03263          xtensa_operand_do_reloc (isa, insn->opcode, i, &new_offset, pc);
03264          if (xg_check_operand (new_offset, insn->opcode, i))
03265            return FALSE;
03266          break;
03267 
03268        default:
03269          /* The symbol should have a fixup associated with it.  */
03270          return FALSE;
03271        }
03272     }
03273 
03274   return TRUE;
03275 }
03276 
03277 
03278 /* Return TRUE on success.  */
03279 
03280 static bfd_boolean
03281 xg_build_to_insn (TInsn *targ, TInsn *insn, BuildInstr *bi)
03282 {
03283   BuildOp *op;
03284   symbolS *sym;
03285 
03286   tinsn_init (targ);
03287   targ->linenum = insn->linenum;
03288   switch (bi->typ)
03289     {
03290     case INSTR_INSTR:
03291       op = bi->ops;
03292       targ->opcode = bi->opcode;
03293       targ->insn_type = ITYPE_INSN;
03294       targ->is_specific_opcode = FALSE;
03295 
03296       for (; op != NULL; op = op->next)
03297        {
03298          int op_num = op->op_num;
03299          int op_data = op->op_data;
03300 
03301          assert (op->op_num < MAX_INSN_ARGS);
03302 
03303          if (targ->ntok <= op_num)
03304            targ->ntok = op_num + 1;
03305 
03306          switch (op->typ)
03307            {
03308            case OP_CONSTANT:
03309              set_expr_const (&targ->tok[op_num], op_data);
03310              break;
03311            case OP_OPERAND:
03312              assert (op_data < insn->ntok);
03313              copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
03314              break;
03315            case OP_LITERAL:
03316              sym = get_special_literal_symbol ();
03317              set_expr_symbol_offset (&targ->tok[op_num], sym, 0);
03318              break;
03319            case OP_LABEL:
03320              sym = get_special_label_symbol ();
03321              set_expr_symbol_offset (&targ->tok[op_num], sym, 0);
03322              break;
03323            case OP_OPERAND_HI16U:
03324            case OP_OPERAND_LOW16U:
03325              assert (op_data < insn->ntok);
03326              if (expr_is_const (&insn->tok[op_data]))
03327               {
03328                 long val;
03329                 copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
03330                 val = xg_apply_userdef_op_fn (op->typ,
03331                                           targ->tok[op_num].
03332                                           X_add_number);
03333                 targ->tok[op_num].X_add_number = val;
03334               }
03335              else
03336               {
03337                 /* For const16 we can create relocations for these.  */
03338                 if (targ->opcode == XTENSA_UNDEFINED
03339                     || (targ->opcode != xtensa_const16_opcode))
03340                   return FALSE;
03341                 assert (op_data < insn->ntok);
03342                 /* Need to build a O_lo16 or O_hi16.  */
03343                 copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
03344                 if (targ->tok[op_num].X_op == O_symbol)
03345                   {
03346                     if (op->typ == OP_OPERAND_HI16U)
03347                      targ->tok[op_num].X_op = O_hi16;
03348                     else if (op->typ == OP_OPERAND_LOW16U)
03349                      targ->tok[op_num].X_op = O_lo16;
03350                     else
03351                      return FALSE;
03352                   }
03353               }
03354              break;
03355            default:
03356              /* currently handles:
03357                OP_OPERAND_LOW8
03358                OP_OPERAND_HI24S
03359                OP_OPERAND_F32MINUS */
03360              if (xg_has_userdef_op_fn (op->typ))
03361               {
03362                 assert (op_data < insn->ntok);
03363                 if (expr_is_const (&insn->tok[op_data]))
03364                   {
03365                     long val;
03366                     copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
03367                     val = xg_apply_userdef_op_fn (op->typ,
03368                                               targ->tok[op_num].
03369                                               X_add_number);
03370                     targ->tok[op_num].X_add_number = val;
03371                   }
03372                 else
03373                   return FALSE; /* We cannot use a relocation for this.  */
03374                 break;
03375               }
03376              assert (0);
03377              break;
03378            }
03379        }
03380       break;
03381 
03382     case INSTR_LITERAL_DEF:
03383       op = bi->ops;
03384       targ->opcode = XTENSA_UNDEFINED;
03385       targ->insn_type = ITYPE_LITERAL;
03386       targ->is_specific_opcode = FALSE;
03387       for (; op != NULL; op = op->next)
03388        {
03389          int op_num = op->op_num;
03390          int op_data = op->op_data;
03391          assert (op->op_num < MAX_INSN_ARGS);
03392 
03393          if (targ->ntok <= op_num)
03394            targ->ntok = op_num + 1;
03395 
03396          switch (op->typ)
03397            {
03398            case OP_OPERAND:
03399              assert (op_data < insn->ntok);
03400              /* We can only pass resolvable literals through.  */
03401              if (!xg_valid_literal_expression (&insn->tok[op_data]))
03402               return FALSE;
03403              copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
03404              break;
03405            case OP_LITERAL:
03406            case OP_CONSTANT:
03407            case OP_LABEL:
03408            default:
03409              assert (0);
03410              break;
03411            }
03412        }
03413       break;
03414 
03415     case INSTR_LABEL_DEF:
03416       op = bi->ops;
03417       targ->opcode = XTENSA_UNDEFINED;
03418       targ->insn_type = ITYPE_LABEL;
03419       targ->is_specific_opcode = FALSE;
03420       /* Literal with no ops is a label?  */
03421       assert (op == NULL);
03422       break;
03423 
03424     default:
03425       assert (0);
03426     }
03427 
03428   return TRUE;
03429 }
03430 
03431 
03432 /* Return TRUE on success.  */
03433 
03434 static bfd_boolean
03435 xg_build_to_stack (IStack *istack, TInsn *insn, BuildInstr *bi)
03436 {
03437   for (; bi != NULL; bi = bi->next)
03438     {
03439       TInsn *next_insn = istack_push_space (istack);
03440 
03441       if (!xg_build_to_insn (next_insn, insn, bi))
03442        return FALSE;
03443     }
03444   return TRUE;
03445 }
03446 
03447 
03448 /* Return TRUE on valid expansion.  */
03449 
03450 static bfd_boolean
03451 xg_expand_to_stack (IStack *istack, TInsn *insn, int lateral_steps)
03452 {
03453   int stack_size = istack->ninsn;
03454   int steps_taken = 0;
03455   TransitionTable *table = xg_build_widen_table (&transition_rule_cmp);
03456   TransitionList *l;
03457 
03458   assert (insn->insn_type == ITYPE_INSN);
03459   assert (insn->opcode < table->num_opcodes);
03460 
03461   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
03462     {
03463       TransitionRule *rule = l->rule;
03464 
03465       if (xg_instruction_matches_rule (insn, rule))
03466        {
03467          if (lateral_steps == steps_taken)
03468            {
03469              int i;
03470 
03471              /* This is it.  Expand the rule to the stack.  */
03472              if (!xg_build_to_stack (istack, insn, rule->to_instr))
03473               return FALSE;
03474 
03475              /* Check to see if it fits.  */
03476              for (i = stack_size; i < istack->ninsn; i++)
03477               {
03478                 TInsn *insn = &istack->insn[i];
03479 
03480                 if (insn->insn_type == ITYPE_INSN
03481                     && !tinsn_has_symbolic_operands (insn)
03482                     && !xg_immeds_fit (insn))
03483                   {
03484                     istack->ninsn = stack_size;
03485                     return FALSE;
03486                   }
03487               }
03488              return TRUE;
03489            }
03490          steps_taken++;
03491        }
03492     }
03493   return FALSE;
03494 }
03495 
03496 
03497 /* Relax the assembly instruction at least "min_steps".
03498    Return the number of steps taken.  */
03499 
03500 static int
03501 xg_assembly_relax (IStack *istack,
03502                  TInsn *insn,
03503                  segT pc_seg,
03504                  fragS *pc_frag,   /* if pc_frag == 0, not pc-relative */
03505                  offsetT pc_offset,       /* offset in fragment */
03506                  int min_steps,    /* minimum conversion steps */
03507                  long stretch)     /* number of bytes stretched so far */
03508 {
03509   int steps_taken = 0;
03510 
03511   /* assert (has no symbolic operands)
03512      Some of its immeds don't fit.
03513      Try to build a relaxed version.
03514      This may go through a couple of stages
03515      of single instruction transformations before
03516      we get there.  */
03517 
03518   TInsn single_target;
03519   TInsn current_insn;
03520   int lateral_steps = 0;
03521   int istack_size = istack->ninsn;
03522 
03523   if (xg_symbolic_immeds_fit (insn, pc_seg, pc_frag, pc_offset, stretch)
03524       && steps_taken >= min_steps)
03525     {
03526       istack_push (istack, insn);
03527       return steps_taken;
03528     }
03529   current_insn = *insn;
03530 
03531   /* Walk through all of the single instruction expansions.  */
03532   while (xg_is_single_relaxable_insn (&current_insn, &single_target, FALSE))
03533     {
03534       steps_taken++;
03535       if (xg_symbolic_immeds_fit (&single_target, pc_seg, pc_frag, pc_offset,
03536                               stretch))
03537        {
03538          if (steps_taken >= min_steps)
03539            {
03540              istack_push (istack, &single_target);
03541              return steps_taken;
03542            }
03543        }
03544       current_insn = single_target;
03545     }
03546 
03547   /* Now check for a multi-instruction expansion.  */
03548   while (xg_is_relaxable_insn (&current_insn, lateral_steps))
03549     {
03550       if (xg_symbolic_immeds_fit (&current_insn, pc_seg, pc_frag, pc_offset,
03551                               stretch))
03552        {
03553          if (steps_taken >= min_steps)
03554            {
03555              istack_push (istack, &current_insn);
03556              return steps_taken;
03557            }
03558        }
03559       steps_taken++;
03560       if (xg_expand_to_stack (istack, &current_insn, lateral_steps))
03561        {
03562          if (steps_taken >= min_steps)
03563            return steps_taken;
03564        }
03565       lateral_steps++;
03566       istack->ninsn = istack_size;
03567     }
03568 
03569   /* It's not going to work -- use the original.  */
03570   istack_push (istack, insn);
03571   return steps_taken;
03572 }
03573 
03574 
03575 static void
03576 xg_force_frag_space (int size)
03577 {
03578   /* This may have the side effect of creating a new fragment for the
03579      space to go into.  I just do not like the name of the "frag"
03580      functions.  */
03581   frag_grow (size);
03582 }
03583 
03584 
03585 static void
03586 xg_finish_frag (char *last_insn,
03587               enum xtensa_relax_statesE frag_state,
03588               enum xtensa_relax_statesE slot0_state,
03589               int max_growth,
03590               bfd_boolean is_insn)
03591 {
03592   /* Finish off this fragment so that it has at LEAST the desired
03593      max_growth.  If it doesn't fit in this fragment, close this one
03594      and start a new one.  In either case, return a pointer to the
03595      beginning of the growth area.  */
03596 
03597   fragS *old_frag;
03598 
03599   xg_force_frag_space (max_growth);
03600 
03601   old_frag = frag_now;
03602 
03603   frag_now->fr_opcode = last_insn;
03604   if (is_insn)
03605     frag_now->tc_frag_data.is_insn = TRUE;
03606 
03607   frag_var (rs_machine_dependent, max_growth, max_growth,
03608            frag_state, frag_now->fr_symbol, frag_now->fr_offset, last_insn);
03609 
03610   old_frag->tc_frag_data.slot_subtypes[0] = slot0_state;
03611   xtensa_set_frag_assembly_state (frag_now);
03612 
03613   /* Just to make sure that we did not split it up.  */
03614   assert (old_frag->fr_next == frag_now);
03615 }
03616 
03617 
03618 /* Return TRUE if the target frag is one of the next non-empty frags.  */
03619 
03620 static bfd_boolean
03621 is_next_frag_target (const fragS *fragP, const fragS *target)
03622 {
03623   if (fragP == NULL)
03624     return FALSE;
03625 
03626   for (; fragP; fragP = fragP->fr_next)
03627     {
03628       if (fragP == target)
03629        return TRUE;
03630       if (fragP->fr_fix != 0)
03631        return FALSE;
03632       if (fragP->fr_type == rs_fill && fragP->fr_offset != 0)
03633        return FALSE;
03634       if ((fragP->fr_type == rs_align || fragP->fr_type == rs_align_code)
03635          && ((fragP->fr_address % (1 << fragP->fr_offset)) != 0))
03636        return FALSE;
03637       if (fragP->fr_type == rs_space)
03638        return FALSE;
03639     }
03640   return FALSE;
03641 }
03642 
03643 
03644 static bfd_boolean
03645 is_branch_jmp_to_next (TInsn *insn, fragS *fragP)
03646 {
03647   xtensa_isa isa = xtensa_default_isa;
03648   int i;
03649   int num_ops = xtensa_opcode_num_operands (isa, insn->opcode);
03650   int target_op = -1;
03651   symbolS *sym;
03652   fragS *target_frag;
03653 
03654   if (xtensa_opcode_is_branch (isa, insn->opcode) != 1
03655       && xtensa_opcode_is_jump (isa, insn->opcode) != 1)
03656     return FALSE;
03657 
03658   for (i = 0; i < num_ops; i++)
03659     {
03660       if (xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 1)
03661        {
03662          target_op = i;
03663          break;
03664        }
03665     }
03666   if (target_op == -1)
03667     return FALSE;
03668 
03669   if (insn->ntok <= target_op)
03670     return FALSE;
03671 
03672   if (insn->tok[target_op].X_op != O_symbol)
03673     return FALSE;
03674 
03675   sym = insn->tok[target_op].X_add_symbol;
03676   if (sym == NULL)
03677     return FALSE;
03678 
03679   if (insn->tok[target_op].X_add_number != 0)
03680     return FALSE;
03681 
03682   target_frag = symbol_get_frag (sym);
03683   if (target_frag == NULL)
03684     return FALSE;
03685 
03686   if (is_next_frag_target (fragP->fr_next, target_frag)
03687       && S_GET_VALUE (sym) == target_frag->fr_address)
03688     return TRUE;
03689 
03690   return FALSE;
03691 }
03692 
03693 
03694 static void
03695 xg_add_branch_and_loop_targets (TInsn *insn)
03696 {
03697   xtensa_isa isa = xtensa_default_isa;
03698   int num_ops = xtensa_opcode_num_operands (isa, insn->opcode);
03699 
03700   if (xtensa_opcode_is_loop (isa, insn->opcode) == 1)
03701     {
03702       int i = 1;
03703       if (xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 1
03704          && insn->tok[i].X_op == O_symbol)
03705        symbol_get_tc (insn->tok[i].X_add_symbol)->is_loop_target = TRUE;
03706       return;
03707     }
03708 
03709   if (xtensa_opcode_is_branch (isa, insn->opcode) == 1
03710       || xtensa_opcode_is_loop (isa, insn->opcode) == 1)
03711     {
03712       int i;
03713 
03714       for (i = 0; i < insn->ntok && i < num_ops; i++)
03715        {
03716          if (xtensa_operand_is_PCrelative (isa, insn->opcode, i) == 1
03717              && insn->tok[i].X_op == O_symbol)
03718            {
03719              symbolS *sym = insn->tok[i].X_add_symbol;
03720              symbol_get_tc (sym)->is_branch_target = TRUE;
03721              if (S_IS_DEFINED (sym))
03722               symbol_get_frag (sym)->tc_frag_data.is_branch_target = TRUE;
03723            }
03724        }
03725     }
03726 }
03727 
03728 
03729 /* Return FALSE if no error.  */
03730 
03731 static bfd_boolean
03732 xg_build_token_insn (BuildInstr *instr_spec, TInsn *old_insn, TInsn *new_insn)
03733 {
03734   int num_ops = 0;
03735   BuildOp *b_op;
03736 
03737   switch (instr_spec->typ)
03738     {
03739     case INSTR_INSTR:
03740       new_insn->insn_type = ITYPE_INSN;
03741       new_insn->opcode = instr_spec->opcode;
03742       new_insn->is_specific_opcode = FALSE;
03743       new_insn->linenum = old_insn->linenum;
03744       break;
03745     case INSTR_LITERAL_DEF:
03746       new_insn->insn_type = ITYPE_LITERAL;
03747       new_insn->opcode = XTENSA_UNDEFINED;
03748       new_insn->is_specific_opcode = FALSE;
03749       new_insn->linenum = old_insn->linenum;
03750       break;
03751     case INSTR_LABEL_DEF:
03752       as_bad (_("INSTR_LABEL_DEF not supported yet"));
03753       break;
03754     }
03755 
03756   for (b_op = instr_spec->ops; b_op != NULL; b_op = b_op->next)
03757     {
03758       expressionS *exp;
03759       const expressionS *src_exp;
03760 
03761       num_ops++;
03762       switch (b_op->typ)
03763        {
03764        case OP_CONSTANT:
03765          /* The expression must be the constant.  */
03766          assert (b_op->op_num < MAX_INSN_ARGS);
03767          exp = &new_insn->tok[b_op->op_num];
03768          set_expr_const (exp, b_op->op_data);
03769          break;
03770 
03771        case OP_OPERAND:
03772          assert (b_op->op_num < MAX_INSN_ARGS);
03773          assert (b_op->op_data < (unsigned) old_insn->ntok);
03774          src_exp = &old_insn->tok[b_op->op_data];
03775          exp = &new_insn->tok[b_op->op_num];
03776          copy_expr (exp, src_exp);
03777          break;
03778 
03779        case OP_LITERAL:
03780        case OP_LABEL:
03781          as_bad (_("can't handle generation of literal/labels yet"));
03782          assert (0);
03783 
03784        default:
03785          as_bad (_("can't handle undefined OP TYPE"));
03786          assert (0);
03787        }
03788     }
03789 
03790   new_insn->ntok = num_ops;
03791   return FALSE;
03792 }
03793 
03794 
03795 /* Return TRUE if it was simplified.  */
03796 
03797 static bfd_boolean
03798 xg_simplify_insn (TInsn *old_insn, TInsn *new_insn)
03799 {
03800   TransitionRule *rule;
03801   BuildInstr *insn_spec;
03802 
03803   if (old_insn->is_specific_opcode || !density_supported)
03804     return FALSE;
03805 
03806   rule = xg_instruction_match (old_insn);
03807   if (rule == NULL)
03808     return FALSE;
03809 
03810   insn_spec = rule->to_instr;
03811   /* There should only be one.  */
03812   assert (insn_spec != NULL);
03813   assert (insn_spec->next == NULL);
03814   if (insn_spec->next != NULL)
03815     return FALSE;
03816 
03817   xg_build_token_insn (insn_spec, old_insn, new_insn);
03818 
03819   return TRUE;
03820 }
03821 
03822 
03823 /* xg_expand_assembly_insn: (1) Simplify the instruction, i.e., l32i ->
03824    l32i.n. (2) Check the number of operands.  (3) Place the instruction
03825    tokens into the stack or relax it and place multiple
03826    instructions/literals onto the stack.  Return FALSE if no error.  */
03827 
03828 static bfd_boolean
03829 xg_expand_assembly_insn (IStack *istack, TInsn *orig_insn)
03830 {
03831   int noperands;
03832   TInsn new_insn;
03833   bfd_boolean do_expand;
03834 
03835   tinsn_init (&new_insn);
03836 
03837   /* Narrow it if we can.  xg_simplify_insn now does all the
03838      appropriate checking (e.g., for the density option).  */
03839   if (xg_simplify_insn (orig_insn, &new_insn))
03840     orig_insn = &new_insn;
03841 
03842   noperands = xtensa_opcode_num_operands (xtensa_default_isa,
03843                                      orig_insn->opcode);
03844   if (orig_insn->ntok < noperands)
03845     {
03846       as_bad (_("found %d operands for '%s':  Expected %d"),
03847              orig_insn->ntok,
03848              xtensa_opcode_name (xtensa_default_isa, orig_insn->opcode),
03849              noperands);
03850       return TRUE;
03851     }
03852   if (orig_insn->ntok > noperands)
03853     as_warn (_("found too many (%d) operands for '%s':  Expected %d"),
03854             orig_insn->ntok,
03855             xtensa_opcode_name (xtensa_default_isa, orig_insn->opcode),
03856             noperands);
03857 
03858   /* If there are not enough operands, we will assert above.  If there
03859      are too many, just cut out the extras here.  */
03860   orig_insn->ntok = noperands;
03861 
03862   if (tinsn_has_invalid_symbolic_operands (orig_insn))
03863     return TRUE;
03864 
03865   /* If the instruction will definitely need to be relaxed, it is better
03866      to expand it now for better scheduling.  Decide whether to expand
03867      now....  */
03868   do_expand = (!orig_insn->is_specific_opcode && use_transform ());
03869 
03870   /* Calls should be expanded to longcalls only in the backend relaxation
03871      so that the assembly scheduler will keep the L32R/CALLX instructions
03872      adjacent.  */
03873   if (is_direct_call_opcode (orig_insn->opcode))
03874     do_expand = FALSE;
03875 
03876   if (tinsn_has_symbolic_operands (orig_insn))
03877     {
03878       /* The values of symbolic operands are not known yet, so only expand
03879         now if an operand is "complex" (e.g., difference of symbols) and
03880         will have to be stored as a literal regardless of the value.  */
03881       if (!tinsn_has_complex_operands (orig_insn))
03882        do_expand = FALSE;
03883     }
03884   else if (xg_immeds_fit (orig_insn))
03885     do_expand = FALSE;
03886 
03887   if (do_expand)
03888     xg_assembly_relax (istack, orig_insn, 0, 0, 0, 0, 0);
03889   else
03890     istack_push (istack, orig_insn);
03891 
03892   return FALSE;
03893 }
03894 
03895 
03896 /* Return TRUE if the section flags are marked linkonce
03897    or the name is .gnu.linkonce.*.  */
03898 
03899 static int linkonce_len = sizeof (".gnu.linkonce.") - 1;
03900 
03901 static bfd_boolean
03902 get_is_linkonce_section (bfd *abfd ATTRIBUTE_UNUSED, segT sec)
03903 {
03904   flagword flags, link_once_flags;
03905 
03906   flags = bfd_get_section_flags (abfd, sec);
03907   link_once_flags = (flags & SEC_LINK_ONCE);
03908 
03909   /* Flags might not be set yet.  */
03910   if (!link_once_flags
03911       && strncmp (segment_name (sec), ".gnu.linkonce.", linkonce_len) == 0)
03912     link_once_flags = SEC_LINK_ONCE;
03913 
03914   return (link_once_flags != 0);
03915 }
03916 
03917 
03918 static void
03919 xtensa_add_literal_sym (symbolS *sym)
03920 {
03921   sym_list *l;
03922 
03923   l = (sym_list *) xmalloc (sizeof (sym_list));
03924   l->sym = sym;
03925   l->next = literal_syms;
03926   literal_syms = l;
03927 }
03928 
03929 
03930 static symbolS *
03931 xtensa_create_literal_symbol (segT sec, fragS *frag)
03932 {
03933   static int lit_num = 0;
03934   static char name[256];
03935   symbolS *symbolP;
03936 
03937   sprintf (name, ".L_lit_sym%d", lit_num);
03938 
03939   /* Create a local symbol.  If it is in a linkonce section, we have to
03940      be careful to make sure that if it is used in a relocation that the
03941      symbol will be in the output file.  */
03942   if (get_is_linkonce_section (stdoutput, sec))
03943     {
03944       symbolP = symbol_new (name, sec, 0, frag);
03945       S_CLEAR_EXTERNAL (symbolP);
03946       /* symbolP->local = 1; */
03947     }
03948   else
03949     symbolP = symbol_new (name, sec, 0, frag);
03950 
03951   xtensa_add_literal_sym (symbolP);
03952 
03953   lit_num++;
03954   return symbolP;
03955 }
03956 
03957 
03958 /* Currently all literals that are generated here are 32-bit L32R targets.  */
03959 
03960 static symbolS *
03961 xg_assemble_literal (/* const */ TInsn *insn)
03962 {
03963   emit_state state;
03964   symbolS *lit_sym = NULL;
03965   bfd_reloc_code_real_type reloc;
03966   char *p;
03967 
03968   /* size = 4 for L32R.  It could easily be larger when we move to
03969      larger constants.  Add a parameter later.  */
03970   offsetT litsize = 4;
03971   offsetT litalign = 2;            /* 2^2 = 4 */
03972   expressionS saved_loc;
03973   expressionS * emit_val;
03974 
03975   set_expr_symbol_offset (&saved_loc, frag_now->fr_symbol, frag_now_fix ());
03976 
03977   assert (insn->insn_type == ITYPE_LITERAL);
03978   assert (insn->ntok == 1); /* must be only one token here */
03979 
03980   xtensa_switch_to_literal_fragment (&state);
03981 
03982   emit_val = &insn->tok[0];
03983   if (emit_val->X_op == O_big)
03984     {
03985       int size = emit_val->X_add_number * CHARS_PER_LITTLENUM;
03986       if (size > litsize)
03987        {
03988          /* This happens when someone writes a "movi a2, big_number".  */
03989          as_bad_where (frag_now->fr_file, frag_now->fr_line,
03990                      _("invalid immediate"));
03991          xtensa_restore_emit_state (&state);
03992          return NULL;
03993        }
03994     }
03995 
03996   /* Force a 4-byte align here.  Note that this opens a new frag, so all
03997      literals done with this function have a frag to themselves.  That's
03998      important for the way text section literals work.  */
03999   frag_align (litalign, 0, 0);
04000   record_alignment (now_seg, litalign);
04001 
04002   switch (emit_val->X_op)
04003     {
04004     case O_pltrel:
04005       p = frag_more (litsize);
04006       xtensa_set_frag_assembly_state (frag_now);
04007       reloc = map_operator_to_reloc (emit_val->X_op);
04008       if (emit_val->X_add_symbol)
04009        emit_val->X_op = O_symbol;
04010       else
04011        emit_val->X_op = O_constant;
04012       fix_new_exp (frag_now, p - frag_now->fr_literal,
04013                  litsize, emit_val, 0, reloc);
04014       break;
04015 
04016     default:
04017       emit_expr (emit_val, litsize);
04018       break;
04019     }
04020 
04021   assert (frag_now->tc_frag_data.literal_frag == NULL);
04022   frag_now->tc_frag_data.literal_frag = get_literal_pool_location (now_seg);
04023   frag_now->fr_symbol = xtensa_create_literal_symbol (now_seg, frag_now);
04024   lit_sym = frag_now->fr_symbol;
04025 
04026   /* Go back.  */
04027   xtensa_restore_emit_state (&state);
04028   return lit_sym;
04029 }
04030 
04031 
04032 static void
04033 xg_assemble_literal_space (/* const */ int size, int slot)
04034 {
04035   emit_state state;
04036   /* We might have to do something about this alignment.  It only
04037      takes effect if something is placed here.  */
04038   offsetT litalign = 2;            /* 2^2 = 4 */
04039   fragS *lit_saved_frag;
04040 
04041   assert (size % 4 == 0);
04042 
04043   xtensa_switch_to_literal_fragment (&state);
04044 
04045   /* Force a 4-byte align here.  */
04046   frag_align (litalign, 0, 0);
04047   record_alignment (now_seg, litalign);
04048 
04049   xg_force_frag_space (size);
04050 
04051   lit_saved_frag = frag_now;
04052   frag_now->tc_frag_data.literal_frag = get_literal_pool_location (now_seg);
04053   frag_now->fr_symbol = xtensa_create_literal_symbol (now_seg, frag_now);
04054   xg_finish_frag (0, RELAX_LITERAL, 0, size, FALSE);
04055 
04056   /* Go back.  */
04057   xtensa_restore_emit_state (&state);
04058   frag_now->tc_frag_data.literal_frags[slot] = lit_saved_frag;
04059 }
04060 
04061 
04062 /* Put in a fixup record based on the opcode.
04063    Return TRUE on success.  */
04064 
04065 static bfd_boolean
04066 xg_add_opcode_fix (TInsn *tinsn,
04067                  int opnum,
04068                  xtensa_format fmt,
04069                  int slot,
04070                  expressionS *expr,
04071                  fragS *fragP,
04072                  offsetT offset)
04073 {
04074   xtensa_opcode opcode = tinsn->opcode;
04075   bfd_reloc_code_real_type reloc;
04076   reloc_howto_type *howto;
04077   int fmt_length;
04078   fixS *the_fix;
04079 
04080   reloc = BFD_RELOC_NONE;
04081 
04082   /* First try the special cases for "alternate" relocs.  */
04083   if (opcode == xtensa_l32r_opcode)
04084     {
04085       if (fragP->tc_frag_data.use_absolute_literals)
04086        reloc = encode_alt_reloc (slot);
04087     }
04088   else if (opcode == xtensa_const16_opcode)
04089     {
04090       if (expr->X_op == O_lo16)
04091        {
04092          reloc = encode_reloc (slot);
04093          expr->X_op = O_symbol;
04094        }
04095       else if (expr->X_op == O_hi16)
04096        {
04097          reloc = encode_alt_reloc (slot);
04098          expr->X_op = O_symbol;
04099        }
04100     }
04101 
04102   if (opnum != get_relaxable_immed (opcode))
04103     {
04104       as_bad (_("invalid relocation for operand %i of '%s'"),
04105              opnum + 1, xtensa_opcode_name (xtensa_default_isa, opcode));
04106       return FALSE;
04107     }
04108 
04109   /* Handle erroneous "@h" and "@l" expressions here before they propagate
04110      into the symbol table where the generic portions of the assembler
04111      won't know what to do with them.  */
04112   if (expr->X_op == O_lo16 || expr->X_op == O_hi16)
04113     {
04114       as_bad (_("invalid expression for operand %i of '%s'"),
04115              opnum + 1, xtensa_opcode_name (xtensa_default_isa, opcode));
04116       return FALSE;
04117     }
04118 
04119   /* Next try the generic relocs.  */
04120   if (reloc == BFD_RELOC_NONE)
04121     reloc = encode_reloc (slot);
04122   if (reloc == BFD_RELOC_NONE)
04123     {
04124       as_bad (_("invalid relocation in instruction slot %i"), slot);
04125       return FALSE;
04126     }
04127 
04128   howto = bfd_reloc_type_lookup (stdoutput, reloc);
04129   if (!howto)
04130     {
04131       as_bad (_("undefined symbol for opcode \"%s\""),
04132              xtensa_opcode_name (xtensa_default_isa, opcode));
04133       return FALSE;
04134     }
04135 
04136   fmt_length = xtensa_format_length (xtensa_default_isa, fmt);
04137   the_fix = fix_new_exp (fragP, offset, fmt_length, expr,
04138                       howto->pc_relative, reloc);
04139   the_fix->fx_no_overflow = 1;
04140   the_fix->tc_fix_data.X_add_symbol = expr->X_add_symbol;
04141   the_fix->tc_fix_data.X_add_number = expr->X_add_number;
04142   the_fix->tc_fix_data.slot = slot;
04143 
04144   return TRUE;
04145 }
04146 
04147 
04148 static bfd_boolean
04149 xg_emit_insn_to_buf (TInsn *tinsn,
04150                    char *buf,
04151                    fragS *fragP,
04152                    offsetT offset,
04153                    bfd_boolean build_fix)
04154 {
04155   static xtensa_insnbuf insnbuf = NULL;
04156   bfd_boolean has_symbolic_immed = FALSE;
04157   bfd_boolean ok = TRUE;
04158 
04159   if (!insnbuf)
04160     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
04161 
04162   has_symbolic_immed = tinsn_to_insnbuf (tinsn, insnbuf);
04163   if (has_symbolic_immed && build_fix)
04164     {
04165       /* Add a fixup.  */
04166       xtensa_format fmt = xg_get_single_format (tinsn->opcode);
04167       int slot = xg_get_single_slot (tinsn->opcode);
04168       int opnum = get_relaxable_immed (tinsn->opcode);
04169       expressionS *exp = &tinsn->tok[opnum];
04170 
04171       if (!xg_add_opcode_fix (tinsn, opnum, fmt, slot, exp, fragP, offset))
04172        ok = FALSE;
04173     }
04174   fragP->tc_frag_data.is_insn = TRUE;
04175   xtensa_insnbuf_to_chars (xtensa_default_isa, insnbuf,
04176                         (unsigned char *) buf, 0);
04177   return ok;
04178 }
04179 
04180 
04181 static void
04182 xg_resolve_literals (TInsn *insn, symbolS *lit_sym)
04183 {
04184   symbolS *sym = get_special_literal_symbol ();
04185   int i;
04186   if (lit_sym == 0)
04187     return;
04188   assert (insn->insn_type == ITYPE_INSN);
04189   for (i = 0; i < insn->ntok; i++)
04190     if (insn->tok[i].X_add_symbol == sym)
04191       insn->tok[i].X_add_symbol = lit_sym;
04192 
04193 }
04194 
04195 
04196 static void
04197 xg_resolve_labels (TInsn *insn, symbolS *label_sym)
04198 {
04199   symbolS *sym = get_special_label_symbol ();
04200   int i;
04201   for (i = 0; i < insn->ntok; i++)
04202     if (insn->tok[i].X_add_symbol == sym)
04203       insn->tok[i].X_add_symbol = label_sym;
04204 
04205 }
04206 
04207 
04208 /* Return TRUE if the instruction can write to the specified
04209    integer register.  */
04210 
04211 static bfd_boolean
04212 is_register_writer (const TInsn *insn, const char *regset, int regnum)
04213 {
04214   int i;
04215   int num_ops;
04216   xtensa_isa isa = xtensa_default_isa;
04217 
04218   num_ops = xtensa_opcode_num_operands (isa, insn->opcode);
04219 
04220   for (i = 0; i < num_ops; i++)
04221     {
04222       char inout;
04223       inout = xtensa_operand_inout (isa, insn->opcode, i);
04224       if ((inout == 'o' || inout == 'm')
04225          && xtensa_operand_is_register (isa, insn->opcode, i) == 1)
04226        {
04227          xtensa_regfile opnd_rf =
04228            xtensa_operand_regfile (isa, insn->opcode, i);
04229          if (!strcmp (xtensa_regfile_shortname (isa, opnd_rf), regset))
04230            {
04231              if ((insn->tok[i].X_op == O_register)
04232                 && (insn->tok[i].X_add_number == regnum))
04233               return TRUE;
04234            }
04235        }
04236     }
04237   return FALSE;
04238 }
04239 
04240 
04241 static bfd_boolean
04242 is_bad_loopend_opcode (const TInsn *tinsn)
04243 {
04244   xtensa_opcode opcode = tinsn->opcode;
04245 
04246   if (opcode == XTENSA_UNDEFINED)
04247     return FALSE;
04248 
04249   if (opcode == xtensa_call0_opcode
04250       || opcode == xtensa_callx0_opcode
04251       || opcode == xtensa_call4_opcode
04252       || opcode == xtensa_callx4_opcode
04253       || opcode == xtensa_call8_opcode
04254       || opcode == xtensa_callx8_opcode
04255       || opcode == xtensa_call12_opcode
04256       || opcode == xtensa_callx12_opcode
04257       || opcode == xtensa_isync_opcode
04258       || opcode == xtensa_ret_opcode
04259       || opcode == xtensa_ret_n_opcode
04260       || opcode == xtensa_retw_opcode
04261       || opcode == xtensa_retw_n_opcode
04262       || opcode == xtensa_waiti_opcode
04263       || opcode == xtensa_rsr_lcount_opcode)
04264     return TRUE;
04265 
04266   return FALSE;
04267 }
04268 
04269 
04270 /* Labels that begin with ".Ln" or ".LM"  are unaligned.
04271    This allows the debugger to add unaligned labels.
04272    Also, the assembler generates stabs labels that need
04273    not be aligned:  FAKE_LABEL_NAME . {"F", "L", "endfunc"}.  */
04274 
04275 static bfd_boolean
04276 is_unaligned_label (symbolS *sym)
04277 {
04278   const char *name = S_GET_NAME (sym);
04279   static size_t fake_size = 0;
04280 
04281   if (name
04282       && name[0] == '.'
04283       && name[1] == 'L' && (name[2] == 'n' || name[2] == 'M'))
04284     return TRUE;
04285 
04286   /* FAKE_LABEL_NAME followed by "F", "L" or "endfunc" */
04287   if (fake_size == 0)
04288     fake_size = strlen (FAKE_LABEL_NAME);
04289 
04290   if (name
04291       && strncmp (FAKE_LABEL_NAME, name, fake_size) == 0
04292       && (name[fake_size] == 'F'
04293          || name[fake_size] == 'L'
04294          || (name[fake_size] == 'e'
04295              && strncmp ("endfunc", name+fake_size, 7) == 0)))
04296     return TRUE;
04297 
04298   return FALSE;
04299 }
04300 
04301 
04302 static fragS *
04303 next_non_empty_frag (const fragS *fragP)
04304 {
04305   fragS *next_fragP = fragP->fr_next;
04306 
04307   /* Sometimes an empty will end up here due storage allocation issues.
04308      So we have to skip until we find something legit.  */
04309   while (next_fragP && next_fragP->fr_fix == 0)
04310     next_fragP = next_fragP->fr_next;
04311 
04312   if (next_fragP == NULL || next_fragP->fr_fix == 0)
04313     return NULL;
04314 
04315   return next_fragP;
04316 }
04317 
04318 
04319 static bfd_boolean
04320 next_frag_opcode_is_loop (const fragS *fragP, xtensa_opcode *opcode)
04321 {
04322   xtensa_opcode out_opcode;
04323   const fragS *next_fragP = next_non_empty_frag (fragP);
04324 
04325   if (next_fragP == NULL)
04326     return FALSE;
04327 
04328   out_opcode = get_opcode_from_buf (next_fragP->fr_literal, 0);
04329   if (xtensa_opcode_is_loop (xtensa_default_isa, out_opcode) == 1)
04330     {
04331       *opcode = out_opcode;
04332       return TRUE;
04333     }
04334   return FALSE;
04335 }
04336 
04337 
04338 static int
04339 frag_format_size (const fragS *fragP)
04340 {
04341   static xtensa_insnbuf insnbuf = NULL;
04342   xtensa_isa isa = xtensa_default_isa;
04343   xtensa_format fmt;
04344   int fmt_size;
04345 
04346   if (!insnbuf)
04347     insnbuf = xtensa_insnbuf_alloc (isa);
04348 
04349   if (fragP == NULL)
04350     return XTENSA_UNDEFINED;
04351 
04352   xtensa_insnbuf_from_chars (isa, insnbuf,
04353                           (unsigned char *) fragP->fr_literal, 0);
04354 
04355   fmt = xtensa_format_decode (isa, insnbuf);
04356   if (fmt == XTENSA_UNDEFINED)
04357     return XTENSA_UNDEFINED;
04358   fmt_size = xtensa_format_length (isa, fmt);
04359 
04360   /* If the next format won't be changing due to relaxation, just
04361      return the length of the first format.  */
04362   if (fragP->fr_opcode != fragP->fr_literal)
04363     return fmt_size;
04364 
04365   /* If during relaxation we have to pull an instruction out of a
04366      multi-slot instruction, we will return the more conservative
04367      number.  This works because alignment on bigger instructions
04368      is more restrictive than alignment on smaller instructions.
04369      This is more conservative than we would like, but it happens
04370      infrequently.  */
04371 
04372   if (xtensa_format_num_slots (xtensa_default_isa, fmt) > 1)
04373     return fmt_size;
04374 
04375   /* If we aren't doing one of our own relaxations or it isn't
04376      slot-based, then the insn size won't change.  */
04377   if (fragP->fr_type != rs_machine_dependent)
04378     return fmt_size;
04379   if (fragP->fr_subtype != RELAX_SLOTS)
04380     return fmt_size;
04381 
04382   /* If an instruction is about to grow, return the longer size.  */
04383   if (fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED_STEP1
04384       || fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED_STEP2)
04385     return 3;
04386 
04387   if (fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
04388     return 2 + fragP->tc_frag_data.text_expansion[0];
04389 
04390   return fmt_size;
04391 }
04392 
04393 
04394 static int
04395 next_frag_format_size (const fragS *fragP)
04396 {
04397   const fragS *next_fragP = next_non_empty_frag (fragP);
04398   return frag_format_size (next_fragP);
04399 }
04400 
04401 
04402 /* In early Xtensa Processors, for reasons that are unclear, the ISA
04403    required two-byte instructions to be treated as three-byte instructions
04404    for loop instruction alignment.  This restriction was removed beginning
04405    with Xtensa LX.  Now the only requirement on loop instruction alignment
04406    is that the first instruction of the loop must appear at an address that
04407    does not cross a fetch boundary.  */
04408 
04409 static int
04410 get_loop_align_size (int insn_size)
04411 {
04412   if (insn_size == XTENSA_UNDEFINED)
04413     return xtensa_fetch_width;
04414 
04415   if (enforce_three_byte_loop_align && insn_size == 2)
04416     return 3;
04417 
04418   return insn_size;
04419 }
04420 
04421 
04422 /* If the next legit fragment is an end-of-loop marker,
04423    switch its state so it will instantiate a NOP.  */
04424 
04425 static void
04426 update_next_frag_state (fragS *fragP)
04427 {
04428   fragS *next_fragP = fragP->fr_next;
04429   fragS *new_target = NULL;
04430 
04431   if (align_targets)
04432     {
04433       /* We are guaranteed there will be one of these...   */
04434       while (!(next_fragP->fr_type == rs_machine_dependent
04435               && (next_fragP->fr_subtype == RELAX_MAYBE_UNREACHABLE
04436                  || next_fragP->fr_subtype == RELAX_UNREACHABLE)))
04437        next_fragP = next_fragP->fr_next;
04438 
04439       assert (next_fragP->fr_type == rs_machine_dependent
04440              && (next_fragP->fr_subtype == RELAX_MAYBE_UNREACHABLE
04441                 || next_fragP->fr_subtype == RELAX_UNREACHABLE));
04442 
04443       /* ...and one of these.  */
04444       new_target = next_fragP->fr_next;
04445       while (!(new_target->fr_type == rs_machine_dependent
04446               && (new_target->fr_subtype == RELAX_MAYBE_DESIRE_ALIGN
04447                  || new_target->fr_subtype == RELAX_DESIRE_ALIGN)))
04448        new_target = new_target->fr_next;
04449 
04450       assert (new_target->fr_type == rs_machine_dependent
04451              && (new_target->fr_subtype == RELAX_MAYBE_DESIRE_ALIGN
04452                 || new_target->fr_subtype == RELAX_DESIRE_ALIGN));
04453     }
04454 
04455   while (next_fragP && next_fragP->fr_fix == 0)
04456     {
04457       if (next_fragP->fr_type == rs_machine_dependent
04458          && next_fragP->fr_subtype == RELAX_LOOP_END)
04459        {
04460          next_fragP->fr_subtype = RELAX_LOOP_END_ADD_NOP;
04461          return;
04462        }
04463 
04464       next_fragP = next_fragP->fr_next;
04465     }
04466 }
04467 
04468 
04469 static bfd_boolean
04470 next_frag_is_branch_target (const fragS *fragP)
04471 {
04472   /* Sometimes an empty will end up here due to storage allocation issues,
04473      so we have to skip until we find something legit.  */
04474   for (fragP = fragP->fr_next; fragP; fragP = fragP->fr_next)
04475     {
04476       if (fragP->tc_frag_data.is_branch_target)
04477        return TRUE;
04478       if (fragP->fr_fix != 0)
04479        break;
04480     }
04481   return FALSE;
04482 }
04483 
04484 
04485 static bfd_boolean
04486 next_frag_is_loop_target (const fragS *fragP)
04487 {
04488   /* Sometimes an empty will end up here due storage allocation issues.
04489      So we have to skip until we find something legit. */
04490   for (fragP = fragP->fr_next; fragP; fragP = fragP->fr_next)
04491     {
04492       if (fragP->tc_frag_data.is_loop_target)
04493        return TRUE;
04494       if (fragP->fr_fix != 0)
04495        break;
04496     }
04497   return FALSE;
04498 }
04499 
04500 
04501 static addressT
04502 next_frag_pre_opcode_bytes (const fragS *fragp)
04503 {
04504   const fragS *next_fragp = fragp->fr_next;
04505   xtensa_opcode next_opcode;
04506 
04507   if (!next_frag_opcode_is_loop (fragp, &next_opcode))
04508     return 0;
04509 
04510   /* Sometimes an empty will end up here due to storage allocation issues,
04511      so we have to skip until we find something legit.  */
04512   while (next_fragp->fr_fix == 0)
04513     next_fragp = next_fragp->fr_next;
04514 
04515   if (next_fragp->fr_type != rs_machine_dependent)
04516     return 0;
04517 
04518   /* There is some implicit knowledge encoded in here.
04519      The LOOP instructions that are NOT RELAX_IMMED have
04520      been relaxed.  Note that we can assume that the LOOP
04521      instruction is in slot 0 because loops aren't bundleable.  */
04522   if (next_fragp->tc_frag_data.slot_subtypes[0] > RELAX_IMMED)
04523       return get_expanded_loop_offset (next_opcode);
04524 
04525   return 0;
04526 }
04527 
04528 
04529 /* Mark a location where we can later insert literal frags.  Update
04530    the section's literal_pool_loc, so subsequent literals can be
04531    placed nearest to their use.  */
04532 
04533 static void
04534 xtensa_mark_literal_pool_location (void)
04535 {
04536   /* Any labels pointing to the current location need
04537      to be adjusted to after the literal pool.  */
04538   emit_state s;
04539   fragS *pool_location;
04540 
04541   if (use_literal_section)
04542     return;
04543 
04544   /* We stash info in these frags so we can later move the literal's
04545      fixes into this frchain's fix list.  */
04546   pool_location = frag_now;
04547   frag_now->tc_frag_data.lit_frchain = frchain_now;
04548   frag_variant (rs_machine_dependent, 0, 0,
04549               RELAX_LITERAL_POOL_BEGIN, NULL, 0, NULL);
04550   xtensa_set_frag_assembly_state (frag_now);
04551   frag_now->tc_frag_data.lit_seg = now_seg;
04552   frag_variant (rs_machine_dependent, 0, 0,
04553               RELAX_LITERAL_POOL_END, NULL, 0, NULL);
04554   xtensa_set_frag_assembly_state (frag_now);
04555 
04556   /* Now put a frag into the literal pool that points to this location.  */
04557   set_literal_pool_location (now_seg, pool_location);
04558   xtensa_switch_to_non_abs_literal_fragment (&s);
04559   frag_align (2, 0, 0);
04560   record_alignment (now_seg, 2);
04561 
04562   /* Close whatever frag is there.  */
04563   frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
04564   xtensa_set_frag_assembly_state (frag_now);
04565   frag_now->tc_frag_data.literal_frag = pool_location;
04566   frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
04567   xtensa_restore_emit_state (&s);
04568   xtensa_set_frag_assembly_state (frag_now);
04569 }
04570 
04571 
04572 /* Build a nop of the correct size into tinsn.  */
04573 
04574 static void
04575 build_nop (TInsn *tinsn, int size)
04576 {
04577   tinsn_init (tinsn);
04578   switch (size)
04579     {
04580     case 2:
04581       tinsn->opcode = xtensa_nop_n_opcode;
04582       tinsn->ntok = 0;
04583       if (tinsn->opcode == XTENSA_UNDEFINED)
04584        as_fatal (_("opcode 'NOP.N' unavailable in this configuration"));
04585       break;
04586 
04587     case 3:
04588       if (xtensa_nop_opcode == XTENSA_UNDEFINED)
04589        {
04590          tinsn->opcode = xtensa_or_opcode;
04591          set_expr_const (&tinsn->tok[0], 1);
04592          set_expr_const (&tinsn->tok[1], 1);
04593          set_expr_const (&tinsn->tok[2], 1);
04594          tinsn->ntok = 3;
04595        }
04596       else
04597        tinsn->opcode = xtensa_nop_opcode;
04598 
04599       assert (tinsn->opcode != XTENSA_UNDEFINED);
04600     }
04601 }
04602 
04603 
04604 /* Assemble a NOP of the requested size in the buffer.  User must have
04605    allocated "buf" with at least "size" bytes.  */
04606 
04607 static void
04608 assemble_nop (int size, char *buf)
04609 {
04610   static xtensa_insnbuf insnbuf = NULL;
04611   TInsn tinsn;
04612 
04613   build_nop (&tinsn, size);
04614 
04615   if (!insnbuf)
04616     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
04617 
04618   tinsn_to_insnbuf (&tinsn, insnbuf);
04619   xtensa_insnbuf_to_chars (xtensa_default_isa, insnbuf,
04620                         (unsigned char *) buf, 0);
04621 }
04622 
04623 
04624 /* Return the number of bytes for the offset of the expanded loop
04625    instruction.  This should be incorporated into the relaxation
04626    specification but is hard-coded here.  This is used to auto-align
04627    the loop instruction.  It is invalid to call this function if the
04628    configuration does not have loops or if the opcode is not a loop
04629    opcode.  */
04630 
04631 static addressT
04632 get_expanded_loop_offset (xtensa_opcode opcode)
04633 {
04634   /* This is the OFFSET of the loop instruction in the expanded loop.
04635      This MUST correspond directly to the specification of the loop
04636      expansion.  It will be validated on fragment conversion.  */
04637   assert (opcode != XTENSA_UNDEFINED);
04638   if (opcode == xtensa_loop_opcode)
04639     return 0;
04640   if (opcode == xtensa_loopnez_opcode)
04641     return 3;
04642   if (opcode == xtensa_loopgtz_opcode)
04643     return 6;
04644   as_fatal (_("get_expanded_loop_offset: invalid opcode"));
04645   return 0;
04646 }
04647 
04648 
04649 static fragS *
04650 get_literal_pool_location (segT seg)
04651 {
04652   return seg_info (seg)->tc_segment_info_data.literal_pool_loc;
04653 }
04654 
04655 
04656 static void
04657 set_literal_pool_location (segT seg, fragS *literal_pool_loc)
04658 {
04659   seg_info (seg)->tc_segment_info_data.literal_pool_loc = literal_pool_loc;
04660 }
04661 
04662 
04663 /* Set frag assembly state should be called when a new frag is
04664    opened and after a frag has been closed.  */
04665 
04666 static void
04667 xtensa_set_frag_assembly_state (fragS *fragP)
04668 {
04669   if (!density_supported)
04670     fragP->tc_frag_data.is_no_density = TRUE;
04671 
04672   /* This function is called from subsegs_finish, which is called
04673      after xtensa_end, so we can't use "use_transform" or
04674      "use_schedule" here.  */
04675   if (!directive_state[directive_transform])
04676     fragP->tc_frag_data.is_no_transform = TRUE;
04677   if (directive_state[directive_longcalls])
04678     fragP->tc_frag_data.use_longcalls = TRUE;
04679   fragP->tc_frag_data.use_absolute_literals =
04680     directive_state[directive_absolute_literals];
04681   fragP->tc_frag_data.is_assembly_state_set = TRUE;
04682 }
04683 
04684 
04685 static bfd_boolean
04686 relaxable_section (asection *sec)
04687 {
04688   return (sec->flags & SEC_DEBUGGING) == 0;
04689 }
04690 
04691 
04692 static void
04693 xtensa_find_unmarked_state_frags (void)
04694 {
04695   segT *seclist;
04696 
04697   /* Walk over each fragment of all of the current segments.  For each
04698      unmarked fragment, mark it with the same info as the previous
04699      fragment.  */
04700   for (seclist = &stdoutput->sections;
04701        seclist && *seclist;
04702        seclist = &(*seclist)->next)
04703     {
04704       segT sec = *seclist;
04705       segment_info_type *seginfo;
04706       fragS *fragP;
04707       flagword flags;
04708       flags = bfd_get_section_flags (stdoutput, sec);
04709       if (flags & SEC_DEBUGGING)
04710        continue;
04711       if (!(flags & SEC_ALLOC))
04712        continue;
04713 
04714       seginfo = seg_info (sec);
04715       if (seginfo && seginfo->frchainP)
04716        {
04717          fragS *last_fragP = 0;
04718          for (fragP = seginfo->frchainP->frch_root; fragP;
04719               fragP = fragP->fr_next)
04720            {
04721              if (fragP->fr_fix != 0
04722                 && !fragP->tc_frag_data.is_assembly_state_set)
04723               {
04724                 if (last_fragP == 0)
04725                   {
04726                     as_warn_where (fragP->fr_file, fragP->fr_line,
04727                                  _("assembly state not set for first frag in section %s"),
04728                                  sec->name);
04729                   }
04730                 else
04731                   {
04732                     fragP->tc_frag_data.is_assembly_state_set = TRUE;
04733                     fragP->tc_frag_data.is_no_density =
04734                      last_fragP->tc_frag_data.is_no_density;
04735                     fragP->tc_frag_data.is_no_transform =
04736                      last_fragP->tc_frag_data.is_no_transform;
04737                     fragP->tc_frag_data.use_longcalls =
04738                      last_fragP->tc_frag_data.use_longcalls;
04739                     fragP->tc_frag_data.use_absolute_literals =
04740                      last_fragP->tc_frag_data.use_absolute_literals;
04741                   }
04742               }
04743              if (fragP->tc_frag_data.is_assembly_state_set)
04744               last_fragP = fragP;
04745            }
04746        }
04747     }
04748 }
04749 
04750 
04751 static void
04752 xtensa_find_unaligned_branch_targets (bfd *abfd ATTRIBUTE_UNUSED,
04753                                   asection *sec,
04754                                   void *unused ATTRIBUTE_UNUSED)
04755 {
04756   flagword flags = bfd_get_section_flags (abfd, sec);
04757   segment_info_type *seginfo = seg_info (sec);
04758   fragS *frag = seginfo->frchainP->frch_root;
04759 
04760   if (flags & SEC_CODE)
04761     {
04762       xtensa_isa isa = xtensa_default_isa;
04763       xtensa_insnbuf insnbuf = xtensa_insnbuf_alloc (isa);
04764       while (frag != NULL)
04765        {
04766          if (frag->tc_frag_data.is_branch_target)
04767            {
04768              int op_size;
04769              addressT branch_align, frag_addr;
04770              xtensa_format fmt;
04771 
04772              xtensa_insnbuf_from_chars
04773               (isa, insnbuf, (unsigned char *) frag->fr_literal, 0);
04774              fmt = xtensa_format_decode (isa, insnbuf);
04775              op_size = xtensa_format_length (isa, fmt);
04776              branch_align = 1 << branch_align_power (sec);
04777              frag_addr = frag->fr_address % branch_align;
04778              if (frag_addr + op_size > branch_align)
04779               as_warn_where (frag->fr_file, frag->fr_line,
04780                             _("unaligned branch target: %d bytes at 0x%lx"),
04781                             op_size, (long) frag->fr_address);
04782            }
04783          frag = frag->fr_next;
04784        }
04785       xtensa_insnbuf_free (isa, insnbuf);
04786     }
04787 }
04788 
04789 
04790 static void
04791 xtensa_find_unaligned_loops (bfd *abfd ATTRIBUTE_UNUSED,
04792                           asection *sec,
04793                           void *unused ATTRIBUTE_UNUSED)
04794 {
04795   flagword flags = bfd_get_section_flags (abfd, sec);
04796   segment_info_type *seginfo = seg_info (sec);
04797   fragS *frag = seginfo->frchainP->frch_root;
04798   xtensa_isa isa = xtensa_default_isa;
04799 
04800   if (flags & SEC_CODE)
04801     {
04802       xtensa_insnbuf insnbuf = xtensa_insnbuf_alloc (isa);
04803       while (frag != NULL)
04804        {
04805          if (frag->tc_frag_data.is_first_loop_insn)
04806            {
04807              int op_size;
04808              addressT frag_addr;
04809              xtensa_format fmt;
04810 
04811              xtensa_insnbuf_from_chars
04812               (isa, insnbuf, (unsigned char *) frag->fr_literal, 0);
04813              fmt = xtensa_format_decode (isa, insnbuf);
04814              op_size = xtensa_format_length (isa, fmt);
04815              frag_addr = frag->fr_address % xtensa_fetch_width;
04816 
04817              if (frag_addr + op_size > xtensa_fetch_width)
04818               as_warn_where (frag->fr_file, frag->fr_line,
04819                             _("unaligned loop: %d bytes at 0x%lx"),
04820                             op_size, (long) frag->fr_address);
04821            }
04822          frag = frag->fr_next;
04823        }
04824       xtensa_insnbuf_free (isa, insnbuf);
04825     }
04826 }
04827 
04828 
04829 static int
04830 xg_apply_fix_value (fixS *fixP, valueT val)
04831 {
04832   xtensa_isa isa = xtensa_default_isa;
04833   static xtensa_insnbuf insnbuf = NULL;
04834   static xtensa_insnbuf slotbuf = NULL;
04835   xtensa_format fmt;
04836   int slot;
04837   bfd_boolean alt_reloc;
04838   xtensa_opcode opcode;
04839   char *const fixpos = fixP->fx_frag->fr_literal + fixP->fx_where;
04840 
04841   (void) decode_reloc (fixP->fx_r_type, &slot, &alt_reloc);
04842   if (alt_reloc)
04843     as_fatal (_("unexpected fix"));
04844 
04845   if (!insnbuf)
04846     {
04847       insnbuf = xtensa_insnbuf_alloc (isa);
04848       slotbuf = xtensa_insnbuf_alloc (isa);
04849     }
04850 
04851   xtensa_insnbuf_from_chars (isa, insnbuf, (unsigned char *) fixpos, 0);
04852   fmt = xtensa_format_decode (isa, insnbuf);
04853   if (fmt == XTENSA_UNDEFINED)
04854     as_fatal (_("undecodable fix"));
04855   xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
04856   opcode = xtensa_opcode_decode (isa, fmt, slot, slotbuf);
04857   if (opcode == XTENSA_UNDEFINED)
04858     as_fatal (_("undecodable fix"));
04859 
04860   /* CONST16 immediates are not PC-relative, despite the fact that we
04861      reuse the normal PC-relative operand relocations for the low part
04862      of a CONST16 operand.  */
04863   if (opcode == xtensa_const16_opcode)
04864     return 0;
04865 
04866   xtensa_insnbuf_set_operand (slotbuf, fmt, slot, opcode,
04867                            get_relaxable_immed (opcode), val,
04868                            fixP->fx_file, fixP->fx_line);
04869 
04870   xtensa_format_set_slot (isa, fmt, slot, insnbuf, slotbuf);
04871   xtensa_insnbuf_to_chars (isa, insnbuf, (unsigned char *) fixpos, 0);
04872 
04873   return 1;
04874 }
04875 
04876 
04877 /* External Functions and Other GAS Hooks.  */
04878 
04879 const char *
04880 xtensa_target_format (void)
04881 {
04882   return (target_big_endian ? "elf32-xtensa-be" : "elf32-xtensa-le");
04883 }
04884 
04885 
04886 void
04887 xtensa_file_arch_init (bfd *abfd)
04888 {
04889   bfd_set_private_flags (abfd, 0x100 | 0x200);
04890 }
04891 
04892 
04893 void
04894 md_number_to_chars (char *buf, valueT val, int n)
04895 {
04896   if (target_big_endian)
04897     number_to_chars_bigendian (buf, val, n);
04898   else
04899     number_to_chars_littleendian (buf, val, n);
04900 }
04901 
04902 
04903 /* This function is called once, at assembler startup time.  It should
04904    set up all the tables, etc. that the MD part of the assembler will
04905    need.  */
04906 
04907 void
04908 md_begin (void)
04909 {
04910   segT current_section = now_seg;
04911   int current_subsec = now_subseg;
04912   xtensa_isa isa;
04913 
04914   xtensa_default_isa = xtensa_isa_init (0, 0);
04915   isa = xtensa_default_isa;
04916 
04917   linkrelax = 1;
04918 
04919   /* Set up the literal sections.  */
04920   memset (&default_lit_sections, 0, sizeof (default_lit_sections));
04921 
04922   subseg_set (current_section, current_subsec);
04923 
04924   xg_init_vinsn (&cur_vinsn);
04925 
04926   xtensa_addi_opcode = xtensa_opcode_lookup (isa, "addi");
04927   xtensa_addmi_opcode = xtensa_opcode_lookup (isa, "addmi");
04928   xtensa_call0_opcode = xtensa_opcode_lookup (isa, "call0");
04929   xtensa_call4_opcode = xtensa_opcode_lookup (isa, "call4");
04930   xtensa_call8_opcode = xtensa_opcode_lookup (isa, "call8");
04931   xtensa_call12_opcode = xtensa_opcode_lookup (isa, "call12");
04932   xtensa_callx0_opcode = xtensa_opcode_lookup (isa, "callx0");
04933   xtensa_callx4_opcode = xtensa_opcode_lookup (isa, "callx4");
04934   xtensa_callx8_opcode = xtensa_opcode_lookup (isa, "callx8");
04935   xtensa_callx12_opcode = xtensa_opcode_lookup (isa, "callx12");
04936   xtensa_const16_opcode = xtensa_opcode_lookup (isa, "const16");
04937   xtensa_entry_opcode = xtensa_opcode_lookup (isa, "entry");
04938   xtensa_movi_opcode = xtensa_opcode_lookup (isa, "movi");
04939   xtensa_movi_n_opcode = xtensa_opcode_lookup (isa, "movi.n");
04940   xtensa_isync_opcode = xtensa_opcode_lookup (isa, "isync");
04941   xtensa_jx_opcode = xtensa_opcode_lookup (isa, "jx");
04942   xtensa_l32r_opcode = xtensa_opcode_lookup (isa, "l32r");
04943   xtensa_loop_opcode = xtensa_opcode_lookup (isa, "loop");
04944   xtensa_loopnez_opcode = xtensa_opcode_lookup (isa, "loopnez");
04945   xtensa_loopgtz_opcode = xtensa_opcode_lookup (isa, "loopgtz");
04946   xtensa_nop_opcode = xtensa_opcode_lookup (isa, "nop");
04947   xtensa_nop_n_opcode = xtensa_opcode_lookup (isa, "nop.n");
04948   xtensa_or_opcode = xtensa_opcode_lookup (isa, "or");
04949   xtensa_ret_opcode = xtensa_opcode_lookup (isa, "ret");
04950   xtensa_ret_n_opcode = xtensa_opcode_lookup (isa, "ret.n");
04951   xtensa_retw_opcode = xtensa_opcode_lookup (isa, "retw");
04952   xtensa_retw_n_opcode = xtensa_opcode_lookup (isa, "retw.n");
04953   xtensa_rsr_lcount_opcode = xtensa_opcode_lookup (isa, "rsr.lcount");
04954   xtensa_waiti_opcode = xtensa_opcode_lookup (isa, "waiti");
04955 
04956   init_op_placement_info_table ();
04957 
04958   /* Set up the assembly state.  */
04959   if (!frag_now->tc_frag_data.is_assembly_state_set)
04960     xtensa_set_frag_assembly_state (frag_now);
04961 }
04962 
04963 
04964 /* TC_INIT_FIX_DATA hook */
04965 
04966 void
04967 xtensa_init_fix_data (fixS *x)
04968 {
04969   x->tc_fix_data.slot = 0;
04970   x->tc_fix_data.X_add_symbol = NULL;
04971   x->tc_fix_data.X_add_number = 0;
04972 }
04973 
04974 
04975 /* tc_frob_label hook */
04976 
04977 void
04978 xtensa_frob_label (symbolS *sym)
04979 {
04980   float freq;
04981 
04982   if (cur_vinsn.inside_bundle)
04983     {
04984       as_bad (_("labels are not valid inside bundles"));
04985       return;
04986     }
04987 
04988   freq = get_subseg_target_freq (now_seg, now_subseg);
04989 
04990   /* Since the label was already attached to a frag associated with the
04991      previous basic block, it now needs to be reset to the current frag.  */
04992   symbol_set_frag (sym, frag_now);
04993   S_SET_VALUE (sym, (valueT) frag_now_fix ());
04994 
04995   if (generating_literals)
04996     xtensa_add_literal_sym (sym);
04997   else
04998     xtensa_add_insn_label (sym);
04999 
05000   if (symbol_get_tc (sym)->is_loop_target)
05001     {
05002       if ((get_last_insn_flags (now_seg, now_subseg)
05003          & FLAG_IS_BAD_LOOPEND) != 0)
05004        as_bad (_("invalid last instruction for a zero-overhead loop"));
05005 
05006       xtensa_set_frag_assembly_state (frag_now);
05007       frag_var (rs_machine_dependent, 4, 4, RELAX_LOOP_END,
05008               frag_now->fr_symbol, frag_now->fr_offset, NULL);
05009 
05010       xtensa_set_frag_assembly_state (frag_now);
05011       xtensa_move_labels (frag_now, 0);
05012     }
05013 
05014   /* No target aligning in the absolute section.  */
05015   if (now_seg != absolute_section
05016       && do_align_targets ()
05017       && !is_unaligned_label (sym)
05018       && !generating_literals)
05019     {
05020       xtensa_set_frag_assembly_state (frag_now);
05021 
05022       frag_var (rs_machine_dependent,
05023               0, (int) freq,
05024               RELAX_DESIRE_ALIGN_IF_TARGET,
05025               frag_now->fr_symbol, frag_now->fr_offset, NULL);
05026       xtensa_set_frag_assembly_state (frag_now);
05027       xtensa_move_labels (frag_now, 0);
05028     }
05029 
05030   /* We need to mark the following properties even if we aren't aligning.  */
05031 
05032   /* If the label is already known to be a branch target, i.e., a
05033      forward branch, mark the frag accordingly.  Backward branches
05034      are handled by xg_add_branch_and_loop_targets.  */
05035   if (symbol_get_tc (sym)->is_branch_target)
05036     symbol_get_frag (sym)->tc_frag_data.is_branch_target = TRUE;
05037 
05038   /* Loops only go forward, so they can be identified here.  */
05039   if (symbol_get_tc (sym)->is_loop_target)
05040     symbol_get_frag (sym)->tc_frag_data.is_loop_target = TRUE;
05041 
05042   dwarf2_emit_label (sym);
05043 }
05044 
05045 
05046 /* tc_unrecognized_line hook */
05047 
05048 int
05049 xtensa_unrecognized_line (int ch)
05050 {
05051   switch (ch)
05052     {
05053     case '{' :
05054       if (cur_vinsn.inside_bundle == 0)
05055        {
05056          /* PR8110: Cannot emit line number info inside a FLIX bundle
05057             when using --gstabs.  Temporarily disable debug info.  */
05058          generate_lineno_debug ();
05059          if (debug_type == DEBUG_STABS)
05060            {
05061              xt_saved_debug_type = debug_type;
05062              debug_type = DEBUG_NONE;
05063            }
05064 
05065          cur_vinsn.inside_bundle = 1;
05066        }
05067       else
05068        {
05069          as_bad (_("extra opening brace"));
05070          return 0;
05071        }
05072       break;
05073 
05074     case '}' :
05075       if (cur_vinsn.inside_bundle)
05076        finish_vinsn (&cur_vinsn);
05077       else
05078        {
05079          as_bad (_("extra closing brace"));
05080          return 0;
05081        }
05082       break;
05083     default:
05084       as_bad (_("syntax error"));
05085       return 0;
05086     }
05087   return 1;
05088 }
05089 
05090 
05091 /* md_flush_pending_output hook */
05092 
05093 void
05094 xtensa_flush_pending_output (void)
05095 {
05096   if (cur_vinsn.inside_bundle)
05097     as_bad (_("missing closing brace"));
05098 
05099   /* If there is a non-zero instruction fragment, close it.  */
05100   if (frag_now_fix () != 0 && frag_now->tc_frag_data.is_insn)
05101     {
05102       frag_wane (frag_now);
05103       frag_new (0);
05104       xtensa_set_frag_assembly_state (frag_now);
05105     }
05106   frag_now->tc_frag_data.is_insn = FALSE;
05107 
05108   xtensa_clear_insn_labels ();
05109 }
05110 
05111 
05112 /* We had an error while parsing an instruction.  The string might look
05113    like this: "insn arg1, arg2 }".  If so, we need to see the closing
05114    brace and reset some fields.  Otherwise, the vinsn never gets closed
05115    and the num_slots field will grow past the end of the array of slots,
05116    and bad things happen.  */
05117 
05118 static void
05119 error_reset_cur_vinsn (void)
05120 {
05121   if (cur_vinsn.inside_bundle)
05122     {
05123       if (*input_line_pointer == '}'
05124          || *(input_line_pointer - 1) == '}'
05125          || *(input_line_pointer - 2) == '}')
05126        xg_clear_vinsn (&cur_vinsn);
05127     }
05128 }
05129 
05130 
05131 void
05132 md_assemble (char *str)
05133 {
05134   xtensa_isa isa = xtensa_default_isa;
05135   char *opname, *file_name;
05136   unsigned opnamelen;
05137   bfd_boolean has_underbar = FALSE;
05138   char *arg_strings[MAX_INSN_ARGS];
05139   int num_args;
05140   TInsn orig_insn;          /* Original instruction from the input.  */
05141 
05142   tinsn_init (&orig_insn);
05143 
05144   /* Split off the opcode.  */
05145   opnamelen = strspn (str, "abcdefghijklmnopqrstuvwxyz_/0123456789.");
05146   opname = xmalloc (opnamelen + 1);
05147   memcpy (opname, str, opnamelen);
05148   opname[opnamelen] = '\0';
05149 
05150   num_args = tokenize_arguments (arg_strings, str + opnamelen);
05151   if (num_args == -1)
05152     {
05153       as_bad (_("syntax error"));
05154       return;
05155     }
05156 
05157   if (xg_translate_idioms (&opname, &num_args, arg_strings))
05158     return;
05159 
05160   /* Check for an underbar prefix.  */
05161   if (*opname == '_')
05162     {
05163       has_underbar = TRUE;
05164       opname += 1;
05165     }
05166 
05167   orig_insn.insn_type = ITYPE_INSN;
05168   orig_insn.ntok = 0;
05169   orig_insn.is_specific_opcode = (has_underbar || !use_transform ());
05170 
05171   orig_insn.opcode = xtensa_opcode_lookup (isa, opname);
05172   if (orig_insn.opcode == XTENSA_UNDEFINED)
05173     {
05174       xtensa_format fmt = xtensa_format_lookup (isa, opname);
05175       if (fmt == XTENSA_UNDEFINED)
05176        {
05177          as_bad (_("unknown opcode or format name '%s'"), opname);
05178          error_reset_cur_vinsn ();
05179          return;
05180        }
05181       if (!cur_vinsn.inside_bundle)
05182        {
05183          as_bad (_("format names only valid inside bundles"));
05184          error_reset_cur_vinsn ();
05185          return;
05186        }
05187       if (cur_vinsn.format != XTENSA_UNDEFINED)
05188        as_warn (_("multiple formats specified for one bundle; using '%s'"),
05189                opname);
05190       cur_vinsn.format = fmt;
05191       free (has_underbar ? opname - 1 : opname);
05192       error_reset_cur_vinsn ();
05193       return;
05194     }
05195 
05196   /* Parse the arguments.  */
05197   if (parse_arguments (&orig_insn, num_args, arg_strings))
05198     {
05199       as_bad (_("syntax error"));
05200       error_reset_cur_vinsn ();
05201       return;
05202     }
05203 
05204   /* Free the opcode and argument strings, now that they've been parsed.  */
05205   free (has_underbar ? opname - 1 : opname);
05206   opname = 0;
05207   while (num_args-- > 0)
05208     free (arg_strings[num_args]);
05209 
05210   /* Get expressions for invisible operands.  */
05211   if (get_invisible_operands (&orig_insn))
05212     {
05213       error_reset_cur_vinsn ();
05214       return;
05215     }
05216 
05217   /* Check for the right number and type of arguments.  */
05218   if (tinsn_check_arguments (&orig_insn))
05219     {
05220       error_reset_cur_vinsn ();
05221       return;
05222     }
05223 
05224   /* A FLIX bundle may be spread across multiple input lines.  We want to
05225      report the first such line in the debug information.  Record the line
05226      number for each TInsn (assume the file name doesn't change), so the
05227      first line can be found later.  */
05228   as_where (&file_name, &orig_insn.linenum);
05229 
05230   xg_add_branch_and_loop_targets (&orig_insn);
05231 
05232   /* Check that immediate value for ENTRY is >= 16.  */
05233   if (orig_insn.opcode == xtensa_entry_opcode && orig_insn.ntok >= 3)
05234     {
05235       expressionS *exp = &orig_insn.tok[2];
05236       if (exp->X_op == O_constant && exp->X_add_number < 16)
05237        as_warn (_("entry instruction with stack decrement < 16"));
05238     }
05239 
05240   /* Finish it off:
05241      assemble_tokens (opcode, tok, ntok);
05242      expand the tokens from the orig_insn into the
05243      stack of instructions that will not expand
05244      unless required at relaxation time.  */
05245 
05246   if (!cur_vinsn.inside_bundle)
05247     emit_single_op (&orig_insn);
05248   else /* We are inside a bundle.  */
05249     {
05250       cur_vinsn.slots[cur_vinsn.num_slots] = orig_insn;
05251       cur_vinsn.num_slots++;
05252       if (*input_line_pointer == '}'
05253          || *(input_line_pointer - 1) == '}'
05254          || *(input_line_pointer - 2) == '}')
05255        finish_vinsn (&cur_vinsn);
05256     }
05257 
05258   /* We've just emitted a new instruction so clear the list of labels.  */
05259   xtensa_clear_insn_labels ();
05260 }
05261 
05262 
05263 /* HANDLE_ALIGN hook */
05264 
05265 /* For a .align directive, we mark the previous block with the alignment
05266    information.  This will be placed in the object file in the
05267    property section corresponding to this section.  */
05268 
05269 void
05270 xtensa_handle_align (fragS *fragP)
05271 {
05272   if (linkrelax
05273       && ! fragP->tc_frag_data.is_literal
05274       && (fragP->fr_type == rs_align
05275          || fragP->fr_type == rs_align_code)
05276       && fragP->fr_address + fragP->fr_fix > 0
05277       && fragP->fr_offset > 0
05278       && now_seg != bss_section)
05279     {
05280       fragP->tc_frag_data.is_align = TRUE;
05281       fragP->tc_frag_data.alignment = fragP->fr_offset;
05282     }
05283 
05284   if (fragP->fr_type == rs_align_test)
05285     {
05286       int count;
05287       count = fragP->fr_next->fr_address - fragP->fr_address - fragP->fr_fix;
05288       if (count != 0)
05289        as_bad_where (fragP->fr_file, fragP->fr_line,
05290                     _("unaligned entry instruction"));
05291     }
05292 }
05293 
05294 
05295 /* TC_FRAG_INIT hook */
05296 
05297 void
05298 xtensa_frag_init (fragS *frag)
05299 {
05300   xtensa_set_frag_assembly_state (frag);
05301 }
05302 
05303 
05304 symbolS *
05305 md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
05306 {
05307   return NULL;
05308 }
05309 
05310 
05311 /* Round up a section size to the appropriate boundary.  */
05312 
05313 valueT
05314 md_section_align (segT segment ATTRIBUTE_UNUSED, valueT size)
05315 {
05316   return size;                     /* Byte alignment is fine.  */
05317 }
05318 
05319 
05320 long
05321 md_pcrel_from (fixS *fixP)
05322 {
05323   char *insn_p;
05324   static xtensa_insnbuf insnbuf = NULL;
05325   static xtensa_insnbuf slotbuf = NULL;
05326   int opnum;
05327   uint32 opnd_value;
05328   xtensa_opcode opcode;
05329   xtensa_format fmt;
05330   int slot;
05331   xtensa_isa isa = xtensa_default_isa;
05332   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
05333   bfd_boolean alt_reloc;
05334 
05335   if (fixP->fx_r_type == BFD_RELOC_XTENSA_ASM_EXPAND)
05336     return 0;
05337 
05338   if (!insnbuf)
05339     {
05340       insnbuf = xtensa_insnbuf_alloc (isa);
05341       slotbuf = xtensa_insnbuf_alloc (isa);
05342     }
05343 
05344   insn_p = &fixP->fx_frag->fr_literal[fixP->fx_where];
05345   xtensa_insnbuf_from_chars (isa, insnbuf, (unsigned char *) insn_p, 0);
05346   fmt = xtensa_format_decode (isa, insnbuf);
05347 
05348   if (fmt == XTENSA_UNDEFINED)
05349     as_fatal (_("bad instruction format"));
05350 
05351   if (decode_reloc (fixP->fx_r_type, &slot, &alt_reloc) != 0)
05352     as_fatal (_("invalid relocation"));
05353 
05354   xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
05355   opcode = xtensa_opcode_decode (isa, fmt, slot, slotbuf);
05356 
05357   /* Check for "alternate" relocations (operand not specified).  None
05358      of the current uses for these are really PC-relative.  */
05359   if (alt_reloc || opcode == xtensa_const16_opcode)
05360     {
05361       if (opcode != xtensa_l32r_opcode
05362          && opcode != xtensa_const16_opcode)
05363        as_fatal (_("invalid relocation for '%s' instruction"),
05364                 xtensa_opcode_name (isa, opcode));
05365       return 0;
05366     }
05367 
05368   opnum = get_relaxable_immed (opcode);
05369   opnd_value = 0;
05370   if (xtensa_operand_is_PCrelative (isa, opcode, opnum) != 1
05371       || xtensa_operand_do_reloc (isa, opcode, opnum, &opnd_value, addr))
05372     {
05373       as_bad_where (fixP->fx_file,
05374                   fixP->fx_line,
05375                   _("invalid relocation for operand %d of '%s'"),
05376                   opnum, xtensa_opcode_name (isa, opcode));
05377       return 0;
05378     }
05379   return 0 - opnd_value;
05380 }
05381 
05382 
05383 /* TC_FORCE_RELOCATION hook */
05384 
05385 int
05386 xtensa_force_relocation (fixS *fix)
05387 {
05388   switch (fix->fx_r_type)
05389     {
05390     case BFD_RELOC_XTENSA_ASM_EXPAND:
05391     case BFD_RELOC_XTENSA_SLOT0_ALT:
05392     case BFD_RELOC_XTENSA_SLOT1_ALT:
05393     case BFD_RELOC_XTENSA_SLOT2_ALT:
05394     case BFD_RELOC_XTENSA_SLOT3_ALT:
05395     case BFD_RELOC_XTENSA_SLOT4_ALT:
05396     case BFD_RELOC_XTENSA_SLOT5_ALT:
05397     case BFD_RELOC_XTENSA_SLOT6_ALT:
05398     case BFD_RELOC_XTENSA_SLOT7_ALT:
05399     case BFD_RELOC_XTENSA_SLOT8_ALT:
05400     case BFD_RELOC_XTENSA_SLOT9_ALT:
05401     case BFD_RELOC_XTENSA_SLOT10_ALT:
05402     case BFD_RELOC_XTENSA_SLOT11_ALT:
05403     case BFD_RELOC_XTENSA_SLOT12_ALT:
05404     case BFD_RELOC_XTENSA_SLOT13_ALT:
05405     case BFD_RELOC_XTENSA_SLOT14_ALT:
05406       return 1;
05407     default:
05408       break;
05409     }
05410 
05411   if (linkrelax && fix->fx_addsy
05412       && relaxable_section (S_GET_SEGMENT (fix->fx_addsy)))
05413     return 1;
05414 
05415   return generic_force_reloc (fix);
05416 }
05417 
05418 
05419 /* TC_VALIDATE_FIX_SUB hook */
05420 
05421 int
05422 xtensa_validate_fix_sub (fixS *fix)
05423 {
05424   segT add_symbol_segment, sub_symbol_segment;
05425 
05426   /* The difference of two symbols should be resolved by the assembler when
05427      linkrelax is not set.  If the linker may relax the section containing
05428      the symbols, then an Xtensa DIFF relocation must be generated so that
05429      the linker knows to adjust the difference value.  */
05430   if (!linkrelax || fix->fx_addsy == NULL)
05431     return 0;
05432 
05433   /* Make sure both symbols are in the same segment, and that segment is
05434      "normal" and relaxable.  If the segment is not "normal", then the
05435      fix is not valid.  If the segment is not "relaxable", then the fix
05436      should have been handled earlier.  */
05437   add_symbol_segment = S_GET_SEGMENT (fix->fx_addsy);
05438   if (! SEG_NORMAL (add_symbol_segment) ||
05439       ! relaxable_section (add_symbol_segment))
05440     return 0;
05441   sub_symbol_segment = S_GET_SEGMENT (fix->fx_subsy);
05442   return (sub_symbol_segment == add_symbol_segment);
05443 }
05444 
05445 
05446 /* NO_PSEUDO_DOT hook */
05447 
05448 /* This function has nothing to do with pseudo dots, but this is the
05449    nearest macro to where the check needs to take place.  FIXME: This
05450    seems wrong.  */
05451 
05452 bfd_boolean
05453 xtensa_check_inside_bundle (void)
05454 {
05455   if (cur_vinsn.inside_bundle && input_line_pointer[-1] == '.')
05456     as_bad (_("directives are not valid inside bundles"));
05457 
05458   /* This function must always return FALSE because it is called via a
05459      macro that has nothing to do with bundling.  */
05460   return FALSE;
05461 }
05462 
05463 
05464 /* md_elf_section_change_hook */
05465 
05466 void
05467 xtensa_elf_section_change_hook (void)
05468 {
05469   /* Set up the assembly state.  */
05470   if (!frag_now->tc_frag_data.is_assembly_state_set)
05471     xtensa_set_frag_assembly_state (frag_now);
05472 }
05473 
05474 
05475 /* tc_fix_adjustable hook */
05476 
05477 bfd_boolean
05478 xtensa_fix_adjustable (fixS *fixP)
05479 {
05480   /* An offset is not allowed in combination with the difference of two
05481      symbols, but that cannot be easily detected after a local symbol
05482      has been adjusted to a (section+offset) form.  Return 0 so that such
05483      an fix will not be adjusted.  */
05484   if (fixP->fx_subsy && fixP->fx_addsy && fixP->fx_offset
05485       && relaxable_section (S_GET_SEGMENT (fixP->fx_subsy)))
05486     return 0;
05487 
05488   /* We need the symbol name for the VTABLE entries.  */
05489   if (fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
05490       || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
05491     return 0;
05492 
05493   return 1;
05494 }
05495 
05496 
05497 void
05498 md_apply_fix (fixS *fixP, valueT *valP, segT seg)
05499 {
05500   char *const fixpos = fixP->fx_frag->fr_literal + fixP->fx_where;
05501   valueT val = 0;
05502 
05503   /* Subtracted symbols are only allowed for a few relocation types, and
05504      unless linkrelax is enabled, they should not make it to this point.  */
05505   if (fixP->fx_subsy && !(linkrelax && (fixP->fx_r_type == BFD_RELOC_32
05506                                    || fixP->fx_r_type == BFD_RELOC_16
05507                                    || fixP->fx_r_type == BFD_RELOC_8)))
05508     as_bad_where (fixP->fx_file, fixP->fx_line, _("expression too complex"));
05509 
05510   switch (fixP->fx_r_type)
05511     {
05512     case BFD_RELOC_32:
05513     case BFD_RELOC_16:
05514     case BFD_RELOC_8:
05515       if (fixP->fx_subsy)
05516        {
05517          switch (fixP->fx_r_type)
05518            {
05519            case BFD_RELOC_8:
05520              fixP->fx_r_type = BFD_RELOC_XTENSA_DIFF8;
05521              break;
05522            case BFD_RELOC_16:
05523              fixP->fx_r_type = BFD_RELOC_XTENSA_DIFF16;
05524              break;
05525            case BFD_RELOC_32:
05526              fixP->fx_r_type = BFD_RELOC_XTENSA_DIFF32;
05527              break;
05528            default:
05529              break;
05530            }
05531 
05532          /* An offset is only allowed when it results from adjusting a
05533             local symbol into a section-relative offset.  If the offset
05534             came from the original expression, tc_fix_adjustable will have
05535             prevented the fix from being converted to a section-relative
05536             form so that we can flag the error here.  */
05537          if (fixP->fx_offset != 0 && !symbol_section_p (fixP->fx_addsy))
05538            as_bad_where (fixP->fx_file, fixP->fx_line,
05539                        _("cannot represent subtraction with an offset"));
05540 
05541          val = (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset
05542                - S_GET_VALUE (fixP->fx_subsy));
05543 
05544          /* The difference value gets written out, and the DIFF reloc
05545             identifies the address of the subtracted symbol (i.e., the one
05546             with the lowest address).  */
05547          *valP = val;
05548          fixP->fx_offset -= val;
05549          fixP->fx_subsy = NULL;
05550        }
05551       else if (! fixP->fx_addsy)
05552        {
05553          val = *valP;
05554          fixP->fx_done = 1;
05555        }
05556       /* fall through */
05557 
05558     case BFD_RELOC_XTENSA_PLT:
05559       md_number_to_chars (fixpos, val, fixP->fx_size);
05560       fixP->fx_no_overflow = 0; /* Use the standard overflow check.  */
05561       break;
05562 
05563     case BFD_RELOC_XTENSA_SLOT0_OP:
05564     case BFD_RELOC_XTENSA_SLOT1_OP:
05565     case BFD_RELOC_XTENSA_SLOT2_OP:
05566     case BFD_RELOC_XTENSA_SLOT3_OP:
05567     case BFD_RELOC_XTENSA_SLOT4_OP:
05568     case BFD_RELOC_XTENSA_SLOT5_OP:
05569     case BFD_RELOC_XTENSA_SLOT6_OP:
05570     case BFD_RELOC_XTENSA_SLOT7_OP:
05571     case BFD_RELOC_XTENSA_SLOT8_OP:
05572     case BFD_RELOC_XTENSA_SLOT9_OP:
05573     case BFD_RELOC_XTENSA_SLOT10_OP:
05574     case BFD_RELOC_XTENSA_SLOT11_OP:
05575     case BFD_RELOC_XTENSA_SLOT12_OP:
05576     case BFD_RELOC_XTENSA_SLOT13_OP:
05577     case BFD_RELOC_XTENSA_SLOT14_OP:
05578       if (linkrelax)
05579        {
05580          /* Write the tentative value of a PC-relative relocation to a
05581             local symbol into the instruction.  The value will be ignored
05582             by the linker, and it makes the object file disassembly
05583             readable when all branch targets are encoded in relocations.  */
05584 
05585          assert (fixP->fx_addsy);
05586          if (S_GET_SEGMENT (fixP->fx_addsy) == seg
05587              && !S_FORCE_RELOC (fixP->fx_addsy, 1))
05588            {
05589              val = (S_GET_VALUE (fixP->fx_addsy) + fixP->fx_offset
05590                    - md_pcrel_from (fixP));
05591              (void) xg_apply_fix_value (fixP, val);
05592            }
05593        }
05594       else if (! fixP->fx_addsy)
05595        {
05596          val = *valP;
05597          if (xg_apply_fix_value (fixP, val))
05598            fixP->fx_done = 1;
05599        }
05600       break;
05601 
05602     case BFD_RELOC_XTENSA_ASM_EXPAND:
05603     case BFD_RELOC_XTENSA_SLOT0_ALT:
05604     case BFD_RELOC_XTENSA_SLOT1_ALT:
05605     case BFD_RELOC_XTENSA_SLOT2_ALT:
05606     case BFD_RELOC_XTENSA_SLOT3_ALT:
05607     case BFD_RELOC_XTENSA_SLOT4_ALT:
05608     case BFD_RELOC_XTENSA_SLOT5_ALT:
05609     case BFD_RELOC_XTENSA_SLOT6_ALT:
05610     case BFD_RELOC_XTENSA_SLOT7_ALT:
05611     case BFD_RELOC_XTENSA_SLOT8_ALT:
05612     case BFD_RELOC_XTENSA_SLOT9_ALT:
05613     case BFD_RELOC_XTENSA_SLOT10_ALT:
05614     case BFD_RELOC_XTENSA_SLOT11_ALT:
05615     case BFD_RELOC_XTENSA_SLOT12_ALT:
05616     case BFD_RELOC_XTENSA_SLOT13_ALT:
05617     case BFD_RELOC_XTENSA_SLOT14_ALT:
05618       /* These all need to be resolved at link-time.  Do nothing now.  */
05619       break;
05620 
05621     case BFD_RELOC_VTABLE_INHERIT:
05622     case BFD_RELOC_VTABLE_ENTRY:
05623       fixP->fx_done = 0;
05624       break;
05625 
05626     default:
05627       as_bad (_("unhandled local relocation fix %s"),
05628              bfd_get_reloc_code_name (fixP->fx_r_type));
05629     }
05630 }
05631 
05632 
05633 char *
05634 md_atof (int type, char *litP, int *sizeP)
05635 {
05636   int prec;
05637   LITTLENUM_TYPE words[4];
05638   char *t;
05639   int i;
05640 
05641   switch (type)
05642     {
05643     case 'f':
05644       prec = 2;
05645       break;
05646 
05647     case 'd':
05648       prec = 4;
05649       break;
05650 
05651     default:
05652       *sizeP = 0;
05653       return "bad call to md_atof";
05654     }
05655 
05656   t = atof_ieee (input_line_pointer, type, words);
05657   if (t)
05658     input_line_pointer = t;
05659 
05660   *sizeP = prec * 2;
05661 
05662   for (i = prec - 1; i >= 0; i--)
05663     {
05664       int idx = i;
05665       if (target_big_endian)
05666        idx = (prec - 1 - i);
05667 
05668       md_number_to_chars (litP, (valueT) words[idx], 2);
05669       litP += 2;
05670     }
05671 
05672   return NULL;
05673 }
05674 
05675 
05676 int
05677 md_estimate_size_before_relax (fragS *fragP, segT seg ATTRIBUTE_UNUSED)
05678 {
05679   return total_frag_text_expansion (fragP);
05680 }
05681 
05682 
05683 /* Translate internal representation of relocation info to BFD target
05684    format.  */
05685 
05686 arelent *
05687 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
05688 {
05689   arelent *reloc;
05690 
05691   reloc = (arelent *) xmalloc (sizeof (arelent));
05692   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
05693   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
05694   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
05695 
05696   /* Make sure none of our internal relocations make it this far.
05697      They'd better have been fully resolved by this point.  */
05698   assert ((int) fixp->fx_r_type > 0);
05699 
05700   reloc->addend = fixp->fx_offset;
05701 
05702   reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
05703   if (reloc->howto == NULL)
05704     {
05705       as_bad_where (fixp->fx_file, fixp->fx_line,
05706                   _("cannot represent `%s' relocation in object file"),
05707                   bfd_get_reloc_code_name (fixp->fx_r_type));
05708       free (reloc->sym_ptr_ptr);
05709       free (reloc);
05710       return NULL;
05711     }
05712 
05713   if (!fixp->fx_pcrel != !reloc->howto->pc_relative)
05714     as_fatal (_("internal error? cannot generate `%s' relocation"),
05715              bfd_get_reloc_code_name (fixp->fx_r_type));
05716 
05717   return reloc;
05718 }
05719 
05720 
05721 /* Checks for resource conflicts between instructions.  */
05722 
05723 /* The func unit stuff could be implemented as bit-vectors rather
05724    than the iterative approach here.  If it ends up being too
05725    slow, we will switch it.  */
05726 
05727 resource_table *
05728 new_resource_table (void *data,
05729                   int cycles,
05730                   int nu,
05731                   unit_num_copies_func uncf,
05732                   opcode_num_units_func onuf,
05733                   opcode_funcUnit_use_unit_func ouuf,
05734                   opcode_funcUnit_use_stage_func ousf)
05735 {
05736   int i;
05737   resource_table *rt = (resource_table *) xmalloc (sizeof (resource_table));
05738   rt->data = data;
05739   rt->cycles = cycles;
05740   rt->allocated_cycles = cycles;
05741   rt->num_units = nu;
05742   rt->unit_num_copies = uncf;
05743   rt->opcode_num_units = onuf;
05744   rt->opcode_unit_use = ouuf;
05745   rt->opcode_unit_stage = ousf;
05746 
05747   rt->units = (unsigned char **) xcalloc (cycles, sizeof (unsigned char *));
05748   for (i = 0; i < cycles; i++)
05749     rt->units[i] = (unsigned char *) xcalloc (nu, sizeof (unsigned char));
05750 
05751   return rt;
05752 }
05753 
05754 
05755 void
05756 clear_resource_table (resource_table *rt)
05757 {
05758   int i, j;
05759   for (i = 0; i < rt->allocated_cycles; i++)
05760     for (j = 0; j < rt->num_units; j++)
05761       rt->units[i][j] = 0;
05762 }
05763 
05764 
05765 /* We never shrink it, just fake it into thinking so.  */
05766 
05767 void
05768 resize_resource_table (resource_table *rt, int cycles)
05769 {
05770   int i, old_cycles;
05771 
05772   rt->cycles = cycles;
05773   if (cycles <= rt->allocated_cycles)
05774     return;
05775 
05776   old_cycles = rt->allocated_cycles;
05777   rt->allocated_cycles = cycles;
05778 
05779   rt->units = xrealloc (rt->units,
05780                      rt->allocated_cycles * sizeof (unsigned char *));
05781   for (i = 0; i < old_cycles; i++)
05782     rt->units[i] = xrealloc (rt->units[i],
05783                           rt->num_units * sizeof (unsigned char));
05784   for (i = old_cycles; i < cycles; i++)
05785     rt->units[i] = xcalloc (rt->num_units, sizeof (unsigned char));
05786 }
05787 
05788 
05789 bfd_boolean
05790 resources_available (resource_table *rt, xtensa_opcode opcode, int cycle)
05791 {
05792   int i;
05793   int uses = (rt->opcode_num_units) (rt->data, opcode);
05794 
05795   for (i = 0; i < uses; i++)
05796     {
05797       xtensa_funcUnit unit = (rt->opcode_unit_use) (rt->data, opcode, i);
05798       int stage = (rt->opcode_unit_stage) (rt->data, opcode, i);
05799       int copies_in_use = rt->units[stage + cycle][unit];
05800       int copies = (rt->unit_num_copies) (rt->data, unit);
05801       if (copies_in_use >= copies)
05802        return FALSE;
05803     }
05804   return TRUE;
05805 }
05806 
05807 
05808 void
05809 reserve_resources (resource_table *rt, xtensa_opcode opcode, int cycle)
05810 {
05811   int i;
05812   int uses = (rt->opcode_num_units) (rt->data, opcode);
05813 
05814   for (i = 0; i < uses; i++)
05815     {
05816       xtensa_funcUnit unit = (rt->opcode_unit_use) (rt->data, opcode, i);
05817       int stage = (rt->opcode_unit_stage) (rt->data, opcode, i);
05818       /* Note that this allows resources to be oversubscribed.  That's
05819         essential to the way the optional scheduler works.
05820         resources_available reports when a resource is over-subscribed,
05821         so it's easy to tell.  */
05822       rt->units[stage + cycle][unit]++;
05823     }
05824 }
05825 
05826 
05827 void
05828 release_resources (resource_table *rt, xtensa_opcode opcode, int cycle)
05829 {
05830   int i;
05831   int uses = (rt->opcode_num_units) (rt->data, opcode);
05832 
05833   for (i = 0; i < uses; i++)
05834     {
05835       xtensa_funcUnit unit = (rt->opcode_unit_use) (rt->data, opcode, i);
05836       int stage = (rt->opcode_unit_stage) (rt->data, opcode, i);
05837       assert (rt->units[stage + cycle][unit] > 0);
05838       rt->units[stage + cycle][unit]--;
05839     }
05840 }
05841 
05842 
05843 /* Wrapper functions make parameterized resource reservation
05844    more convenient.  */
05845 
05846 int
05847 opcode_funcUnit_use_unit (void *data, xtensa_opcode opcode, int idx)
05848 {
05849   xtensa_funcUnit_use *use = xtensa_opcode_funcUnit_use (data, opcode, idx);
05850   return use->unit;
05851 }
05852 
05853 
05854 int
05855 opcode_funcUnit_use_stage (void *data, xtensa_opcode opcode, int idx)
05856 {
05857   xtensa_funcUnit_use *use = xtensa_opcode_funcUnit_use (data, opcode, idx);
05858   return use->stage;
05859 }
05860 
05861 
05862 /* Note that this function does not check issue constraints, but
05863    solely whether the hardware is available to execute the given
05864    instructions together.  It also doesn't check if the tinsns
05865    write the same state, or access the same tieports.  That is
05866    checked by check_t1_t2_reads_and_writes.  */
05867 
05868 static bfd_boolean
05869 resources_conflict (vliw_insn *vinsn)
05870 {
05871   int i;
05872   static resource_table *rt = NULL;
05873 
05874   /* This is the most common case by far.  Optimize it.  */
05875   if (vinsn->num_slots == 1)
05876     return FALSE;
05877 
05878   if (rt == NULL)
05879     {
05880       xtensa_isa isa = xtensa_default_isa;
05881       rt = new_resource_table
05882        (isa, xtensa_isa_num_pipe_stages (isa),
05883         xtensa_isa_num_funcUnits (isa),
05884         (unit_num_copies_func) xtensa_funcUnit_num_copies,
05885         (opcode_num_units_func) xtensa_opcode_num_funcUnit_uses,
05886         opcode_funcUnit_use_unit,
05887         opcode_funcUnit_use_stage);
05888     }
05889 
05890   clear_resource_table (rt);
05891 
05892   for (i = 0; i < vinsn->num_slots; i++)
05893     {
05894       if (!resources_available (rt, vinsn->slots[i].opcode, 0))
05895        return TRUE;
05896       reserve_resources (rt, vinsn->slots[i].opcode, 0);
05897     }
05898 
05899   return FALSE;
05900 }
05901 
05902 
05903 /* finish_vinsn, emit_single_op and helper functions.  */
05904 
05905 static bfd_boolean find_vinsn_conflicts (vliw_insn *);
05906 static xtensa_format xg_find_narrowest_format (vliw_insn *);
05907 static void xg_assemble_vliw_tokens (vliw_insn *);
05908 
05909 
05910 /* We have reached the end of a bundle; emit into the frag.  */
05911 
05912 static void
05913 finish_vinsn (vliw_insn *vinsn)
05914 {
05915   IStack slotstack;
05916   int i;
05917   char *file_name;
05918   unsigned line;
05919 
05920   if (find_vinsn_conflicts (vinsn))
05921     {
05922       xg_clear_vinsn (vinsn);
05923       return;
05924     }
05925 
05926   /* First, find a format that works.  */
05927   if (vinsn->format == XTENSA_UNDEFINED)
05928     vinsn->format = xg_find_narrowest_format (vinsn);
05929 
05930   if (vinsn->format == XTENSA_UNDEFINED)
05931     {
05932       as_where (&file_name, &line);
05933       as_bad_where (file_name, line,
05934                   _("couldn't find a valid instruction format"));
05935       fprintf (stderr, _("    ops were: "));
05936       for (i = 0; i < vinsn->num_slots; i++)
05937        fprintf (stderr, _(" %s;"),
05938                xtensa_opcode_name (xtensa_default_isa,
05939                                  vinsn->slots[i].opcode));
05940       fprintf (stderr, _("\n"));
05941       xg_clear_vinsn (vinsn);
05942       return;
05943     }
05944 
05945   if (vinsn->num_slots
05946       != xtensa_format_num_slots (xtensa_default_isa, vinsn->format))
05947     {
05948       as_bad (_("format '%s' allows %d slots, but there are %d opcodes"),
05949              xtensa_format_name (xtensa_default_isa, vinsn->format),
05950              xtensa_format_num_slots (xtensa_default_isa, vinsn->format),
05951              vinsn->num_slots);
05952       xg_clear_vinsn (vinsn);
05953       return;
05954     }
05955 
05956   if (resources_conflict (vinsn))
05957     {
05958       as_where (&file_name, &line);
05959       as_bad_where (file_name, line, _("illegal resource usage in bundle"));
05960       fprintf (stderr, "    ops were: ");
05961       for (i = 0; i < vinsn->num_slots; i++)
05962        fprintf (stderr, " %s;",
05963                xtensa_opcode_name (xtensa_default_isa,
05964                                  vinsn->slots[i].opcode));
05965       fprintf (stderr, "\n");
05966       xg_clear_vinsn (vinsn);
05967       return;
05968     }
05969 
05970   for (i = 0; i < vinsn->num_slots; i++)
05971     {
05972       if (vinsn->slots[i].opcode != XTENSA_UNDEFINED)
05973        {
05974          symbolS *lit_sym = NULL;
05975          int j;
05976          bfd_boolean e = FALSE;
05977          bfd_boolean saved_density = density_supported;
05978 
05979          /* We don't want to narrow ops inside multi-slot bundles.  */
05980          if (vinsn->num_slots > 1)
05981            density_supported = FALSE;
05982 
05983          istack_init (&slotstack);
05984          if (vinsn->slots[i].opcode == xtensa_nop_opcode)
05985            {
05986              vinsn->slots[i].opcode =
05987               xtensa_format_slot_nop_opcode (xtensa_default_isa,
05988                                           vinsn->format, i);
05989              vinsn->slots[i].ntok = 0;
05990            }
05991 
05992          if (xg_expand_assembly_insn (&slotstack, &vinsn->slots[i]))
05993            {
05994              e = TRUE;
05995              continue;
05996            }
05997 
05998          density_supported = saved_density;
05999 
06000          if (e)
06001            {
06002              xg_clear_vinsn (vinsn);
06003              return;
06004            }
06005 
06006          for (j = 0; j < slotstack.ninsn; j++)
06007            {
06008              TInsn *insn = &slotstack.insn[j];
06009              if (insn->insn_type == ITYPE_LITERAL)
06010               {
06011                 assert (lit_sym == NULL);
06012                 lit_sym = xg_assemble_literal (insn);
06013               }
06014              else
06015               {
06016                 assert (insn->insn_type == ITYPE_INSN);
06017                 if (lit_sym)
06018                   xg_resolve_literals (insn, lit_sym);
06019                 if (j != slotstack.ninsn - 1)
06020                   emit_single_op (insn);
06021               }
06022            }
06023 
06024          if (vinsn->num_slots > 1)
06025            {
06026              if (opcode_fits_format_slot
06027                 (slotstack.insn[slotstack.ninsn - 1].opcode,
06028                  vinsn->format, i))
06029               {
06030                 vinsn->slots[i] = slotstack.insn[slotstack.ninsn - 1];
06031               }
06032              else
06033               {
06034                 emit_single_op (&slotstack.insn[slotstack.ninsn - 1]);
06035                 if (vinsn->format == XTENSA_UNDEFINED)
06036                   vinsn->slots[i].opcode = xtensa_nop_opcode;
06037                 else
06038                   vinsn->slots[i].opcode
06039                     = xtensa_format_slot_nop_opcode (xtensa_default_isa,
06040                                                  vinsn->format, i);
06041 
06042                 vinsn->slots[i].ntok = 0;
06043               }
06044            }
06045          else
06046            {
06047              vinsn->slots[0] = slotstack.insn[slotstack.ninsn - 1];
06048              vinsn->format = XTENSA_UNDEFINED;
06049            }
06050        }
06051     }
06052 
06053   /* Now check resource conflicts on the modified bundle.  */
06054   if (resources_conflict (vinsn))
06055     {
06056       as_where (&file_name, &line);
06057       as_bad_where (file_name, line, _("illegal resource usage in bundle"));
06058       fprintf (stderr, "    ops were: ");
06059       for (i = 0; i < vinsn->num_slots; i++)
06060        fprintf (stderr, " %s;",
06061                xtensa_opcode_name (xtensa_default_isa,
06062                                  vinsn->slots[i].opcode));
06063       fprintf (stderr, "\n");
06064       xg_clear_vinsn (vinsn);
06065       return;
06066     }
06067 
06068   /* First, find a format that works.  */
06069   if (vinsn->format == XTENSA_UNDEFINED)
06070       vinsn->format = xg_find_narrowest_format (vinsn);
06071 
06072   xg_assemble_vliw_tokens (vinsn);
06073 
06074   xg_clear_vinsn (vinsn);
06075 }
06076 
06077 
06078 /* Given an vliw instruction, what conflicts are there in register
06079    usage and in writes to states and queues?
06080 
06081    This function does two things:
06082    1. Reports an error when a vinsn contains illegal combinations
06083       of writes to registers states or queues.
06084    2. Marks individual tinsns as not relaxable if the combination
06085       contains antidependencies.
06086 
06087    Job 2 handles things like swap semantics in instructions that need
06088    to be relaxed.  For example,
06089 
06090        addi a0, a1, 100000
06091 
06092    normally would be relaxed to
06093 
06094        l32r a0, some_label
06095        add a0, a1, a0
06096 
06097    _but_, if the above instruction is bundled with an a0 reader, e.g.,
06098 
06099        { addi a0, a1, 10000 ; add a2, a0, a4 ; }
06100 
06101    then we can't relax it into
06102 
06103        l32r a0, some_label
06104        { add a0, a1, a0 ; add a2, a0, a4 ; }
06105 
06106    because the value of a0 is trashed before the second add can read it.  */
06107 
06108 static char check_t1_t2_reads_and_writes (TInsn *, TInsn *);
06109 
06110 static bfd_boolean
06111 find_vinsn_conflicts (vliw_insn *vinsn)
06112 {
06113   int i, j;
06114   int branches = 0;
06115   xtensa_isa isa = xtensa_default_isa;
06116 
06117   assert (!past_xtensa_end);
06118 
06119   for (i = 0 ; i < vinsn->num_slots; i++)
06120     {
06121       TInsn *op1 = &vinsn->slots[i];
06122       if (op1->is_specific_opcode)
06123        op1->keep_wide = TRUE;
06124       else
06125        op1->keep_wide = FALSE;
06126     }
06127 
06128   for (i = 0 ; i < vinsn->num_slots; i++)
06129     {
06130       TInsn *op1 = &vinsn->slots[i];
06131 
06132       if (xtensa_opcode_is_branch (isa, op1->opcode) == 1)
06133        branches++;
06134 
06135       for (j = 0; j < vinsn->num_slots; j++)
06136        {
06137          if (i != j)
06138            {
06139              TInsn *op2 = &vinsn->slots[j];
06140              char conflict_type = check_t1_t2_reads_and_writes (op1, op2);
06141              switch (conflict_type)
06142               {
06143               case 'c':
06144                 as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) write the same register"),
06145                        xtensa_opcode_name (isa, op1->opcode), i,
06146                        xtensa_opcode_name (isa, op2->opcode), j);
06147                 return TRUE;
06148               case 'd':
06149                 as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) write the same state"),
06150                        xtensa_opcode_name (isa, op1->opcode), i,
06151                        xtensa_opcode_name (isa, op2->opcode), j);
06152                 return TRUE;
06153               case 'e':
06154                 as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) write the same port"),
06155                        xtensa_opcode_name (isa, op1->opcode), i,
06156                        xtensa_opcode_name (isa, op2->opcode), j);
06157                 return TRUE;
06158               case 'f':
06159                 as_bad (_("opcodes '%s' (slot %d) and '%s' (slot %d) both have volatile port accesses"),
06160                        xtensa_opcode_name (isa, op1->opcode), i,
06161                        xtensa_opcode_name (isa, op2->opcode), j);
06162                 return TRUE;
06163               default:
06164                 /* Everything is OK.  */
06165                 break;
06166               }
06167              op2->is_specific_opcode = (op2->is_specific_opcode
06168                                     || conflict_type == 'a');
06169            }
06170        }
06171     }
06172 
06173   if (branches > 1)
06174     {
06175       as_bad (_("multiple branches or jumps in the same bundle"));
06176       return TRUE;
06177     }
06178 
06179   return FALSE;
06180 }
06181 
06182 
06183 /* Check how the state used by t1 and t2 relate.
06184    Cases found are:
06185 
06186    case A: t1 reads a register t2 writes (an antidependency within a bundle)
06187    case B: no relationship between what is read and written (both could
06188            read the same reg though)
06189    case C: t1 writes a register t2 writes (a register conflict within a
06190            bundle)
06191    case D: t1 writes a state that t2 also writes
06192    case E: t1 writes a tie queue that t2 also writes
06193    case F: two volatile queue accesses
06194 */
06195 
06196 static char
06197 check_t1_t2_reads_and_writes (TInsn *t1, TInsn *t2)
06198 {
06199   xtensa_isa isa = xtensa_default_isa;
06200   xtensa_regfile t1_regfile, t2_regfile;
06201   int t1_reg, t2_reg;
06202   int t1_base_reg, t1_last_reg;
06203   int t2_base_reg, t2_last_reg;
06204   char t1_inout, t2_inout;
06205   int i, j;
06206   char conflict = 'b';
06207   int t1_states;
06208   int t2_states;
06209   int t1_interfaces;
06210   int t2_interfaces;
06211   bfd_boolean t1_volatile = FALSE;
06212   bfd_boolean t2_volatile = FALSE;
06213 
06214   /* Check registers.  */
06215   for (j = 0; j < t2->ntok; j++)
06216     {
06217       if (xtensa_operand_is_register (isa, t2->opcode, j) != 1)
06218        continue;
06219 
06220       t2_regfile = xtensa_operand_regfile (isa, t2->opcode, j);
06221       t2_base_reg = t2->tok[j].X_add_number;
06222       t2_last_reg = t2_base_reg + xtensa_operand_num_regs (isa, t2->opcode, j);
06223 
06224       for (i = 0; i < t1->ntok; i++)
06225        {
06226          if (xtensa_operand_is_register (isa, t1->opcode, i) != 1)
06227            continue;
06228 
06229          t1_regfile = xtensa_operand_regfile (isa, t1->opcode, i);
06230 
06231          if (t1_regfile != t2_regfile)
06232            continue;
06233 
06234          t1_inout = xtensa_operand_inout (isa, t1->opcode, i);
06235          t2_inout = xtensa_operand_inout (isa, t2->opcode, j);
06236 
06237          if (xtensa_operand_is_known_reg (isa, t1->opcode, i) == 0
06238              || xtensa_operand_is_known_reg (isa, t2->opcode, j) == 0)
06239            {
06240              if (t1_inout == 'm' || t1_inout == 'o'
06241                 || t2_inout == 'm' || t2_inout == 'o')
06242               {
06243                 conflict = 'a';
06244                 continue;
06245               }
06246            }
06247 
06248          t1_base_reg = t1->tok[i].X_add_number;
06249          t1_last_reg = (t1_base_reg
06250                       + xtensa_operand_num_regs (isa, t1->opcode, i));
06251 
06252          for (t1_reg = t1_base_reg; t1_reg < t1_last_reg; t1_reg++)
06253            {
06254              for (t2_reg = t2_base_reg; t2_reg < t2_last_reg; t2_reg++)
06255               {
06256                 if (t1_reg != t2_reg)
06257                   continue;
06258 
06259                 if (t2_inout == 'i' && (t1_inout == 'm' || t1_inout == 'o'))
06260                   {
06261                     conflict = 'a';
06262                     continue;
06263                   }
06264 
06265                 if (t1_inout == 'i' && (t2_inout == 'm' || t2_inout == 'o'))
06266                   {
06267                     conflict = 'a';
06268                     continue;
06269                   }
06270 
06271                 if (t1_inout != 'i' && t2_inout != 'i')
06272                   return 'c';
06273               }
06274            }
06275        }
06276     }
06277 
06278   /* Check states.  */
06279   t1_states = xtensa_opcode_num_stateOperands (isa, t1->opcode);
06280   t2_states = xtensa_opcode_num_stateOperands (isa, t2->opcode);
06281   for (j = 0; j < t2_states; j++)
06282     {
06283       xtensa_state t2_so = xtensa_stateOperand_state (isa, t2->opcode, j);
06284       t2_inout = xtensa_stateOperand_inout (isa, t2->opcode, j);
06285       for (i = 0; i < t1_states; i++)
06286        {
06287          xtensa_state t1_so = xtensa_stateOperand_state (isa, t1->opcode, i);
06288          t1_inout = xtensa_stateOperand_inout (isa, t1->opcode, i);
06289          if (t1_so != t2_so)
06290            continue;
06291 
06292          if (t2_inout == 'i' && (t1_inout == 'm' || t1_inout == 'o'))
06293            {
06294              conflict = 'a';
06295              continue;
06296            }
06297 
06298          if (t1_inout == 'i' && (t2_inout == 'm' || t2_inout == 'o'))
06299            {
06300              conflict = 'a';
06301              continue;
06302            }
06303 
06304          if (t1_inout != 'i' && t2_inout != 'i')
06305            return 'd';
06306        }
06307     }
06308 
06309   /* Check tieports.  */
06310   t1_interfaces = xtensa_opcode_num_interfaceOperands (isa, t1->opcode);
06311   t2_interfaces = xtensa_opcode_num_interfaceOperands (isa, t2->opcode);
06312   for (j = 0; j < t2_interfaces; j++)
06313     {
06314       xtensa_interface t2_int
06315        = xtensa_interfaceOperand_interface (isa, t2->opcode, j);
06316       int t2_class = xtensa_interface_class_id (isa, t2_int);
06317 
06318       t2_inout = xtensa_interface_inout (isa, t2_int);
06319       if (xtensa_interface_has_side_effect (isa, t2_int) == 1)
06320        t2_volatile = TRUE;
06321 
06322       for (i = 0; i < t1_interfaces; i++)
06323        {
06324          xtensa_interface t1_int
06325            = xtensa_interfaceOperand_interface (isa, t1->opcode, j);
06326          int t1_class = xtensa_interface_class_id (isa, t1_int);
06327 
06328          t1_inout = xtensa_interface_inout (isa, t1_int);
06329          if (xtensa_interface_has_side_effect (isa, t1_int) == 1)
06330            t1_volatile = TRUE;
06331 
06332          if (t1_volatile && t2_volatile && (t1_class == t2_class))
06333            return 'f';
06334 
06335          if (t1_int != t2_int)
06336            continue;
06337 
06338          if (t2_inout == 'i' && t1_inout == 'o')
06339            {
06340              conflict = 'a';
06341              continue;
06342            }
06343 
06344          if (t1_inout == 'i' && t2_inout == 'o')
06345            {
06346              conflict = 'a';
06347              continue;
06348            }
06349 
06350          if (t1_inout != 'i' && t2_inout != 'i')
06351            return 'e';
06352        }
06353     }
06354 
06355   return conflict;
06356 }
06357 
06358 
06359 static xtensa_format
06360 xg_find_narrowest_format (vliw_insn *vinsn)
06361 {
06362   /* Right now we assume that the ops within the vinsn are properly
06363      ordered for the slots that the programmer wanted them in.  In
06364      other words, we don't rearrange the ops in hopes of finding a
06365      better format.  The scheduler handles that.  */
06366 
06367   xtensa_isa isa = xtensa_default_isa;
06368   xtensa_format format;
06369   vliw_insn v_copy = *vinsn;
06370   xtensa_opcode nop_opcode = xtensa_nop_opcode;
06371 
06372   if (vinsn->num_slots == 1)
06373     return xg_get_single_format (vinsn->slots[0].opcode);
06374 
06375   for (format = 0; format < xtensa_isa_num_formats (isa); format++)
06376     {
06377       v_copy = *vinsn;
06378       if (xtensa_format_num_slots (isa, format) == v_copy.num_slots)
06379        {
06380          int slot;
06381          int fit = 0;
06382          for (slot = 0; slot < v_copy.num_slots; slot++)
06383            {
06384              if (v_copy.slots[slot].opcode == nop_opcode)
06385               {
06386                 v_copy.slots[slot].opcode =
06387                   xtensa_format_slot_nop_opcode (isa, format, slot);
06388                 v_copy.slots[slot].ntok = 0;
06389               }
06390 
06391              if (opcode_fits_format_slot (v_copy.slots[slot].opcode,
06392                                       format, slot))
06393               fit++;
06394              else if (v_copy.num_slots > 1)
06395               {
06396                 TInsn widened;
06397                 /* Try the widened version.  */
06398                 if (!v_copy.slots[slot].keep_wide
06399                     && !v_copy.slots[slot].is_specific_opcode
06400                     && xg_is_single_relaxable_insn (&v_copy.slots[slot],
06401                                                 &widened, TRUE)
06402                     && opcode_fits_format_slot (widened.opcode,
06403                                             format, slot))
06404                   {
06405                     v_copy.slots[slot] = widened;
06406                     fit++;
06407                   }
06408               }
06409            }
06410          if (fit == v_copy.num_slots)
06411            {
06412              *vinsn = v_copy;
06413              xtensa_format_encode (isa, format, vinsn->insnbuf);
06414              vinsn->format = format;
06415              break;
06416            }
06417        }
06418     }
06419 
06420   if (format == xtensa_isa_num_formats (isa))
06421     return XTENSA_UNDEFINED;
06422 
06423   return format;
06424 }
06425 
06426 
06427 /* Return the additional space needed in a frag
06428    for possible relaxations of any ops in a VLIW insn.
06429    Also fill out the relaxations that might be required of
06430    each tinsn in the vinsn.  */
06431 
06432 static int
06433 relaxation_requirements (vliw_insn *vinsn, bfd_boolean *pfinish_frag)
06434 {
06435   bfd_boolean finish_frag = FALSE;
06436   int extra_space = 0;
06437   int slot;
06438 
06439   for (slot = 0; slot < vinsn->num_slots; slot++)
06440     {
06441       TInsn *tinsn = &vinsn->slots[slot];
06442       if (!tinsn_has_symbolic_operands (tinsn))
06443        {
06444          /* A narrow instruction could be widened later to help
06445             alignment issues.  */
06446          if (xg_is_single_relaxable_insn (tinsn, 0, TRUE)
06447              && !tinsn->is_specific_opcode
06448              && vinsn->num_slots == 1)
06449            {
06450              /* Difference in bytes between narrow and wide insns...  */
06451              extra_space += 1;
06452              tinsn->subtype = RELAX_NARROW;
06453            }
06454        }
06455       else
06456        {
06457          if (workaround_b_j_loop_end
06458              && tinsn->opcode == xtensa_jx_opcode
06459              && use_transform ())
06460            {
06461              /* Add 2 of these.  */
06462              extra_space += 3; /* for the nop size */
06463              tinsn->subtype = RELAX_ADD_NOP_IF_PRE_LOOP_END;
06464            }
06465 
06466          /* Need to assemble it with space for the relocation.  */
06467          if (xg_is_relaxable_insn (tinsn, 0)
06468              && !tinsn->is_specific_opcode)
06469            {
06470              int max_size = xg_get_max_insn_widen_size (tinsn->opcode);
06471              int max_literal_size =
06472               xg_get_max_insn_widen_literal_size (tinsn->opcode);
06473 
06474              tinsn->literal_space = max_literal_size;
06475 
06476              tinsn->subtype = RELAX_IMMED;
06477              extra_space += max_size;
06478            }
06479          else
06480            {
06481              /* A fix record will be added for this instruction prior
06482                to relaxation, so make it end the frag.  */
06483              finish_frag = TRUE;
06484            }
06485        }
06486     }
06487   *pfinish_frag = finish_frag;
06488   return extra_space;
06489 }
06490 
06491 
06492 static void
06493 bundle_tinsn (TInsn *tinsn, vliw_insn *vinsn)
06494 {
06495   xtensa_isa isa = xtensa_default_isa;
06496   int slot, chosen_slot;
06497 
06498   vinsn->format = xg_get_single_format (tinsn->opcode);
06499   assert (vinsn->format != XTENSA_UNDEFINED);
06500   vinsn->num_slots = xtensa_format_num_slots (isa, vinsn->format);
06501 
06502   chosen_slot = xg_get_single_slot (tinsn->opcode);
06503   for (slot = 0; slot < vinsn->num_slots; slot++)
06504     {
06505       if (slot == chosen_slot)
06506        vinsn->slots[slot] = *tinsn;
06507       else
06508        {
06509          vinsn->slots[slot].opcode =
06510            xtensa_format_slot_nop_opcode (isa, vinsn->format, slot);
06511          vinsn->slots[slot].ntok = 0;
06512          vinsn->slots[slot].insn_type = ITYPE_INSN;
06513        }
06514     }
06515 }
06516 
06517 
06518 static bfd_boolean
06519 emit_single_op (TInsn *orig_insn)
06520 {
06521   int i;
06522   IStack istack;            /* put instructions into here */
06523   symbolS *lit_sym = NULL;
06524   symbolS *label_sym = NULL;
06525 
06526   istack_init (&istack);
06527 
06528   /* Special-case for "movi aX, foo" which is guaranteed to need relaxing.
06529      Because the scheduling and bundling characteristics of movi and
06530      l32r or const16 are so different, we can do much better if we relax
06531      it prior to scheduling and bundling, rather than after.  */
06532   if ((orig_insn->opcode == xtensa_movi_opcode
06533        || orig_insn->opcode == xtensa_movi_n_opcode)
06534       && !cur_vinsn.inside_bundle
06535       && (orig_insn->tok[1].X_op == O_symbol
06536          || orig_insn->tok[1].X_op == O_pltrel)
06537       && !orig_insn->is_specific_opcode && use_transform ())
06538     xg_assembly_relax (&istack, orig_insn, now_seg, frag_now, 0, 1, 0);
06539   else
06540     if (xg_expand_assembly_insn (&istack, orig_insn))
06541       return TRUE;
06542 
06543   for (i = 0; i < istack.ninsn; i++)
06544     {
06545       TInsn *insn = &istack.insn[i];
06546       switch (insn->insn_type)
06547        {
06548        case ITYPE_LITERAL:
06549          assert (lit_sym == NULL);
06550          lit_sym = xg_assemble_literal (insn);
06551          break;
06552        case ITYPE_LABEL:
06553          {
06554            static int relaxed_sym_idx = 0;
06555            char *label = xmalloc (strlen (FAKE_LABEL_NAME) + 12);
06556            sprintf (label, "%s_rl_%x", FAKE_LABEL_NAME, relaxed_sym_idx++);
06557            colon (label);
06558            assert (label_sym == NULL);
06559            label_sym = symbol_find_or_make (label);
06560            assert (label_sym);
06561            free (label);
06562          }
06563          break;
06564        case ITYPE_INSN:
06565          {
06566            vliw_insn v;
06567            if (lit_sym)
06568              xg_resolve_literals (insn, lit_sym);
06569            if (label_sym)
06570              xg_resolve_labels (insn, label_sym);
06571            xg_init_vinsn (&v);
06572            bundle_tinsn (insn, &v);
06573            finish_vinsn (&v);
06574            xg_free_vinsn (&v);
06575          }
06576          break;
06577        default:
06578          assert (0);
06579          break;
06580        }
06581     }
06582   return FALSE;
06583 }
06584 
06585 
06586 static int
06587 total_frag_text_expansion (fragS *fragP)
06588 {
06589   int slot;
06590   int total_expansion = 0;
06591 
06592   for (slot = 0; slot < MAX_SLOTS; slot++)
06593     total_expansion += fragP->tc_frag_data.text_expansion[slot];
06594 
06595   return total_expansion;
06596 }
06597 
06598 
06599 /* Emit a vliw instruction to the current fragment.  */
06600 
06601 static void
06602 xg_assemble_vliw_tokens (vliw_insn *vinsn)
06603 {
06604   bfd_boolean finish_frag;
06605   bfd_boolean is_jump = FALSE;
06606   bfd_boolean is_branch = FALSE;
06607   xtensa_isa isa = xtensa_default_isa;
06608   int i;
06609   int insn_size;
06610   int extra_space;
06611   char *f = NULL;
06612   int slot;
06613   unsigned current_line, best_linenum;
06614   char *current_file;
06615 
06616   best_linenum = UINT_MAX;
06617 
06618   if (generating_literals)
06619     {
06620       static int reported = 0;
06621       if (reported < 4)
06622        as_bad_where (frag_now->fr_file, frag_now->fr_line,
06623                     _("cannot assemble into a literal fragment"));
06624       if (reported == 3)
06625        as_bad (_("..."));
06626       reported++;
06627       return;
06628     }
06629 
06630   if (frag_now_fix () != 0
06631       && (! frag_now->tc_frag_data.is_insn
06632          || (vinsn_has_specific_opcodes (vinsn) && use_transform ())
06633          || !use_transform () != frag_now->tc_frag_data.is_no_transform
06634          || (directive_state[directive_longcalls]
06635              != frag_now->tc_frag_data.use_longcalls)
06636          || (directive_state[directive_absolute_literals]
06637              != frag_now->tc_frag_data.use_absolute_literals)))
06638     {
06639       frag_wane (frag_now);
06640       frag_new (0);
06641       xtensa_set_frag_assembly_state (frag_now);
06642     }
06643 
06644   if (workaround_a0_b_retw
06645       && vinsn->num_slots == 1
06646       && (get_last_insn_flags (now_seg, now_subseg) & FLAG_IS_A0_WRITER) != 0
06647       && xtensa_opcode_is_branch (isa, vinsn->slots[0].opcode) == 1
06648       && use_transform ())
06649     {
06650       has_a0_b_retw = TRUE;
06651 
06652       /* Mark this fragment with the special RELAX_ADD_NOP_IF_A0_B_RETW.
06653         After the first assembly pass we will check all of them and
06654         add a nop if needed.  */
06655       frag_now->tc_frag_data.is_insn = TRUE;
06656       frag_var (rs_machine_dependent, 4, 4,
06657               RELAX_ADD_NOP_IF_A0_B_RETW,
06658               frag_now->fr_symbol,
06659               frag_now->fr_offset,
06660               NULL);
06661       xtensa_set_frag_assembly_state (frag_now);
06662       frag_now->tc_frag_data.is_insn = TRUE;
06663       frag_var (rs_machine_dependent, 4, 4,
06664               RELAX_ADD_NOP_IF_A0_B_RETW,
06665               frag_now->fr_symbol,
06666               frag_now->fr_offset,
06667               NULL);
06668       xtensa_set_frag_assembly_state (frag_now);
06669     }
06670 
06671   for (i = 0; i < vinsn->num_slots; i++)
06672     {
06673       /* See if the instruction implies an aligned section.  */
06674       if (xtensa_opcode_is_loop (isa, vinsn->slots[i].opcode) == 1)
06675        record_alignment (now_seg, 2);
06676 
06677       /* Also determine the best line number for debug info.  */
06678       best_linenum = vinsn->slots[i].linenum < best_linenum
06679        ? vinsn->slots[i].linenum : best_linenum;
06680     }
06681 
06682   /* Special cases for instructions that force an alignment... */
06683   /* None of these opcodes are bundle-able.  */
06684   if (xtensa_opcode_is_loop (isa, vinsn->slots[0].opcode) == 1)
06685     {
06686       int max_fill;
06687 
06688       /* Remember the symbol that marks the end of the loop in the frag
06689         that marks the start of the loop.  This way we can easily find
06690         the end of the loop at the beginning, without adding special code
06691         to mark the loop instructions themselves.  */
06692       symbolS *target_sym = NULL;
06693       if (vinsn->slots[0].tok[1].X_op == O_symbol)
06694        target_sym = vinsn->slots[0].tok[1].X_add_symbol;
06695 
06696       xtensa_set_frag_assembly_state (frag_now);
06697       frag_now->tc_frag_data.is_insn = TRUE;
06698 
06699       max_fill = get_text_align_max_fill_size
06700        (get_text_align_power (xtensa_fetch_width),
06701         TRUE, frag_now->tc_frag_data.is_no_density);
06702 
06703       if (use_transform ())
06704        frag_var (rs_machine_dependent, max_fill, max_fill,
06705                 RELAX_ALIGN_NEXT_OPCODE, target_sym, 0, NULL);
06706       else
06707        frag_var (rs_machine_dependent, 0, 0,
06708                 RELAX_CHECK_ALIGN_NEXT_OPCODE, target_sym, 0, NULL);
06709       xtensa_set_frag_assembly_state (frag_now);
06710     }
06711 
06712   if (vinsn->slots[0].opcode == xtensa_entry_opcode
06713       && !vinsn->slots[0].is_specific_opcode)
06714     {
06715       xtensa_mark_literal_pool_location ();
06716       xtensa_move_labels (frag_now, 0);
06717       frag_var (rs_align_test, 1, 1, 0, NULL, 2, NULL);
06718     }
06719 
06720   if (vinsn->num_slots == 1)
06721     {
06722       if (workaround_a0_b_retw && use_transform ())
06723        set_last_insn_flags (now_seg, now_subseg, FLAG_IS_A0_WRITER,
06724                           is_register_writer (&vinsn->slots[0], "a", 0));
06725 
06726       set_last_insn_flags (now_seg, now_subseg, FLAG_IS_BAD_LOOPEND,
06727                         is_bad_loopend_opcode (&vinsn->slots[0]));
06728     }
06729   else
06730     set_last_insn_flags (now_seg, now_subseg, FLAG_IS_BAD_LOOPEND, FALSE);
06731 
06732   insn_size = xtensa_format_length (isa, vinsn->format);
06733 
06734   extra_space = relaxation_requirements (vinsn, &finish_frag);
06735 
06736   /* vinsn_to_insnbuf will produce the error.  */
06737   if (vinsn->format != XTENSA_UNDEFINED)
06738     {
06739       f = frag_more (insn_size + extra_space);
06740       xtensa_set_frag_assembly_state (frag_now);
06741       frag_now->tc_frag_data.is_insn = TRUE;
06742     }
06743 
06744   vinsn_to_insnbuf (vinsn, f, frag_now, FALSE);
06745   if (vinsn->format == XTENSA_UNDEFINED)
06746     return;
06747 
06748   xtensa_insnbuf_to_chars (isa, vinsn->insnbuf, (unsigned char *) f, 0);
06749 
06750   /* Temporarily set the logical line number to the one we want to appear
06751      in the debug information.  */
06752   as_where (&current_file, &current_line);
06753   new_logical_line (current_file, best_linenum);
06754   dwarf2_emit_insn (insn_size + extra_space);
06755   new_logical_line (current_file, current_line);
06756 
06757   for (slot = 0; slot < vinsn->num_slots; slot++)
06758     {
06759       TInsn *tinsn = &vinsn->slots[slot];
06760       frag_now->tc_frag_data.slot_subtypes[slot] = tinsn->subtype;
06761       frag_now->tc_frag_data.slot_symbols[slot] = tinsn->symbol;
06762       frag_now->tc_frag_data.slot_offsets[slot] = tinsn->offset;
06763       frag_now->tc_frag_data.literal_frags[slot] = tinsn->literal_frag;
06764       if (tinsn->literal_space != 0)
06765        xg_assemble_literal_space (tinsn->literal_space, slot);
06766 
06767       if (tinsn->subtype == RELAX_NARROW)
06768        assert (vinsn->num_slots == 1);
06769       if (xtensa_opcode_is_jump (isa, tinsn->opcode) == 1)
06770        is_jump = TRUE;
06771       if (xtensa_opcode_is_branch (isa, tinsn->opcode) == 1)
06772        is_branch = TRUE;
06773 
06774       if (tinsn->subtype || tinsn->symbol || tinsn->offset
06775          || tinsn->literal_frag || is_jump || is_branch)
06776        finish_frag = TRUE;
06777     }
06778 
06779   if (vinsn_has_specific_opcodes (vinsn) && use_transform ())
06780     frag_now->tc_frag_data.is_specific_opcode = TRUE;
06781 
06782   if (finish_frag)
06783     {
06784       frag_variant (rs_machine_dependent,
06785                   extra_space, extra_space, RELAX_SLOTS,
06786                   frag_now->fr_symbol, frag_now->fr_offset, f);
06787       xtensa_set_frag_assembly_state (frag_now);
06788     }
06789 
06790   /* Special cases for loops:
06791      close_loop_end should be inserted AFTER short_loop.
06792      Make sure that CLOSE loops are processed BEFORE short_loops
06793      when converting them.  */
06794 
06795   /* "short_loop": Add a NOP if the loop is < 4 bytes.  */
06796   if (xtensa_opcode_is_loop (isa, vinsn->slots[0].opcode) == 1
06797       && !vinsn->slots[0].is_specific_opcode)
06798     {
06799       if (workaround_short_loop && use_transform ())
06800        {
06801          maybe_has_short_loop = TRUE;
06802          frag_now->tc_frag_data.is_insn = TRUE;
06803          frag_var (rs_machine_dependent, 4, 4,
06804                   RELAX_ADD_NOP_IF_SHORT_LOOP,
06805                   frag_now->fr_symbol, frag_now->fr_offset, NULL);
06806          frag_now->tc_frag_data.is_insn = TRUE;
06807          frag_var (rs_machine_dependent, 4, 4,
06808                   RELAX_ADD_NOP_IF_SHORT_LOOP,
06809                   frag_now->fr_symbol, frag_now->fr_offset, NULL);
06810        }
06811 
06812       /* "close_loop_end": Add up to 12 bytes of NOPs to keep a
06813         loop at least 12 bytes away from another loop's end.  */
06814       if (workaround_close_loop_end && use_transform ())
06815        {
06816          maybe_has_close_loop_end = TRUE;
06817          frag_now->tc_frag_data.is_insn = TRUE;
06818          frag_var (rs_machine_dependent, 12, 12,
06819                   RELAX_ADD_NOP_IF_CLOSE_LOOP_END,
06820                   frag_now->fr_symbol, frag_now->fr_offset, NULL);
06821        }
06822     }
06823 
06824   if (use_transform ())
06825     {
06826       if (is_jump)
06827        {
06828          assert (finish_frag);
06829          frag_var (rs_machine_dependent,
06830                   UNREACHABLE_MAX_WIDTH, UNREACHABLE_MAX_WIDTH,
06831                   RELAX_UNREACHABLE,
06832                   frag_now->fr_symbol, frag_now->fr_offset, NULL);
06833          xtensa_set_frag_assembly_state (frag_now);
06834        }
06835       else if (is_branch && do_align_targets ())
06836        {
06837          assert (finish_frag);
06838          frag_var (rs_machine_dependent,
06839                   UNREACHABLE_MAX_WIDTH, UNREACHABLE_MAX_WIDTH,
06840                   RELAX_MAYBE_UNREACHABLE,
06841                   frag_now->fr_symbol, frag_now->fr_offset, NULL);
06842          xtensa_set_frag_assembly_state (frag_now);
06843          frag_var (rs_machine_dependent,
06844                   0, 0,
06845                   RELAX_MAYBE_DESIRE_ALIGN,
06846                   frag_now->fr_symbol, frag_now->fr_offset, NULL);
06847          xtensa_set_frag_assembly_state (frag_now);
06848        }
06849     }
06850 
06851   /* Now, if the original opcode was a call...  */
06852   if (do_align_targets ()
06853       && xtensa_opcode_is_call (isa, vinsn->slots[0].opcode) == 1)
06854     {
06855       float freq = get_subseg_total_freq (now_seg, now_subseg);
06856       frag_now->tc_frag_data.is_insn = TRUE;
06857       frag_var (rs_machine_dependent, 4, (int) freq, RELAX_DESIRE_ALIGN,
06858               frag_now->fr_symbol, frag_now->fr_offset, NULL);
06859       xtensa_set_frag_assembly_state (frag_now);
06860     }
06861 
06862   if (vinsn_has_specific_opcodes (vinsn) && use_transform ())
06863     {
06864       frag_wane (frag_now);
06865       frag_new (0);
06866       xtensa_set_frag_assembly_state (frag_now);
06867     }
06868 }
06869 
06870 
06871 /* xtensa_end and helper functions.  */
06872 
06873 static void xtensa_cleanup_align_frags (void);
06874 static void xtensa_fix_target_frags (void);
06875 static void xtensa_mark_narrow_branches (void);
06876 static void xtensa_mark_zcl_first_insns (void);
06877 static void xtensa_fix_a0_b_retw_frags (void);
06878 static void xtensa_fix_b_j_loop_end_frags (void);
06879 static void xtensa_fix_close_loop_end_frags (void);
06880 static void xtensa_fix_short_loop_frags (void);
06881 static void xtensa_sanity_check (void);
06882 static void xtensa_add_config_info (void);
06883 
06884 void
06885 xtensa_end (void)
06886 {
06887   directive_balance ();
06888   xtensa_flush_pending_output ();
06889 
06890   past_xtensa_end = TRUE;
06891 
06892   xtensa_move_literals ();
06893 
06894   xtensa_reorder_segments ();
06895   xtensa_cleanup_align_frags ();
06896   xtensa_fix_target_frags ();
06897   if (workaround_a0_b_retw && has_a0_b_retw)
06898     xtensa_fix_a0_b_retw_frags ();
06899   if (workaround_b_j_loop_end)
06900     xtensa_fix_b_j_loop_end_frags ();
06901 
06902   /* "close_loop_end" should be processed BEFORE "short_loop".  */
06903   if (workaround_close_loop_end && maybe_has_close_loop_end)
06904     xtensa_fix_close_loop_end_frags ();
06905 
06906   if (workaround_short_loop && maybe_has_short_loop)
06907     xtensa_fix_short_loop_frags ();
06908   if (align_targets)
06909     xtensa_mark_narrow_branches ();
06910   xtensa_mark_zcl_first_insns ();
06911 
06912   xtensa_sanity_check ();
06913 
06914   xtensa_add_config_info ();
06915 }
06916 
06917 
06918 static void
06919 xtensa_cleanup_align_frags (void)
06920 {
06921   frchainS *frchP;
06922   asection *s;
06923 
06924   for (s = stdoutput->sections; s; s = s->next)
06925     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
06926       {
06927        fragS *fragP;
06928        /* Walk over all of the fragments in a subsection.  */
06929        for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
06930          {
06931            if ((fragP->fr_type == rs_align
06932                || fragP->fr_type == rs_align_code
06933                || (fragP->fr_type == rs_machine_dependent
06934                    && (fragP->fr_subtype == RELAX_DESIRE_ALIGN
06935                       || fragP->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET)))
06936               && fragP->fr_fix == 0)
06937              {
06938               fragS *next = fragP->fr_next;
06939 
06940               while (next
06941                      && next->fr_fix == 0
06942                      && next->fr_type == rs_machine_dependent
06943                      && next->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET)
06944                 {
06945                   frag_wane (next);
06946                   next = next->fr_next;
06947                 }
06948              }
06949            /* If we don't widen branch targets, then they
06950               will be easier to align.  */
06951            if (fragP->tc_frag_data.is_branch_target
06952               && fragP->fr_opcode == fragP->fr_literal
06953               && fragP->fr_type == rs_machine_dependent
06954               && fragP->fr_subtype == RELAX_SLOTS
06955               && fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
06956              frag_wane (fragP);
06957            if (fragP->fr_type == rs_machine_dependent
06958               && fragP->fr_subtype == RELAX_UNREACHABLE)
06959              fragP->tc_frag_data.is_unreachable = TRUE;
06960          }
06961       }
06962 }
06963 
06964 
06965 /* Re-process all of the fragments looking to convert all of the
06966    RELAX_DESIRE_ALIGN_IF_TARGET fragments.  If there is a branch
06967    target in the next fragment, convert this to RELAX_DESIRE_ALIGN.
06968    Otherwise, convert to a .fill 0.  */
06969 
06970 static void
06971 xtensa_fix_target_frags (void)
06972 {
06973   frchainS *frchP;
06974   asection *s;
06975 
06976   /* When this routine is called, all of the subsections are still intact
06977      so we walk over subsections instead of sections.  */
06978   for (s = stdoutput->sections; s; s = s->next)
06979     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
06980       {
06981        fragS *fragP;
06982 
06983        /* Walk over all of the fragments in a subsection.  */
06984        for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
06985          {
06986            if (fragP->fr_type == rs_machine_dependent
06987               && fragP->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET)
06988              {
06989               if (next_frag_is_branch_target (fragP))
06990                 fragP->fr_subtype = RELAX_DESIRE_ALIGN;
06991               else
06992                 frag_wane (fragP);
06993              }
06994          }
06995       }
06996 }
06997 
06998 
06999 static bfd_boolean is_narrow_branch_guaranteed_in_range (fragS *, TInsn *);
07000 
07001 static void
07002 xtensa_mark_narrow_branches (void)
07003 {
07004   frchainS *frchP;
07005   asection *s;
07006 
07007   for (s = stdoutput->sections; s; s = s->next)
07008     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
07009       {
07010        fragS *fragP;
07011        /* Walk over all of the fragments in a subsection.  */
07012        for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
07013          {
07014            if (fragP->fr_type == rs_machine_dependent
07015               && fragP->fr_subtype == RELAX_SLOTS
07016               && fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED)
07017              {
07018               vliw_insn vinsn;
07019 
07020               vinsn_from_chars (&vinsn, fragP->fr_opcode);
07021               tinsn_immed_from_frag (&vinsn.slots[0], fragP, 0);
07022 
07023               if (vinsn.num_slots == 1
07024                   && xtensa_opcode_is_branch (xtensa_default_isa,
07025                                           vinsn.slots[0].opcode) == 1
07026                   && xg_get_single_size (vinsn.slots[0].opcode) == 2
07027                   && is_narrow_branch_guaranteed_in_range (fragP,
07028                                                       &vinsn.slots[0]))
07029                 {
07030                   fragP->fr_subtype = RELAX_SLOTS;
07031                   fragP->tc_frag_data.slot_subtypes[0] = RELAX_NARROW;
07032                   fragP->tc_frag_data.is_aligning_branch = 1;
07033                 }
07034              }
07035          }
07036       }
07037 }
07038 
07039 
07040 /* A branch is typically widened only when its target is out of
07041    range.  However, we would like to widen them to align a subsequent
07042    branch target when possible.
07043 
07044    Because the branch relaxation code is so convoluted, the optimal solution
07045    (combining the two cases) is difficult to get right in all circumstances.
07046    We therefore go with an "almost as good" solution, where we only
07047    use for alignment narrow branches that definitely will not expand to a
07048    jump and a branch.  These functions find and mark these cases.  */
07049 
07050 /* The range in bytes of BNEZ.N and BEQZ.N.  The target operand is encoded
07051    as PC + 4 + imm6, where imm6 is a 6-bit immediate ranging from 0 to 63.
07052    We start counting beginning with the frag after the 2-byte branch, so the
07053    maximum offset is (4 - 2) + 63 = 65.  */
07054 #define MAX_IMMED6 65
07055 
07056 static offsetT unrelaxed_frag_max_size (fragS *);
07057 
07058 static bfd_boolean
07059 is_narrow_branch_guaranteed_in_range (fragS *fragP, TInsn *tinsn)
07060 {
07061   const expressionS *expr = &tinsn->tok[1];
07062   symbolS *symbolP = expr->X_add_symbol;
07063   offsetT max_distance = expr->X_add_number;
07064   fragS *target_frag;
07065 
07066   if (expr->X_op != O_symbol)
07067     return FALSE;
07068 
07069   target_frag = symbol_get_frag (symbolP);
07070 
07071   max_distance += (S_GET_VALUE (symbolP) - target_frag->fr_address);
07072   if (is_branch_jmp_to_next (tinsn, fragP))
07073     return FALSE;
07074 
07075   /* The branch doesn't branch over it's own frag,
07076      but over the subsequent ones.  */
07077   fragP = fragP->fr_next;
07078   while (fragP != NULL && fragP != target_frag && max_distance <= MAX_IMMED6)
07079     {
07080       max_distance += unrelaxed_frag_max_size (fragP);
07081       fragP = fragP->fr_next;
07082     }
07083   if (max_distance <= MAX_IMMED6 && fragP == target_frag)
07084     return TRUE;
07085   return FALSE;
07086 }
07087 
07088 
07089 static void
07090 xtensa_mark_zcl_first_insns (void)
07091 {
07092   frchainS *frchP;
07093   asection *s;
07094 
07095   for (s = stdoutput->sections; s; s = s->next)
07096     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
07097       {
07098        fragS *fragP;
07099        /* Walk over all of the fragments in a subsection.  */
07100        for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
07101          {
07102            if (fragP->fr_type == rs_machine_dependent
07103               && (fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE
07104                   || fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE))
07105              {
07106               /* Find the loop frag.  */
07107               fragS *targ_frag = next_non_empty_frag (fragP);
07108               /* Find the first insn frag.  */
07109               targ_frag = next_non_empty_frag (targ_frag);
07110 
07111               /* Of course, sometimes (mostly for toy test cases) a
07112                  zero-cost loop instruction is the last in a section.  */
07113               if (targ_frag)
07114                 {
07115                   targ_frag->tc_frag_data.is_first_loop_insn = TRUE;
07116                   /* Do not widen a frag that is the first instruction of a
07117                      zero-cost loop.  It makes that loop harder to align.  */
07118                   if (targ_frag->fr_type == rs_machine_dependent
07119                      && targ_frag->fr_subtype == RELAX_SLOTS
07120                      && (targ_frag->tc_frag_data.slot_subtypes[0]
07121                          == RELAX_NARROW))
07122                     {
07123                      if (targ_frag->tc_frag_data.is_aligning_branch)
07124                        targ_frag->tc_frag_data.slot_subtypes[0] = RELAX_IMMED;
07125                      else
07126                        {
07127                          frag_wane (targ_frag);
07128                          targ_frag->tc_frag_data.slot_subtypes[0] = 0;
07129                        }
07130                     }
07131                 }
07132               if (fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE)
07133                 frag_wane (fragP);
07134              }
07135          }
07136       }
07137 }
07138 
07139 
07140 /* Re-process all of the fragments looking to convert all of the
07141    RELAX_ADD_NOP_IF_A0_B_RETW.  If the next instruction is a
07142    conditional branch or a retw/retw.n, convert this frag to one that
07143    will generate a NOP.  In any case close it off with a .fill 0.  */
07144 
07145 static bfd_boolean next_instrs_are_b_retw (fragS *);
07146 
07147 static void
07148 xtensa_fix_a0_b_retw_frags (void)
07149 {
07150   frchainS *frchP;
07151   asection *s;
07152 
07153   /* When this routine is called, all of the subsections are still intact
07154      so we walk over subsections instead of sections.  */
07155   for (s = stdoutput->sections; s; s = s->next)
07156     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
07157       {
07158        fragS *fragP;
07159 
07160        /* Walk over all of the fragments in a subsection.  */
07161        for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
07162          {
07163            if (fragP->fr_type == rs_machine_dependent
07164               && fragP->fr_subtype == RELAX_ADD_NOP_IF_A0_B_RETW)
07165              {
07166               if (next_instrs_are_b_retw (fragP))
07167                 {
07168                   if (fragP->tc_frag_data.is_no_transform)
07169                     as_bad (_("instruction sequence (write a0, branch, retw) may trigger hardware errata"));
07170                   else
07171                     relax_frag_add_nop (fragP);
07172                 }
07173               frag_wane (fragP);
07174              }
07175          }
07176       }
07177 }
07178 
07179 
07180 static bfd_boolean
07181 next_instrs_are_b_retw (fragS *fragP)
07182 {
07183   xtensa_opcode opcode;
07184   xtensa_format fmt;
07185   const fragS *next_fragP = next_non_empty_frag (fragP);
07186   static xtensa_insnbuf insnbuf = NULL;
07187   static xtensa_insnbuf slotbuf = NULL;
07188   xtensa_isa isa = xtensa_default_isa;
07189   int offset = 0;
07190   int slot;
07191   bfd_boolean branch_seen = FALSE;
07192 
07193   if (!insnbuf)
07194     {
07195       insnbuf = xtensa_insnbuf_alloc (isa);
07196       slotbuf = xtensa_insnbuf_alloc (isa);
07197     }
07198 
07199   if (next_fragP == NULL)
07200     return FALSE;
07201 
07202   /* Check for the conditional branch.  */
07203   xtensa_insnbuf_from_chars
07204     (isa, insnbuf, (unsigned char *) &next_fragP->fr_literal[offset], 0);
07205   fmt = xtensa_format_decode (isa, insnbuf);
07206   if (fmt == XTENSA_UNDEFINED)
07207     return FALSE;
07208 
07209   for (slot = 0; slot < xtensa_format_num_slots (isa, fmt); slot++)
07210     {
07211       xtensa_format_get_slot (isa, fmt, slot, insnbuf, slotbuf);
07212       opcode = xtensa_opcode_decode (isa, fmt, slot, slotbuf);
07213 
07214       branch_seen = (branch_seen
07215                    || xtensa_opcode_is_branch (isa, opcode) == 1);
07216     }
07217 
07218   if (!branch_seen)
07219     return FALSE;
07220 
07221   offset += xtensa_format_length (isa, fmt);
07222   if (offset == next_fragP->fr_fix)
07223     {
07224       next_fragP = next_non_empty_frag (next_fragP);
07225       offset = 0;
07226     }
07227 
07228   if (next_fragP == NULL)
07229     return FALSE;
07230 
07231   /* Check for the retw/retw.n.  */
07232   xtensa_insnbuf_from_chars
07233     (isa, insnbuf, (unsigned char *) &next_fragP->fr_literal[offset], 0);
07234   fmt = xtensa_format_decode (isa, insnbuf);
07235 
07236   /* Because RETW[.N] is not bundleable, a VLIW bundle here means that we
07237      have no problems.  */
07238   if (fmt == XTENSA_UNDEFINED
07239       || xtensa_format_num_slots (isa, fmt) != 1)
07240     return FALSE;
07241 
07242   xtensa_format_get_slot (isa, fmt, 0, insnbuf, slotbuf);
07243   opcode = xtensa_opcode_decode (isa, fmt, 0, slotbuf);
07244 
07245   if (opcode == xtensa_retw_opcode || opcode == xtensa_retw_n_opcode)
07246     return TRUE;
07247 
07248   return FALSE;
07249 }
07250 
07251 
07252 /* Re-process all of the fragments looking to convert all of the
07253    RELAX_ADD_NOP_IF_PRE_LOOP_END.  If there is one instruction and a
07254    loop end label, convert this frag to one that will generate a NOP.
07255    In any case close it off with a .fill 0.  */
07256 
07257 static bfd_boolean next_instr_is_loop_end (fragS *);
07258 
07259 static void
07260 xtensa_fix_b_j_loop_end_frags (void)
07261 {
07262   frchainS *frchP;
07263   asection *s;
07264 
07265   /* When this routine is called, all of the subsections are still intact
07266      so we walk over subsections instead of sections.  */
07267   for (s = stdoutput->sections; s; s = s->next)
07268     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
07269       {
07270        fragS *fragP;
07271 
07272        /* Walk over all of the fragments in a subsection.  */
07273        for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
07274          {
07275            if (fragP->fr_type == rs_machine_dependent
07276               && fragP->fr_subtype == RELAX_ADD_NOP_IF_PRE_LOOP_END)
07277              {
07278               if (next_instr_is_loop_end (fragP))
07279                 {
07280                   if (fragP->tc_frag_data.is_no_transform)
07281                     as_bad (_("branching or jumping to a loop end may trigger hardware errata"));
07282                   else
07283                     relax_frag_add_nop (fragP);
07284                 }
07285               frag_wane (fragP);
07286              }
07287          }
07288       }
07289 }
07290 
07291 
07292 static bfd_boolean
07293 next_instr_is_loop_end (fragS *fragP)
07294 {
07295   const fragS *next_fragP;
07296 
07297   if (next_frag_is_loop_target (fragP))
07298     return FALSE;
07299 
07300   next_fragP = next_non_empty_frag (fragP);
07301   if (next_fragP == NULL)
07302     return FALSE;
07303 
07304   if (!next_frag_is_loop_target (next_fragP))
07305     return FALSE;
07306 
07307   /* If the size is >= 3 then there is more than one instruction here.
07308      The hardware bug will not fire.  */
07309   if (next_fragP->fr_fix > 3)
07310     return FALSE;
07311 
07312   return TRUE;
07313 }
07314 
07315 
07316 /* Re-process all of the fragments looking to convert all of the
07317    RELAX_ADD_NOP_IF_CLOSE_LOOP_END.  If there is an loop end that is
07318    not MY loop's loop end within 12 bytes, add enough nops here to
07319    make it at least 12 bytes away.  In any case close it off with a
07320    .fill 0.  */
07321 
07322 static offsetT min_bytes_to_other_loop_end
07323   (fragS *, fragS *, offsetT);
07324 
07325 static void
07326 xtensa_fix_close_loop_end_frags (void)
07327 {
07328   frchainS *frchP;
07329   asection *s;
07330 
07331   /* When this routine is called, all of the subsections are still intact
07332      so we walk over subsections instead of sections.  */
07333   for (s = stdoutput->sections; s; s = s->next)
07334     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
07335       {
07336        fragS *fragP;
07337 
07338        fragS *current_target = NULL;
07339 
07340        /* Walk over all of the fragments in a subsection.  */
07341        for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
07342          {
07343            if (fragP->fr_type == rs_machine_dependent
07344               && ((fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE)
07345                   || (fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE)))
07346              current_target = symbol_get_frag (fragP->fr_symbol);
07347 
07348            if (current_target
07349               && fragP->fr_type == rs_machine_dependent
07350               && fragP->fr_subtype == RELAX_ADD_NOP_IF_CLOSE_LOOP_END)
07351              {
07352               offsetT min_bytes;
07353               int bytes_added = 0;
07354 
07355 #define REQUIRED_LOOP_DIVIDING_BYTES 12
07356               /* Max out at 12.  */
07357               min_bytes = min_bytes_to_other_loop_end
07358                 (fragP->fr_next, current_target, REQUIRED_LOOP_DIVIDING_BYTES);
07359 
07360               if (min_bytes < REQUIRED_LOOP_DIVIDING_BYTES)
07361                 {
07362                   if (fragP->tc_frag_data.is_no_transform)
07363                     as_bad (_("loop end too close to another loop end may trigger hardware errata"));
07364                   else
07365                     {
07366                      while (min_bytes + bytes_added
07367                             < REQUIRED_LOOP_DIVIDING_BYTES)
07368                        {
07369                          int length = 3;
07370 
07371                          if (fragP->fr_var < length)
07372                            as_fatal (_("fr_var %lu < length %d"),
07373                                    (long) fragP->fr_var, length);
07374                          else
07375                            {
07376                             assemble_nop (length,
07377                                          fragP->fr_literal + fragP->fr_fix);
07378                             fragP->fr_fix += length;
07379                             fragP->fr_var -= length;
07380                            }
07381                          bytes_added += length;
07382                        }
07383                     }
07384                 }
07385               frag_wane (fragP);
07386              }
07387            assert (fragP->fr_type != rs_machine_dependent
07388                   || fragP->fr_subtype != RELAX_ADD_NOP_IF_CLOSE_LOOP_END);
07389          }
07390       }
07391 }
07392 
07393 
07394 static offsetT unrelaxed_frag_min_size (fragS *);
07395 
07396 static offsetT
07397 min_bytes_to_other_loop_end (fragS *fragP,
07398                           fragS *current_target,
07399                           offsetT max_size)
07400 {
07401   offsetT offset = 0;
07402   fragS *current_fragP;
07403 
07404   for (current_fragP = fragP;
07405        current_fragP;
07406        current_fragP = current_fragP->fr_next)
07407     {
07408       if (current_fragP->tc_frag_data.is_loop_target
07409          && current_fragP != current_target)
07410        return offset;
07411 
07412       offset += unrelaxed_frag_min_size (current_fragP);
07413 
07414       if (offset >= max_size)
07415        return max_size;
07416     }
07417   return max_size;
07418 }
07419 
07420 
07421 static offsetT
07422 unrelaxed_frag_min_size (fragS *fragP)
07423 {
07424   offsetT size = fragP->fr_fix;
07425 
07426   /* Add fill size.  */
07427   if (fragP->fr_type == rs_fill)
07428     size += fragP->fr_offset;
07429 
07430   return size;
07431 }
07432 
07433 
07434 static offsetT
07435 unrelaxed_frag_max_size (fragS *fragP)
07436 {
07437   offsetT size = fragP->fr_fix;
07438   switch (fragP->fr_type)
07439     {
07440     case 0:
07441       /* Empty frags created by the obstack allocation scheme
07442         end up with type 0.  */
07443       break;
07444     case rs_fill:
07445     case rs_org:
07446     case rs_space:
07447       size += fragP->fr_offset;
07448       break;
07449     case rs_align:
07450     case rs_align_code:
07451     case rs_align_test:
07452     case rs_leb128:
07453     case rs_cfa:
07454     case rs_dwarf2dbg:
07455       /* No further adjustments needed.  */
07456       break;
07457     case rs_machine_dependent:
07458       if (fragP->fr_subtype != RELAX_DESIRE_ALIGN)
07459        size += fragP->fr_var;
07460       break;
07461     default:
07462       /* We had darn well better know how big it is.  */
07463       assert (0);
07464       break;
07465     }
07466 
07467   return size;
07468 }
07469 
07470 
07471 /* Re-process all of the fragments looking to convert all
07472    of the RELAX_ADD_NOP_IF_SHORT_LOOP.  If:
07473 
07474    A)
07475      1) the instruction size count to the loop end label
07476         is too short (<= 2 instructions),
07477      2) loop has a jump or branch in it
07478 
07479    or B)
07480      1) workaround_all_short_loops is TRUE
07481      2) The generating loop was a  'loopgtz' or 'loopnez'
07482      3) the instruction size count to the loop end label is too short
07483         (<= 2 instructions)
07484    then convert this frag (and maybe the next one) to generate a NOP.
07485    In any case close it off with a .fill 0.  */
07486 
07487 static int count_insns_to_loop_end (fragS *, bfd_boolean, int);
07488 static bfd_boolean branch_before_loop_end (fragS *);
07489 
07490 static void
07491 xtensa_fix_short_loop_frags (void)
07492 {
07493   frchainS *frchP;
07494   asection *s;
07495 
07496   /* When this routine is called, all of the subsections are still intact
07497      so we walk over subsections instead of sections.  */
07498   for (s = stdoutput->sections; s; s = s->next)
07499     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
07500       {
07501        fragS *fragP;
07502        fragS *current_target = NULL;
07503        xtensa_opcode current_opcode = XTENSA_UNDEFINED;
07504 
07505        /* Walk over all of the fragments in a subsection.  */
07506        for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
07507          {
07508            if (fragP->fr_type == rs_machine_dependent
07509               && ((fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE)
07510                   || (fragP->fr_subtype == RELAX_CHECK_ALIGN_NEXT_OPCODE)))
07511              {
07512               TInsn t_insn;
07513               fragS *loop_frag = next_non_empty_frag (fragP);
07514               tinsn_from_chars (&t_insn, loop_frag->fr_opcode, 0);
07515               current_target = symbol_get_frag (fragP->fr_symbol);
07516               current_opcode = t_insn.opcode;
07517               assert (xtensa_opcode_is_loop (xtensa_default_isa,
07518                                           current_opcode) == 1);
07519              }
07520 
07521            if (fragP->fr_type == rs_machine_dependent
07522               && fragP->fr_subtype == RELAX_ADD_NOP_IF_SHORT_LOOP)
07523              {
07524               if (count_insns_to_loop_end (fragP->fr_next, TRUE, 3) < 3
07525                   && (branch_before_loop_end (fragP->fr_next)
07526                      || (workaround_all_short_loops
07527                          && current_opcode != XTENSA_UNDEFINED
07528                          && current_opcode != xtensa_loop_opcode)))
07529                 {
07530                   if (fragP->tc_frag_data.is_no_transform)
07531                     as_bad (_("loop containing less than three instructions may trigger hardware errata"));
07532                   else
07533                     relax_frag_add_nop (fragP);
07534                 }
07535               frag_wane (fragP);
07536              }
07537          }
07538       }
07539 }
07540 
07541 
07542 static int unrelaxed_frag_min_insn_count (fragS *);
07543 
07544 static int
07545 count_insns_to_loop_end (fragS *base_fragP,
07546                       bfd_boolean count_relax_add,
07547                       int max_count)
07548 {
07549   fragS *fragP = NULL;
07550   int insn_count = 0;
07551 
07552   fragP = base_fragP;
07553 
07554   for (; fragP && !fragP->tc_frag_data.is_loop_target; fragP = fragP->fr_next)
07555     {
07556       insn_count += unrelaxed_frag_min_insn_count (fragP);
07557       if (insn_count >= max_count)
07558        return max_count;
07559 
07560       if (count_relax_add)
07561        {
07562          if (fragP->fr_type == rs_machine_dependent
07563              && fragP->fr_subtype == RELAX_ADD_NOP_IF_SHORT_LOOP)
07564            {
07565              /* In order to add the appropriate number of
07566                 NOPs, we count an instruction for downstream
07567                 occurrences.  */
07568              insn_count++;
07569              if (insn_count >= max_count)
07570               return max_count;
07571            }
07572        }
07573     }
07574   return insn_count;
07575 }
07576 
07577 
07578 static int
07579 unrelaxed_frag_min_insn_count (fragS *fragP)
07580 {
07581   xtensa_isa isa = xtensa_default_isa;
07582   static xtensa_insnbuf insnbuf = NULL;
07583   int insn_count = 0;
07584   int offset = 0;
07585 
07586   if (!fragP->tc_frag_data.is_insn)
07587     return insn_count;
07588 
07589   if (!insnbuf)
07590     insnbuf = xtensa_insnbuf_alloc (isa);
07591 
07592   /* Decode the fixed instructions.  */
07593   while (offset < fragP->fr_fix)
07594     {
07595       xtensa_format fmt;
07596 
07597       xtensa_insnbuf_from_chars
07598        (isa, insnbuf, (unsigned char *) fragP->fr_literal + offset, 0);
07599       fmt = xtensa_format_decode (isa, insnbuf);
07600 
07601       if (fmt == XTENSA_UNDEFINED)
07602        {
07603          as_fatal (_("undecodable instruction in instruction frag"));
07604          return insn_count;
07605        }
07606       offset += xtensa_format_length (isa, fmt);
07607       insn_count++;
07608     }
07609 
07610   return insn_count;
07611 }
07612 
07613 
07614 static bfd_boolean unrelaxed_frag_has_b_j (fragS *);
07615 
07616 static bfd_boolean
07617 branch_before_loop_end (fragS *base_fragP)
07618 {
07619   fragS *fragP;
07620 
07621   for (fragP = base_fragP;
07622        fragP && !fragP->tc_frag_data.is_loop_target;
07623        fragP = fragP->fr_next)
07624     {
07625       if (unrelaxed_frag_has_b_j (fragP))
07626        return TRUE;
07627     }
07628   return FALSE;
07629 }
07630 
07631 
07632 static bfd_boolean
07633 unrelaxed_frag_has_b_j (fragS *fragP)
07634 {
07635   static xtensa_insnbuf insnbuf = NULL;
07636   xtensa_isa isa = xtensa_default_isa;
07637   int offset = 0;
07638 
07639   if (!fragP->tc_frag_data.is_insn)
07640     return FALSE;
07641 
07642   if (!insnbuf)
07643     insnbuf = xtensa_insnbuf_alloc (isa);
07644 
07645   /* Decode the fixed instructions.  */
07646   while (offset < fragP->fr_fix)
07647     {
07648       xtensa_format fmt;
07649       int slot;
07650 
07651       xtensa_insnbuf_from_chars
07652        (isa, insnbuf, (unsigned char *) fragP->fr_literal + offset, 0);
07653       fmt = xtensa_format_decode (isa, insnbuf);
07654       if (fmt == XTENSA_UNDEFINED)
07655        return FALSE;
07656 
07657       for (slot = 0; slot < xtensa_format_num_slots (isa, fmt); slot++)
07658        {
07659          xtensa_opcode opcode =
07660            get_opcode_from_buf (fragP->fr_literal + offset, slot);
07661          if (xtensa_opcode_is_branch (isa, opcode) == 1
07662              || xtensa_opcode_is_jump (isa, opcode) == 1)
07663            return TRUE;
07664        }
07665       offset += xtensa_format_length (isa, fmt);
07666     }
07667   return FALSE;
07668 }
07669 
07670 
07671 /* Checks to be made after initial assembly but before relaxation.  */
07672 
07673 static bfd_boolean is_empty_loop (const TInsn *, fragS *);
07674 static bfd_boolean is_local_forward_loop (const TInsn *, fragS *);
07675 
07676 static void
07677 xtensa_sanity_check (void)
07678 {
07679   char *file_name;
07680   unsigned line;
07681   frchainS *frchP;
07682   asection *s;
07683 
07684   as_where (&file_name, &line);
07685   for (s = stdoutput->sections; s; s = s->next)
07686     for (frchP = seg_info (s)->frchainP; frchP; frchP = frchP->frch_next)
07687       {
07688        fragS *fragP;
07689 
07690        /* Walk over all of the fragments in a subsection.  */
07691        for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
07692          {
07693            if (fragP->fr_type == rs_machine_dependent
07694               && fragP->fr_subtype == RELAX_SLOTS 
07695               && fragP->tc_frag_data.slot_subtypes[0] == RELAX_IMMED)
07696              {
07697               static xtensa_insnbuf insnbuf = NULL;
07698               TInsn t_insn;
07699 
07700               if (fragP->fr_opcode != NULL)
07701                 {
07702                   if (!insnbuf)
07703                     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
07704                   tinsn_from_chars (&t_insn, fragP->fr_opcode, 0);
07705                   tinsn_immed_from_frag (&t_insn, fragP, 0);
07706 
07707                   if (xtensa_opcode_is_loop (xtensa_default_isa,
07708                                           t_insn.opcode) == 1)
07709                     {
07710                      if (is_empty_loop (&t_insn, fragP))
07711                        {
07712                          new_logical_line (fragP->fr_file, fragP->fr_line);
07713                          as_bad (_("invalid empty loop"));
07714                        }
07715                      if (!is_local_forward_loop (&t_insn, fragP))
07716                        {
07717                          new_logical_line (fragP->fr_file, fragP->fr_line);
07718                          as_bad (_("loop target does not follow "
07719                                   "loop instruction in section"));
07720                        }
07721                     }
07722                 }
07723              }
07724          }
07725       }
07726   new_logical_line (file_name, line);
07727 }
07728 
07729 
07730 #define LOOP_IMMED_OPN 1
07731 
07732 /* Return TRUE if the loop target is the next non-zero fragment.  */
07733 
07734 static bfd_boolean
07735 is_empty_loop (const TInsn *insn, fragS *fragP)
07736 {
07737   const expressionS *expr;
07738   symbolS *symbolP;
07739   fragS *next_fragP;
07740 
07741   if (insn->insn_type != ITYPE_INSN)
07742     return FALSE;
07743 
07744   if (xtensa_opcode_is_loop (xtensa_default_isa, insn->opcode) != 1)
07745     return FALSE;
07746 
07747   if (insn->ntok <= LOOP_IMMED_OPN)
07748     return FALSE;
07749 
07750   expr = &insn->tok[LOOP_IMMED_OPN];
07751 
07752   if (expr->X_op != O_symbol)
07753     return FALSE;
07754 
07755   symbolP = expr->X_add_symbol;
07756   if (!symbolP)
07757     return FALSE;
07758 
07759   if (symbol_get_frag (symbolP) == NULL)
07760     return FALSE;
07761 
07762   if (S_GET_VALUE (symbolP) != 0)
07763     return FALSE;
07764 
07765   /* Walk through the zero-size fragments from this one.  If we find
07766      the target fragment, then this is a zero-size loop.  */
07767 
07768   for (next_fragP = fragP->fr_next;
07769        next_fragP != NULL;
07770        next_fragP = next_fragP->fr_next)
07771     {
07772       if (next_fragP == symbol_get_frag (symbolP))
07773        return TRUE;
07774       if (next_fragP->fr_fix != 0)
07775        return FALSE;
07776     }
07777   return FALSE;
07778 }
07779 
07780 
07781 static bfd_boolean
07782 is_local_forward_loop (const TInsn *insn, fragS *fragP)
07783 {
07784   const expressionS *expr;
07785   symbolS *symbolP;
07786   fragS *next_fragP;
07787 
07788   if (insn->insn_type != ITYPE_INSN)
07789     return FALSE;
07790 
07791   if (xtensa_opcode_is_loop (xtensa_default_isa, insn->opcode) != 1)
07792     return FALSE;
07793 
07794   if (insn->ntok <= LOOP_IMMED_OPN)
07795     return FALSE;
07796 
07797   expr = &insn->tok[LOOP_IMMED_OPN];
07798 
07799   if (expr->X_op != O_symbol)
07800     return FALSE;
07801 
07802   symbolP = expr->X_add_symbol;
07803   if (!symbolP)
07804     return FALSE;
07805 
07806   if (symbol_get_frag (symbolP) == NULL)
07807     return FALSE;
07808 
07809   /* Walk through fragments until we find the target.
07810      If we do not find the target, then this is an invalid loop.  */
07811 
07812   for (next_fragP = fragP->fr_next;
07813        next_fragP != NULL;
07814        next_fragP = next_fragP->fr_next)
07815     {
07816       if (next_fragP == symbol_get_frag (symbolP))
07817        return TRUE;
07818     }
07819 
07820   return FALSE;
07821 }
07822 
07823 
07824 #define XTINFO_NAME "Xtensa_Info"
07825 #define XTINFO_NAMESZ 12
07826 #define XTINFO_TYPE 1
07827 
07828 static void
07829 xtensa_add_config_info (void)
07830 {
07831   asection *info_sec;
07832   char *data, *p;
07833   int sz;
07834 
07835   info_sec = subseg_new (".xtensa.info", 0);
07836   bfd_set_section_flags (stdoutput, info_sec, SEC_HAS_CONTENTS | SEC_READONLY);
07837 
07838   data = xmalloc (100);
07839   sprintf (data, "USE_ABSOLUTE_LITERALS=%d\nABI=%d\n",
07840           XSHAL_USE_ABSOLUTE_LITERALS, XSHAL_ABI);
07841   sz = strlen (data) + 1;
07842 
07843   /* Add enough null terminators to pad to a word boundary.  */
07844   do
07845     data[sz++] = 0;
07846   while ((sz & 3) != 0);
07847 
07848   /* Follow the standard note section layout:
07849      First write the length of the name string.  */
07850   p = frag_more (4);
07851   md_number_to_chars (p, (valueT) XTINFO_NAMESZ, 4);
07852 
07853   /* Next comes the length of the "descriptor", i.e., the actual data.  */
07854   p = frag_more (4);
07855   md_number_to_chars (p, (valueT) sz, 4);
07856 
07857   /* Write the note type.  */
07858   p = frag_more (4);
07859   md_number_to_chars (p, (valueT) XTINFO_TYPE, 4);
07860 
07861   /* Write the name field.  */
07862   p = frag_more (XTINFO_NAMESZ);
07863   memcpy (p, XTINFO_NAME, XTINFO_NAMESZ);
07864 
07865   /* Finally, write the descriptor.  */
07866   p = frag_more (sz);
07867   memcpy (p, data, sz);
07868 
07869   free (data);
07870 }
07871 
07872 
07873 /* Alignment Functions.  */
07874 
07875 static int
07876 get_text_align_power (unsigned target_size)
07877 {
07878   if (target_size <= 4)
07879     return 2;
07880   assert (target_size == 8);
07881   return 3;
07882 }
07883 
07884 
07885 static int
07886 get_text_align_max_fill_size (int align_pow,
07887                            bfd_boolean use_nops,
07888                            bfd_boolean use_no_density)
07889 {
07890   if (!use_nops)
07891     return (1 << align_pow);
07892   if (use_no_density)
07893     return 3 * (1 << align_pow);
07894 
07895   return 1 + (1 << align_pow);
07896 }
07897 
07898 
07899 /* Calculate the minimum bytes of fill needed at "address" to align a
07900    target instruction of size "target_size" so that it does not cross a
07901    power-of-two boundary specified by "align_pow".  If "use_nops" is FALSE,
07902    the fill can be an arbitrary number of bytes.  Otherwise, the space must
07903    be filled by NOP instructions.  */
07904 
07905 static int
07906 get_text_align_fill_size (addressT address,
07907                        int align_pow,
07908                        int target_size,
07909                        bfd_boolean use_nops,
07910                        bfd_boolean use_no_density)
07911 {
07912   addressT alignment, fill, fill_limit, fill_step;
07913   bfd_boolean skip_one = FALSE;
07914 
07915   alignment = (1 << align_pow);
07916   assert (target_size > 0 && alignment >= (addressT) target_size);
07917 
07918   if (!use_nops)
07919     {
07920       fill_limit = alignment;
07921       fill_step = 1;
07922     }
07923   else if (!use_no_density)
07924     {
07925       /* Combine 2- and 3-byte NOPs to fill anything larger than one.  */
07926       fill_limit = alignment * 2;
07927       fill_step = 1;
07928       skip_one = TRUE;
07929     }
07930   else
07931     {
07932       /* Fill with 3-byte NOPs -- can only fill multiples of 3.  */
07933       fill_limit = alignment * 3;
07934       fill_step = 3;
07935     }
07936 
07937   /* Try all fill sizes until finding one that works.  */
07938   for (fill = 0; fill < fill_limit; fill += fill_step)
07939     {
07940       if (skip_one && fill == 1)
07941        continue;
07942       if ((address + fill) >> align_pow
07943          == (address + fill + target_size - 1) >> align_pow)
07944        return fill;
07945     }
07946   assert (0);
07947   return 0;
07948 }
07949 
07950 
07951 static int
07952 branch_align_power (segT sec)
07953 {
07954   /* If the Xtensa processor has a fetch width of 8 bytes, and the section
07955      is aligned to at least an 8-byte boundary, then a branch target need
07956      only fit within an 8-byte aligned block of memory to avoid a stall.
07957      Otherwise, try to fit branch targets within 4-byte aligned blocks
07958      (which may be insufficient, e.g., if the section has no alignment, but
07959      it's good enough).  */
07960   if (xtensa_fetch_width == 8)
07961     {
07962       if (get_recorded_alignment (sec) >= 3)
07963        return 3;
07964     }
07965   else
07966     assert (xtensa_fetch_width == 4);
07967 
07968   return 2;
07969 }
07970 
07971 
07972 /* This will assert if it is not possible.  */
07973 
07974 static int
07975 get_text_align_nop_count (offsetT fill_size, bfd_boolean use_no_density)
07976 {
07977   int count = 0;
07978 
07979   if (use_no_density)
07980     {
07981       assert (fill_size % 3 == 0);
07982       return (fill_size / 3);
07983     }
07984 
07985   assert (fill_size != 1);  /* Bad argument.  */
07986 
07987   while (fill_size > 1)
07988     {
07989       int insn_size = 3;
07990       if (fill_size == 2 || fill_size == 4)
07991        insn_size = 2;
07992       fill_size -= insn_size;
07993       count++;
07994     }
07995   assert (fill_size != 1);  /* Bad algorithm.  */
07996   return count;
07997 }
07998 
07999 
08000 static int
08001 get_text_align_nth_nop_size (offsetT fill_size,
08002                           int n,
08003                           bfd_boolean use_no_density)
08004 {
08005   int count = 0;
08006 
08007   if (use_no_density)
08008     return 3;
08009 
08010   assert (fill_size != 1);  /* Bad argument.  */
08011 
08012   while (fill_size > 1)
08013     {
08014       int insn_size = 3;
08015       if (fill_size == 2 || fill_size == 4)
08016        insn_size = 2;
08017       fill_size -= insn_size;
08018       count++;
08019       if (n + 1 == count)
08020        return insn_size;
08021     }
08022   assert (0);
08023   return 0;
08024 }
08025 
08026 
08027 /* For the given fragment, find the appropriate address
08028    for it to begin at if we are using NOPs to align it.  */
08029 
08030 static addressT
08031 get_noop_aligned_address (fragS *fragP, addressT address)
08032 {
08033   /* The rule is: get next fragment's FIRST instruction.  Find
08034      the smallest number of bytes that need to be added to
08035      ensure that the next fragment's FIRST instruction will fit
08036      in a single word.
08037 
08038      E.G.,   2 bytes : 0, 1, 2 mod 4
08039             3 bytes: 0, 1 mod 4
08040 
08041      If the FIRST instruction MIGHT be relaxed,
08042      assume that it will become a 3-byte instruction.
08043 
08044      Note again here that LOOP instructions are not bundleable,
08045      and this relaxation only applies to LOOP opcodes.  */
08046 
08047   int fill_size = 0;
08048   int first_insn_size;
08049   int loop_insn_size;
08050   addressT pre_opcode_bytes;
08051   int align_power;
08052   fragS *first_insn;
08053   xtensa_opcode opcode;
08054   bfd_boolean is_loop;
08055 
08056   assert (fragP->fr_type == rs_machine_dependent);
08057   assert (fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE);
08058 
08059   /* Find the loop frag.  */
08060   first_insn = next_non_empty_frag (fragP);
08061   /* Now find the first insn frag.  */
08062   first_insn = next_non_empty_frag (first_insn);
08063 
08064   is_loop = next_frag_opcode_is_loop (fragP, &opcode);
08065   assert (is_loop);
08066   loop_insn_size = xg_get_single_size (opcode);
08067 
08068   pre_opcode_bytes = next_frag_pre_opcode_bytes (fragP);
08069   pre_opcode_bytes += loop_insn_size;
08070 
08071   /* For loops, the alignment depends on the size of the
08072      instruction following the loop, not the LOOP instruction.  */
08073 
08074   if (first_insn == NULL)
08075     first_insn_size = xtensa_fetch_width;
08076   else
08077     first_insn_size = get_loop_align_size (frag_format_size (first_insn));
08078 
08079   /* If it was 8, then we'll need a larger alignment for the section.  */
08080   align_power = get_text_align_power (first_insn_size);
08081   record_alignment (now_seg, align_power);
08082 
08083   fill_size = get_text_align_fill_size
08084     (address + pre_opcode_bytes, align_power, first_insn_size, TRUE,
08085      fragP->tc_frag_data.is_no_density);
08086 
08087   return address + fill_size;
08088 }
08089 
08090 
08091 /* 3 mechanisms for relaxing an alignment:
08092 
08093    Align to a power of 2.
08094    Align so the next fragment's instruction does not cross a word boundary.
08095    Align the current instruction so that if the next instruction
08096        were 3 bytes, it would not cross a word boundary.
08097 
08098    We can align with:
08099 
08100    zeros    - This is easy; always insert zeros.
08101    nops     - 3-byte and 2-byte instructions
08102               2 - 2-byte nop
08103               3 - 3-byte nop
08104               4 - 2 2-byte nops
08105               >=5 : 3-byte instruction + fn (n-3)
08106    widening - widen previous instructions.  */
08107 
08108 static offsetT
08109 get_aligned_diff (fragS *fragP, addressT address, offsetT *max_diff)
08110 {
08111   addressT target_address, loop_insn_offset;
08112   int target_size;
08113   xtensa_opcode loop_opcode;
08114   bfd_boolean is_loop;
08115   int align_power;
08116   offsetT opt_diff;
08117   offsetT branch_align;
08118 
08119   assert (fragP->fr_type == rs_machine_dependent);
08120   switch (fragP->fr_subtype)
08121     {
08122     case RELAX_DESIRE_ALIGN:
08123       target_size = next_frag_format_size (fragP);
08124       if (target_size == XTENSA_UNDEFINED)
08125        target_size = 3;
08126       align_power = branch_align_power (now_seg);
08127       branch_align = 1 << align_power;
08128       /* Don't count on the section alignment being as large as the target.  */
08129       if (target_size > branch_align)
08130        target_size = branch_align;
08131       opt_diff = get_text_align_fill_size (address, align_power,
08132                                       target_size, FALSE, FALSE);
08133 
08134       *max_diff = (opt_diff + branch_align
08135                  - (target_size + ((address + opt_diff) % branch_align)));
08136       assert (*max_diff >= opt_diff);
08137       return opt_diff;
08138 
08139     case RELAX_ALIGN_NEXT_OPCODE:
08140       target_size = get_loop_align_size (next_frag_format_size (fragP));
08141       loop_insn_offset = 0;
08142       is_loop = next_frag_opcode_is_loop (fragP, &loop_opcode);
08143       assert (is_loop);
08144 
08145       /* If the loop has been expanded then the LOOP instruction
08146         could be at an offset from this fragment.  */
08147       if (next_non_empty_frag(fragP)->tc_frag_data.slot_subtypes[0]
08148          != RELAX_IMMED)
08149        loop_insn_offset = get_expanded_loop_offset (loop_opcode);
08150 
08151       /* In an ideal world, which is what we are shooting for here,
08152         we wouldn't need to use any NOPs immediately prior to the
08153         LOOP instruction.  If this approach fails, relax_frag_loop_align
08154         will call get_noop_aligned_address.  */
08155       target_address =
08156        address + loop_insn_offset + xg_get_single_size (loop_opcode);
08157       align_power = get_text_align_power (target_size),
08158       opt_diff = get_text_align_fill_size (target_address, align_power,
08159                                       target_size, FALSE, FALSE);
08160 
08161       *max_diff = xtensa_fetch_width
08162        - ((target_address + opt_diff) % xtensa_fetch_width)
08163        - target_size + opt_diff;
08164       assert (*max_diff >= opt_diff);
08165       return opt_diff;
08166 
08167     default:
08168       break;
08169     }
08170   assert (0);
08171   return 0;
08172 }
08173 
08174 
08175 /* md_relax_frag Hook and Helper Functions.  */
08176 
08177 static long relax_frag_loop_align (fragS *, long);
08178 static long relax_frag_for_align (fragS *, long);
08179 static long relax_frag_immed
08180   (segT, fragS *, long, int, xtensa_format, int, int *, bfd_boolean);
08181 
08182 
08183 /* Return the number of bytes added to this fragment, given that the
08184    input has been stretched already by "stretch".  */
08185 
08186 long
08187 xtensa_relax_frag (fragS *fragP, long stretch, int *stretched_p)
08188 {
08189   xtensa_isa isa = xtensa_default_isa;
08190   int unreported = fragP->tc_frag_data.unreported_expansion;
08191   long new_stretch = 0;
08192   char *file_name;
08193   unsigned line;
08194   int lit_size;
08195   static xtensa_insnbuf vbuf = NULL;
08196   int slot, num_slots;
08197   xtensa_format fmt;
08198 
08199   as_where (&file_name, &line);
08200   new_logical_line (fragP->fr_file, fragP->fr_line);
08201 
08202   fragP->tc_frag_data.unreported_expansion = 0;
08203 
08204   switch (fragP->fr_subtype)
08205     {
08206     case RELAX_ALIGN_NEXT_OPCODE:
08207       /* Always convert.  */
08208       if (fragP->tc_frag_data.relax_seen)
08209        new_stretch = relax_frag_loop_align (fragP, stretch);
08210       break;
08211 
08212     case RELAX_LOOP_END:
08213       /* Do nothing.  */
08214       break;
08215 
08216     case RELAX_LOOP_END_ADD_NOP:
08217       /* Add a NOP and switch to .fill 0.  */
08218       new_stretch = relax_frag_add_nop (fragP);
08219       frag_wane (fragP);
08220       break;
08221 
08222     case RELAX_DESIRE_ALIGN:
08223       /* Do nothing. The narrowing before this frag will either align
08224          it or not.  */
08225       break;
08226 
08227     case RELAX_LITERAL:
08228     case RELAX_LITERAL_FINAL:
08229       return 0;
08230 
08231     case RELAX_LITERAL_NR:
08232       lit_size = 4;
08233       fragP->fr_subtype = RELAX_LITERAL_FINAL;
08234       assert (unreported == lit_size);
08235       memset (&fragP->fr_literal[fragP->fr_fix], 0, 4);
08236       fragP->fr_var -= lit_size;
08237       fragP->fr_fix += lit_size;
08238       new_stretch = 4;
08239       break;
08240 
08241     case RELAX_SLOTS:
08242       if (vbuf == NULL)
08243        vbuf = xtensa_insnbuf_alloc (isa);
08244 
08245       xtensa_insnbuf_from_chars
08246        (isa, vbuf, (unsigned char *) fragP->fr_opcode, 0);
08247       fmt = xtensa_format_decode (isa, vbuf);
08248       num_slots = xtensa_format_num_slots (isa, fmt);
08249 
08250       for (slot = 0; slot < num_slots; slot++)
08251        {
08252          switch (fragP->tc_frag_data.slot_subtypes[slot])
08253            {
08254            case RELAX_NARROW:
08255              if (fragP->tc_frag_data.relax_seen)
08256               new_stretch += relax_frag_for_align (fragP, stretch);
08257              break;
08258 
08259            case RELAX_IMMED:
08260            case RELAX_IMMED_STEP1:
08261            case RELAX_IMMED_STEP2:
08262              /* Place the immediate.  */
08263              new_stretch += relax_frag_immed
08264               (now_seg, fragP, stretch,
08265                fragP->tc_frag_data.slot_subtypes[slot] - RELAX_IMMED,
08266                fmt, slot, stretched_p, FALSE);
08267              break;
08268 
08269            default:
08270              /* This is OK; see the note in xg_assemble_vliw_tokens.  */
08271              break;
08272            }
08273        }
08274       break;
08275 
08276     case RELAX_LITERAL_POOL_BEGIN:
08277     case RELAX_LITERAL_POOL_END:
08278     case RELAX_MAYBE_UNREACHABLE:
08279     case RELAX_MAYBE_DESIRE_ALIGN:
08280       /* No relaxation required.  */
08281       break;
08282 
08283     case RELAX_FILL_NOP:
08284     case RELAX_UNREACHABLE:
08285       if (fragP->tc_frag_data.relax_seen)
08286        new_stretch += relax_frag_for_align (fragP, stretch);
08287       break;
08288 
08289     default:
08290       as_bad (_("bad relaxation state"));
08291     }
08292 
08293   /* Tell gas we need another relaxation pass.  */
08294   if (! fragP->tc_frag_data.relax_seen)
08295     {
08296       fragP->tc_frag_data.relax_seen = TRUE;
08297       *stretched_p = 1;
08298     }
08299 
08300   new_logical_line (file_name, line);
08301   return new_stretch;
08302 }
08303 
08304 
08305 static long
08306 relax_frag_loop_align (fragS *fragP, long stretch)
08307 {
08308   addressT old_address, old_next_address, old_size;
08309   addressT new_address, new_next_address, new_size;
08310   addressT growth;
08311 
08312   /* All the frags with relax_frag_for_alignment prior to this one in the
08313      section have been done, hopefully eliminating the need for a NOP here.
08314      But, this will put it in if necessary.  */
08315 
08316   /* Calculate the old address of this fragment and the next fragment.  */
08317   old_address = fragP->fr_address - stretch;
08318   old_next_address = (fragP->fr_address - stretch + fragP->fr_fix +
08319                     fragP->tc_frag_data.text_expansion[0]);
08320   old_size = old_next_address - old_address;
08321 
08322   /* Calculate the new address of this fragment and the next fragment.  */
08323   new_address = fragP->fr_address;
08324   new_next_address =
08325     get_noop_aligned_address (fragP, fragP->fr_address + fragP->fr_fix);
08326   new_size = new_next_address - new_address;
08327 
08328   growth = new_size - old_size;
08329 
08330   /* Fix up the text_expansion field and return the new growth.  */
08331   fragP->tc_frag_data.text_expansion[0] += growth;
08332   return growth;
08333 }
08334 
08335 
08336 /* Add a NOP instruction.  */
08337 
08338 static long
08339 relax_frag_add_nop (fragS *fragP)
08340 {
08341   char *nop_buf = fragP->fr_literal + fragP->fr_fix;
08342   int length = fragP->tc_frag_data.is_no_density ? 3 : 2;
08343   assemble_nop (length, nop_buf);
08344   fragP->tc_frag_data.is_insn = TRUE;
08345 
08346   if (fragP->fr_var < length)
08347     {
08348       as_fatal (_("fr_var (%ld) < length (%d)"), (long) fragP->fr_var, length);
08349       return 0;
08350     }
08351 
08352   fragP->fr_fix += length;
08353   fragP->fr_var -= length;
08354   return length;
08355 }
08356 
08357 
08358 static long future_alignment_required (fragS *, long);
08359 
08360 static long
08361 relax_frag_for_align (fragS *fragP, long stretch)
08362 {
08363   /* Overview of the relaxation procedure for alignment:
08364      We can widen with NOPs or by widening instructions or by filling
08365      bytes after jump instructions.  Find the opportune places and widen
08366      them if necessary.  */
08367 
08368   long stretch_me;
08369   long diff;
08370 
08371   assert (fragP->fr_subtype == RELAX_FILL_NOP
08372          || fragP->fr_subtype == RELAX_UNREACHABLE
08373          || (fragP->fr_subtype == RELAX_SLOTS
08374              && fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW));
08375 
08376   stretch_me = future_alignment_required (fragP, stretch);
08377   diff = stretch_me - fragP->tc_frag_data.text_expansion[0];
08378   if (diff == 0)
08379     return 0;
08380 
08381   if (diff < 0)
08382     {
08383       /* We expanded on a previous pass.  Can we shrink now?  */
08384       long shrink = fragP->tc_frag_data.text_expansion[0] - stretch_me;
08385       if (shrink <= stretch && stretch > 0)
08386        {
08387          fragP->tc_frag_data.text_expansion[0] = stretch_me;
08388          return -shrink;
08389        }
08390       return 0;
08391     }
08392 
08393   /* Below here, diff > 0.  */
08394   fragP->tc_frag_data.text_expansion[0] = stretch_me;
08395 
08396   return diff;
08397 }
08398 
08399 
08400 /* Return the address of the next frag that should be aligned.
08401 
08402    By "address" we mean the address it _would_ be at if there
08403    is no action taken to align it between here and the target frag.
08404    In other words, if no narrows and no fill nops are used between
08405    here and the frag to align, _even_if_ some of the frags we use
08406    to align targets have already expanded on a previous relaxation
08407    pass.
08408 
08409    Also, count each frag that may be used to help align the target.
08410 
08411    Return 0 if there are no frags left in the chain that need to be
08412    aligned.  */
08413 
08414 static addressT
08415 find_address_of_next_align_frag (fragS **fragPP,
08416                              int *wide_nops,
08417                              int *narrow_nops,
08418                              int *widens,
08419                              bfd_boolean *paddable)
08420 {
08421   fragS *fragP = *fragPP;
08422   addressT address = fragP->fr_address;
08423 
08424   /* Do not reset the counts to 0.  */
08425 
08426   while (fragP)
08427     {
08428       /* Limit this to a small search.  */
08429       if (*widens >= (int) xtensa_fetch_width)
08430        {
08431          *fragPP = fragP;
08432          return 0;
08433        }
08434       address += fragP->fr_fix;
08435 
08436       if (fragP->fr_type == rs_fill)
08437        address += fragP->fr_offset * fragP->fr_var;
08438       else if (fragP->fr_type == rs_machine_dependent)
08439        {
08440          switch (fragP->fr_subtype)
08441            {
08442            case RELAX_UNREACHABLE:
08443              *paddable = TRUE;
08444              break;
08445 
08446            case RELAX_FILL_NOP:
08447              (*wide_nops)++;
08448              if (!fragP->tc_frag_data.is_no_density)
08449               (*narrow_nops)++;
08450              break;
08451 
08452            case RELAX_SLOTS:
08453              if (fragP->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
08454               {
08455                 (*widens)++;
08456                 break;
08457               }
08458              address += total_frag_text_expansion (fragP);;
08459              break;
08460 
08461            case RELAX_IMMED:
08462              address += fragP->tc_frag_data.text_expansion[0];
08463              break;
08464 
08465            case RELAX_ALIGN_NEXT_OPCODE:
08466            case RELAX_DESIRE_ALIGN:
08467              *fragPP = fragP;
08468              return address;
08469 
08470            case RELAX_MAYBE_UNREACHABLE:
08471            case RELAX_MAYBE_DESIRE_ALIGN:
08472              /* Do nothing.  */
08473              break;
08474 
08475            default:
08476              /* Just punt if we don't know the type.  */
08477              *fragPP = fragP;
08478              return 0;
08479            }
08480        }
08481       else
08482        {
08483          /* Just punt if we don't know the type.  */
08484          *fragPP = fragP;
08485          return 0;
08486        }
08487       fragP = fragP->fr_next;
08488     }
08489 
08490   *fragPP = fragP;
08491   return 0;
08492 }
08493 
08494 
08495 static long bytes_to_stretch (fragS *, int, int, int, int);
08496 
08497 static long
08498 future_alignment_required (fragS *fragP, long stretch ATTRIBUTE_UNUSED)
08499 {
08500   fragS *this_frag = fragP;
08501   long address;
08502   int num_widens = 0;
08503   int wide_nops = 0;
08504   int narrow_nops = 0;
08505   bfd_boolean paddable = FALSE;
08506   offsetT local_opt_diff;
08507   offsetT opt_diff;
08508   offsetT max_diff;
08509   int stretch_amount = 0;
08510   int local_stretch_amount;
08511   int global_stretch_amount;
08512 
08513   address = find_address_of_next_align_frag
08514     (&fragP, &wide_nops, &narrow_nops, &num_widens, &paddable);
08515 
08516   if (!address)
08517     {
08518       if (this_frag->tc_frag_data.is_aligning_branch)
08519        this_frag->tc_frag_data.slot_subtypes[0] = RELAX_IMMED;
08520       else
08521        frag_wane (this_frag);
08522     }
08523   else
08524     {
08525       local_opt_diff = get_aligned_diff (fragP, address, &max_diff);
08526       opt_diff = local_opt_diff;
08527       assert (opt_diff >= 0);
08528       assert (max_diff >= opt_diff);
08529       if (max_diff == 0)
08530        return 0;
08531 
08532       if (fragP)
08533        fragP = fragP->fr_next;
08534 
08535       while (fragP && opt_diff < max_diff && address)
08536        {
08537          /* We only use these to determine if we can exit early
08538             because there will be plenty of ways to align future
08539             align frags.  */
08540          int glob_widens = 0;
08541          int dnn = 0;
08542          int dw = 0;
08543          bfd_boolean glob_pad = 0;
08544          address = find_address_of_next_align_frag
08545            (&fragP, &glob_widens, &dnn, &dw, &glob_pad);
08546          /* If there is a padable portion, then skip.  */
08547          if (glob_pad || glob_widens >= (1 << branch_align_power (now_seg)))
08548            address = 0;
08549 
08550          if (address)
08551            {
08552              offsetT next_m_diff;
08553              offsetT next_o_diff;
08554 
08555              /* Downrange frags haven't had stretch added to them yet.  */
08556              address += stretch;
08557 
08558              /* The address also includes any text expansion from this
08559                frag in a previous pass, but we don't want that.  */
08560              address -= this_frag->tc_frag_data.text_expansion[0];
08561 
08562              /* Assume we are going to move at least opt_diff.  In
08563                reality, we might not be able to, but assuming that
08564                we will helps catch cases where moving opt_diff pushes
08565                the next target from aligned to unaligned.  */
08566              address += opt_diff;
08567 
08568              next_o_diff = get_aligned_diff (fragP, address, &next_m_diff);
08569 
08570              /* Now cleanup for the adjustments to address.  */
08571              next_o_diff += opt_diff;
08572              next_m_diff += opt_diff;
08573              if (next_o_diff <= max_diff && next_o_diff > opt_diff)
08574               opt_diff = next_o_diff;
08575              if (next_m_diff < max_diff)
08576               max_diff = next_m_diff;
08577              fragP = fragP->fr_next;
08578            }
08579        }
08580 
08581       /* If there are enough wideners in between, do it.  */
08582       if (paddable)
08583        {
08584          if (this_frag->fr_subtype == RELAX_UNREACHABLE)
08585            {
08586              assert (opt_diff <= UNREACHABLE_MAX_WIDTH);
08587              return opt_diff;
08588            }
08589          return 0;
08590        }
08591       local_stretch_amount
08592        = bytes_to_stretch (this_frag, wide_nops, narrow_nops,
08593                          num_widens, local_opt_diff);
08594       global_stretch_amount
08595        = bytes_to_stretch (this_frag, wide_nops, narrow_nops,
08596                          num_widens, opt_diff);
08597       /* If the condition below is true, then the frag couldn't
08598         stretch the correct amount for the global case, so we just
08599         optimize locally.  We'll rely on the subsequent frags to get
08600         the correct alignment in the global case.  */
08601       if (global_stretch_amount < local_stretch_amount)
08602        stretch_amount = local_stretch_amount;
08603       else
08604        stretch_amount = global_stretch_amount;
08605 
08606       if (this_frag->fr_subtype == RELAX_SLOTS
08607          && this_frag->tc_frag_data.slot_subtypes[0] == RELAX_NARROW)
08608        assert (stretch_amount <= 1);
08609       else if (this_frag->fr_subtype == RELAX_FILL_NOP)
08610        {
08611          if (this_frag->tc_frag_data.is_no_density)
08612            assert (stretch_amount == 3 || stretch_amount == 0);
08613          else
08614            assert (stretch_amount <= 3);
08615        }
08616     }
08617   return stretch_amount;
08618 }
08619 
08620 
08621 /* The idea: widen everything you can to get a target or loop aligned,
08622    then start using NOPs.
08623 
08624    When we must have a NOP, here is a table of how we decide
08625    (so you don't have to fight through the control flow below):
08626 
08627    wide_nops   = the number of wide NOPs available for aligning
08628    narrow_nops = the number of narrow NOPs available for aligning
08629                (a subset of wide_nops)
08630    widens      = the number of narrow instructions that should be widened
08631 
08632    Desired   wide   narrow
08633    Diff      nop    nop      widens
08634    1           0      0         1
08635    2           0      1         0
08636    3a          1      0         0
08637     b          0      1         1 (case 3a makes this case unnecessary)
08638    4a          1      0         1
08639     b          0      2         0
08640     c          0      1         2 (case 4a makes this case unnecessary)
08641    5a          1      0         2
08642     b          1      1         0
08643     c          0      2         1 (case 5b makes this case unnecessary)
08644    6a          2      0         0
08645     b          1      0         3
08646     c          0      1         4 (case 6b makes this case unnecessary)
08647     d          1      1         1 (case 6a makes this case unnecessary)
08648     e          0      2         2 (case 6a makes this case unnecessary)
08649     f          0      3         0 (case 6a makes this case unnecessary)
08650    7a          1      0         4
08651     b          2      0         1
08652     c          1      1         2 (case 7b makes this case unnecessary)
08653     d          0      1         5 (case 7a makes this case unnecessary)
08654     e          0      2         3 (case 7b makes this case unnecessary)
08655     f          0      3         1 (case 7b makes this case unnecessary)
08656     g          1      2         1 (case 7b makes this case unnecessary)
08657 */
08658 
08659 static long
08660 bytes_to_stretch (fragS *this_frag,
08661                 int wide_nops,
08662                 int narrow_nops,
08663                 int num_widens,
08664                 int desired_diff)
08665 {
08666   int bytes_short = desired_diff - num_widens;
08667