2000-09-03 Kazu Hirata <kazu@hxi.com>
[platform/upstream/binutils.git] / gas / cgen.c
1 /* GAS interface for targets using CGEN: Cpu tools GENerator.
2    Copyright (C) 1996, 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
3
4 This file is part of GAS, the GNU Assembler.
5
6 GAS is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GAS is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GAS; see the file COPYING.  If not, write to the Free Software
18 Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 #include <setjmp.h>
21 #include "ansidecl.h"
22 #include "libiberty.h"
23 #include "bfd.h"
24 #include "symcat.h"
25 #include "cgen-desc.h"
26 #include "as.h"
27 #include "subsegs.h"
28 #include "cgen.h"
29
30 /* Opcode table descriptor, must be set by md_begin.  */
31
32 CGEN_CPU_DESC gas_cgen_cpu_desc;
33
34 /* Callback to insert a register into the symbol table.
35    A target may choose to let GAS parse the registers.
36    ??? Not currently used.  */
37
38 void
39 cgen_asm_record_register (name, number)
40      char *name;
41      int number;
42 {
43   /* Use symbol_create here instead of symbol_new so we don't try to
44      output registers into the object file's symbol table.  */
45   symbol_table_insert (symbol_create (name, reg_section,
46                                       number, &zero_address_frag));
47 }
48
49 /* We need to keep a list of fixups.  We can't simply generate them as
50    we go, because that would require us to first create the frag, and
51    that would screw up references to ``.''.
52
53    This is used by cpu's with simple operands.  It keeps knowledge of what
54    an `expressionS' is and what a `fixup' is out of CGEN which for the time
55    being is preferable.
56
57    OPINDEX is the index in the operand table.
58    OPINFO is something the caller chooses to help in reloc determination.  */
59
60 struct fixup
61 {
62   int opindex;
63   int opinfo;
64   expressionS exp;
65 };
66
67 static struct fixup fixups[GAS_CGEN_MAX_FIXUPS];
68 static int num_fixups;
69
70 /* Prepare to parse an instruction.
71    ??? May wish to make this static and delete calls in md_assemble.  */
72
73 void
74 gas_cgen_init_parse ()
75 {
76   num_fixups = 0;
77 }
78
79 /* Queue a fixup.  */
80
81 static void
82 queue_fixup (opindex, opinfo, expP)
83      int           opindex;
84      int           opinfo;
85      expressionS * expP;
86 {
87   /* We need to generate a fixup for this expression.  */
88   if (num_fixups >= GAS_CGEN_MAX_FIXUPS)
89     as_fatal (_("too many fixups"));
90   fixups[num_fixups].exp     = * expP;
91   fixups[num_fixups].opindex = opindex;
92   fixups[num_fixups].opinfo  = opinfo;
93   ++ num_fixups;
94 }
95
96 /* The following three functions allow a backup of the fixup chain to be made,
97    and to have this backup be swapped with the current chain.  This allows
98    certain ports, eg the m32r, to swap two instructions and swap their fixups
99    at the same time.  */
100 /* ??? I think with cgen_asm_finish_insn (or something else) there is no
101    more need for this.  */
102
103 static struct fixup saved_fixups[GAS_CGEN_MAX_FIXUPS];
104 static int saved_num_fixups;
105
106 void
107 gas_cgen_save_fixups ()
108 {
109   saved_num_fixups = num_fixups;
110
111   memcpy (saved_fixups, fixups, sizeof (fixups[0]) * num_fixups);
112
113   num_fixups = 0;
114 }
115
116 void
117 gas_cgen_restore_fixups ()
118 {
119   num_fixups = saved_num_fixups;
120
121   memcpy (fixups, saved_fixups, sizeof (fixups[0]) * num_fixups);
122
123   saved_num_fixups = 0;
124 }
125
126 void
127 gas_cgen_swap_fixups ()
128 {
129   int tmp;
130   struct fixup tmp_fixup;
131
132   if (num_fixups == 0)
133     {
134       gas_cgen_restore_fixups ();
135     }
136   else if (saved_num_fixups == 0)
137     {
138       gas_cgen_save_fixups ();
139     }
140   else
141     {
142       tmp = saved_num_fixups;
143       saved_num_fixups = num_fixups;
144       num_fixups = tmp;
145
146       for (tmp = GAS_CGEN_MAX_FIXUPS; tmp--;)
147         {
148           tmp_fixup          = saved_fixups [tmp];
149           saved_fixups [tmp] = fixups [tmp];
150           fixups [tmp]       = tmp_fixup;
151         }
152     }
153 }
154
155 /* Default routine to record a fixup.
156    This is a cover function to fix_new.
157    It exists because we record INSN with the fixup.
158
159    FRAG and WHERE are their respective arguments to fix_new_exp.
160    LENGTH is in bits.
161    OPINFO is something the caller chooses to help in reloc determination.
162
163    At this point we do not use a bfd_reloc_code_real_type for
164    operands residing in the insn, but instead just use the
165    operand index.  This lets us easily handle fixups for any
166    operand type.  We pick a BFD reloc type in md_apply_fix.  */
167
168 fixS *
169 gas_cgen_record_fixup (frag, where, insn, length, operand, opinfo, symbol, offset)
170      fragS *              frag;
171      int                  where;
172      const CGEN_INSN *    insn;
173      int                  length;
174      const CGEN_OPERAND * operand;
175      int                  opinfo;
176      symbolS *            symbol;
177      offsetT              offset;
178 {
179   fixS *fixP;
180
181   /* It may seem strange to use operand->attrs and not insn->attrs here,
182      but it is the operand that has a pc relative relocation.  */
183
184   fixP = fix_new (frag, where, length / 8, symbol, offset,
185                   CGEN_OPERAND_ATTR_VALUE (operand, CGEN_OPERAND_PCREL_ADDR),
186                   (bfd_reloc_code_real_type)
187                     ((int) BFD_RELOC_UNUSED
188                      + (int) operand->type));
189   fixP->fx_cgen.insn = insn;
190   fixP->fx_cgen.opinfo = opinfo;
191
192   return fixP;
193 }
194
195 /* Default routine to record a fixup given an expression.
196    This is a cover function to fix_new_exp.
197    It exists because we record INSN with the fixup.
198
199    FRAG and WHERE are their respective arguments to fix_new_exp.
200    LENGTH is in bits.
201    OPINFO is something the caller chooses to help in reloc determination.
202
203    At this point we do not use a bfd_reloc_code_real_type for
204    operands residing in the insn, but instead just use the
205    operand index.  This lets us easily handle fixups for any
206    operand type.  We pick a BFD reloc type in md_apply_fix.  */
207
208 fixS *
209 gas_cgen_record_fixup_exp (frag, where, insn, length, operand, opinfo, exp)
210      fragS *              frag;
211      int                  where;
212      const CGEN_INSN *    insn;
213      int                  length;
214      const CGEN_OPERAND * operand;
215      int                  opinfo;
216      expressionS *        exp;
217 {
218   fixS *fixP;
219
220   /* It may seem strange to use operand->attrs and not insn->attrs here,
221      but it is the operand that has a pc relative relocation.  */
222
223   fixP = fix_new_exp (frag, where, length / 8, exp,
224                       CGEN_OPERAND_ATTR_VALUE (operand, CGEN_OPERAND_PCREL_ADDR),
225                       (bfd_reloc_code_real_type)
226                         ((int) BFD_RELOC_UNUSED
227                          + (int) operand->type));
228   fixP->fx_cgen.insn = insn;
229   fixP->fx_cgen.opinfo = opinfo;
230
231   return fixP;
232 }
233
234 /* Used for communication between the next two procedures.  */
235 static jmp_buf expr_jmp_buf;
236 static int expr_jmp_buf_p;
237
238 /* Callback for cgen interface.  Parse the expression at *STRP.
239    The result is an error message or NULL for success (in which case
240    *STRP is advanced past the parsed text).
241    WANT is an indication of what the caller is looking for.
242    If WANT == CGEN_ASM_PARSE_INIT the caller is beginning to try to match
243    a table entry with the insn, reset the queued fixups counter.
244    An enum cgen_parse_operand_result is stored in RESULTP.
245    OPINDEX is the operand's table entry index.
246    OPINFO is something the caller chooses to help in reloc determination.
247    The resulting value is stored in VALUEP.  */
248
249 const char *
250 gas_cgen_parse_operand (cd, want, strP, opindex, opinfo, resultP, valueP)
251      CGEN_CPU_DESC cd ATTRIBUTE_UNUSED;
252      enum cgen_parse_operand_type want;
253      const char **strP;
254      int opindex;
255      int opinfo;
256      enum cgen_parse_operand_result *resultP;
257      bfd_vma *valueP;
258 {
259 #ifdef __STDC__
260   /* These are volatile to survive the setjmp.  */
261   char * volatile hold;
262   enum cgen_parse_operand_result * volatile resultP_1;
263 #else
264   static char *hold;
265   static enum cgen_parse_operand_result *resultP_1;
266 #endif
267   const char *errmsg = NULL;
268   expressionS exp;
269
270   if (want == CGEN_PARSE_OPERAND_INIT)
271     {
272       gas_cgen_init_parse ();
273       return NULL;
274     }
275
276   resultP_1 = resultP;
277   hold = input_line_pointer;
278   input_line_pointer = (char *) *strP;
279
280   /* We rely on md_operand to longjmp back to us.
281      This is done via gas_cgen_md_operand.  */
282   if (setjmp (expr_jmp_buf) != 0)
283     {
284       expr_jmp_buf_p = 0;
285       input_line_pointer = (char *) hold;
286       *resultP_1 = CGEN_PARSE_OPERAND_RESULT_ERROR;
287       return "illegal operand";
288     }
289
290   expr_jmp_buf_p = 1;
291   expression (&exp);
292   expr_jmp_buf_p = 0;
293
294   *strP = input_line_pointer;
295   input_line_pointer = hold;
296
297   /* FIXME: Need to check `want'.  */
298
299   switch (exp.X_op)
300     {
301     case O_illegal:
302       errmsg = _("illegal operand");
303       *resultP = CGEN_PARSE_OPERAND_RESULT_ERROR;
304       break;
305     case O_absent:
306       errmsg = _("missing operand");
307       *resultP = CGEN_PARSE_OPERAND_RESULT_ERROR;
308       break;
309     case O_constant:
310       *valueP = exp.X_add_number;
311       *resultP = CGEN_PARSE_OPERAND_RESULT_NUMBER;
312       break;
313     case O_register:
314       *valueP = exp.X_add_number;
315       *resultP = CGEN_PARSE_OPERAND_RESULT_REGISTER;
316       break;
317     default:
318       queue_fixup (opindex, opinfo, & exp);
319       *valueP = 0;
320       *resultP = CGEN_PARSE_OPERAND_RESULT_QUEUED;
321       break;
322     }
323
324   return errmsg;
325 }
326
327 /* md_operand handler to catch unrecognized expressions and halt the
328    parsing process so the next entry can be tried.
329
330    ??? This could be done differently by adding code to `expression'.  */
331
332 void
333 gas_cgen_md_operand (expressionP)
334      expressionS *expressionP ATTRIBUTE_UNUSED;
335 {
336   /* Don't longjmp if we're not called from within cgen_parse_operand().  */
337   if (expr_jmp_buf_p)
338     longjmp (expr_jmp_buf, 1);
339 }
340
341 /* Finish assembling instruction INSN.
342    BUF contains what we've built up so far.
343    LENGTH is the size of the insn in bits.
344    RELAX_P is non-zero if relaxable insns should be emitted as such.
345    Otherwise they're emitted in non-relaxable forms.
346    The "result" is stored in RESULT if non-NULL.  */
347
348 void
349 gas_cgen_finish_insn (insn, buf, length, relax_p, result)
350      const CGEN_INSN *insn;
351      CGEN_INSN_BYTES_PTR buf;
352      unsigned int length;
353      int relax_p;
354      finished_insnS *result;
355 {
356   int i;
357   int relax_operand;
358   char *f;
359   unsigned int byte_len = length / 8;
360
361   /* ??? Target foo issues various warnings here, so one might want to provide
362      a hook here.  However, our caller is defined in tc-foo.c so there
363      shouldn't be a need for a hook.  */
364
365   /* Write out the instruction.
366      It is important to fetch enough space in one call to `frag_more'.
367      We use (f - frag_now->fr_literal) to compute where we are and we
368      don't want frag_now to change between calls.
369
370      Relaxable instructions: We need to ensure we allocate enough
371      space for the largest insn.  */
372
373   if (CGEN_INSN_ATTR_VALUE (insn, CGEN_INSN_RELAX))
374     /* These currently shouldn't get here.  */
375     abort ();
376
377   /* Is there a relaxable insn with the relaxable operand needing a fixup?  */
378
379   relax_operand = -1;
380   if (relax_p && CGEN_INSN_ATTR_VALUE (insn, CGEN_INSN_RELAXABLE))
381     {
382       /* Scan the fixups for the operand affected by relaxing
383          (i.e. the branch address).  */
384
385       for (i = 0; i < num_fixups; ++i)
386         {
387           if (CGEN_OPERAND_ATTR_VALUE (cgen_operand_lookup_by_num (gas_cgen_cpu_desc, fixups[i].opindex),
388                                        CGEN_OPERAND_RELAX))
389             {
390               relax_operand = i;
391               break;
392             }
393         }
394     }
395
396   if (relax_operand != -1)
397     {
398       int max_len;
399       fragS *old_frag;
400
401 #ifdef TC_CGEN_MAX_RELAX
402       max_len = TC_CGEN_MAX_RELAX (insn, byte_len);
403 #else
404       max_len = CGEN_MAX_INSN_SIZE;
405 #endif
406       /* Ensure variable part and fixed part are in same fragment.  */
407       /* FIXME: Having to do this seems like a hack.  */
408       frag_grow (max_len);
409
410       /* Allocate space for the fixed part.  */
411       f = frag_more (byte_len);
412
413       /* Create a relaxable fragment for this instruction.  */
414       old_frag = frag_now;
415
416       frag_var (rs_machine_dependent,
417                 max_len - byte_len /* max chars */,
418                 0 /* variable part already allocated */,
419                 /* FIXME: When we machine generate the relax table,
420                    machine generate a macro to compute subtype.  */
421                 1 /* subtype */,
422                 fixups[relax_operand].exp.X_add_symbol,
423                 fixups[relax_operand].exp.X_add_number,
424                 f);
425
426       /* Record the operand number with the fragment so md_convert_frag
427          can use gas_cgen_md_record_fixup to record the appropriate reloc.  */
428       old_frag->fr_cgen.insn    = insn;
429       old_frag->fr_cgen.opindex = fixups[relax_operand].opindex;
430       old_frag->fr_cgen.opinfo  = fixups[relax_operand].opinfo;
431       if (result)
432         result->frag = old_frag;
433     }
434   else
435     {
436       f = frag_more (byte_len);
437       if (result)
438         result->frag = frag_now;
439     }
440
441   /* If we're recording insns as numbers (rather than a string of bytes),
442      target byte order handling is deferred until now.  */
443 #if CGEN_INT_INSN_P
444   cgen_put_insn_value (gas_cgen_cpu_desc, f, length, *buf);
445 #else
446   memcpy (f, buf, byte_len);
447 #endif
448
449   /* Create any fixups.  */
450   for (i = 0; i < num_fixups; ++i)
451     {
452       fixS *fixP;
453       const CGEN_OPERAND *operand =
454         cgen_operand_lookup_by_num (gas_cgen_cpu_desc, fixups[i].opindex);
455
456       /* Don't create fixups for these.  That's done during relaxation.
457          We don't need to test for CGEN_INSN_RELAX as they can't get here
458          (see above).  */
459       if (relax_p
460           && CGEN_INSN_ATTR_VALUE (insn, CGEN_INSN_RELAXABLE)
461           && CGEN_OPERAND_ATTR_VALUE (operand, CGEN_OPERAND_RELAX))
462         continue;
463
464 #ifndef md_cgen_record_fixup_exp
465 #define md_cgen_record_fixup_exp gas_cgen_record_fixup_exp
466 #endif
467
468       fixP = md_cgen_record_fixup_exp (frag_now, f - frag_now->fr_literal,
469                                        insn, length, operand,
470                                        fixups[i].opinfo,
471                                        &fixups[i].exp);
472       if (result)
473         result->fixups[i] = fixP;
474     }
475
476   if (result)
477     {
478       result->num_fixups = num_fixups;
479       result->addr = f;
480     }
481 }
482
483 /* Apply a fixup to the object code.  This is called for all the
484    fixups we generated by the call to fix_new_exp, above.  In the call
485    above we used a reloc code which was the largest legal reloc code
486    plus the operand index.  Here we undo that to recover the operand
487    index.  At this point all symbol values should be fully resolved,
488    and we attempt to completely resolve the reloc.  If we can not do
489    that, we determine the correct reloc code and put it back in the fixup.  */
490
491 /* FIXME: This function handles some of the fixups and bfd_install_relocation
492    handles the rest.  bfd_install_relocation (or some other bfd function)
493    should handle them all.  */
494
495 int
496 gas_cgen_md_apply_fix3 (fixP, valueP, seg)
497      fixS *   fixP;
498      valueT * valueP;
499      segT     seg ATTRIBUTE_UNUSED;
500 {
501   char *where = fixP->fx_frag->fr_literal + fixP->fx_where;
502   valueT value;
503   /* Canonical name, since used a lot.  */
504   CGEN_CPU_DESC cd = gas_cgen_cpu_desc;
505
506   /* FIXME FIXME FIXME: The value we are passed in *valuep includes
507      the symbol values.  Since we are using BFD_ASSEMBLER, if we are
508      doing this relocation the code in write.c is going to call
509      bfd_install_relocation, which is also going to use the symbol
510      value.  That means that if the reloc is fully resolved we want to
511      use *valuep since bfd_install_relocation is not being used.
512      However, if the reloc is not fully resolved we do not want to use
513      *valuep, and must use fx_offset instead.  However, if the reloc
514      is PC relative, we do want to use *valuep since it includes the
515      result of md_pcrel_from.  This is confusing.  */
516
517   if (fixP->fx_addsy == (symbolS *) NULL)
518     {
519       value = *valueP;
520       fixP->fx_done = 1;
521     }
522   else if (fixP->fx_pcrel)
523     value = *valueP;
524   else
525     {
526       value = fixP->fx_offset;
527       if (fixP->fx_subsy != (symbolS *) NULL)
528         {
529           if (S_GET_SEGMENT (fixP->fx_subsy) == absolute_section)
530             value -= S_GET_VALUE (fixP->fx_subsy);
531           else
532             {
533               /* We don't actually support subtracting a symbol.  */
534               as_bad_where (fixP->fx_file, fixP->fx_line,
535                             _("expression too complex"));
536             }
537         }
538     }
539
540   if ((int) fixP->fx_r_type >= (int) BFD_RELOC_UNUSED)
541     {
542       int opindex = (int) fixP->fx_r_type - (int) BFD_RELOC_UNUSED;
543       const CGEN_OPERAND *operand = cgen_operand_lookup_by_num (cd, opindex);
544       const char *errmsg;
545       bfd_reloc_code_real_type reloc_type;
546       CGEN_FIELDS *fields = alloca (CGEN_CPU_SIZEOF_FIELDS (cd));
547       const CGEN_INSN *insn = fixP->fx_cgen.insn;
548
549       /* If the reloc has been fully resolved finish the operand here.  */
550       /* FIXME: This duplicates the capabilities of code in BFD.  */
551       if (fixP->fx_done
552           /* FIXME: If partial_inplace isn't set bfd_install_relocation won't
553              finish the job.  Testing for pcrel is a temporary hack.  */
554           || fixP->fx_pcrel)
555         {
556           CGEN_CPU_SET_FIELDS_BITSIZE (cd) (fields, CGEN_INSN_BITSIZE (insn));
557           CGEN_CPU_SET_VMA_OPERAND (cd) (cd, opindex, fields, (bfd_vma) value);
558
559 #if CGEN_INT_INSN_P
560           {
561             CGEN_INSN_INT insn_value =
562               cgen_get_insn_value (cd, where, CGEN_INSN_BITSIZE (insn));
563
564             /* ??? 0 is passed for `pc'.  */
565             errmsg = CGEN_CPU_INSERT_OPERAND (cd) (cd, opindex, fields,
566                                                    &insn_value, (bfd_vma) 0);
567             cgen_put_insn_value (cd, where, CGEN_INSN_BITSIZE (insn),
568                                  insn_value);
569           }
570 #else
571           /* ??? 0 is passed for `pc'.  */
572           errmsg = CGEN_CPU_INSERT_OPERAND (cd) (cd, opindex, fields, where,
573                                                  (bfd_vma) 0);
574 #endif
575           if (errmsg)
576             as_bad_where (fixP->fx_file, fixP->fx_line, "%s", errmsg);
577         }
578
579       if (fixP->fx_done)
580         return 1;
581
582       /* The operand isn't fully resolved.  Determine a BFD reloc value
583          based on the operand information and leave it to
584          bfd_install_relocation.  Note that this doesn't work when
585          partial_inplace == false.  */
586
587       reloc_type = md_cgen_lookup_reloc (insn, operand, fixP);
588       if (reloc_type != BFD_RELOC_NONE)
589         {
590           fixP->fx_r_type = reloc_type;
591         }
592       else
593         {
594           as_bad_where (fixP->fx_file, fixP->fx_line,
595                         _("unresolved expression that must be resolved"));
596           fixP->fx_done = 1;
597           return 1;
598         }
599     }
600   else if (fixP->fx_done)
601     {
602       /* We're finished with this fixup.  Install it because
603          bfd_install_relocation won't be called to do it.  */
604       switch (fixP->fx_r_type)
605         {
606         case BFD_RELOC_8:
607           md_number_to_chars (where, value, 1);
608           break;
609         case BFD_RELOC_16:
610           md_number_to_chars (where, value, 2);
611           break;
612         case BFD_RELOC_32:
613           md_number_to_chars (where, value, 4);
614           break;
615         /* FIXME: later add support for 64 bits.  */
616         default:
617           as_bad_where (fixP->fx_file, fixP->fx_line,
618                         _("internal error: can't install fix for reloc type %d (`%s')"),
619                         fixP->fx_r_type, bfd_get_reloc_code_name (fixP->fx_r_type));
620           break;
621         }
622     }
623   else
624     {
625       /* bfd_install_relocation will be called to finish things up.  */
626     }
627
628   /* Tuck `value' away for use by tc_gen_reloc.
629      See the comment describing fx_addnumber in write.h.
630      This field is misnamed (or misused :-).  */
631   fixP->fx_addnumber = value;
632
633   return 1;
634 }
635
636 /* Translate internal representation of relocation info to BFD target format.
637
638    FIXME: To what extent can we get all relevant targets to use this?  */
639
640 arelent *
641 gas_cgen_tc_gen_reloc (section, fixP)
642      asection * section ATTRIBUTE_UNUSED;
643      fixS *     fixP;
644 {
645   arelent *reloc;
646
647   reloc = (arelent *) xmalloc (sizeof (arelent));
648
649   reloc->howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
650   if (reloc->howto == (reloc_howto_type *) NULL)
651     {
652       as_bad_where (fixP->fx_file, fixP->fx_line,
653                     _("internal error: can't export reloc type %d (`%s')"),
654                     fixP->fx_r_type, bfd_get_reloc_code_name (fixP->fx_r_type));
655       return NULL;
656     }
657
658   assert (!fixP->fx_pcrel == !reloc->howto->pc_relative);
659
660   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
661   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixP->fx_addsy);
662
663   /* Use fx_offset for these cases.  */
664   if (fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
665       || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT)
666     reloc->addend = fixP->fx_offset;
667   else
668     reloc->addend = fixP->fx_addnumber;
669
670   reloc->address = fixP->fx_frag->fr_address + fixP->fx_where;
671   return reloc;
672 }