5d5ccea5dac1a3d79e3e1a8aec833f2ed9d8a481
[external/binutils.git] / gas / config / tc-xtensa.c
1 /* tc-xtensa.c -- Assemble Xtensa instructions.
2    Copyright 2003 Free Software Foundation, Inc.
3
4    This file is part of GAS, the GNU Assembler.
5
6    GAS is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    GAS is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with GAS; see the file COPYING.  If not, write to
18    the Free Software Foundation, 59 Temple Place - Suite 330, Boston, 
19    MA 02111-1307, USA.  */
20
21 #include <string.h>
22 #include "as.h"
23 #include "sb.h"
24 #include "safe-ctype.h"
25 #include "tc-xtensa.h"
26 #include "frags.h"
27 #include "subsegs.h"
28 #include "xtensa-relax.h"
29 #include "xtensa-istack.h"
30 #include "dwarf2dbg.h"
31 #include "struc-symbol.h"
32 #include "xtensa-config.h"
33
34 #ifndef uint32
35 #define uint32 unsigned int
36 #endif
37 #ifndef int32
38 #define int32 signed int
39 #endif
40
41 /* Notes:
42
43    There are 3 forms for instructions,
44    1) the MEMORY format -- this is the encoding 2 or 3 byte instruction
45    2) the TInsn -- handles instructions/labels and literals;
46       all operands are assumed to be expressions
47    3) the IStack -- a stack of TInsn.  this allows us to 
48       reason about the generated expansion instructions
49   
50    Naming conventions (used somewhat inconsistently):
51       The xtensa_ functions are exported
52       The xg_ functions are internal
53
54    We also have a couple of different extensibility mechanisms.
55    1) The idiom replacement:
56       This is used when a line is first parsed to
57       replace an instruction pattern with another instruction
58       It is currently limited to replacements of instructions
59       with constant operands.
60    2) The xtensa-relax.c mechanism that has stronger instruction
61       replacement patterns.  When an instruction's immediate field
62       does not fit the next instruction sequence is attempted.
63       In addition, "narrow" opcodes are supported this way.  */
64
65
66 /* Define characters with special meanings to GAS.  */
67 const char comment_chars[] = "#";
68 const char line_comment_chars[] = "#";
69 const char line_separator_chars[] = ";";
70 const char EXP_CHARS[] = "eE";
71 const char FLT_CHARS[] = "rRsSfFdDxXpP";
72
73
74 /* Flag to indicate whether the hardware supports the density option.
75    If not, enabling density instructions (via directives or --density flag)
76    is illegal.  */
77
78 #if STATIC_LIBISA
79 bfd_boolean density_supported = XCHAL_HAVE_DENSITY;
80 #else
81 bfd_boolean density_supported = TRUE;
82 #endif
83
84 #define XTENSA_FETCH_WIDTH 4
85
86 /* Flags for properties of the last instruction in a segment.  */
87 #define FLAG_IS_A0_WRITER       0x1
88 #define FLAG_IS_BAD_LOOPEND     0x2
89
90
91 /* We define a special segment names ".literal" to place literals
92    into.  The .fini and .init sections are special because they
93    contain code that is moved together by the linker.  We give them
94    their own special .fini.literal and .init.literal sections.  */
95
96 #define LITERAL_SECTION_NAME            xtensa_section_rename (".literal")
97 #define FINI_SECTION_NAME               xtensa_section_rename (".fini")
98 #define INIT_SECTION_NAME               xtensa_section_rename (".init")
99 #define FINI_LITERAL_SECTION_NAME       xtensa_section_rename (".fini.literal")
100 #define INIT_LITERAL_SECTION_NAME       xtensa_section_rename (".init.literal")
101
102
103 /* This type is used for the directive_stack to keep track of the 
104    state of the literal collection pools.  */
105
106 typedef struct lit_state_struct
107 {
108   const char *lit_seg_name;
109   const char *init_lit_seg_name;
110   const char *fini_lit_seg_name;
111   segT lit_seg;
112   segT init_lit_seg;
113   segT fini_lit_seg;
114 } lit_state;
115
116 static lit_state default_lit_sections;
117
118
119 /* We keep lists of literal segments.  The seg_list type is the node
120    for such a list.  The *_literal_head locals are the heads of the
121    various lists.  All of these lists have a dummy node at the start.  */
122
123 typedef struct seg_list_struct
124 {
125   struct seg_list_struct *next;
126   segT seg;
127 } seg_list;
128
129 static seg_list literal_head_h;
130 static seg_list *literal_head = &literal_head_h;
131 static seg_list init_literal_head_h;
132 static seg_list *init_literal_head = &init_literal_head_h;
133 static seg_list fini_literal_head_h;
134 static seg_list *fini_literal_head = &fini_literal_head_h;
135
136
137 /* Lists of symbols.  We keep a list of symbols that label the current
138    instruction, so that we can adjust the symbols when inserting alignment
139    for various instructions.  We also keep a list of all the symbols on
140    literals, so that we can fix up those symbols when the literals are
141    later moved into the text sections.  */
142
143 typedef struct sym_list_struct
144 {
145   struct sym_list_struct *next;
146   symbolS *sym;
147 } sym_list;
148
149 static sym_list *insn_labels = NULL;
150 static sym_list *free_insn_labels = NULL;
151 static sym_list *saved_insn_labels = NULL;
152
153 static sym_list *literal_syms;
154
155
156 /* Global flag to indicate when we are emitting literals.  */
157 int generating_literals = 0;
158
159
160 /* Structure for saving the current state before emitting literals.  */
161 typedef struct emit_state_struct
162 {
163   const char *name;
164   segT now_seg;
165   subsegT now_subseg;
166   int generating_literals;
167 } emit_state;
168
169
170 /* Directives.  */
171
172 typedef enum
173 {
174   directive_none = 0,
175   directive_literal,
176   directive_density,
177   directive_generics,
178   directive_relax,
179   directive_freeregs,
180   directive_longcalls,
181   directive_literal_prefix
182 } directiveE;
183
184 typedef struct
185 {
186   const char *name;
187   bfd_boolean can_be_negated;
188 } directive_infoS;
189
190 const directive_infoS directive_info[] =
191 {
192   {"none",      FALSE},
193   {"literal",   FALSE},
194   {"density",   TRUE},
195   {"generics",  TRUE},
196   {"relax",     TRUE},
197   {"freeregs",  FALSE},
198   {"longcalls", TRUE},
199   {"literal_prefix", FALSE}
200 };
201
202 bfd_boolean directive_state[] =
203 {
204   FALSE,                        /* none */
205   FALSE,                        /* literal */
206 #if STATIC_LIBISA && !XCHAL_HAVE_DENSITY
207   FALSE,                        /* density */
208 #else
209   TRUE,                         /* density */
210 #endif
211   TRUE,                         /* generics */
212   TRUE,                         /* relax */
213   FALSE,                        /* freeregs */
214   FALSE,                        /* longcalls */
215   FALSE                         /* literal_prefix */
216 };
217
218
219 enum xtensa_relax_statesE
220 {
221   RELAX_ALIGN_NEXT_OPCODE,
222   /* Use the first opcode of the next fragment to determine the
223      alignment requirements.  This is ONLY used for LOOPS
224      currently.  */
225
226   RELAX_DESIRE_ALIGN_IF_TARGET,
227   /* These are placed in front of labels.  They will all be converted
228      to RELAX_DESIRE_ALIGN / RELAX_LOOP_END or rs_fill of 0 before
229      relaxation begins.  */
230
231   RELAX_ADD_NOP_IF_A0_B_RETW,
232   /* These are placed in front of conditional branches.  It will be
233      turned into a NOP (using a1) if the branch is immediately
234      followed by a RETW or RETW.N.  Otherwise it will be turned into
235      an rs_fill of 0 before relaxation begins.  */
236
237   RELAX_ADD_NOP_IF_PRE_LOOP_END,
238   /* These are placed after JX instructions.  It will be turned into a
239      NOP if there is one instruction before a loop end label.
240      Otherwise it will be turned into an rs_fill of 0 before
241      relaxation begins.  This is used to avoid a hardware TIE
242      interlock issue prior to T1040.  */
243
244   RELAX_ADD_NOP_IF_SHORT_LOOP,
245   /* These are placed after LOOP instructions.  It will be turned into
246      a NOP when: (1) there are less than 3 instructions in the loop;
247      we place 2 of these in a row to add up to 2 NOPS in short loops;
248      or (2) The instructions in the loop do not include a branch or
249      jump.  Otherwise it will be turned into an rs_fill of 0 before
250      relaxation begins.  This is used to avoid hardware bug
251      PR3830.  */
252
253   RELAX_ADD_NOP_IF_CLOSE_LOOP_END,
254   /* These are placed after LOOP instructions.  It will be turned into
255      a NOP if there are less than 12 bytes to the end of some other
256      loop's end.  Otherwise it will be turned into an rs_fill of 0
257      before relaxation begins.  This is used to avoid hardware bug
258      PR3830.  */
259
260   RELAX_DESIRE_ALIGN,
261   /* The next fragment like its first instruction to NOT cross a
262      4-byte boundary.  */
263
264   RELAX_LOOP_END,
265   /* This will be turned into a NOP or NOP.N if the previous
266      instruction is expanded to negate a loop.  */
267
268   RELAX_LOOP_END_ADD_NOP,
269   /* When the code density option is available, this will generate a
270      NOP.N marked RELAX_NARROW.  Otherwise, it will create an rs_fill
271      fragment with a NOP in it.  */
272
273   RELAX_LITERAL,
274   /* Another fragment could generate an expansion here but has not yet.  */
275
276   RELAX_LITERAL_NR,
277   /* Expansion has been generated by an instruction that generates a
278      literal.  However, the stretch has NOT been reported yet in this
279      fragment.  */
280
281   RELAX_LITERAL_FINAL,
282   /* Expansion has been generated by an instruction that generates a
283      literal.  */
284
285   RELAX_LITERAL_POOL_BEGIN,
286   RELAX_LITERAL_POOL_END,
287   /* Technically these are not relaxations at all, but mark a location
288      to store literals later.  Note that fr_var stores the frchain for
289      BEGIN frags and fr_var stores now_seg for END frags.  */
290
291   RELAX_NARROW,
292   /* The last instruction in this fragment (at->fr_opcode) can be
293      freely replaced with a single wider instruction if a future
294      alignment desires or needs it.  */
295
296   RELAX_IMMED,
297   /* The last instruction in this fragment (at->fr_opcode) contains
298      the value defined by fr_symbol (fr_offset = 0).  If the value
299      does not fit, use the specified expansion.  This is similar to
300      "NARROW", except that these may not be expanded in order to align
301      code.  */
302   
303   RELAX_IMMED_STEP1,
304   /* The last instruction in this fragment (at->fr_opcode) contains a
305      literal.  It has already been expanded at least 1 step.  */
306
307   RELAX_IMMED_STEP2
308   /* The last instruction in this fragment (at->fr_opcode) contains a
309      literal.  It has already been expanded at least 2 steps.  */
310 };
311
312 /* This is used as a stopper to bound the number of steps that
313    can be taken.  */
314 #define RELAX_IMMED_MAXSTEPS (RELAX_IMMED_STEP2 - RELAX_IMMED)
315
316
317 typedef bfd_boolean (*frag_predicate) (const fragS *);
318
319
320 /* Directive functions.  */
321
322 static bfd_boolean use_generics
323   PARAMS ((void));
324 static bfd_boolean use_longcalls
325   PARAMS ((void));
326 static bfd_boolean code_density_available
327   PARAMS ((void));
328 static bfd_boolean can_relax
329   PARAMS ((void));
330 static void directive_push
331   PARAMS ((directiveE, bfd_boolean, const void *));
332 static void directive_pop
333   PARAMS ((directiveE *, bfd_boolean *, const char **,
334            unsigned int *, const void **));
335 static void directive_balance
336   PARAMS ((void));
337 static bfd_boolean inside_directive
338   PARAMS ((directiveE));
339 static void get_directive
340   PARAMS ((directiveE *, bfd_boolean *));
341 static void xtensa_begin_directive
342   PARAMS ((int));
343 static void xtensa_end_directive
344   PARAMS ((int));
345 static void xtensa_literal_prefix
346   PARAMS ((char const *, int));
347 static void xtensa_literal_position
348   PARAMS ((int));
349 static void xtensa_literal_pseudo
350   PARAMS ((int));
351
352 /* Parsing and Idiom Translation Functions.  */
353
354 static const char *expression_end
355   PARAMS ((const char *));
356 static unsigned tc_get_register
357   PARAMS ((const char *));
358 static void expression_maybe_register
359   PARAMS ((xtensa_operand, expressionS *));
360 static int tokenize_arguments
361   PARAMS ((char **, char *));
362 static bfd_boolean parse_arguments
363   PARAMS ((TInsn *, int, char **));
364 static int xg_translate_idioms
365   PARAMS ((char **, int *, char **));
366 static int xg_translate_sysreg_op
367   PARAMS ((char **, int *, char **));
368 static void xg_reverse_shift_count
369   PARAMS ((char **));
370 static int xg_arg_is_constant
371   PARAMS ((char *, offsetT *));
372 static void xg_replace_opname
373   PARAMS ((char **, char *));
374 static int xg_check_num_args
375   PARAMS ((int *, int, char *, char **));
376
377 /* Functions for dealing with the Xtensa ISA.  */
378
379 static bfd_boolean operand_is_immed
380   PARAMS ((xtensa_operand));
381 static bfd_boolean operand_is_pcrel_label
382   PARAMS ((xtensa_operand));
383 static int get_relaxable_immed
384   PARAMS ((xtensa_opcode));
385 static xtensa_opcode get_opcode_from_buf
386   PARAMS ((const char *));
387 static bfd_boolean is_direct_call_opcode
388   PARAMS ((xtensa_opcode));
389 static bfd_boolean is_call_opcode
390   PARAMS ((xtensa_opcode));
391 static bfd_boolean is_entry_opcode
392   PARAMS ((xtensa_opcode));
393 static bfd_boolean is_loop_opcode
394   PARAMS ((xtensa_opcode));
395 static bfd_boolean is_the_loop_opcode
396   PARAMS ((xtensa_opcode));
397 static bfd_boolean is_jx_opcode
398   PARAMS ((xtensa_opcode));
399 static bfd_boolean is_windowed_return_opcode
400   PARAMS ((xtensa_opcode));
401 static bfd_boolean is_conditional_branch_opcode
402   PARAMS ((xtensa_opcode));
403 static bfd_boolean is_branch_or_jump_opcode
404   PARAMS ((xtensa_opcode));
405 static bfd_reloc_code_real_type opnum_to_reloc
406   PARAMS ((int));
407 static int reloc_to_opnum
408   PARAMS ((bfd_reloc_code_real_type));
409 static void xtensa_insnbuf_set_operand
410   PARAMS ((xtensa_insnbuf, xtensa_opcode, xtensa_operand, int32,
411            const char *, unsigned int));
412 static uint32 xtensa_insnbuf_get_operand
413   PARAMS ((xtensa_insnbuf, xtensa_opcode, int));
414 static void xtensa_insnbuf_set_immediate_field
415   PARAMS ((xtensa_opcode, xtensa_insnbuf, int32, const char *,
416            unsigned int));
417 static bfd_boolean is_negatable_branch
418   PARAMS ((TInsn *));
419
420 /* Various Other Internal Functions.  */
421
422 static bfd_boolean is_unique_insn_expansion
423   PARAMS ((TransitionRule *));
424 static int xg_get_insn_size
425   PARAMS ((TInsn *));
426 static int xg_get_build_instr_size
427   PARAMS ((BuildInstr *));
428 static bfd_boolean xg_is_narrow_insn
429   PARAMS ((TInsn *));
430 static bfd_boolean xg_is_single_relaxable_insn
431   PARAMS ((TInsn *));
432 static int xg_get_max_narrow_insn_size
433   PARAMS ((xtensa_opcode));
434 static int xg_get_max_insn_widen_size
435   PARAMS ((xtensa_opcode));
436 static int xg_get_max_insn_widen_literal_size
437   PARAMS ((xtensa_opcode));
438 static bfd_boolean xg_is_relaxable_insn
439   PARAMS ((TInsn *, int));
440 static symbolS *get_special_literal_symbol
441   PARAMS ((void));
442 static symbolS *get_special_label_symbol
443   PARAMS ((void));
444 static bfd_boolean xg_build_to_insn
445   PARAMS ((TInsn *, TInsn *, BuildInstr *));
446 static bfd_boolean xg_build_to_stack
447   PARAMS ((IStack *, TInsn *, BuildInstr *));
448 static bfd_boolean xg_expand_to_stack
449   PARAMS ((IStack *, TInsn *, int));
450 static bfd_boolean xg_expand_narrow
451   PARAMS ((TInsn *, TInsn *));
452 static bfd_boolean xg_immeds_fit
453   PARAMS ((const TInsn *));
454 static bfd_boolean xg_symbolic_immeds_fit
455   PARAMS ((const TInsn *, segT, fragS *, offsetT, long));
456 static bfd_boolean xg_check_operand
457   PARAMS ((int32, xtensa_operand));
458 static int is_dnrange
459   PARAMS ((fragS *, symbolS *, long));
460 static int xg_assembly_relax
461   PARAMS ((IStack *, TInsn *, segT, fragS *, offsetT, int, long));
462 static void xg_force_frag_space
463   PARAMS ((int));
464 static void xg_finish_frag
465   PARAMS ((char *, enum xtensa_relax_statesE, int, bfd_boolean));
466 static bfd_boolean is_branch_jmp_to_next
467   PARAMS ((TInsn *, fragS *));
468 static void xg_add_branch_and_loop_targets
469   PARAMS ((TInsn *));
470 static bfd_boolean xg_instruction_matches_rule
471   PARAMS ((TInsn *, TransitionRule *));
472 static TransitionRule *xg_instruction_match
473   PARAMS ((TInsn *));
474 static bfd_boolean xg_build_token_insn
475   PARAMS ((BuildInstr *, TInsn *, TInsn *));
476 static bfd_boolean xg_simplify_insn
477   PARAMS ((TInsn *, TInsn *));
478 static bfd_boolean xg_expand_assembly_insn
479   PARAMS ((IStack *, TInsn *));
480 static symbolS *xg_assemble_literal
481   PARAMS ((TInsn *));
482 static void xg_assemble_literal_space
483   PARAMS ((int));
484 static symbolS *xtensa_create_literal_symbol
485   PARAMS ((segT, fragS *));
486 static void xtensa_add_literal_sym
487   PARAMS ((symbolS *));
488 static void xtensa_add_insn_label
489   PARAMS ((symbolS *));
490 static void xtensa_clear_insn_labels
491   PARAMS ((void));
492 static bfd_boolean get_is_linkonce_section
493   PARAMS ((bfd *, segT));
494 static bfd_boolean xg_emit_insn
495   PARAMS ((TInsn *, bfd_boolean));
496 static bfd_boolean xg_emit_insn_to_buf
497   PARAMS ((TInsn *, char *, fragS *, offsetT, bfd_boolean));
498 static bfd_boolean xg_add_opcode_fix
499   PARAMS ((xtensa_opcode, int, expressionS *, fragS *, offsetT));
500 static void xg_resolve_literals
501   PARAMS ((TInsn *, symbolS *));
502 static void xg_resolve_labels
503   PARAMS ((TInsn *, symbolS *));
504 static void xg_assemble_tokens
505   PARAMS ((TInsn *));
506 static bfd_boolean is_register_writer
507   PARAMS ((const TInsn *, const char *, int));
508 static bfd_boolean is_bad_loopend_opcode
509   PARAMS ((const TInsn *));
510 static bfd_boolean is_unaligned_label
511   PARAMS ((symbolS *));
512 static fragS *next_non_empty_frag
513   PARAMS ((const fragS *));
514 static xtensa_opcode next_frag_opcode
515   PARAMS ((const fragS *));
516 static void update_next_frag_nop_state
517   PARAMS ((fragS *));
518 static bfd_boolean next_frag_is_branch_target
519   PARAMS ((const fragS *));
520 static bfd_boolean next_frag_is_loop_target
521   PARAMS ((const fragS *));
522 static addressT next_frag_pre_opcode_bytes
523   PARAMS ((const fragS *));
524 static bfd_boolean is_next_frag_target
525   PARAMS ((const fragS *, const fragS *));
526 static void xtensa_mark_literal_pool_location
527   PARAMS ((void));
528 static void xtensa_move_labels
529   PARAMS ((fragS *, valueT, bfd_boolean));
530 static void assemble_nop
531   PARAMS ((size_t, char *));
532 static addressT get_expanded_loop_offset
533   PARAMS ((xtensa_opcode));
534 static fragS *get_literal_pool_location
535   PARAMS ((segT));
536 static void set_literal_pool_location
537   PARAMS ((segT, fragS *));
538
539 /* Helpers for xtensa_end().  */
540
541 static void xtensa_cleanup_align_frags
542   PARAMS ((void));
543 static void xtensa_fix_target_frags
544   PARAMS ((void));
545 static bfd_boolean frag_can_negate_branch
546   PARAMS ((fragS *));
547 static void xtensa_fix_a0_b_retw_frags
548   PARAMS ((void));
549 static bfd_boolean next_instrs_are_b_retw
550   PARAMS ((fragS *));
551 static void xtensa_fix_b_j_loop_end_frags
552   PARAMS ((void));
553 static bfd_boolean next_instr_is_loop_end
554   PARAMS ((fragS *));
555 static void xtensa_fix_close_loop_end_frags
556   PARAMS ((void));
557 static size_t min_bytes_to_other_loop_end
558   PARAMS ((fragS *, fragS *, offsetT, size_t));
559 static size_t unrelaxed_frag_min_size
560   PARAMS ((fragS *));
561 static void xtensa_fix_short_loop_frags
562   PARAMS ((void));
563 static size_t count_insns_to_loop_end
564   PARAMS ((fragS *, bfd_boolean, size_t));
565 static size_t unrelaxed_frag_min_insn_count
566   PARAMS ((fragS *));
567 static bfd_boolean branch_before_loop_end
568   PARAMS ((fragS *));
569 static bfd_boolean unrelaxed_frag_has_b_j
570   PARAMS ((fragS *));
571 static void xtensa_sanity_check
572   PARAMS ((void));
573 static bfd_boolean is_empty_loop
574   PARAMS ((const TInsn *, fragS *));
575 static bfd_boolean is_local_forward_loop
576   PARAMS ((const TInsn *, fragS *));
577
578 /* Alignment Functions.  */
579
580 static size_t get_text_align_power
581   PARAMS ((int));
582 static addressT get_text_align_max_fill_size
583   PARAMS ((int, bfd_boolean, bfd_boolean));
584 static addressT get_text_align_fill_size
585   PARAMS ((addressT, int, int, bfd_boolean, bfd_boolean));
586 static size_t get_text_align_nop_count
587   PARAMS ((size_t, bfd_boolean));
588 static size_t get_text_align_nth_nop_size
589   PARAMS ((size_t, size_t, bfd_boolean));
590 static addressT get_noop_aligned_address
591   PARAMS ((fragS *, addressT));
592 static addressT get_widen_aligned_address
593   PARAMS ((fragS *, addressT));
594
595 /* Helpers for xtensa_relax_frag().  */
596
597 static long relax_frag_text_align
598   PARAMS ((fragS *, long));
599 static long relax_frag_add_nop
600   PARAMS ((fragS *));
601 static long relax_frag_narrow
602   PARAMS ((fragS *, long));
603 static bfd_boolean future_alignment_required
604   PARAMS ((fragS *, long));
605 static long relax_frag_immed
606   PARAMS ((segT, fragS *, long, int, int *));
607
608 /* Helpers for md_convert_frag().  */
609
610 static void convert_frag_align_next_opcode
611   PARAMS ((fragS *));
612 static void convert_frag_narrow
613   PARAMS ((fragS *));
614 static void convert_frag_immed
615   PARAMS ((segT, fragS *, int));
616 static fixS *fix_new_exp_in_seg
617   PARAMS ((segT, subsegT, fragS *, int, int, expressionS *, int,
618            bfd_reloc_code_real_type));
619 static void convert_frag_immed_finish_loop
620   PARAMS ((segT, fragS *, TInsn *));
621 static offsetT get_expression_value
622   PARAMS ((segT, expressionS *));
623
624 /* Flags for the Last Instruction in Each Subsegment.  */
625
626 static unsigned get_last_insn_flags
627   PARAMS ((segT, subsegT));
628 static void set_last_insn_flags
629   PARAMS ((segT, subsegT, unsigned, bfd_boolean));
630
631 /* Segment list functions.  */
632
633 static void xtensa_remove_section
634   PARAMS ((segT));
635 static void xtensa_insert_section
636   PARAMS ((segT, segT));
637 static void xtensa_move_seg_list_to_beginning
638   PARAMS ((seg_list *));
639 static void xtensa_move_literals
640   PARAMS ((void));
641 static void mark_literal_frags
642   PARAMS ((seg_list *));
643 static void xtensa_reorder_seg_list
644   PARAMS ((seg_list *, segT));
645 static void xtensa_reorder_segments
646   PARAMS ((void));
647 static segT get_last_sec
648   PARAMS ((void));
649 static void xtensa_switch_to_literal_fragment
650   PARAMS ((emit_state *));
651 static void xtensa_switch_section_emit_state
652   PARAMS ((emit_state *, segT, subsegT));
653 static void xtensa_restore_emit_state
654   PARAMS ((emit_state *));
655 static void cache_literal_section
656   PARAMS ((seg_list *, const char *, segT *));
657 static segT retrieve_literal_seg
658   PARAMS ((seg_list *, const char *));
659 static segT seg_present
660   PARAMS ((const char *));
661 static void add_seg_list
662   PARAMS ((seg_list *, segT));
663
664 /* Property Table (e.g., ".xt.insn" and ".xt.lit") Functions.  */
665
666 static void xtensa_create_property_segments
667   PARAMS ((frag_predicate, const char *, xt_section_type));
668 static segment_info_type *retrieve_segment_info
669   PARAMS ((segT));
670 static segT retrieve_xtensa_section
671   PARAMS ((char *));
672 static bfd_boolean section_has_property
673   PARAMS ((segT sec, frag_predicate));
674 static void add_xt_block_frags
675   PARAMS ((segT, segT, xtensa_block_info **, frag_predicate));
676 static bfd_boolean get_frag_is_literal
677   PARAMS ((const fragS *));
678 static bfd_boolean get_frag_is_insn
679   PARAMS ((const fragS *));
680
681 /* Import from elf32-xtensa.c in BFD library.  */
682 extern char *xtensa_get_property_section_name
683   PARAMS ((asection *, const char *));
684
685 /* TInsn and IStack functions.  */
686 static bfd_boolean tinsn_has_symbolic_operands
687   PARAMS ((const TInsn *));
688 static bfd_boolean tinsn_has_invalid_symbolic_operands
689   PARAMS ((const TInsn *));
690 static bfd_boolean tinsn_has_complex_operands
691   PARAMS ((const TInsn *));
692 static bfd_boolean tinsn_to_insnbuf
693   PARAMS ((TInsn *, xtensa_insnbuf));
694 static bfd_boolean tinsn_check_arguments
695   PARAMS ((const TInsn *));
696 static void tinsn_from_chars
697   PARAMS ((TInsn *, char *));
698 static void tinsn_immed_from_frag
699   PARAMS ((TInsn *, fragS *));
700 static int get_num_stack_text_bytes
701   PARAMS ((IStack *));
702 static int get_num_stack_literal_bytes
703   PARAMS ((IStack *));
704
705 /* Expression Utilities.  */
706 bfd_boolean expr_is_const
707   PARAMS ((const expressionS *));
708 offsetT get_expr_const
709   PARAMS ((const expressionS *));
710 void set_expr_const
711   PARAMS ((expressionS *, offsetT));
712 void set_expr_symbol_offset
713   PARAMS ((expressionS *, symbolS *, offsetT));
714 bfd_boolean expr_is_equal
715   PARAMS ((expressionS *, expressionS *));
716 static void copy_expr
717   PARAMS ((expressionS *, const expressionS *));
718
719 #ifdef XTENSA_SECTION_RENAME
720 static void build_section_rename
721   PARAMS ((const char *));
722 static void add_section_rename
723   PARAMS ((char *, char *));
724 #endif
725
726
727 /* ISA imported from bfd.  */
728 extern xtensa_isa xtensa_default_isa;
729
730 extern int target_big_endian;
731
732 static xtensa_opcode xtensa_addi_opcode;
733 static xtensa_opcode xtensa_addmi_opcode;
734 static xtensa_opcode xtensa_call0_opcode;
735 static xtensa_opcode xtensa_call4_opcode;
736 static xtensa_opcode xtensa_call8_opcode;
737 static xtensa_opcode xtensa_call12_opcode;
738 static xtensa_opcode xtensa_callx0_opcode;
739 static xtensa_opcode xtensa_callx4_opcode;
740 static xtensa_opcode xtensa_callx8_opcode;
741 static xtensa_opcode xtensa_callx12_opcode;
742 static xtensa_opcode xtensa_entry_opcode;
743 static xtensa_opcode xtensa_isync_opcode;
744 static xtensa_opcode xtensa_j_opcode;
745 static xtensa_opcode xtensa_jx_opcode;
746 static xtensa_opcode xtensa_loop_opcode;
747 static xtensa_opcode xtensa_loopnez_opcode;
748 static xtensa_opcode xtensa_loopgtz_opcode;
749 static xtensa_opcode xtensa_nop_n_opcode;
750 static xtensa_opcode xtensa_or_opcode;
751 static xtensa_opcode xtensa_ret_opcode;
752 static xtensa_opcode xtensa_ret_n_opcode;
753 static xtensa_opcode xtensa_retw_opcode;
754 static xtensa_opcode xtensa_retw_n_opcode;
755 static xtensa_opcode xtensa_rsr_opcode;
756 static xtensa_opcode xtensa_waiti_opcode;
757
758 \f
759 /* Command-line Options.  */
760
761 bfd_boolean use_literal_section = TRUE;
762 static bfd_boolean align_targets = TRUE;
763 static bfd_boolean align_only_targets = FALSE;
764 static bfd_boolean software_a0_b_retw_interlock = TRUE;
765 static bfd_boolean has_a0_b_retw = FALSE;
766 static bfd_boolean workaround_a0_b_retw = TRUE;
767
768 static bfd_boolean software_avoid_b_j_loop_end = TRUE;
769 static bfd_boolean workaround_b_j_loop_end = TRUE;
770 static bfd_boolean maybe_has_b_j_loop_end = FALSE;
771
772 static bfd_boolean software_avoid_short_loop = TRUE;
773 static bfd_boolean workaround_short_loop = TRUE;
774 static bfd_boolean maybe_has_short_loop = FALSE;
775
776 static bfd_boolean software_avoid_close_loop_end = TRUE;
777 static bfd_boolean workaround_close_loop_end = TRUE;
778 static bfd_boolean maybe_has_close_loop_end = FALSE;
779
780 /* When avoid_short_loops is true, all loops with early exits must
781    have at least 3 instructions.  avoid_all_short_loops is a modifier
782    to the avoid_short_loop flag.  In addition to the avoid_short_loop
783    actions, all straightline loopgtz and loopnez must have at least 3
784    instructions.  */
785
786 static bfd_boolean software_avoid_all_short_loops = TRUE;
787 static bfd_boolean workaround_all_short_loops = TRUE;
788
789 /* This is on a per-instruction basis.  */
790 static bfd_boolean specific_opcode = FALSE;
791
792 enum
793 {
794   option_density = OPTION_MD_BASE,
795   option_no_density,
796
797   option_relax,
798   option_no_relax,
799
800   option_generics,
801   option_no_generics,
802
803   option_text_section_literals,
804   option_no_text_section_literals,
805
806   option_align_targets,
807   option_no_align_targets,
808
809   option_align_only_targets,
810   option_no_align_only_targets,
811
812   option_longcalls,
813   option_no_longcalls,
814
815   option_workaround_a0_b_retw,
816   option_no_workaround_a0_b_retw,
817
818   option_workaround_b_j_loop_end,
819   option_no_workaround_b_j_loop_end,
820
821   option_workaround_short_loop,
822   option_no_workaround_short_loop,
823
824   option_workaround_all_short_loops,
825   option_no_workaround_all_short_loops,
826
827   option_workaround_close_loop_end,
828   option_no_workaround_close_loop_end,
829
830   option_no_workarounds,
831
832 #ifdef XTENSA_SECTION_RENAME
833   option_literal_section_name,
834   option_text_section_name,
835   option_data_section_name,
836   option_bss_section_name,
837   option_rename_section_name,
838 #endif
839
840   option_eb,
841   option_el
842 };
843
844 const char *md_shortopts = "";
845
846 struct option md_longopts[] =
847 {
848   {"density", no_argument, NULL, option_density},
849   {"no-density", no_argument, NULL, option_no_density},
850   /* At least as early as alameda, --[no-]relax didn't work as
851      documented, so as of albany, --[no-]relax is equivalent to
852      --[no-]generics.  Both of these will be deprecated in
853      BearValley.  */
854   {"relax", no_argument, NULL, option_generics},
855   {"no-relax", no_argument, NULL, option_no_generics},
856   {"generics", no_argument, NULL, option_generics},
857   {"no-generics", no_argument, NULL, option_no_generics},
858   {"text-section-literals", no_argument, NULL, option_text_section_literals},
859   {"no-text-section-literals", no_argument, NULL,
860    option_no_text_section_literals},
861   /* This option was changed from -align-target to -target-align
862      because it conflicted with the "-al" option.  */
863   {"target-align", no_argument, NULL, option_align_targets},
864   {"no-target-align", no_argument, NULL,
865    option_no_align_targets},
866 #if 0
867   /* This option  should do a better job aligning targets because
868      it will only attempt to align targets that are the target of a 
869      branch.  */
870    { "target-align-only", no_argument, NULL, option_align_only_targets },
871    { "no-target-align-only", no_argument, NULL, option_no_align_only_targets },
872 #endif /* 0 */
873   {"longcalls", no_argument, NULL, option_longcalls},
874   {"no-longcalls", no_argument, NULL, option_no_longcalls},
875
876   {"no-workaround-a0-b-retw", no_argument, NULL,
877    option_no_workaround_a0_b_retw},
878   {"workaround-a0-b-retw", no_argument, NULL, option_workaround_a0_b_retw},
879   
880   {"no-workaround-b-j-loop-end", no_argument, NULL,
881    option_no_workaround_b_j_loop_end},
882   {"workaround-b-j-loop-end", no_argument, NULL,
883    option_workaround_b_j_loop_end},
884   
885   {"no-workaround-short-loops", no_argument, NULL,
886    option_no_workaround_short_loop},
887   {"workaround-short-loops", no_argument, NULL, option_workaround_short_loop},
888
889   {"no-workaround-all-short-loops", no_argument, NULL,
890    option_no_workaround_all_short_loops},
891   {"workaround-all-short-loop", no_argument, NULL,
892    option_workaround_all_short_loops},
893
894   {"no-workaround-close-loop-end", no_argument, NULL,
895    option_no_workaround_close_loop_end},
896   {"workaround-close-loop-end", no_argument, NULL,
897    option_workaround_close_loop_end},
898
899   {"no-workarounds", no_argument, NULL, option_no_workarounds},
900
901 #ifdef XTENSA_SECTION_RENAME
902   {"literal-section-name", required_argument, NULL,
903    option_literal_section_name},
904   {"text-section-name", required_argument, NULL,
905    option_text_section_name},
906   {"data-section-name", required_argument, NULL,
907    option_data_section_name},
908   {"rename-section", required_argument, NULL,
909    option_rename_section_name},
910   {"bss-section-name", required_argument, NULL,
911    option_bss_section_name},
912 #endif /* XTENSA_SECTION_RENAME */
913
914   {NULL, no_argument, NULL, 0}
915 };
916
917 size_t md_longopts_size = sizeof md_longopts;
918
919
920 int
921 md_parse_option (c, arg)
922      int c;
923      char *arg;
924 {
925   switch (c)
926     {
927     case option_density:
928       if (!density_supported)
929         {
930           as_bad (_("'--density' option not supported in this Xtensa "
931                   "configuration"));
932           return 0;
933         }
934       directive_state[directive_density] = TRUE;
935       return 1;
936     case option_no_density:
937       directive_state[directive_density] = FALSE;
938       return 1;
939     case option_generics:
940       directive_state[directive_generics] = TRUE;
941       return 1;
942     case option_no_generics:
943       directive_state[directive_generics] = FALSE;
944       return 1;
945     case option_longcalls:
946       directive_state[directive_longcalls] = TRUE;
947       return 1;
948     case option_no_longcalls:
949       directive_state[directive_longcalls] = FALSE;
950       return 1;
951     case option_text_section_literals:
952       use_literal_section = FALSE;
953       return 1;
954     case option_no_text_section_literals:
955       use_literal_section = TRUE;
956       return 1;
957     case option_workaround_a0_b_retw:
958       workaround_a0_b_retw = TRUE;
959       software_a0_b_retw_interlock = TRUE;
960       return 1;
961     case option_no_workaround_a0_b_retw:
962       workaround_a0_b_retw = FALSE;
963       software_a0_b_retw_interlock = FALSE;
964       return 1;
965     case option_workaround_b_j_loop_end:
966       workaround_b_j_loop_end = TRUE;
967       software_avoid_b_j_loop_end = TRUE;
968       return 1;
969     case option_no_workaround_b_j_loop_end:
970       workaround_b_j_loop_end = FALSE;
971       software_avoid_b_j_loop_end = FALSE;
972       return 1;
973
974     case option_workaround_short_loop:
975       workaround_short_loop = TRUE;
976       software_avoid_short_loop = TRUE;
977       return 1;
978     case option_no_workaround_short_loop:
979       workaround_short_loop = FALSE;
980       software_avoid_short_loop = FALSE;
981       return 1;
982
983     case option_workaround_all_short_loops:
984       workaround_all_short_loops = TRUE;
985       software_avoid_all_short_loops = TRUE;
986       return 1;
987     case option_no_workaround_all_short_loops:
988       workaround_all_short_loops = FALSE;
989       software_avoid_all_short_loops = FALSE;
990       return 1;
991
992     case option_workaround_close_loop_end:
993       workaround_close_loop_end = TRUE;
994       software_avoid_close_loop_end = TRUE;
995       return 1;
996     case option_no_workaround_close_loop_end:
997       workaround_close_loop_end = FALSE;
998       software_avoid_close_loop_end = FALSE;
999       return 1;
1000
1001     case option_no_workarounds:
1002       workaround_a0_b_retw = FALSE;
1003       software_a0_b_retw_interlock = FALSE;
1004       workaround_b_j_loop_end = FALSE;
1005       software_avoid_b_j_loop_end = FALSE;
1006       workaround_short_loop = FALSE;
1007       software_avoid_short_loop = FALSE;
1008       workaround_all_short_loops = FALSE;
1009       software_avoid_all_short_loops = FALSE;
1010       workaround_close_loop_end = FALSE;
1011       software_avoid_close_loop_end = FALSE;
1012       return 1;
1013       
1014     case option_align_targets:
1015       align_targets = TRUE;
1016       return 1;
1017     case option_no_align_targets:
1018       align_targets = FALSE;
1019       return 1;
1020
1021     case option_align_only_targets:
1022       align_only_targets = TRUE;
1023       return 1;
1024     case option_no_align_only_targets:
1025       align_only_targets = FALSE;
1026       return 1;
1027
1028 #ifdef XTENSA_SECTION_RENAME
1029     case option_literal_section_name:
1030       add_section_rename (".literal", arg);
1031       as_warn (_("'--literal-section-name' is deprecated; "
1032                  "use '--rename-section .literal=NEWNAME'"));
1033       return 1;
1034
1035     case option_text_section_name:
1036       add_section_rename (".text", arg);
1037       as_warn (_("'--text-section-name' is deprecated; "
1038                  "use '--rename-section .text=NEWNAME'"));
1039       return 1;
1040
1041     case option_data_section_name:
1042       add_section_rename (".data", arg);
1043       as_warn (_("'--data-section-name' is deprecated; "
1044                  "use '--rename-section .data=NEWNAME'"));
1045       return 1;
1046
1047     case option_bss_section_name:
1048       add_section_rename (".bss", arg);
1049       as_warn (_("'--bss-section-name' is deprecated; "
1050                  "use '--rename-section .bss=NEWNAME'"));
1051       return 1;
1052
1053     case option_rename_section_name:
1054       build_section_rename (arg);
1055       return 1;
1056 #endif /* XTENSA_SECTION_RENAME */
1057
1058     case 'Q':
1059       /* -Qy, -Qn: SVR4 arguments controlling whether a .comment section
1060          should be emitted or not.  FIXME: Not implemented.  */
1061       return 1;
1062       
1063     default:
1064       return 0;
1065     }
1066 }
1067
1068
1069 void
1070 md_show_usage (stream)
1071      FILE *stream;
1072 {
1073   fputs ("\nXtensa options:\n"
1074          "--[no-]density          [Do not] emit density instructions\n"
1075          "--[no-]relax            [Do not] perform branch relaxation\n"
1076          "--[no-]generics         [Do not] transform instructions\n"
1077          "--[no-]longcalls        [Do not] emit 32-bit call sequences\n"
1078          "--[no-]target-align     [Do not] try to align branch targets\n"
1079          "--[no-]text-section-literals\n"
1080          "                        [Do not] put literals in the text section\n"
1081          "--no-workarounds        Do not use any Xtensa workarounds\n"
1082 #ifdef XTENSA_SECTION_RENAME
1083          "--rename-section old=new(:old1=new1)*\n"
1084          "                        Rename section 'old' to 'new'\n"
1085          "\nThe following Xtensa options are deprecated\n"
1086          "--literal-section-name  Name of literal section (default .literal)\n"
1087          "--text-section-name     Name of text section (default .text)\n"
1088          "--data-section-name     Name of data section (default .data)\n"
1089          "--bss-section-name      Name of bss section (default .bss)\n"
1090 #endif
1091          , stream);
1092 }
1093
1094 \f
1095 /* Directive data and functions.  */
1096
1097 typedef struct state_stackS_struct
1098 {
1099   directiveE directive;
1100   bfd_boolean negated;
1101   bfd_boolean old_state;
1102   const char *file;
1103   unsigned int line;
1104   const void *datum;
1105   struct state_stackS_struct *prev;
1106 } state_stackS;
1107
1108 state_stackS *directive_state_stack;
1109
1110 const pseudo_typeS md_pseudo_table[] =
1111 {
1112   {"align", s_align_bytes, 0},  /* Defaulting is invalid (0) */
1113   {"literal_position", xtensa_literal_position, 0},
1114   {"frame", s_ignore, 0},       /* formerly used for STABS debugging */
1115   {"word", cons, 4},
1116   {"begin", xtensa_begin_directive, 0},
1117   {"end", xtensa_end_directive, 0},
1118   {"literal", xtensa_literal_pseudo, 0},
1119   {NULL, 0, 0},
1120 };
1121
1122
1123 bfd_boolean
1124 use_generics ()
1125 {
1126   return directive_state[directive_generics];
1127 }
1128
1129
1130 bfd_boolean
1131 use_longcalls ()
1132 {
1133   return directive_state[directive_longcalls];
1134 }
1135
1136
1137 bfd_boolean
1138 code_density_available ()
1139 {
1140   return directive_state[directive_density];
1141 }
1142
1143
1144 bfd_boolean
1145 can_relax ()
1146 {
1147   return use_generics ();
1148 }
1149
1150
1151 static void
1152 directive_push (directive, negated, datum)
1153      directiveE directive;
1154      bfd_boolean negated;
1155      const void *datum;
1156 {
1157   char *file;
1158   unsigned int line;
1159   state_stackS *stack = (state_stackS *) xmalloc (sizeof (state_stackS));
1160
1161   as_where (&file, &line);
1162
1163   stack->directive = directive;
1164   stack->negated = negated;
1165   stack->old_state = directive_state[directive];
1166   stack->file = file;
1167   stack->line = line;
1168   stack->datum = datum;
1169   stack->prev = directive_state_stack;
1170   directive_state_stack = stack;
1171
1172   directive_state[directive] = !negated;
1173 }
1174
1175 static void
1176 directive_pop (directive, negated, file, line, datum)
1177      directiveE *directive;
1178      bfd_boolean *negated;
1179      const char **file;
1180      unsigned int *line;
1181      const void **datum;
1182 {
1183   state_stackS *top = directive_state_stack;
1184
1185   if (!directive_state_stack)
1186     {
1187       as_bad (_("unmatched end directive"));
1188       *directive = directive_none;
1189       return;
1190     }
1191
1192   directive_state[directive_state_stack->directive] = top->old_state;
1193   *directive = top->directive;
1194   *negated = top->negated;
1195   *file = top->file;
1196   *line = top->line;
1197   *datum = top->datum;
1198   directive_state_stack = top->prev;
1199   free (top);
1200 }
1201
1202
1203 static void
1204 directive_balance ()
1205 {
1206   while (directive_state_stack)
1207     {
1208       directiveE directive;
1209       bfd_boolean negated;
1210       const char *file;
1211       unsigned int line;
1212       const void *datum;
1213
1214       directive_pop (&directive, &negated, &file, &line, &datum);
1215       as_warn_where ((char *) file, line,
1216                      _(".begin directive with no matching .end directive"));
1217     }
1218 }
1219
1220
1221 static bfd_boolean
1222 inside_directive (dir)
1223      directiveE dir;
1224 {
1225   state_stackS *top = directive_state_stack;
1226
1227   while (top && top->directive != dir)
1228     top = top->prev;
1229
1230   return (top != NULL);
1231 }
1232
1233
1234 static void
1235 get_directive (directive, negated)
1236      directiveE *directive;
1237      bfd_boolean *negated;
1238 {
1239   int len;
1240   unsigned i;
1241
1242   if (strncmp (input_line_pointer, "no-", 3) != 0)
1243     *negated = FALSE;
1244   else
1245     {
1246       *negated = TRUE;
1247       input_line_pointer += 3;
1248     }
1249
1250   len = strspn (input_line_pointer,
1251                 "abcdefghijklmnopqrstuvwxyz_/0123456789.");
1252
1253   for (i = 0; i < sizeof (directive_info) / sizeof (*directive_info); ++i)
1254     {
1255       if (strncmp (input_line_pointer, directive_info[i].name, len) == 0)
1256         {
1257           input_line_pointer += len;
1258           *directive = (directiveE) i;
1259           if (*negated && !directive_info[i].can_be_negated)
1260             as_bad (_("directive %s can't be negated"),
1261                     directive_info[i].name);
1262           return;
1263         }
1264     }
1265
1266   as_bad (_("unknown directive"));
1267   *directive = (directiveE) XTENSA_UNDEFINED;
1268 }
1269
1270
1271 static void
1272 xtensa_begin_directive (ignore)
1273      int ignore ATTRIBUTE_UNUSED;
1274 {
1275   directiveE directive;
1276   bfd_boolean negated;
1277   emit_state *state;
1278   int len;
1279   lit_state *ls;
1280
1281   md_flush_pending_output ();
1282
1283   get_directive (&directive, &negated);
1284   if (directive == (directiveE) XTENSA_UNDEFINED)
1285     {
1286       discard_rest_of_line ();
1287       return;
1288     }
1289
1290   switch (directive)
1291     {
1292     case directive_literal:
1293       if (!inside_directive (directive_literal))
1294         {
1295           /* Previous labels go with whatever follows this directive, not with
1296              the literal, so save them now.  */
1297           saved_insn_labels = insn_labels;
1298           insn_labels = NULL;
1299         }
1300       state = (emit_state *) xmalloc (sizeof (emit_state));
1301       xtensa_switch_to_literal_fragment (state);
1302       directive_push (directive_literal, negated, state);
1303       break;
1304
1305     case directive_literal_prefix:
1306       /* Check to see if the current fragment is a literal
1307          fragment.  If it is, then this operation is not allowed.  */
1308       if (frag_now->tc_frag_data.is_literal)
1309         {
1310           as_bad (_("cannot set literal_prefix inside literal fragment"));
1311           return;
1312         }
1313
1314       /* Allocate the literal state for this section and push
1315          onto the directive stack.  */
1316       ls = xmalloc (sizeof (lit_state));
1317       assert (ls);
1318
1319       *ls = default_lit_sections;
1320
1321       directive_push (directive_literal_prefix, negated, ls);
1322
1323       /* Parse the new prefix from the input_line_pointer.  */
1324       SKIP_WHITESPACE ();
1325       len = strspn (input_line_pointer,
1326                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1327                     "abcdefghijklmnopqrstuvwxyz_/0123456789.$");
1328
1329       /* Process the new prefix.  */
1330       xtensa_literal_prefix (input_line_pointer, len);
1331
1332       /* Skip the name in the input line.  */
1333       input_line_pointer += len;
1334       break;
1335
1336     case directive_freeregs:
1337       /* This information is currently unused, but we'll accept the statement
1338          and just discard the rest of the line.  This won't check the syntax,
1339          but it will accept every correct freeregs directive.  */
1340       input_line_pointer += strcspn (input_line_pointer, "\n");
1341       directive_push (directive_freeregs, negated, 0);
1342       break;
1343
1344     case directive_density:
1345       if (!density_supported && !negated)
1346         {
1347           as_warn (_("Xtensa density option not supported; ignored"));
1348           break;
1349         }
1350       /* fall through */
1351
1352     default:
1353       directive_push (directive, negated, 0);
1354       break;
1355     }
1356
1357   demand_empty_rest_of_line ();
1358 }
1359
1360
1361 static void
1362 xtensa_end_directive (ignore)
1363      int ignore ATTRIBUTE_UNUSED;
1364 {
1365   directiveE begin_directive, end_directive;
1366   bfd_boolean begin_negated, end_negated;
1367   const char *file;
1368   unsigned int line;
1369   emit_state *state;
1370   lit_state *s;
1371
1372   md_flush_pending_output ();
1373
1374   get_directive (&end_directive, &end_negated);
1375   if (end_directive == (directiveE) XTENSA_UNDEFINED)
1376     {
1377       discard_rest_of_line ();
1378       return;
1379     }
1380
1381   if (end_directive == directive_density && !density_supported && !end_negated)
1382     {
1383       as_warn (_("Xtensa density option not supported; ignored"));
1384       demand_empty_rest_of_line ();
1385       return;
1386     }
1387
1388   directive_pop (&begin_directive, &begin_negated, &file, &line,
1389                  (const void **) &state);
1390
1391   if (begin_directive != directive_none)
1392     {
1393       if (begin_directive != end_directive || begin_negated != end_negated)
1394         {
1395           as_bad (_("does not match begin %s%s at %s:%d"),
1396                   begin_negated ? "no-" : "",
1397                   directive_info[begin_directive].name, file, line);
1398         }
1399       else
1400         {
1401           switch (end_directive)
1402             {
1403             case directive_literal:
1404               frag_var (rs_fill, 0, 0, 0, NULL, 0, NULL);
1405               xtensa_restore_emit_state (state);
1406               free (state);
1407               if (!inside_directive (directive_literal))
1408                 {
1409                   /* Restore the list of current labels.  */
1410                   xtensa_clear_insn_labels ();
1411                   insn_labels = saved_insn_labels;
1412                 }
1413               break;
1414
1415             case directive_freeregs:
1416               break;
1417
1418             case directive_literal_prefix:
1419               /* Restore the default collection sections from saved state.  */
1420               s = (lit_state *) state;
1421               assert (s);
1422
1423               if (use_literal_section)
1424                 default_lit_sections = *s;
1425
1426               /* free the state storage */
1427               free (s);
1428               break;
1429
1430             default:
1431               break;
1432             }
1433         }
1434     }
1435
1436   demand_empty_rest_of_line ();
1437 }
1438
1439
1440 /* Place an aligned literal fragment at the current location.  */
1441
1442 static void
1443 xtensa_literal_position (ignore)
1444      int ignore ATTRIBUTE_UNUSED;
1445 {
1446   if (inside_directive (directive_literal))
1447     as_warn (_(".literal_position inside literal directive; ignoring"));
1448   else if (!use_literal_section)
1449     xtensa_mark_literal_pool_location ();
1450
1451   demand_empty_rest_of_line ();
1452   xtensa_clear_insn_labels ();
1453 }
1454
1455
1456 /* Support .literal label, value@plt + offset.  */
1457
1458 static void
1459 xtensa_literal_pseudo (ignored)
1460      int ignored ATTRIBUTE_UNUSED;
1461 {
1462   emit_state state;
1463   char *p, *base_name;
1464   char c;
1465   expressionS expP;
1466   segT dest_seg;
1467
1468   if (inside_directive (directive_literal))
1469     {
1470       as_bad (_(".literal not allowed inside .begin literal region"));
1471       ignore_rest_of_line ();
1472       return;
1473     }
1474
1475   /* Previous labels go with whatever follows this directive, not with
1476      the literal, so save them now.  */
1477   saved_insn_labels = insn_labels;
1478   insn_labels = NULL;
1479
1480   /* If we are using text-section literals, then this is the right value... */
1481   dest_seg = now_seg;
1482
1483   base_name = input_line_pointer;
1484
1485   xtensa_switch_to_literal_fragment (&state);
1486
1487   /* ...but if we aren't using text-section-literals, then we 
1488      need to put them in the section we just switched to.  */
1489   if (use_literal_section)
1490     dest_seg = now_seg;
1491
1492   /* All literals are aligned to four-byte boundaries
1493      which is handled by switch to literal fragment.  */
1494   /* frag_align (2, 0, 0);  */
1495
1496   c = get_symbol_end ();
1497   /* Just after name is now '\0'.  */
1498   p = input_line_pointer;
1499   *p = c;
1500   SKIP_WHITESPACE ();
1501
1502   if (*input_line_pointer != ',' && *input_line_pointer != ':')
1503     {
1504       as_bad (_("expected comma or colon after symbol name; "
1505                 "rest of line ignored"));
1506       ignore_rest_of_line ();
1507       xtensa_restore_emit_state (&state);
1508       return;
1509     }
1510   *p = 0;
1511
1512   colon (base_name);
1513
1514   do 
1515     {
1516       input_line_pointer++;             /* skip ',' or ':' */
1517       
1518       expr (0, &expP);
1519
1520       /* We only support 4-byte literals with .literal.  */
1521       emit_expr (&expP, 4);
1522     }
1523   while (*input_line_pointer == ',');
1524
1525   *p = c;
1526
1527   demand_empty_rest_of_line ();
1528
1529   xtensa_restore_emit_state (&state);
1530
1531   /* Restore the list of current labels.  */
1532   xtensa_clear_insn_labels ();
1533   insn_labels = saved_insn_labels;
1534 }
1535
1536
1537 static void
1538 xtensa_literal_prefix (start, len)
1539      char const *start;
1540      int len;
1541 {
1542   segT s_now;                   /* Storage for the current seg and subseg.  */
1543   subsegT ss_now;
1544   char *name;                   /* Pointer to the name itself.  */
1545   char *newname;
1546
1547   if (!use_literal_section)
1548     return;
1549
1550   /* Store away the current section and subsection.  */
1551   s_now = now_seg;
1552   ss_now = now_subseg;
1553
1554   /* Get a null-terminated copy of the name.  */
1555   name = xmalloc (len + 1);
1556   assert (name);
1557
1558   strncpy (name, start, len);
1559   name[len] = 0;
1560
1561   /* Allocate the sections (interesting note: the memory pointing to
1562      the name is actually used for the name by the new section). */
1563   newname = xmalloc (len + strlen (".literal") + 1);
1564   strcpy (newname, name);
1565   strcpy (newname + len, ".literal");
1566
1567   /* Note that retrieve_literal_seg does not create a segment if 
1568      it already exists.  */
1569   default_lit_sections.lit_seg = NULL;  /* retrieved on demand */
1570
1571   /* Canonicalizing section names allows renaming literal
1572      sections to occur correctly.  */
1573   default_lit_sections.lit_seg_name =
1574     tc_canonicalize_symbol_name (newname);
1575
1576   free (name);
1577
1578   /* Restore the current section and subsection and set the 
1579      generation into the old segment.  */
1580   subseg_set (s_now, ss_now);
1581 }
1582
1583 \f
1584 /* Parsing and Idiom Translation.  */
1585
1586 static const char *
1587 expression_end (name)
1588      const char *name;
1589 {
1590   while (1)
1591     {
1592       switch (*name)
1593         {
1594         case ';':
1595         case '\0':
1596         case ',':
1597           return name;
1598         case ' ':
1599         case '\t':
1600           ++name;
1601           continue;
1602         default:
1603           return 0;
1604         }
1605     }
1606 }
1607
1608
1609 #define ERROR_REG_NUM ((unsigned) -1)
1610
1611 static unsigned
1612 tc_get_register (prefix)
1613      const char *prefix;
1614 {
1615   unsigned reg;
1616   const char *next_expr;
1617   const char *old_line_pointer;
1618
1619   SKIP_WHITESPACE ();
1620   old_line_pointer = input_line_pointer;
1621
1622   if (*input_line_pointer == '$')
1623     ++input_line_pointer;
1624
1625   /* Accept "sp" as a synonym for "a1".  */
1626   if (input_line_pointer[0] == 's' && input_line_pointer[1] == 'p'
1627       && expression_end (input_line_pointer + 2))
1628     {
1629       input_line_pointer += 2;
1630       return 1;  /* AR[1] */
1631     }
1632
1633   while (*input_line_pointer++ == *prefix++)
1634     ;
1635   --input_line_pointer;
1636   --prefix;
1637
1638   if (*prefix)
1639     {
1640       as_bad (_("bad register name: %s"), old_line_pointer);
1641       return ERROR_REG_NUM;
1642     }
1643
1644   if (!ISDIGIT ((unsigned char) *input_line_pointer))
1645     {
1646       as_bad (_("bad register number: %s"), input_line_pointer);
1647       return ERROR_REG_NUM;
1648     }
1649
1650   reg = 0;
1651
1652   while (ISDIGIT ((int) *input_line_pointer))
1653     reg = reg * 10 + *input_line_pointer++ - '0';
1654
1655   if (!(next_expr = expression_end (input_line_pointer)))
1656     {
1657       as_bad (_("bad register name: %s"), old_line_pointer);
1658       return ERROR_REG_NUM;
1659     }
1660
1661   input_line_pointer = (char *) next_expr;
1662
1663   return reg;
1664 }
1665
1666
1667 #define PLT_SUFFIX "@PLT"
1668 #define plt_suffix "@plt"
1669
1670 static void
1671 expression_maybe_register (opnd, tok)
1672      xtensa_operand opnd;
1673      expressionS *tok;
1674 {
1675   char *kind = xtensa_operand_kind (opnd);
1676
1677   if ((strlen (kind) == 1)
1678       && (*kind == 'l' || *kind == 'L' || *kind == 'i' || *kind == 'r'))
1679     {
1680       segT t = expression (tok);
1681       if (t == absolute_section && operand_is_pcrel_label (opnd))
1682         {
1683           assert (tok->X_op == O_constant);
1684           tok->X_op = O_symbol;
1685           tok->X_add_symbol = &abs_symbol;
1686         }
1687       if (tok->X_op == O_symbol 
1688           && (!strncmp (input_line_pointer, PLT_SUFFIX,
1689                         strlen (PLT_SUFFIX) - 1)
1690               || !strncmp (input_line_pointer, plt_suffix,
1691                            strlen (plt_suffix) - 1)))
1692         {
1693           symbol_get_tc (tok->X_add_symbol)->plt = 1;
1694           input_line_pointer += strlen (plt_suffix);
1695         }
1696     }
1697   else
1698     {
1699       unsigned reg = tc_get_register (kind);
1700
1701       if (reg != ERROR_REG_NUM) /* Already errored */
1702         {
1703           uint32 buf = reg;
1704           if ((xtensa_operand_encode (opnd, &buf) != xtensa_encode_result_ok)
1705               || (reg != xtensa_operand_decode (opnd, buf)))
1706             as_bad (_("register number out of range"));
1707         }
1708
1709       tok->X_op = O_register;
1710       tok->X_add_symbol = 0;
1711       tok->X_add_number = reg;
1712     }
1713 }
1714
1715
1716 /* Split up the arguments for an opcode or pseudo-op.  */
1717
1718 static int
1719 tokenize_arguments (args, str)
1720      char **args;
1721      char *str;
1722 {
1723   char *old_input_line_pointer;
1724   bfd_boolean saw_comma = FALSE;
1725   bfd_boolean saw_arg = FALSE;
1726   int num_args = 0;
1727   char *arg_end, *arg;
1728   int arg_len;
1729   
1730   /* Save and restore input_line_pointer around this function.  */ 
1731   old_input_line_pointer = input_line_pointer;
1732   input_line_pointer = str;
1733
1734   while (*input_line_pointer)
1735     {
1736       SKIP_WHITESPACE ();
1737       switch (*input_line_pointer)
1738         {
1739         case '\0':
1740           goto fini;
1741
1742         case ',':
1743           input_line_pointer++;
1744           if (saw_comma || !saw_arg)
1745             goto err;
1746           saw_comma = TRUE;
1747           break;
1748
1749         default:
1750           if (!saw_comma && saw_arg)
1751             goto err;
1752
1753           arg_end = input_line_pointer + 1;
1754           while (!expression_end (arg_end))
1755             arg_end += 1;
1756  
1757           arg_len = arg_end - input_line_pointer;
1758           arg = (char *) xmalloc (arg_len + 1);
1759           args[num_args] = arg;
1760
1761           strncpy (arg, input_line_pointer, arg_len);
1762           arg[arg_len] = '\0';
1763  
1764           input_line_pointer = arg_end;
1765           num_args += 1;
1766           saw_comma = FALSE; 
1767           saw_arg = TRUE; 
1768           break;
1769         }
1770     }
1771
1772 fini:
1773   if (saw_comma)
1774     goto err;
1775   input_line_pointer = old_input_line_pointer;
1776   return num_args;
1777
1778 err:
1779   input_line_pointer = old_input_line_pointer;
1780   return -1;
1781 }
1782
1783
1784 /* Parse the arguments to an opcode.  Return true on error.  */
1785
1786 static bfd_boolean
1787 parse_arguments (insn, num_args, arg_strings)
1788      TInsn *insn;
1789      int num_args;
1790      char **arg_strings;
1791 {
1792   expressionS *tok = insn->tok;
1793   xtensa_opcode opcode = insn->opcode;
1794   bfd_boolean had_error = TRUE;
1795   xtensa_isa isa = xtensa_default_isa; 
1796   int n;
1797   int opcode_operand_count;
1798   int actual_operand_count = 0;
1799   xtensa_operand opnd = NULL; 
1800   char *old_input_line_pointer;
1801
1802   if (insn->insn_type == ITYPE_LITERAL)
1803     opcode_operand_count = 1;
1804   else
1805     opcode_operand_count = xtensa_num_operands (isa, opcode);
1806
1807   memset (tok, 0, sizeof (*tok) * MAX_INSN_ARGS);
1808
1809   /* Save and restore input_line_pointer around this function.  */
1810   old_input_line_pointer = input_line_pointer; 
1811
1812   for (n = 0; n < num_args; n++)
1813     { 
1814       input_line_pointer = arg_strings[n];
1815
1816       if (actual_operand_count >= opcode_operand_count)
1817         { 
1818           as_warn (_("too many arguments")); 
1819           goto err;
1820         } 
1821       assert (actual_operand_count < MAX_INSN_ARGS);
1822
1823       opnd = xtensa_get_operand (isa, opcode, actual_operand_count); 
1824       expression_maybe_register (opnd, tok);
1825
1826       if (tok->X_op == O_illegal || tok->X_op == O_absent) 
1827         goto err; 
1828       actual_operand_count++;
1829       tok++; 
1830     } 
1831
1832   insn->ntok = tok - insn->tok;
1833   had_error = FALSE; 
1834
1835  err:
1836   input_line_pointer = old_input_line_pointer; 
1837   return had_error;
1838 }
1839
1840
1841 static void
1842 xg_reverse_shift_count (cnt_argp)
1843      char **cnt_argp;
1844 {
1845   char *cnt_arg, *new_arg;
1846   cnt_arg = *cnt_argp;
1847
1848   /* replace the argument with "31-(argument)" */
1849   new_arg = (char *) xmalloc (strlen (cnt_arg) + 6);
1850   sprintf (new_arg, "31-(%s)", cnt_arg);
1851
1852   free (cnt_arg);
1853   *cnt_argp = new_arg;
1854 }
1855
1856
1857 /* If "arg" is a constant expression, return non-zero with the value
1858    in *valp.  */
1859
1860 static int
1861 xg_arg_is_constant (arg, valp)
1862      char *arg;
1863      offsetT *valp;
1864 {
1865   expressionS exp;
1866   char *save_ptr = input_line_pointer;
1867
1868   input_line_pointer = arg;
1869   expression (&exp);
1870   input_line_pointer = save_ptr;
1871
1872   if (exp.X_op == O_constant)
1873     {
1874       *valp = exp.X_add_number;
1875       return 1;
1876     }
1877
1878   return 0;
1879 }
1880
1881
1882 static void
1883 xg_replace_opname (popname, newop)
1884      char **popname;
1885      char *newop;
1886 {
1887   free (*popname);
1888   *popname = (char *) xmalloc (strlen (newop) + 1);
1889   strcpy (*popname, newop);
1890 }
1891
1892
1893 static int
1894 xg_check_num_args (pnum_args, expected_num, opname, arg_strings)
1895      int *pnum_args;
1896      int expected_num; 
1897      char *opname;
1898      char **arg_strings;
1899 {
1900   int num_args = *pnum_args;
1901
1902   if (num_args < expected_num) 
1903     {
1904       as_bad (_("not enough operands (%d) for '%s'; expected %d"),
1905               num_args, opname, expected_num);
1906       return -1;
1907     }
1908
1909   if (num_args > expected_num)
1910     {
1911       as_warn (_("too many operands (%d) for '%s'; expected %d"),
1912                num_args, opname, expected_num);
1913       while (num_args-- > expected_num)
1914         {
1915           free (arg_strings[num_args]);
1916           arg_strings[num_args] = 0;
1917         }
1918       *pnum_args = expected_num;
1919       return -1;
1920     }
1921
1922   return 0;
1923 }
1924
1925
1926 static int
1927 xg_translate_sysreg_op (popname, pnum_args, arg_strings)
1928      char **popname;
1929      int *pnum_args;
1930      char **arg_strings;
1931 {
1932   char *opname, *new_opname;
1933   offsetT val;
1934   bfd_boolean has_underbar = FALSE;
1935
1936   opname = *popname;
1937   if (*opname == '_')
1938     {
1939       has_underbar = TRUE;
1940       opname += 1;
1941     }
1942
1943   /* Opname == [rw]ur... */
1944
1945   if (opname[3] == '\0')
1946     {
1947       /* If the register is not specified as part of the opcode,
1948          then get it from the operand and move it to the opcode.  */
1949
1950       if (xg_check_num_args (pnum_args, 2, opname, arg_strings))
1951         return -1;
1952
1953       if (!xg_arg_is_constant (arg_strings[1], &val))
1954         {
1955           as_bad (_("register number for `%s' is not a constant"), opname);
1956           return -1;
1957         }
1958       if ((unsigned) val > 255)
1959         {
1960           as_bad (_("register number (%ld) for `%s' is out of range"),
1961                   val, opname);
1962           return -1;
1963         }
1964
1965       /* Remove the last argument, which is now part of the opcode.  */
1966       free (arg_strings[1]);
1967       arg_strings[1] = 0;
1968       *pnum_args = 1;
1969
1970       /* Translate the opcode.  */
1971       new_opname = (char *) xmalloc (8);
1972       sprintf (new_opname, "%s%cur%u", (has_underbar ? "_" : ""),
1973                opname[0], (unsigned) val);
1974       free (*popname);
1975       *popname = new_opname;
1976     }
1977
1978   return 0;
1979 }
1980
1981
1982 /* If the instruction is an idiom (i.e., a built-in macro), translate it.
1983    Returns non-zero if an error was found.  */
1984
1985 static int
1986 xg_translate_idioms (popname, pnum_args, arg_strings)
1987      char **popname;
1988      int *pnum_args;
1989      char **arg_strings;
1990 {
1991   char *opname = *popname;
1992   bfd_boolean has_underbar = FALSE;
1993
1994   if (*opname == '_')
1995     {
1996       has_underbar = TRUE;
1997       opname += 1;
1998     }
1999
2000   if (strcmp (opname, "mov") == 0)
2001     {
2002       if (!has_underbar && code_density_available ())
2003         xg_replace_opname (popname, "mov.n");
2004       else
2005         {
2006           if (xg_check_num_args (pnum_args, 2, opname, arg_strings))
2007             return -1;
2008           xg_replace_opname (popname, (has_underbar ? "_or" : "or"));
2009           arg_strings[2] = (char *) xmalloc (strlen (arg_strings[1]) + 1);
2010           strcpy (arg_strings[2], arg_strings[1]);
2011           *pnum_args = 3;
2012         }
2013       return 0;
2014     }
2015
2016   if (strcmp (opname, "bbsi.l") == 0)
2017     {
2018       if (xg_check_num_args (pnum_args, 3, opname, arg_strings))
2019         return -1;
2020       xg_replace_opname (popname, (has_underbar ? "_bbsi" : "bbsi"));
2021       if (target_big_endian)
2022         xg_reverse_shift_count (&arg_strings[1]);
2023       return 0;
2024     }
2025
2026   if (strcmp (opname, "bbci.l") == 0)
2027     {
2028       if (xg_check_num_args (pnum_args, 3, opname, arg_strings))
2029         return -1;
2030       xg_replace_opname (popname, (has_underbar ? "_bbci" : "bbci"));
2031       if (target_big_endian)
2032         xg_reverse_shift_count (&arg_strings[1]);
2033       return 0;
2034     }
2035
2036   if (strcmp (opname, "nop") == 0)
2037     {
2038       if (!has_underbar && code_density_available ())
2039         xg_replace_opname (popname, "nop.n");
2040       else
2041         {
2042           if (xg_check_num_args (pnum_args, 0, opname, arg_strings))
2043             return -1;
2044           xg_replace_opname (popname, (has_underbar ? "_or" : "or"));
2045           arg_strings[0] = (char *) xmalloc (3);
2046           arg_strings[1] = (char *) xmalloc (3);
2047           arg_strings[2] = (char *) xmalloc (3);
2048           strcpy (arg_strings[0], "a1");
2049           strcpy (arg_strings[1], "a1");
2050           strcpy (arg_strings[2], "a1");
2051           *pnum_args = 3;
2052         }
2053       return 0;
2054     }
2055
2056   if ((opname[0] == 'r' || opname[0] == 'w')
2057       && opname[1] == 'u'
2058       && opname[2] == 'r')
2059     return xg_translate_sysreg_op (popname, pnum_args, arg_strings);
2060
2061
2062   /* WIDENING DENSITY OPCODES
2063
2064      questionable relaxations (widening) from old "tai" idioms:
2065
2066        ADD.N --> ADD
2067        BEQZ.N --> BEQZ
2068        RET.N --> RET
2069        RETW.N --> RETW
2070        MOVI.N --> MOVI
2071        MOV.N --> MOV
2072        NOP.N --> NOP
2073
2074      Note: this incomplete list was imported to match the "tai"
2075      behavior; other density opcodes are not handled.
2076
2077      The xtensa-relax code may know how to do these but it doesn't do
2078      anything when these density opcodes appear inside a no-density
2079      region.  Somehow GAS should either print an error when that happens
2080      or do the widening.  The old "tai" behavior was to do the widening.
2081      For now, I'll make it widen but print a warning.
2082
2083      FIXME: GAS needs to detect density opcodes inside no-density
2084      regions and treat them as errors.  This code should be removed
2085      when that is done.  */
2086
2087   if (use_generics ()
2088       && !has_underbar
2089       && density_supported
2090       && !code_density_available ())
2091     {
2092       if (strcmp (opname, "add.n") == 0)
2093         xg_replace_opname (popname, "add");
2094
2095       else if (strcmp (opname, "beqz.n") == 0)
2096         xg_replace_opname (popname, "beqz");
2097
2098       else if (strcmp (opname, "ret.n") == 0)
2099         xg_replace_opname (popname, "ret");
2100
2101       else if (strcmp (opname, "retw.n") == 0)
2102         xg_replace_opname (popname, "retw");
2103
2104       else if (strcmp (opname, "movi.n") == 0)
2105         xg_replace_opname (popname, "movi");
2106
2107       else if (strcmp (opname, "mov.n") == 0)
2108         {
2109           if (xg_check_num_args (pnum_args, 2, opname, arg_strings))
2110             return -1;
2111           xg_replace_opname (popname, "or");
2112           arg_strings[2] = (char *) xmalloc (strlen (arg_strings[1]) + 1);
2113           strcpy (arg_strings[2], arg_strings[1]);
2114           *pnum_args = 3;
2115         }
2116
2117       else if (strcmp (opname, "nop.n") == 0)
2118         {
2119           if (xg_check_num_args (pnum_args, 0, opname, arg_strings))
2120             return -1;
2121           xg_replace_opname (popname, "or");
2122           arg_strings[0] = (char *) xmalloc (3);
2123           arg_strings[1] = (char *) xmalloc (3);
2124           arg_strings[2] = (char *) xmalloc (3);
2125           strcpy (arg_strings[0], "a1");
2126           strcpy (arg_strings[1], "a1");
2127           strcpy (arg_strings[2], "a1");
2128           *pnum_args = 3;
2129         }
2130     }
2131
2132   return 0;
2133 }
2134
2135 \f
2136 /* Functions for dealing with the Xtensa ISA.  */
2137
2138 /* Return true if the given operand is an immed or target instruction,
2139    i.e., has a reloc associated with it.  Currently, this is only true
2140    if the operand kind is "i, "l" or "L".  */
2141
2142 static bfd_boolean
2143 operand_is_immed (opnd)
2144      xtensa_operand opnd;
2145 {
2146   const char *opkind = xtensa_operand_kind (opnd);
2147   if (opkind[0] == '\0' || opkind[1] != '\0')
2148     return FALSE;
2149   switch (opkind[0])
2150     {
2151     case 'i':
2152     case 'l':
2153     case 'L':
2154       return TRUE;
2155     }
2156   return FALSE;
2157 }
2158
2159
2160 /* Return true if the given operand is a pc-relative label.  This is
2161    true for "l", "L", and "r" operand kinds.  */
2162
2163 bfd_boolean
2164 operand_is_pcrel_label (opnd)
2165      xtensa_operand opnd;
2166 {
2167   const char *opkind = xtensa_operand_kind (opnd);
2168   if (opkind[0] == '\0' || opkind[1] != '\0')
2169     return FALSE;
2170   switch (opkind[0])
2171     {
2172     case 'r':
2173     case 'l':
2174     case 'L':
2175       return TRUE;
2176     }
2177   return FALSE;
2178 }
2179
2180
2181 /* Currently the assembler only allows us to use a single target per
2182    fragment.  Because of this, only one operand for a given
2183    instruction may be symbolic.  If there is an operand of kind "lrL",
2184    the last one is chosen.  Otherwise, the result is the number of the
2185    last operand of type "i", and if there are none of those, we fail
2186    and return -1.  */
2187
2188 int
2189 get_relaxable_immed (opcode)
2190      xtensa_opcode opcode;
2191 {
2192   int last_immed = -1;
2193   int noperands, opi;
2194   xtensa_operand operand;
2195
2196   if (opcode == XTENSA_UNDEFINED)
2197     return -1;
2198
2199   noperands = xtensa_num_operands (xtensa_default_isa, opcode);
2200   for (opi = noperands - 1; opi >= 0; opi--)
2201     {
2202       operand = xtensa_get_operand (xtensa_default_isa, opcode, opi);
2203       if (operand_is_pcrel_label (operand))
2204         return opi;
2205       if (last_immed == -1 && operand_is_immed (operand))
2206         last_immed = opi;
2207     }
2208   return last_immed;
2209 }
2210
2211
2212 xtensa_opcode
2213 get_opcode_from_buf (buf)
2214      const char *buf;
2215 {
2216   static xtensa_insnbuf insnbuf = NULL;
2217   xtensa_opcode opcode;
2218   xtensa_isa isa = xtensa_default_isa;
2219   if (!insnbuf)
2220     insnbuf = xtensa_insnbuf_alloc (isa);
2221
2222   xtensa_insnbuf_from_chars (isa, insnbuf, buf);
2223   opcode = xtensa_decode_insn (isa, insnbuf);
2224   return opcode;
2225 }
2226
2227
2228 static bfd_boolean
2229 is_direct_call_opcode (opcode)
2230      xtensa_opcode opcode;
2231 {
2232   if (opcode == XTENSA_UNDEFINED)
2233     return FALSE;
2234
2235   return (opcode == xtensa_call0_opcode
2236           || opcode == xtensa_call4_opcode
2237           || opcode == xtensa_call8_opcode
2238           || opcode == xtensa_call12_opcode);
2239 }
2240
2241
2242 static bfd_boolean
2243 is_call_opcode (opcode)
2244      xtensa_opcode opcode;
2245 {
2246   if (is_direct_call_opcode (opcode))
2247     return TRUE;
2248
2249   if (opcode == XTENSA_UNDEFINED)
2250     return FALSE;
2251
2252   return (opcode == xtensa_callx0_opcode
2253           || opcode == xtensa_callx4_opcode
2254           || opcode == xtensa_callx8_opcode
2255           || opcode == xtensa_callx12_opcode);
2256 }
2257
2258
2259 /* Return true if the opcode is an entry opcode.  This is used because
2260    "entry" adds an implicit ".align 4" and also the entry instruction
2261    has an extra check for an operand value.  */
2262
2263 static bfd_boolean
2264 is_entry_opcode (opcode)
2265      xtensa_opcode opcode;
2266 {
2267   if (opcode == XTENSA_UNDEFINED)
2268     return FALSE;
2269
2270   return (opcode == xtensa_entry_opcode);
2271 }
2272
2273
2274 /* Return true if it is one of the loop opcodes.  Loops are special
2275    because they need automatic alignment and they have a relaxation so
2276    complex that we hard-coded it.  */
2277
2278 static bfd_boolean
2279 is_loop_opcode (opcode)
2280      xtensa_opcode opcode;
2281 {
2282   if (opcode == XTENSA_UNDEFINED)
2283     return FALSE;
2284
2285   return (opcode == xtensa_loop_opcode
2286           || opcode == xtensa_loopnez_opcode
2287           || opcode == xtensa_loopgtz_opcode);
2288 }
2289
2290
2291 static bfd_boolean
2292 is_the_loop_opcode (opcode)
2293      xtensa_opcode opcode;
2294 {
2295   if (opcode == XTENSA_UNDEFINED)
2296     return FALSE;
2297
2298   return (opcode == xtensa_loop_opcode);
2299 }
2300
2301
2302 static bfd_boolean
2303 is_jx_opcode (opcode)
2304      xtensa_opcode opcode;
2305 {
2306   if (opcode == XTENSA_UNDEFINED)
2307     return FALSE;
2308
2309   return (opcode == xtensa_jx_opcode);
2310 }
2311
2312
2313 /* Return true if the opcode is a retw or retw.n.
2314    Needed to add nops to avoid a hardware interlock issue.  */
2315
2316 static bfd_boolean
2317 is_windowed_return_opcode (opcode)
2318      xtensa_opcode opcode;
2319 {
2320   if (opcode == XTENSA_UNDEFINED)
2321     return FALSE;
2322
2323   return (opcode == xtensa_retw_opcode || opcode == xtensa_retw_n_opcode);
2324 }
2325
2326
2327 /* Return true if the opcode type is "l" and the opcode is NOT a jump.  */
2328
2329 static bfd_boolean
2330 is_conditional_branch_opcode (opcode)
2331      xtensa_opcode opcode;
2332 {
2333   xtensa_isa isa = xtensa_default_isa;
2334   int num_ops, i;
2335
2336   if (opcode == xtensa_j_opcode && opcode != XTENSA_UNDEFINED)
2337     return FALSE;
2338
2339   num_ops = xtensa_num_operands (isa, opcode);
2340   for (i = 0; i < num_ops; i++)
2341     {
2342       xtensa_operand operand = xtensa_get_operand (isa, opcode, i);
2343       if (strcmp (xtensa_operand_kind (operand), "l") == 0)
2344         return TRUE;
2345     }
2346   return FALSE;
2347 }
2348
2349
2350 /* Return true if the given opcode is a conditional branch
2351    instruction, i.e., currently this is true if the instruction 
2352    is a jx or has an operand with 'l' type and is not a loop.  */
2353
2354 bfd_boolean
2355 is_branch_or_jump_opcode (opcode)
2356      xtensa_opcode opcode;
2357 {
2358   int opn, op_count;
2359
2360   if (opcode == XTENSA_UNDEFINED)
2361     return FALSE;
2362
2363   if (is_loop_opcode (opcode))
2364     return FALSE;
2365
2366   if (is_jx_opcode (opcode))
2367     return TRUE;
2368
2369   op_count = xtensa_num_operands (xtensa_default_isa, opcode);
2370   for (opn = 0; opn < op_count; opn++)
2371     {
2372       xtensa_operand opnd =
2373         xtensa_get_operand (xtensa_default_isa, opcode, opn);
2374       const char *opkind = xtensa_operand_kind (opnd);
2375       if (opkind && opkind[0] == 'l' && opkind[1] == '\0')
2376         return TRUE;
2377     }
2378   return FALSE;
2379 }
2380
2381
2382 /* Convert from operand numbers to BFD relocation type code.
2383    Return BFD_RELOC_NONE on failure.  */
2384
2385 bfd_reloc_code_real_type
2386 opnum_to_reloc (opnum)
2387      int opnum;
2388 {
2389   switch (opnum)
2390     {
2391     case 0:
2392       return BFD_RELOC_XTENSA_OP0;
2393     case 1:
2394       return BFD_RELOC_XTENSA_OP1;
2395     case 2:
2396       return BFD_RELOC_XTENSA_OP2;
2397     default:
2398       break;
2399     }
2400   return BFD_RELOC_NONE;
2401 }
2402
2403
2404 /* Convert from BFD relocation type code to operand number.
2405    Return -1 on failure.  */
2406
2407 int
2408 reloc_to_opnum (reloc)
2409      bfd_reloc_code_real_type reloc;
2410 {
2411   switch (reloc)
2412     {
2413     case BFD_RELOC_XTENSA_OP0:
2414       return 0;
2415     case BFD_RELOC_XTENSA_OP1:
2416       return 1;
2417     case BFD_RELOC_XTENSA_OP2:
2418       return 2;
2419     default:
2420       break;
2421     }
2422   return -1;
2423 }
2424
2425
2426 static void
2427 xtensa_insnbuf_set_operand (insnbuf, opcode, operand, value, file, line)
2428      xtensa_insnbuf insnbuf;
2429      xtensa_opcode opcode;
2430      xtensa_operand operand;
2431      int32 value;
2432      const char *file;
2433      unsigned int line;
2434 {
2435   xtensa_encode_result encode_result;
2436   uint32 valbuf = value;
2437
2438   encode_result = xtensa_operand_encode (operand, &valbuf);
2439
2440   switch (encode_result)
2441     {
2442     case xtensa_encode_result_ok:
2443       break;
2444     case xtensa_encode_result_align:
2445       as_bad_where ((char *) file, line,
2446                     _("operand %d not properly aligned for '%s'"),
2447                     value, xtensa_opcode_name (xtensa_default_isa, opcode));
2448       break;
2449     case xtensa_encode_result_not_in_table:
2450       as_bad_where ((char *) file, line,
2451                     _("operand %d not in immediate table for '%s'"),
2452                     value, xtensa_opcode_name (xtensa_default_isa, opcode));
2453       break;
2454     case xtensa_encode_result_too_high:
2455       as_bad_where ((char *) file, line,
2456                     _("operand %d too large for '%s'"), value,
2457                     xtensa_opcode_name (xtensa_default_isa, opcode));
2458       break;
2459     case xtensa_encode_result_too_low:
2460       as_bad_where ((char *) file, line,
2461                     _("operand %d too small for '%s'"), value,
2462                     xtensa_opcode_name (xtensa_default_isa, opcode));
2463       break;
2464     case xtensa_encode_result_not_ok:
2465       as_bad_where ((char *) file, line,
2466                     _("operand %d is invalid for '%s'"), value,
2467                     xtensa_opcode_name (xtensa_default_isa, opcode));
2468       break;
2469     default:
2470       abort ();
2471     }
2472
2473   xtensa_operand_set_field (operand, insnbuf, valbuf);
2474 }
2475
2476
2477 static uint32
2478 xtensa_insnbuf_get_operand (insnbuf, opcode, opnum)
2479      xtensa_insnbuf insnbuf;
2480      xtensa_opcode opcode;
2481      int opnum;
2482 {
2483   xtensa_operand op = xtensa_get_operand (xtensa_default_isa, opcode, opnum);
2484   return xtensa_operand_decode (op, xtensa_operand_get_field (op, insnbuf));
2485 }
2486
2487
2488 static void
2489 xtensa_insnbuf_set_immediate_field (opcode, insnbuf, value, file, line)
2490      xtensa_opcode opcode;
2491      xtensa_insnbuf insnbuf;
2492      int32 value;
2493      const char *file;
2494      unsigned int line;
2495 {
2496   xtensa_isa isa = xtensa_default_isa;
2497   int last_opnd = xtensa_num_operands (isa, opcode) - 1;
2498   xtensa_operand operand = xtensa_get_operand (isa, opcode, last_opnd);
2499   xtensa_insnbuf_set_operand (insnbuf, opcode, operand, value, file, line);
2500 }
2501
2502
2503 static bfd_boolean
2504 is_negatable_branch (insn)
2505      TInsn *insn;
2506 {
2507   xtensa_isa isa = xtensa_default_isa;
2508   int i;
2509   int num_ops = xtensa_num_operands (isa, insn->opcode);
2510
2511   for (i = 0; i < num_ops; i++)
2512     {
2513       xtensa_operand opnd = xtensa_get_operand (isa, insn->opcode, i);
2514       char *kind = xtensa_operand_kind (opnd);
2515       if (strlen (kind) == 1 && *kind == 'l')
2516         return TRUE;
2517     }
2518   return FALSE;
2519 }
2520
2521 \f
2522 /* Various Other Internal Functions.  */
2523
2524 static bfd_boolean
2525 is_unique_insn_expansion (r)
2526      TransitionRule *r;
2527 {
2528   if (!r->to_instr || r->to_instr->next != NULL)
2529     return FALSE;
2530   if (r->to_instr->typ != INSTR_INSTR)
2531     return FALSE;
2532   return TRUE;
2533 }
2534
2535
2536 static int
2537 xg_get_insn_size (insn)
2538      TInsn *insn;
2539 {
2540   assert (insn->insn_type == ITYPE_INSN);
2541   return xtensa_insn_length (xtensa_default_isa, insn->opcode);
2542 }
2543
2544
2545 static int
2546 xg_get_build_instr_size (insn)
2547      BuildInstr *insn;
2548 {
2549   assert (insn->typ == INSTR_INSTR);
2550   return xtensa_insn_length (xtensa_default_isa, insn->opcode);
2551 }
2552
2553
2554 bfd_boolean
2555 xg_is_narrow_insn (insn)
2556      TInsn *insn;
2557 {
2558   TransitionTable *table = xg_build_widen_table ();
2559   TransitionList *l;
2560   int num_match = 0;
2561   assert (insn->insn_type == ITYPE_INSN);
2562   assert (insn->opcode < table->num_opcodes);
2563
2564   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
2565     {
2566       TransitionRule *rule = l->rule;
2567
2568       if (xg_instruction_matches_rule (insn, rule)
2569           && is_unique_insn_expansion (rule))
2570         {
2571           /* It only generates one instruction... */
2572           assert (insn->insn_type == ITYPE_INSN);
2573           /* ...and it is a larger instruction.  */
2574           if (xg_get_insn_size (insn)
2575               < xg_get_build_instr_size (rule->to_instr))
2576             {
2577               num_match++;
2578               if (num_match > 1)
2579                 return FALSE;
2580             }
2581         }
2582     }
2583   return (num_match == 1);
2584 }
2585
2586
2587 bfd_boolean
2588 xg_is_single_relaxable_insn (insn)
2589      TInsn *insn;
2590 {
2591   TransitionTable *table = xg_build_widen_table ();
2592   TransitionList *l;
2593   int num_match = 0;
2594   assert (insn->insn_type == ITYPE_INSN);
2595   assert (insn->opcode < table->num_opcodes);
2596
2597   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
2598     {
2599       TransitionRule *rule = l->rule;
2600
2601       if (xg_instruction_matches_rule (insn, rule)
2602           && is_unique_insn_expansion (rule))
2603         {
2604           assert (insn->insn_type == ITYPE_INSN);
2605           /* ... and it is a larger instruction.  */
2606           if (xg_get_insn_size (insn)
2607               <= xg_get_build_instr_size (rule->to_instr))
2608             {
2609               num_match++;
2610               if (num_match > 1)
2611                 return FALSE;
2612             }
2613         }
2614     }
2615   return (num_match == 1);
2616 }
2617
2618
2619 /* Return the largest size instruction that this instruction can
2620    expand to.  Currently, in all cases, this is 3 bytes.  Of course we
2621    could just calculate this once and generate a table.  */
2622
2623 int
2624 xg_get_max_narrow_insn_size (opcode)
2625      xtensa_opcode opcode;
2626 {
2627   /* Go ahead and compute it, but it better be 3.  */
2628   TransitionTable *table = xg_build_widen_table ();
2629   TransitionList *l;
2630   int old_size = xtensa_insn_length (xtensa_default_isa, opcode);
2631   assert (opcode < table->num_opcodes);
2632
2633   /* Actually we can do better. Check to see of Only one applies.  */
2634   for (l = table->table[opcode]; l != NULL; l = l->next)
2635     {
2636       TransitionRule *rule = l->rule;
2637
2638       /* If it only generates one instruction.  */
2639       if (is_unique_insn_expansion (rule))
2640         {
2641           int new_size = xtensa_insn_length (xtensa_default_isa,
2642                                              rule->to_instr->opcode);
2643           if (new_size > old_size)
2644             {
2645               assert (new_size == 3);
2646               return 3;
2647             }
2648         }
2649     }
2650   return old_size;
2651 }
2652
2653
2654 /* Return the maximum number of bytes this opcode can expand to.  */
2655
2656 int
2657 xg_get_max_insn_widen_size (opcode)
2658      xtensa_opcode opcode;
2659 {
2660   TransitionTable *table = xg_build_widen_table ();
2661   TransitionList *l;
2662   int max_size = xtensa_insn_length (xtensa_default_isa, opcode);
2663
2664   assert (opcode < table->num_opcodes);
2665
2666   for (l = table->table[opcode]; l != NULL; l = l->next)
2667     {
2668       TransitionRule *rule = l->rule;
2669       BuildInstr *build_list;
2670       int this_size = 0;
2671
2672       if (!rule)
2673         continue;
2674       build_list = rule->to_instr;
2675       if (is_unique_insn_expansion (rule))
2676         {
2677           assert (build_list->typ == INSTR_INSTR);
2678           this_size = xg_get_max_insn_widen_size (build_list->opcode);
2679         }
2680       else
2681         for (; build_list != NULL; build_list = build_list->next)
2682           {
2683             switch (build_list->typ)
2684               {
2685               case INSTR_INSTR:
2686                 this_size += xtensa_insn_length (xtensa_default_isa,
2687                                                  build_list->opcode);
2688
2689                 break;
2690               case INSTR_LITERAL_DEF:
2691               case INSTR_LABEL_DEF:
2692               default:
2693                 break;
2694               }
2695           }
2696       if (this_size > max_size)
2697         max_size = this_size;
2698     }
2699   return max_size;
2700 }
2701
2702
2703 /* Return the maximum number of literal bytes this opcode can generate.  */
2704
2705 int
2706 xg_get_max_insn_widen_literal_size (opcode)
2707      xtensa_opcode opcode;
2708 {
2709   TransitionTable *table = xg_build_widen_table ();
2710   TransitionList *l;
2711   int max_size = 0;
2712
2713   assert (opcode < table->num_opcodes);
2714
2715   for (l = table->table[opcode]; l != NULL; l = l->next)
2716     {
2717       TransitionRule *rule = l->rule;
2718       BuildInstr *build_list;
2719       int this_size = 0;
2720
2721       if (!rule)
2722         continue;
2723       build_list = rule->to_instr;
2724       if (is_unique_insn_expansion (rule))
2725         {
2726           assert (build_list->typ == INSTR_INSTR);
2727           this_size = xg_get_max_insn_widen_literal_size (build_list->opcode);
2728         }
2729       else
2730         for (; build_list != NULL; build_list = build_list->next)
2731           {
2732             switch (build_list->typ)
2733               {
2734               case INSTR_LITERAL_DEF:
2735                 /* hard coded 4-byte literal.  */
2736                 this_size += 4;
2737                 break;
2738               case INSTR_INSTR:
2739               case INSTR_LABEL_DEF:
2740               default:
2741                 break;
2742               }
2743           }
2744       if (this_size > max_size)
2745         max_size = this_size;
2746     }
2747   return max_size;
2748 }
2749
2750
2751 bfd_boolean
2752 xg_is_relaxable_insn (insn, lateral_steps)
2753      TInsn *insn;
2754      int lateral_steps;
2755 {
2756   int steps_taken = 0;
2757   TransitionTable *table = xg_build_widen_table ();
2758   TransitionList *l;
2759
2760   assert (insn->insn_type == ITYPE_INSN);
2761   assert (insn->opcode < table->num_opcodes);
2762
2763   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
2764     {
2765       TransitionRule *rule = l->rule;
2766
2767       if (xg_instruction_matches_rule (insn, rule))
2768         {
2769           if (steps_taken == lateral_steps)
2770             return TRUE;
2771           steps_taken++;
2772         }
2773     }
2774   return FALSE;
2775 }
2776
2777
2778 static symbolS *
2779 get_special_literal_symbol ()
2780 {
2781   static symbolS *sym = NULL;
2782
2783   if (sym == NULL)
2784     sym = symbol_find_or_make ("SPECIAL_LITERAL0\001");
2785   return sym;
2786 }
2787
2788
2789 static symbolS *
2790 get_special_label_symbol ()
2791 {
2792   static symbolS *sym = NULL;
2793
2794   if (sym == NULL)
2795     sym = symbol_find_or_make ("SPECIAL_LABEL0\001");
2796   return sym;
2797 }
2798
2799
2800 /* Return true on success.  */
2801
2802 bfd_boolean
2803 xg_build_to_insn (targ, insn, bi)
2804      TInsn *targ;
2805      TInsn *insn;
2806      BuildInstr *bi;
2807 {
2808   BuildOp *op;
2809   symbolS *sym;
2810
2811   memset (targ, 0, sizeof (TInsn));
2812   switch (bi->typ)
2813     {
2814     case INSTR_INSTR:
2815       op = bi->ops;
2816       targ->opcode = bi->opcode;
2817       targ->insn_type = ITYPE_INSN;
2818       targ->is_specific_opcode = FALSE;
2819
2820       for (; op != NULL; op = op->next)
2821         {
2822           int op_num = op->op_num;
2823           int op_data = op->op_data;
2824
2825           assert (op->op_num < MAX_INSN_ARGS);
2826
2827           if (targ->ntok <= op_num)
2828             targ->ntok = op_num + 1;
2829
2830           switch (op->typ)
2831             {
2832             case OP_CONSTANT:
2833               set_expr_const (&targ->tok[op_num], op_data);
2834               break;
2835             case OP_OPERAND:
2836               assert (op_data < insn->ntok);
2837               copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
2838               break;
2839             case OP_LITERAL:
2840               sym = get_special_literal_symbol ();
2841               set_expr_symbol_offset (&targ->tok[op_num], sym, 0);
2842               break;
2843             case OP_LABEL:
2844               sym = get_special_label_symbol ();
2845               set_expr_symbol_offset (&targ->tok[op_num], sym, 0);
2846               break;
2847             default:
2848               /* currently handles:
2849                  OP_OPERAND_LOW8
2850                  OP_OPERAND_HI24S
2851                  OP_OPERAND_F32MINUS */
2852               if (xg_has_userdef_op_fn (op->typ))
2853                 {
2854                   assert (op_data < insn->ntok);
2855                   if (expr_is_const (&insn->tok[op_data]))
2856                     {
2857                       long val;
2858                       copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
2859                       val = xg_apply_userdef_op_fn (op->typ,
2860                                                     targ->tok[op_num].
2861                                                     X_add_number);
2862                       targ->tok[op_num].X_add_number = val;
2863                     }
2864                   else
2865                     return FALSE; /* We cannot use a relocation for this.  */
2866                   break;
2867                 }
2868               assert (0);
2869               break;
2870             }
2871         }
2872       break;
2873
2874     case INSTR_LITERAL_DEF:
2875       op = bi->ops;
2876       targ->opcode = XTENSA_UNDEFINED;
2877       targ->insn_type = ITYPE_LITERAL;
2878       targ->is_specific_opcode = FALSE;
2879       for (; op != NULL; op = op->next)
2880         {
2881           int op_num = op->op_num;
2882           int op_data = op->op_data;
2883           assert (op->op_num < MAX_INSN_ARGS);
2884
2885           if (targ->ntok <= op_num)
2886             targ->ntok = op_num + 1;
2887
2888           switch (op->typ)
2889             {
2890             case OP_OPERAND:
2891               assert (op_data < insn->ntok);
2892               copy_expr (&targ->tok[op_num], &insn->tok[op_data]);
2893               break;
2894             case OP_LITERAL:
2895             case OP_CONSTANT:
2896             case OP_LABEL:
2897             default:
2898               assert (0);
2899               break;
2900             }
2901         }
2902       break;
2903
2904     case INSTR_LABEL_DEF:
2905       op = bi->ops;
2906       targ->opcode = XTENSA_UNDEFINED;
2907       targ->insn_type = ITYPE_LABEL;
2908       targ->is_specific_opcode = FALSE;
2909       /* Literal with no ops. is a label?  */
2910       assert (op == NULL);
2911       break;
2912
2913     default:
2914       assert (0);
2915     }
2916
2917   return TRUE;
2918 }
2919
2920
2921 /* Return true on success.  */
2922
2923 bfd_boolean
2924 xg_build_to_stack (istack, insn, bi)
2925      IStack *istack;
2926      TInsn *insn;
2927      BuildInstr *bi;
2928 {
2929   for (; bi != NULL; bi = bi->next)
2930     {
2931       TInsn *next_insn = istack_push_space (istack);
2932
2933       if (!xg_build_to_insn (next_insn, insn, bi))
2934         return FALSE;
2935     }
2936   return TRUE;
2937 }
2938
2939
2940 /* Return true on valid expansion.  */
2941
2942 bfd_boolean
2943 xg_expand_to_stack (istack, insn, lateral_steps)
2944      IStack *istack;
2945      TInsn *insn;
2946      int lateral_steps;
2947 {
2948   int stack_size = istack->ninsn;
2949   int steps_taken = 0;
2950   TransitionTable *table = xg_build_widen_table ();
2951   TransitionList *l;
2952
2953   assert (insn->insn_type == ITYPE_INSN);
2954   assert (insn->opcode < table->num_opcodes);
2955
2956   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
2957     {
2958       TransitionRule *rule = l->rule;
2959
2960       if (xg_instruction_matches_rule (insn, rule))
2961         {
2962           if (lateral_steps == steps_taken)
2963             {
2964               int i;
2965
2966               /* This is it.  Expand the rule to the stack.  */
2967               if (!xg_build_to_stack (istack, insn, rule->to_instr))
2968                 return FALSE;
2969
2970               /* Check to see if it fits.  */
2971               for (i = stack_size; i < istack->ninsn; i++)
2972                 {
2973                   TInsn *insn = &istack->insn[i];
2974
2975                   if (insn->insn_type == ITYPE_INSN
2976                       && !tinsn_has_symbolic_operands (insn)
2977                       && !xg_immeds_fit (insn))
2978                     {
2979                       istack->ninsn = stack_size;
2980                       return FALSE;
2981                     }
2982                 }
2983               return TRUE;
2984             }
2985           steps_taken++;
2986         }
2987     }
2988   return FALSE;
2989 }
2990
2991
2992 bfd_boolean
2993 xg_expand_narrow (targ, insn)
2994      TInsn *targ;
2995      TInsn *insn;
2996 {
2997   TransitionTable *table = xg_build_widen_table ();
2998   TransitionList *l;
2999
3000   assert (insn->insn_type == ITYPE_INSN);
3001   assert (insn->opcode < table->num_opcodes);
3002
3003   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
3004     {
3005       TransitionRule *rule = l->rule;
3006       if (xg_instruction_matches_rule (insn, rule)
3007           && is_unique_insn_expansion (rule))
3008         {
3009           /* Is it a larger instruction?  */
3010           if (xg_get_insn_size (insn)
3011               <= xg_get_build_instr_size (rule->to_instr))
3012             {
3013               xg_build_to_insn (targ, insn, rule->to_instr);
3014               return FALSE;
3015             }
3016         }
3017     }
3018   return TRUE;
3019 }
3020
3021
3022 /* Assumes: All immeds are constants.  Check that all constants fit
3023    into their immeds; return false if not.  */
3024
3025 static bfd_boolean
3026 xg_immeds_fit (insn)
3027      const TInsn *insn;
3028 {
3029   int i;
3030
3031   int n = insn->ntok;
3032   assert (insn->insn_type == ITYPE_INSN);
3033   for (i = 0; i < n; ++i)
3034     {
3035       const expressionS *expr = &insn->tok[i];
3036       xtensa_operand opnd = xtensa_get_operand (xtensa_default_isa,
3037                                                 insn->opcode, i);
3038       if (!operand_is_immed (opnd))
3039         continue;
3040
3041       switch (expr->X_op)
3042         {
3043         case O_register:
3044         case O_constant:
3045           {
3046             if (xg_check_operand (expr->X_add_number, opnd))
3047               return FALSE;
3048           }
3049           break;
3050         default:
3051           /* The symbol should have a fixup associated with it.  */
3052           assert (FALSE);
3053           break;
3054         }
3055     }
3056   return TRUE;
3057 }
3058
3059
3060 /* This should only be called after we have an initial
3061    estimate of the addresses.  */
3062
3063 static bfd_boolean
3064 xg_symbolic_immeds_fit (insn, pc_seg, pc_frag, pc_offset, stretch)
3065      const TInsn *insn;
3066      segT pc_seg;
3067      fragS *pc_frag;
3068      offsetT pc_offset;
3069      long stretch;
3070 {
3071   symbolS *symbolP;
3072   offsetT target, pc, new_offset;
3073   int i;
3074   int n = insn->ntok;
3075
3076   assert (insn->insn_type == ITYPE_INSN);
3077
3078   for (i = 0; i < n; ++i)
3079     {
3080       const expressionS *expr = &insn->tok[i];
3081       xtensa_operand opnd = xtensa_get_operand (xtensa_default_isa,
3082                                                 insn->opcode, i);
3083       if (!operand_is_immed (opnd))
3084         continue;
3085
3086       switch (expr->X_op)
3087         {
3088         case O_register:
3089         case O_constant:
3090           if (xg_check_operand (expr->X_add_number, opnd))
3091             return FALSE;
3092           break;
3093
3094         case O_symbol:
3095           /* We only allow symbols for pc-relative stuff.
3096              If pc_frag == 0, then we don't have frag locations yet.  */
3097           if (pc_frag == 0)
3098             return FALSE;
3099
3100           /* If it is PC-relative and the symbol is in the same segment as
3101              the PC.... */
3102           if (!xtensa_operand_isPCRelative (opnd)
3103               || S_GET_SEGMENT (expr->X_add_symbol) != pc_seg)
3104             return FALSE;
3105
3106           symbolP = expr->X_add_symbol;
3107           target = S_GET_VALUE (symbolP) + expr->X_add_number;
3108           pc = pc_frag->fr_address + pc_offset;
3109
3110           /* If frag has yet to be reached on this pass, assume it
3111              will move by STRETCH just as we did.  If this is not so,
3112              it will be because some frag between grows, and that will
3113              force another pass.  Beware zero-length frags.  There
3114              should be a faster way to do this.  */
3115
3116           if (stretch && is_dnrange (pc_frag, symbolP, stretch))
3117             target += stretch;
3118
3119           new_offset = xtensa_operand_do_reloc (opnd, target, pc);
3120           if (xg_check_operand (new_offset, opnd))
3121             return FALSE;
3122           break;
3123
3124         default:
3125           /* The symbol should have a fixup associated with it.  */
3126           return FALSE;
3127         }
3128     }
3129
3130   return TRUE;
3131 }
3132
3133
3134 /* This will check to see if the value can be converted into the
3135    operand type.  It will return true if it does not fit.  */
3136
3137 static bfd_boolean
3138 xg_check_operand (value, operand)
3139      int32 value;
3140      xtensa_operand operand;
3141 {
3142   uint32 valbuf = value;
3143   return (xtensa_operand_encode (operand, &valbuf) != xtensa_encode_result_ok);
3144 }
3145
3146
3147 /* Check if a symbol is pointing to somewhere after
3148    the start frag, given that the segment has stretched 
3149    by stretch during relaxation.
3150
3151    This is more complicated than it might appear at first blush
3152    because of the stretching that goes on. Here is how the check
3153    works:
3154
3155    If the symbol and the frag are in the same segment, then
3156    the symbol could be down range. Note that this function 
3157    assumes that start_frag is in now_seg.
3158
3159    If the symbol is pointing to a frag with an address greater than 
3160    than the start_frag's address, then it _could_ be down range. 
3161
3162    The problem comes because target_frag may or may not have had
3163    stretch bytes added to its address already, depending on if it is 
3164    before or after start frag. (And if we knew that, then we wouldn't
3165    need this function.) start_frag has definitely already had stretch
3166    bytes added to its address.
3167    
3168    If target_frag's address hasn't been adjusted yet, then to 
3169    determine if it comes after start_frag, we need to subtract
3170    stretch from start_frag's address.
3171
3172    If target_frag's address has been adjusted, then it might have
3173    been adjusted such that it comes after start_frag's address minus
3174    stretch bytes.
3175
3176    So, in that case, we scan for it down stream to within 
3177    stretch bytes. We could search to the end of the fr_chain, but
3178    that ends up taking too much time (over a minute on some gnu 
3179    tests).  */
3180
3181 int
3182 is_dnrange (start_frag, sym, stretch)
3183      fragS *start_frag;
3184      symbolS *sym;
3185      long stretch;
3186 {
3187   if (S_GET_SEGMENT (sym) == now_seg)
3188     {
3189       fragS *cur_frag = symbol_get_frag (sym);
3190
3191       if (cur_frag->fr_address >= start_frag->fr_address - stretch)
3192         {
3193           int distance = stretch;
3194
3195           while (cur_frag && distance >= 0) 
3196             {
3197               distance -= cur_frag->fr_fix;
3198               if (cur_frag == start_frag)
3199                 return 0;
3200               cur_frag = cur_frag->fr_next;
3201             }
3202           return 1;
3203         }
3204     }
3205   return 0;
3206 }
3207
3208 \f
3209 /* Relax the assembly instruction at least "min_steps".
3210    Return the number of steps taken.  */
3211
3212 int
3213 xg_assembly_relax (istack, insn, pc_seg, pc_frag, pc_offset, min_steps,
3214                    stretch)
3215      IStack *istack;
3216      TInsn *insn;
3217      segT pc_seg;
3218      fragS *pc_frag;            /* If pc_frag == 0, then no pc-relative.  */
3219      offsetT pc_offset;         /* Offset in fragment.  */
3220      int min_steps;             /* Minimum number of conversion steps.  */
3221      long stretch;              /* Number of bytes stretched so far.  */
3222 {
3223   int steps_taken = 0;
3224
3225   /* assert (has no symbolic operands)
3226      Some of its immeds don't fit.
3227      Try to build a relaxed version.
3228      This may go through a couple of stages
3229      of single instruction transformations before
3230      we get there.  */
3231
3232   TInsn single_target;
3233   TInsn current_insn;
3234   int lateral_steps = 0;
3235   int istack_size = istack->ninsn;
3236
3237   if (xg_symbolic_immeds_fit (insn, pc_seg, pc_frag, pc_offset, stretch)
3238       && steps_taken >= min_steps)
3239     {
3240       istack_push (istack, insn);
3241       return steps_taken;
3242     }
3243   tinsn_copy (&current_insn, insn);
3244
3245   /* Walk through all of the single instruction expansions. */
3246   while (xg_is_single_relaxable_insn (&current_insn))
3247     {
3248       int error_val = xg_expand_narrow (&single_target, &current_insn);
3249
3250       assert (!error_val);
3251
3252       if (xg_symbolic_immeds_fit (&single_target, pc_seg, pc_frag, pc_offset,
3253                                   stretch))
3254         {
3255           steps_taken++;
3256           if (steps_taken >= min_steps)
3257             {
3258               istack_push (istack, &single_target);
3259               return steps_taken;
3260             }
3261         }
3262       tinsn_copy (&current_insn, &single_target);
3263     }
3264
3265   /* Now check for a multi-instruction expansion.  */
3266   while (xg_is_relaxable_insn (&current_insn, lateral_steps))
3267     {
3268       if (xg_symbolic_immeds_fit (&current_insn, pc_seg, pc_frag, pc_offset,
3269                                   stretch))
3270         {
3271           if (steps_taken >= min_steps)
3272             {
3273               istack_push (istack, &current_insn);
3274               return steps_taken;
3275             }
3276         }
3277       steps_taken++;
3278       if (xg_expand_to_stack (istack, &current_insn, lateral_steps))
3279         {
3280           if (steps_taken >= min_steps)
3281             return steps_taken;
3282         }
3283       lateral_steps++;
3284       istack->ninsn = istack_size;
3285     }
3286
3287   /* It's not going to work -- use the original.  */
3288   istack_push (istack, insn);
3289   return steps_taken;
3290 }
3291
3292
3293 static void
3294 xg_force_frag_space (size)
3295      int size;
3296 {
3297   /* This may have the side effect of creating a new fragment for the
3298      space to go into.  I just do not like the name of the "frag"
3299      functions.  */
3300   frag_grow (size);
3301 }
3302
3303
3304 void
3305 xg_finish_frag (last_insn, state, max_growth, is_insn)
3306      char *last_insn;
3307      enum xtensa_relax_statesE state;
3308      int max_growth;
3309      bfd_boolean is_insn;
3310 {
3311   /* Finish off this fragment so that it has at LEAST the desired
3312      max_growth.  If it doesn't fit in this fragment, close this one
3313      and start a new one.  In either case, return a pointer to the
3314      beginning of the growth area.  */
3315
3316   fragS *old_frag;
3317   xg_force_frag_space (max_growth);
3318
3319   old_frag = frag_now;
3320
3321   frag_now->fr_opcode = last_insn;
3322   if (is_insn)
3323     frag_now->tc_frag_data.is_insn = TRUE;
3324
3325   frag_var (rs_machine_dependent, max_growth, max_growth,
3326             state, frag_now->fr_symbol, frag_now->fr_offset, last_insn);
3327
3328   /* Just to make sure that we did not split it up.  */
3329   assert (old_frag->fr_next == frag_now);
3330 }
3331
3332
3333 static bfd_boolean
3334 is_branch_jmp_to_next (insn, fragP)
3335      TInsn *insn;
3336      fragS *fragP;
3337 {
3338   xtensa_isa isa = xtensa_default_isa;
3339   int i;
3340   int num_ops = xtensa_num_operands (isa, insn->opcode);
3341   int target_op = -1;
3342   symbolS *sym;
3343   fragS *target_frag;
3344
3345   if (is_loop_opcode (insn->opcode))
3346     return FALSE;
3347
3348   for (i = 0; i < num_ops; i++)
3349     {
3350       xtensa_operand opnd = xtensa_get_operand (isa, insn->opcode, i);
3351       char *kind = xtensa_operand_kind (opnd);
3352       if (strlen (kind) == 1 && *kind == 'l')
3353         {
3354           target_op = i;
3355           break;
3356         }
3357     }
3358   if (target_op == -1)
3359     return FALSE;
3360
3361   if (insn->ntok <= target_op)
3362     return FALSE;
3363
3364   if (insn->tok[target_op].X_op != O_symbol)
3365     return FALSE;
3366
3367   sym = insn->tok[target_op].X_add_symbol;
3368   if (sym == NULL)
3369     return FALSE;
3370
3371   if (insn->tok[target_op].X_add_number != 0)
3372     return FALSE;
3373
3374   target_frag = symbol_get_frag (sym);
3375   if (target_frag == NULL)
3376     return FALSE;
3377
3378   if (is_next_frag_target (fragP->fr_next, target_frag) 
3379       && S_GET_VALUE (sym) == target_frag->fr_address)
3380     return TRUE;
3381
3382   return FALSE;
3383 }
3384
3385
3386 static void
3387 xg_add_branch_and_loop_targets (insn)
3388      TInsn *insn;
3389 {
3390   xtensa_isa isa = xtensa_default_isa;
3391   int num_ops = xtensa_num_operands (isa, insn->opcode);
3392
3393   if (is_loop_opcode (insn->opcode))
3394     {
3395       int i = 1;
3396       xtensa_operand opnd = xtensa_get_operand (isa, insn->opcode, i);
3397       char *kind = xtensa_operand_kind (opnd);
3398       if (strlen (kind) == 1 && *kind == 'l')
3399         if (insn->tok[i].X_op == O_symbol)
3400           symbol_get_tc (insn->tok[i].X_add_symbol)->is_loop_target = TRUE;
3401       return;
3402     }
3403
3404   /* Currently, we do not add branch targets.  This is an optimization
3405      for later that tries to align only branch targets, not just any
3406      label in a text section.  */
3407
3408   if (align_only_targets)
3409     {
3410       int i;
3411
3412       for (i = 0; i < insn->ntok && i < num_ops; i++)
3413         {
3414           xtensa_operand opnd = xtensa_get_operand (isa, insn->opcode, i);
3415           char *kind = xtensa_operand_kind (opnd);
3416           if (strlen (kind) == 1 && *kind == 'l'
3417               && insn->tok[i].X_op == O_symbol)
3418             {
3419               symbolS *sym = insn->tok[i].X_add_symbol;
3420               symbol_get_tc (sym)->is_branch_target = TRUE;
3421               if (S_IS_DEFINED (sym))
3422                 symbol_get_frag (sym)->tc_frag_data.is_branch_target = TRUE;
3423             }
3424         }
3425     }
3426 }
3427
3428
3429 /* Return the transition rule that matches or NULL if none matches.  */
3430
3431 bfd_boolean
3432 xg_instruction_matches_rule (insn, rule)
3433      TInsn *insn;
3434      TransitionRule *rule;
3435 {
3436   PreconditionList *condition_l;
3437
3438   if (rule->opcode != insn->opcode)
3439     return FALSE;
3440
3441   for (condition_l = rule->conditions;
3442        condition_l != NULL;
3443        condition_l = condition_l->next)
3444     {
3445       expressionS *exp1;
3446       expressionS *exp2;
3447       Precondition *cond = condition_l->precond;
3448
3449       switch (cond->typ)
3450         {
3451         case OP_CONSTANT:
3452           /* The expression must be the constant.  */
3453           assert (cond->op_num < insn->ntok);
3454           exp1 = &insn->tok[cond->op_num];
3455           if (!expr_is_const (exp1))
3456             return FALSE;
3457           switch (cond->cmp)
3458             {
3459             case OP_EQUAL:
3460               if (get_expr_const (exp1) != cond->op_data)
3461                 return FALSE;
3462               break;
3463             case OP_NOTEQUAL:
3464               if (get_expr_const (exp1) == cond->op_data)
3465                 return FALSE;
3466               break;
3467             }
3468           break;
3469
3470         case OP_OPERAND:
3471           assert (cond->op_num < insn->ntok);
3472           assert (cond->op_data < insn->ntok);
3473           exp1 = &insn->tok[cond->op_num];
3474           exp2 = &insn->tok[cond->op_data];
3475
3476           switch (cond->cmp)
3477             {
3478             case OP_EQUAL:
3479               if (!expr_is_equal (exp1, exp2))
3480                 return FALSE;
3481               break;
3482             case OP_NOTEQUAL:
3483               if (expr_is_equal (exp1, exp2))
3484                 return FALSE;
3485               break;
3486             }
3487           break;
3488
3489         case OP_LITERAL:
3490         case OP_LABEL:
3491         default:
3492           return FALSE;
3493         }
3494     }
3495   return TRUE;
3496 }
3497
3498
3499 TransitionRule *
3500 xg_instruction_match (insn)
3501      TInsn *insn;
3502 {
3503   TransitionTable *table = xg_build_simplify_table ();
3504   TransitionList *l;
3505   assert (insn->opcode < table->num_opcodes);
3506
3507   /* Walk through all of the possible transitions.  */
3508   for (l = table->table[insn->opcode]; l != NULL; l = l->next)
3509     {
3510       TransitionRule *rule = l->rule;
3511       if (xg_instruction_matches_rule (insn, rule))
3512         return rule;
3513     }
3514   return NULL;
3515 }
3516
3517
3518 /* Return false if no error.  */
3519
3520 bfd_boolean
3521 xg_build_token_insn (instr_spec, old_insn, new_insn)
3522      BuildInstr *instr_spec;
3523      TInsn *old_insn;
3524      TInsn *new_insn;
3525 {
3526   int num_ops = 0;
3527   BuildOp *b_op;
3528
3529   switch (instr_spec->typ)
3530     {
3531     case INSTR_INSTR:
3532       new_insn->insn_type = ITYPE_INSN;
3533       new_insn->opcode = instr_spec->opcode;
3534       new_insn->is_specific_opcode = FALSE;
3535       break;
3536     case INSTR_LITERAL_DEF:
3537       new_insn->insn_type = ITYPE_LITERAL;
3538       new_insn->opcode = XTENSA_UNDEFINED;
3539       new_insn->is_specific_opcode = FALSE;
3540       break;
3541     case INSTR_LABEL_DEF:
3542       as_bad (_("INSTR_LABEL_DEF not supported yet"));
3543       break;
3544     }
3545
3546   for (b_op = instr_spec->ops; b_op != NULL; b_op = b_op->next)
3547     {
3548       expressionS *exp;
3549       const expressionS *src_exp;
3550
3551       num_ops++;
3552       switch (b_op->typ)
3553         {
3554         case OP_CONSTANT:
3555           /* The expression must be the constant.  */
3556           assert (b_op->op_num < MAX_INSN_ARGS);
3557           exp = &new_insn->tok[b_op->op_num];
3558           set_expr_const (exp, b_op->op_data);
3559           break;
3560
3561         case OP_OPERAND:
3562           assert (b_op->op_num < MAX_INSN_ARGS);
3563           assert (b_op->op_data < (unsigned) old_insn->ntok);
3564           src_exp = &old_insn->tok[b_op->op_data];
3565           exp = &new_insn->tok[b_op->op_num];
3566           copy_expr (exp, src_exp);
3567           break;
3568
3569         case OP_LITERAL:
3570         case OP_LABEL:
3571           as_bad (_("can't handle generation of literal/labels yet"));
3572           assert (0);
3573
3574         default:
3575           as_bad (_("can't handle undefined OP TYPE"));
3576           assert (0);
3577         }
3578     }
3579
3580   new_insn->ntok = num_ops;
3581   return FALSE;
3582 }
3583
3584
3585 /* Return true if it was simplified.  */
3586
3587 bfd_boolean
3588 xg_simplify_insn (old_insn, new_insn)
3589      TInsn *old_insn;
3590      TInsn *new_insn;
3591 {
3592   TransitionRule *rule = xg_instruction_match (old_insn);
3593   BuildInstr *insn_spec;
3594   if (rule == NULL)
3595     return FALSE;
3596
3597   insn_spec = rule->to_instr;
3598   /* There should only be one.  */
3599   assert (insn_spec != NULL);
3600   assert (insn_spec->next == NULL);
3601   if (insn_spec->next != NULL)
3602     return FALSE;
3603
3604   xg_build_token_insn (insn_spec, old_insn, new_insn);
3605
3606   return TRUE;
3607 }
3608
3609
3610 /* xg_expand_assembly_insn: (1) Simplify the instruction, i.e., l32i ->
3611    l32i.n. (2) Check the number of operands.  (3) Place the instruction
3612    tokens into the stack or if we can relax it at assembly time, place
3613    multiple instructions/literals onto the stack.  Return false if no
3614    error.  */
3615
3616 static bfd_boolean
3617 xg_expand_assembly_insn (istack, orig_insn)
3618      IStack *istack;
3619      TInsn *orig_insn;
3620 {
3621   int noperands;
3622   TInsn new_insn;
3623   memset (&new_insn, 0, sizeof (TInsn));
3624
3625   /* On return, we will be using the "use_tokens" with "use_ntok".
3626      This will reduce things like addi to addi.n.  */
3627   if (code_density_available () && !orig_insn->is_specific_opcode)
3628     {
3629       if (xg_simplify_insn (orig_insn, &new_insn))
3630         orig_insn = &new_insn;
3631     }
3632
3633   noperands = xtensa_num_operands (xtensa_default_isa, orig_insn->opcode);
3634   if (orig_insn->ntok < noperands)
3635     {
3636       as_bad (_("found %d operands for '%s':  Expected %d"),
3637               orig_insn->ntok,
3638               xtensa_opcode_name (xtensa_default_isa, orig_insn->opcode),
3639               noperands);
3640       return TRUE;
3641     }
3642   if (orig_insn->ntok > noperands)
3643     as_warn (_("found too many (%d) operands for '%s':  Expected %d"),
3644              orig_insn->ntok,
3645              xtensa_opcode_name (xtensa_default_isa, orig_insn->opcode),
3646              noperands);
3647
3648   /* If there are not enough operands, we will assert above. If there
3649      are too many, just cut out the extras here.  */
3650
3651   orig_insn->ntok = noperands;
3652
3653   /* Cases: 
3654
3655      Instructions with all constant immeds:
3656      Assemble them and relax the instruction if possible.
3657      Give error if not possible; no fixup needed.
3658
3659      Instructions with symbolic immeds:
3660      Assemble them with a Fix up (that may cause instruction expansion).
3661      Also close out the fragment if the fixup may cause instruction expansion. 
3662      
3663      There are some other special cases where we need alignment.
3664      1) before certain instructions with required alignment (OPCODE_ALIGN)
3665      2) before labels that have jumps (LABEL_ALIGN)
3666      3) after call instructions (RETURN_ALIGN)
3667         Multiple of these may be possible on the same fragment. 
3668         If so, make sure to satisfy the required alignment. 
3669         Then try to get the desired alignment.  */
3670
3671   if (tinsn_has_invalid_symbolic_operands (orig_insn))
3672     return TRUE;
3673
3674   if (orig_insn->is_specific_opcode || !can_relax ())
3675     {
3676       istack_push (istack, orig_insn);
3677       return FALSE;
3678     }
3679
3680   if (tinsn_has_symbolic_operands (orig_insn))
3681     {
3682       if (tinsn_has_complex_operands (orig_insn))
3683         xg_assembly_relax (istack, orig_insn, 0, 0, 0, 0, 0);
3684       else
3685         istack_push (istack, orig_insn);
3686     }
3687   else
3688     {
3689       if (xg_immeds_fit (orig_insn))
3690         istack_push (istack, orig_insn);
3691       else
3692         xg_assembly_relax (istack, orig_insn, 0, 0, 0, 0, 0);
3693     }
3694
3695 #if 0
3696   for (i = 0; i < istack->ninsn; i++)
3697     {
3698       if (xg_simplify_insn (&new_insn, &istack->insn[i]))
3699         istack->insn[i] = new_insn;
3700     }
3701 #endif
3702
3703   return FALSE;
3704 }
3705
3706
3707 /* Currently all literals that are generated here are 32-bit L32R targets.  */
3708
3709 symbolS *
3710 xg_assemble_literal (insn)
3711      /* const */ TInsn *insn;
3712 {
3713   emit_state state;
3714   symbolS *lit_sym = NULL;
3715
3716   /* size = 4 for L32R.  It could easily be larger when we move to
3717      larger constants.  Add a parameter later.  */
3718   offsetT litsize = 4;
3719   offsetT litalign = 2;         /* 2^2 = 4 */
3720   expressionS saved_loc;
3721   set_expr_symbol_offset (&saved_loc, frag_now->fr_symbol, frag_now_fix ());
3722
3723   assert (insn->insn_type == ITYPE_LITERAL);
3724   assert (insn->ntok == 1);     /* must be only one token here */
3725
3726   xtensa_switch_to_literal_fragment (&state);
3727
3728   /* Force a 4-byte align here.  Note that this opens a new frag, so all
3729      literals done with this function have a frag to themselves.  That's
3730      important for the way text section literals work.  */
3731   frag_align (litalign, 0, 0);
3732
3733   emit_expr (&insn->tok[0], litsize);
3734
3735   assert (frag_now->tc_frag_data.literal_frag == NULL);
3736   frag_now->tc_frag_data.literal_frag = get_literal_pool_location (now_seg);
3737   frag_now->fr_symbol = xtensa_create_literal_symbol (now_seg, frag_now);
3738   lit_sym = frag_now->fr_symbol;
3739   frag_now->tc_frag_data.is_literal = TRUE;
3740
3741   /* Go back.  */
3742   xtensa_restore_emit_state (&state);
3743   return lit_sym;
3744 }
3745
3746
3747 static void
3748 xg_assemble_literal_space (size)
3749      /* const */ int size;
3750 {
3751   emit_state state;
3752   /* We might have to do something about this alignment.  It only  
3753      takes effect if something is placed here.  */
3754   offsetT litalign = 2;         /* 2^2 = 4 */
3755   fragS *lit_saved_frag;
3756
3757   expressionS saved_loc;
3758
3759   assert (size % 4 == 0);
3760   set_expr_symbol_offset (&saved_loc, frag_now->fr_symbol, frag_now_fix ());
3761
3762   xtensa_switch_to_literal_fragment (&state);
3763
3764   /* Force a 4-byte align here.  */
3765   frag_align (litalign, 0, 0);
3766
3767   xg_force_frag_space (size);
3768
3769   lit_saved_frag = frag_now;
3770   frag_now->tc_frag_data.literal_frag = get_literal_pool_location (now_seg);
3771   frag_now->tc_frag_data.is_literal = TRUE;
3772   frag_now->fr_symbol = xtensa_create_literal_symbol (now_seg, frag_now);
3773   xg_finish_frag (0, RELAX_LITERAL, size, FALSE);
3774
3775   /* Go back.  */
3776   xtensa_restore_emit_state (&state);
3777   frag_now->tc_frag_data.literal_frag = lit_saved_frag;
3778 }
3779
3780
3781 symbolS *
3782 xtensa_create_literal_symbol (sec, frag)
3783      segT sec;
3784      fragS *frag;
3785 {
3786   static int lit_num = 0;
3787   static char name[256];
3788   symbolS *symbolP;
3789
3790   sprintf (name, ".L_lit_sym%d", lit_num);
3791
3792   /* Create a local symbol.  If it is in a linkonce section, we have to
3793      be careful to make sure that if it is used in a relocation that the
3794      symbol will be in the output file.  */
3795   if (get_is_linkonce_section (stdoutput, sec))
3796     {
3797       symbolP = symbol_new (name, sec, 0, frag);
3798       S_CLEAR_EXTERNAL (symbolP);
3799       /* symbolP->local = 1; */
3800     }
3801   else
3802     symbolP = symbol_new (name, sec, 0, frag);
3803
3804   xtensa_add_literal_sym (symbolP);
3805
3806   frag->tc_frag_data.is_literal = TRUE;
3807   lit_num++;
3808   return symbolP;
3809 }
3810
3811
3812 static void
3813 xtensa_add_literal_sym (sym)
3814      symbolS *sym;
3815 {
3816   sym_list *l;
3817
3818   l = (sym_list *) xmalloc (sizeof (sym_list));
3819   l->sym = sym;
3820   l->next = literal_syms;
3821   literal_syms = l;
3822 }
3823
3824
3825 static void
3826 xtensa_add_insn_label (sym)
3827      symbolS *sym;
3828 {
3829   sym_list *l;
3830
3831   if (!free_insn_labels)
3832     l = (sym_list *) xmalloc (sizeof (sym_list));
3833   else
3834     {
3835       l = free_insn_labels;
3836       free_insn_labels = l->next;
3837     }
3838
3839   l->sym = sym;
3840   l->next = insn_labels;
3841   insn_labels = l;
3842 }
3843
3844
3845 static void
3846 xtensa_clear_insn_labels (void)
3847 {
3848   sym_list **pl;
3849
3850   for (pl = &free_insn_labels; *pl != NULL; pl = &(*pl)->next)
3851     ;
3852   *pl = insn_labels;
3853   insn_labels = NULL;
3854 }
3855
3856
3857 /* Return true if the section flags are marked linkonce
3858    or the name is .gnu.linkonce*.  */
3859
3860 bfd_boolean
3861 get_is_linkonce_section (abfd, sec)
3862      bfd *abfd ATTRIBUTE_UNUSED;
3863      segT sec;
3864 {
3865   flagword flags, link_once_flags;
3866
3867   flags = bfd_get_section_flags (abfd, sec);
3868   link_once_flags = (flags & SEC_LINK_ONCE);
3869
3870   /* Flags might not be set yet.  */
3871   if (!link_once_flags)
3872     {
3873       static size_t len = sizeof ".gnu.linkonce.t.";
3874
3875       if (strncmp (segment_name (sec), ".gnu.linkonce.t.", len - 1) == 0)
3876         link_once_flags = SEC_LINK_ONCE;
3877     }
3878   return (link_once_flags != 0);
3879 }
3880
3881
3882 /* Emit an instruction to the current fragment.  If record_fix is true,
3883    then this instruction will not change and we can go ahead and record
3884    the fixup.  If record_fix is false, then the instruction may change
3885    and we are going to close out this fragment.  Go ahead and set the
3886    fr_symbol and fr_offset instead of adding a fixup.  */
3887
3888 static bfd_boolean
3889 xg_emit_insn (t_insn, record_fix)
3890      TInsn *t_insn;
3891      bfd_boolean record_fix;
3892 {
3893   bfd_boolean ok = TRUE;
3894   xtensa_isa isa = xtensa_default_isa;
3895   xtensa_opcode opcode = t_insn->opcode;
3896   bfd_boolean has_fixup = FALSE;
3897   int noperands;
3898   int i, byte_count;
3899   fragS *oldfrag;
3900   size_t old_size;
3901   char *f;
3902   static xtensa_insnbuf insnbuf = NULL;
3903   
3904   /* Use a static pointer to the insn buffer so we don't have to call 
3905      malloc each time through.  */
3906   if (!insnbuf)
3907     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
3908
3909   has_fixup = tinsn_to_insnbuf (t_insn, insnbuf);
3910
3911   noperands = xtensa_num_operands (isa, opcode);
3912   assert (noperands == t_insn->ntok);
3913
3914   byte_count = xtensa_insn_length (isa, opcode);
3915   oldfrag = frag_now;
3916   /* This should NEVER cause us to jump into a new frag;
3917      we've already reserved space.  */
3918   old_size = frag_now_fix ();
3919   f = frag_more (byte_count);
3920   assert (oldfrag == frag_now);
3921
3922   /* This needs to generate a record that lists the parts that are
3923      instructions.  */
3924   if (!frag_now->tc_frag_data.is_insn)
3925     {
3926       /* If we are at the beginning of a fragment, switch this
3927          fragment to an instruction fragment.  */
3928       if (now_seg != absolute_section && old_size != 0)
3929         as_warn (_("instruction fragment may contain data"));
3930       frag_now->tc_frag_data.is_insn = TRUE;
3931     }
3932
3933   xtensa_insnbuf_to_chars (isa, insnbuf, f);
3934
3935   dwarf2_emit_insn (byte_count);
3936
3937   /* Now spit out the opcode fixup.... */
3938   if (!has_fixup)
3939     return !ok;
3940
3941   for (i = 0; i < noperands; ++i)
3942     {
3943       expressionS *expr = &t_insn->tok[i];
3944       switch (expr->X_op)
3945         {
3946         case O_symbol:
3947           if (get_relaxable_immed (opcode) == i)
3948             {
3949               if (record_fix)
3950                 {
3951                   if (!xg_add_opcode_fix (opcode, i, expr, frag_now,
3952                                           f - frag_now->fr_literal))
3953                     ok = FALSE;
3954                 }
3955               else
3956                 {
3957                   /* Write it to the fr_offset, fr_symbol.  */
3958                   frag_now->fr_symbol = expr->X_add_symbol;
3959                   frag_now->fr_offset = expr->X_add_number;
3960                 }
3961             }
3962           else
3963             {
3964               as_bad (_("invalid operand %d on '%s'"),
3965                       i, xtensa_opcode_name (isa, opcode));
3966               ok = FALSE;
3967             }
3968           break;
3969
3970         case O_constant:
3971         case O_register:
3972           break;
3973
3974         default:
3975           as_bad (_("invalid expression for operand %d on '%s'"),
3976                   i, xtensa_opcode_name (isa, opcode));
3977           ok = FALSE;
3978           break;
3979         }
3980     }
3981
3982   return !ok;
3983 }
3984
3985
3986 static bfd_boolean
3987 xg_emit_insn_to_buf (t_insn, buf, fragP, offset, build_fix)
3988      TInsn *t_insn;
3989      char *buf;
3990      fragS *fragP;
3991      offsetT offset;
3992      bfd_boolean build_fix;
3993 {
3994   static xtensa_insnbuf insnbuf = NULL;
3995   bfd_boolean has_symbolic_immed = FALSE;
3996   bfd_boolean ok = TRUE;
3997   if (!insnbuf)
3998     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
3999
4000   has_symbolic_immed = tinsn_to_insnbuf (t_insn, insnbuf);
4001   if (has_symbolic_immed && build_fix)
4002     {
4003       /* Add a fixup.  */
4004       int opnum = get_relaxable_immed (t_insn->opcode);
4005       expressionS *exp = &t_insn->tok[opnum];
4006
4007       if (!xg_add_opcode_fix (t_insn->opcode, 
4008                               opnum, exp, fragP, offset))
4009         ok = FALSE;
4010     }
4011   fragP->tc_frag_data.is_insn = TRUE;
4012   xtensa_insnbuf_to_chars (xtensa_default_isa, insnbuf, buf);
4013   return ok;
4014 }
4015
4016
4017 /* Put in a fixup record based on the opcode.
4018    Return true on success.  */
4019
4020 bfd_boolean
4021 xg_add_opcode_fix (opcode, opnum, expr, fragP, offset)
4022      xtensa_opcode opcode;
4023      int opnum;
4024      expressionS *expr;
4025      fragS *fragP;
4026      offsetT offset;
4027
4028   bfd_reloc_code_real_type reloc; 
4029   reloc_howto_type *howto; 
4030   int insn_length;
4031   fixS *the_fix;
4032
4033   reloc = opnum_to_reloc (opnum);
4034   if (reloc == BFD_RELOC_NONE)
4035     {
4036       as_bad (_("invalid relocation operand %i on '%s'"),
4037               opnum, xtensa_opcode_name (xtensa_default_isa, opcode));
4038       return FALSE;
4039     }
4040
4041   howto = bfd_reloc_type_lookup (stdoutput, reloc);
4042
4043   if (!howto)
4044     {
4045       as_bad (_("undefined symbol for opcode \"%s\"."),
4046               xtensa_opcode_name (xtensa_default_isa, opcode));
4047       return FALSE;
4048     }
4049
4050   insn_length = xtensa_insn_length (xtensa_default_isa, opcode);
4051   the_fix = fix_new_exp (fragP, offset, insn_length, expr,
4052                          howto->pc_relative, reloc);
4053
4054   if (expr->X_add_symbol && 
4055       (S_IS_EXTERNAL (expr->X_add_symbol) || S_IS_WEAK (expr->X_add_symbol)))
4056     the_fix->fx_plt = TRUE;
4057   
4058   return TRUE;
4059 }
4060
4061
4062 void
4063 xg_resolve_literals (insn, lit_sym)
4064      TInsn *insn;
4065      symbolS *lit_sym;
4066 {
4067   symbolS *sym = get_special_literal_symbol ();
4068   int i;
4069   if (lit_sym == 0)
4070     return;
4071   assert (insn->insn_type == ITYPE_INSN);
4072   for (i = 0; i < insn->ntok; i++)
4073     if (insn->tok[i].X_add_symbol == sym)
4074       insn->tok[i].X_add_symbol = lit_sym;
4075
4076 }
4077
4078
4079 void
4080 xg_resolve_labels (insn, label_sym)
4081      TInsn *insn;
4082      symbolS *label_sym;
4083 {
4084   symbolS *sym = get_special_label_symbol ();
4085   int i;
4086   /* assert(!insn->is_literal); */
4087   for (i = 0; i < insn->ntok; i++)
4088     if (insn->tok[i].X_add_symbol == sym)
4089       insn->tok[i].X_add_symbol = label_sym;
4090
4091 }
4092
4093
4094 static void
4095 xg_assemble_tokens (insn)
4096      /*const */ TInsn *insn;
4097 {
4098   /* By the time we get here, there's not too much left to do. 
4099      1) Check our assumptions. 
4100      2) Check if the current instruction is "narrow". 
4101         If so, then finish the frag, create another one.
4102         We could also go back to change some previous
4103         "narrow" frags into no-change ones if we have more than
4104         MAX_NARROW_ALIGNMENT of them without alignment restrictions
4105         between them.
4106
4107      Cases:
4108         1) It has constant operands and doesn't fit.
4109            Go ahead and assemble it so it will fail.
4110         2) It has constant operands that fit.
4111            If narrow and !is_specific_opcode,
4112               assemble it and put in a relocation
4113            else
4114               assemble it.
4115         3) It has a symbolic immediate operand
4116            a) Find the worst-case relaxation required
4117            b) Find the worst-case literal pool space required.
4118               Insert appropriate alignment & space in the literal.
4119               Assemble it.
4120               Add the relocation.  */
4121
4122   assert (insn->insn_type == ITYPE_INSN);
4123
4124   if (!tinsn_has_symbolic_operands (insn))
4125     {
4126       if (xg_is_narrow_insn (insn) && !insn->is_specific_opcode)
4127         {
4128           /* assemble it but add max required space */
4129           int max_size = xg_get_max_narrow_insn_size (insn->opcode);
4130           int min_size = xg_get_insn_size (insn);
4131           char *last_insn;
4132           assert (max_size == 3);
4133           /* make sure we have enough space to widen it */
4134           xg_force_frag_space (max_size);
4135           /* Output the instruction.  It may cause an error if some 
4136              operands do not fit.  */
4137           last_insn = frag_more (0);
4138           if (xg_emit_insn (insn, TRUE))
4139             as_warn (_("instruction with constant operands does not fit"));
4140           xg_finish_frag (last_insn, RELAX_NARROW, max_size - min_size, TRUE);
4141         }
4142       else
4143         {
4144           /* Assemble it.  No relocation needed.  */
4145           int max_size = xg_get_insn_size (insn);
4146           xg_force_frag_space (max_size);
4147           if (xg_emit_insn (insn, FALSE))
4148             as_warn (_("instruction with constant operands does not "
4149                        "fit without widening"));
4150           /* frag_more (max_size); */
4151
4152           /* Special case for jx.  If the jx is the next to last
4153              instruction in a loop, we will add a NOP after it.  This
4154              avoids a hardware issue that could occur if the jx jumped
4155              to the next instruction.  */
4156           if (software_avoid_b_j_loop_end
4157               && is_jx_opcode (insn->opcode))
4158             {
4159               maybe_has_b_j_loop_end = TRUE;
4160               /* add 2 of these */
4161               frag_now->tc_frag_data.is_insn = TRUE;
4162               frag_var (rs_machine_dependent, 4, 4,
4163                         RELAX_ADD_NOP_IF_PRE_LOOP_END,
4164                         frag_now->fr_symbol, frag_now->fr_offset, NULL);
4165             }
4166         }
4167     }
4168   else
4169     {
4170       /* Need to assemble it with space for the relocation.  */
4171       if (!insn->is_specific_opcode)
4172         {
4173           /* Assemble it but add max required space.  */
4174           char *last_insn;
4175           int min_size = xg_get_insn_size (insn);
4176           int max_size = xg_get_max_insn_widen_size (insn->opcode);
4177           int max_literal_size =
4178             xg_get_max_insn_widen_literal_size (insn->opcode);
4179
4180 #if 0
4181           symbolS *immed_sym = xg_get_insn_immed_symbol (insn);
4182           set_frag_segment (frag_now, now_seg);
4183 #endif /* 0 */
4184
4185           /* Make sure we have enough space to widen the instruction. 
4186              This may open a new fragment.  */
4187           xg_force_frag_space (max_size);
4188           if (max_literal_size != 0)
4189             xg_assemble_literal_space (max_literal_size);
4190
4191           /* Output the instruction.  It may cause an error if some 
4192              operands do not fit.  Emit the incomplete instruction.  */
4193           last_insn = frag_more (0);
4194           xg_emit_insn (insn, FALSE);
4195
4196           xg_finish_frag (last_insn, RELAX_IMMED, max_size - min_size, TRUE);
4197
4198           /* Special cases for loops:
4199              close_loop_end should be inserted AFTER short_loop.
4200              Make sure that CLOSE loops are processed BEFORE short_loops
4201              when converting them.  */
4202
4203           /* "short_loop": add a NOP if the loop is < 4 bytes.  */
4204           if (software_avoid_short_loop
4205               && is_loop_opcode (insn->opcode))
4206             {
4207               maybe_has_short_loop = TRUE;
4208               frag_now->tc_frag_data.is_insn = TRUE;
4209               frag_var (rs_machine_dependent, 4, 4,
4210                         RELAX_ADD_NOP_IF_SHORT_LOOP,
4211                         frag_now->fr_symbol, frag_now->fr_offset, NULL);
4212               frag_now->tc_frag_data.is_insn = TRUE;
4213               frag_var (rs_machine_dependent, 4, 4,
4214                         RELAX_ADD_NOP_IF_SHORT_LOOP,
4215                         frag_now->fr_symbol, frag_now->fr_offset, NULL);
4216             }
4217
4218           /* "close_loop_end": Add up to 12 bytes of NOPs to keep a
4219              loop at least 12 bytes away from another loop's loop
4220              end.  */
4221           if (software_avoid_close_loop_end
4222               && is_loop_opcode (insn->opcode))
4223             {
4224               maybe_has_close_loop_end = TRUE;
4225               frag_now->tc_frag_data.is_insn = TRUE;
4226               frag_var (rs_machine_dependent, 12, 12,
4227                         RELAX_ADD_NOP_IF_CLOSE_LOOP_END,
4228                         frag_now->fr_symbol, frag_now->fr_offset, NULL);
4229             }
4230         }
4231       else
4232         {
4233           /* Assemble it in place.  No expansion will be required, 
4234              but we'll still need a relocation record.  */
4235           int max_size = xg_get_insn_size (insn);
4236           xg_force_frag_space (max_size);
4237           if (xg_emit_insn (insn, TRUE))
4238             as_warn (_("instruction's constant operands do not fit"));
4239         }
4240     }
4241 }
4242
4243
4244 /* Return true if the instruction can write to the specified
4245    integer register.  */
4246
4247 static bfd_boolean
4248 is_register_writer (insn, regset, regnum)
4249      const TInsn *insn;
4250      const char *regset;
4251      int regnum;
4252 {
4253   int i;
4254   int num_ops;
4255   xtensa_isa isa = xtensa_default_isa;
4256
4257   num_ops = xtensa_num_operands (isa, insn->opcode);
4258
4259   for (i = 0; i < num_ops; i++)
4260     {
4261       xtensa_operand operand = xtensa_get_operand (isa, insn->opcode, i);
4262       char inout = xtensa_operand_inout (operand);
4263
4264       if (inout == '>' || inout == '=')
4265         {
4266           if (strcmp (xtensa_operand_kind (operand), regset) == 0)
4267             {
4268               if ((insn->tok[i].X_op == O_register)
4269                   && (insn->tok[i].X_add_number == regnum))
4270                 return TRUE;
4271             }
4272         }
4273     }
4274   return FALSE;
4275 }
4276
4277
4278 static bfd_boolean
4279 is_bad_loopend_opcode (tinsn)
4280      const TInsn * tinsn;
4281 {
4282   xtensa_opcode opcode = tinsn->opcode;
4283
4284   if (opcode == XTENSA_UNDEFINED)
4285     return FALSE;
4286
4287   if (opcode == xtensa_call0_opcode
4288       || opcode == xtensa_callx0_opcode
4289       || opcode == xtensa_call4_opcode
4290       || opcode == xtensa_callx4_opcode
4291       || opcode == xtensa_call8_opcode
4292       || opcode == xtensa_callx8_opcode
4293       || opcode == xtensa_call12_opcode
4294       || opcode == xtensa_callx12_opcode
4295       || opcode == xtensa_isync_opcode
4296       || opcode == xtensa_ret_opcode
4297       || opcode == xtensa_ret_n_opcode
4298       || opcode == xtensa_retw_opcode
4299       || opcode == xtensa_retw_n_opcode
4300       || opcode == xtensa_waiti_opcode)
4301     return TRUE;
4302   
4303   /* An RSR of LCOUNT is illegal as the last opcode in a loop.  */
4304   if (opcode == xtensa_rsr_opcode
4305       && tinsn->ntok >= 2
4306       && tinsn->tok[1].X_op == O_constant
4307       && tinsn->tok[1].X_add_number == 2)
4308     return TRUE;
4309
4310   return FALSE;
4311 }
4312
4313
4314 /* Labels that begin with ".Ln" or ".LM"  are unaligned.
4315    This allows the debugger to add unaligned labels.
4316    Also, the assembler generates stabs labels that need
4317    not be aligned:  FAKE_LABEL_NAME . {"F", "L", "endfunc"}.  */
4318
4319 bfd_boolean
4320 is_unaligned_label (sym) 
4321      symbolS *sym; 
4322 {
4323   const char *name = S_GET_NAME (sym);
4324   static size_t fake_size = 0;
4325
4326   if (name
4327       && name[0] == '.'
4328       && name[1] == 'L' && (name[2] == 'n' || name[2] == 'M'))
4329     return TRUE;
4330
4331   /* FAKE_LABEL_NAME followed by "F", "L" or "endfunc" */
4332   if (fake_size == 0)
4333     fake_size = strlen (FAKE_LABEL_NAME);
4334
4335   if (name 
4336       && strncmp (FAKE_LABEL_NAME, name, fake_size) == 0
4337       && (name[fake_size] == 'F'
4338           || name[fake_size] == 'L'
4339           || (name[fake_size] == 'e'
4340               && strncmp ("endfunc", name+fake_size, 7) == 0)))
4341     return TRUE;
4342
4343   return FALSE;
4344 }
4345
4346
4347 fragS *
4348 next_non_empty_frag (fragP)
4349      const fragS *fragP;
4350 {
4351   fragS *next_fragP = fragP->fr_next;
4352
4353   /* Sometimes an empty will end up here due storage allocation issues. 
4354      So we have to skip until we find something legit.  */
4355   while (next_fragP && next_fragP->fr_fix == 0)
4356     next_fragP = next_fragP->fr_next;
4357
4358   if (next_fragP == NULL || next_fragP->fr_fix == 0)
4359     return NULL;
4360
4361   return next_fragP;
4362 }
4363
4364
4365 xtensa_opcode
4366 next_frag_opcode (fragP)
4367      const fragS * fragP;
4368 {
4369   const fragS *next_fragP = next_non_empty_frag (fragP);
4370   static xtensa_insnbuf insnbuf = NULL;
4371   xtensa_isa isa = xtensa_default_isa;
4372
4373   if (!insnbuf)
4374     insnbuf = xtensa_insnbuf_alloc (isa);
4375
4376   if (next_fragP == NULL)
4377     return XTENSA_UNDEFINED;
4378
4379   xtensa_insnbuf_from_chars (isa, insnbuf, next_fragP->fr_literal);
4380   return xtensa_decode_insn (isa, insnbuf);
4381 }
4382
4383
4384 /* Return true if the target frag is one of the next non-empty frags.  */
4385
4386 bfd_boolean
4387 is_next_frag_target (fragP, target)
4388      const fragS *fragP;
4389      const fragS *target;
4390 {
4391   if (fragP == NULL)
4392     return FALSE;
4393
4394   for (; fragP; fragP = fragP->fr_next)
4395     {
4396       if (fragP == target)
4397         return TRUE;
4398       if (fragP->fr_fix != 0)
4399         return FALSE;
4400       if (fragP->fr_type == rs_fill && fragP->fr_offset != 0)
4401         return FALSE;
4402       if ((fragP->fr_type == rs_align || fragP->fr_type == rs_align_code)
4403           && ((fragP->fr_address % (1 << fragP->fr_offset)) != 0))
4404         return FALSE;
4405       if (fragP->fr_type == rs_space)
4406         return FALSE;
4407     }
4408   return FALSE;
4409 }
4410
4411
4412 /* If the next legit fragment is an end-of-loop marker,
4413    switch its state so it will instantiate a NOP.  */
4414
4415 static void
4416 update_next_frag_nop_state (fragP)
4417      fragS *fragP;
4418 {
4419   fragS *next_fragP = fragP->fr_next;
4420
4421   while (next_fragP && next_fragP->fr_fix == 0)
4422     {
4423       if (next_fragP->fr_type == rs_machine_dependent
4424           && next_fragP->fr_subtype == RELAX_LOOP_END)
4425         {
4426           next_fragP->fr_subtype = RELAX_LOOP_END_ADD_NOP;
4427           return;
4428         }
4429       next_fragP = next_fragP->fr_next;
4430     }
4431 }
4432
4433
4434 static bfd_boolean
4435 next_frag_is_branch_target (fragP)
4436      const fragS *fragP;
4437 {
4438   /* Sometimes an empty will end up here due storage allocation issues,
4439      so we have to skip until we find something legit.  */
4440   for (fragP = fragP->fr_next; fragP; fragP = fragP->fr_next)
4441     {
4442       if (fragP->tc_frag_data.is_branch_target)
4443         return TRUE;
4444       if (fragP->fr_fix != 0)
4445         break;
4446     }
4447   return FALSE;
4448 }
4449
4450
4451 static bfd_boolean
4452 next_frag_is_loop_target (fragP)
4453      const fragS *fragP;
4454 {
4455   /* Sometimes an empty will end up here due storage allocation issues. 
4456      So we have to skip until we find something legit. */
4457   for (fragP = fragP->fr_next; fragP; fragP = fragP->fr_next)
4458     {
4459       if (fragP->tc_frag_data.is_loop_target)
4460         return TRUE;
4461       if (fragP->fr_fix != 0)
4462         break;
4463     }
4464   return FALSE;
4465 }
4466
4467
4468 static addressT
4469 next_frag_pre_opcode_bytes (fragp)
4470      const fragS *fragp;
4471 {
4472   const fragS *next_fragp = fragp->fr_next;
4473
4474   xtensa_opcode next_opcode = next_frag_opcode (fragp);
4475   if (!is_loop_opcode (next_opcode))
4476     return 0;
4477
4478   /* Sometimes an empty will end up here due storage allocation issues.
4479      So we have to skip until we find something legit.  */
4480   while (next_fragp->fr_fix == 0)
4481     next_fragp = next_fragp->fr_next;
4482
4483   if (next_fragp->fr_type != rs_machine_dependent)
4484     return 0;
4485
4486   /* There is some implicit knowledge encoded in here.
4487      The LOOP instructions that are NOT RELAX_IMMED have
4488      been relaxed.  */
4489   if (next_fragp->fr_subtype > RELAX_IMMED)
4490       return get_expanded_loop_offset (next_opcode);
4491
4492   return 0;
4493 }
4494
4495
4496 /* Mark a location where we can later insert literal frags.  Update
4497    the section's literal_pool_loc, so subsequent literals can be
4498    placed nearest to their use.  */
4499
4500 static void
4501 xtensa_mark_literal_pool_location ()
4502 {
4503   /* Any labels pointing to the current location need
4504      to be adjusted to after the literal pool.  */
4505   emit_state s;
4506   fragS *pool_location;
4507
4508   frag_align (2, 0, 0);
4509
4510   /* We stash info in the fr_var of these frags
4511      so we can later move the literal's fixes into this 
4512      frchain's fix list.  We can use fr_var because fr_var's
4513      interpretation depends solely on the fr_type and subtype.  */
4514   pool_location = frag_now;
4515   frag_variant (rs_machine_dependent, 0, (int) frchain_now, 
4516                 RELAX_LITERAL_POOL_BEGIN, NULL, 0, NULL);
4517   frag_variant (rs_machine_dependent, 0, (int) now_seg, 
4518                 RELAX_LITERAL_POOL_END, NULL, 0, NULL);
4519
4520   /* Now put a frag into the literal pool that points to this location.  */
4521   set_literal_pool_location (now_seg, pool_location);
4522   xtensa_switch_to_literal_fragment (&s);
4523
4524   /* Close whatever frag is there.  */
4525   frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
4526   frag_now->tc_frag_data.literal_frag = pool_location;
4527   frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
4528   xtensa_restore_emit_state (&s);
4529 }
4530
4531
4532 /* The "loops_ok" argument is provided to allow ignoring labels that 
4533    define loop ends.  This fixes a bug where the NOPs to align a 
4534    loop opcode were included in a previous zero-cost loop:
4535
4536    loop a0, loopend
4537      <loop1 body>
4538    loopend:
4539
4540    loop a2, loopend2
4541      <loop2 body>
4542
4543    would become:
4544
4545    loop a0, loopend
4546      <loop1 body>
4547      nop.n <===== bad!
4548    loopend:
4549
4550    loop a2, loopend2
4551      <loop2 body>
4552
4553    This argument is used to prevent moving the NOP to before the
4554    loop-end label, which is what you want in this special case.  */
4555
4556 static void
4557 xtensa_move_labels (new_frag, new_offset, loops_ok)
4558      fragS *new_frag;
4559      valueT new_offset;
4560      bfd_boolean loops_ok;
4561 {
4562   sym_list *lit;
4563
4564   for (lit = insn_labels; lit; lit = lit->next)
4565     {
4566       symbolS *lit_sym = lit->sym;
4567       if (loops_ok || symbol_get_tc (lit_sym)->is_loop_target == 0)
4568         {
4569           S_SET_VALUE (lit_sym, new_offset);
4570           symbol_set_frag (lit_sym, new_frag);
4571         }
4572     }
4573 }
4574
4575
4576 /* Assemble a NOP of the requested size in the buffer.  User must have
4577    allocated "buf" with at least "size" bytes.  */
4578
4579 void
4580 assemble_nop (size, buf)
4581      size_t size;
4582      char *buf;
4583 {
4584   static xtensa_insnbuf insnbuf = NULL;
4585   TInsn t_insn;
4586   if (!insnbuf)
4587     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
4588
4589   tinsn_init (&t_insn);
4590   switch (size)
4591     {
4592     case 2:
4593       t_insn.opcode = xtensa_nop_n_opcode;
4594       t_insn.ntok = 0;
4595       if (t_insn.opcode == XTENSA_UNDEFINED)
4596         as_fatal (_("opcode 'NOP.N' unavailable in this configuration"));
4597       tinsn_to_insnbuf (&t_insn, insnbuf);
4598       xtensa_insnbuf_to_chars (xtensa_default_isa, insnbuf, buf);
4599       break;
4600
4601     case 3:
4602       t_insn.opcode = xtensa_or_opcode;
4603       assert (t_insn.opcode != XTENSA_UNDEFINED);
4604       if (t_insn.opcode == XTENSA_UNDEFINED)
4605         as_fatal (_("opcode 'OR' unavailable in this configuration"));
4606       set_expr_const (&t_insn.tok[0], 1);
4607       set_expr_const (&t_insn.tok[1], 1);
4608       set_expr_const (&t_insn.tok[2], 1);
4609       t_insn.ntok = 3;
4610       tinsn_to_insnbuf (&t_insn, insnbuf);
4611       xtensa_insnbuf_to_chars (xtensa_default_isa, insnbuf, buf);
4612       break;
4613
4614     default:
4615       as_fatal (_("invalid %d-byte NOP requested"), size);
4616     }
4617 }
4618
4619
4620 /* Return the number of bytes for the offset of the expanded loop
4621    instruction.  This should be incorporated into the relaxation
4622    specification but is hard-coded here.  This is used to auto-align
4623    the loop instruction.  It is invalid to call this function if the
4624    configuration does not have loops or if the opcode is not a loop
4625    opcode.  */
4626
4627 static addressT
4628 get_expanded_loop_offset (opcode)
4629      xtensa_opcode opcode;
4630 {
4631   /* This is the OFFSET of the loop instruction in the expanded loop.
4632      This MUST correspond directly to the specification of the loop
4633      expansion.  It will be validated on fragment conversion.  */
4634   if (opcode == XTENSA_UNDEFINED)
4635     as_fatal (_("get_expanded_loop_offset: undefined opcode"));
4636   if (opcode == xtensa_loop_opcode)
4637     return 0;
4638   if (opcode == xtensa_loopnez_opcode)
4639     return 3;
4640   if (opcode == xtensa_loopgtz_opcode)
4641     return 6;
4642   as_fatal (_("get_expanded_loop_offset: invalid opcode"));
4643   return 0;
4644 }
4645
4646
4647 fragS *
4648 get_literal_pool_location (seg)
4649      segT seg;
4650 {
4651   return seg_info (seg)->tc_segment_info_data.literal_pool_loc;
4652 }
4653
4654
4655 static void
4656 set_literal_pool_location (seg, literal_pool_loc)
4657      segT seg;
4658      fragS *literal_pool_loc;
4659 {
4660   seg_info (seg)->tc_segment_info_data.literal_pool_loc = literal_pool_loc;
4661 }
4662
4663 \f
4664 /* External Functions and Other GAS Hooks.  */
4665
4666 const char *
4667 xtensa_target_format ()
4668 {
4669   return (target_big_endian ? "elf32-xtensa-be" : "elf32-xtensa-le");
4670 }
4671
4672
4673 void
4674 xtensa_file_arch_init (abfd)
4675      bfd *abfd;
4676 {
4677   bfd_set_private_flags (abfd, 0x100 | 0x200);
4678 }
4679
4680
4681 void
4682 md_number_to_chars (buf, val, n)
4683      char *buf;
4684      valueT val;
4685      int n;
4686 {
4687   if (target_big_endian)
4688     number_to_chars_bigendian (buf, val, n);
4689   else
4690     number_to_chars_littleendian (buf, val, n);
4691 }
4692
4693
4694 /* This function is called once, at assembler startup time.  It should
4695    set up all the tables, etc. that the MD part of the assembler will
4696    need.  */
4697
4698 void
4699 md_begin ()
4700 {
4701   segT current_section = now_seg;
4702   int current_subsec = now_subseg;
4703   xtensa_isa isa;
4704
4705 #if STATIC_LIBISA
4706   isa = xtensa_isa_init ();
4707 #else
4708   /* ISA was already initialized by xtensa_init().  */
4709   isa = xtensa_default_isa;
4710 #endif
4711
4712   /* Set  up the .literal, .fini.literal and .init.literal sections.  */
4713   memset (&default_lit_sections, 0, sizeof (default_lit_sections));
4714   default_lit_sections.init_lit_seg_name = INIT_LITERAL_SECTION_NAME;
4715   default_lit_sections.fini_lit_seg_name = FINI_LITERAL_SECTION_NAME;
4716   default_lit_sections.lit_seg_name = LITERAL_SECTION_NAME;
4717
4718   subseg_set (current_section, current_subsec);
4719
4720   xtensa_addi_opcode = xtensa_opcode_lookup (isa, "addi");
4721   xtensa_addmi_opcode = xtensa_opcode_lookup (isa, "addmi");
4722   xtensa_call0_opcode = xtensa_opcode_lookup (isa, "call0");
4723   xtensa_call4_opcode = xtensa_opcode_lookup (isa, "call4");
4724   xtensa_call8_opcode = xtensa_opcode_lookup (isa, "call8");
4725   xtensa_call12_opcode = xtensa_opcode_lookup (isa, "call12");
4726   xtensa_callx0_opcode = xtensa_opcode_lookup (isa, "callx0");
4727   xtensa_callx4_opcode = xtensa_opcode_lookup (isa, "callx4");
4728   xtensa_callx8_opcode = xtensa_opcode_lookup (isa, "callx8");
4729   xtensa_callx12_opcode = xtensa_opcode_lookup (isa, "callx12");
4730   xtensa_entry_opcode = xtensa_opcode_lookup (isa, "entry");
4731   xtensa_isync_opcode = xtensa_opcode_lookup (isa, "isync");
4732   xtensa_j_opcode = xtensa_opcode_lookup (isa, "j");
4733   xtensa_jx_opcode = xtensa_opcode_lookup (isa, "jx");
4734   xtensa_loop_opcode = xtensa_opcode_lookup (isa, "loop");
4735   xtensa_loopnez_opcode = xtensa_opcode_lookup (isa, "loopnez");
4736   xtensa_loopgtz_opcode = xtensa_opcode_lookup (isa, "loopgtz");
4737   xtensa_nop_n_opcode = xtensa_opcode_lookup (isa, "nop.n");
4738   xtensa_or_opcode = xtensa_opcode_lookup (isa, "or");
4739   xtensa_ret_opcode = xtensa_opcode_lookup (isa, "ret");
4740   xtensa_ret_n_opcode = xtensa_opcode_lookup (isa, "ret.n");
4741   xtensa_retw_opcode = xtensa_opcode_lookup (isa, "retw");
4742   xtensa_retw_n_opcode = xtensa_opcode_lookup (isa, "retw.n");
4743   xtensa_rsr_opcode = xtensa_opcode_lookup (isa, "rsr");
4744   xtensa_waiti_opcode = xtensa_opcode_lookup (isa, "waiti");
4745 }
4746
4747
4748 /* tc_frob_label hook */
4749
4750 void
4751 xtensa_frob_label (sym)
4752      symbolS *sym;
4753 {
4754   if (generating_literals)
4755     xtensa_add_literal_sym (sym);
4756   else
4757     xtensa_add_insn_label (sym);
4758
4759   if (symbol_get_tc (sym)->is_loop_target
4760       && (get_last_insn_flags (now_seg, now_subseg)
4761           & FLAG_IS_BAD_LOOPEND) != 0)
4762     as_bad (_("invalid last instruction for a zero-overhead loop"));
4763
4764   /* No target aligning in the absolute section.  */
4765   if (now_seg != absolute_section
4766       && align_targets
4767       && !is_unaligned_label (sym)
4768       && !frag_now->tc_frag_data.is_literal)
4769     {
4770       /* frag_now->tc_frag_data.is_insn = TRUE; */
4771       frag_var (rs_machine_dependent, 4, 4,
4772                 RELAX_DESIRE_ALIGN_IF_TARGET,
4773                 frag_now->fr_symbol, frag_now->fr_offset, NULL);
4774       xtensa_move_labels (frag_now, 0, TRUE);
4775
4776       /* If the label is already known to be a branch target, i.e., a
4777          forward branch, mark the frag accordingly.  Backward branches
4778          are handled by xg_add_branch_and_loop_targets.  */
4779       if (symbol_get_tc (sym)->is_branch_target)
4780         symbol_get_frag (sym)->tc_frag_data.is_branch_target = TRUE;
4781
4782       /* Loops only go forward, so they can be identified here.  */
4783       if (symbol_get_tc (sym)->is_loop_target)
4784         symbol_get_frag (sym)->tc_frag_data.is_loop_target = TRUE;
4785     }
4786 }
4787
4788
4789 /* md_flush_pending_output hook */
4790
4791 void
4792 xtensa_flush_pending_output ()
4793 {
4794   /* If there is a non-zero instruction fragment, close it.  */
4795   if (frag_now_fix () != 0 && frag_now->tc_frag_data.is_insn)
4796     {
4797       frag_wane (frag_now);
4798       frag_new (0);
4799     }
4800   frag_now->tc_frag_data.is_insn = FALSE;
4801
4802   xtensa_clear_insn_labels ();
4803 }
4804
4805
4806 void
4807 md_assemble (str)
4808      char *str;
4809 {
4810   xtensa_isa isa = xtensa_default_isa;
4811   char *opname;
4812   unsigned opnamelen;
4813   bfd_boolean has_underbar = FALSE;
4814   char *arg_strings[MAX_INSN_ARGS]; 
4815   int num_args;
4816   IStack istack;                /* Put instructions into here.  */
4817   TInsn orig_insn;              /* Original instruction from the input.  */
4818   int i;
4819   symbolS *lit_sym = NULL;
4820
4821   if (frag_now->tc_frag_data.is_literal)
4822     {
4823       static bfd_boolean reported = 0;
4824       if (reported < 4)
4825         as_bad (_("cannot assemble '%s' into a literal fragment"), str);
4826       if (reported == 3)
4827         as_bad (_("..."));
4828       reported++;
4829       return;
4830     }
4831
4832   istack_init (&istack);
4833   tinsn_init (&orig_insn);
4834
4835   /* Split off the opcode.  */
4836   opnamelen = strspn (str, "abcdefghijklmnopqrstuvwxyz_/0123456789.");
4837   opname = xmalloc (opnamelen + 1);
4838   memcpy (opname, str, opnamelen);
4839   opname[opnamelen] = '\0';
4840
4841   num_args = tokenize_arguments (arg_strings, str + opnamelen);
4842   if (num_args == -1)
4843     {
4844       as_bad (_("syntax error"));
4845       return;
4846     }
4847
4848   if (xg_translate_idioms (&opname, &num_args, arg_strings))
4849     return;
4850
4851   /* Check for an underbar prefix.  */
4852   if (*opname == '_')
4853     {
4854       has_underbar = TRUE;
4855       opname += 1;
4856     }
4857
4858   orig_insn.insn_type = ITYPE_INSN;
4859   orig_insn.ntok = 0;
4860   orig_insn.is_specific_opcode = (has_underbar || !use_generics ());
4861   specific_opcode = orig_insn.is_specific_opcode;
4862
4863   orig_insn.opcode = xtensa_opcode_lookup (isa, opname);
4864   if (orig_insn.opcode == XTENSA_UNDEFINED)
4865     {
4866       as_bad (_("unknown opcode %s"), opname);
4867       return;
4868     }
4869
4870   if (frag_now_fix () != 0 && !frag_now->tc_frag_data.is_insn)
4871     {
4872       frag_wane (frag_now);
4873       frag_new (0);
4874     }
4875
4876   if (software_a0_b_retw_interlock)
4877     {
4878       if ((get_last_insn_flags (now_seg, now_subseg) & FLAG_IS_A0_WRITER) != 0
4879           && is_conditional_branch_opcode (orig_insn.opcode))
4880         {
4881           has_a0_b_retw = TRUE;
4882
4883           /* Mark this fragment with the special RELAX_ADD_NOP_IF_A0_B_RETW.
4884              After the first assembly pass we will check all of them and
4885              add a nop if needed.  */
4886           frag_now->tc_frag_data.is_insn = TRUE;
4887           frag_var (rs_machine_dependent, 4, 4,
4888                     RELAX_ADD_NOP_IF_A0_B_RETW,
4889                     frag_now->fr_symbol, frag_now->fr_offset, NULL);
4890           frag_now->tc_frag_data.is_insn = TRUE;
4891           frag_var (rs_machine_dependent, 4, 4,
4892                     RELAX_ADD_NOP_IF_A0_B_RETW,
4893                     frag_now->fr_symbol, frag_now->fr_offset, NULL);
4894         }
4895     }
4896
4897   /* Special case: The call instructions should be marked "specific opcode"
4898      to keep them from expanding.  */
4899   if (!use_longcalls () && is_direct_call_opcode (orig_insn.opcode))
4900     orig_insn.is_specific_opcode = TRUE;
4901
4902   /* Parse the arguments.  */
4903   if (parse_arguments (&orig_insn, num_args, arg_strings))
4904     {
4905       as_bad (_("syntax error"));
4906       return;
4907     }
4908
4909   /* Free the opcode and argument strings, now that they've been parsed.  */
4910   free (has_underbar ? opname - 1 : opname);
4911   opname = 0;
4912   while (num_args-- > 0)
4913     free (arg_strings[num_args]);
4914
4915   /* Check for the right number and type of arguments.  */
4916   if (tinsn_check_arguments (&orig_insn))
4917     return;
4918
4919   /* See if the instruction implies an aligned section.  */
4920   if (is_entry_opcode (orig_insn.opcode) || is_loop_opcode (orig_insn.opcode))
4921     record_alignment (now_seg, 2);
4922
4923   xg_add_branch_and_loop_targets (&orig_insn);
4924
4925   /* Special cases for instructions that force an alignment... */
4926   if (!orig_insn.is_specific_opcode && is_loop_opcode (orig_insn.opcode))
4927     {
4928       size_t max_fill;
4929
4930       frag_now->tc_frag_data.is_insn = TRUE;
4931       frag_now->tc_frag_data.is_no_density = !code_density_available ();
4932       max_fill = get_text_align_max_fill_size
4933         (get_text_align_power (XTENSA_FETCH_WIDTH),
4934          TRUE, frag_now->tc_frag_data.is_no_density);
4935       frag_var (rs_machine_dependent, max_fill, max_fill,
4936                 RELAX_ALIGN_NEXT_OPCODE, frag_now->fr_symbol,
4937                 frag_now->fr_offset, NULL);
4938
4939       xtensa_move_labels (frag_now, 0, FALSE);
4940     }
4941
4942   /* Special-case for "entry" instruction.  */
4943   if (is_entry_opcode (orig_insn.opcode))
4944     {
4945       /* Check that the second opcode (#1) is >= 16.  */
4946       if (orig_insn.ntok >= 2)
4947         {
4948           expressionS *exp = &orig_insn.tok[1];
4949           switch (exp->X_op)
4950             {
4951             case O_constant:
4952               if (exp->X_add_number < 16)
4953                 as_warn (_("entry instruction with stack decrement < 16"));
4954               break;
4955
4956             default:
4957               as_warn (_("entry instruction with non-constant decrement"));
4958             }
4959         }
4960
4961       if (!orig_insn.is_specific_opcode)
4962         {
4963           xtensa_mark_literal_pool_location ();
4964
4965           /* Automatically align ENTRY instructions.  */
4966           xtensa_move_labels (frag_now, 0, TRUE);
4967           frag_align (2, 0, 0);
4968         }
4969     }
4970
4971   /* Any extra alignment frags have been inserted now, and we're about to
4972      emit a new instruction so clear the list of labels.  */
4973   xtensa_clear_insn_labels ();
4974
4975   if (software_a0_b_retw_interlock)
4976     set_last_insn_flags (now_seg, now_subseg, FLAG_IS_A0_WRITER,
4977                          is_register_writer (&orig_insn, "a", 0));
4978
4979   set_last_insn_flags (now_seg, now_subseg, FLAG_IS_BAD_LOOPEND,
4980                        is_bad_loopend_opcode (&orig_insn));
4981
4982   /* Finish it off:
4983      assemble_tokens (opcode, tok, ntok); 
4984      expand the tokens from the orig_insn into the 
4985      stack of instructions that will not expand 
4986      unless required at relaxation time.  */
4987   if (xg_expand_assembly_insn (&istack, &orig_insn))
4988     return;
4989
4990   for (i = 0; i < istack.ninsn; i++)
4991     {
4992       TInsn *insn = &istack.insn[i];
4993       if (insn->insn_type == ITYPE_LITERAL)
4994         {
4995           assert (lit_sym == NULL);
4996           lit_sym = xg_assemble_literal (insn);
4997         }
4998       else
4999         {
5000           if (lit_sym)
5001             xg_resolve_literals (insn, lit_sym);
5002           xg_assemble_tokens (insn);
5003         }
5004     }
5005
5006   /* Now, if the original opcode was a call... */
5007   if (align_targets && is_call_opcode (orig_insn.opcode))
5008     {
5009       frag_now->tc_frag_data.is_insn = TRUE;
5010       frag_var (rs_machine_dependent, 4, 4,
5011                 RELAX_DESIRE_ALIGN,
5012                 frag_now->fr_symbol,
5013                 frag_now->fr_offset,
5014                 NULL);
5015     }
5016 }
5017
5018
5019 /* TC_CONS_FIX_NEW hook: Check for "@PLT" suffix on symbol references.
5020    If found, use an XTENSA_PLT reloc for 4-byte values.  Otherwise, this
5021    is the same as the standard code in read.c.  */
5022
5023 void 
5024 xtensa_cons_fix_new (frag, where, size, exp)
5025      fragS *frag;
5026      int where; 
5027      int size;
5028      expressionS *exp;
5029 {
5030   bfd_reloc_code_real_type r;
5031   bfd_boolean plt = FALSE;
5032
5033   if (*input_line_pointer == '@') 
5034     {
5035       if (!strncmp (input_line_pointer, PLT_SUFFIX, strlen (PLT_SUFFIX) - 1)
5036           && !strncmp (input_line_pointer, plt_suffix,
5037                        strlen (plt_suffix) - 1))
5038         {
5039           as_bad (_("undefined @ suffix '%s', expected '%s'"), 
5040                   input_line_pointer, plt_suffix);
5041           ignore_rest_of_line ();
5042           return;
5043         }
5044
5045       input_line_pointer += strlen (plt_suffix);
5046       plt = TRUE;
5047     }
5048
5049   switch (size)
5050     {
5051     case 1:
5052       r = BFD_RELOC_8;
5053       break;
5054     case 2:
5055       r = BFD_RELOC_16;
5056       break;
5057     case 4:
5058       r = plt ? BFD_RELOC_XTENSA_PLT : BFD_RELOC_32;
5059       break;
5060     case 8:
5061       r = BFD_RELOC_64;
5062       break;
5063     default:
5064       as_bad (_("unsupported BFD relocation size %u"), size);
5065       r = BFD_RELOC_32;
5066       break;
5067     }
5068   fix_new_exp (frag, where, size, exp, 0, r);
5069 }
5070   
5071
5072 /* TC_FRAG_INIT hook */
5073
5074 void
5075 xtensa_frag_init (frag)
5076      fragS *frag;
5077 {
5078   frag->tc_frag_data.is_no_density = !code_density_available ();
5079 }
5080
5081
5082 symbolS *
5083 md_undefined_symbol (name)
5084      char *name ATTRIBUTE_UNUSED;
5085 {
5086   return NULL;
5087 }
5088
5089
5090 /* Round up a section size to the appropriate boundary.  */
5091
5092 valueT
5093 md_section_align (segment, size)
5094      segT segment ATTRIBUTE_UNUSED;
5095      valueT size;
5096 {
5097   return size;                  /* Byte alignment is fine.  */
5098 }
5099
5100
5101 long
5102 md_pcrel_from (fixP)
5103      fixS *fixP;
5104 {
5105   char *insn_p;
5106   static xtensa_insnbuf insnbuf = NULL;
5107   int opnum;
5108   xtensa_operand operand;
5109   xtensa_opcode opcode;
5110   xtensa_isa isa = xtensa_default_isa;
5111   valueT addr = fixP->fx_where + fixP->fx_frag->fr_address;
5112
5113   if (fixP->fx_done)
5114     return addr;
5115
5116   if (fixP->fx_r_type == BFD_RELOC_XTENSA_ASM_EXPAND)
5117     return addr;
5118
5119   if (!insnbuf)
5120     insnbuf = xtensa_insnbuf_alloc (isa);
5121
5122   insn_p = &fixP->fx_frag->fr_literal[fixP->fx_where];
5123   xtensa_insnbuf_from_chars (isa, insnbuf, insn_p);
5124   opcode = xtensa_decode_insn (isa, insnbuf);
5125
5126   opnum = reloc_to_opnum (fixP->fx_r_type);
5127
5128   if (opnum < 0)
5129     as_fatal (_("invalid operand relocation for '%s' instruction"),
5130               xtensa_opcode_name (isa, opcode));
5131   if (opnum >= xtensa_num_operands (isa, opcode))
5132     as_fatal (_("invalid relocation for operand %d in '%s' instruction"),
5133               opnum, xtensa_opcode_name (isa, opcode));
5134   operand = xtensa_get_operand (isa, opcode, opnum);
5135   if (!operand)
5136     {
5137       as_warn_where (fixP->fx_file,
5138                      fixP->fx_line,
5139                      _("invalid relocation type %d for %s instruction"),
5140                      fixP->fx_r_type, xtensa_opcode_name (isa, opcode));
5141       return addr;
5142     }
5143
5144   if (!operand_is_pcrel_label (operand))
5145     {
5146       as_bad_where (fixP->fx_file,
5147                     fixP->fx_line,
5148                     _("invalid relocation for operand %d of '%s'"),
5149                     opnum, xtensa_opcode_name (isa, opcode));
5150       return addr;
5151     }
5152   if (!xtensa_operand_isPCRelative (operand))
5153     {
5154       as_warn_where (fixP->fx_file,
5155                      fixP->fx_line,
5156                      _("non-PCREL relocation operand %d for '%s': %s"),
5157                      opnum, xtensa_opcode_name (isa, opcode),
5158                      bfd_get_reloc_code_name (fixP->fx_r_type));
5159       return addr;
5160     }
5161
5162   return 0 - xtensa_operand_do_reloc (operand, 0, addr);
5163 }
5164
5165
5166 /* tc_symbol_new_hook */
5167
5168 void
5169 xtensa_symbol_new_hook (symbolP)
5170      symbolS *symbolP;
5171 {
5172   symbol_get_tc (symbolP)->plt = 0;
5173 }
5174
5175
5176 /* tc_fix_adjustable hook */
5177
5178 bfd_boolean
5179 xtensa_fix_adjustable (fixP)
5180      fixS *fixP;
5181 {
5182   /* We need the symbol name for the VTABLE entries.  */
5183   if (fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
5184       || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
5185     return 0;
5186
5187   return 1;
5188 }
5189
5190
5191 void
5192 md_apply_fix3 (fixP, valP, seg)
5193      fixS *fixP;
5194      valueT *valP;
5195      segT seg ATTRIBUTE_UNUSED;
5196 {
5197   if (fixP->fx_pcrel == 0 && fixP->fx_addsy == 0)
5198     {
5199       /* This happens when the relocation is within the current section. 
5200          It seems this implies a PCREL operation.  We'll catch it and error 
5201          if not.  */
5202
5203       char *const fixpos = fixP->fx_frag->fr_literal + fixP->fx_where;
5204       static xtensa_insnbuf insnbuf = NULL;
5205       xtensa_opcode opcode;
5206       xtensa_isa isa;
5207
5208       switch (fixP->fx_r_type)
5209         {
5210         case BFD_RELOC_XTENSA_ASM_EXPAND:
5211           fixP->fx_done = 1;
5212           break;
5213
5214         case BFD_RELOC_XTENSA_ASM_SIMPLIFY:
5215           as_bad (_("unhandled local relocation fix %s"),
5216                   bfd_get_reloc_code_name (fixP->fx_r_type));
5217           break;
5218
5219         case BFD_RELOC_32:
5220         case BFD_RELOC_16:
5221         case BFD_RELOC_8:
5222           /* The only one we support that isn't an instruction field.  */
5223           md_number_to_chars (fixpos, *valP, fixP->fx_size);
5224           fixP->fx_done = 1;
5225           break;
5226
5227         case BFD_RELOC_XTENSA_OP0:
5228         case BFD_RELOC_XTENSA_OP1:
5229         case BFD_RELOC_XTENSA_OP2:
5230           isa = xtensa_default_isa;
5231           if (!insnbuf)
5232             insnbuf = xtensa_insnbuf_alloc (isa);
5233
5234           xtensa_insnbuf_from_chars (isa, insnbuf, fixpos);
5235           opcode = xtensa_decode_insn (isa, insnbuf);
5236           if (opcode == XTENSA_UNDEFINED)
5237             as_fatal (_("undecodable FIX"));
5238
5239           xtensa_insnbuf_set_immediate_field (opcode, insnbuf, *valP,
5240                                               fixP->fx_file, fixP->fx_line);
5241
5242           fixP->fx_frag->tc_frag_data.is_insn = TRUE;
5243           xtensa_insnbuf_to_chars (isa, insnbuf, fixpos);
5244           fixP->fx_done = 1;
5245           break;
5246
5247         case BFD_RELOC_VTABLE_INHERIT:
5248         case BFD_RELOC_VTABLE_ENTRY:
5249           fixP->fx_done = 0;
5250           break;
5251
5252         default:
5253           as_bad (_("unhandled local relocation fix %s"),
5254                   bfd_get_reloc_code_name (fixP->fx_r_type));
5255         }
5256     }
5257 }
5258
5259
5260 char *
5261 md_atof (type, litP, sizeP)
5262      int type;
5263      char *litP;
5264      int *sizeP;
5265 {
5266   int prec;
5267   LITTLENUM_TYPE words[4];
5268   char *t;
5269   int i;
5270
5271   switch (type)
5272     {
5273     case 'f':
5274       prec = 2;
5275       break;
5276
5277     case 'd':
5278       prec = 4;
5279       break;
5280
5281     default:
5282       *sizeP = 0;
5283       return "bad call to md_atof";
5284     }
5285
5286   t = atof_ieee (input_line_pointer, type, words);
5287   if (t)
5288     input_line_pointer = t;
5289
5290   *sizeP = prec * 2;
5291
5292   for (i = prec - 1; i >= 0; i--)
5293     {
5294       int idx = i;
5295       if (target_big_endian)
5296         idx = (prec - 1 - i);
5297
5298       md_number_to_chars (litP, (valueT) words[idx], 2);
5299       litP += 2;
5300     }
5301
5302   return NULL;
5303 }
5304
5305
5306 int
5307 md_estimate_size_before_relax (fragP, seg)
5308      fragS *fragP;
5309      segT seg ATTRIBUTE_UNUSED;
5310 {
5311   return fragP->tc_frag_data.text_expansion;
5312 }
5313
5314
5315 /* Translate internal representation of relocation info to BFD target
5316    format.  */
5317
5318 arelent *
5319 tc_gen_reloc (section, fixp)
5320      asection *section ATTRIBUTE_UNUSED;
5321      fixS *fixp;
5322 {
5323   arelent *reloc;
5324
5325   reloc = (arelent *) xmalloc (sizeof (arelent));
5326   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
5327   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
5328   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
5329
5330   /* Make sure none of our internal relocations make it this far.
5331      They'd better have been fully resolved by this point.  */
5332   assert ((int) fixp->fx_r_type > 0);
5333
5334   reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
5335   if (reloc->howto == NULL)
5336     {
5337       as_bad_where (fixp->fx_file, fixp->fx_line,
5338                     _("cannot represent `%s' relocation in object file"),
5339                     bfd_get_reloc_code_name (fixp->fx_r_type));
5340       return NULL;
5341     }
5342
5343   if (!fixp->fx_pcrel != !reloc->howto->pc_relative)
5344     {
5345       as_fatal (_("internal error? cannot generate `%s' relocation"),
5346                 bfd_get_reloc_code_name (fixp->fx_r_type));
5347     }
5348   assert (!fixp->fx_pcrel == !reloc->howto->pc_relative);
5349
5350   reloc->addend = fixp->fx_offset;
5351
5352   switch (fixp->fx_r_type)
5353     {
5354     case BFD_RELOC_XTENSA_OP0:
5355     case BFD_RELOC_XTENSA_OP1:
5356     case BFD_RELOC_XTENSA_OP2:
5357     case BFD_RELOC_XTENSA_ASM_EXPAND:
5358     case BFD_RELOC_32: 
5359     case BFD_RELOC_XTENSA_PLT: 
5360     case BFD_RELOC_VTABLE_INHERIT:
5361     case BFD_RELOC_VTABLE_ENTRY:
5362       break;
5363
5364     case BFD_RELOC_XTENSA_ASM_SIMPLIFY:
5365       as_warn (_("emitting simplification relocation"));
5366       break;
5367
5368     default:
5369       as_warn (_("emitting unknown relocation"));
5370     }
5371
5372   return reloc;
5373 }
5374
5375 \f
5376 void
5377 xtensa_end ()
5378 {
5379   directive_balance ();
5380   xtensa_move_literals ();
5381
5382   xtensa_reorder_segments ();
5383   xtensa_cleanup_align_frags ();
5384   xtensa_fix_target_frags ();
5385   if (software_a0_b_retw_interlock && has_a0_b_retw)
5386     xtensa_fix_a0_b_retw_frags ();
5387   if (software_avoid_b_j_loop_end && maybe_has_b_j_loop_end)
5388     xtensa_fix_b_j_loop_end_frags ();
5389
5390   /* "close_loop_end" should be processed BEFORE "short_loop".  */
5391   if (software_avoid_close_loop_end && maybe_has_close_loop_end)
5392     xtensa_fix_close_loop_end_frags ();
5393
5394   if (software_avoid_short_loop && maybe_has_short_loop)
5395     xtensa_fix_short_loop_frags ();
5396
5397   xtensa_sanity_check ();
5398 }
5399
5400
5401 static void
5402 xtensa_cleanup_align_frags ()
5403 {
5404   frchainS *frchP;
5405
5406   for (frchP = frchain_root; frchP; frchP = frchP->frch_next)
5407     {
5408       fragS *fragP;
5409
5410       /* Walk over all of the fragments in a subsection.  */
5411       for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
5412         {
5413           if ((fragP->fr_type == rs_align
5414                || fragP->fr_type == rs_align_code
5415                || (fragP->fr_type == rs_machine_dependent
5416                    && (fragP->fr_subtype == RELAX_DESIRE_ALIGN
5417                        || fragP->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET)))
5418               && fragP->fr_fix == 0)
5419             {
5420               fragS * next = fragP->fr_next;
5421
5422               while (next
5423                      && next->fr_type == rs_machine_dependent 
5424                      && next->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET) 
5425                 {
5426                   frag_wane (next);
5427                   next = next->fr_next;
5428                 }
5429             }
5430         }
5431     }
5432 }
5433
5434
5435 /* Re-process all of the fragments looking to convert all of the
5436    RELAX_DESIRE_ALIGN_IF_TARGET fragments.  If there is a branch
5437    target in the next fragment, convert this to RELAX_DESIRE_ALIGN.
5438    If the next fragment starts with a loop target, AND the previous
5439    fragment can be expanded to negate the branch, convert this to a
5440    RELAX_LOOP_END.  Otherwise, convert to a .fill 0.  */
5441
5442 static void
5443 xtensa_fix_target_frags ()
5444 {
5445   frchainS *frchP;
5446
5447   /* When this routine is called, all of the subsections are still intact
5448      so we walk over subsections instead of sections.  */
5449   for (frchP = frchain_root; frchP; frchP = frchP->frch_next)
5450     {
5451       bfd_boolean prev_frag_can_negate_branch = FALSE;
5452       fragS *fragP;
5453
5454       /* Walk over all of the fragments in a subsection.  */
5455       for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
5456         {
5457           if (fragP->fr_type == rs_machine_dependent
5458               && fragP->fr_subtype == RELAX_DESIRE_ALIGN_IF_TARGET)
5459             {
5460               if (next_frag_is_loop_target (fragP))
5461                 {
5462                   if (prev_frag_can_negate_branch)
5463                     fragP->fr_subtype = RELAX_LOOP_END;
5464                   else
5465                     {
5466                       if (!align_only_targets ||
5467                           next_frag_is_branch_target (fragP))
5468                         fragP->fr_subtype = RELAX_DESIRE_ALIGN;
5469                       else
5470                         frag_wane (fragP);
5471                     }
5472                 }
5473               else if (!align_only_targets
5474                        || next_frag_is_branch_target (fragP))
5475                 fragP->fr_subtype = RELAX_DESIRE_ALIGN;
5476               else
5477                 frag_wane (fragP);
5478             }
5479           if (fragP->fr_fix != 0)
5480             prev_frag_can_negate_branch = FALSE;
5481           if (frag_can_negate_branch (fragP))
5482             prev_frag_can_negate_branch = TRUE;
5483         }
5484     }
5485 }
5486
5487
5488 static bfd_boolean
5489 frag_can_negate_branch (fragP)
5490      fragS *fragP;
5491 {
5492   if (fragP->fr_type == rs_machine_dependent
5493       && fragP->fr_subtype == RELAX_IMMED)
5494     {
5495       TInsn t_insn;
5496       tinsn_from_chars (&t_insn, fragP->fr_opcode);
5497       if (is_negatable_branch (&t_insn))
5498         return TRUE;
5499     }
5500   return FALSE;
5501 }
5502
5503
5504 /* Re-process all of the fragments looking to convert all of the
5505    RELAX_ADD_NOP_IF_A0_B_RETW.  If the next instruction is a
5506    conditional branch or a retw/retw.n, convert this frag to one that
5507    will generate a NOP.  In any case close it off with a .fill 0.  */
5508
5509 static void
5510 xtensa_fix_a0_b_retw_frags ()
5511 {
5512   frchainS *frchP;
5513
5514   /* When this routine is called, all of the subsections are still intact
5515      so we walk over subsections instead of sections.  */
5516   for (frchP = frchain_root; frchP; frchP = frchP->frch_next)
5517     {
5518       fragS *fragP;
5519
5520       /* Walk over all of the fragments in a subsection.  */
5521       for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
5522         {
5523           if (fragP->fr_type == rs_machine_dependent
5524               && fragP->fr_subtype == RELAX_ADD_NOP_IF_A0_B_RETW)
5525             {
5526               if (next_instrs_are_b_retw (fragP))
5527                 relax_frag_add_nop (fragP);
5528               else
5529                 frag_wane (fragP);
5530             }
5531         }
5532     }
5533 }
5534
5535
5536 bfd_boolean
5537 next_instrs_are_b_retw (fragP)
5538      fragS * fragP;
5539 {
5540   xtensa_opcode opcode;
5541   const fragS *next_fragP = next_non_empty_frag (fragP);
5542   static xtensa_insnbuf insnbuf = NULL;
5543   xtensa_isa isa = xtensa_default_isa;
5544   int offset = 0;
5545
5546   if (!insnbuf)
5547     insnbuf = xtensa_insnbuf_alloc (isa);
5548
5549   if (next_fragP == NULL)
5550     return FALSE;
5551
5552   /* Check for the conditional branch.  */
5553   xtensa_insnbuf_from_chars (isa, insnbuf, &next_fragP->fr_literal[offset]);
5554   opcode = xtensa_decode_insn (isa, insnbuf);
5555
5556   if (!is_conditional_branch_opcode (opcode))
5557     return FALSE;
5558
5559   offset += xtensa_insn_length (isa, opcode);
5560   if (offset == next_fragP->fr_fix)
5561     {
5562       next_fragP = next_non_empty_frag (next_fragP);
5563       offset = 0;
5564     }
5565   if (next_fragP == NULL)
5566     return FALSE;
5567
5568   /* Check for the retw/retw.n.  */
5569   xtensa_insnbuf_from_chars (isa, insnbuf, &next_fragP->fr_literal[offset]);
5570   opcode = xtensa_decode_insn (isa, insnbuf);
5571
5572   if (is_windowed_return_opcode (opcode))
5573     return TRUE;
5574   return FALSE;
5575 }
5576
5577
5578 /* Re-process all of the fragments looking to convert all of the
5579    RELAX_ADD_NOP_IF_PRE_LOOP_END.  If there is one instruction and a
5580    loop end label, convert this frag to one that will generate a NOP.
5581    In any case close it off with a .fill 0.  */
5582
5583 static void
5584 xtensa_fix_b_j_loop_end_frags ()
5585 {
5586   frchainS *frchP;
5587
5588   /* When this routine is called, all of the subsections are still intact
5589      so we walk over subsections instead of sections.  */
5590   for (frchP = frchain_root; frchP; frchP = frchP->frch_next)
5591     {
5592       fragS *fragP;
5593
5594       /* Walk over all of the fragments in a subsection.  */
5595       for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
5596         {
5597           if (fragP->fr_type == rs_machine_dependent
5598               && fragP->fr_subtype == RELAX_ADD_NOP_IF_PRE_LOOP_END)
5599             {
5600               if (next_instr_is_loop_end (fragP))
5601                 relax_frag_add_nop (fragP);
5602               else
5603                 frag_wane (fragP);
5604             }
5605         }
5606     }
5607 }
5608
5609
5610 bfd_boolean
5611 next_instr_is_loop_end (fragP)
5612      fragS * fragP;
5613 {
5614   const fragS *next_fragP;
5615
5616   if (next_frag_is_loop_target (fragP))
5617     return FALSE;
5618
5619   next_fragP = next_non_empty_frag (fragP);
5620   if (next_fragP == NULL)
5621     return FALSE;
5622
5623   if (!next_frag_is_loop_target (next_fragP))
5624     return FALSE;
5625
5626   /* If the size is >= 3 then there is more than one instruction here.
5627      The hardware bug will not fire.  */
5628   if (next_fragP->fr_fix > 3)
5629     return FALSE;
5630
5631   return TRUE;
5632 }
5633
5634
5635 /* Re-process all of the fragments looking to convert all of the
5636    RELAX_ADD_NOP_IF_CLOSE_LOOP_END.  If there is an loop end that is
5637    not MY loop's loop end within 12 bytes, add enough nops here to
5638    make it at least 12 bytes away.  In any case close it off with a
5639    .fill 0.  */
5640
5641 static void
5642 xtensa_fix_close_loop_end_frags ()
5643 {
5644   frchainS *frchP;
5645
5646   /* When this routine is called, all of the subsections are still intact
5647      so we walk over subsections instead of sections.  */
5648   for (frchP = frchain_root; frchP; frchP = frchP->frch_next)
5649     {
5650       fragS *fragP;
5651
5652       fragS *current_target = NULL;
5653       offsetT current_offset = 0;
5654
5655       /* Walk over all of the fragments in a subsection.  */
5656       for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
5657         {
5658           if (fragP->fr_type == rs_machine_dependent
5659               && fragP->fr_subtype == RELAX_IMMED)
5660             {
5661               /* Read it.  If the instruction is a loop, get the target.  */
5662               xtensa_opcode opcode = get_opcode_from_buf (fragP->fr_opcode);
5663               if (is_loop_opcode (opcode))
5664                 {
5665                   TInsn t_insn;
5666
5667                   tinsn_from_chars (&t_insn, fragP->fr_opcode);
5668                   tinsn_immed_from_frag (&t_insn, fragP);
5669
5670                   /* Get the current fragment target.  */
5671                   if (fragP->fr_symbol)
5672                     {
5673                       current_target = symbol_get_frag (fragP->fr_symbol);
5674                       current_offset = fragP->fr_offset;
5675                     }
5676                 }
5677             }
5678
5679           if (current_target
5680               && fragP->fr_type == rs_machine_dependent
5681               && fragP->fr_subtype == RELAX_ADD_NOP_IF_CLOSE_LOOP_END)
5682             {
5683               size_t min_bytes;
5684               size_t bytes_added = 0;
5685
5686 #define REQUIRED_LOOP_DIVIDING_BYTES 12
5687               /* Max out at 12.  */
5688               min_bytes = min_bytes_to_other_loop_end
5689                 (fragP->fr_next, current_target, current_offset,
5690                  REQUIRED_LOOP_DIVIDING_BYTES);
5691
5692               if (min_bytes < REQUIRED_LOOP_DIVIDING_BYTES)
5693                 {
5694                   while (min_bytes + bytes_added
5695                          < REQUIRED_LOOP_DIVIDING_BYTES)
5696                     {
5697                       int length = 3;
5698
5699                       if (fragP->fr_var < length)
5700                         as_warn (_("fr_var %lu < length %d; ignoring"),
5701                                  fragP->fr_var, length);
5702                       else
5703                         {
5704                           assemble_nop (length,
5705                                         fragP->fr_literal + fragP->fr_fix);
5706                           fragP->fr_fix += length;
5707                           fragP->fr_var -= length;
5708                         }
5709                       bytes_added += length;
5710                     }
5711                 }
5712               frag_wane (fragP);
5713             }
5714         }
5715     }
5716 }
5717
5718
5719 size_t
5720 min_bytes_to_other_loop_end (fragP, current_target, current_offset, max_size)
5721      fragS *fragP;
5722      fragS *current_target;
5723      offsetT current_offset;
5724      size_t max_size;
5725 {
5726   size_t offset = 0;
5727   fragS *current_fragP;
5728
5729   for (current_fragP = fragP;
5730        current_fragP;
5731        current_fragP = current_fragP->fr_next)
5732     {
5733       if (current_fragP->tc_frag_data.is_loop_target
5734           && current_fragP != current_target)
5735         return offset + current_offset;
5736
5737       offset += unrelaxed_frag_min_size (current_fragP);
5738
5739       if (offset + current_offset >= max_size)
5740         return max_size;
5741     }
5742   return max_size;
5743 }
5744
5745
5746 size_t
5747 unrelaxed_frag_min_size (fragP)
5748      fragS * fragP;
5749 {
5750   size_t size = fragP->fr_fix;
5751
5752   /* add fill size */
5753   if (fragP->fr_type == rs_fill)
5754     size += fragP->fr_offset;
5755
5756   return size;
5757 }
5758
5759
5760 /* Re-process all of the fragments looking to convert all
5761    of the RELAX_ADD_NOP_IF_SHORT_LOOP.  If:
5762
5763    A)
5764      1) the instruction size count to the loop end label
5765         is too short (<= 2 instructions),
5766      2) loop has a jump or branch in it
5767
5768    or B)
5769      1) software_avoid_all_short_loops is true
5770      2) The generating loop was a  'loopgtz' or 'loopnez'
5771      3) the instruction size count to the loop end label is too short
5772         (<= 2 instructions)
5773    then convert this frag (and maybe the next one) to generate a NOP.
5774    In any case close it off with a .fill 0.  */
5775
5776 static void
5777 xtensa_fix_short_loop_frags ()
5778 {
5779   frchainS *frchP;
5780
5781   /* When this routine is called, all of the subsections are still intact
5782      so we walk over subsections instead of sections.  */
5783   for (frchP = frchain_root; frchP; frchP = frchP->frch_next)
5784     {
5785       fragS *fragP;
5786       fragS *current_target = NULL;
5787       offsetT current_offset = 0;
5788       xtensa_opcode current_opcode = XTENSA_UNDEFINED;
5789
5790       /* Walk over all of the fragments in a subsection.  */
5791       for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
5792         {
5793           /* check on the current loop */
5794           if (fragP->fr_type == rs_machine_dependent
5795               && fragP->fr_subtype == RELAX_IMMED)
5796             {
5797               /* Read it.  If the instruction is a loop, get the target.  */
5798               xtensa_opcode opcode = get_opcode_from_buf (fragP->fr_opcode);
5799               if (is_loop_opcode (opcode))
5800                 {
5801                   TInsn t_insn;
5802
5803                   tinsn_from_chars (&t_insn, fragP->fr_opcode);
5804                   tinsn_immed_from_frag (&t_insn, fragP);
5805
5806                   /* Get the current fragment target.  */
5807                   if (fragP->fr_symbol)
5808                     {
5809                       current_target = symbol_get_frag (fragP->fr_symbol);
5810                       current_offset = fragP->fr_offset;
5811                       current_opcode = opcode;
5812                     }
5813                 }
5814             }
5815
5816           if (fragP->fr_type == rs_machine_dependent
5817               && fragP->fr_subtype == RELAX_ADD_NOP_IF_SHORT_LOOP)
5818             {
5819               size_t insn_count =
5820                 count_insns_to_loop_end (fragP->fr_next, TRUE, 3);
5821               if (insn_count < 3
5822                   && (branch_before_loop_end (fragP->fr_next)
5823                       || (software_avoid_all_short_loops
5824                           && current_opcode != XTENSA_UNDEFINED
5825                           && !is_the_loop_opcode (current_opcode))))
5826                 relax_frag_add_nop (fragP);
5827               else
5828                 frag_wane (fragP);
5829             }
5830         }
5831     }
5832 }
5833
5834
5835 size_t
5836 count_insns_to_loop_end (base_fragP, count_relax_add, max_count)
5837      fragS *base_fragP;
5838      bfd_boolean count_relax_add;
5839      size_t max_count;
5840 {
5841   fragS *fragP = NULL;
5842   size_t insn_count = 0;
5843
5844   fragP = base_fragP;
5845
5846   for (; fragP && !fragP->tc_frag_data.is_loop_target; fragP = fragP->fr_next)
5847     {
5848       insn_count += unrelaxed_frag_min_insn_count (fragP);
5849       if (insn_count >= max_count)
5850         return max_count;
5851
5852       if (count_relax_add)
5853         {
5854           if (fragP->fr_type == rs_machine_dependent
5855               && fragP->fr_subtype == RELAX_ADD_NOP_IF_SHORT_LOOP)
5856             {
5857               /* In order to add the appropriate number of
5858                  NOPs, we count an instruction for downstream
5859                  occurrences.  */
5860               insn_count++;
5861               if (insn_count >= max_count)
5862                 return max_count;
5863             }
5864         }
5865     }
5866   return insn_count;
5867 }
5868
5869
5870 size_t
5871 unrelaxed_frag_min_insn_count (fragP)
5872      fragS *fragP;
5873 {
5874   size_t insn_count = 0;
5875   int offset = 0;
5876
5877   if (!fragP->tc_frag_data.is_insn)
5878     return insn_count;
5879
5880   /* Decode the fixed instructions.  */
5881   while (offset < fragP->fr_fix)
5882     {
5883       xtensa_opcode opcode = get_opcode_from_buf (fragP->fr_literal + offset);
5884       if (opcode == XTENSA_UNDEFINED)
5885         {
5886           as_fatal (_("undecodable instruction in instruction frag"));
5887           return insn_count;
5888         }
5889       offset += xtensa_insn_length (xtensa_default_isa, opcode);
5890       insn_count++;
5891     }
5892
5893   return insn_count;
5894 }
5895
5896
5897 bfd_boolean
5898 branch_before_loop_end (base_fragP)
5899      fragS *base_fragP;
5900 {
5901   fragS *fragP;
5902
5903   for (fragP = base_fragP;
5904        fragP && !fragP->tc_frag_data.is_loop_target;
5905        fragP = fragP->fr_next)
5906     {
5907       if (unrelaxed_frag_has_b_j (fragP))
5908         return TRUE;
5909     }
5910   return FALSE;
5911 }
5912
5913
5914 bfd_boolean
5915 unrelaxed_frag_has_b_j (fragP)
5916      fragS *fragP;
5917 {
5918   size_t insn_count = 0;
5919   int offset = 0;
5920
5921   if (!fragP->tc_frag_data.is_insn)
5922     return FALSE;
5923
5924   /* Decode the fixed instructions.  */
5925   while (offset < fragP->fr_fix)
5926     {
5927       xtensa_opcode opcode = get_opcode_from_buf (fragP->fr_literal + offset);
5928       if (opcode == XTENSA_UNDEFINED)
5929         {
5930           as_fatal (_("undecodable instruction in instruction frag"));
5931           return insn_count;
5932         }
5933       if (is_branch_or_jump_opcode (opcode))
5934         return TRUE;
5935       offset += xtensa_insn_length (xtensa_default_isa, opcode);
5936     }
5937   return FALSE;
5938 }
5939
5940
5941 /* Checks to be made after initial assembly but before relaxation.  */
5942
5943 static void
5944 xtensa_sanity_check ()
5945 {
5946   char *file_name;
5947   int line;
5948
5949   frchainS *frchP;
5950
5951   as_where (&file_name, &line);
5952   for (frchP = frchain_root; frchP; frchP = frchP->frch_next)
5953     {
5954       fragS *fragP;
5955
5956       /* Walk over all of the fragments in a subsection.  */
5957       for (fragP = frchP->frch_root; fragP; fragP = fragP->fr_next)
5958         {
5959           /* Currently we only check for empty loops here.  */
5960           if (fragP->fr_type == rs_machine_dependent
5961               && fragP->fr_subtype == RELAX_IMMED)
5962             {
5963               static xtensa_insnbuf insnbuf = NULL;
5964               TInsn t_insn;
5965
5966               if (fragP->fr_opcode != NULL)
5967                 {
5968                   if (!insnbuf)
5969                     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
5970                   tinsn_from_chars (&t_insn, fragP->fr_opcode);
5971                   tinsn_immed_from_frag (&t_insn, fragP);
5972
5973                   if (is_loop_opcode (t_insn.opcode))
5974                     {
5975                       if (is_empty_loop (&t_insn, fragP))
5976                         {
5977                           new_logical_line (fragP->fr_file, fragP->fr_line);
5978                           as_bad (_("invalid empty loop"));
5979                         }
5980                       if (!is_local_forward_loop (&t_insn, fragP))
5981                         {
5982                           new_logical_line (fragP->fr_file, fragP->fr_line);
5983                           as_bad (_("loop target does not follow "
5984                                     "loop instruction in section"));
5985                         }
5986                     }
5987                 }
5988             }
5989         }
5990     }
5991   new_logical_line (file_name, line);
5992 }
5993
5994
5995 #define LOOP_IMMED_OPN 1
5996
5997 /* Return true if the loop target is the next non-zero fragment.  */
5998
5999 bfd_boolean
6000 is_empty_loop (insn, fragP)
6001      const TInsn *insn;
6002      fragS *fragP;
6003 {
6004   const expressionS *expr;
6005   symbolS *symbolP;
6006   fragS *next_fragP;
6007
6008   if (insn->insn_type != ITYPE_INSN)
6009     return FALSE;
6010
6011   if (!is_loop_opcode (insn->opcode))
6012     return FALSE;
6013
6014   if (insn->ntok <= LOOP_IMMED_OPN)
6015     return FALSE;
6016
6017   expr = &insn->tok[LOOP_IMMED_OPN];
6018
6019   if (expr->X_op != O_symbol)
6020     return FALSE;
6021
6022   symbolP = expr->X_add_symbol;
6023   if (!symbolP)
6024     return FALSE;
6025
6026   if (symbol_get_frag (symbolP) == NULL)
6027     return FALSE;
6028
6029   if (S_GET_VALUE (symbolP) != 0)
6030     return FALSE;
6031
6032   /* Walk through the zero-size fragments from this one.  If we find
6033      the target fragment, then this is a zero-size loop.  */
6034   for (next_fragP = fragP->fr_next;
6035        next_fragP != NULL;
6036        next_fragP = next_fragP->fr_next)
6037     {
6038       if (next_fragP == symbol_get_frag (symbolP))
6039         return TRUE;
6040       if (next_fragP->fr_fix != 0)
6041         return FALSE;
6042     }
6043   return FALSE;
6044 }
6045
6046
6047 bfd_boolean
6048 is_local_forward_loop (insn, fragP)
6049      const TInsn *insn;
6050      fragS *fragP;
6051 {
6052   const expressionS *expr;
6053   symbolS *symbolP;
6054   fragS *next_fragP;
6055
6056   if (insn->insn_type != ITYPE_INSN)
6057     return FALSE;
6058
6059   if (!is_loop_opcode (insn->opcode))
6060     return FALSE;
6061
6062   if (insn->ntok <= LOOP_IMMED_OPN)
6063     return FALSE;
6064
6065   expr = &insn->tok[LOOP_IMMED_OPN];
6066
6067   if (expr->X_op != O_symbol)
6068     return FALSE;
6069
6070   symbolP = expr->X_add_symbol;
6071   if (!symbolP)
6072     return FALSE;
6073
6074   if (symbol_get_frag (symbolP) == NULL)
6075     return FALSE;
6076
6077   /* Walk through fragments until we find the target.
6078      If we do not find the target, then this is an invalid loop.  */
6079   for (next_fragP = fragP->fr_next;
6080        next_fragP != NULL;
6081        next_fragP = next_fragP->fr_next)
6082     if (next_fragP == symbol_get_frag (symbolP))
6083       return TRUE;
6084
6085   return FALSE;
6086 }
6087
6088 \f
6089 /* Alignment Functions.  */
6090
6091 size_t
6092 get_text_align_power (target_size)
6093      int target_size;
6094 {
6095   size_t i = 0;
6096   for (i = 0; i < sizeof (size_t); i++)
6097     {
6098       if (target_size <= (1 << i))
6099         return i;
6100     }
6101   as_fatal (_("get_text_align_power: argument too large"));
6102   return 0;
6103 }
6104
6105
6106 addressT
6107 get_text_align_max_fill_size (align_pow, use_nops, use_no_density)
6108      int align_pow;
6109      bfd_boolean use_nops;
6110      bfd_boolean use_no_density;
6111 {
6112   if (!use_nops)
6113     return (1 << align_pow);
6114   if (use_no_density)
6115     return 3 * (1 << align_pow);
6116
6117   return 1 + (1 << align_pow);
6118 }
6119
6120
6121 /* get_text_align_fill_size ()
6122   
6123    Desired alignments:
6124       give the address
6125       target_size = size of next instruction
6126       align_pow = get_text_align_power (target_size).
6127       use_nops = 0
6128       use_no_density = 0;
6129    Loop alignments:
6130       address = current address + loop instruction size;
6131       target_size = 3 (for 2 or 3 byte target)
6132                   = 8 (for 8 byte target)
6133       align_pow = get_text_align_power (target_size);
6134       use_nops = 1
6135       use_no_density = set appropriately
6136    Text alignments:
6137       address = current address + loop instruction size;
6138       target_size = 0
6139       align_pow = get_text_align_power (target_size);
6140       use_nops = 0
6141       use_no_density = 0.  */
6142
6143 addressT
6144 get_text_align_fill_size (address, align_pow, target_size,
6145                           use_nops, use_no_density)
6146      addressT address;
6147      int align_pow;
6148      int target_size;
6149      bfd_boolean use_nops;
6150      bfd_boolean use_no_density;
6151 {
6152   /* Input arguments:
6153
6154      align_pow: log2 (required alignment).
6155
6156      target_size: alignment must allow the new_address and
6157      new_address+target_size-1.
6158
6159      use_nops: if true, then we can only use 2 or 3 byte nops.
6160
6161      use_no_density: if use_nops and use_no_density, we can only use
6162      3-byte nops.
6163
6164      Usually, for non-zero target_size, the align_pow is the power of 2
6165      that is greater than or equal to the target_size.  This handles the
6166      2-byte, 3-byte and 8-byte instructions.  */
6167
6168   size_t alignment = (1 << align_pow);
6169   if (!use_nops)
6170     {
6171       /* This is the easy case.  */
6172       size_t mod;
6173       mod = address % alignment;
6174       if (mod != 0)
6175         mod = alignment - mod;
6176       assert ((address + mod) % alignment == 0);
6177       return mod;
6178     }
6179
6180   /* This is the slightly harder case.  */
6181   assert ((int) alignment >= target_size);
6182   assert (target_size > 0);
6183   if (!use_no_density)
6184     {
6185       size_t i;
6186       for (i = 0; i < alignment * 2; i++)
6187         {
6188           if (i == 1)
6189             continue;
6190           if ((address + i) >> align_pow ==
6191               (address + i + target_size - 1) >> align_pow)
6192             return i;
6193         }
6194     }
6195   else
6196     {
6197       size_t i;
6198
6199       /* Can only fill multiples of 3.  */
6200       for (i = 0; i <= alignment * 3; i += 3)
6201         {
6202           if ((address + i) >> align_pow ==
6203               (address + i + target_size - 1) >> align_pow)
6204             return i;
6205         }
6206     }
6207   assert (0);
6208   return 0;
6209 }
6210
6211
6212 /* This will assert if it is not possible.  */
6213
6214 size_t
6215 get_text_align_nop_count (fill_size, use_no_density)
6216      size_t fill_size;
6217      bfd_boolean use_no_density;
6218 {
6219   size_t count = 0;
6220   if (use_no_density)
6221     {
6222       assert (fill_size % 3 == 0);
6223       return (fill_size / 3);
6224     }
6225
6226   assert (fill_size != 1);      /* Bad argument.  */
6227
6228   while (fill_size > 1)
6229     {
6230       size_t insn_size = 3;
6231       if (fill_size == 2 || fill_size == 4)
6232         insn_size = 2;
6233       fill_size -= insn_size;
6234       count++;
6235     }
6236   assert (fill_size != 1);      /* Bad algorithm.  */
6237   return count;
6238 }
6239
6240
6241 size_t
6242 get_text_align_nth_nop_size (fill_size, n, use_no_density)
6243      size_t fill_size;
6244      size_t n;
6245      bfd_boolean use_no_density;
6246 {
6247   size_t count = 0;
6248
6249   assert (get_text_align_nop_count (fill_size, use_no_density) > n);
6250
6251   if (use_no_density)
6252     return 3;
6253
6254   while (fill_size > 1)
6255     {
6256       size_t insn_size = 3;
6257       if (fill_size == 2 || fill_size == 4)
6258         insn_size = 2;
6259       fill_size -= insn_size;
6260       count++;
6261       if (n + 1 == count)
6262         return insn_size;
6263     }
6264   assert (0);
6265   return 0;
6266 }
6267
6268
6269 /* For the given fragment, find the appropriate address
6270    for it to begin at if we are using NOPs to align it.  */
6271
6272 static addressT
6273 get_noop_aligned_address (fragP, address)
6274      fragS *fragP;
6275      addressT address;
6276 {
6277   static xtensa_insnbuf insnbuf = NULL;
6278   size_t fill_size = 0;
6279
6280   if (!insnbuf)
6281     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
6282
6283   switch (fragP->fr_type)
6284     {
6285     case rs_machine_dependent:
6286       if (fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE)
6287         {
6288           /* The rule is: get next fragment's FIRST instruction.  Find
6289              the smallest number of bytes that need to be added to
6290              ensure that the next fragment's FIRST instruction will fit
6291              in a single word.
6292
6293              E.G.,   2 bytes : 0, 1, 2 mod 4 
6294                      3 bytes: 0, 1 mod 4 
6295
6296              If the FIRST instruction MIGHT be relaxed, 
6297              assume that it will become a 3 byte instruction.  */
6298
6299           int target_insn_size;
6300           xtensa_opcode opcode = next_frag_opcode (fragP);
6301           addressT pre_opcode_bytes;
6302
6303           if (opcode == XTENSA_UNDEFINED)
6304             {
6305               as_bad_where (fragP->fr_file, fragP->fr_line,
6306                             _("invalid opcode for RELAX_ALIGN_NEXT_OPCODE"));
6307               as_fatal (_("cannot continue"));
6308             }
6309
6310           target_insn_size = xtensa_insn_length (xtensa_default_isa, opcode);
6311
6312           pre_opcode_bytes = next_frag_pre_opcode_bytes (fragP);
6313
6314           if (is_loop_opcode (opcode))
6315             {
6316               /* next_fragP should be the loop.  */
6317               const fragS *next_fragP = next_non_empty_frag (fragP);
6318               xtensa_opcode next_opcode = next_frag_opcode (next_fragP);
6319               size_t alignment;
6320
6321               pre_opcode_bytes += target_insn_size;
6322
6323               /* For loops, the alignment depends on the size of the
6324                  instruction following the loop, not the loop instruction.  */
6325               if (next_opcode == XTENSA_UNDEFINED)
6326                 target_insn_size = 3;
6327               else
6328                 {
6329                   target_insn_size =
6330                     xtensa_insn_length (xtensa_default_isa, next_opcode);
6331
6332                   if (target_insn_size == 2)
6333                     target_insn_size = 3;       /* ISA specifies this.  */
6334                 }
6335
6336               /* If it was 8, then we'll need a larger alignment
6337                  for the section.  */
6338               alignment = get_text_align_power (target_insn_size);
6339
6340               /* Is Now_seg valid */
6341               record_alignment (now_seg, alignment);
6342             }
6343           else
6344             as_fatal (_("expected loop opcode in relax align next target"));
6345
6346           fill_size = get_text_align_fill_size
6347             (address + pre_opcode_bytes,
6348              get_text_align_power (target_insn_size),
6349              target_insn_size, TRUE, fragP->tc_frag_data.is_no_density);
6350         }
6351       break;
6352 #if 0
6353     case rs_align:
6354     case rs_align_code:
6355       fill_size = get_text_align_fill_size
6356         (address, fragP->fr_offset, 1, TRUE,
6357          fragP->tc_frag_data.is_no_density);
6358       break;
6359 #endif
6360     default:
6361       as_fatal (_("expected align_code or RELAX_ALIGN_NEXT_OPCODE"));
6362     }
6363
6364   return address + fill_size;
6365 }
6366
6367
6368 /* 3 mechanisms for relaxing an alignment: 
6369    
6370    Align to a power of 2. 
6371    Align so the next fragment's instruction does not cross a word boundary. 
6372    Align the current instruction so that if the next instruction 
6373        were 3 bytes, it would not cross a word boundary. 
6374    
6375    We can align with:
6376
6377    zeros    - This is easy; always insert zeros. 
6378    nops     - 3 and 2 byte instructions 
6379               2 - 2 byte nop 
6380               3 - 3 byte nop 
6381               4 - 2, 2-byte nops 
6382               >=5 : 3 byte instruction + fn(n-3) 
6383    widening - widen previous instructions.  */
6384
6385 static addressT
6386 get_widen_aligned_address (fragP, address)
6387      fragS *fragP;
6388      addressT address;
6389 {
6390   addressT align_pow, new_address, loop_insn_offset;
6391   fragS *next_frag;
6392   int insn_size;
6393   xtensa_opcode opcode, next_opcode;
6394   static xtensa_insnbuf insnbuf = NULL;
6395
6396   if (!insnbuf)
6397     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
6398
6399   if (fragP->fr_type == rs_align || fragP->fr_type == rs_align_code)
6400     {
6401       align_pow = fragP->fr_offset;
6402       new_address = ((address + ((1 << align_pow) - 1))
6403                      << align_pow) >> align_pow;
6404       return new_address;
6405     }
6406
6407   if (fragP->fr_type == rs_machine_dependent)
6408     {
6409       switch (fragP->fr_subtype)
6410         {
6411         case RELAX_DESIRE_ALIGN:
6412
6413           /* The rule is: get the next fragment's FIRST instruction. 
6414              Find the smallest number of bytes needed to be added 
6415              in order to ensure that the next fragment is FIRST 
6416              instruction will fit in a single word. 
6417              i.e.    2 bytes : 0, 1, 2.  mod 4 
6418                      3 bytes: 0, 1 mod 4 
6419              If the FIRST instruction MIGHT be relaxed, 
6420              assume that it will become a 3-byte instruction.  */
6421
6422           insn_size = 3;
6423           /* Check to see if it might be 2 bytes.  */
6424           next_opcode = next_frag_opcode (fragP);
6425           if (next_opcode != XTENSA_UNDEFINED
6426               && xtensa_insn_length (xtensa_default_isa, next_opcode) == 2)
6427             insn_size = 2;
6428
6429           assert (insn_size <= 4);
6430           for (new_address = address; new_address < address + 4; new_address++)
6431             {
6432               if (new_address >> 2 == (new_address + insn_size - 1) >> 2)
6433                 return new_address;
6434             }
6435           as_bad (_("internal error aligning"));
6436           return address;
6437
6438         case RELAX_ALIGN_NEXT_OPCODE:
6439           /* The rule is: get next fragment's FIRST instruction. 
6440              Find the smallest number of bytes needed to be added 
6441              in order to ensure that the next fragment's FIRST 
6442              instruction will fit in a single word. 
6443              i.e.    2 bytes : 0, 1, 2.  mod 4 
6444                      3 bytes: 0, 1 mod 4 
6445              If the FIRST instruction MIGHT be relaxed, 
6446              assume that it will become a 3 byte instruction.  */
6447
6448           opcode = next_frag_opcode (fragP);
6449           if (opcode == XTENSA_UNDEFINED)
6450             {
6451               as_bad_where (fragP->fr_file, fragP->fr_line,
6452                             _("invalid opcode for RELAX_ALIGN_NEXT_OPCODE"));
6453               as_fatal (_("cannot continue"));
6454             }
6455           insn_size = xtensa_insn_length (xtensa_default_isa, opcode);
6456           assert (insn_size <= 4);
6457           assert (is_loop_opcode (opcode));
6458
6459           loop_insn_offset = 0;
6460           next_frag = next_non_empty_frag (fragP);
6461
6462           /* If the loop has been expanded then the loop
6463              instruction could be at an offset from this fragment.  */
6464           if (next_frag->fr_subtype != RELAX_IMMED)
6465             loop_insn_offset = get_expanded_loop_offset (opcode);
6466
6467           for (new_address = address; new_address < address + 4; new_address++)
6468             {
6469               if ((new_address + loop_insn_offset + insn_size) >> 2 ==
6470                   (new_address + loop_insn_offset + insn_size + 2) >> 2)
6471                 return new_address;
6472             }
6473           as_bad (_("internal error aligning"));
6474           return address;
6475
6476         default:
6477           as_bad (_("internal error aligning"));
6478           return address;
6479         }
6480     }
6481   as_bad (_("internal error aligning"));
6482   return address;
6483 }
6484
6485 \f
6486 /* md_relax_frag Hook and Helper Functions.  */
6487
6488 /* Return the number of bytes added to this fragment, given that the
6489    input has been stretched already by "stretch".  */
6490
6491 long
6492 xtensa_relax_frag (fragP, stretch, stretched_p)
6493      fragS *fragP;
6494      long stretch;
6495      int *stretched_p;
6496 {
6497   int unreported = fragP->tc_frag_data.unreported_expansion;
6498   long new_stretch = 0;
6499   char *file_name;
6500   int line, lit_size;
6501
6502   as_where (&file_name, &line);
6503   new_logical_line (fragP->fr_file, fragP->fr_line);
6504
6505   fragP->tc_frag_data.unreported_expansion = 0;
6506
6507   switch (fragP->fr_subtype)
6508     {
6509     case RELAX_ALIGN_NEXT_OPCODE:
6510       /* Always convert.  */
6511       new_stretch = relax_frag_text_align (fragP, stretch);
6512       break;
6513
6514     case RELAX_LOOP_END:
6515       /* Do nothing.  */
6516       break;
6517
6518     case RELAX_LOOP_END_ADD_NOP:
6519       /* Add a NOP and switch to .fill 0.  */
6520       new_stretch = relax_frag_add_nop (fragP);
6521       break;
6522
6523     case RELAX_DESIRE_ALIGN:
6524       /* We REALLY want to change the relaxation order here.  This
6525          should do NOTHING.  The narrowing before it will either align
6526          it or not.  */
6527       break;
6528
6529     case RELAX_LITERAL:
6530     case RELAX_LITERAL_FINAL:
6531       return 0;
6532
6533     case RELAX_LITERAL_NR:
6534       lit_size = 4;
6535       fragP->fr_subtype = RELAX_LITERAL_FINAL;
6536       assert (unreported == lit_size);
6537       memset (&fragP->fr_literal[fragP->fr_fix], 0, 4);
6538       fragP->fr_var -= lit_size;
6539       fragP->fr_fix += lit_size;
6540       new_stretch = 4;
6541       break;
6542
6543     case RELAX_NARROW:
6544       new_stretch = relax_frag_narrow (fragP, stretch);
6545       break;
6546
6547     case RELAX_IMMED:
6548     case RELAX_IMMED_STEP1:
6549     case RELAX_IMMED_STEP2:
6550       /* Place the immediate.  */
6551       new_stretch = relax_frag_immed (now_seg, fragP, stretch,
6552                                       fragP->fr_subtype - RELAX_IMMED,
6553                                       stretched_p);
6554       break;
6555
6556     case RELAX_LITERAL_POOL_BEGIN:
6557     case RELAX_LITERAL_POOL_END:
6558       /* No relaxation required.  */
6559       break;
6560
6561     default:
6562       as_bad (_("bad relaxation state"));
6563     }
6564
6565   new_logical_line (file_name, line);
6566   return new_stretch;
6567 }
6568
6569
6570 static long
6571 relax_frag_text_align (fragP, stretch)
6572      fragS *fragP;
6573      long stretch;
6574 {
6575   addressT old_address, old_next_address, old_size;
6576   addressT new_address, new_next_address, new_size;
6577   addressT growth;
6578
6579   /* Overview of the relaxation procedure for alignment
6580      inside an executable section:
6581     
6582      The old size is stored in the tc_frag_data.text_expansion field.
6583     
6584      Calculate the new address, fix up the text_expansion and
6585      return the growth.  */
6586
6587   /* Calculate the old address of this fragment and the next fragment.  */
6588   old_address = fragP->fr_address - stretch;
6589   old_next_address = (fragP->fr_address - stretch + fragP->fr_fix +
6590                       fragP->tc_frag_data.text_expansion);
6591   old_size = old_next_address - old_address;
6592
6593   /* Calculate the new address of this fragment and the next fragment.  */
6594   new_address = fragP->fr_address;
6595   new_next_address =
6596     get_noop_aligned_address (fragP, fragP->fr_address + fragP->fr_fix);
6597   new_size = new_next_address - new_address;
6598
6599   growth = new_size - old_size;
6600
6601   /* Fix up the text_expansion field and return the new growth.  */
6602   fragP->tc_frag_data.text_expansion += growth;
6603   return growth;
6604 }
6605
6606
6607 /* Add a NOP (i.e., "or a1, a1, a1").  Use the 3-byte one because we
6608    don't know about the availability of density yet.  TODO: When the
6609    flags are stored per fragment, use NOP.N when possible.  */
6610
6611 static long
6612 relax_frag_add_nop (fragP)
6613      fragS *fragP;
6614 {
6615   static xtensa_insnbuf insnbuf = NULL;
6616   TInsn t_insn;
6617   char *nop_buf = fragP->fr_literal + fragP->fr_fix;
6618   int length;
6619   if (!insnbuf)
6620     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
6621
6622   tinsn_init (&t_insn);
6623   t_insn.opcode = xtensa_or_opcode;
6624   assert (t_insn.opcode != XTENSA_UNDEFINED);
6625
6626   t_insn.ntok = 3;
6627   set_expr_const (&t_insn.tok[0], 1);
6628   set_expr_const (&t_insn.tok[1], 1);
6629   set_expr_const (&t_insn.tok[2], 1);
6630
6631   tinsn_to_insnbuf (&t_insn, insnbuf);
6632   fragP->tc_frag_data.is_insn = TRUE;
6633   xtensa_insnbuf_to_chars (xtensa_default_isa, insnbuf, nop_buf);
6634
6635   length = xtensa_insn_length (xtensa_default_isa, t_insn.opcode);
6636   if (fragP->fr_var < length)
6637     {
6638       as_warn (_("fr_var (%ld) < length (%d); ignoring"),
6639                fragP->fr_var, length);
6640       frag_wane (fragP);
6641       return 0;
6642     }
6643
6644   fragP->fr_fix += length;
6645   fragP->fr_var -= length;
6646   frag_wane (fragP);
6647   return length;
6648 }
6649
6650
6651 static long
6652 relax_frag_narrow (fragP, stretch)
6653      fragS *fragP;
6654      long stretch;
6655 {
6656   /* Overview of the relaxation procedure for alignment inside an
6657      executable section: Find the number of widenings required and the
6658      number of nop bytes required. Store the number of bytes ALREADY
6659      widened. If there are enough instructions to widen (must go back
6660      ONLY through NARROW fragments), mark each of the fragments as TO BE
6661      widened, recalculate the fragment addresses.  */
6662
6663   assert (fragP->fr_type == rs_machine_dependent
6664           && fragP->fr_subtype == RELAX_NARROW);
6665
6666   if (!future_alignment_required (fragP, 0))
6667     {
6668       /* If already expanded but no longer needed because of a prior
6669          stretch, it is SAFE to unexpand because the next fragment will
6670          NEVER start at an address > the previous time through the
6671          relaxation.  */
6672       if (fragP->tc_frag_data.text_expansion)
6673         {
6674           if (stretch > 0)
6675             {
6676               fragP->tc_frag_data.text_expansion = 0;
6677               return -1;
6678             }
6679           /* Otherwise we have to live with this bad choice.  */
6680           return 0;
6681         }
6682       return 0;
6683     }
6684
6685   if (fragP->tc_frag_data.text_expansion == 0)
6686     {
6687       fragP->tc_frag_data.text_expansion = 1;
6688       return 1;
6689     }
6690
6691   return 0;
6692 }
6693
6694
6695 static bfd_boolean
6696 future_alignment_required (fragP, stretch)
6697      fragS *fragP;
6698      long stretch;
6699 {
6700   long address = fragP->fr_address + stretch;
6701   int num_widens = 0;
6702   addressT aligned_address;
6703   offsetT desired_diff;
6704
6705   while (fragP)
6706     {
6707       /* Limit this to a small search.  */
6708       if (num_widens > 8)
6709         return FALSE;
6710       address += fragP->fr_fix;
6711
6712       switch (fragP->fr_type)
6713         {
6714         case rs_fill:
6715           address += fragP->fr_offset * fragP->fr_var;
6716           break;
6717
6718         case rs_machine_dependent:
6719           switch (fragP->fr_subtype)
6720             {
6721             case RELAX_NARROW:
6722               /* address += fragP->fr_fix; */
6723               num_widens++;
6724               break;
6725
6726             case RELAX_IMMED:
6727               address += (/* fragP->fr_fix + */
6728                           fragP->tc_frag_data.text_expansion);
6729               break;
6730
6731             case RELAX_ALIGN_NEXT_OPCODE:
6732             case RELAX_DESIRE_ALIGN:
6733               /* address += fragP->fr_fix; */
6734               aligned_address = get_widen_aligned_address (fragP, address);
6735               desired_diff = aligned_address - address;
6736               assert (desired_diff >= 0);
6737               /* If there are enough wideners in between do it.  */
6738               /* return (num_widens == desired_diff); */
6739               if (num_widens == desired_diff)
6740                 return TRUE;
6741               if (fragP->fr_subtype == RELAX_ALIGN_NEXT_OPCODE)
6742                 return FALSE;
6743               break;
6744
6745             default:
6746               return FALSE;
6747             }
6748           break;
6749
6750         default:
6751           return FALSE;
6752         }
6753       fragP = fragP->fr_next;
6754     }
6755
6756   return FALSE;
6757 }
6758
6759
6760 static long
6761 relax_frag_immed (segP, fragP, stretch, min_steps, stretched_p)
6762      segT segP;
6763      fragS *fragP;
6764      long stretch;
6765      int min_steps;
6766      int *stretched_p;
6767 {
6768   static xtensa_insnbuf insnbuf = NULL;
6769   TInsn t_insn;
6770   int old_size;
6771   bfd_boolean negatable_branch = FALSE;
6772   bfd_boolean branch_jmp_to_next = FALSE;
6773   IStack istack;
6774   offsetT frag_offset;
6775   int num_steps;
6776   fragS *lit_fragP;
6777   int num_text_bytes, num_literal_bytes;
6778   int literal_diff, text_diff;
6779
6780   assert (fragP->fr_opcode != NULL);
6781
6782   if (!insnbuf)
6783     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
6784
6785   tinsn_from_chars (&t_insn, fragP->fr_opcode);
6786   tinsn_immed_from_frag (&t_insn, fragP);
6787
6788   negatable_branch = is_negatable_branch (&t_insn);
6789
6790   old_size = xtensa_insn_length (xtensa_default_isa, t_insn.opcode);
6791
6792   if (software_avoid_b_j_loop_end)
6793     branch_jmp_to_next = is_branch_jmp_to_next (&t_insn, fragP);
6794
6795   /* Special case: replace a branch to the next instruction with a NOP.
6796      This is required to work around a hardware bug in T1040.0 and also
6797      serves as an optimization.  */
6798
6799   if (branch_jmp_to_next
6800       && ((old_size == 2) || (old_size == 3))
6801       && !next_frag_is_loop_target (fragP))
6802     return 0;
6803
6804   /* Here is the fun stuff: Get the immediate field from this
6805      instruction.  If it fits, we are done.  If not, find the next
6806      instruction sequence that fits.  */
6807
6808   frag_offset = fragP->fr_opcode - fragP->fr_literal;
6809   istack_init (&istack);
6810   num_steps = xg_assembly_relax (&istack, &t_insn, segP, fragP, frag_offset,
6811                                  min_steps, stretch);
6812   if (num_steps < min_steps)
6813     {
6814       as_fatal (_("internal error: relaxation failed"));
6815       return 0;
6816     }
6817
6818   if (num_steps > RELAX_IMMED_MAXSTEPS)
6819     {
6820       as_fatal (_("internal error: relaxation requires too many steps"));
6821       return 0;
6822     }
6823
6824   fragP->fr_subtype = (int) RELAX_IMMED + num_steps;
6825
6826   /* Figure out the number of bytes needed.  */
6827   lit_fragP = 0;
6828   num_text_bytes = get_num_stack_text_bytes (&istack) - old_size;
6829   num_literal_bytes = get_num_stack_literal_bytes (&istack);
6830   literal_diff = num_literal_bytes - fragP->tc_frag_data.literal_expansion;
6831   text_diff = num_text_bytes - fragP->tc_frag_data.text_expansion;
6832
6833   /* It MUST get larger.  If not, we could get an infinite loop.  */
6834   know (num_text_bytes >= 0);
6835   know (literal_diff >= 0 && text_diff >= 0);
6836
6837   fragP->tc_frag_data.text_expansion = num_text_bytes;
6838   fragP->tc_frag_data.literal_expansion = num_literal_bytes;
6839
6840   /* Find the associated expandable literal for this.  */
6841   if (literal_diff != 0)
6842     {
6843       lit_fragP = fragP->tc_frag_data.literal_frag;
6844       if (lit_fragP)
6845         {
6846           assert (literal_diff == 4);
6847           lit_fragP->tc_frag_data.unreported_expansion += literal_diff;
6848
6849           /* We expect that the literal section state has NOT been
6850              modified yet.  */
6851           assert (lit_fragP->fr_type == rs_machine_dependent
6852                   && lit_fragP->fr_subtype == RELAX_LITERAL);
6853           lit_fragP->fr_subtype = RELAX_LITERAL_NR;
6854
6855           /* We need to mark this section for another iteration
6856              of relaxation.  */
6857           (*stretched_p)++;
6858         }
6859     }
6860
6861   /* This implicitly uses the assumption that a branch is negated
6862      when the size of the output increases by at least 2 bytes.  */
6863
6864   if (negatable_branch && num_text_bytes >= 2)
6865     {
6866       /* If next frag is a loop end, then switch it to add a NOP.  */
6867       update_next_frag_nop_state (fragP);
6868     }
6869
6870   return text_diff;
6871 }
6872
6873 \f
6874 /* md_convert_frag Hook and Helper Functions.  */
6875
6876 void
6877 md_convert_frag (abfd, sec, fragp)
6878      bfd *abfd ATTRIBUTE_UNUSED;
6879      segT sec;
6880      fragS *fragp;
6881 {
6882   char *file_name;
6883   int line;
6884
6885   as_where (&file_name, &line);
6886   new_logical_line (fragp->fr_file, fragp->fr_line);
6887
6888   switch (fragp->fr_subtype)
6889     {
6890     case RELAX_ALIGN_NEXT_OPCODE:
6891       /* Always convert.  */
6892       convert_frag_align_next_opcode (fragp);
6893       break;
6894
6895     case RELAX_DESIRE_ALIGN:
6896       /* Do nothing.  If not aligned already, too bad.  */
6897       break;
6898
6899     case RELAX_LITERAL:
6900     case RELAX_LITERAL_FINAL:
6901       break;
6902
6903     case RELAX_NARROW:
6904       /* No conversion.  */
6905       convert_frag_narrow (fragp);
6906       break;
6907
6908     case RELAX_IMMED:
6909     case RELAX_IMMED_STEP1:
6910     case RELAX_IMMED_STEP2:
6911       /* Place the immediate.  */
6912       convert_frag_immed (sec, fragp, fragp->fr_subtype - RELAX_IMMED);
6913       break;
6914
6915     case RELAX_LITERAL_NR:
6916       if (use_literal_section)
6917         {
6918           /* This should have been handled during relaxation.  When
6919              relaxing a code segment, literals sometimes need to be
6920              added to the corresponding literal segment.  If that
6921              literal segment has already been relaxed, then we end up
6922              in this situation.  Marking the literal segments as data
6923              would make this happen less often (since GAS always relaxes
6924              code before data), but we could still get into trouble if
6925              there are instructions in a segment that is not marked as
6926              containing code.  Until we can implement a better solution,
6927              cheat and adjust the addresses of all the following frags.
6928              This could break subsequent alignments, but the linker's
6929              literal coalescing will do that anyway.  */
6930
6931           fragS *f;
6932           fragp->fr_subtype = RELAX_LITERAL_FINAL;
6933           assert (fragp->tc_frag_data.unreported_expansion == 4);
6934           memset (&fragp->fr_literal[fragp->fr_fix], 0, 4);
6935           fragp->fr_var -= 4;
6936           fragp->fr_fix += 4;
6937           for (f = fragp->fr_next; f; f = f->fr_next)
6938             f->fr_address += 4;
6939         }
6940       else
6941         as_bad (_("invalid relaxation fragment result"));
6942       break;
6943     }
6944
6945   fragp->fr_var = 0;
6946   new_logical_line (file_name, line);
6947 }
6948
6949
6950 void
6951 convert_frag_align_next_opcode (fragp)
6952      fragS *fragp;
6953 {
6954   char *nop_buf;                /* Location for Writing.  */
6955   size_t i;
6956
6957   bfd_boolean use_no_density = fragp->tc_frag_data.is_no_density;
6958   addressT aligned_address;
6959   size_t fill_size, nop_count;
6960
6961   aligned_address = get_noop_aligned_address (fragp, fragp->fr_address +
6962                                               fragp->fr_fix);
6963   fill_size = aligned_address - (fragp->fr_address + fragp->fr_fix);
6964   nop_count = get_text_align_nop_count (fill_size, use_no_density);
6965   nop_buf = fragp->fr_literal + fragp->fr_fix;
6966
6967   for (i = 0; i < nop_count; i++)
6968     {
6969       size_t nop_size;
6970       nop_size = get_text_align_nth_nop_size (fill_size, i, use_no_density);
6971
6972       assemble_nop (nop_size, nop_buf);
6973       nop_buf += nop_size;
6974     }
6975
6976   fragp->fr_fix += fill_size;
6977   fragp->fr_var -= fill_size;
6978 }
6979
6980
6981 static void
6982 convert_frag_narrow (fragP)
6983      fragS *fragP;
6984 {
6985   static xtensa_insnbuf insnbuf = NULL;
6986   TInsn t_insn, single_target;
6987   int size, old_size, diff, error_val;
6988   offsetT frag_offset;
6989
6990   if (fragP->tc_frag_data.text_expansion == 0)
6991     {
6992       /* No conversion.  */
6993       fragP->fr_var = 0;
6994       return;
6995     }
6996
6997   assert (fragP->fr_opcode != NULL);
6998
6999   if (!insnbuf)
7000     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
7001
7002   tinsn_from_chars (&t_insn, fragP->fr_opcode);
7003   tinsn_immed_from_frag (&t_insn, fragP);
7004
7005   /* Just convert it to a wide form....  */
7006   size = 0;
7007   old_size = xtensa_insn_length (xtensa_default_isa, t_insn.opcode);
7008
7009   tinsn_init (&single_target);
7010   frag_offset = fragP->fr_opcode - fragP->fr_literal;
7011
7012   error_val = xg_expand_narrow (&single_target, &t_insn);
7013   if (error_val)
7014     as_bad (_("unable to widen instruction"));
7015
7016   size = xtensa_insn_length (xtensa_default_isa, single_target.opcode);
7017   xg_emit_insn_to_buf (&single_target, fragP->fr_opcode,
7018                        fragP, frag_offset, TRUE);
7019
7020   diff = size - old_size;
7021   assert (diff >= 0);
7022   assert (diff <= fragP->fr_var);
7023   fragP->fr_var -= diff;
7024   fragP->fr_fix += diff;
7025
7026   /* clean it up */
7027   fragP->fr_var = 0;
7028 }
7029
7030
7031 static void
7032 convert_frag_immed (segP, fragP, min_steps)
7033      segT segP;
7034      fragS *fragP;
7035      int min_steps;
7036 {
7037   char *immed_instr = fragP->fr_opcode;
7038   static xtensa_insnbuf insnbuf = NULL;
7039   TInsn orig_t_insn;
7040   bfd_boolean expanded = FALSE;
7041   char *fr_opcode = fragP->fr_opcode;
7042   bfd_boolean branch_jmp_to_next = FALSE;
7043   int size;
7044
7045   assert (fragP->fr_opcode != NULL);
7046
7047   if (!insnbuf)
7048     insnbuf = xtensa_insnbuf_alloc (xtensa_default_isa);
7049
7050   tinsn_from_chars (&orig_t_insn, fragP->fr_opcode);
7051   tinsn_immed_from_frag (&orig_t_insn, fragP);
7052
7053   /* Here is the fun stuff:  Get the immediate field from this
7054      instruction.  If it fits, we're done.  If not, find the next
7055      instruction sequence that fits.  */
7056
7057   if (software_avoid_b_j_loop_end)
7058     branch_jmp_to_next = is_branch_jmp_to_next (&orig_t_insn, fragP);
7059
7060   if (branch_jmp_to_next && !next_frag_is_loop_target (fragP))
7061     {
7062       /* Conversion just inserts a NOP and marks the fix as completed.  */
7063       size = xtensa_insn_length (xtensa_default_isa, orig_t_insn.opcode);
7064       assemble_nop (size, fragP->fr_opcode);
7065       fragP->fr_var = 0;
7066     }
7067   else
7068     {
7069       IStack istack;
7070       int i;
7071       symbolS *lit_sym = NULL;
7072       int total_size = 0;
7073       int old_size;
7074       int diff;
7075       symbolS *gen_label = NULL;
7076       offsetT frag_offset;
7077
7078       /* It does not fit.  Find something that does and 
7079          convert immediately.  */
7080       frag_offset = fragP->fr_opcode - fragP->fr_literal;
7081       istack_init (&istack);
7082       xg_assembly_relax (&istack, &orig_t_insn,
7083                          segP, fragP, frag_offset, min_steps, 0);
7084
7085       old_size = xtensa_insn_length (xtensa_default_isa, orig_t_insn.opcode);
7086
7087       /* Assemble this right inline.  */
7088
7089       /* First, create the mapping from a label name to the REAL label.  */
7090       total_size = 0;
7091       for (i = 0; i < istack.ninsn; i++)
7092         {
7093           TInsn *t_insn = &istack.insn[i];
7094           int size = 0;
7095           fragS *lit_frag;
7096
7097           switch (t_insn->insn_type)
7098             {
7099             case ITYPE_LITERAL:
7100               if (lit_sym != NULL)
7101                 as_bad (_("multiple literals in expansion"));
7102               /* First find the appropriate space in the literal pool.  */
7103               lit_frag = fragP->tc_frag_data.literal_frag;
7104               if (lit_frag == NULL)
7105                 as_bad (_("no registered fragment for literal"));
7106               if (t_insn->ntok != 1)
7107                 as_bad (_("number of literal tokens != 1"));
7108
7109               /* Set the literal symbol and add a fixup.  */
7110               lit_sym = lit_frag->fr_symbol;
7111               break;
7112
7113             case ITYPE_LABEL:
7114               assert (gen_label == NULL);
7115               gen_label = symbol_new (FAKE_LABEL_NAME, now_seg,
7116                                       fragP->fr_opcode - fragP->fr_literal +
7117                                       total_size, fragP);
7118               break;
7119
7120             case ITYPE_INSN:
7121               size = xtensa_insn_length (xtensa_default_isa, t_insn->opcode);
7122               total_size += size;
7123               break;
7124             }
7125         }
7126
7127       total_size = 0;
7128       for (i = 0; i < istack.ninsn; i++)
7129         {
7130           TInsn *t_insn = &istack.insn[i];
7131           fragS *lit_frag;
7132           int size;
7133           segT target_seg;
7134
7135           switch (t_insn->insn_type)
7136             {
7137             case ITYPE_LITERAL:
7138               lit_frag = fragP->tc_frag_data.literal_frag;
7139               /* already checked */
7140               assert (lit_frag != NULL);
7141               assert (lit_sym != NULL);
7142               assert (t_insn->ntok == 1);
7143               /* add a fixup */
7144               target_seg = S_GET_SEGMENT (lit_sym);
7145               assert (target_seg);
7146               fix_new_exp_in_seg (target_seg, 0, lit_frag, 0, 4,
7147                                   &t_insn->tok[0], FALSE, BFD_RELOC_32);
7148               break;
7149
7150             case ITYPE_LABEL:
7151               break;
7152
7153             case ITYPE_INSN:
7154               xg_resolve_labels (t_insn, gen_label);
7155               xg_resolve_literals (t_insn, lit_sym);
7156               size = xtensa_insn_length (xtensa_default_isa, t_insn->opcode);
7157               total_size += size;
7158               xg_emit_insn_to_buf (t_insn, immed_instr, fragP,
7159                                    immed_instr - fragP->fr_literal, TRUE);
7160               immed_instr += size;
7161               break;
7162             }
7163         }
7164
7165       diff = total_size - old_size;
7166       assert (diff >= 0);
7167       if (diff != 0)
7168         expanded = TRUE;
7169       assert (diff <= fragP->fr_var);
7170       fragP->fr_var -= diff;
7171       fragP->fr_fix += diff;
7172     }
7173
7174   /* Clean it up.  */
7175   fragP->fr_var = 0;
7176
7177   /* Check for undefined immediates in LOOP instructions.  */
7178   if (is_loop_opcode (orig_t_insn.opcode))
7179     {
7180       symbolS *sym;
7181       sym = orig_t_insn.tok[1].X_add_symbol;
7182       if (sym != NULL && !S_IS_DEFINED (sym))
7183         {
7184           as_bad (_("unresolved loop target symbol: %s"), S_GET_NAME (sym));
7185           return;
7186         }
7187       sym = orig_t_insn.tok[1].X_op_symbol;
7188       if (sym != NULL && !S_IS_DEFINED (sym))
7189         {
7190           as_bad (_("unresolved loop target symbol: %s"), S_GET_NAME (sym));
7191           return;
7192         }
7193     }
7194
7195   if (expanded && is_loop_opcode (orig_t_insn.opcode))
7196     convert_frag_immed_finish_loop (segP, fragP, &orig_t_insn);
7197
7198   if (expanded && is_direct_call_opcode (orig_t_insn.opcode))
7199     {
7200       /* Add an expansion note on the expanded instruction.  */
7201       fix_new_exp_in_seg (now_seg, 0, fragP, fr_opcode - fragP->fr_literal, 4,
7202                           &orig_t_insn.tok[0], TRUE,
7203                           BFD_RELOC_XTENSA_ASM_EXPAND);
7204
7205     }
7206 }
7207
7208
7209 /* Add a new fix expression into the desired segment.  We have to
7210    switch to that segment to do this.  */
7211
7212 static fixS *
7213 fix_new_exp_in_seg (new_seg, new_subseg,
7214                     frag, where, size, exp, pcrel, r_type)
7215      segT new_seg;
7216      subsegT new_subseg;
7217      fragS *frag;
7218      int where;
7219      int size;
7220      expressionS *exp;
7221      int pcrel;
7222      bfd_reloc_code_real_type r_type;
7223 {
7224   fixS *new_fix;
7225   segT seg = now_seg;
7226   subsegT subseg = now_subseg;
7227   assert (new_seg != 0);
7228   subseg_set (new_seg, new_subseg);
7229
7230   if (r_type == BFD_RELOC_32
7231       && exp->X_add_symbol
7232       && symbol_get_tc (exp->X_add_symbol)->plt == 1)
7233     {
7234       r_type = BFD_RELOC_XTENSA_PLT;
7235     }
7236
7237   new_fix = fix_new_exp (frag, where, size, exp, pcrel, r_type);
7238   subseg_set (seg, subseg);
7239   return new_fix;
7240 }
7241
7242
7243 /* Relax a loop instruction so that it can span loop >256 bytes.  */
7244 /* 
7245                   loop    as, .L1 
7246           .L0: 
7247                   rsr     as, LEND 
7248                   wsr     as, LBEG 
7249                   addi    as, as, lo8(label-.L1) 
7250                   addmi   as, as, mid8(label-.L1) 
7251                   wsr     as, LEND 
7252                   isync 
7253                   rsr     as, LCOUNT 
7254                   addi    as, as, 1 
7255           .L1: 
7256                   <<body>> 
7257           label:                                     */
7258
7259 static void
7260 convert_frag_immed_finish_loop (segP, fragP, t_insn)
7261      segT segP;
7262      fragS *fragP;
7263      TInsn *t_insn;
7264 {
7265   TInsn loop_insn;
7266   TInsn addi_insn;
7267   TInsn addmi_insn;
7268   unsigned long target;
7269   static xtensa_insnbuf insnbuf = NULL;
7270   unsigned int loop_length, loop_length_hi, loop_length_lo;
7271   xtensa_isa isa = xtensa_default_isa;
7272   addressT loop_offset;
7273   addressT addi_offset = 9;
7274   addressT addmi_offset = 12;
7275
7276   if (!insnbuf)
7277     insnbuf = xtensa_insnbuf_alloc (isa);
7278
7279   /* Get the loop offset.  */
7280   loop_offset = get_expanded_loop_offset (t_insn->opcode);
7281   /* Validate that there really is a LOOP at the loop_offset.  */
7282   tinsn_from_chars (&loop_insn, fragP->fr_opcode + loop_offset);
7283
7284   if (!is_loop_opcode (loop_insn.opcode))
7285     {
7286       as_bad_where (fragP->fr_file, fragP->fr_line,
7287                     _("loop relaxation specification does not correspond"));
7288       assert (0);
7289     }
7290   addi_offset += loop_offset;
7291   addmi_offset += loop_offset;
7292
7293   assert (t_insn->ntok == 2);
7294   target = get_expression_value (segP, &t_insn->tok[1]);
7295
7296   know (symbolP);
7297   know (symbolP->sy_frag);
7298   know (!(S_GET_SEGMENT (symbolP) == absolute_section)
7299         || symbol_get_frag (symbolP) == &zero_address_frag);
7300
7301   loop_length = target - (fragP->fr_address + fragP->fr_fix);
7302   loop_length_hi = loop_length & ~0x0ff;
7303   loop_length_lo = loop_length & 0x0ff;
7304   if (loop_length_lo >= 128)
7305     {
7306       loop_length_lo -= 256;
7307       loop_length_hi += 256;
7308     }
7309
7310   /* Because addmi sign-extends the immediate, 'loop_length_hi' can be at most 
7311      32512.  If the loop is larger than that, then we just fail.  */
7312   if (loop_length_hi > 32512)
7313     as_bad_where (fragP->fr_file, fragP->fr_line,
7314                   _("loop too long for LOOP instruction"));
7315
7316   tinsn_from_chars (&addi_insn, fragP->fr_opcode + addi_offset);
7317   assert (addi_insn.opcode == xtensa_addi_opcode);
7318
7319   tinsn_from_chars (&addmi_insn, fragP->fr_opcode + addmi_offset);
7320   assert (addmi_insn.opcode == xtensa_addmi_opcode);
7321
7322   set_expr_const (&addi_insn.tok[2], loop_length_lo);
7323   tinsn_to_insnbuf (&addi_insn, insnbuf);
7324   
7325   fragP->tc_frag_data.is_insn = TRUE;
7326   xtensa_insnbuf_to_chars (isa, insnbuf, fragP->fr_opcode + addi_offset);
7327
7328   set_expr_const (&addmi_insn.tok[2], loop_length_hi);
7329   tinsn_to_insnbuf (&addmi_insn, insnbuf);
7330   xtensa_insnbuf_to_chars (isa, insnbuf, fragP->fr_opcode + addmi_offset);
7331 }
7332
7333
7334 static offsetT
7335 get_expression_value (segP, exp)
7336      segT segP;
7337      expressionS *exp;
7338 {
7339   if (exp->X_op == O_constant)
7340     return exp->X_add_number;
7341   if (exp->X_op == O_symbol)
7342     {
7343       /* Find the fragment.  */
7344       symbolS *sym = exp->X_add_symbol;
7345
7346       assert (S_GET_SEGMENT (sym) == segP
7347               || S_GET_SEGMENT (sym) == absolute_section);
7348
7349       return (S_GET_VALUE (sym) + exp->X_add_number);
7350     }
7351   as_bad (_("invalid expression evaluation type %d"), exp->X_op);
7352   return 0;
7353 }
7354
7355 \f
7356 /* A map that keeps information on a per-subsegment basis.  This is
7357    maintained during initial assembly, but is invalid once the
7358    subsegments are smashed together.  I.E., it cannot be used during
7359    the relaxation.  */
7360
7361 typedef struct subseg_map_struct
7362 {
7363   /* the key */
7364   segT seg;
7365   subsegT subseg;
7366
7367   /* the data */
7368   unsigned flags;
7369
7370   struct subseg_map_struct *next;
7371 } subseg_map;
7372
7373 static subseg_map *sseg_map = NULL;
7374
7375
7376 static unsigned
7377 get_last_insn_flags (seg, subseg)
7378      segT seg;
7379      subsegT subseg;
7380 {
7381   subseg_map *subseg_e;
7382
7383   for (subseg_e = sseg_map; subseg_e != NULL; subseg_e = subseg_e->next)
7384     if (seg == subseg_e->seg && subseg == subseg_e->subseg)
7385       return subseg_e->flags;
7386
7387   return 0;
7388 }
7389
7390
7391 static void
7392 set_last_insn_flags (seg, subseg, fl, val)
7393      segT seg;
7394      subsegT subseg;
7395      unsigned fl;
7396      bfd_boolean val;
7397 {
7398   subseg_map *subseg_e;
7399
7400   for (subseg_e = sseg_map; subseg_e; subseg_e = subseg_e->next)
7401     if (seg == subseg_e->seg && subseg == subseg_e->subseg)
7402       break;
7403
7404   if (!subseg_e)
7405     {
7406       subseg_e = (subseg_map *) xmalloc (sizeof (subseg_map));
7407       memset (subseg_e, 0, sizeof (subseg_map));
7408       subseg_e->seg = seg;
7409       subseg_e->subseg = subseg;
7410       subseg_e->flags = 0;
7411       subseg_e->next = sseg_map;
7412       sseg_map = subseg_e;
7413     }
7414
7415   if (val)
7416     subseg_e->flags |= fl;
7417   else
7418     subseg_e->flags &= ~fl;
7419 }
7420
7421 \f
7422 /* Segment Lists and emit_state Stuff.  */
7423
7424 /* Remove the segment from the global sections list.  */
7425
7426 static void
7427 xtensa_remove_section (sec)
7428      segT sec;
7429 {
7430   /* Handle brain-dead bfd_section_list_remove macro, which
7431      expect the address of the prior section's "next" field, not
7432      just the address of the section to remove.  */
7433
7434   segT *ps_next_ptr = &stdoutput->sections;
7435   while (*ps_next_ptr != sec && *ps_next_ptr != NULL) 
7436     ps_next_ptr = &(*ps_next_ptr)->next;
7437   
7438   assert (*ps_next_ptr != NULL);
7439
7440   bfd_section_list_remove (stdoutput, ps_next_ptr);
7441 }
7442
7443
7444 static void
7445 xtensa_insert_section (after_sec, sec)
7446      segT after_sec;
7447      segT sec;
7448 {
7449   segT *after_sec_next;
7450   if (after_sec == NULL)
7451     after_sec_next = &stdoutput->sections;
7452   else
7453     after_sec_next = &after_sec->next;
7454
7455   bfd_section_list_insert (stdoutput, after_sec_next, sec);
7456 }
7457
7458
7459 static void
7460 xtensa_move_seg_list_to_beginning (head)
7461      seg_list *head;
7462 {
7463   head = head->next;
7464   while (head)
7465     {
7466       segT literal_section = head->seg;
7467
7468       /* Move the literal section to the front of the section list.  */
7469       assert (literal_section);
7470       xtensa_remove_section (literal_section);
7471       xtensa_insert_section (NULL, literal_section);
7472
7473       head = head->next;
7474     }
7475 }
7476
7477
7478 void
7479 xtensa_move_literals ()
7480 {
7481   seg_list *segment;
7482   frchainS *frchain_from, *frchain_to;
7483   fragS *search_frag, *next_frag, *last_frag, *literal_pool, *insert_after;
7484   fragS **frag_splice;
7485   emit_state state;
7486   segT dest_seg;
7487   fixS *fix, *next_fix, **fix_splice;
7488   sym_list *lit;
7489
7490   mark_literal_frags (literal_head->next);
7491   mark_literal_frags (init_literal_head->next);
7492   mark_literal_frags (fini_literal_head->next);
7493
7494   if (use_literal_section)
7495     return;
7496
7497   segment = literal_head->next;
7498   while (segment)
7499     {
7500       frchain_from = seg_info (segment->seg)->frchainP;
7501       search_frag = frchain_from->frch_root;
7502       literal_pool = NULL;
7503       frchain_to = NULL;
7504       frag_splice = &(frchain_from->frch_root);
7505
7506       while (!search_frag->tc_frag_data.literal_frag)
7507         {
7508           assert (search_frag->fr_fix == 0
7509                   || search_frag->fr_type == rs_align);
7510           search_frag = search_frag->fr_next;
7511         }
7512
7513       assert (search_frag->tc_frag_data.literal_frag->fr_subtype
7514               == RELAX_LITERAL_POOL_BEGIN);
7515       xtensa_switch_section_emit_state (&state, segment->seg, 0);
7516
7517       /* Make sure that all the frags in this series are closed, and
7518          that there is at least one left over of zero-size.  This
7519          prevents us from making a segment with an frchain without any
7520          frags in it.  */
7521       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
7522       last_frag = frag_now;
7523       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
7524
7525       while (search_frag != frag_now) 
7526         {
7527           next_frag = search_frag->fr_next;
7528
7529           /* First, move the frag out of the literal section and 
7530              to the appropriate place.  */
7531           if (search_frag->tc_frag_data.literal_frag)
7532             {
7533               literal_pool = search_frag->tc_frag_data.literal_frag;
7534               assert (literal_pool->fr_subtype == RELAX_LITERAL_POOL_BEGIN);
7535               /* Note that we set this fr_var to be a fix 
7536                  chain when we created the literal pool location
7537                  as RELAX_LITERAL_POOL_BEGIN.  */
7538               frchain_to = (frchainS *) literal_pool->fr_var;
7539             }
7540           insert_after = literal_pool;
7541           
7542           while (insert_after->fr_next->fr_subtype != RELAX_LITERAL_POOL_END)
7543             insert_after = insert_after->fr_next;
7544
7545           dest_seg = (segT) insert_after->fr_next->fr_var;
7546           
7547           *frag_splice = next_frag;
7548           search_frag->fr_next = insert_after->fr_next;
7549           insert_after->fr_next = search_frag;
7550           search_frag->tc_frag_data.lit_seg = dest_seg;
7551
7552           /* Now move any fixups associated with this frag to the
7553              right section.  */
7554           fix = frchain_from->fix_root;
7555           fix_splice = &(frchain_from->fix_root);
7556           while (fix)
7557             {
7558               next_fix = fix->fx_next;
7559               if (fix->fx_frag == search_frag)
7560                 {
7561                   *fix_splice = next_fix;
7562                   fix->fx_next = frchain_to->fix_root;
7563                   frchain_to->fix_root = fix;
7564                   if (frchain_to->fix_tail == NULL)
7565                     frchain_to->fix_tail = fix;
7566                 }
7567               else
7568                 fix_splice = &(fix->fx_next);
7569               fix = next_fix;
7570             }
7571           search_frag = next_frag;
7572         }
7573
7574       if (frchain_from->fix_root != NULL)
7575         {
7576           frchain_from = seg_info (segment->seg)->frchainP;
7577           as_warn (_("fixes not all moved from %s"), segment->seg->name);
7578
7579           assert (frchain_from->fix_root == NULL);
7580         }
7581       frchain_from->fix_tail = NULL;
7582       xtensa_restore_emit_state (&state);
7583       segment = segment->next;
7584     }
7585
7586   /* Now fix up the SEGMENT value for all the literal symbols.  */
7587   for (lit = literal_syms; lit; lit = lit->next)
7588     {
7589       symbolS *lit_sym = lit->sym;
7590       segT dest_seg = symbol_get_frag (lit_sym)->tc_frag_data.lit_seg;
7591       S_SET_SEGMENT (lit_sym, dest_seg);
7592     }
7593 }
7594
7595
7596 /* Walk over all the frags for segments in a list and mark them as
7597    containing literals.  As clunky as this is, we can't rely on frag_var
7598    and frag_variant to get called in all situations.  */
7599
7600 static void
7601 mark_literal_frags (segment)
7602      seg_list *segment;
7603 {
7604   frchainS *frchain_from;
7605   fragS *search_frag;
7606
7607   while (segment)
7608     {
7609       frchain_from = seg_info (segment->seg)->frchainP;
7610       search_frag = frchain_from->frch_root;
7611       while (search_frag) 
7612         {
7613           search_frag->tc_frag_data.is_literal = TRUE;
7614           search_frag = search_frag->fr_next;
7615         }
7616       segment = segment->next;
7617     }
7618 }
7619
7620
7621 static void
7622 xtensa_reorder_seg_list (head, after)
7623      seg_list *head;
7624      segT after;
7625 {
7626   /* Move all of the sections in the section list to come
7627      after "after" in the gnu segment list.  */
7628
7629   head = head->next;
7630   while (head)
7631     {
7632       segT literal_section = head->seg;
7633
7634       /* Move the literal section after "after".  */
7635       assert (literal_section);
7636       if (literal_section != after)
7637         {
7638           xtensa_remove_section (literal_section);
7639           xtensa_insert_section (after, literal_section);
7640         }
7641
7642       head = head->next;
7643     }
7644 }
7645
7646
7647 /* Push all the literal segments to the end of the gnu list.  */
7648
7649 void
7650 xtensa_reorder_segments ()
7651 {
7652   segT sec;
7653   segT last_sec;
7654   int old_count = 0;
7655   int new_count = 0;
7656
7657   for (sec = stdoutput->sections; sec != NULL; sec = sec->next)
7658     old_count++;
7659
7660   /* Now that we have the last section, push all the literal
7661      sections to the end.  */
7662   last_sec = get_last_sec ();
7663   xtensa_reorder_seg_list (literal_head, last_sec);
7664   xtensa_reorder_seg_list (init_literal_head, last_sec);
7665   xtensa_reorder_seg_list (fini_literal_head, last_sec);
7666
7667   /* Now perform the final error check.  */
7668   for (sec = stdoutput->sections; sec != NULL; sec = sec->next)
7669     new_count++;
7670   assert (new_count == old_count);
7671 }
7672
7673
7674 segT
7675 get_last_sec ()
7676 {
7677   segT last_sec = stdoutput->sections;
7678   while (last_sec->next != NULL)
7679     last_sec = last_sec->next;
7680
7681   return last_sec;
7682 }
7683
7684
7685 /* Change the emit state (seg, subseg, and frag related stuff) to the
7686    correct location.  Return a emit_state which can be passed to
7687    xtensa_restore_emit_state to return to current fragment.  */
7688
7689 void
7690 xtensa_switch_to_literal_fragment (result)
7691      emit_state *result;
7692 {
7693   /* When we mark a literal pool location, we want to put a frag in
7694      the literal pool that points to it.  But to do that, we want to
7695      switch_to_literal_fragment.  But literal sections don't have
7696      literal pools, so their location is always null, so we would
7697      recurse forever.  This is kind of hacky, but it works.  */
7698
7699   static bfd_boolean recursive = FALSE;
7700   fragS *pool_location = get_literal_pool_location (now_seg);
7701   bfd_boolean is_init = 
7702     (now_seg && !strcmp (segment_name (now_seg), INIT_SECTION_NAME));
7703
7704   bfd_boolean is_fini = 
7705     (now_seg && !strcmp (segment_name (now_seg), FINI_SECTION_NAME));
7706   
7707
7708   if (pool_location == NULL 
7709       && !use_literal_section 
7710       && !recursive
7711       && !is_init && ! is_fini)
7712     {
7713       as_warn (_("inlining literal pool; "
7714                  "specify location with .literal_position."));
7715       recursive = TRUE;
7716       xtensa_mark_literal_pool_location ();
7717       recursive = FALSE;
7718     }
7719
7720   /* Special case: If we are in the ".fini" or ".init" section, then
7721      we will ALWAYS be generating to the ".fini.literal" and
7722      ".init.literal" sections.  */
7723
7724   if (is_init)
7725     {
7726       cache_literal_section (init_literal_head,
7727                              default_lit_sections.init_lit_seg_name,
7728                              &default_lit_sections.init_lit_seg);
7729       xtensa_switch_section_emit_state (result,
7730                                         default_lit_sections.init_lit_seg, 0);
7731     }
7732   else if (is_fini)
7733     {
7734       cache_literal_section (fini_literal_head,
7735                              default_lit_sections.fini_lit_seg_name,
7736                              &default_lit_sections.fini_lit_seg);
7737       xtensa_switch_section_emit_state (result,
7738                                         default_lit_sections.fini_lit_seg, 0);
7739     }
7740   else 
7741     {
7742       cache_literal_section (literal_head,
7743                              default_lit_sections.lit_seg_name,
7744                              &default_lit_sections.lit_seg);
7745       xtensa_switch_section_emit_state (result,
7746                                         default_lit_sections.lit_seg, 0);
7747     }
7748
7749   if (!use_literal_section &&
7750       !is_init && !is_fini &&
7751       get_literal_pool_location (now_seg) != pool_location)
7752     {
7753       /* Close whatever frag is there.  */
7754       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
7755       frag_now->tc_frag_data.literal_frag = pool_location;
7756       frag_variant (rs_fill, 0, 0, 0, NULL, 0, NULL);
7757     }
7758
7759   /* Do a 4 byte align here.  */
7760   frag_align (2, 0, 0);
7761 }
7762
7763
7764 /* Call this function before emitting data into the literal section.
7765    This is a helper function for xtensa_switch_to_literal_fragment.
7766    This is similar to a .section new_now_seg subseg. */
7767
7768 void
7769 xtensa_switch_section_emit_state (state, new_now_seg, new_now_subseg)
7770      emit_state *state;
7771      segT new_now_seg;
7772      subsegT new_now_subseg;
7773 {
7774   state->name = now_seg->name;
7775   state->now_seg = now_seg;
7776   state->now_subseg = now_subseg;
7777   state->generating_literals = generating_literals;
7778   generating_literals++;
7779   subseg_new (segment_name (new_now_seg), new_now_subseg);
7780 }
7781
7782
7783 /* Use to restore the emitting into the normal place.  */
7784
7785 void
7786 xtensa_restore_emit_state (state)
7787      emit_state *state;
7788 {
7789   generating_literals = state->generating_literals;
7790   subseg_new (state->name, state->now_subseg);
7791 }
7792
7793
7794 /* Get a segment of a given name.  If the segment is already
7795    present, return it; otherwise, create a new one.  */
7796
7797 static void
7798 cache_literal_section (head, name, seg)
7799      seg_list *head;
7800      const char *name;
7801      segT *seg;
7802 {
7803   segT current_section = now_seg;
7804   int current_subsec = now_subseg;
7805
7806   if (*seg != 0)
7807     return;
7808   *seg = retrieve_literal_seg (head, name);
7809   subseg_set (current_section, current_subsec);
7810 }
7811
7812
7813 /* Get a segment of a given name.  If the segment is already
7814    present, return it; otherwise, create a new one.  */
7815
7816 static segT
7817 retrieve_literal_seg (head, name)
7818      seg_list *head;
7819      const char *name;
7820 {
7821   segT ret = 0;
7822
7823   assert (head);
7824
7825   ret = seg_present (name);
7826   if (!ret)
7827     {
7828       ret = subseg_new (name, (subsegT) 0);
7829       add_seg_list (head, ret);
7830       bfd_set_section_flags (stdoutput, ret, SEC_HAS_CONTENTS |
7831                              SEC_READONLY | SEC_ALLOC | SEC_LOAD | SEC_CODE);
7832       bfd_set_section_alignment (stdoutput, ret, 2);
7833     }
7834
7835   return ret;
7836 }
7837
7838
7839 /* Return a segment of a given name if it is present.  */
7840
7841 static segT
7842 seg_present (name)
7843      const char *name;
7844 {
7845   segT seg;
7846   seg = stdoutput->sections;
7847
7848   while (seg)
7849     {
7850       if (!strcmp (segment_name (seg), name))
7851         return seg;
7852       seg = seg->next;
7853     }
7854
7855   return 0;
7856 }
7857
7858
7859 /* Add a segment to a segment list.  */
7860
7861 static void
7862 add_seg_list (head, seg)
7863      seg_list *head;
7864      segT seg;
7865 {
7866   seg_list *n;
7867   n = (seg_list *) xmalloc (sizeof (seg_list));
7868   assert (n);
7869
7870   n->seg = seg;
7871   n->next = head->next;
7872   head->next = n;
7873 }
7874
7875 \f
7876 /* Set up Property Tables after Relaxation.  */
7877
7878 #define XTENSA_INSN_SEC_NAME ".xt.insn"
7879 #define XTENSA_LIT_SEC_NAME ".xt.lit"
7880
7881 void
7882 xtensa_post_relax_hook ()
7883 {
7884   xtensa_move_seg_list_to_beginning (literal_head);
7885   xtensa_move_seg_list_to_beginning (init_literal_head);
7886   xtensa_move_seg_list_to_beginning (fini_literal_head);
7887
7888   xtensa_create_property_segments (get_frag_is_insn,
7889                                    XTENSA_INSN_SEC_NAME,
7890                                    xt_insn_sec);
7891   xtensa_create_property_segments (get_frag_is_literal,
7892                                    XTENSA_LIT_SEC_NAME,
7893                                    xt_literal_sec);
7894 }
7895
7896
7897 static bfd_boolean
7898 get_frag_is_literal (fragP)
7899      const fragS *fragP;
7900 {
7901   assert (fragP != NULL);
7902   return (fragP->tc_frag_data.is_literal);
7903 }
7904  
7905
7906 static bfd_boolean
7907 get_frag_is_insn (fragP)
7908      const fragS *fragP;
7909 {
7910   assert (fragP != NULL);
7911   return (fragP->tc_frag_data.is_insn);
7912 }
7913
7914
7915 static void
7916 xtensa_create_property_segments (property_function, section_name_base, 
7917                                  sec_type)
7918      frag_predicate property_function;
7919      const char * section_name_base;
7920      xt_section_type sec_type;
7921 {
7922   segT *seclist;
7923
7924   /* Walk over all of the current segments.
7925      Walk over each fragment
7926       For each fragment that has instructions
7927       Build an instruction record (append where possible).  */
7928
7929   for (seclist = &stdoutput->sections;
7930        seclist && *seclist;
7931        seclist = &(*seclist)->next)
7932     {
7933       segT sec = *seclist;
7934       if (section_has_property (sec, property_function))
7935         {
7936           char *property_section_name =
7937             xtensa_get_property_section_name (sec, section_name_base);
7938           segT insn_sec = retrieve_xtensa_section (property_section_name);
7939           segment_info_type *xt_seg_info = retrieve_segment_info (insn_sec);
7940           xtensa_block_info **xt_blocks = 
7941             &xt_seg_info->tc_segment_info_data.blocks[sec_type];
7942           /* Walk over all of the frchains here and add new sections.  */
7943           add_xt_block_frags (sec, insn_sec, xt_blocks, property_function);
7944         }
7945     }
7946
7947   /* Now we fill them out....  */
7948
7949   for (seclist = &stdoutput->sections;
7950        seclist && *seclist;
7951        seclist = &(*seclist)->next)
7952     {
7953       segment_info_type *seginfo;
7954       xtensa_block_info *block;
7955       segT sec = *seclist;
7956       seginfo = seg_info (sec);
7957       block = seginfo->tc_segment_info_data.blocks[sec_type];
7958
7959       if (block)
7960         {
7961           xtensa_block_info *cur_block;
7962           /* This is a section with some data.  */
7963           size_t num_recs = 0;
7964           size_t rec_size;
7965
7966           for (cur_block = block; cur_block; cur_block = cur_block->next)
7967             num_recs++;
7968
7969           rec_size = num_recs * 8;
7970           bfd_set_section_size (stdoutput, sec, rec_size);
7971
7972           /* In order to make this work with the assembler, we have to
7973              build some frags and then build the "fixups" for it.  It
7974              would be easier to just set the contents then set the
7975              arlents.  */
7976
7977           if (num_recs)
7978             {
7979               /* Allocate a fragment and leak it.  */
7980               fragS *fragP;
7981               size_t frag_size;
7982               fixS *fixes;
7983               frchainS *frchainP;
7984               size_t i;
7985               char *frag_data;
7986
7987               frag_size = sizeof (fragS) + rec_size;
7988               fragP = (fragS *) xmalloc (frag_size);
7989
7990               memset (fragP, 0, frag_size);
7991               fragP->fr_address = 0;
7992               fragP->fr_next = NULL;
7993               fragP->fr_fix = rec_size;
7994               fragP->fr_var = 0;
7995               fragP->fr_type = rs_fill;
7996               /* the rest are zeros */
7997
7998               frchainP = seginfo->frchainP;
7999               frchainP->frch_root = fragP;
8000               frchainP->frch_last = fragP;
8001
8002               fixes = (fixS *) xmalloc (sizeof (fixS) * num_recs);
8003               memset (fixes, 0, sizeof (fixS) * num_recs);
8004
8005               seginfo->fix_root = fixes;
8006               seginfo->fix_tail = &fixes[num_recs - 1];
8007               cur_block = block;
8008               frag_data = &fragP->fr_literal[0];
8009               for (i = 0; i < num_recs; i++)
8010                 {
8011                   fixS *fix = &fixes[i];
8012                   assert (cur_block);
8013
8014                   /* Write the fixup.  */
8015                   if (i != num_recs - 1)
8016                     fix->fx_next = &fixes[i + 1];
8017                   else
8018                     fix->fx_next = NULL;
8019                   fix->fx_size = 4;
8020                   fix->fx_done = 0;
8021                   fix->fx_frag = fragP;
8022                   fix->fx_where = i * 8;
8023                   fix->fx_addsy = section_symbol (cur_block->sec);
8024                   fix->fx_offset = cur_block->offset;
8025                   fix->fx_r_type = BFD_RELOC_32;
8026                   fix->fx_file = "Internal Assembly";
8027                   fix->fx_line = 0;
8028
8029                   /* Write the length.  */
8030                   md_number_to_chars (&frag_data[4 + 8 * i],
8031                                       cur_block->size, 4);
8032                   cur_block = cur_block->next;
8033                 }
8034             }
8035         }
8036     }
8037 }
8038
8039
8040 segment_info_type *
8041 retrieve_segment_info (seg)
8042      segT seg;
8043 {
8044   segment_info_type *seginfo;
8045   seginfo = (segment_info_type *) bfd_get_section_userdata (stdoutput, seg);
8046   if (!seginfo)
8047     {
8048       frchainS *frchainP;
8049
8050       seginfo = (segment_info_type *) xmalloc (sizeof (*seginfo));
8051       memset ((PTR) seginfo, 0, sizeof (*seginfo));
8052       seginfo->fix_root = NULL;
8053       seginfo->fix_tail = NULL;
8054       seginfo->bfd_section = seg;
8055       seginfo->sym = 0;
8056       /* We will not be dealing with these, only our special ones.  */
8057 #if 0
8058       if (seg == bfd_abs_section_ptr)
8059         abs_seg_info = seginfo;
8060       else if (seg == bfd_und_section_ptr)
8061         und_seg_info = seginfo;
8062       else
8063 #endif
8064         bfd_set_section_userdata (stdoutput, seg, (PTR) seginfo);
8065 #if 0
8066       seg_fix_rootP = &segment_info[seg].fix_root;
8067       seg_fix_tailP = &segment_info[seg].fix_tail;
8068 #endif
8069
8070       frchainP = (frchainS *) xmalloc (sizeof (frchainS));
8071       frchainP->frch_root = NULL;
8072       frchainP->frch_last = NULL;
8073       frchainP->frch_next = NULL;
8074       frchainP->frch_seg = seg;
8075       frchainP->frch_subseg = 0;
8076       frchainP->fix_root = NULL;
8077       frchainP->fix_tail = NULL;
8078       /* Do not init the objstack.  */
8079       /* obstack_begin (&frchainP->frch_obstack, chunksize); */
8080       /* frchainP->frch_frag_now = fragP; */
8081       frchainP->frch_frag_now = NULL;
8082
8083       seginfo->frchainP = frchainP;
8084     }
8085
8086   return seginfo;
8087 }
8088
8089
8090 segT
8091 retrieve_xtensa_section (sec_name)
8092      char *sec_name;
8093 {
8094   bfd *abfd = stdoutput;
8095   flagword flags, out_flags, link_once_flags;
8096   segT s;
8097
8098   flags = bfd_get_section_flags (abfd, now_seg);
8099   link_once_flags = (flags & SEC_LINK_ONCE);
8100   if (link_once_flags)
8101     link_once_flags |= (flags & SEC_LINK_DUPLICATES);
8102   out_flags = (SEC_RELOC | SEC_HAS_CONTENTS | SEC_READONLY | link_once_flags);
8103
8104   s = bfd_make_section_old_way (abfd, sec_name);
8105   if (s == NULL)
8106     as_bad (_("could not create section %s"), sec_name);
8107   if (!bfd_set_section_flags (abfd, s, out_flags))
8108     as_bad (_("invalid flag combination on section %s"), sec_name);
8109
8110   return s;
8111 }
8112
8113
8114 bfd_boolean
8115 section_has_property (sec, property_function)
8116      segT sec;
8117      frag_predicate property_function;
8118 {
8119   segment_info_type *seginfo = seg_info (sec);
8120   fragS *fragP;
8121
8122   if (seginfo && seginfo->frchainP)
8123     {
8124       for (fragP = seginfo->frchainP->frch_root; fragP; fragP = fragP->fr_next)
8125         {
8126           if (property_function (fragP)
8127               && (fragP->fr_type != rs_fill || fragP->fr_fix != 0))
8128             return TRUE;
8129         }
8130     }
8131   return FALSE;
8132 }
8133
8134
8135 /* Two types of block sections exist right now: literal and insns.  */
8136
8137 void
8138 add_xt_block_frags (sec, xt_block_sec, xt_block, property_function)
8139      segT sec;
8140      segT xt_block_sec;
8141      xtensa_block_info **xt_block;
8142      frag_predicate property_function;
8143 {
8144   segment_info_type *seg_info;
8145   segment_info_type *xt_seg_info;
8146   bfd_vma seg_offset;
8147   fragS *fragP;
8148
8149   xt_seg_info = retrieve_segment_info (xt_block_sec);
8150   seg_info = retrieve_segment_info (sec);
8151
8152   /* Build it if needed.  */
8153   while (*xt_block != NULL)
8154     xt_block = &(*xt_block)->next;
8155   /* We are either at NULL at the beginning or at the end.  */
8156
8157   /* Walk through the frags.  */
8158   seg_offset = 0;
8159
8160   if (seg_info->frchainP)
8161     {
8162       for (fragP = seg_info->frchainP->frch_root;
8163            fragP;
8164            fragP = fragP->fr_next)
8165         {
8166           if (property_function (fragP)
8167               && (fragP->fr_type != rs_fill || fragP->fr_fix != 0))
8168             {
8169               if (*xt_block != NULL)
8170                 {
8171                   if ((*xt_block)->offset + (*xt_block)->size
8172                       == fragP->fr_address)
8173                     (*xt_block)->size += fragP->fr_fix;
8174                   else
8175                     xt_block = &((*xt_block)->next);
8176                 }
8177               if (*xt_block == NULL)
8178                 {
8179                   xtensa_block_info *new_block = (xtensa_block_info *)
8180                     xmalloc (sizeof (xtensa_block_info));
8181                   new_block->sec = sec;
8182                   new_block->offset = fragP->fr_address;
8183                   new_block->size = fragP->fr_fix;
8184                   new_block->next = NULL;
8185                   *xt_block = new_block;
8186                 }
8187             }
8188         }
8189     }
8190 }
8191
8192 \f
8193 /* Instruction Stack Functions (from "xtensa-istack.h").  */
8194
8195 void
8196 istack_init (stack)
8197      IStack *stack;
8198 {
8199   memset (stack, 0, sizeof (IStack));
8200   stack->ninsn = 0;
8201 }
8202
8203
8204 bfd_boolean
8205 istack_empty (stack)
8206      IStack *stack;
8207 {
8208   return (stack->ninsn == 0);
8209 }
8210
8211
8212 bfd_boolean
8213 istack_full (stack)
8214      IStack *stack;
8215 {
8216   return (stack->ninsn == MAX_ISTACK);
8217 }
8218
8219
8220 /* Return a pointer to the top IStack entry.
8221    It is an error to call this if istack_empty () is true. */
8222
8223 TInsn *
8224 istack_top (stack)
8225      IStack *stack;
8226 {
8227   int rec = stack->ninsn - 1;
8228   assert (!istack_empty (stack));
8229   return &stack->insn[rec];
8230 }
8231
8232
8233 /* Add a new TInsn to an IStack.
8234    It is an error to call this if istack_full () is true.  */
8235
8236 void
8237 istack_push (stack, insn)
8238      IStack *stack;
8239      TInsn *insn;
8240 {
8241   int rec = stack->ninsn;
8242   assert (!istack_full (stack));
8243   tinsn_copy (&stack->insn[rec], insn);
8244   stack->ninsn++;
8245 }
8246
8247
8248 /* Clear space for the next TInsn on the IStack and return a pointer
8249    to it.  It is an error to call this if istack_full () is true.  */
8250
8251 TInsn *
8252 istack_push_space (stack)
8253      IStack *stack;
8254 {
8255   int rec = stack->ninsn;
8256   TInsn *insn;
8257   assert (!istack_full (stack));
8258   insn = &stack->insn[rec];
8259   memset (insn, 0, sizeof (TInsn));
8260   stack->ninsn++;
8261   return insn;
8262 }
8263
8264
8265 /* Remove the last pushed instruction.  It is an error to call this if
8266    istack_empty () returns true.  */
8267
8268 void
8269 istack_pop (stack)
8270      IStack *stack;
8271 {
8272   int rec = stack->ninsn - 1;
8273   assert (!istack_empty (stack));
8274   stack->ninsn--;
8275   memset (&stack->insn[rec], 0, sizeof (TInsn));
8276 }
8277
8278 \f
8279 /* TInsn functions.  */
8280
8281 void
8282 tinsn_init (dst)
8283      TInsn *dst;
8284 {
8285   memset (dst, 0, sizeof (TInsn));
8286 }
8287
8288
8289 void
8290 tinsn_copy (dst, src)
8291      TInsn *dst;
8292      const TInsn *src;
8293 {
8294   tinsn_init (dst);
8295   memcpy (dst, src, sizeof (TInsn));
8296 }
8297
8298
8299 /* Get the ``num''th token of the TInsn.
8300    It is illegal to call this if num > insn->ntoks.  */
8301
8302 expressionS *
8303 tinsn_get_tok (insn, num)
8304      TInsn *insn;
8305      int num;
8306 {
8307   assert (num < insn->ntok);
8308   return &insn->tok[num];
8309 }
8310
8311
8312 /* Return true if ANY of the operands in the insn are symbolic.  */
8313
8314 static bfd_boolean
8315 tinsn_has_symbolic_operands (insn)
8316      const TInsn *insn;
8317 {
8318   int i;
8319   int n = insn->ntok;
8320
8321   assert (insn->insn_type == ITYPE_INSN);
8322
8323   for (i = 0; i < n; ++i)
8324     {
8325       switch (insn->tok[i].X_op)
8326         {
8327         case O_register:
8328         case O_constant:
8329           break;
8330         default:
8331           return TRUE;
8332         }
8333     }
8334   return FALSE;
8335 }
8336
8337
8338 bfd_boolean
8339 tinsn_has_invalid_symbolic_operands (insn)
8340      const TInsn *insn;
8341 {
8342   int i;
8343   int n = insn->ntok;
8344
8345   assert (insn->insn_type == ITYPE_INSN);
8346
8347   for (i = 0; i < n; ++i)
8348     {
8349       switch (insn->tok[i].X_op)
8350         {
8351         case O_register:
8352         case O_constant:
8353           break;
8354         default:
8355           if (i == get_relaxable_immed (insn->opcode))
8356             break;
8357           as_bad (_("invalid symbolic operand %d on '%s'"),
8358                   i, xtensa_opcode_name (xtensa_default_isa, insn->opcode));
8359           return TRUE;
8360         }
8361     }
8362   return FALSE;
8363 }
8364
8365
8366 /* For assembly code with complex expressions (e.g. subtraction),
8367    we have to build them in the literal pool so that
8368    their results are calculated correctly after relaxation.
8369    The relaxation only handles expressions that
8370    boil down to SYMBOL + OFFSET.  */
8371
8372 static bfd_boolean
8373 tinsn_has_complex_operands (insn)
8374      const TInsn *insn;
8375 {
8376   int i;
8377   int n = insn->ntok;
8378   assert (insn->insn_type == ITYPE_INSN);
8379   for (i = 0; i < n; ++i)
8380     {
8381       switch (insn->tok[i].X_op)
8382         {
8383         case O_register:
8384         case O_constant:
8385         case O_symbol:
8386           break;
8387         default:
8388           return TRUE;
8389         }
8390     }
8391   return FALSE;
8392 }
8393
8394
8395 /* Convert the constant operands in the t_insn to insnbuf.
8396    Return true if there is a symbol in the immediate field.
8397
8398    Before this is called, 
8399    1) the number of operands are correct
8400    2) the t_insn is a ITYPE_INSN
8401    3) ONLY the relaxable_ is built
8402    4) All operands are O_constant, O_symbol.  All constants fit
8403    The return value tells whether there are any remaining O_symbols.  */
8404
8405 static bfd_boolean
8406 tinsn_to_insnbuf (t_insn, insnbuf)
8407      TInsn *t_insn;
8408      xtensa_insnbuf insnbuf;
8409 {
8410   xtensa_isa isa = xtensa_default_isa;
8411   xtensa_opcode opcode = t_insn->opcode;
8412   bfd_boolean has_fixup = FALSE;
8413   int noperands = xtensa_num_operands (isa, opcode);
8414   int i;
8415   uint32 opnd_value;
8416   char *file_name;
8417   int line;
8418
8419   assert (t_insn->insn_type == ITYPE_INSN);
8420   if (noperands != t_insn->ntok)
8421     as_fatal (_("operand number mismatch"));
8422
8423   xtensa_encode_insn (isa, opcode, insnbuf);
8424
8425   for (i = 0; i < noperands; ++i)
8426     {
8427       expressionS *expr = &t_insn->tok[i];
8428       xtensa_operand operand = xtensa_get_operand (isa, opcode, i);
8429       switch (expr->X_op)
8430         {
8431         case O_register:
8432           /* The register number has already been checked in  
8433              expression_maybe_register, so we don't need to check here.  */
8434           opnd_value = expr->X_add_number;
8435           (void) xtensa_operand_encode (operand, &opnd_value);
8436           xtensa_operand_set_field (operand, insnbuf, opnd_value);
8437           break;
8438
8439         case O_constant:
8440           as_where (&file_name, &line);
8441           /* It is a constant and we called this function,
8442              then we have to try to fit it.  */
8443           xtensa_insnbuf_set_operand (insnbuf, opcode, operand,
8444                                       expr->X_add_number, file_name, line);
8445           break;
8446
8447         case O_symbol:
8448         default:
8449           has_fixup = TRUE;
8450           break;
8451         }
8452     }
8453   return has_fixup;
8454 }
8455
8456
8457 /* Check the instruction arguments.  Return true on failure.  */
8458
8459 bfd_boolean
8460 tinsn_check_arguments (insn)
8461      const TInsn *insn;
8462 {
8463   xtensa_isa isa = xtensa_default_isa;
8464   xtensa_opcode opcode = insn->opcode;
8465
8466   if (opcode == XTENSA_UNDEFINED)
8467     {
8468       as_bad (_("invalid opcode"));
8469       return TRUE;
8470     }
8471
8472   if (xtensa_num_operands (isa, opcode) > insn->ntok)
8473     {
8474       as_bad (_("too few operands"));
8475       return TRUE;
8476     }
8477
8478   if (xtensa_num_operands (isa, opcode) < insn->ntok)
8479     {
8480       as_bad (_("too many operands"));
8481       return TRUE;
8482     }
8483   return FALSE;
8484 }
8485
8486
8487 /* Load an instruction from its encoded form.  */
8488
8489 static void
8490 tinsn_from_chars (t_insn, f)
8491      TInsn *t_insn;
8492      char *f;
8493 {
8494   static xtensa_insnbuf insnbuf = NULL;
8495   int i;
8496   xtensa_opcode opcode;
8497   xtensa_isa isa = xtensa_default_isa;
8498
8499   if (!insnbuf)
8500     insnbuf = xtensa_insnbuf_alloc (isa);
8501
8502   xtensa_insnbuf_from_chars (isa, insnbuf, f);
8503   opcode = xtensa_decode_insn (isa, insnbuf);
8504
8505   /* Find the immed.  */
8506   tinsn_init (t_insn);
8507   t_insn->insn_type = ITYPE_INSN;
8508   t_insn->is_specific_opcode = FALSE;   /* Must not be specific.  */
8509   t_insn->opcode = opcode;
8510   t_insn->ntok = xtensa_num_operands (isa, opcode);
8511   for (i = 0; i < t_insn->ntok; i++)
8512     {
8513       set_expr_const (&t_insn->tok[i],
8514                       xtensa_insnbuf_get_operand (insnbuf, opcode, i));
8515     }
8516 }
8517
8518
8519 /* Read the value of the relaxable immed from the fr_symbol and fr_offset.  */
8520
8521 static void
8522 tinsn_immed_from_frag (t_insn, fragP)
8523      TInsn *t_insn;
8524      fragS *fragP;
8525 {
8526   xtensa_opcode opcode = t_insn->opcode;
8527   int opnum;
8528
8529   if (fragP->fr_symbol)
8530     {
8531       opnum = get_relaxable_immed (opcode);
8532       set_expr_symbol_offset (&t_insn->tok[opnum],
8533                               fragP->fr_symbol, fragP->fr_offset);
8534     }
8535 }
8536
8537
8538 static int
8539 get_num_stack_text_bytes (istack)
8540      IStack *istack;
8541 {
8542   int i;
8543   int text_bytes = 0;
8544
8545   for (i = 0; i < istack->ninsn; i++)
8546     {
8547       TInsn *t_insn = &istack->insn[i];
8548       if (t_insn->insn_type == ITYPE_INSN)
8549         text_bytes += xg_get_insn_size (t_insn);
8550     }
8551   return text_bytes;
8552 }
8553
8554
8555 static int
8556 get_num_stack_literal_bytes (istack)
8557      IStack *istack;
8558 {
8559   int i;
8560   int lit_bytes = 0;
8561
8562   for (i = 0; i < istack->ninsn; i++)
8563     {
8564       TInsn *t_insn = &istack->insn[i];
8565
8566       if (t_insn->insn_type == ITYPE_LITERAL && t_insn->ntok == 1)
8567         lit_bytes += 4;
8568     }
8569   return lit_bytes;
8570 }
8571
8572 \f
8573 /* Expression utilities.  */
8574
8575 /* Return true if the expression is an integer constant.  */
8576
8577 bfd_boolean
8578 expr_is_const (s)
8579      const expressionS *s;
8580 {
8581   return (s->X_op == O_constant);
8582 }
8583
8584
8585 /* Get the expression constant.
8586    Calling this is illegal if expr_is_const () returns true.  */
8587
8588 offsetT
8589 get_expr_const (s)
8590      const expressionS *s;
8591 {
8592   assert (expr_is_const (s));
8593   return s->X_add_number;
8594 }
8595
8596
8597 /* Set the expression to a constant value.  */
8598
8599 void
8600 set_expr_const (s, val)
8601      expressionS *s;
8602      offsetT val;
8603 {
8604   s->X_op = O_constant;
8605   s->X_add_number = val;
8606   s->X_add_symbol = NULL;
8607   s->X_op_symbol = NULL;
8608 }
8609
8610
8611 /* Set the expression to a symbol + constant offset.  */
8612
8613 void
8614 set_expr_symbol_offset (s, sym, offset)
8615      expressionS *s;
8616      symbolS *sym;
8617      offsetT offset;
8618 {
8619   s->X_op = O_symbol;
8620   s->X_add_symbol = sym;
8621   s->X_op_symbol = NULL;        /* unused */
8622   s->X_add_number = offset;
8623 }
8624
8625
8626 bfd_boolean
8627 expr_is_equal (s1, s2)
8628      expressionS *s1;
8629      expressionS *s2;
8630 {
8631   if (s1->X_op != s2->X_op)
8632     return FALSE;
8633   if (s1->X_add_symbol != s2->X_add_symbol)
8634     return FALSE;
8635   if (s1->X_op_symbol != s2->X_op_symbol)
8636     return FALSE;
8637   if (s1->X_add_number != s2->X_add_number)
8638     return FALSE;
8639   return TRUE;
8640 }
8641
8642
8643 static void
8644 copy_expr (dst, src)
8645      expressionS *dst;
8646      const expressionS *src;
8647 {
8648   memcpy (dst, src, sizeof (expressionS));
8649 }
8650
8651 \f
8652 /* Support for Tensilica's "--rename-section" option.  */
8653
8654 #ifdef XTENSA_SECTION_RENAME
8655
8656 struct rename_section_struct
8657 {
8658   char *old_name;
8659   char *new_name;
8660   struct rename_section_struct *next;
8661 };
8662
8663 static struct rename_section_struct *section_rename;
8664
8665
8666 /* Parse the string oldname=new_name:oldname2=new_name2 
8667    and call add_section_rename.  */
8668
8669 void
8670 build_section_rename (arg)
8671      const char *arg;
8672 {
8673   char *this_arg = NULL;
8674   char *next_arg = NULL;
8675
8676   for (this_arg = strdup (arg); this_arg != NULL; this_arg = next_arg)
8677     {
8678       if (this_arg)
8679         {
8680           next_arg = strchr (this_arg, ':');
8681           if (next_arg)
8682             {
8683               *next_arg = '\0';
8684               next_arg++;
8685             }
8686         }
8687       {
8688         char *old_name = this_arg;
8689         char *new_name = strchr (this_arg, '=');
8690
8691         if (*old_name == '\0')
8692           {
8693             as_warn (_("ignoring extra '-rename-section' delimiter ':'"));
8694             continue;
8695           }
8696         if (!new_name || new_name[1] == '\0')
8697           {
8698             as_warn (_("ignoring invalid '-rename-section' "
8699                        "specification: '%s'"), old_name);
8700             continue;
8701           }
8702         *new_name = '\0';
8703         new_name++;
8704         add_section_rename (old_name, new_name);
8705       }
8706     }
8707 }
8708
8709
8710 static void
8711 add_section_rename (old_name, new_name)
8712      char *old_name;
8713      char *new_name;
8714 {
8715   struct rename_section_struct *r = section_rename;
8716
8717   /* Check for invalid section renaming.  */
8718   for (r = section_rename; r != NULL; r = r->next)
8719     {
8720       if (strcmp (r->old_name, old_name) == 0)
8721         as_bad (_("section %s renamed multiple times"), old_name);
8722       if (strcmp (r->new_name, new_name) == 0)
8723         as_bad (_("multiple sections remapped to output section %s"),
8724                 new_name);
8725     }
8726
8727   /* Now add it.  */
8728   r = (struct rename_section_struct *)
8729     xmalloc (sizeof (struct rename_section_struct));
8730   r->old_name = strdup (old_name);
8731   r->new_name = strdup (new_name);
8732   r->next = section_rename;
8733   section_rename = r;
8734 }
8735
8736
8737 const char *
8738 xtensa_section_rename (name)
8739      const char *name;
8740 {
8741   struct rename_section_struct *r = section_rename;
8742
8743   for (r = section_rename; r != NULL; r = r->next)
8744     if (strcmp (r->old_name, name) == 0)
8745       return r->new_name;
8746
8747   return name;
8748 }
8749
8750 #endif /* XTENSA_SECTION_RENAME */