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