* cgen.h: New file.
[external/binutils.git] / gas / config / tc-m32r.c
1 /* tc-m32r.c -- Assembler for the Mitsubishi M32R.
2    Copyright (C) 1996, 1997, 1998 Free Software Foundation.
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,
19    Boston, MA 02111-1307, USA.  */
20
21 #include <stdio.h>
22 #include <ctype.h>
23 #include "as.h"
24 #include "subsegs.h"     
25 #include "symcat.h"
26 #include "cgen-opc.h"
27 #include "cgen.h"
28
29 /* Linked list of symbols that are debugging symbols to be defined as the
30    beginning of the current instruction.  */
31 typedef struct sym_link
32 {
33   struct sym_link *next;
34   symbolS         *symbol;
35 } sym_linkS;
36
37 static sym_linkS *debug_sym_link = (sym_linkS *)0;
38   
39 /* Structure to hold all of the different components describing an individual instruction.  */
40 typedef struct
41 {
42   const CGEN_INSN *     insn;
43   const CGEN_INSN *     orig_insn;
44   CGEN_FIELDS           fields;
45 #ifdef CGEN_INT_INSN
46   cgen_insn_t           buffer [CGEN_MAX_INSN_SIZE / sizeof (cgen_insn_t)];
47 #else
48   char                  buffer [CGEN_MAX_INSN_SIZE];
49 #endif
50   char *                addr;
51   fragS *               frag;
52   int                   num_fixups;
53   fixS *                fixups [CGEN_MAX_FIXUPS];
54   int                   indices [MAX_OPERAND_INSTANCES];
55   sym_linkS             *debug_sym_link;
56 }
57 m32r_insn;
58
59 /* prev_insn.insn is non-null if last insn was a 16 bit insn on a 32 bit
60    boundary (i.e. was the first of two 16 bit insns).  */
61 static m32r_insn        prev_insn;
62
63 /* Non-zero if we've seen a relaxable insn since the last 32 bit
64    alignment request.  */
65 static int seen_relaxable_p = 0;
66
67 /* Non-zero if -relax specified, in which case sufficient relocs are output
68    for the linker to do relaxing.
69    We do simple forms of relaxing internally, but they are always done.
70    This flag does not apply to them.  */
71 static int m32r_relax;
72
73 /* If non-NULL, pointer to cpu description file to read.
74    This allows runtime additions to the assembler.  */
75 static char * m32r_cpu_desc;
76
77 /* start-sanitize-m32rx */
78 /* Non-zero if -m32rx has been specified, in which case support for the
79    extended M32RX instruction set should be enabled.  */
80 static int enable_m32rx = 0;
81
82 /* Non-zero if the programmer should be warned when an explicit parallel
83    instruction might have constraint violations.  */
84 static int warn_explicit_parallel_conflicts = 1;
85
86 /* Non-zero if insns can be made parallel.  */
87 static int optimize;
88 /* end-sanitize-m32rx */
89
90 /* stuff for .scomm symbols.  */
91 static segT     sbss_section;
92 static asection scom_section;
93 static asymbol  scom_symbol;
94
95 const char comment_chars[]        = ";";
96 const char line_comment_chars[]   = "#";
97 const char line_separator_chars[] = "";
98 const char EXP_CHARS[]            = "eE";
99 const char FLT_CHARS[]            = "dD";
100
101 /* Relocations against symbols are done in two
102    parts, with a HI relocation and a LO relocation.  Each relocation
103    has only 16 bits of space to store an addend.  This means that in
104    order for the linker to handle carries correctly, it must be able
105    to locate both the HI and the LO relocation.  This means that the
106    relocations must appear in order in the relocation table.
107
108    In order to implement this, we keep track of each unmatched HI
109    relocation.  We then sort them so that they immediately precede the
110    corresponding LO relocation. */
111
112 struct m32r_hi_fixup
113 {
114   struct m32r_hi_fixup * next;  /* Next HI fixup.  */
115   fixS *                 fixp;  /* This fixup.  */
116   segT                   seg;   /* The section this fixup is in.  */
117
118 };
119
120 /* The list of unmatched HI relocs.  */
121
122 static struct m32r_hi_fixup * m32r_hi_fixup_list;
123
124 \f
125 /* start-sanitize-m32rx */
126 static void
127 allow_m32rx (on)
128      int on;
129 {
130   enable_m32rx = on;
131
132   if (stdoutput != NULL)
133     bfd_set_arch_mach (stdoutput, TARGET_ARCH,
134                        enable_m32rx ? bfd_mach_m32rx : bfd_mach_m32r);
135 }
136 /* end-sanitize-m32rx */
137 \f
138 #define M32R_SHORTOPTS ""
139 /* start-sanitize-m32rx */
140 #undef M32R_SHORTOPTS
141 #define M32R_SHORTOPTS "O"
142 /* end-sanitize-m32rx */
143 const char * md_shortopts = M32R_SHORTOPTS;
144
145 struct option md_longopts[] =
146 {
147 /* start-sanitize-m32rx */
148 #define OPTION_M32RX    (OPTION_MD_BASE)
149   {"m32rx", no_argument, NULL, OPTION_M32RX},
150 #define OPTION_WARN     (OPTION_MD_BASE + 1)
151   {"warn-explicit-parallel-conflicts", no_argument, NULL, OPTION_WARN},
152   {"Wp", no_argument, NULL, OPTION_WARN},
153 #define OPTION_NO_WARN  (OPTION_MD_BASE + 2)
154   {"no-warn-explicit-parallel-conflicts", no_argument, NULL, OPTION_NO_WARN},
155   {"Wnp", no_argument, NULL, OPTION_NO_WARN},
156 /* end-sanitize-m32rx */
157
158 #if 0 /* not supported yet */
159 #define OPTION_RELAX  (OPTION_MD_BASE + 3)
160   {"relax", no_argument, NULL, OPTION_RELAX},
161 #define OPTION_CPU_DESC (OPTION_MD_BASE + 4)
162   {"cpu-desc", required_argument, NULL, OPTION_CPU_DESC},
163 #endif
164
165   {NULL, no_argument, NULL, 0}
166 };
167 size_t md_longopts_size = sizeof (md_longopts);
168
169 int
170 md_parse_option (c, arg)
171      int    c;
172      char * arg;
173 {
174   switch (c)
175     {
176 /* start-sanitize-m32rx */
177     case 'O':
178       optimize = 1;
179       break;
180
181     case OPTION_M32RX:
182       allow_m32rx (1);
183       break;
184       
185     case OPTION_WARN:
186       warn_explicit_parallel_conflicts = 1;
187       break;
188       
189     case OPTION_NO_WARN:
190       warn_explicit_parallel_conflicts = 0;
191       break;
192 /* end-sanitize-m32rx */
193       
194 #if 0 /* not supported yet */
195     case OPTION_RELAX:
196       m32r_relax = 1;
197       break;
198     case OPTION_CPU_DESC:
199       m32r_cpu_desc = arg;
200       break;
201 #endif
202     default:
203       return 0;
204     }
205   return 1;
206 }
207
208 void
209 md_show_usage (stream)
210   FILE * stream;
211 {
212 /* start-sanitize-m32rx */
213   fprintf (stream, _("M32R/X specific command line options:\n"));
214   fprintf (stream, _("\
215 --m32rx                 support the extended m32rx instruction set\n"));
216
217   fprintf (stream, _("\
218 -O                      try to combine instructions in parallel\n"));
219
220   fprintf (stream, _("\
221 --warn-explicit-parallel-conflicts      warn when parallel instrucitons violate contraints\n"));
222   fprintf (stream, _("\
223 --no-warn-explicit-parallel-conflicts   do not warn when parallel instrucitons violate contraints\n"));
224   fprintf (stream, _("\
225 --Wp                                    synonym for --warn-explicit-parallel-conflicts\n"));
226   fprintf (stream, _("\
227 --Wnp                                   synonym for --no-warn-explicit-parallel-conflicts\n"));
228 /* end-sanitize-m32rx */
229
230 #if 0
231   fprintf (stream, _("\
232 --relax                 create linker relaxable code\n"));
233   fprintf (stream, _("\
234 --cpu-desc              provide runtime cpu description file\n"));
235 #endif
236
237
238 static void fill_insn PARAMS ((int));
239 static void m32r_scomm PARAMS ((int));
240 static void debug_sym PARAMS ((int));
241 static void expand_debug_syms PARAMS ((sym_linkS *, int));
242
243 /* Set by md_assemble for use by m32r_fill_insn.  */
244 static subsegT prev_subseg;
245 static segT prev_seg;
246
247 /* The target specific pseudo-ops which we support.  */
248 const pseudo_typeS md_pseudo_table[] =
249 {
250   { "word",     cons,           4 },
251   { "fillinsn", fill_insn,      0 },
252   { "scomm",    m32r_scomm,     0 },
253   { "debugsym", debug_sym,      0 },
254 /* start-sanitize-m32rx */
255   { "m32r",     allow_m32rx,    0 },
256   { "m32rx",    allow_m32rx,    1 },
257 /* end-sanitize-m32rx */
258   { NULL, NULL, 0 }
259 };
260
261 /* FIXME: Should be machine generated.  */
262 #define NOP_INSN 0x7000
263 #define PAR_NOP_INSN 0xf000 /* can only be used in 2nd slot */
264
265 /* When we align the .text section, insert the correct NOP pattern.
266    N is the power of 2 alignment.  LEN is the length of pattern FILL.
267    MAX is the maximum number of characters to skip when doing the alignment,
268    or 0 if there is no maximum.  */
269
270 int
271 m32r_do_align (n, fill, len, max)
272      int          n;
273      const char * fill;
274      int          len;
275      int          max;
276 {
277   if ((fill == NULL || (* fill == 0 && len == 1))
278       && (now_seg->flags & SEC_CODE) != 0
279       /* Only do this special handling if aligning to at least a
280          4 byte boundary.  */
281       && n > 1
282      /* Only do this special handling if we're allowed to emit at
283          least two bytes.  */
284       && (max == 0 || max > 1))
285     {
286       static const unsigned char nop_pattern[] = { 0xf0, 0x00 };
287
288 #if 0
289       /* First align to a 2 byte boundary, in case there is an odd .byte.  */
290       /* FIXME: How much memory will cause gas to use when assembling a big
291          program?  Perhaps we can avoid the frag_align call?  */
292       frag_align (1, 0, 0);
293 #endif
294       /* Next align to a 4 byte boundary (we know n >= 2) using a parallel
295          nop.  */
296       frag_align_pattern (2, nop_pattern, sizeof nop_pattern, 0);
297       /* If doing larger alignments use a repeating sequence of appropriate
298          nops.  */
299       if (n > 2)
300         {
301           static const unsigned char multi_nop_pattern[] =
302           { 0x70, 0x00, 0xf0, 0x00 };
303           frag_align_pattern (n, multi_nop_pattern, sizeof multi_nop_pattern,
304                               max ? max - 2 : 0);
305         }
306       return 1;
307     }
308
309   return 0;
310 }
311
312 static void
313 assemble_nop (opcode)
314      int opcode;
315 {
316   char * f = frag_more (2);
317   md_number_to_chars (f, opcode, 2);
318 }
319
320 /* If the last instruction was the first of 2 16 bit insns,
321    output a nop to move the PC to a 32 bit boundary.
322
323    This is done via an alignment specification since branch relaxing
324    may make it unnecessary.
325
326    Internally, we need to output one of these each time a 32 bit insn is
327    seen after an insn that is relaxable.  */
328
329 static void
330 fill_insn (ignore)
331      int ignore;
332 {
333   (void) m32r_do_align (2, NULL, 0, 0);
334   prev_insn.insn = NULL;
335   seen_relaxable_p = 0;
336 }
337
338 /* Record the symbol so that when we output the insn, we can create
339    a symbol that is at the start of the instruction.  This is used
340    to emit the label for the start of a breakpoint without causing
341    the assembler to emit a NOP if the previous instruction was a
342    16 bit instruction.  */
343
344 static void
345 debug_sym (ignore)
346      int ignore;
347 {
348   register char *name;
349   register char delim;
350   register char *end_name;
351   register symbolS *symbolP;
352   register sym_linkS *link;
353
354   name = input_line_pointer;
355   delim = get_symbol_end ();
356   end_name = input_line_pointer;
357  
358   if ((symbolP = symbol_find (name)) == NULL
359       && (symbolP = md_undefined_symbol (name)) == NULL)
360     {
361       symbolP = symbol_new (name, undefined_section, 0, &zero_address_frag);
362     }
363
364   symbol_table_insert (symbolP);
365   if (S_IS_DEFINED (symbolP) && S_GET_SEGMENT (symbolP) != reg_section)
366     as_bad (_("symbol `%s' already defined"), S_GET_NAME (symbolP));
367
368   else
369     {
370       link = (sym_linkS *) xmalloc (sizeof (sym_linkS));
371       link->symbol = symbolP;
372       link->next = debug_sym_link;
373       debug_sym_link = link;
374       symbolP->local = 1;
375     }
376
377   *end_name = delim;
378   demand_empty_rest_of_line ();
379 }
380
381 /* Second pass to expanding the debug symbols, go through linked
382    list of symbols and reassign the address.  */
383
384 static void
385 expand_debug_syms (syms, align)
386      sym_linkS *syms;
387      int align;
388 {
389   char *save_input_line = input_line_pointer;
390   sym_linkS *next_syms;
391   expressionS exp;
392
393   if (!syms)
394     return;
395
396   (void) m32r_do_align (align, NULL, 0, 0);
397   for (; syms != (sym_linkS *)0; syms = next_syms)
398     {
399       symbolS *symbolP = syms->symbol;
400       next_syms = syms->next;
401       input_line_pointer = ".\n";
402       pseudo_set (symbolP);
403       free ((char *)syms);
404     }
405
406   input_line_pointer = save_input_line;
407 }
408
409 /* Cover function to fill_insn called after a label and at end of assembly.
410
411    The result is always 1: we're called in a conditional to see if the
412    current line is a label.  */
413
414 int
415 m32r_fill_insn (done)
416      int done;
417 {
418   if (prev_seg != NULL)
419     {
420       segT    seg    = now_seg;
421       subsegT subseg = now_subseg;
422
423       subseg_set (prev_seg, prev_subseg);
424       
425       fill_insn (0);
426       
427       subseg_set (seg, subseg);
428     }
429   
430   return 1;
431 }
432 \f
433 void
434 md_begin ()
435 {
436   flagword applicable;
437   segT     seg;
438   subsegT  subseg;
439
440   /* Initialize the `cgen' interface.  */
441
442   /* This is a callback from cgen to gas to parse operands.  */
443   cgen_parse_operand_fn = cgen_parse_operand;
444   
445   /* Set the machine number and endian.  */
446   CGEN_SYM (init_asm) (0 /* mach number */,
447                        target_big_endian ?
448                        CGEN_ENDIAN_BIG : CGEN_ENDIAN_LITTLE);
449
450 #if 0 /* not supported yet */
451   /* If a runtime cpu description file was provided, parse it.  */
452   if (m32r_cpu_desc != NULL)
453     {
454       const char * errmsg;
455
456       errmsg = cgen_read_cpu_file (m32r_cpu_desc);
457       if (errmsg != NULL)
458         as_bad ("%s: %s", m32r_cpu_desc, errmsg);
459     }
460 #endif
461
462   /* Save the current subseg so we can restore it [it's the default one and
463      we don't want the initial section to be .sbss].  */
464   seg    = now_seg;
465   subseg = now_subseg;
466
467   /* The sbss section is for local .scomm symbols.  */
468   sbss_section = subseg_new (".sbss", 0);
469   
470   /* This is copied from perform_an_assembly_pass.  */
471   applicable = bfd_applicable_section_flags (stdoutput);
472   bfd_set_section_flags (stdoutput, sbss_section, applicable & SEC_ALLOC);
473   
474 #if 0 /* What does this do? [see perform_an_assembly_pass]  */
475   seg_info (bss_section)->bss = 1;
476 #endif
477
478   subseg_set (seg, subseg);
479
480   /* We must construct a fake section similar to bfd_com_section
481      but with the name .scommon.  */
482   scom_section                = bfd_com_section;
483   scom_section.name           = ".scommon";
484   scom_section.output_section = & scom_section;
485   scom_section.symbol         = & scom_symbol;
486   scom_section.symbol_ptr_ptr = & scom_section.symbol;
487   scom_symbol                 = * bfd_com_section.symbol;
488   scom_symbol.name            = ".scommon";
489   scom_symbol.section         = & scom_section;
490
491 /* start-sanitize-m32rx */
492   allow_m32rx (enable_m32rx);
493 /* end-sanitize-m32rx */
494 }
495
496 /* start-sanitize-m32rx */
497
498 #define OPERAND_IS_COND_BIT(operand, indices, index)                    \
499         (CGEN_OPERAND_INSTANCE_HW (operand)->type == HW_H_COND          \
500          || (CGEN_OPERAND_INSTANCE_HW (operand)->type == HW_H_CR        \
501              && (indices [index] == 0 || indices [index] == 1)))
502      
503 /* Returns true if an output of instruction 'a' is referenced by an operand
504    of instruction 'b'.  If 'check_outputs' is true then b's outputs are
505    checked, otherwise its inputs are examined.  */
506
507 static int
508 first_writes_to_seconds_operands (a, b, check_outputs)
509      m32r_insn * a;
510      m32r_insn * b;
511      const int   check_outputs;
512 {
513   const CGEN_OPERAND_INSTANCE * a_operands = CGEN_INSN_OPERANDS (a->insn);
514   const CGEN_OPERAND_INSTANCE * b_ops = CGEN_INSN_OPERANDS (b->insn);
515   int                           a_index;
516
517   /* If at least one of the instructions takes no operands, then there is
518      nothing to check.  There really are instructions without operands,
519      eg 'nop'.  */
520   if (a_operands == NULL || b_ops == NULL)
521     return 0;
522       
523   /* Scan the operand list of 'a' looking for an output operand.  */
524   for (a_index = 0;
525        CGEN_OPERAND_INSTANCE_TYPE (a_operands) != CGEN_OPERAND_INSTANCE_END;
526        a_index ++, a_operands ++)
527     {
528       if (CGEN_OPERAND_INSTANCE_TYPE (a_operands) == CGEN_OPERAND_INSTANCE_OUTPUT)
529         {
530           int b_index;
531           const CGEN_OPERAND_INSTANCE * b_operands = b_ops;
532
533           /* Special Case:
534              The Condition bit 'C' is a shadow of the CBR register (control
535              register 1) and also a shadow of bit 31 of the program status
536              word (control register 0).  For now this is handled here, rather
537              than by cgen.... */
538           
539           if (OPERAND_IS_COND_BIT (a_operands, a->indices, a_index))
540             {
541               /* Scan operand list of 'b' looking for another reference to the
542                  condition bit, which goes in the right direction.  */
543               for (b_index = 0;
544                    CGEN_OPERAND_INSTANCE_TYPE (b_operands) != CGEN_OPERAND_INSTANCE_END;
545                    b_index ++, b_operands ++)
546                 {
547                   if ((CGEN_OPERAND_INSTANCE_TYPE (b_operands) ==
548                        (check_outputs ? CGEN_OPERAND_INSTANCE_OUTPUT : CGEN_OPERAND_INSTANCE_INPUT))
549                       && OPERAND_IS_COND_BIT (b_operands, b->indices, b_index))
550                     return 1;
551                 }
552             }
553           else
554             {
555               /* Scan operand list of 'b' looking for an operand that references
556                  the same hardware element, and which goes in the right direction.  */
557               for (b_index = 0;
558                    CGEN_OPERAND_INSTANCE_TYPE (b_operands) != CGEN_OPERAND_INSTANCE_END;
559                    b_index ++, b_operands ++)
560                 {
561                   if ((CGEN_OPERAND_INSTANCE_TYPE (b_operands) ==
562                        (check_outputs ? CGEN_OPERAND_INSTANCE_OUTPUT : CGEN_OPERAND_INSTANCE_INPUT))
563                       && (CGEN_OPERAND_INSTANCE_HW (b_operands) == CGEN_OPERAND_INSTANCE_HW (a_operands))
564                       && (a->indices [a_index] == b->indices [b_index]))
565                     return 1;
566                 }
567             }
568         }
569     }
570
571     return 0;
572 }
573
574 /* Returns true if the insn can (potentially) alter the program counter.  */
575
576 static int
577 writes_to_pc (a)
578      m32r_insn * a;
579 {
580 #if 0  /* Once PC operands are working.... */
581   const CGEN_OPERAND_INSTANCE * a_operands == CGEN_INSN_OPERANDS (a->insn);
582
583   if (a_operands == NULL)
584     return 0;
585
586   while (CGEN_OPERAND_INSTANCE_TYPE (a_operands) != CGEN_OPERAND_INSTANCE_END)
587     {
588       if (CGEN_OPERAND_INSTANCE_OPERAND (a_operands) != NULL
589           && CGEN_OPERAND_INDEX (CGEN_OPERAND_INSTANCE_OPERAND (a_operands)) == M32R_OPERAND_PC)
590         return 1;
591       
592       a_operands ++;
593     }
594 #else
595   if (CGEN_INSN_ATTR (a->insn, CGEN_INSN_UNCOND_CTI)
596       || CGEN_INSN_ATTR (a->insn, CGEN_INSN_COND_CTI))
597     return 1;
598 #endif
599   return 0;
600 }
601
602 /* Returns NULL if the two 16 bit insns can be executed in parallel,
603    otherwise it returns a pointer to an error message explaining why not.  */
604
605 static const char *
606 can_make_parallel (a, b)
607      m32r_insn * a;
608      m32r_insn * b;
609 {
610   PIPE_ATTR a_pipe;
611   PIPE_ATTR b_pipe;
612   
613   /* Make sure the instructions are the right length.  */
614   if (   CGEN_FIELDS_BITSIZE (& a->fields) != 16
615       || CGEN_FIELDS_BITSIZE (& b->fields) != 16)
616     abort();
617
618   if (first_writes_to_seconds_operands (a, b, true))
619     return _("Instructions write to the same destination register.");
620   
621   a_pipe = CGEN_INSN_ATTR (a->insn, CGEN_INSN_PIPE);
622   b_pipe = CGEN_INSN_ATTR (b->insn, CGEN_INSN_PIPE);
623
624   /* Make sure that the instructions use the correct execution pipelines.  */
625   if (   a_pipe == PIPE_NONE
626       || b_pipe == PIPE_NONE)
627     return _("Instructions do not use parallel execution pipelines.");
628
629   /* Leave this test for last, since it is the only test that can
630      go away if the instructions are swapped, and we want to make
631      sure that any other errors are detected before this happens.  */
632   if (   a_pipe == PIPE_S
633       || b_pipe == PIPE_O)
634     return _("Instructions share the same execution pipeline");
635   
636   return NULL;
637 }
638
639 #ifdef CGEN_INT_INSN
640
641 static void
642 make_parallel (buffer)
643      cgen_insn_t * buffer;
644 {
645   /* Force the top bit of the second insn to be set.  */
646
647   bfd_vma value;
648       
649   if (CGEN_CURRENT_ENDIAN == CGEN_ENDIAN_BIG)
650     {
651       value = bfd_getb16 ((bfd_byte *) buffer);
652       value |= 0x8000;
653       bfd_putb16 (value, (char *) buffer);
654     }
655   else
656     {
657       value = bfd_getl16 ((bfd_byte *) buffer);
658       value |= 0x8000;
659       bfd_putl16 (value, (char *) buffer);
660     }
661 }
662
663 #else
664
665 static void
666 make_parallel (buffer)
667      char * buffer;
668 {
669   /* Force the top bit of the second insn to be set.  */
670
671   buffer [CGEN_CURRENT_ENDIAN == CGEN_ENDIAN_BIG ? 0 : 1] |= 0x80;
672 }
673
674 #endif /* ! CGEN_INT_INSN */
675
676 static void
677 assemble_parallel_insn (str, str2)
678      char * str;
679      char * str2;
680 {
681   char *    str3;
682   m32r_insn first;
683   m32r_insn second;
684   char *    errmsg;
685   
686   * str2 = 0; /* Seperate the two instructions.  */
687
688   /* If there was a previous 16 bit insn, then fill the following 16 bit slot,
689      so that the parallel instruction will start on a 32 bit boundary.  */
690   if (prev_insn.insn)
691     fill_insn (0);
692
693   first.debug_sym_link = debug_sym_link;
694   debug_sym_link = (sym_linkS *)0;
695
696   /* Parse the first instruction.  */
697   if (! (first.insn = CGEN_SYM (assemble_insn)
698          (str, & first.fields, first.buffer, & errmsg)))
699     {
700       as_bad (errmsg);
701       return;
702     }
703
704   if (! enable_m32rx
705       /* FIXME: Need standard macro to perform this test.  */
706       && CGEN_INSN_ATTR (first.insn, CGEN_INSN_MACH) == (1 << MACH_M32RX))
707     {
708       as_bad (_("instruction '%s' is for the M32RX only"), str);
709       return;
710     }
711
712   /* Check to see if this is an allowable parallel insn.  */
713   if (CGEN_INSN_ATTR (first.insn, CGEN_INSN_PIPE) == PIPE_NONE)
714     {
715       as_bad (_("instruction '%s' cannot be executed in parallel."), str);
716       return;
717     }
718   
719   *str2 = '|';       /* Restore the original assembly text, just in case it is needed.  */
720   str3  = str;       /* Save the original string pointer.  */
721   str   = str2 + 2;  /* Advanced past the parsed string.  */
722   str2  = str3;      /* Remember the entire string in case it is needed for error messages.  */
723
724   /* Preserve any fixups that have been generated and reset the list to empty.  */
725   cgen_save_fixups();
726
727   /* Get the indices of the operands of the instruction.  */
728   /* FIXME: CGEN_FIELDS is already recorded, but relying on that fact
729      doesn't seem right.  Perhaps allow passing fields like we do insn.  */
730   /* FIXME: ALIAS insns do not have operands, so we use this function
731      to find the equivalent insn and overwrite the value stored in our
732      structure.  We still need the original insn, however, since this
733      may have certain attributes that are not present in the unaliased
734      version (eg relaxability).  When aliases behave differently this
735      may have to change.  */
736   first.orig_insn = first.insn;
737   first.insn = m32r_cgen_lookup_get_insn_operands (NULL,
738                                                    bfd_getb16 ((char *) first.buffer),
739                                                    16,
740                                                    first.indices);
741   if (first.insn == NULL)
742     as_fatal (_("internal error: m32r_cgen_lookup_get_insn_operands failed for first insn"));
743
744   second.debug_sym_link = NULL;
745
746   /* Parse the second instruction.  */
747   if (! (second.insn = CGEN_SYM (assemble_insn)
748          (str, & second.fields, second.buffer, & errmsg)))
749     {
750       as_bad (errmsg);
751       return;
752     }
753
754   /* Check it.  */
755   if (! enable_m32rx
756       && CGEN_INSN_ATTR (second.insn, CGEN_INSN_MACH) == (1 << MACH_M32RX))
757     {
758       as_bad (_("instruction '%s' is for the M32RX only"), str);
759       return;
760     }
761
762   /* Check to see if this is an allowable parallel insn.  */
763   if (CGEN_INSN_ATTR (second.insn, CGEN_INSN_PIPE) == PIPE_NONE)
764     {
765       as_bad (_("instruction '%s' cannot be executed in parallel."), str);
766       return;
767     }
768   
769   if (! enable_m32rx)
770     {
771       if (CGEN_INSN_NUM (first.insn) != M32R_INSN_NOP
772           && CGEN_INSN_NUM (second.insn) != M32R_INSN_NOP)
773         {
774           as_bad (_("'%s': only the NOP instruction can be issued in parallel on the m32r"), str2);
775           return;
776         }
777     }
778
779   /* Get the indices of the operands of the instruction.  */
780   second.orig_insn = second.insn;
781   second.insn = m32r_cgen_lookup_get_insn_operands (NULL,
782                                                     bfd_getb16 ((char *) second.buffer),
783                                                     16,
784                                                     second.indices);
785   if (second.insn == NULL)
786     as_fatal (_("internal error: m32r_cgen_lookup_get_insn_operands failed for second insn"));
787
788   /* We assume that if the first instruction writes to a register that is
789      read by the second instruction it is because the programmer intended
790      this to happen, (after all they have explicitly requested that these
791      two instructions be executed in parallel).  Although if the global
792      variable warn_explicit_parallel_conflicts is true then we do generate
793      a warning message.  Similarly we assume that parallel branch and jump
794      instructions are deliberate and should not produce errors.  */
795   
796   if (warn_explicit_parallel_conflicts)
797     {
798       if (first_writes_to_seconds_operands (& first, & second, false))
799         as_warn (_("%s: output of 1st instruction is the same as an input to 2nd instruction - is this intentional ?"), str2);
800       
801       if (first_writes_to_seconds_operands (& second, & first, false))
802         as_warn (_("%s: output of 2nd instruction is the same as an input to 1st instruction - is this intentional ?"), str2);
803     }
804       
805   if ((errmsg = (char *) can_make_parallel (& first, & second)) == NULL)
806     {
807       /* Get the fixups for the first instruction.  */
808       cgen_swap_fixups ();
809
810       /* Write it out.  */
811       expand_debug_syms (first.debug_sym_link, 1);
812       cgen_asm_finish_insn (first.orig_insn, first.buffer,
813                             CGEN_FIELDS_BITSIZE (& first.fields), 0, NULL);
814       
815       /* Force the top bit of the second insn to be set.  */
816       make_parallel (second.buffer);
817
818       /* Get its fixups.  */
819       cgen_restore_fixups ();
820
821       /* Write it out.  */
822       expand_debug_syms (second.debug_sym_link, 1);
823       cgen_asm_finish_insn (second.orig_insn, second.buffer,
824                             CGEN_FIELDS_BITSIZE (& second.fields), 0, NULL);
825     }
826   /* Try swapping the instructions to see if they work that way.  */
827   else if (can_make_parallel (& second, & first) == NULL)
828     {
829       /* Write out the second instruction first.  */
830       expand_debug_syms (second.debug_sym_link, 1);
831       cgen_asm_finish_insn (second.orig_insn, second.buffer,
832                             CGEN_FIELDS_BITSIZE (& second.fields), 0, NULL);
833       
834       /* Force the top bit of the first instruction to be set.  */
835       make_parallel (first.buffer);
836
837       /* Get the fixups for the first instruction.  */
838       cgen_restore_fixups ();
839
840       /* Write out the first instruction.  */
841       expand_debug_syms (first.debug_sym_link, 1);
842       cgen_asm_finish_insn (first.orig_insn, first.buffer,
843                             CGEN_FIELDS_BITSIZE (& first.fields), 0, NULL);
844     }
845   else
846     {
847       as_bad ("'%s': %s", str2, errmsg);
848       return;
849     }
850       
851   /* Set these so m32r_fill_insn can use them.  */
852   prev_seg    = now_seg;
853   prev_subseg = now_subseg;
854 }
855
856 /* end-sanitize-m32rx */
857
858
859 void
860 md_assemble (str)
861      char * str;
862 {
863   m32r_insn insn;
864   char *    errmsg;
865   char *    str2 = NULL;
866
867   /* Initialize GAS's cgen interface for a new instruction.  */
868   cgen_asm_init_parse ();
869
870 /* start-sanitize-m32rx */
871   /* Look for a parallel instruction seperator.  */
872   if ((str2 = strstr (str, "||")) != NULL)
873     {
874       assemble_parallel_insn (str, str2);
875       return;
876     }
877 /* end-sanitize-m32rx */
878   
879   insn.debug_sym_link = debug_sym_link;
880   debug_sym_link = (sym_linkS *)0;
881
882   insn.insn = CGEN_SYM (assemble_insn) (str, & insn.fields, insn.buffer, & errmsg);
883   if (!insn.insn)
884     {
885       as_bad (errmsg);
886       return;
887     }
888
889 /* start-sanitize-m32rx */
890   if (! enable_m32rx && CGEN_INSN_ATTR (insn.insn, CGEN_INSN_MACH) == (1 << MACH_M32RX))
891     {
892       as_bad (_("instruction '%s' is for the M32RX only"), str);
893       return;
894     }
895 /* end-sanitize-m32rx */
896   
897   if (CGEN_INSN_BITSIZE (insn.insn) == 32)
898     {
899       /* 32 bit insns must live on 32 bit boundaries.  */
900       if (prev_insn.insn || seen_relaxable_p)
901         {
902           /* ??? If calling fill_insn too many times turns us into a memory
903              pig, can we call assemble_nop instead of !seen_relaxable_p?  */
904           fill_insn (0);
905         }
906
907       expand_debug_syms (insn.debug_sym_link, 2);
908
909       /* Doesn't really matter what we pass for RELAX_P here.  */
910       cgen_asm_finish_insn (insn.insn, insn.buffer,
911                             CGEN_FIELDS_BITSIZE (& insn.fields), 1, NULL);
912     }
913   else
914     {
915       int on_32bit_boundary_p;
916 /* start-sanitize-m32rx */
917       int swap = false;
918 /* end-sanitize-m32rx */
919
920       if (CGEN_INSN_BITSIZE (insn.insn) != 16)
921         abort();
922
923       insn.orig_insn = insn.insn;
924 /* start-sanitize-m32rx */
925       if (enable_m32rx)
926         {
927           /* Get the indices of the operands of the instruction.
928              FIXME: See assemble_parallel for notes on orig_insn.  */
929           insn.insn = m32r_cgen_lookup_get_insn_operands (NULL,
930                                                           bfd_getb16 ((char *) insn.buffer),
931                                                           16,
932                                                           insn.indices);
933           if (insn.insn == NULL)
934             as_fatal (_("internal error: m32r_cgen_get_insn_operands failed"));
935         }
936 /* end-sanitize-m32rx */
937
938       /* Compute whether we're on a 32 bit boundary or not.
939          prev_insn.insn is NULL when we're on a 32 bit boundary.  */
940       on_32bit_boundary_p = prev_insn.insn == NULL;
941
942 /* start-sanitize-m32rx */
943       /* Look to see if this instruction can be combined with the
944          previous instruction to make one, parallel, 32 bit instruction.
945          If the previous instruction (potentially) changed the flow of
946          program control, then it cannot be combined with the current
947          instruction.  If the current instruction is relaxable, then it
948          might be replaced with a longer version, so we cannot combine it.
949          Also if the output of the previous instruction is used as an
950          input to the current instruction then it cannot be combined.
951          Otherwise call can_make_parallel() with both orderings of the
952          instructions to see if they can be combined.  */
953       if (     ! on_32bit_boundary_p
954           &&   enable_m32rx
955           &&   optimize
956           &&   CGEN_INSN_ATTR (insn.orig_insn, CGEN_INSN_RELAXABLE) == 0
957           && ! writes_to_pc (& prev_insn)
958           && ! first_writes_to_seconds_operands (& prev_insn, &insn, false)
959           )
960         {
961           if (can_make_parallel (& prev_insn, & insn) == NULL)
962             make_parallel (insn.buffer);
963           else if (can_make_parallel (& insn, & prev_insn) == NULL)
964             swap = true;
965         }
966 /* end-sanitize-m32rx */
967
968       expand_debug_syms (insn.debug_sym_link, 1);
969
970       {
971         int i;
972         finished_insnS fi;
973
974         /* Ensure each pair of 16 bit insns is in the same frag.  */
975         frag_grow (4);
976
977         cgen_asm_finish_insn (insn.orig_insn, insn.buffer,
978                               CGEN_FIELDS_BITSIZE (& insn.fields),
979                               1 /*relax_p*/, &fi);
980         insn.addr = fi.addr;
981         insn.frag = fi.frag;
982         insn.num_fixups = fi.num_fixups;
983         for (i = 0; i < fi.num_fixups; ++i)
984           insn.fixups[i] = fi.fixups[i];
985       }
986
987 /* start-sanitize-m32rx */
988       if (swap)
989         {
990           int i,tmp;
991
992 #define SWAP_BYTES(a,b) tmp = a; a = b; b = tmp
993
994           /* Swap the two insns */
995           SWAP_BYTES (prev_insn.addr [0], insn.addr [0]);
996           SWAP_BYTES (prev_insn.addr [1], insn.addr [1]);
997
998           make_parallel (insn.addr);
999
1000           /* Swap any relaxable frags recorded for the two insns.  */
1001           /* FIXME: Clarify.  relaxation precludes parallel insns */
1002           if (prev_insn.frag->fr_opcode == prev_insn.addr)
1003             prev_insn.frag->fr_opcode = insn.addr;
1004           else if (insn.frag->fr_opcode == insn.addr)
1005             insn.frag->fr_opcode = prev_insn.addr;
1006
1007           /* Update the addresses in any fixups.
1008              Note that we don't have to handle the case where each insn is in
1009              a different frag as we ensure they're in the same frag above.  */
1010           for (i = 0; i < prev_insn.num_fixups; ++i)
1011             prev_insn.fixups[i]->fx_where += 2;
1012           for (i = 0; i < insn.num_fixups; ++i)
1013             insn.fixups[i]->fx_where -= 2;
1014         }
1015 /* end-sanitize-m32rx */
1016
1017       /* Keep track of whether we've seen a pair of 16 bit insns.
1018          prev_insn.insn is NULL when we're on a 32 bit boundary.  */
1019       if (on_32bit_boundary_p)
1020         prev_insn = insn;
1021       else
1022         prev_insn.insn = NULL;
1023       
1024       /* If the insn needs the following one to be on a 32 bit boundary
1025          (e.g. subroutine calls), fill this insn's slot.  */
1026       if (on_32bit_boundary_p
1027           && CGEN_INSN_ATTR (insn.orig_insn, CGEN_INSN_FILL_SLOT) != 0)
1028         fill_insn (0);
1029
1030       /* If this is a relaxable insn (can be replaced with a larger version)
1031          mark the fact so that we can emit an alignment directive for a
1032          following 32 bit insn if we see one.   */
1033       if (CGEN_INSN_ATTR (insn.orig_insn, CGEN_INSN_RELAXABLE) != 0)
1034         seen_relaxable_p = 1;
1035     }
1036
1037   /* Set these so m32r_fill_insn can use them.  */
1038   prev_seg    = now_seg;
1039   prev_subseg = now_subseg;
1040 }
1041
1042 /* The syntax in the manual says constants begin with '#'.
1043    We just ignore it.  */
1044
1045 void 
1046 md_operand (expressionP)
1047      expressionS * expressionP;
1048 {
1049   if (* input_line_pointer == '#')
1050     {
1051       input_line_pointer ++;
1052       expression (expressionP);
1053     }
1054 }
1055
1056 valueT
1057 md_section_align (segment, size)
1058      segT   segment;
1059      valueT size;
1060 {
1061   int align = bfd_get_section_alignment (stdoutput, segment);
1062   return ((size + (1 << align) - 1) & (-1 << align));
1063 }
1064
1065 symbolS *
1066 md_undefined_symbol (name)
1067   char * name;
1068 {
1069   return 0;
1070 }
1071 \f
1072 /* .scomm pseudo-op handler.
1073
1074    This is a new pseudo-op to handle putting objects in .scommon.
1075    By doing this the linker won't need to do any work and more importantly
1076    it removes the implicit -G arg necessary to correctly link the object file.
1077 */
1078
1079 static void
1080 m32r_scomm (ignore)
1081      int ignore;
1082 {
1083   register char *    name;
1084   register char      c;
1085   register char *    p;
1086   offsetT            size;
1087   register symbolS * symbolP;
1088   offsetT            align;
1089   int                align2;
1090
1091   name = input_line_pointer;
1092   c = get_symbol_end ();
1093
1094   /* just after name is now '\0' */
1095   p = input_line_pointer;
1096   * p = c;
1097   SKIP_WHITESPACE ();
1098   if (* input_line_pointer != ',')
1099     {
1100       as_bad (_("Expected comma after symbol-name: rest of line ignored."));
1101       ignore_rest_of_line ();
1102       return;
1103     }
1104
1105   input_line_pointer ++;                /* skip ',' */
1106   if ((size = get_absolute_expression ()) < 0)
1107     {
1108       as_warn (_(".SCOMMon length (%ld.) <0! Ignored."), (long) size);
1109       ignore_rest_of_line ();
1110       return;
1111     }
1112
1113   /* The third argument to .scomm is the alignment.  */
1114   if (* input_line_pointer != ',')
1115     align = 8;
1116   else
1117     {
1118       ++ input_line_pointer;
1119       align = get_absolute_expression ();
1120       if (align <= 0)
1121         {
1122           as_warn (_("ignoring bad alignment"));
1123           align = 8;
1124         }
1125     }
1126   /* Convert to a power of 2 alignment.  */
1127   if (align)
1128     {
1129       for (align2 = 0; (align & 1) == 0; align >>= 1, ++ align2)
1130         continue;
1131       if (align != 1)
1132         {
1133           as_bad (_("Common alignment not a power of 2"));
1134           ignore_rest_of_line ();
1135           return;
1136         }
1137     }
1138   else
1139     align2 = 0;
1140
1141   * p = 0;
1142   symbolP = symbol_find_or_make (name);
1143   * p = c;
1144
1145   if (S_IS_DEFINED (symbolP))
1146     {
1147       as_bad (_("Ignoring attempt to re-define symbol `%s'."),
1148               S_GET_NAME (symbolP));
1149       ignore_rest_of_line ();
1150       return;
1151     }
1152
1153   if (S_GET_VALUE (symbolP) && S_GET_VALUE (symbolP) != (valueT) size)
1154     {
1155       as_bad (_("Length of .scomm \"%s\" is already %ld. Not changed to %ld."),
1156               S_GET_NAME (symbolP),
1157               (long) S_GET_VALUE (symbolP),
1158               (long) size);
1159
1160       ignore_rest_of_line ();
1161       return;
1162     }
1163
1164   if (symbolP->local)
1165     {
1166       segT   old_sec    = now_seg;
1167       int    old_subsec = now_subseg;
1168       char * pfrag;
1169
1170       record_alignment (sbss_section, align2);
1171       subseg_set (sbss_section, 0);
1172       
1173       if (align2)
1174         frag_align (align2, 0, 0);
1175       
1176       if (S_GET_SEGMENT (symbolP) == sbss_section)
1177         symbolP->sy_frag->fr_symbol = 0;
1178       
1179       symbolP->sy_frag = frag_now;
1180       
1181       pfrag = frag_var (rs_org, 1, 1, (relax_substateT) 0, symbolP, size,
1182                         (char *) 0);
1183       * pfrag = 0;
1184       S_SET_SIZE (symbolP, size);
1185       S_SET_SEGMENT (symbolP, sbss_section);
1186       S_CLEAR_EXTERNAL (symbolP);
1187       subseg_set (old_sec, old_subsec);
1188     }
1189   else
1190     {
1191       S_SET_VALUE (symbolP, (valueT) size);
1192       S_SET_ALIGN (symbolP, align2);
1193       S_SET_EXTERNAL (symbolP);
1194       S_SET_SEGMENT (symbolP, & scom_section);
1195     }
1196
1197   demand_empty_rest_of_line ();
1198 }
1199 \f
1200 /* Interface to relax_segment.  */
1201
1202 /* FIXME: Build table by hand, get it working, then machine generate.  */
1203
1204 const relax_typeS md_relax_table[] =
1205 {
1206 /* The fields are:
1207    1) most positive reach of this state,
1208    2) most negative reach of this state,
1209    3) how many bytes this mode will add to the size of the current frag
1210    4) which index into the table to try if we can't fit into this one.  */
1211
1212   /* The first entry must be unused because an `rlx_more' value of zero ends
1213      each list.  */
1214   {1, 1, 0, 0},
1215
1216   /* The displacement used by GAS is from the end of the 2 byte insn,
1217      so we subtract 2 from the following.  */
1218   /* 16 bit insn, 8 bit disp -> 10 bit range.
1219      This doesn't handle a branch in the right slot at the border:
1220      the "& -4" isn't taken into account.  It's not important enough to
1221      complicate things over it, so we subtract an extra 2 (or + 2 in -ve
1222      case).  */
1223   {511 - 2 - 2, -512 - 2 + 2, 0, 2 },
1224   /* 32 bit insn, 24 bit disp -> 26 bit range.  */
1225   {0x2000000 - 1 - 2, -0x2000000 - 2, 2, 0 },
1226   /* Same thing, but with leading nop for alignment.  */
1227   {0x2000000 - 1 - 2, -0x2000000 - 2, 4, 0 }
1228 };
1229
1230 long
1231 m32r_relax_frag (fragP, stretch)
1232      fragS * fragP;
1233      long    stretch;
1234 {
1235   /* Address of branch insn.  */
1236   long address = fragP->fr_address + fragP->fr_fix - 2;
1237   long growth = 0;
1238
1239   /* Keep 32 bit insns aligned on 32 bit boundaries.  */
1240   if (fragP->fr_subtype == 2)
1241     {
1242       if ((address & 3) != 0)
1243         {
1244           fragP->fr_subtype = 3;
1245           growth = 2;
1246         }
1247     }
1248   else if (fragP->fr_subtype == 3)
1249     {
1250       if ((address & 3) == 0)
1251         {
1252           fragP->fr_subtype = 2;
1253           growth = -2;
1254         }
1255     }
1256   else
1257     {
1258       growth = relax_frag (fragP, stretch);
1259
1260       /* Long jump on odd halfword boundary?  */
1261       if (fragP->fr_subtype == 2 && (address & 3) != 0)
1262         {
1263           fragP->fr_subtype = 3;
1264           growth += 2;
1265         }
1266     }
1267
1268   return growth;
1269 }
1270
1271 /* Return an initial guess of the length by which a fragment must grow to
1272    hold a branch to reach its destination.
1273    Also updates fr_type/fr_subtype as necessary.
1274
1275    Called just before doing relaxation.
1276    Any symbol that is now undefined will not become defined.
1277    The guess for fr_var is ACTUALLY the growth beyond fr_fix.
1278    Whatever we do to grow fr_fix or fr_var contributes to our returned value.
1279    Although it may not be explicit in the frag, pretend fr_var starts with a
1280    0 value.  */
1281
1282 int
1283 md_estimate_size_before_relax (fragP, segment)
1284      fragS * fragP;
1285      segT    segment;
1286 {
1287   int    old_fr_fix = fragP->fr_fix;
1288   char * opcode = fragP->fr_opcode;
1289
1290   /* The only thing we have to handle here are symbols outside of the
1291      current segment.  They may be undefined or in a different segment in
1292      which case linker scripts may place them anywhere.
1293      However, we can't finish the fragment here and emit the reloc as insn
1294      alignment requirements may move the insn about.  */
1295
1296   if (S_GET_SEGMENT (fragP->fr_symbol) != segment)
1297     {
1298       /* The symbol is undefined in this segment.
1299          Change the relaxation subtype to the max allowable and leave
1300          all further handling to md_convert_frag.  */
1301       fragP->fr_subtype = 2;
1302
1303 #if 0 /* Can't use this, but leave in for illustration.  */     
1304       /* Change 16 bit insn to 32 bit insn.  */
1305       opcode[0] |= 0x80;
1306
1307       /* Increase known (fixed) size of fragment.  */
1308       fragP->fr_fix += 2;
1309
1310       /* Create a relocation for it.  */
1311       fix_new (fragP, old_fr_fix, 4,
1312                fragP->fr_symbol,
1313                fragP->fr_offset, 1 /* pcrel */,
1314                /* FIXME: Can't use a real BFD reloc here.
1315                   cgen_md_apply_fix3 can't handle it.  */
1316                BFD_RELOC_M32R_26_PCREL);
1317
1318       /* Mark this fragment as finished.  */
1319       frag_wane (fragP);
1320 #else
1321       {
1322         const CGEN_INSN * insn;
1323         int               i;
1324
1325         /* Update the recorded insn.
1326            Fortunately we don't have to look very far.
1327            FIXME: Change this to record in the instruction the next higher
1328            relaxable insn to use.  */
1329         for (i = 0, insn = fragP->fr_cgen.insn; i < 4; i++, insn++)
1330           {
1331             if ((strcmp (CGEN_INSN_MNEMONIC (insn),
1332                          CGEN_INSN_MNEMONIC (fragP->fr_cgen.insn))
1333                  == 0)
1334                 && CGEN_INSN_ATTR (insn, CGEN_INSN_RELAX))
1335               break;
1336           }
1337         if (i == 4)
1338           abort ();
1339
1340         fragP->fr_cgen.insn = insn;
1341         return 2;
1342       }
1343 #endif
1344     }
1345
1346   return (fragP->fr_var + fragP->fr_fix - old_fr_fix);
1347
1348
1349 /* *fragP has been relaxed to its final size, and now needs to have
1350    the bytes inside it modified to conform to the new size.
1351
1352    Called after relaxation is finished.
1353    fragP->fr_type == rs_machine_dependent.
1354    fragP->fr_subtype is the subtype of what the address relaxed to.  */
1355
1356 void
1357 md_convert_frag (abfd, sec, fragP)
1358   bfd *   abfd;
1359   segT    sec;
1360   fragS * fragP;
1361 {
1362   char * opcode;
1363   char * displacement;
1364   int    target_address;
1365   int    opcode_address;
1366   int    extension;
1367   int    addend;
1368
1369   opcode = fragP->fr_opcode;
1370
1371   /* Address opcode resides at in file space.  */
1372   opcode_address = fragP->fr_address + fragP->fr_fix - 2;
1373
1374   switch (fragP->fr_subtype)
1375     {
1376     case 1 :
1377       extension = 0;
1378       displacement = & opcode[1];
1379       break;
1380     case 2 :
1381       opcode[0] |= 0x80;
1382       extension = 2;
1383       displacement = & opcode[1];
1384       break;
1385     case 3 :
1386       opcode[2] = opcode[0] | 0x80;
1387       md_number_to_chars (opcode, PAR_NOP_INSN, 2);
1388       opcode_address += 2;
1389       extension = 4;
1390       displacement = & opcode[3];
1391       break;
1392     default :
1393       abort ();
1394     }
1395
1396   if (S_GET_SEGMENT (fragP->fr_symbol) != sec)
1397     {
1398       /* symbol must be resolved by linker */
1399       if (fragP->fr_offset & 3)
1400         as_warn (_("Addend to unresolved symbol not on word boundary."));
1401       addend = fragP->fr_offset >> 2;
1402     }
1403   else
1404     {
1405       /* Address we want to reach in file space.  */
1406       target_address = S_GET_VALUE (fragP->fr_symbol) + fragP->fr_offset;
1407       target_address += fragP->fr_symbol->sy_frag->fr_address;
1408       addend = (target_address - (opcode_address & -4)) >> 2;
1409     }
1410
1411   /* Create a relocation for symbols that must be resolved by the linker.
1412      Otherwise output the completed insn.  */
1413
1414   if (S_GET_SEGMENT (fragP->fr_symbol) != sec)
1415     {
1416       assert (fragP->fr_subtype != 1);
1417       assert (fragP->fr_cgen.insn != 0);
1418       cgen_record_fixup (fragP,
1419                          /* Offset of branch insn in frag.  */
1420                          fragP->fr_fix + extension - 4,
1421                          fragP->fr_cgen.insn,
1422                          4 /*length*/,
1423                          /* FIXME: quick hack */
1424 #if 0
1425                          CGEN_OPERAND_ENTRY (fragP->fr_cgen.opindex),
1426 #else
1427                          CGEN_OPERAND_ENTRY (M32R_OPERAND_DISP24),
1428 #endif
1429                          fragP->fr_cgen.opinfo,
1430                          fragP->fr_symbol, fragP->fr_offset);
1431     }
1432
1433 #define SIZE_FROM_RELAX_STATE(n) ((n) == 1 ? 1 : 3)
1434
1435   md_number_to_chars (displacement, (valueT) addend,
1436                       SIZE_FROM_RELAX_STATE (fragP->fr_subtype));
1437
1438   fragP->fr_fix += extension;
1439 }
1440 \f
1441 /* Functions concerning relocs.  */
1442
1443 /* The location from which a PC relative jump should be calculated,
1444    given a PC relative reloc.  */
1445
1446 long
1447 md_pcrel_from_section (fixP, sec)
1448      fixS * fixP;
1449      segT   sec;
1450 {
1451   if (fixP->fx_addsy != (symbolS *) NULL
1452       && (! S_IS_DEFINED (fixP->fx_addsy)
1453           || S_GET_SEGMENT (fixP->fx_addsy) != sec))
1454     {
1455       /* The symbol is undefined (or is defined but not in this section).
1456          Let the linker figure it out.  */
1457       return 0;
1458     }
1459
1460   return (fixP->fx_frag->fr_address + fixP->fx_where) & -4L;
1461 }
1462
1463 /* Return the bfd reloc type for OPERAND of INSN at fixup FIXP.
1464    Returns BFD_RELOC_NONE if no reloc type can be found.
1465    *FIXP may be modified if desired.  */
1466
1467 bfd_reloc_code_real_type
1468 CGEN_SYM (lookup_reloc) (insn, operand, fixP)
1469      const CGEN_INSN *    insn;
1470      const CGEN_OPERAND * operand;
1471      fixS *               fixP;
1472 {
1473   switch (CGEN_OPERAND_TYPE (operand))
1474     {
1475     case M32R_OPERAND_DISP8 : return  BFD_RELOC_M32R_10_PCREL;
1476     case M32R_OPERAND_DISP16 : return BFD_RELOC_M32R_18_PCREL;
1477     case M32R_OPERAND_DISP24 : return BFD_RELOC_M32R_26_PCREL;
1478     case M32R_OPERAND_UIMM24 : return BFD_RELOC_M32R_24;
1479     case M32R_OPERAND_HI16 :
1480     case M32R_OPERAND_SLO16 :
1481     case M32R_OPERAND_ULO16 :
1482       /* If low/high/shigh/sda was used, it is recorded in `opinfo'.  */
1483       if (fixP->tc_fix_data.opinfo != 0)
1484         return fixP->tc_fix_data.opinfo;
1485       break;
1486     }
1487   return BFD_RELOC_NONE;
1488 }
1489
1490 /* Record a HI16 reloc for later matching with its LO16 cousin.  */
1491
1492 static void
1493 m32r_record_hi16 (reloc_type, fixP, seg)
1494      int    reloc_type;
1495      fixS * fixP;
1496      segT   seg;
1497 {
1498   struct m32r_hi_fixup * hi_fixup;
1499
1500   assert (reloc_type == BFD_RELOC_M32R_HI16_SLO
1501           || reloc_type == BFD_RELOC_M32R_HI16_ULO);
1502
1503   hi_fixup = ((struct m32r_hi_fixup *)
1504               xmalloc (sizeof (struct m32r_hi_fixup)));
1505   hi_fixup->fixp = fixP;
1506   hi_fixup->seg  = now_seg;
1507   hi_fixup->next = m32r_hi_fixup_list;
1508   
1509   m32r_hi_fixup_list = hi_fixup;
1510 }
1511
1512 /* Called while parsing an instruction to create a fixup.
1513    We need to check for HI16 relocs and queue them up for later sorting.  */
1514
1515 fixS *
1516 m32r_cgen_record_fixup_exp (frag, where, insn, length, operand, opinfo, exp)
1517      fragS *              frag;
1518      int                  where;
1519      const CGEN_INSN *    insn;
1520      int                  length;
1521      const CGEN_OPERAND * operand;
1522      int                  opinfo;
1523      expressionS *        exp;
1524 {
1525   fixS * fixP = cgen_record_fixup_exp (frag, where, insn, length,
1526                                       operand, opinfo, exp);
1527
1528   switch (CGEN_OPERAND_TYPE (operand))
1529     {
1530     case M32R_OPERAND_HI16 :
1531       /* If low/high/shigh/sda was used, it is recorded in `opinfo'.  */
1532       if (fixP->tc_fix_data.opinfo == BFD_RELOC_M32R_HI16_SLO
1533           || fixP->tc_fix_data.opinfo == BFD_RELOC_M32R_HI16_ULO)
1534         m32r_record_hi16 (fixP->tc_fix_data.opinfo, fixP, now_seg);
1535       break;
1536     }
1537
1538   return fixP;
1539 }
1540
1541 /* Return BFD reloc type from opinfo field in a fixS.
1542    It's tricky using fx_r_type in m32r_frob_file because the values
1543    are BFD_RELOC_UNUSED + operand number.  */
1544 #define FX_OPINFO_R_TYPE(f) ((f)->tc_fix_data.opinfo)
1545
1546 /* Sort any unmatched HI16 relocs so that they immediately precede
1547    the corresponding LO16 reloc.  This is called before md_apply_fix and
1548    tc_gen_reloc.  */
1549
1550 void
1551 m32r_frob_file ()
1552 {
1553   struct m32r_hi_fixup * l;
1554
1555   for (l = m32r_hi_fixup_list; l != NULL; l = l->next)
1556     {
1557       segment_info_type * seginfo;
1558       int                 pass;
1559
1560       assert (FX_OPINFO_R_TYPE (l->fixp) == BFD_RELOC_M32R_HI16_SLO
1561               || FX_OPINFO_R_TYPE (l->fixp) == BFD_RELOC_M32R_HI16_ULO);
1562
1563       /* Check quickly whether the next fixup happens to be a matching low.  */
1564       if (l->fixp->fx_next != NULL
1565           && FX_OPINFO_R_TYPE (l->fixp->fx_next) == BFD_RELOC_M32R_LO16
1566           && l->fixp->fx_addsy == l->fixp->fx_next->fx_addsy
1567           && l->fixp->fx_offset == l->fixp->fx_next->fx_offset)
1568         continue;
1569
1570       /* Look through the fixups for this segment for a matching `low'.
1571          When we find one, move the high/shigh just in front of it.  We do
1572          this in two passes.  In the first pass, we try to find a
1573          unique `low'.  In the second pass, we permit multiple high's
1574          relocs for a single `low'.  */
1575       seginfo = seg_info (l->seg);
1576       for (pass = 0; pass < 2; pass++)
1577         {
1578           fixS * f;
1579           fixS * prev;
1580
1581           prev = NULL;
1582           for (f = seginfo->fix_root; f != NULL; f = f->fx_next)
1583             {
1584               /* Check whether this is a `low' fixup which matches l->fixp.  */
1585               if (FX_OPINFO_R_TYPE (f) == BFD_RELOC_M32R_LO16
1586                   && f->fx_addsy == l->fixp->fx_addsy
1587                   && f->fx_offset == l->fixp->fx_offset
1588                   && (pass == 1
1589                       || prev == NULL
1590                       || (FX_OPINFO_R_TYPE (prev) != BFD_RELOC_M32R_HI16_SLO
1591                           && FX_OPINFO_R_TYPE (prev) != BFD_RELOC_M32R_HI16_ULO)
1592                       || prev->fx_addsy != f->fx_addsy
1593                       || prev->fx_offset !=  f->fx_offset))
1594                 {
1595                   fixS ** pf;
1596
1597                   /* Move l->fixp before f.  */
1598                   for (pf = &seginfo->fix_root;
1599                        * pf != l->fixp;
1600                        pf = & (* pf)->fx_next)
1601                     assert (* pf != NULL);
1602
1603                   * pf = l->fixp->fx_next;
1604
1605                   l->fixp->fx_next = f;
1606                   if (prev == NULL)
1607                     seginfo->fix_root = l->fixp;
1608                   else
1609                     prev->fx_next = l->fixp;
1610
1611                   break;
1612                 }
1613
1614               prev = f;
1615             }
1616
1617           if (f != NULL)
1618             break;
1619
1620           if (pass == 1)
1621             as_warn_where (l->fixp->fx_file, l->fixp->fx_line,
1622                            _("Unmatched high/shigh reloc"));
1623         }
1624     }
1625 }
1626
1627 /* See whether we need to force a relocation into the output file.
1628    This is used to force out switch and PC relative relocations when
1629    relaxing.  */
1630
1631 int
1632 m32r_force_relocation (fix)
1633      fixS * fix;
1634 {
1635   if (! m32r_relax)
1636     return 0;
1637
1638   return (fix->fx_pcrel
1639           || 0 /* ??? */);
1640 }
1641 \f
1642 /* Write a value out to the object file, using the appropriate endianness.  */
1643
1644 void
1645 md_number_to_chars (buf, val, n)
1646      char * buf;
1647      valueT val;
1648      int    n;
1649 {
1650   if (target_big_endian)
1651     number_to_chars_bigendian (buf, val, n);
1652   else
1653     number_to_chars_littleendian (buf, val, n);
1654 }
1655
1656 /* Turn a string in input_line_pointer into a floating point constant of type
1657    type, and store the appropriate bytes in *litP.  The number of LITTLENUMS
1658    emitted is stored in *sizeP .  An error message is returned, or NULL on OK.
1659 */
1660
1661 /* Equal to MAX_PRECISION in atof-ieee.c */
1662 #define MAX_LITTLENUMS 6
1663
1664 char *
1665 md_atof (type, litP, sizeP)
1666      char type;
1667      char *litP;
1668      int *sizeP;
1669 {
1670   int              i;
1671   int              prec;
1672   LITTLENUM_TYPE   words [MAX_LITTLENUMS];
1673   LITTLENUM_TYPE * wordP;
1674   char *           t;
1675   char *           atof_ieee ();
1676
1677   switch (type)
1678     {
1679     case 'f':
1680     case 'F':
1681     case 's':
1682     case 'S':
1683       prec = 2;
1684       break;
1685
1686     case 'd':
1687     case 'D':
1688     case 'r':
1689     case 'R':
1690       prec = 4;
1691       break;
1692
1693    /* FIXME: Some targets allow other format chars for bigger sizes here.  */
1694
1695     default:
1696       * sizeP = 0;
1697       return _("Bad call to md_atof()");
1698     }
1699
1700   t = atof_ieee (input_line_pointer, type, words);
1701   if (t)
1702     input_line_pointer = t;
1703   * sizeP = prec * sizeof (LITTLENUM_TYPE);
1704
1705   if (target_big_endian)
1706     {
1707       for (i = 0; i < prec; i++)
1708         {
1709           md_number_to_chars (litP, (valueT) words[i],
1710                               sizeof (LITTLENUM_TYPE));
1711           litP += sizeof (LITTLENUM_TYPE);
1712         }
1713     }
1714   else
1715     {
1716       for (i = prec - 1; i >= 0; i--)
1717         {
1718           md_number_to_chars (litP, (valueT) words[i],
1719                               sizeof (LITTLENUM_TYPE));
1720           litP += sizeof (LITTLENUM_TYPE);
1721         }
1722     }
1723      
1724   return 0;
1725 }
1726
1727 void
1728 m32r_elf_section_change_hook ()
1729 {
1730   /* If we have reached the end of a section and we have just emitted a
1731      16 bit insn, then emit a nop to make sure that the section ends on
1732      a 32 bit boundary.  */
1733   
1734   if (prev_insn.insn || seen_relaxable_p)
1735     (void) m32r_fill_insn (0);
1736 }