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