Add support for parallel instructions.
[external/binutils.git] / gas / config / tc-m32r.c
1 /* tc-m32r.c -- Assembler for the Mitsubishi M32R/X.
2    Copyright (C) 1996, 1997 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 "cgen-opc.h"
26
27 #include "../../opcodes/m32r-asm.c"
28 #include "../../opcodes/m32r-asm.in"
29
30 /* Non-null if last insn was a 16 bit insn on a 32 bit boundary
31    (i.e. was the first of two 16 bit insns).  */
32 static const CGEN_INSN * prev_insn = NULL;
33
34 /* Non-zero if we've seen a relaxable insn since the last 32 bit
35    alignment request.  */
36 static int seen_relaxable_p = 0;
37
38 /* Non-zero if -relax specified, in which case sufficient relocs are output
39    for the linker to do relaxing.
40    We do simple forms of relaxing internally, but they are always done.
41    This flag does not apply to them.  */
42 static int m32r_relax;
43
44 /* If non-NULL, pointer to cpu description file to read.
45    This allows runtime additions to the assembler.  */
46 static char * m32r_cpu_desc;
47
48 /* start-sanitize-m32rx */
49 /* Non-zero if -m32rx has been specified, in which case support for the
50    extended M32RX instruction set should be enabled.  */
51 static int enable_m32rx = 0;
52 /* end-sanitize-m32rx */
53
54 /* stuff for .scomm symbols.  */
55 static segT     sbss_section;
56 static asection scom_section;
57 static asymbol  scom_symbol;
58
59 const char comment_chars[]        = ";";
60 const char line_comment_chars[]   = "#";
61 const char line_separator_chars[] = "";
62 const char EXP_CHARS[]            = "eE";
63 const char FLT_CHARS[]            = "dD";
64
65 /* Relocations against symbols are done in two
66    parts, with a HI relocation and a LO relocation.  Each relocation
67    has only 16 bits of space to store an addend.  This means that in
68    order for the linker to handle carries correctly, it must be able
69    to locate both the HI and the LO relocation.  This means that the
70    relocations must appear in order in the relocation table.
71
72    In order to implement this, we keep track of each unmatched HI
73    relocation.  We then sort them so that they immediately precede the
74    corresponding LO relocation. */
75
76 struct m32r_hi_fixup
77 {
78   struct m32r_hi_fixup * next;  /* Next HI fixup.  */
79   fixS *                 fixp;  /* This fixup.  */
80   segT                   seg;   /* The section this fixup is in.  */
81
82 };
83
84 /* The list of unmatched HI relocs.  */
85
86 static struct m32r_hi_fixup * m32r_hi_fixup_list;
87
88 static void m32r_record_hi16 PARAMS ((int, fixS *, segT seg));
89
90 \f
91 /* start-sanitize-m32rx */
92 static void
93 allow_m32rx (int on)
94 {
95   enable_m32rx = on;
96
97   if (stdoutput != NULL)
98     bfd_set_arch_mach (stdoutput, TARGET_ARCH,
99                        enable_m32rx ? bfd_mach_m32rx : bfd_mach_m32r);
100 }
101 /* end-sanitize-m32rx */
102 \f
103 const char * md_shortopts = "";
104
105 struct option md_longopts[] =
106 {
107 /* start-sanitize-m32rx */
108 #define OPTION_M32RX    (OPTION_MD_BASE)
109   {"m32rx", no_argument, NULL, OPTION_M32RX},
110 /* end-sanitize-m32rx */
111
112 #if 0 /* not supported yet */
113 #define OPTION_RELAX  (OPTION_MD_BASE + 1)
114   {"relax", no_argument, NULL, OPTION_RELAX},
115 #define OPTION_CPU_DESC (OPTION_MD_BASE + 2)
116   {"cpu-desc", required_argument, NULL, OPTION_CPU_DESC},
117 #endif
118
119   {NULL, no_argument, NULL, 0}
120 };
121 size_t md_longopts_size = sizeof (md_longopts);
122
123 int
124 md_parse_option (c, arg)
125      int    c;
126      char * arg;
127 {
128   switch (c)
129     {
130 /* start-sanitize-m32rx */
131     case OPTION_M32RX:
132       allow_m32rx (1);
133       break;
134 /* end-sanitize-m32rx */
135       
136 #if 0 /* not supported yet */
137     case OPTION_RELAX:
138       m32r_relax = 1;
139       break;
140     case OPTION_CPU_DESC:
141       m32r_cpu_desc = arg;
142       break;
143 #endif
144     default:
145       return 0;
146     }
147   return 1;
148 }
149
150 void
151 md_show_usage (stream)
152   FILE * stream;
153 {
154   fprintf (stream, "M32R/X options:\n");
155 /* start-sanitize-m32rx */
156   fprintf (stream, "\
157 --m32rx                 support the extended m32rx instruction set\n");
158 /* end-sanitize-m32rx */
159
160 #if 0
161   fprintf (stream, "\
162 --relax                 create linker relaxable code\n");
163   fprintf (stream, "\
164 --cpu-desc              provide runtime cpu description file\n");
165 #endif
166
167
168 static void fill_insn PARAMS ((int));
169 static void m32r_scomm PARAMS ((int));
170
171 /* Set by md_assemble for use by m32r_fill_insn.  */
172 static subsegT prev_subseg;
173 static segT prev_seg;
174
175 /* The target specific pseudo-ops which we support.  */
176 const pseudo_typeS md_pseudo_table[] =
177 {
178   { "word", cons, 4 },
179   { "fillinsn", fill_insn, 0 },
180   { "scomm", m32r_scomm, 0 },
181 /* start-sanitize-m32rx */
182   { "m32r",  allow_m32rx, 0},
183   { "m32rx", allow_m32rx, 1},
184 /* end-sanitize-m32rx */
185   { NULL, NULL, 0 }
186 };
187
188 /* FIXME: Should be machine generated.  */
189 #define NOP_INSN 0x7000
190 #define PAR_NOP_INSN 0xf000 /* can only be used in 2nd slot */
191
192 /* When we align the .text section, insert the correct NOP pattern.
193    N is the power of 2 alignment.  LEN is the length of pattern FILL.
194    MAX is the maximum number of characters to skip when doing the alignment,
195    or 0 if there is no maximum.  */
196
197 int
198 m32r_do_align (n, fill, len, max)
199      int          n;
200      const char * fill;
201      int          len;
202      int          max;
203 {
204   if ((fill == NULL || (* fill == 0 && len == 1))
205       && (now_seg->flags & SEC_CODE) != 0
206       /* Only do this special handling if aligning to at least a
207          4 byte boundary.  */
208       && n > 1
209       /* Only do this special handling if we're allowed to emit at
210          least two bytes.  */
211       && (max == 0 || max > 1))
212     {
213       static const unsigned char nop_pattern[] = { 0xf0, 0x00 };
214
215 #if 0
216       /* First align to a 2 byte boundary, in case there is an odd .byte.  */
217       /* FIXME: How much memory will cause gas to use when assembling a big
218          program?  Perhaps we can avoid the frag_align call?  */
219       frag_align (1, 0, 0);
220 #endif
221       /* Next align to a 4 byte boundary (we know n >= 2) using a parallel
222          nop.  */
223       frag_align_pattern (2, nop_pattern, sizeof nop_pattern, 0);
224       /* If doing larger alignments use a repeating sequence of appropriate
225          nops.  */
226       if (n > 2)
227         {
228           static const unsigned char multi_nop_pattern[] =
229           { 0x70, 0x00, 0xf0, 0x00 };
230           frag_align_pattern (n, multi_nop_pattern, sizeof multi_nop_pattern,
231                               max ? max - 2 : 0);
232         }
233       return 1;
234     }
235
236   return 0;
237 }
238
239 static void
240 assemble_nop (opcode)
241      int opcode;
242 {
243   char * f = frag_more (2);
244   md_number_to_chars (f, opcode, 2);
245 }
246
247 /* If the last instruction was the first of 2 16 bit insns,
248    output a nop to move the PC to a 32 bit boundary.
249
250    This is done via an alignment specification since branch relaxing
251    may make it unnecessary.
252
253    Internally, we need to output one of these each time a 32 bit insn is
254    seen after an insn that is relaxable.  */
255
256 static void
257 fill_insn (ignore)
258      int ignore;
259 {
260   (void) m32r_do_align (2, NULL, 0, 0);
261   prev_insn = NULL;
262   seen_relaxable_p = 0;
263 }
264
265 /* Cover function to fill_insn called after a label and at end of assembly.
266
267    The result is always 1: we're called in a conditional to see if the
268    current line is a label.  */
269
270 int
271 m32r_fill_insn (done)
272      int done;
273 {
274   segT    seg;
275   subsegT subseg;
276
277   if (prev_seg != NULL)
278     {
279       seg    = now_seg;
280       subseg = now_subseg;
281       
282       subseg_set (prev_seg, prev_subseg);
283       
284       fill_insn (0);
285       
286       subseg_set (seg, subseg);
287     }
288   
289   return 1;
290 }
291 \f
292 void
293 md_begin ()
294 {
295   flagword applicable;
296   segT     seg;
297   subsegT  subseg;
298
299   /* Initialize the `cgen' interface.  */
300
301   /* This is a callback from cgen to gas to parse operands.  */
302   cgen_parse_operand_fn = cgen_parse_operand;
303   
304   /* Set the machine number and endian.  */
305   CGEN_SYM (init_asm) (0 /* mach number */,
306                        target_big_endian ?
307                        CGEN_ENDIAN_BIG : CGEN_ENDIAN_LITTLE);
308
309 #if 0 /* not supported yet */
310   /* If a runtime cpu description file was provided, parse it.  */
311   if (m32r_cpu_desc != NULL)
312     {
313       const char * errmsg;
314
315       errmsg = cgen_read_cpu_file (m32r_cpu_desc);
316       if (errmsg != NULL)
317         as_bad ("%s: %s", m32r_cpu_desc, errmsg);
318     }
319 #endif
320
321   /* Save the current subseg so we can restore it [it's the default one and
322      we don't want the initial section to be .sbss].  */
323   seg    = now_seg;
324   subseg = now_subseg;
325
326   /* The sbss section is for local .scomm symbols.  */
327   sbss_section = subseg_new (".sbss", 0);
328   
329   /* This is copied from perform_an_assembly_pass.  */
330   applicable = bfd_applicable_section_flags (stdoutput);
331   bfd_set_section_flags (stdoutput, sbss_section, applicable & SEC_ALLOC);
332   
333 #if 0 /* What does this do? [see perform_an_assembly_pass]  */
334   seg_info (bss_section)->bss = 1;
335 #endif
336
337   subseg_set (seg, subseg);
338
339   /* We must construct a fake section similar to bfd_com_section
340      but with the name .scommon.  */
341   scom_section                = bfd_com_section;
342   scom_section.name           = ".scommon";
343   scom_section.output_section = & scom_section;
344   scom_section.symbol         = & scom_symbol;
345   scom_section.symbol_ptr_ptr = & scom_section.symbol;
346   scom_symbol                 = * bfd_com_section.symbol;
347   scom_symbol.name            = ".scommon";
348   scom_symbol.section         = & scom_section;
349
350 /* start-sanitize-m32rx */
351   allow_m32rx (enable_m32rx);
352 /* end-sanitize-m32rx */
353 }
354
355 /* Returns non zero if the given instruction writes to a destination register.  */
356 static int
357 writes_to_dest_reg (insn)
358      const CGEN_INSN * insn;
359 {
360   unsigned char * syntax = CGEN_SYNTAX_STRING (CGEN_INSN_SYNTAX (insn));
361   unsigned char   c;
362   
363   /* Scan the syntax string looking for a destination register.  */
364   while ((c = (* syntax ++)) != 0)
365     if (c == 128 + M32R_OPERAND_DR)
366       break;
367
368   return c;
369 }
370
371 /* Returns an integer representing the destination register of
372    the given insn, or -1 if the insn has no destination.  */
373 static int
374 get_dest_reg (insn)
375      const CGEN_INSN * insn;
376 {
377   /* XXX to be done.  */
378   return -1;
379 }
380
381 void
382 md_assemble (str)
383      char * str;
384 {
385 #ifdef CGEN_INT_INSN
386   cgen_insn_t              buffer [CGEN_MAX_INSN_SIZE / sizeof (cgen_insn_t)];
387   cgen_insn_t              prev_buffer [CGEN_MAX_INSN_SIZE / sizeof (cgen_insn_t)];
388 #else
389   char                     buffer [CGEN_MAX_INSN_SIZE];
390   char                     prev_buffer [CGEN_MAX_INSN_SIZE];
391 #endif
392   CGEN_FIELDS              fields;
393   CGEN_FIELDS              prev_fields;
394   const CGEN_INSN *        insn;
395   char *                   errmsg;
396   char *                   str2 = NULL;
397   int                      is_parallel = false;
398   
399   /* Initialize GAS's cgen interface for a new instruction.  */
400   cgen_asm_init_parse ();
401
402   /* Look for a parallel instruction seperator.  */
403   if ((str2 = strstr (str, "||")) != NULL)
404     {
405       char * str3;
406       
407       * str2 = 0; /* Seperate the two instructions.  */
408
409       /* If there was a previous 16 bit insn, then fill the following 16 bit slot,
410          so that the parallel instruction will start on a 32 bit boundary.  */
411       if (prev_insn)
412         fill_insn (0);
413
414       /* Assemble the first instruction.  */
415       prev_insn = CGEN_SYM (assemble_insn) (str, & prev_fields, prev_buffer, & errmsg);
416       if (! prev_insn)
417         {
418           as_bad (errmsg);
419           return;
420         }
421
422       /* Check to see if this is an allowable parallel insn.  */
423       if (CGEN_INSN_ATTR (prev_insn, CGEN_INSN_PIPE) == PIPE_NONE)
424         {
425           as_bad ("instruction '%s' cannot be executed in parallel.", str);
426           return;
427         }
428         
429 /* start-sanitize-m32rx */
430       if (! enable_m32rx && 
431           CGEN_INSN_ATTR (prev_insn, CGEN_INSN_MACH) == MACH_M32RX)
432         {
433           as_bad ("instruction '%s' is for the M32RX only", str);
434           return;
435         }
436 /* end-sanitize-m32rx */
437   
438       /* fixups = fixups->next; */
439
440       *str2 = '|';       /* Restore the original assembly text, just in case it is needed.  */
441       str3  = str;       /* Save the original string pointer.  */
442       str   = str2 + 2;  /* Advanced past the parsed string.  */
443       str2  = str3;      /* Remember the entire string in case it is needed for error messages.  */
444
445       is_parallel = true;
446     }
447   
448   insn = CGEN_SYM (assemble_insn) (str, & fields, buffer, & errmsg);
449   if (!insn)
450     {
451       as_bad (errmsg);
452       return;
453     }
454
455 /* start-sanitize-m32rx */
456   if (! enable_m32rx
457       && CGEN_INSN_ATTR (insn, CGEN_INSN_MACH) == (1 << MACH_M32RX))
458     {
459       as_bad ("instruction '%s' is for the M32RX only", str);
460       return;
461     }
462 /* end-sanitize-m32rx */
463   
464   if (is_parallel)
465     {
466 /* start-sanitize-m32rx */
467       if (! enable_m32rx)
468         {
469           if (strcmp (prev_insn->name, "nop") != 0
470               && strcmp (insn->name, "nop") != 0)
471             {
472               as_bad ("'%s': only the NOP instruction can be issued in parallel on the m32r", str2);
473               return;
474             }
475         }
476 /* end-sanitize-m32rx */
477       
478       /* Check to see if this is an allowable parallel insn.  */
479       if (CGEN_INSN_ATTR (insn, CGEN_INSN_PIPE) == PIPE_NONE)
480         {
481           as_bad ("instruction '%s', cannot be executed in parallel.", str);
482           return;
483         }
484
485       /* Check to see that the two instructions can be placed in parallel. */
486       if ((CGEN_INSN_ATTR (insn, CGEN_INSN_PIPE) == CGEN_INSN_ATTR (prev_insn, CGEN_INSN_PIPE))
487           && (CGEN_INSN_ATTR (insn, CGEN_INSN_PIPE) != PIPE_OS))
488         {
489           as_bad ("'%s': both instructions use the same execution pipeline", str2);
490           return;
491         }
492 #if 0
493       /* Check that the instructions do not write to the same destination register.  */
494       if (writes_to_dest_reg (insn)
495           && writes_to_dest_reg (prev_insn) /* This test is actually redundant.  */
496           && get_dest_reg (insn) == get_dest_reg (prev_insn))
497         {
498           as_bad ("'%s': both instructions write to the same destination register", str2);
499           return;
500         }
501 #endif
502       
503       /* Force the top bit of the second insn to be set.  */
504 #if 0 /*def CGEN_INT_INSN*/
505 #define MAKE_PARALLEL(insn)     ((insn) |= 0x8000)
506       switch (CGEN_FIELDS_BITSIZE (& fields))
507         {
508           bfd_vma value;
509           
510         case 16:
511           if (CGEN_CURRENT_ENDIAN == CGEN_ENDIAN_BIG)
512             {
513               value = bfd_getb16 ((bfd_vma) * buffer);
514               MAKE_PARALLEL (value);
515               bfd_putb16 (value, buffer);
516             }
517           else
518             {
519               value = bfd_getl16 ((bfd_vma) * buffer);
520               MAKE_PARALLEL (value);
521               bfd_putl16 (value, buffer);
522             }
523           break;
524         default:
525           abort ();
526         }
527 #else
528 #define MAKE_PARALLEL(insn)     ((insn) |= 0x80)
529       MAKE_PARALLEL (buffer [CGEN_CURRENT_ENDIAN == CGEN_ENDIAN_BIG ? 0 : 1]);
530 #endif
531       
532       /* Generate the parallel instructions */
533       cgen_asm_finish_insn (prev_insn, prev_buffer, CGEN_FIELDS_BITSIZE (& prev_fields));
534       cgen_asm_finish_insn (insn, buffer, CGEN_FIELDS_BITSIZE (& fields));
535
536       /* If prev_ins is relaxable (and insn is not), then swap them, so that the test
537          after the end of this if-then-else section will work.  */
538       if (CGEN_INSN_ATTR (prev_insn, CGEN_INSN_RELAXABLE))
539         insn = prev_insn;
540       
541       /* Clear the prev_insn variable, since it only used if the insn was the first
542          16 bit insn in a 32 bit word.  */
543       prev_insn = NULL;
544     }
545   else if (CGEN_INSN_BITSIZE (insn) == 32)
546     {
547       /* 32 bit insns must live on 32 bit boundaries.  */
548       if (prev_insn || seen_relaxable_p)
549         {
550           /* FIXME: If calling fill_insn too many times turns us into a memory
551              pig, can we call assemble_nop instead of !seen_relaxable_p?  */
552           fill_insn (0);
553         }
554       
555       cgen_asm_finish_insn (insn, buffer, CGEN_FIELDS_BITSIZE (& fields));
556     }
557   else
558     {
559       /* Keep track of whether we've seen a pair of 16 bit insns.
560          PREV_INSN is NULL when we're on a 32 bit boundary.  */
561       if (prev_insn)
562         prev_insn = NULL;
563       else
564         prev_insn = insn;
565       
566       cgen_asm_finish_insn (insn, buffer, CGEN_FIELDS_BITSIZE (& fields));
567
568       /* If the insn needs the following one to be on a 32 bit boundary
569          (e.g. subroutine calls), fill this insn's slot.  */
570       if (prev_insn
571           && CGEN_INSN_ATTR (insn, CGEN_INSN_FILL_SLOT) != 0)
572         fill_insn (0);
573     }
574
575   /* If this is a relaxable insn (can be replaced with a larger version)
576      mark the fact so that we can emit an alignment directive for a following
577      32 bit insn if we see one.   */
578   if (CGEN_INSN_ATTR (insn, CGEN_INSN_RELAXABLE) != 0)
579     seen_relaxable_p = 1;
580
581   /* Set these so m32r_fill_insn can use them.  */
582   prev_seg    = now_seg;
583   prev_subseg = now_subseg;
584 }
585
586 /* The syntax in the manual says constants begin with '#'.
587    We just ignore it.  */
588
589 void 
590 md_operand (expressionP)
591      expressionS * expressionP;
592 {
593   if (* input_line_pointer == '#')
594     {
595       input_line_pointer ++;
596       expression (expressionP);
597     }
598 }
599
600 valueT
601 md_section_align (segment, size)
602      segT   segment;
603      valueT size;
604 {
605   int align = bfd_get_section_alignment (stdoutput, segment);
606   return ((size + (1 << align) - 1) & (-1 << align));
607 }
608
609 symbolS *
610 md_undefined_symbol (name)
611   char * name;
612 {
613   return 0;
614 }
615 \f
616 /* .scomm pseudo-op handler.
617
618    This is a new pseudo-op to handle putting objects in .scommon.
619    By doing this the linker won't need to do any work and more importantly
620    it removes the implicit -G arg necessary to correctly link the object file.
621 */
622
623 static void
624 m32r_scomm (ignore)
625      int ignore;
626 {
627   register char *    name;
628   register char      c;
629   register char *    p;
630   offsetT            size;
631   register symbolS * symbolP;
632   offsetT            align;
633   int                align2;
634
635   name = input_line_pointer;
636   c = get_symbol_end ();
637
638   /* just after name is now '\0' */
639   p = input_line_pointer;
640   * p = c;
641   SKIP_WHITESPACE ();
642   if (* input_line_pointer != ',')
643     {
644       as_bad ("Expected comma after symbol-name: rest of line ignored.");
645       ignore_rest_of_line ();
646       return;
647     }
648
649   input_line_pointer++;         /* skip ',' */
650   if ((size = get_absolute_expression ()) < 0)
651     {
652       as_warn (".SCOMMon length (%ld.) <0! Ignored.", (long) size);
653       ignore_rest_of_line ();
654       return;
655     }
656
657   /* The third argument to .scomm is the alignment.  */
658   if (* input_line_pointer != ',')
659     align = 8;
660   else
661     {
662       ++ input_line_pointer;
663       align = get_absolute_expression ();
664       if (align <= 0)
665         {
666           as_warn ("ignoring bad alignment");
667           align = 8;
668         }
669     }
670   /* Convert to a power of 2 alignment.  */
671   if (align)
672     {
673       for (align2 = 0; (align & 1) == 0; align >>= 1, ++ align2)
674         continue;
675       if (align != 1)
676         {
677           as_bad ("Common alignment not a power of 2");
678           ignore_rest_of_line ();
679           return;
680         }
681     }
682   else
683     align2 = 0;
684
685   * p = 0;
686   symbolP = symbol_find_or_make (name);
687   * p = c;
688
689   if (S_IS_DEFINED (symbolP))
690     {
691       as_bad ("Ignoring attempt to re-define symbol `%s'.",
692               S_GET_NAME (symbolP));
693       ignore_rest_of_line ();
694       return;
695     }
696
697   if (S_GET_VALUE (symbolP) && S_GET_VALUE (symbolP) != (valueT) size)
698     {
699       as_bad ("Length of .scomm \"%s\" is already %ld. Not changed to %ld.",
700               S_GET_NAME (symbolP),
701               (long) S_GET_VALUE (symbolP),
702               (long) size);
703
704       ignore_rest_of_line ();
705       return;
706     }
707
708   if (symbolP->local)
709     {
710       segT   old_sec    = now_seg;
711       int    old_subsec = now_subseg;
712       char * pfrag;
713
714       record_alignment (sbss_section, align2);
715       subseg_set (sbss_section, 0);
716       if (align2)
717         frag_align (align2, 0, 0);
718       if (S_GET_SEGMENT (symbolP) == sbss_section)
719         symbolP->sy_frag->fr_symbol = 0;
720       symbolP->sy_frag = frag_now;
721       pfrag = frag_var (rs_org, 1, 1, (relax_substateT) 0, symbolP, size,
722                         (char *) 0);
723       * pfrag = 0;
724       S_SET_SIZE (symbolP, size);
725       S_SET_SEGMENT (symbolP, sbss_section);
726       S_CLEAR_EXTERNAL (symbolP);
727       subseg_set (old_sec, old_subsec);
728     }
729   else
730     {
731       S_SET_VALUE (symbolP, (valueT) size);
732       S_SET_ALIGN (symbolP, align2);
733       S_SET_EXTERNAL (symbolP);
734       S_SET_SEGMENT (symbolP, &scom_section);
735     }
736
737   demand_empty_rest_of_line ();
738 }
739 \f
740 /* Interface to relax_segment.  */
741
742 /* FIXME: Build table by hand, get it working, then machine generate.  */
743
744 const relax_typeS md_relax_table[] =
745 {
746 /* The fields are:
747    1) most positive reach of this state,
748    2) most negative reach of this state,
749    3) how many bytes this mode will add to the size of the current frag
750    4) which index into the table to try if we can't fit into this one.  */
751
752   /* The first entry must be unused because an `rlx_more' value of zero ends
753      each list.  */
754   {1, 1, 0, 0},
755
756   /* The displacement used by GAS is from the end of the 2 byte insn,
757      so we subtract 2 from the following.  */
758   /* 16 bit insn, 8 bit disp -> 10 bit range.
759      This doesn't handle a branch in the right slot at the border:
760      the "& -4" isn't taken into account.  It's not important enough to
761      complicate things over it, so we subtract an extra 2 (or + 2 in -ve
762      case).  */
763   {511 - 2 - 2, -512 - 2 + 2, 0, 2 },
764   /* 32 bit insn, 24 bit disp -> 26 bit range.  */
765   {0x2000000 - 1 - 2, -0x2000000 - 2, 2, 0 },
766   /* Same thing, but with leading nop for alignment.  */
767   {0x2000000 - 1 - 2, -0x2000000 - 2, 4, 0 }
768 };
769
770 long
771 m32r_relax_frag (fragP, stretch)
772      fragS * fragP;
773      long    stretch;
774 {
775   /* Address of branch insn.  */
776   long address = fragP->fr_address + fragP->fr_fix - 2;
777   long growth = 0;
778
779   /* Keep 32 bit insns aligned on 32 bit boundaries.  */
780   if (fragP->fr_subtype == 2)
781     {
782       if ((address & 3) != 0)
783         {
784           fragP->fr_subtype = 3;
785           growth = 2;
786         }
787     }
788   else if (fragP->fr_subtype == 3)
789     {
790       if ((address & 3) == 0)
791         {
792           fragP->fr_subtype = 2;
793           growth = -2;
794         }
795     }
796   else
797     {
798       growth = relax_frag (fragP, stretch);
799
800       /* Long jump on odd halfword boundary?  */
801       if (fragP->fr_subtype == 2 && (address & 3) != 0)
802         {
803           fragP->fr_subtype = 3;
804           growth += 2;
805         }
806     }
807
808   return growth;
809 }
810
811 /* Return an initial guess of the length by which a fragment must grow to
812    hold a branch to reach its destination.
813    Also updates fr_type/fr_subtype as necessary.
814
815    Called just before doing relaxation.
816    Any symbol that is now undefined will not become defined.
817    The guess for fr_var is ACTUALLY the growth beyond fr_fix.
818    Whatever we do to grow fr_fix or fr_var contributes to our returned value.
819    Although it may not be explicit in the frag, pretend fr_var starts with a
820    0 value.  */
821
822 int
823 md_estimate_size_before_relax (fragP, segment)
824      fragS * fragP;
825      segT    segment;
826 {
827   int    old_fr_fix = fragP->fr_fix;
828   char * opcode = fragP->fr_opcode;
829
830   /* The only thing we have to handle here are symbols outside of the
831      current segment.  They may be undefined or in a different segment in
832      which case linker scripts may place them anywhere.
833      However, we can't finish the fragment here and emit the reloc as insn
834      alignment requirements may move the insn about.  */
835
836   if (S_GET_SEGMENT (fragP->fr_symbol) != segment)
837     {
838       /* The symbol is undefined in this segment.
839          Change the relaxation subtype to the max allowable and leave
840          all further handling to md_convert_frag.  */
841       fragP->fr_subtype = 2;
842
843 #if 0 /* Can't use this, but leave in for illustration.  */     
844       /* Change 16 bit insn to 32 bit insn.  */
845       opcode[0] |= 0x80;
846
847       /* Increase known (fixed) size of fragment.  */
848       fragP->fr_fix += 2;
849
850       /* Create a relocation for it.  */
851       fix_new (fragP, old_fr_fix, 4,
852                fragP->fr_symbol,
853                fragP->fr_offset, 1 /* pcrel */,
854                /* FIXME: Can't use a real BFD reloc here.
855                   cgen_md_apply_fix3 can't handle it.  */
856                BFD_RELOC_M32R_26_PCREL);
857
858       /* Mark this fragment as finished.  */
859       frag_wane (fragP);
860 #else
861       {
862         const CGEN_INSN * insn;
863         int               i;
864
865         /* Update the recorded insn.
866            Fortunately we don't have to look very far.
867            FIXME: Change this to record in the instruction the next higher
868            relaxable insn to use.  */
869         for (i = 0, insn = fragP->fr_cgen.insn; i < 4; i++, insn++)
870           {
871             if ((strcmp (CGEN_INSN_MNEMONIC (insn),
872                          CGEN_INSN_MNEMONIC (fragP->fr_cgen.insn))
873                  == 0)
874                 && CGEN_INSN_ATTR (insn, CGEN_INSN_RELAX))
875               break;
876           }
877         if (i == 4)
878           abort ();
879         fragP->fr_cgen.insn = insn;
880         return 2;
881       }
882 #endif
883     }
884
885   return (fragP->fr_var + fragP->fr_fix - old_fr_fix);
886
887
888 /* *fragP has been relaxed to its final size, and now needs to have
889    the bytes inside it modified to conform to the new size.
890
891    Called after relaxation is finished.
892    fragP->fr_type == rs_machine_dependent.
893    fragP->fr_subtype is the subtype of what the address relaxed to.  */
894
895 void
896 md_convert_frag (abfd, sec, fragP)
897   bfd *abfd;
898   segT sec;
899   fragS *fragP;
900 {
901   char * opcode;
902   char * displacement;
903   int    target_address;
904   int    opcode_address;
905   int    extension;
906   int    addend;
907
908   opcode = fragP->fr_opcode;
909
910   /* Address opcode resides at in file space.  */
911   opcode_address = fragP->fr_address + fragP->fr_fix - 2;
912
913   switch (fragP->fr_subtype)
914     {
915     case 1 :
916       extension = 0;
917       displacement = & opcode[1];
918       break;
919     case 2 :
920       opcode[0] |= 0x80;
921       extension = 2;
922       displacement = & opcode[1];
923       break;
924     case 3 :
925       opcode[2] = opcode[0] | 0x80;
926       md_number_to_chars (opcode, PAR_NOP_INSN, 2);
927       opcode_address += 2;
928       extension = 4;
929       displacement = & opcode[3];
930       break;
931     default :
932       abort ();
933     }
934
935   if (S_GET_SEGMENT (fragP->fr_symbol) != sec)
936     {
937       /* symbol must be resolved by linker */
938       if (fragP->fr_offset & 3)
939         as_warn ("Addend to unresolved symbol not on word boundary.");
940       addend = fragP->fr_offset >> 2;
941     }
942   else
943     {
944       /* Address we want to reach in file space.  */
945       target_address = S_GET_VALUE (fragP->fr_symbol) + fragP->fr_offset;
946       target_address += fragP->fr_symbol->sy_frag->fr_address;
947       addend = (target_address - (opcode_address & -4)) >> 2;
948     }
949
950   /* Create a relocation for symbols that must be resolved by the linker.
951      Otherwise output the completed insn.  */
952
953   if (S_GET_SEGMENT (fragP->fr_symbol) != sec)
954     {
955       assert (fragP->fr_subtype != 1);
956       assert (fragP->fr_cgen.insn != 0);
957       cgen_record_fixup (fragP,
958                          /* Offset of branch insn in frag.  */
959                          fragP->fr_fix + extension - 4,
960                          fragP->fr_cgen.insn,
961                          4 /*length*/,
962                          /* FIXME: quick hack */
963 #if 0
964                          CGEN_OPERAND_ENTRY (fragP->fr_cgen.opindex),
965 #else
966                          CGEN_OPERAND_ENTRY (M32R_OPERAND_DISP24),
967 #endif
968                          fragP->fr_cgen.opinfo,
969                          fragP->fr_symbol, fragP->fr_offset);
970     }
971
972 #define SIZE_FROM_RELAX_STATE(n) ((n) == 1 ? 1 : 3)
973
974   md_number_to_chars (displacement, (valueT) addend,
975                       SIZE_FROM_RELAX_STATE (fragP->fr_subtype));
976
977   fragP->fr_fix += extension;
978 }
979 \f
980 /* Functions concerning relocs.  */
981
982 /* The location from which a PC relative jump should be calculated,
983    given a PC relative reloc.  */
984
985 long
986 md_pcrel_from_section (fixP, sec)
987      fixS * fixP;
988      segT   sec;
989 {
990   if (fixP->fx_addsy != (symbolS *) NULL
991       && (! S_IS_DEFINED (fixP->fx_addsy)
992           || S_GET_SEGMENT (fixP->fx_addsy) != sec))
993     {
994       /* The symbol is undefined (or is defined but not in this section).
995          Let the linker figure it out.  */
996       return 0;
997     }
998
999   return (fixP->fx_frag->fr_address + fixP->fx_where) & -4L;
1000 }
1001
1002 /* Return the bfd reloc type for OPERAND of INSN at fixup FIXP.
1003    Returns BFD_RELOC_NONE if no reloc type can be found.
1004    *FIXP may be modified if desired.  */
1005
1006 bfd_reloc_code_real_type
1007 CGEN_SYM (lookup_reloc) (insn, operand, fixP)
1008      const CGEN_INSN *    insn;
1009      const CGEN_OPERAND * operand;
1010      fixS *               fixP;
1011 {
1012   switch (CGEN_OPERAND_TYPE (operand))
1013     {
1014     case M32R_OPERAND_DISP8 : return  BFD_RELOC_M32R_10_PCREL;
1015     case M32R_OPERAND_DISP16 : return BFD_RELOC_M32R_18_PCREL;
1016     case M32R_OPERAND_DISP24 : return BFD_RELOC_M32R_26_PCREL;
1017     case M32R_OPERAND_UIMM24 : return BFD_RELOC_M32R_24;
1018     case M32R_OPERAND_HI16 :
1019     case M32R_OPERAND_SLO16 :
1020     case M32R_OPERAND_ULO16 :
1021       /* If low/high/shigh/sda was used, it is recorded in `opinfo'.  */
1022       if (fixP->tc_fix_data.opinfo != 0)
1023         return fixP->tc_fix_data.opinfo;
1024       break;
1025     }
1026   return BFD_RELOC_NONE;
1027 }
1028
1029 /* Called while parsing an instruction to create a fixup.
1030    We need to check for HI16 relocs and queue them up for later sorting.  */
1031
1032 fixS *
1033 m32r_cgen_record_fixup_exp (frag, where, insn, length, operand, opinfo, exp)
1034      fragS *              frag;
1035      int                  where;
1036      const CGEN_INSN *    insn;
1037      int                  length;
1038      const CGEN_OPERAND * operand;
1039      int                  opinfo;
1040      expressionS *        exp;
1041 {
1042   fixS * fixP = cgen_record_fixup_exp (frag, where, insn, length,
1043                                       operand, opinfo, exp);
1044
1045   switch (CGEN_OPERAND_TYPE (operand))
1046     {
1047     case M32R_OPERAND_HI16 :
1048       /* If low/high/shigh/sda was used, it is recorded in `opinfo'.  */
1049       if (fixP->tc_fix_data.opinfo == BFD_RELOC_M32R_HI16_SLO
1050           || fixP->tc_fix_data.opinfo == BFD_RELOC_M32R_HI16_ULO)
1051         m32r_record_hi16 (fixP->tc_fix_data.opinfo, fixP, now_seg);
1052       break;
1053     }
1054
1055   return fixP;
1056 }
1057
1058 /* Record a HI16 reloc for later matching with its LO16 cousin.  */
1059
1060 static void
1061 m32r_record_hi16 (reloc_type, fixP, seg)
1062      int    reloc_type;
1063      fixS * fixP;
1064      segT   seg;
1065 {
1066   struct m32r_hi_fixup * hi_fixup;
1067
1068   assert (reloc_type == BFD_RELOC_M32R_HI16_SLO
1069           || reloc_type == BFD_RELOC_M32R_HI16_ULO);
1070
1071   hi_fixup = ((struct m32r_hi_fixup *)
1072               xmalloc (sizeof (struct m32r_hi_fixup)));
1073   hi_fixup->fixp = fixP;
1074   hi_fixup->seg  = now_seg;
1075   hi_fixup->next = m32r_hi_fixup_list;
1076   
1077   m32r_hi_fixup_list = hi_fixup;
1078 }
1079
1080 /* Return BFD reloc type from opinfo field in a fixS.
1081    It's tricky using fx_r_type in m32r_frob_file because the values
1082    are BFD_RELOC_UNUSED + operand number.  */
1083 #define FX_OPINFO_R_TYPE(f) ((f)->tc_fix_data.opinfo)
1084
1085 /* Sort any unmatched HI16 relocs so that they immediately precede
1086    the corresponding LO16 reloc.  This is called before md_apply_fix and
1087    tc_gen_reloc.  */
1088
1089 void
1090 m32r_frob_file ()
1091 {
1092   struct m32r_hi_fixup * l;
1093
1094   for (l = m32r_hi_fixup_list; l != NULL; l = l->next)
1095     {
1096       segment_info_type * seginfo;
1097       int                 pass;
1098
1099       assert (FX_OPINFO_R_TYPE (l->fixp) == BFD_RELOC_M32R_HI16_SLO
1100               || FX_OPINFO_R_TYPE (l->fixp) == BFD_RELOC_M32R_HI16_ULO);
1101
1102       /* Check quickly whether the next fixup happens to be a matching low.  */
1103       if (l->fixp->fx_next != NULL
1104           && FX_OPINFO_R_TYPE (l->fixp->fx_next) == BFD_RELOC_M32R_LO16
1105           && l->fixp->fx_addsy == l->fixp->fx_next->fx_addsy
1106           && l->fixp->fx_offset == l->fixp->fx_next->fx_offset)
1107         continue;
1108
1109       /* Look through the fixups for this segment for a matching `low'.
1110          When we find one, move the high/shigh just in front of it.  We do
1111          this in two passes.  In the first pass, we try to find a
1112          unique `low'.  In the second pass, we permit multiple high's
1113          relocs for a single `low'.  */
1114       seginfo = seg_info (l->seg);
1115       for (pass = 0; pass < 2; pass++)
1116         {
1117           fixS * f;
1118           fixS * prev;
1119
1120           prev = NULL;
1121           for (f = seginfo->fix_root; f != NULL; f = f->fx_next)
1122             {
1123               /* Check whether this is a `low' fixup which matches l->fixp.  */
1124               if (FX_OPINFO_R_TYPE (f) == BFD_RELOC_M32R_LO16
1125                   && f->fx_addsy == l->fixp->fx_addsy
1126                   && f->fx_offset == l->fixp->fx_offset
1127                   && (pass == 1
1128                       || prev == NULL
1129                       || (FX_OPINFO_R_TYPE (prev) != BFD_RELOC_M32R_HI16_SLO
1130                           && FX_OPINFO_R_TYPE (prev) != BFD_RELOC_M32R_HI16_ULO)
1131                       || prev->fx_addsy != f->fx_addsy
1132                       || prev->fx_offset !=  f->fx_offset))
1133                 {
1134                   fixS ** pf;
1135
1136                   /* Move l->fixp before f.  */
1137                   for (pf = &seginfo->fix_root;
1138                        * pf != l->fixp;
1139                        pf = & (* pf)->fx_next)
1140                     assert (* pf != NULL);
1141
1142                   * pf = l->fixp->fx_next;
1143
1144                   l->fixp->fx_next = f;
1145                   if (prev == NULL)
1146                     seginfo->fix_root = l->fixp;
1147                   else
1148                     prev->fx_next = l->fixp;
1149
1150                   break;
1151                 }
1152
1153               prev = f;
1154             }
1155
1156           if (f != NULL)
1157             break;
1158
1159           if (pass == 1)
1160             as_warn_where (l->fixp->fx_file, l->fixp->fx_line,
1161                            "Unmatched high/shigh reloc");
1162         }
1163     }
1164 }
1165
1166 /* See whether we need to force a relocation into the output file.
1167    This is used to force out switch and PC relative relocations when
1168    relaxing.  */
1169
1170 int
1171 m32r_force_relocation (fix)
1172      fixS * fix;
1173 {
1174   if (! m32r_relax)
1175     return 0;
1176
1177   return (fix->fx_pcrel
1178           || 0 /* ??? */);
1179 }
1180 \f
1181 /* Write a value out to the object file, using the appropriate endianness.  */
1182
1183 void
1184 md_number_to_chars (buf, val, n)
1185      char * buf;
1186      valueT val;
1187      int    n;
1188 {
1189   if (target_big_endian)
1190     number_to_chars_bigendian (buf, val, n);
1191   else
1192     number_to_chars_littleendian (buf, val, n);
1193 }
1194
1195 /* Turn a string in input_line_pointer into a floating point constant of type
1196    type, and store the appropriate bytes in *litP.  The number of LITTLENUMS
1197    emitted is stored in *sizeP .  An error message is returned, or NULL on OK.
1198 */
1199
1200 /* Equal to MAX_PRECISION in atof-ieee.c */
1201 #define MAX_LITTLENUMS 6
1202
1203 char *
1204 md_atof (type, litP, sizeP)
1205      char type;
1206      char *litP;
1207      int *sizeP;
1208 {
1209   int              i;
1210   int              prec;
1211   LITTLENUM_TYPE   words [MAX_LITTLENUMS];
1212   LITTLENUM_TYPE * wordP;
1213   char *           t;
1214   char *           atof_ieee ();
1215
1216   switch (type)
1217     {
1218     case 'f':
1219     case 'F':
1220     case 's':
1221     case 'S':
1222       prec = 2;
1223       break;
1224
1225     case 'd':
1226     case 'D':
1227     case 'r':
1228     case 'R':
1229       prec = 4;
1230       break;
1231
1232    /* FIXME: Some targets allow other format chars for bigger sizes here.  */
1233
1234     default:
1235       * sizeP = 0;
1236       return "Bad call to md_atof()";
1237     }
1238
1239   t = atof_ieee (input_line_pointer, type, words);
1240   if (t)
1241     input_line_pointer = t;
1242   * sizeP = prec * sizeof (LITTLENUM_TYPE);
1243
1244   if (target_big_endian)
1245     {
1246       for (i = 0; i < prec; i++)
1247         {
1248           md_number_to_chars (litP, (valueT) words[i],
1249                               sizeof (LITTLENUM_TYPE));
1250           litP += sizeof (LITTLENUM_TYPE);
1251         }
1252     }
1253   else
1254     {
1255       for (i = prec - 1; i >= 0; i--)
1256         {
1257           md_number_to_chars (litP, (valueT) words[i],
1258                               sizeof (LITTLENUM_TYPE));
1259           litP += sizeof (LITTLENUM_TYPE);
1260         }
1261     }
1262      
1263   return 0;
1264 }