1/* tc-i960.c - All the i80960-specific stuff
2   Copyright 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
3   1999, 2000, 2001, 2002, 2003, 2005
4   Free Software Foundation, Inc.
5
6   This file is part of GAS.
7
8   GAS is free software; you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2, or (at your option)
11   any later version.
12
13   GAS is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with GAS; see the file COPYING.  If not, write to the Free
20   Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
21   02110-1301, USA.  */
22
23/* See comment on md_parse_option for 80960-specific invocation options.  */
24
25/* There are 4 different lengths of (potentially) symbol-based displacements
26   in the 80960 instruction set, each of which could require address fix-ups
27   and (in the case of external symbols) emission of relocation directives:
28
29   32-bit (MEMB)
30        This is a standard length for the base assembler and requires no
31        special action.
32
33   13-bit (COBR)
34        This is a non-standard length, but the base assembler has a
35        hook for bit field address fixups: the fixS structure can
36        point to a descriptor of the field, in which case our
37        md_number_to_field() routine gets called to process it.
38
39        I made the hook a little cleaner by having fix_new() (in the base
40        assembler) return a pointer to the fixS in question.  And I made it a
41        little simpler by storing the field size (in this case 13) instead of
42        of a pointer to another structure:  80960 displacements are ALWAYS
43        stored in the low-order bits of a 4-byte word.
44
45        Since the target of a COBR cannot be external, no relocation
46        directives for this size displacement have to be generated.
47        But the base assembler had to be modified to issue error
48        messages if the symbol did turn out to be external.
49
50   24-bit (CTRL)
51        Fixups are handled as for the 13-bit case (except that 24 is stored
52        in the fixS).
53
54        The relocation directive generated is the same as that for the 32-bit
55        displacement, except that it's PC-relative (the 32-bit displacement
56        never is).   The i80960 version of the linker needs a mod to
57        distinguish and handle the 24-bit case.
58
59   12-bit (MEMA)
60        MEMA formats are always promoted to MEMB (32-bit) if the displacement
61        is based on a symbol, because it could be relocated at link time.
62        The only time we use the 12-bit format is if an absolute value of
63        less than 4096 is specified, in which case we need neither a fixup nor
64        a relocation directive.  */
65
66#include <stdio.h>
67
68#include "as.h"
69
70#include "safe-ctype.h"
71#include "obstack.h"
72
73#include "opcode/i960.h"
74
75#if defined (OBJ_AOUT) || defined (OBJ_BOUT)
76
77#define TC_S_IS_SYSPROC(s)	((1 <= S_GET_OTHER (s)) && (S_GET_OTHER (s) <= 32))
78#define TC_S_IS_BALNAME(s)	(S_GET_OTHER (s) == N_BALNAME)
79#define TC_S_IS_CALLNAME(s)	(S_GET_OTHER (s) == N_CALLNAME)
80#define TC_S_IS_BADPROC(s)	((S_GET_OTHER (s) != 0) && !TC_S_IS_CALLNAME (s) && !TC_S_IS_BALNAME (s) && !TC_S_IS_SYSPROC (s))
81
82#define TC_S_SET_SYSPROC(s, p)	(S_SET_OTHER ((s), (p) + 1))
83#define TC_S_GET_SYSPROC(s)	(S_GET_OTHER (s) - 1)
84
85#define TC_S_FORCE_TO_BALNAME(s)	(S_SET_OTHER ((s), N_BALNAME))
86#define TC_S_FORCE_TO_CALLNAME(s)	(S_SET_OTHER ((s), N_CALLNAME))
87#define TC_S_FORCE_TO_SYSPROC(s)	{;}
88
89#else /* ! OBJ_A/BOUT */
90#ifdef OBJ_COFF
91
92#define TC_S_IS_SYSPROC(s)	(S_GET_STORAGE_CLASS (s) == C_SCALL)
93#define TC_S_IS_BALNAME(s)	(SF_GET_BALNAME (s))
94#define TC_S_IS_CALLNAME(s)	(SF_GET_CALLNAME (s))
95#define TC_S_IS_BADPROC(s)	(TC_S_IS_SYSPROC (s) && TC_S_GET_SYSPROC (s) < 0 && 31 < TC_S_GET_SYSPROC (s))
96
97#define TC_S_SET_SYSPROC(s, p)	((s)->sy_symbol.ost_auxent[1].x_sc.x_stindx = (p))
98#define TC_S_GET_SYSPROC(s)	((s)->sy_symbol.ost_auxent[1].x_sc.x_stindx)
99
100#define TC_S_FORCE_TO_BALNAME(s)	(SF_SET_BALNAME (s))
101#define TC_S_FORCE_TO_CALLNAME(s)	(SF_SET_CALLNAME (s))
102#define TC_S_FORCE_TO_SYSPROC(s)	(S_SET_STORAGE_CLASS ((s), C_SCALL))
103
104#else /* ! OBJ_COFF */
105#ifdef OBJ_ELF
106#define TC_S_IS_SYSPROC(s)	0
107
108#define TC_S_IS_BALNAME(s)	0
109#define TC_S_IS_CALLNAME(s)	0
110#define TC_S_IS_BADPROC(s)	0
111
112#define TC_S_SET_SYSPROC(s, p)
113#define TC_S_GET_SYSPROC(s)     0
114
115#define TC_S_FORCE_TO_BALNAME(s)
116#define TC_S_FORCE_TO_CALLNAME(s)
117#define TC_S_FORCE_TO_SYSPROC(s)
118#else
119 #error COFF, a.out, b.out, and ELF are the only supported formats.
120#endif /* ! OBJ_ELF */
121#endif /* ! OBJ_COFF */
122#endif /* ! OBJ_A/BOUT */
123
124extern char *input_line_pointer;
125
126/* Local i80960 routines.  */
127struct memS;
128struct regop;
129
130/* See md_parse_option() for meanings of these options.  */
131static char norelax;			/* True if -norelax switch seen.  */
132static char instrument_branches;	/* True if -b switch seen.  */
133
134/* Characters that always start a comment.
135   If the pre-processor is disabled, these aren't very useful.  */
136const char comment_chars[] = "#";
137
138/* Characters that only start a comment at the beginning of
139   a line.  If the line seems to have the form '# 123 filename'
140   .line and .file directives will appear in the pre-processed output.
141
142   Note that input_file.c hand checks for '#' at the beginning of the
143   first line of the input file.  This is because the compiler outputs
144   #NO_APP at the beginning of its output.  */
145
146/* Also note that comments started like this one will always work.  */
147
148const char line_comment_chars[]   = "#";
149const char line_separator_chars[] = ";";
150
151/* Chars that can be used to separate mant from exp in floating point nums.  */
152const char EXP_CHARS[] = "eE";
153
154/* Chars that mean this number is a floating point constant,
155   as in 0f12.456 or 0d1.2345e12.  */
156const char FLT_CHARS[] = "fFdDtT";
157
158/* Table used by base assembler to relax addresses based on varying length
159   instructions.  The fields are:
160     1) most positive reach of this state,
161     2) most negative reach of this state,
162     3) how many bytes this mode will add to the size of the current frag
163     4) which index into the table to try if we can't fit into this one.
164
165   For i80960, the only application is the (de-)optimization of cobr
166   instructions into separate compare and branch instructions when a 13-bit
167   displacement won't hack it.  */
168const relax_typeS md_relax_table[] =
169{
170  {0, 0, 0, 0},				/* State 0 => no more relaxation possible.  */
171  {4088, -4096, 0, 2},			/* State 1: conditional branch (cobr).  */
172  {0x800000 - 8, -0x800000, 4, 0},	/* State 2: compare (reg) & branch (ctrl).  */
173};
174
175/* These are the machine dependent pseudo-ops.
176
177   This table describes all the machine specific pseudo-ops the assembler
178   has to support.  The fields are:
179        pseudo-op name without dot
180        function to call to execute this pseudo-op
181        integer arg to pass to the function.  */
182#define S_LEAFPROC	1
183#define S_SYSPROC	2
184
185/* Macros to extract info from an 'expressionS' structure 'e'.  */
186#define adds(e)	e.X_add_symbol
187#define offs(e)	e.X_add_number
188
189/* Branch-prediction bits for CTRL/COBR format opcodes.  */
190#define BP_MASK		0x00000002	/* Mask for branch-prediction bit.  */
191#define BP_TAKEN	0x00000000	/* Value to OR in to predict branch.  */
192#define BP_NOT_TAKEN	0x00000002	/* Value to OR in to predict no branch.  */
193
194/* Some instruction opcodes that we need explicitly.  */
195#define BE	0x12000000
196#define BG	0x11000000
197#define BGE	0x13000000
198#define BL	0x14000000
199#define BLE	0x16000000
200#define BNE	0x15000000
201#define BNO	0x10000000
202#define BO	0x17000000
203#define CHKBIT	0x5a002700
204#define CMPI	0x5a002080
205#define CMPO	0x5a002000
206
207#define B	0x08000000
208#define BAL	0x0b000000
209#define CALL	0x09000000
210#define CALLS	0x66003800
211#define RET	0x0a000000
212
213/* These masks are used to build up a set of MEMB mode bits.  */
214#define	A_BIT		0x0400
215#define	I_BIT		0x0800
216#define MEMB_BIT	0x1000
217#define	D_BIT		0x2000
218
219/* Mask for the only mode bit in a MEMA instruction (if set, abase reg is
220   used).  */
221#define MEMA_ABASE	0x2000
222
223/* Info from which a MEMA or MEMB format instruction can be generated.  */
224typedef struct memS
225  {
226    /* (First) 32 bits of instruction.  */
227    long opcode;
228    /* 0-(none), 12- or, 32-bit displacement needed.  */
229    int disp;
230    /* The expression in the source instruction from which the
231       displacement should be determined.  */
232    char *e;
233  }
234memS;
235
236/* The two pieces of info we need to generate a register operand.  */
237struct regop
238  {
239    int mode;			/* 0 =>local/global/spec reg; 1=> literal or fp reg.  */
240    int special;		/* 0 =>not a sfr;  1=> is a sfr (not valid w/mode=0).  */
241    int n;			/* Register number or literal value.  */
242  };
243
244/* Number and assembler mnemonic for all registers that can appear in
245   operands.  */
246static const struct
247  {
248    char *reg_name;
249    int reg_num;
250  }
251regnames[] =
252{
253  { "pfp", 0 },
254  { "sp", 1 },
255  { "rip", 2 },
256  { "r3", 3 },
257  { "r4", 4 },
258  { "r5", 5 },
259  { "r6", 6 },
260  { "r7", 7 },
261  { "r8", 8 },
262  { "r9", 9 },
263  { "r10", 10 },
264  { "r11", 11 },
265  { "r12", 12 },
266  { "r13", 13 },
267  { "r14", 14 },
268  { "r15", 15 },
269  { "g0", 16 },
270  { "g1", 17 },
271  { "g2", 18 },
272  { "g3", 19 },
273  { "g4", 20 },
274  { "g5", 21 },
275  { "g6", 22 },
276  { "g7", 23 },
277  { "g8", 24 },
278  { "g9", 25 },
279  { "g10", 26 },
280  { "g11", 27 },
281  { "g12", 28 },
282  { "g13", 29 },
283  { "g14", 30 },
284  { "fp", 31 },
285
286  /* Numbers for special-function registers are for assembler internal
287     use only: they are scaled back to range [0-31] for binary output.  */
288#define SF0	32
289
290  { "sf0", 32 },
291  { "sf1", 33 },
292  { "sf2", 34 },
293  { "sf3", 35 },
294  { "sf4", 36 },
295  { "sf5", 37 },
296  { "sf6", 38 },
297  { "sf7", 39 },
298  { "sf8", 40 },
299  { "sf9", 41 },
300  { "sf10", 42 },
301  { "sf11", 43 },
302  { "sf12", 44 },
303  { "sf13", 45 },
304  { "sf14", 46 },
305  { "sf15", 47 },
306  { "sf16", 48 },
307  { "sf17", 49 },
308  { "sf18", 50 },
309  { "sf19", 51 },
310  { "sf20", 52 },
311  { "sf21", 53 },
312  { "sf22", 54 },
313  { "sf23", 55 },
314  { "sf24", 56 },
315  { "sf25", 57 },
316  { "sf26", 58 },
317  { "sf27", 59 },
318  { "sf28", 60 },
319  { "sf29", 61 },
320  { "sf30", 62 },
321  { "sf31", 63 },
322
323  /* Numbers for floating point registers are for assembler internal
324     use only: they are scaled back to [0-3] for binary output.  */
325#define FP0	64
326
327  { "fp0", 64 },
328  { "fp1", 65 },
329  { "fp2", 66 },
330  { "fp3", 67 },
331
332  { NULL, 0 },				/* END OF LIST */
333};
334
335#define	IS_RG_REG(n)	((0 <= (n)) && ((n) < SF0))
336#define	IS_SF_REG(n)	((SF0 <= (n)) && ((n) < FP0))
337#define	IS_FP_REG(n)	((n) >= FP0)
338
339/* Number and assembler mnemonic for all registers that can appear as
340   'abase' (indirect addressing) registers.  */
341static const struct
342{
343  char *areg_name;
344  int areg_num;
345}
346aregs[] =
347{
348  { "(pfp)", 0 },
349  { "(sp)", 1 },
350  { "(rip)", 2 },
351  { "(r3)", 3 },
352  { "(r4)", 4 },
353  { "(r5)", 5 },
354  { "(r6)", 6 },
355  { "(r7)", 7 },
356  { "(r8)", 8 },
357  { "(r9)", 9 },
358  { "(r10)", 10 },
359  { "(r11)", 11 },
360  { "(r12)", 12 },
361  { "(r13)", 13 },
362  { "(r14)", 14 },
363  { "(r15)", 15 },
364  { "(g0)", 16 },
365  { "(g1)", 17 },
366  { "(g2)", 18 },
367  { "(g3)", 19 },
368  { "(g4)", 20 },
369  { "(g5)", 21 },
370  { "(g6)", 22 },
371  { "(g7)", 23 },
372  { "(g8)", 24 },
373  { "(g9)", 25 },
374  { "(g10)", 26 },
375  { "(g11)", 27 },
376  { "(g12)", 28 },
377  { "(g13)", 29 },
378  { "(g14)", 30 },
379  { "(fp)", 31 },
380
381#define IPREL	32
382  /* For assembler internal use only: this number never appears in binary
383     output.  */
384  { "(ip)", IPREL },
385
386  { NULL, 0 },				/* END OF LIST */
387};
388
389/* Hash tables.  */
390static struct hash_control *op_hash;	/* Opcode mnemonics.  */
391static struct hash_control *reg_hash;	/* Register name hash table.  */
392static struct hash_control *areg_hash;	/* Abase register hash table.  */
393
394/* Architecture for which we are assembling.  */
395#define ARCH_ANY	0	/* Default: no architecture checking done.  */
396#define ARCH_KA		1
397#define ARCH_KB		2
398#define ARCH_MC		3
399#define ARCH_CA		4
400#define ARCH_JX		5
401#define ARCH_HX		6
402int architecture = ARCH_ANY;	/* Architecture requested on invocation line.  */
403int iclasses_seen;		/* OR of instruction classes (I_* constants)
404				      for which we've actually assembled
405				        instructions.  */
406
407/* BRANCH-PREDICTION INSTRUMENTATION
408
409        The following supports generation of branch-prediction instrumentation
410        (turned on by -b switch).  The instrumentation collects counts
411        of branches taken/not-taken for later input to a utility that will
412        set the branch prediction bits of the instructions in accordance with
413        the behavior observed.  (Note that the KX series does not have
414        brach-prediction.)
415
416        The instrumentation consists of:
417
418        (1) before and after each conditional branch, a call to an external
419            routine that increments and steps over an inline counter.  The
420            counter itself, initialized to 0, immediately follows the call
421            instruction.  For each branch, the counter following the branch
422            is the number of times the branch was not taken, and the difference
423            between the counters is the number of times it was taken.  An
424            example of an instrumented conditional branch:
425
426                                call    BR_CNT_FUNC
427                                .word   0
428                LBRANCH23:      be      label
429                                call    BR_CNT_FUNC
430                                .word   0
431
432        (2) a table of pointers to the instrumented branches, so that an
433            external postprocessing routine can locate all of the counters.
434            the table begins with a 2-word header: a pointer to the next in
435            a linked list of such tables (initialized to 0);  and a count
436            of the number of entries in the table (exclusive of the header.
437
438            Note that input source code is expected to already contain calls
439            an external routine that will link the branch local table into a
440            list of such tables.  */
441
442/* Number of branches instrumented so far.  Also used to generate
443   unique local labels for each instrumented branch.  */
444static int br_cnt;
445
446#define BR_LABEL_BASE	"LBRANCH"
447/* Basename of local labels on instrumented branches, to avoid
448   conflict with compiler- generated local labels.  */
449
450#define BR_CNT_FUNC	"__inc_branch"
451/* Name of the external routine that will increment (and step over) an
452   inline counter.  */
453
454#define BR_TAB_NAME	"__BRANCH_TABLE__"
455/* Name of the table of pointers to branches.  A local (i.e.,
456   non-external) symbol.  */
457
458static void ctrl_fmt (char *, long, int);
459
460
461void
462md_begin (void)
463{
464  int i;			/* Loop counter.  */
465  const struct i960_opcode *oP;	/* Pointer into opcode table.  */
466  const char *retval;		/* Value returned by hash functions.  */
467
468  op_hash = hash_new ();
469  reg_hash = hash_new ();
470  areg_hash = hash_new ();
471
472  /* For some reason, the base assembler uses an empty string for "no
473     error message", instead of a NULL pointer.  */
474  retval = 0;
475
476  for (oP = i960_opcodes; oP->name && !retval; oP++)
477    retval = hash_insert (op_hash, oP->name, (void *) oP);
478
479  for (i = 0; regnames[i].reg_name && !retval; i++)
480    retval = hash_insert (reg_hash, regnames[i].reg_name,
481			  (char *) &regnames[i].reg_num);
482
483  for (i = 0; aregs[i].areg_name && !retval; i++)
484    retval = hash_insert (areg_hash, aregs[i].areg_name,
485			  (char *) &aregs[i].areg_num);
486
487  if (retval)
488    as_fatal (_("Hashing returned \"%s\"."), retval);
489}
490
491/* parse_expr:		parse an expression
492
493   Use base assembler's expression parser to parse an expression.
494   It, unfortunately, runs off a global which we have to save/restore
495   in order to make it work for us.
496
497   An empty expression string is treated as an absolute 0.
498
499   Sets O_illegal regardless of expression evaluation if entire input
500   string is not consumed in the evaluation -- tolerate no dangling junk!  */
501
502static void
503parse_expr (char *textP,		/* Text of expression to be parsed.  */
504	    expressionS *expP)		/* Where to put the results of parsing.  */
505{
506  char *save_in;		/* Save global here.  */
507  symbolS *symP;
508
509  know (textP);
510
511  if (*textP == '\0')
512    {
513      /* Treat empty string as absolute 0.  */
514      expP->X_add_symbol = expP->X_op_symbol = NULL;
515      expP->X_add_number = 0;
516      expP->X_op = O_constant;
517    }
518  else
519    {
520      save_in = input_line_pointer;	/* Save global.  */
521      input_line_pointer = textP;	/* Make parser work for us.  */
522
523      (void) expression (expP);
524      if ((size_t) (input_line_pointer - textP) != strlen (textP))
525	/* Did not consume all of the input.  */
526	expP->X_op = O_illegal;
527
528      symP = expP->X_add_symbol;
529      if (symP && (hash_find (reg_hash, S_GET_NAME (symP))))
530	/* Register name in an expression.  */
531	/* FIXME: this isn't much of a check any more.  */
532	expP->X_op = O_illegal;
533
534      input_line_pointer = save_in;	/* Restore global.  */
535    }
536}
537
538/* emit:	output instruction binary
539
540   Output instruction binary, in target byte order, 4 bytes at a time.
541   Return pointer to where it was placed.  */
542
543static char *
544emit (long instr)		/* Word to be output, host byte order.  */
545{
546  char *toP;			/* Where to output it.  */
547
548  toP = frag_more (4);		/* Allocate storage.  */
549  md_number_to_chars (toP, instr, 4);	/* Convert to target byte order.  */
550  return toP;
551}
552
553/* get_cdisp:	handle displacement for a COBR or CTRL instruction.
554
555   Parse displacement for a COBR or CTRL instruction.
556
557   If successful, output the instruction opcode and set up for it,
558   depending on the arg 'var_frag', either:
559  	    o an address fixup to be done when all symbol values are known, or
560  	    o a varying length code fragment, with address fixup info.  This
561  		will be done for cobr instructions that may have to be relaxed
562  		in to compare/branch instructions (8 bytes) if the final
563  		address displacement is greater than 13 bits.  */
564
565static void
566get_cdisp (char *dispP, /* Displacement as specified in source instruction.  */
567	   char *ifmtP, /* "COBR" or "CTRL" (for use in error message).  */
568	   long instr,  /* Instruction needing the displacement.  */
569	   int numbits, /* # bits of displacement (13 for COBR, 24 for CTRL).  */
570	   int var_frag,/* 1 if varying length code fragment should be emitted;
571			   0 if an address fix should be emitted.  */
572	   int callj)	/* 1 if callj relocation should be done; else 0.  */
573{
574  expressionS e;		/* Parsed expression.  */
575  fixS *fixP;			/* Structure describing needed address fix.  */
576  char *outP;			/* Where instruction binary is output to.  */
577
578  fixP = NULL;
579
580  parse_expr (dispP, &e);
581  switch (e.X_op)
582    {
583    case O_illegal:
584      as_bad (_("expression syntax error"));
585
586    case O_symbol:
587      if (S_GET_SEGMENT (e.X_add_symbol) == now_seg
588	  || S_GET_SEGMENT (e.X_add_symbol) == undefined_section)
589	{
590	  if (var_frag)
591	    {
592	      outP = frag_more (8);	/* Allocate worst-case storage.  */
593	      md_number_to_chars (outP, instr, 4);
594	      frag_variant (rs_machine_dependent, 4, 4, 1,
595			    adds (e), offs (e), outP);
596	    }
597	  else
598	    {
599	      /* Set up a new fix structure, so address can be updated
600	         when all symbol values are known.  */
601	      outP = emit (instr);
602	      fixP = fix_new (frag_now,
603			      outP - frag_now->fr_literal,
604			      4,
605			      adds (e),
606			      offs (e),
607			      1,
608			      NO_RELOC);
609
610	      fixP->fx_tcbit = callj;
611
612	      /* We want to modify a bit field when the address is
613	         known.  But we don't need all the garbage in the
614	         bit_fix structure.  So we're going to lie and store
615	         the number of bits affected instead of a pointer.  */
616	      fixP->fx_bit_fixP = (bit_fixS *) (size_t) numbits;
617	    }
618	}
619      else
620	as_bad (_("attempt to branch into different segment"));
621      break;
622
623    default:
624      as_bad (_("target of %s instruction must be a label"), ifmtP);
625      break;
626    }
627}
628
629static int
630md_chars_to_number (char * val,		/* Value in target byte order.  */
631		    int n)		/* Number of bytes in the input.  */
632{
633  int retval;
634
635  for (retval = 0; n--;)
636    {
637      retval <<= 8;
638      retval |= (unsigned char) val[n];
639    }
640  return retval;
641}
642
643/* mema_to_memb:	convert a MEMA-format opcode to a MEMB-format opcode.
644
645   There are 2 possible MEMA formats:
646  	- displacement only
647  	- displacement + abase
648
649   They are distinguished by the setting of the MEMA_ABASE bit.  */
650
651static void
652mema_to_memb (char * opcodeP)	/* Where to find the opcode, in target byte order.  */
653{
654  long opcode;			/* Opcode in host byte order.  */
655  long mode;			/* Mode bits for MEMB instruction.  */
656
657  opcode = md_chars_to_number (opcodeP, 4);
658  know (!(opcode & MEMB_BIT));
659
660  mode = MEMB_BIT | D_BIT;
661  if (opcode & MEMA_ABASE)
662    mode |= A_BIT;
663
664  opcode &= 0xffffc000;		/* Clear MEMA offset and mode bits.  */
665  opcode |= mode;		/* Set MEMB mode bits.  */
666
667  md_number_to_chars (opcodeP, opcode, 4);
668}
669
670/* targ_has_sfr:
671
672   Return TRUE iff the target architecture supports the specified
673   special-function register (sfr).  */
674
675static int
676targ_has_sfr (int n)		/* Number (0-31) of sfr.  */
677{
678  switch (architecture)
679    {
680    case ARCH_KA:
681    case ARCH_KB:
682    case ARCH_MC:
683    case ARCH_JX:
684      return 0;
685    case ARCH_HX:
686      return ((0 <= n) && (n <= 4));
687    case ARCH_CA:
688    default:
689      return ((0 <= n) && (n <= 2));
690    }
691}
692
693/* Look up a (suspected) register name in the register table and return the
694   associated register number (or -1 if not found).  */
695
696static int
697get_regnum (char *regname)	/* Suspected register name.  */
698{
699  int *rP;
700
701  rP = (int *) hash_find (reg_hash, regname);
702  return (rP == NULL) ? -1 : *rP;
703}
704
705/* syntax: Issue a syntax error.  */
706
707static void
708syntax (void)
709{
710  as_bad (_("syntax error"));
711}
712
713/* parse_regop: parse a register operand.
714
715   In case of illegal operand, issue a message and return some valid
716   information so instruction processing can continue.  */
717
718static void
719parse_regop (struct regop *regopP,	/* Where to put description of register operand.  */
720	     char *optext,		/* Text of operand.  */
721	     char opdesc)      		/* Descriptor byte:  what's legal for this operand.  */
722{
723  int n;			/* Register number.  */
724  expressionS e;		/* Parsed expression.  */
725
726  /* See if operand is a register.  */
727  n = get_regnum (optext);
728  if (n >= 0)
729    {
730      if (IS_RG_REG (n))
731	{
732	  /* Global or local register.  */
733	  if (!REG_ALIGN (opdesc, n))
734	    as_bad (_("unaligned register"));
735
736	  regopP->n = n;
737	  regopP->mode = 0;
738	  regopP->special = 0;
739	  return;
740	}
741      else if (IS_FP_REG (n) && FP_OK (opdesc))
742	{
743	  /* Floating point register, and it's allowed.  */
744	  regopP->n = n - FP0;
745	  regopP->mode = 1;
746	  regopP->special = 0;
747	  return;
748	}
749      else if (IS_SF_REG (n) && SFR_OK (opdesc))
750	{
751	  /* Special-function register, and it's allowed.  */
752	  regopP->n = n - SF0;
753	  regopP->mode = 0;
754	  regopP->special = 1;
755	  if (!targ_has_sfr (regopP->n))
756	    as_bad (_("no such sfr in this architecture"));
757
758	  return;
759	}
760    }
761  else if (LIT_OK (opdesc))
762    {
763      /* How about a literal?  */
764      regopP->mode = 1;
765      regopP->special = 0;
766      if (FP_OK (opdesc))
767	{
768	  /* Floating point literal acceptable.  */
769	  /* Skip over 0f, 0d, or 0e prefix.  */
770	  if ((optext[0] == '0')
771	      && (optext[1] >= 'd')
772	      && (optext[1] <= 'f'))
773	    optext += 2;
774
775	  if (!strcmp (optext, "0.0") || !strcmp (optext, "0"))
776	    {
777	      regopP->n = 0x10;
778	      return;
779	    }
780
781	  if (!strcmp (optext, "1.0") || !strcmp (optext, "1"))
782	    {
783	      regopP->n = 0x16;
784	      return;
785	    }
786	}
787      else
788	{
789	  /* Fixed point literal acceptable.  */
790	  parse_expr (optext, &e);
791	  if (e.X_op != O_constant
792	      || (offs (e) < 0) || (offs (e) > 31))
793	    {
794	      as_bad (_("illegal literal"));
795	      offs (e) = 0;
796	    }
797	  regopP->n = offs (e);
798	  return;
799	}
800    }
801
802  /* Nothing worked.  */
803  syntax ();
804  regopP->mode = 0;		/* Register r0 is always a good one.  */
805  regopP->n = 0;
806  regopP->special = 0;
807}
808
809/* get_ispec:	parse a memory operand for an index specification
810
811   Here, an "index specification" is taken to be anything surrounded
812   by square brackets and NOT followed by anything else.
813
814   If it's found, detach it from the input string, remove the surrounding
815   square brackets, and return a pointer to it.  Otherwise, return NULL.  */
816
817static char *
818get_ispec (char *textP)  /* Pointer to memory operand from source instruction, no white space.  */
819
820{
821  /* Points to start of index specification.  */
822  char *start;
823  /* Points to end of index specification.  */
824  char *end;
825
826  /* Find opening square bracket, if any.  */
827  start = strchr (textP, '[');
828
829  if (start != NULL)
830    {
831      /* Eliminate '[', detach from rest of operand.  */
832      *start++ = '\0';
833
834      end = strchr (start, ']');
835
836      if (end == NULL)
837	as_bad (_("unmatched '['"));
838      else
839	{
840	  /* Eliminate ']' and make sure it was the last thing
841	     in the string.  */
842	  *end = '\0';
843	  if (*(end + 1) != '\0')
844	    as_bad (_("garbage after index spec ignored"));
845	}
846    }
847  return start;
848}
849
850/* parse_memop:	parse a memory operand
851
852  	This routine is based on the observation that the 4 mode bits of the
853  	MEMB format, taken individually, have fairly consistent meaning:
854
855  		 M3 (bit 13): 1 if displacement is present (D_BIT)
856  		 M2 (bit 12): 1 for MEMB instructions (MEMB_BIT)
857  		 M1 (bit 11): 1 if index is present (I_BIT)
858  		 M0 (bit 10): 1 if abase is present (A_BIT)
859
860  	So we parse the memory operand and set bits in the mode as we find
861  	things.  Then at the end, if we go to MEMB format, we need only set
862  	the MEMB bit (M2) and our mode is built for us.
863
864  	Unfortunately, I said "fairly consistent".  The exceptions:
865
866  		 DBIA
867  		 0100	Would seem illegal, but means "abase-only".
868
869  		 0101	Would seem to mean "abase-only" -- it means IP-relative.
870  			Must be converted to 0100.
871
872  		 0110	Would seem to mean "index-only", but is reserved.
873  			We turn on the D bit and provide a 0 displacement.
874
875  	The other thing to observe is that we parse from the right, peeling
876  	things * off as we go:  first any index spec, then any abase, then
877  	the displacement.  */
878
879static void
880parse_memop (memS *memP,	/* Where to put the results.  */
881	     char *argP,	/* Text of the operand to be parsed.  */
882	     int optype)	/* MEM1, MEM2, MEM4, MEM8, MEM12, or MEM16.  */
883{
884  char *indexP;			/* Pointer to index specification with "[]" removed.  */
885  char *p;			/* Temp char pointer.  */
886  char iprel_flag;		/* True if this is an IP-relative operand.  */
887  int regnum;			/* Register number.  */
888  /* Scale factor: 1,2,4,8, or 16.  Later converted to internal format
889     (0,1,2,3,4 respectively).  */
890  int scale;
891  int mode;			/* MEMB mode bits.  */
892  int *intP;			/* Pointer to register number.  */
893
894  /* The following table contains the default scale factors for each
895     type of memory instruction.  It is accessed using (optype-MEM1)
896     as an index -- thus it assumes the 'optype' constants are
897     assigned consecutive values, in the order they appear in this
898     table.  */
899  static const int def_scale[] =
900  {
901    1,				/* MEM1 */
902    2,				/* MEM2 */
903    4,				/* MEM4 */
904    8,				/* MEM8 */
905    -1,				/* MEM12 -- no valid default */
906    16				/* MEM16 */
907  };
908
909  iprel_flag = mode = 0;
910
911  /* Any index present? */
912  indexP = get_ispec (argP);
913  if (indexP)
914    {
915      p = strchr (indexP, '*');
916      if (p == NULL)
917	{
918	  /* No explicit scale -- use default for this instruction
919	     type and assembler mode.  */
920	  if (flag_mri)
921	    scale = 1;
922	  else
923	    /* GNU960 compatibility */
924	    scale = def_scale[optype - MEM1];
925	}
926      else
927	{
928	  *p++ = '\0';		/* Eliminate '*' */
929
930	  /* Now indexP->a '\0'-terminated register name,
931	     and p->a scale factor.  */
932
933	  if (!strcmp (p, "16"))
934	    scale = 16;
935	  else if (strchr ("1248", *p) && (p[1] == '\0'))
936	    scale = *p - '0';
937	  else
938	    scale = -1;
939	}
940
941      regnum = get_regnum (indexP);	/* Get index reg. # */
942      if (!IS_RG_REG (regnum))
943	{
944	  as_bad (_("invalid index register"));
945	  return;
946	}
947
948      /* Convert scale to its binary encoding.  */
949      switch (scale)
950	{
951	case 1:
952	  scale = 0 << 7;
953	  break;
954	case 2:
955	  scale = 1 << 7;
956	  break;
957	case 4:
958	  scale = 2 << 7;
959	  break;
960	case 8:
961	  scale = 3 << 7;
962	  break;
963	case 16:
964	  scale = 4 << 7;
965	  break;
966	default:
967	  as_bad (_("invalid scale factor"));
968	  return;
969	};
970
971      memP->opcode |= scale | regnum;	/* Set index bits in opcode.  */
972      mode |= I_BIT;			/* Found a valid index spec.  */
973    }
974
975  /* Any abase (Register Indirect) specification present?  */
976  if ((p = strrchr (argP, '(')) != NULL)
977    {
978      /* "(" is there -- does it start a legal abase spec?  If not, it
979         could be part of a displacement expression.  */
980      intP = (int *) hash_find (areg_hash, p);
981      if (intP != NULL)
982	{
983	  /* Got an abase here.  */
984	  regnum = *intP;
985	  *p = '\0';		/* Discard register spec.  */
986	  if (regnum == IPREL)
987	    /* We have to specialcase ip-rel mode.  */
988	    iprel_flag = 1;
989	  else
990	    {
991	      memP->opcode |= regnum << 14;
992	      mode |= A_BIT;
993	    }
994	}
995    }
996
997  /* Any expression present?  */
998  memP->e = argP;
999  if (*argP != '\0')
1000    mode |= D_BIT;
1001
1002  /* Special-case ip-relative addressing.  */
1003  if (iprel_flag)
1004    {
1005      if (mode & I_BIT)
1006	syntax ();
1007      else
1008	{
1009	  memP->opcode |= 5 << 10;	/* IP-relative mode.  */
1010	  memP->disp = 32;
1011	}
1012      return;
1013    }
1014
1015  /* Handle all other modes.  */
1016  switch (mode)
1017    {
1018    case D_BIT | A_BIT:
1019      /* Go with MEMA instruction format for now (grow to MEMB later
1020         if 12 bits is not enough for the displacement).  MEMA format
1021         has a single mode bit: set it to indicate that abase is
1022         present.  */
1023      memP->opcode |= MEMA_ABASE;
1024      memP->disp = 12;
1025      break;
1026
1027    case D_BIT:
1028      /* Go with MEMA instruction format for now (grow to MEMB later
1029         if 12 bits is not enough for the displacement).  */
1030      memP->disp = 12;
1031      break;
1032
1033    case A_BIT:
1034      /* For some reason, the bit string for this mode is not
1035         consistent: it should be 0 (exclusive of the MEMB bit), so we
1036         set it "by hand" here.  */
1037      memP->opcode |= MEMB_BIT;
1038      break;
1039
1040    case A_BIT | I_BIT:
1041      /* set MEMB bit in mode, and OR in mode bits.  */
1042      memP->opcode |= mode | MEMB_BIT;
1043      break;
1044
1045    case I_BIT:
1046      /* Treat missing displacement as displacement of 0.  */
1047      mode |= D_BIT;
1048      /* Fall into next case.  */
1049    case D_BIT | A_BIT | I_BIT:
1050    case D_BIT | I_BIT:
1051      /* Set MEMB bit in mode, and OR in mode bits.  */
1052      memP->opcode |= mode | MEMB_BIT;
1053      memP->disp = 32;
1054      break;
1055
1056    default:
1057      syntax ();
1058      break;
1059    }
1060}
1061
1062/* Generate a MEMA- or MEMB-format instruction.  */
1063
1064static void
1065mem_fmt (char *args[],		/* args[0]->opcode mnemonic, args[1-3]->operands.  */
1066	 struct i960_opcode *oP,/* Pointer to description of instruction.  */
1067	 int callx)		/* Is this a callx opcode.  */
1068{
1069  int i;			/* Loop counter.  */
1070  struct regop regop;		/* Description of register operand.  */
1071  char opdesc;			/* Operand descriptor byte.  */
1072  memS instr;			/* Description of binary to be output.  */
1073  char *outP;			/* Where the binary was output to.  */
1074  expressionS expr;		/* Parsed expression.  */
1075  /* ->description of deferred address fixup.  */
1076  fixS *fixP;
1077
1078#ifdef OBJ_COFF
1079  /* COFF support isn't in place yet for callx relaxing.  */
1080  callx = 0;
1081#endif
1082
1083  memset (&instr, '\0', sizeof (memS));
1084  instr.opcode = oP->opcode;
1085
1086  /* Process operands.  */
1087  for (i = 1; i <= oP->num_ops; i++)
1088    {
1089      opdesc = oP->operand[i - 1];
1090
1091      if (MEMOP (opdesc))
1092	parse_memop (&instr, args[i], oP->format);
1093      else
1094	{
1095	  parse_regop (&regop, args[i], opdesc);
1096	  instr.opcode |= regop.n << 19;
1097	}
1098    }
1099
1100  /* Parse the displacement; this must be done before emitting the
1101     opcode, in case it is an expression using `.'.  */
1102  parse_expr (instr.e, &expr);
1103
1104  /* Output opcode.  */
1105  outP = emit (instr.opcode);
1106
1107  if (instr.disp == 0)
1108    return;
1109
1110  /* Process the displacement.  */
1111  switch (expr.X_op)
1112    {
1113    case O_illegal:
1114      as_bad (_("expression syntax error"));
1115      break;
1116
1117    case O_constant:
1118      if (instr.disp == 32)
1119	(void) emit (offs (expr));	/* Output displacement.  */
1120      else
1121	{
1122	  /* 12-bit displacement.  */
1123	  if (offs (expr) & ~0xfff)
1124	    {
1125	      /* Won't fit in 12 bits: convert already-output
1126	         instruction to MEMB format, output
1127	         displacement.  */
1128	      mema_to_memb (outP);
1129	      (void) emit (offs (expr));
1130	    }
1131	  else
1132	    {
1133	      /* WILL fit in 12 bits:  OR into opcode and
1134	         overwrite the binary we already put out.  */
1135	      instr.opcode |= offs (expr);
1136	      md_number_to_chars (outP, instr.opcode, 4);
1137	    }
1138	}
1139      break;
1140
1141    default:
1142      if (instr.disp == 12)
1143	/* Displacement is dependent on a symbol, whose value
1144	   may change at link time.  We HAVE to reserve 32 bits.
1145	   Convert already-output opcode to MEMB format.  */
1146	mema_to_memb (outP);
1147
1148      /* Output 0 displacement and set up address fixup for when
1149         this symbol's value becomes known.  */
1150      outP = emit ((long) 0);
1151      fixP = fix_new_exp (frag_now,
1152			  outP - frag_now->fr_literal,
1153			  4, & expr, 0, NO_RELOC);
1154      /* Steve's linker relaxing hack.  Mark this 32-bit relocation as
1155         being in the instruction stream, specifically as part of a callx
1156         instruction.  */
1157      fixP->fx_bsr = callx;
1158      break;
1159    }
1160}
1161
1162/* targ_has_iclass:
1163
1164   Return TRUE iff the target architecture supports the indicated
1165   class of instructions.  */
1166
1167static int
1168targ_has_iclass (int ic) /* Instruction class;  one of:
1169			    I_BASE, I_CX, I_DEC, I_KX, I_FP, I_MIL, I_CASIM, I_CX2, I_HX, I_HX2.  */
1170{
1171  iclasses_seen |= ic;
1172
1173  switch (architecture)
1174    {
1175    case ARCH_KA:
1176      return ic & (I_BASE | I_KX);
1177    case ARCH_KB:
1178      return ic & (I_BASE | I_KX | I_FP | I_DEC);
1179    case ARCH_MC:
1180      return ic & (I_BASE | I_KX | I_FP | I_DEC | I_MIL);
1181    case ARCH_CA:
1182      return ic & (I_BASE | I_CX | I_CX2 | I_CASIM);
1183    case ARCH_JX:
1184      return ic & (I_BASE | I_CX2 | I_JX);
1185    case ARCH_HX:
1186      return ic & (I_BASE | I_CX2 | I_JX | I_HX);
1187    default:
1188      if ((iclasses_seen & (I_KX | I_FP | I_DEC | I_MIL))
1189	  && (iclasses_seen & (I_CX | I_CX2)))
1190	{
1191	  as_warn (_("architecture of opcode conflicts with that of earlier instruction(s)"));
1192	  iclasses_seen &= ~ic;
1193	}
1194      return 1;
1195    }
1196}
1197
1198/* shift_ok:
1199   Determine if a "shlo" instruction can be used to implement a "ldconst".
1200   This means that some number X < 32 can be shifted left to produce the
1201   constant of interest.
1202
1203   Return the shift count, or 0 if we can't do it.
1204   Caller calculates X by shifting original constant right 'shift' places.  */
1205
1206static int
1207shift_ok (int n)		/* The constant of interest.  */
1208{
1209  int shift;			/* The shift count.  */
1210
1211  if (n <= 0)
1212    /* Can't do it for negative numbers.  */
1213    return 0;
1214
1215  /* Shift 'n' right until a 1 is about to be lost.  */
1216  for (shift = 0; (n & 1) == 0; shift++)
1217    n >>= 1;
1218
1219  if (n >= 32)
1220    return 0;
1221
1222  return shift;
1223}
1224
1225/* parse_ldcont:
1226   Parse and replace a 'ldconst' pseudo-instruction with an appropriate
1227   i80960 instruction.
1228
1229   Assumes the input consists of:
1230  		arg[0]	opcode mnemonic ('ldconst')
1231  		arg[1]  first operand (constant)
1232  		arg[2]	name of register to be loaded
1233
1234   Replaces opcode and/or operands as appropriate.
1235
1236   Returns the new number of arguments, or -1 on failure.  */
1237
1238static int
1239parse_ldconst (char *arg[])	/* See above.  */
1240{
1241  int n;			/* Constant to be loaded.  */
1242  int shift;			/* Shift count for "shlo" instruction.  */
1243  static char buf[5];		/* Literal for first operand.  */
1244  static char buf2[5];		/* Literal for second operand.  */
1245  expressionS e;		/* Parsed expression.  */
1246
1247  arg[3] = NULL;		/* So we can tell at the end if it got used or not.  */
1248
1249  parse_expr (arg[1], &e);
1250  switch (e.X_op)
1251    {
1252    default:
1253      /* We're dependent on one or more symbols -- use "lda".  */
1254      arg[0] = "lda";
1255      break;
1256
1257    case O_constant:
1258      /* Try the following mappings:
1259              ldconst   0,<reg>  -> mov  0,<reg>
1260              ldconst  31,<reg>  -> mov  31,<reg>
1261              ldconst  32,<reg>  -> addo 1,31,<reg>
1262              ldconst  62,<reg>  -> addo 31,31,<reg>
1263              ldconst  64,<reg>  -> shlo 8,3,<reg>
1264              ldconst  -1,<reg>  -> subo 1,0,<reg>
1265              ldconst -31,<reg>  -> subo 31,0,<reg>
1266
1267         Anything else becomes:
1268                lda xxx,<reg>.  */
1269      n = offs (e);
1270      if ((0 <= n) && (n <= 31))
1271	arg[0] = "mov";
1272      else if ((-31 <= n) && (n <= -1))
1273	{
1274	  arg[0] = "subo";
1275	  arg[3] = arg[2];
1276	  sprintf (buf, "%d", -n);
1277	  arg[1] = buf;
1278	  arg[2] = "0";
1279	}
1280      else if ((32 <= n) && (n <= 62))
1281	{
1282	  arg[0] = "addo";
1283	  arg[3] = arg[2];
1284	  arg[1] = "31";
1285	  sprintf (buf, "%d", n - 31);
1286	  arg[2] = buf;
1287	}
1288      else if ((shift = shift_ok (n)) != 0)
1289	{
1290	  arg[0] = "shlo";
1291	  arg[3] = arg[2];
1292	  sprintf (buf, "%d", shift);
1293	  arg[1] = buf;
1294	  sprintf (buf2, "%d", n >> shift);
1295	  arg[2] = buf2;
1296	}
1297      else
1298	arg[0] = "lda";
1299      break;
1300
1301    case O_illegal:
1302      as_bad (_("invalid constant"));
1303      return -1;
1304      break;
1305    }
1306  return (arg[3] == 0) ? 2 : 3;
1307}
1308
1309/* reg_fmt:	generate a REG-format instruction.  */
1310
1311static void
1312reg_fmt (char *args[],		/* args[0]->opcode mnemonic, args[1-3]->operands.  */
1313	 struct i960_opcode *oP)/* Pointer to description of instruction.  */
1314{
1315  long instr;			/* Binary to be output.  */
1316  struct regop regop;		/* Description of register operand.  */
1317  int n_ops;			/* Number of operands.  */
1318
1319  instr = oP->opcode;
1320  n_ops = oP->num_ops;
1321
1322  if (n_ops >= 1)
1323    {
1324      parse_regop (&regop, args[1], oP->operand[0]);
1325
1326      if ((n_ops == 1) && !(instr & M3))
1327	{
1328	  /* 1-operand instruction in which the dst field should
1329	     be used (instead of src1).  */
1330	  regop.n <<= 19;
1331	  if (regop.special)
1332	    regop.mode = regop.special;
1333	  regop.mode <<= 13;
1334	  regop.special = 0;
1335	}
1336      else
1337	{
1338	  /* regop.n goes in bit 0, needs no shifting.  */
1339	  regop.mode <<= 11;
1340	  regop.special <<= 5;
1341	}
1342      instr |= regop.n | regop.mode | regop.special;
1343    }
1344
1345  if (n_ops >= 2)
1346    {
1347      parse_regop (&regop, args[2], oP->operand[1]);
1348
1349      if ((n_ops == 2) && !(instr & M3))
1350	{
1351	  /* 2-operand instruction in which the dst field should
1352	     be used instead of src2).  */
1353	  regop.n <<= 19;
1354	  if (regop.special)
1355	    regop.mode = regop.special;
1356	  regop.mode <<= 13;
1357	  regop.special = 0;
1358	}
1359      else
1360	{
1361	  regop.n <<= 14;
1362	  regop.mode <<= 12;
1363	  regop.special <<= 6;
1364	}
1365      instr |= regop.n | regop.mode | regop.special;
1366    }
1367  if (n_ops == 3)
1368    {
1369      parse_regop (&regop, args[3], oP->operand[2]);
1370      if (regop.special)
1371	regop.mode = regop.special;
1372      instr |= (regop.n <<= 19) | (regop.mode <<= 13);
1373    }
1374  emit (instr);
1375}
1376
1377/* get_args:	break individual arguments out of comma-separated list
1378
1379   Input assumptions:
1380  	- all comments and labels have been removed
1381  	- all strings of whitespace have been collapsed to a single blank.
1382  	- all character constants ('x') have been replaced with decimal
1383
1384   Output:
1385  	args[0] is untouched. args[1] points to first operand, etc. All args:
1386  	- are NULL-terminated
1387  	- contain no whitespace
1388
1389   Return value:
1390   Number of operands (0,1,2, or 3) or -1 on error.  */
1391
1392static int
1393get_args (char *p, 	/* Pointer to comma-separated operands; Mucked by us.  */
1394	  char *args[]) /* Output arg: pointers to operands placed in args[1-3].
1395			   Must accommodate 4 entries (args[0-3]).  */
1396
1397{
1398  int n;		/* Number of operands.  */
1399  char *to;
1400
1401  /* Skip lead white space.  */
1402  while (*p == ' ')
1403    p++;
1404
1405  if (*p == '\0')
1406    return 0;
1407
1408  n = 1;
1409  args[1] = p;
1410
1411  /* Squeze blanks out by moving non-blanks toward start of string.
1412     Isolate operands, whenever comma is found.  */
1413  to = p;
1414  while (*p != '\0')
1415    {
1416      if (*p == ' '
1417	  && (! ISALNUM (p[1])
1418	      || ! ISALNUM (p[-1])))
1419	p++;
1420      else if (*p == ',')
1421	{
1422	  /* Start of operand.  */
1423	  if (n == 3)
1424	    {
1425	      as_bad (_("too many operands"));
1426	      return -1;
1427	    }
1428	  *to++ = '\0';		/* Terminate argument.  */
1429	  args[++n] = to;	/* Start next argument.  */
1430	  p++;
1431	}
1432      else
1433	*to++ = *p++;
1434    }
1435  *to = '\0';
1436  return n;
1437}
1438
1439/* i_scan:	perform lexical scan of ascii assembler instruction.
1440
1441   Input assumptions:
1442  	- input string is an i80960 instruction (not a pseudo-op)
1443  	- all comments and labels have been removed
1444  	- all strings of whitespace have been collapsed to a single blank.
1445
1446   Output:
1447  	args[0] points to opcode, other entries point to operands. All strings:
1448  	- are NULL-terminated
1449  	- contain no whitespace
1450  	- have character constants ('x') replaced with a decimal number
1451
1452   Return value:
1453     Number of operands (0,1,2, or 3) or -1 on error.  */
1454
1455static int
1456i_scan (char *iP,     /* Pointer to ascii instruction;  Mucked by us.  */
1457	char *args[]) /* Output arg: pointers to opcode and operands placed here.
1458			 Must accommodate 4 entries.  */
1459{
1460  /* Isolate opcode.  */
1461  if (*(iP) == ' ')
1462    iP++;
1463
1464  args[0] = iP;
1465  for (; *iP != ' '; iP++)
1466    {
1467      if (*iP == '\0')
1468	{
1469	  /* There are no operands.  */
1470	  if (args[0] == iP)
1471	    {
1472	      /* We never moved: there was no opcode either!  */
1473	      as_bad (_("missing opcode"));
1474	      return -1;
1475	    }
1476	  return 0;
1477	}
1478    }
1479  *iP++ = '\0';
1480  return (get_args (iP, args));
1481}
1482
1483static void
1484brcnt_emit (void)
1485{
1486  /* Emit call to "increment" routine.  */
1487  ctrl_fmt (BR_CNT_FUNC, CALL, 1);
1488  /* Emit inline counter to be incremented.  */
1489  emit (0);
1490}
1491
1492static char *
1493brlab_next (void)
1494{
1495  static char buf[20];
1496
1497  sprintf (buf, "%s%d", BR_LABEL_BASE, br_cnt++);
1498  return buf;
1499}
1500
1501static void
1502ctrl_fmt (char *targP,		/* Pointer to text of lone operand (if any).  */
1503	  long opcode,		/* Template of instruction.  */
1504	  int num_ops)		/* Number of operands.  */
1505{
1506  int instrument;		/* TRUE iff we should add instrumentation to track
1507				   how often the branch is taken.  */
1508
1509  if (num_ops == 0)
1510    emit (opcode);		/* Output opcode.  */
1511  else
1512    {
1513      instrument = instrument_branches && (opcode != CALL)
1514	&& (opcode != B) && (opcode != RET) && (opcode != BAL);
1515
1516      if (instrument)
1517	{
1518	  brcnt_emit ();
1519	  colon (brlab_next ());
1520	}
1521
1522      /* The operand MUST be an ip-relative displacement. Parse it
1523         and set up address fix for the instruction we just output.  */
1524      get_cdisp (targP, "CTRL", opcode, 24, 0, 0);
1525
1526      if (instrument)
1527	brcnt_emit ();
1528    }
1529}
1530
1531static void
1532cobr_fmt (/* arg[0]->opcode mnemonic, arg[1-3]->operands (ascii) */
1533	  char *arg[],
1534	  /* Opcode, with branch-prediction bits already set if necessary.  */
1535	  long opcode,
1536	  /* Pointer to description of instruction.  */
1537	  struct i960_opcode *oP)
1538{
1539  long instr;			/* 32-bit instruction.  */
1540  struct regop regop;		/* Description of register operand.  */
1541  int n;			/* Number of operands.  */
1542  int var_frag;			/* 1 if varying length code fragment should
1543				     be emitted;  0 if an address fix
1544				        should be emitted.  */
1545
1546  instr = opcode;
1547  n = oP->num_ops;
1548
1549  if (n >= 1)
1550    {
1551      /* First operand (if any) of a COBR is always a register
1552	 operand.  Parse it.  */
1553      parse_regop (&regop, arg[1], oP->operand[0]);
1554      instr |= (regop.n << 19) | (regop.mode << 13);
1555    }
1556
1557  if (n >= 2)
1558    {
1559      /* Second operand (if any) of a COBR is always a register
1560	 operand.  Parse it.  */
1561      parse_regop (&regop, arg[2], oP->operand[1]);
1562      instr |= (regop.n << 14) | regop.special;
1563    }
1564
1565  if (n < 3)
1566    emit (instr);
1567  else
1568    {
1569      if (instrument_branches)
1570	{
1571	  brcnt_emit ();
1572	  colon (brlab_next ());
1573	}
1574
1575      /* A third operand to a COBR is always a displacement.  Parse
1576         it; if it's relaxable (a cobr "j" directive, or any cobr
1577         other than bbs/bbc when the "-norelax" option is not in use)
1578         set up a variable code fragment; otherwise set up an address
1579         fix.  */
1580      var_frag = !norelax || (oP->format == COJ);	/* TRUE or FALSE */
1581      get_cdisp (arg[3], "COBR", instr, 13, var_frag, 0);
1582
1583      if (instrument_branches)
1584	brcnt_emit ();
1585    }
1586}
1587
1588/* Assumptions about the passed-in text:
1589  	- all comments, labels removed
1590  	- text is an instruction
1591  	- all white space compressed to single blanks
1592  	- all character constants have been replaced with decimal.  */
1593
1594void
1595md_assemble (char *textP)
1596{
1597  /* Parsed instruction text, containing NO whitespace: arg[0]->opcode
1598     mnemonic arg[1-3]->operands, with char constants replaced by
1599     decimal numbers.  */
1600  char *args[4];
1601  /* Number of instruction operands.  */
1602  int n_ops;
1603  /* Pointer to instruction description.  */
1604  struct i960_opcode *oP;
1605  /* TRUE iff opcode mnemonic included branch-prediction suffix (".f"
1606     or ".t").  */
1607  int branch_predict;
1608  /* Setting of branch-prediction bit(s) to be OR'd into instruction
1609     opcode of CTRL/COBR format instructions.  */
1610  long bp_bits;
1611  /* Offset of last character in opcode mnemonic.  */
1612  int n;
1613  const char *bp_error_msg = _("branch prediction invalid on this opcode");
1614
1615  /* Parse instruction into opcode and operands.  */
1616  memset (args, '\0', sizeof (args));
1617
1618  n_ops = i_scan (textP, args);
1619
1620  if (n_ops == -1)
1621    return;			/* Error message already issued.  */
1622
1623  /* Do "macro substitution" (sort of) on 'ldconst' pseudo-instruction.  */
1624  if (!strcmp (args[0], "ldconst"))
1625    {
1626      n_ops = parse_ldconst (args);
1627      if (n_ops == -1)
1628	return;
1629    }
1630
1631  /* Check for branch-prediction suffix on opcode mnemonic, strip it off.  */
1632  n = strlen (args[0]) - 1;
1633  branch_predict = 0;
1634  bp_bits = 0;
1635
1636  if (args[0][n - 1] == '.' && (args[0][n] == 't' || args[0][n] == 'f'))
1637    {
1638      /* We could check here to see if the target architecture
1639	 supports branch prediction, but why bother?  The bit will
1640	 just be ignored by processors that don't use it.  */
1641      branch_predict = 1;
1642      bp_bits = (args[0][n] == 't') ? BP_TAKEN : BP_NOT_TAKEN;
1643      args[0][n - 1] = '\0';	/* Strip suffix from opcode mnemonic */
1644    }
1645
1646  /* Look up opcode mnemonic in table and check number of operands.
1647     Check that opcode is legal for the target architecture.  If all
1648     looks good, assemble instruction.  */
1649  oP = (struct i960_opcode *) hash_find (op_hash, args[0]);
1650  if (!oP || !targ_has_iclass (oP->iclass))
1651    as_bad (_("invalid opcode, \"%s\"."), args[0]);
1652  else if (n_ops != oP->num_ops)
1653    as_bad (_("improper number of operands.  expecting %d, got %d"),
1654	    oP->num_ops, n_ops);
1655  else
1656    {
1657      switch (oP->format)
1658	{
1659	case FBRA:
1660	case CTRL:
1661	  ctrl_fmt (args[1], oP->opcode | bp_bits, oP->num_ops);
1662	  if (oP->format == FBRA)
1663	    /* Now generate a 'bno' to same arg */
1664	    ctrl_fmt (args[1], BNO | bp_bits, 1);
1665	  break;
1666	case COBR:
1667	case COJ:
1668	  cobr_fmt (args, oP->opcode | bp_bits, oP);
1669	  break;
1670	case REG:
1671	  if (branch_predict)
1672	    as_warn (bp_error_msg);
1673	  reg_fmt (args, oP);
1674	  break;
1675	case MEM1:
1676	  if (args[0][0] == 'c' && args[0][1] == 'a')
1677	    {
1678	      if (branch_predict)
1679		as_warn (bp_error_msg);
1680	      mem_fmt (args, oP, 1);
1681	      break;
1682	    }
1683	case MEM2:
1684	case MEM4:
1685	case MEM8:
1686	case MEM12:
1687	case MEM16:
1688	  if (branch_predict)
1689	    as_warn (bp_error_msg);
1690	  mem_fmt (args, oP, 0);
1691	  break;
1692	case CALLJ:
1693	  if (branch_predict)
1694	    as_warn (bp_error_msg);
1695	  /* Output opcode & set up "fixup" (relocation); flag
1696	     relocation as 'callj' type.  */
1697	  know (oP->num_ops == 1);
1698	  get_cdisp (args[1], "CTRL", oP->opcode, 24, 0, 1);
1699	  break;
1700	default:
1701	  BAD_CASE (oP->format);
1702	  break;
1703	}
1704    }
1705}
1706
1707void
1708md_number_to_chars (char *buf,
1709		    valueT value,
1710		    int n)
1711{
1712  number_to_chars_littleendian (buf, value, n);
1713}
1714
1715#define MAX_LITTLENUMS	6
1716#define LNUM_SIZE	sizeof (LITTLENUM_TYPE)
1717
1718/* md_atof:	convert ascii to floating point
1719
1720   Turn a string at input_line_pointer into a floating point constant of type
1721   'type', and store the appropriate bytes at *litP.  The number of LITTLENUMS
1722   emitted is returned at 'sizeP'.  An error message is returned, or a pointer
1723   to an empty message if OK.
1724
1725   Note we call the i386 floating point routine, rather than complicating
1726   things with more files or symbolic links.  */
1727
1728char *
1729md_atof (int type, char *litP, int *sizeP)
1730{
1731  LITTLENUM_TYPE words[MAX_LITTLENUMS];
1732  LITTLENUM_TYPE *wordP;
1733  int prec;
1734  char *t;
1735
1736  switch (type)
1737    {
1738    case 'f':
1739    case 'F':
1740      prec = 2;
1741      break;
1742
1743    case 'd':
1744    case 'D':
1745      prec = 4;
1746      break;
1747
1748    case 't':
1749    case 'T':
1750      prec = 5;
1751      type = 'x';		/* That's what atof_ieee() understands.  */
1752      break;
1753
1754    default:
1755      *sizeP = 0;
1756      return _("Bad call to md_atof()");
1757    }
1758
1759  t = atof_ieee (input_line_pointer, type, words);
1760  if (t)
1761    input_line_pointer = t;
1762
1763  *sizeP = prec * LNUM_SIZE;
1764
1765  /* Output the LITTLENUMs in REVERSE order in accord with i80960
1766     word-order.  (Dunno why atof_ieee doesn't do it in the right
1767     order in the first place -- probably because it's a hack of
1768     atof_m68k.)  */
1769  for (wordP = words + prec - 1; prec--;)
1770    {
1771      md_number_to_chars (litP, (long) (*wordP--), LNUM_SIZE);
1772      litP += sizeof (LITTLENUM_TYPE);
1773    }
1774
1775  return 0;
1776}
1777
1778static void
1779md_number_to_imm (char *buf, long val, int n)
1780{
1781  md_number_to_chars (buf, val, n);
1782}
1783
1784static void
1785md_number_to_field (char *instrP,		/* Pointer to instruction to be fixed.  */
1786		    long val,			/* Address fixup value.  */
1787		    bit_fixS *bfixP)		/* Description of bit field to be fixed up.  */
1788{
1789  int numbits;			/* Length of bit field to be fixed.  */
1790  long instr;			/* 32-bit instruction to be fixed-up.  */
1791  long sign;			/* 0 or -1, according to sign bit of 'val'.  */
1792
1793  /* Convert instruction back to host byte order.  */
1794  instr = md_chars_to_number (instrP, 4);
1795
1796  /* Surprise! -- we stored the number of bits to be modified rather
1797     than a pointer to a structure.  */
1798  numbits = (int) (size_t) bfixP;
1799  if (numbits == 1)
1800    /* This is a no-op, stuck here by reloc_callj().  */
1801    return;
1802
1803  know ((numbits == 13) || (numbits == 24));
1804
1805  /* Propagate sign bit of 'val' for the given number of bits.  Result
1806     should be all 0 or all 1.  */
1807  sign = val >> ((int) numbits - 1);
1808  if (((val < 0) && (sign != -1))
1809      || ((val > 0) && (sign != 0)))
1810    as_bad (_("Fixup of %ld too large for field width of %d"),
1811	    val, numbits);
1812  else
1813    {
1814      /* Put bit field into instruction and write back in target
1815         * byte order.  */
1816      val &= ~(-1 << (int) numbits);	/* Clear unused sign bits.  */
1817      instr |= val;
1818      md_number_to_chars (instrP, instr, 4);
1819    }
1820}
1821
1822
1823/* md_parse_option
1824  	Invocation line includes a switch not recognized by the base assembler.
1825  	See if it's a processor-specific option.  For the 960, these are:
1826
1827  	-norelax:
1828  		Conditional branch instructions that require displacements
1829  		greater than 13 bits (or that have external targets) should
1830  		generate errors.  The default is to replace each such
1831  		instruction with the corresponding compare (or chkbit) and
1832  		branch instructions.  Note that the Intel "j" cobr directives
1833  		are ALWAYS "de-optimized" in this way when necessary,
1834  		regardless of the setting of this option.
1835
1836  	-b:
1837  		Add code to collect information about branches taken, for
1838  		later optimization of branch prediction bits by a separate
1839  		tool.  COBR and CNTL format instructions have branch
1840  		prediction bits (in the CX architecture);  if "BR" represents
1841  		an instruction in one of these classes, the following rep-
1842  		resents the code generated by the assembler:
1843
1844  			call	<increment routine>
1845  			.word	0	# pre-counter
1846  		Label:  BR
1847  			call	<increment routine>
1848  			.word	0	# post-counter
1849
1850  		A table of all such "Labels" is also generated.
1851
1852  	-AKA, -AKB, -AKC, -ASA, -ASB, -AMC, -ACA:
1853  		Select the 80960 architecture.  Instructions or features not
1854  		supported by the selected architecture cause fatal errors.
1855  		The default is to generate code for any instruction or feature
1856  		that is supported by SOME version of the 960 (even if this
1857  		means mixing architectures!).  */
1858
1859const char *md_shortopts = "A:b";
1860struct option md_longopts[] =
1861{
1862#define OPTION_LINKRELAX (OPTION_MD_BASE)
1863  {"linkrelax", no_argument, NULL, OPTION_LINKRELAX},
1864  {"link-relax", no_argument, NULL, OPTION_LINKRELAX},
1865#define OPTION_NORELAX (OPTION_MD_BASE + 1)
1866  {"norelax", no_argument, NULL, OPTION_NORELAX},
1867  {"no-relax", no_argument, NULL, OPTION_NORELAX},
1868  {NULL, no_argument, NULL, 0}
1869};
1870size_t md_longopts_size = sizeof (md_longopts);
1871
1872struct tabentry
1873{
1874  char *flag;
1875  int arch;
1876};
1877static const struct tabentry arch_tab[] =
1878{
1879  {"KA", ARCH_KA},
1880  {"KB", ARCH_KB},
1881  {"SA", ARCH_KA},		/* Synonym for KA.  */
1882  {"SB", ARCH_KB},		/* Synonym for KB.  */
1883  {"KC", ARCH_MC},		/* Synonym for MC.  */
1884  {"MC", ARCH_MC},
1885  {"CA", ARCH_CA},
1886  {"JX", ARCH_JX},
1887  {"HX", ARCH_HX},
1888  {NULL, 0}
1889};
1890
1891int
1892md_parse_option (int c, char *arg)
1893{
1894  switch (c)
1895    {
1896    case OPTION_LINKRELAX:
1897      linkrelax = 1;
1898      flag_keep_locals = 1;
1899      break;
1900
1901    case OPTION_NORELAX:
1902      norelax = 1;
1903      break;
1904
1905    case 'b':
1906      instrument_branches = 1;
1907      break;
1908
1909    case 'A':
1910      {
1911	const struct tabentry *tp;
1912	char *p = arg;
1913
1914	for (tp = arch_tab; tp->flag != NULL; tp++)
1915	  if (!strcmp (p, tp->flag))
1916	    break;
1917
1918	if (tp->flag == NULL)
1919	  {
1920	    as_bad (_("invalid architecture %s"), p);
1921	    return 0;
1922	  }
1923	else
1924	  architecture = tp->arch;
1925      }
1926      break;
1927
1928    default:
1929      return 0;
1930    }
1931
1932  return 1;
1933}
1934
1935void
1936md_show_usage (FILE *stream)
1937{
1938  int i;
1939
1940  fprintf (stream, _("I960 options:\n"));
1941  for (i = 0; arch_tab[i].flag; i++)
1942    fprintf (stream, "%s-A%s", i ? " | " : "", arch_tab[i].flag);
1943  fprintf (stream, _("\n\
1944			specify variant of 960 architecture\n\
1945-b			add code to collect statistics about branches taken\n\
1946-link-relax		preserve individual alignment directives so linker\n\
1947			can do relaxing (b.out format only)\n\
1948-no-relax		don't alter compare-and-branch instructions for\n\
1949			long displacements\n"));
1950}
1951
1952/* relax_cobr:
1953   Replace cobr instruction in a code fragment with equivalent branch and
1954   compare instructions, so it can reach beyond a 13-bit displacement.
1955   Set up an address fix/relocation for the new branch instruction.  */
1956
1957/* This "conditional jump" table maps cobr instructions into
1958   equivalent compare and branch opcodes.  */
1959
1960static const
1961struct
1962{
1963  long compare;
1964  long branch;
1965}
1966
1967coj[] =
1968{				/* COBR OPCODE: */
1969  { CHKBIT, BNO },		/*      0x30 - bbc */
1970  { CMPO, BG },			/*      0x31 - cmpobg */
1971  { CMPO, BE },			/*      0x32 - cmpobe */
1972  { CMPO, BGE },		/*      0x33 - cmpobge */
1973  { CMPO, BL },			/*      0x34 - cmpobl */
1974  { CMPO, BNE },		/*      0x35 - cmpobne */
1975  { CMPO, BLE },		/*      0x36 - cmpoble */
1976  { CHKBIT, BO },		/*      0x37 - bbs */
1977  { CMPI, BNO },		/*      0x38 - cmpibno */
1978  { CMPI, BG },			/*      0x39 - cmpibg */
1979  { CMPI, BE },			/*      0x3a - cmpibe */
1980  { CMPI, BGE },		/*      0x3b - cmpibge */
1981  { CMPI, BL },			/*      0x3c - cmpibl */
1982  { CMPI, BNE },		/*      0x3d - cmpibne */
1983  { CMPI, BLE },		/*      0x3e - cmpible */
1984  { CMPI, BO },			/*      0x3f - cmpibo */
1985};
1986
1987static void
1988relax_cobr (fragS *fragP)	/* fragP->fr_opcode is assumed to point to
1989				   the cobr instruction, which comes at the
1990				   end of the code fragment.  */
1991{
1992  int opcode, src1, src2, m1, s2;
1993  /* Bit fields from cobr instruction.  */
1994  long bp_bits;			/* Branch prediction bits from cobr instruction.  */
1995  long instr;			/* A single i960 instruction.  */
1996  /* ->instruction to be replaced.  */
1997  char *iP;
1998  fixS *fixP;			/* Relocation that can be done at assembly time.  */
1999
2000  /* Pick up & parse cobr instruction.  */
2001  iP = fragP->fr_opcode;
2002  instr = md_chars_to_number (iP, 4);
2003  opcode = ((instr >> 24) & 0xff) - 0x30;	/* "-0x30" for table index.  */
2004  src1 = (instr >> 19) & 0x1f;
2005  m1 = (instr >> 13) & 1;
2006  s2 = instr & 1;
2007  src2 = (instr >> 14) & 0x1f;
2008  bp_bits = instr & BP_MASK;
2009
2010  /* Generate and output compare instruction.  */
2011  instr = coj[opcode].compare
2012    | src1 | (m1 << 11) | (s2 << 6) | (src2 << 14);
2013  md_number_to_chars (iP, instr, 4);
2014
2015  /* Output branch instruction.  */
2016  md_number_to_chars (iP + 4, coj[opcode].branch | bp_bits, 4);
2017
2018  /* Set up address fixup/relocation.  */
2019  fixP = fix_new (fragP,
2020		  iP + 4 - fragP->fr_literal,
2021		  4,
2022		  fragP->fr_symbol,
2023		  fragP->fr_offset,
2024		  1,
2025		  NO_RELOC);
2026
2027  fixP->fx_bit_fixP = (bit_fixS *) 24;	/* Store size of bit field.  */
2028
2029  fragP->fr_fix += 4;
2030  frag_wane (fragP);
2031}
2032
2033/* md_convert_frag:
2034
2035   Called by base assembler after address relaxation is finished:  modify
2036   variable fragments according to how much relaxation was done.
2037
2038   If the fragment substate is still 1, a 13-bit displacement was enough
2039   to reach the symbol in question.  Set up an address fixup, but otherwise
2040   leave the cobr instruction alone.
2041
2042   If the fragment substate is 2, a 13-bit displacement was not enough.
2043   Replace the cobr with a two instructions (a compare and a branch).  */
2044
2045void
2046md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED,
2047		 segT sec ATTRIBUTE_UNUSED,
2048		 fragS *fragP)
2049{
2050  /* Structure describing needed address fix.  */
2051  fixS *fixP;
2052
2053  switch (fragP->fr_subtype)
2054    {
2055    case 1:
2056      /* Leave single cobr instruction.  */
2057      fixP = fix_new (fragP,
2058		      fragP->fr_opcode - fragP->fr_literal,
2059		      4,
2060		      fragP->fr_symbol,
2061		      fragP->fr_offset,
2062		      1,
2063		      NO_RELOC);
2064
2065      fixP->fx_bit_fixP = (bit_fixS *) 13;	/* Size of bit field.  */
2066      break;
2067    case 2:
2068      /* Replace cobr with compare/branch instructions.  */
2069      relax_cobr (fragP);
2070      break;
2071    default:
2072      BAD_CASE (fragP->fr_subtype);
2073      break;
2074    }
2075}
2076
2077/* md_estimate_size_before_relax:  How much does it look like *fragP will grow?
2078
2079   Called by base assembler just before address relaxation.
2080   Return the amount by which the fragment will grow.
2081
2082   Any symbol that is now undefined will not become defined; cobr's
2083   based on undefined symbols will have to be replaced with a compare
2084   instruction and a branch instruction, and the code fragment will grow
2085   by 4 bytes.  */
2086
2087int
2088md_estimate_size_before_relax (fragS *fragP, segT segment_type)
2089{
2090  /* If symbol is undefined in this segment, go to "relaxed" state
2091     (compare and branch instructions instead of cobr) right now.  */
2092  if (S_GET_SEGMENT (fragP->fr_symbol) != segment_type)
2093    {
2094      relax_cobr (fragP);
2095      return 4;
2096    }
2097
2098  return md_relax_table[fragP->fr_subtype].rlx_length;
2099}
2100
2101#if defined(OBJ_AOUT) | defined(OBJ_BOUT)
2102
2103/* md_ri_to_chars:
2104   This routine exists in order to overcome machine byte-order problems
2105   when dealing with bit-field entries in the relocation_info struct.
2106
2107   But relocation info will be used on the host machine only (only
2108   executable code is actually downloaded to the i80960).  Therefore,
2109   we leave it in host byte order.  */
2110
2111static void
2112md_ri_to_chars (char *where, struct relocation_info *ri)
2113{
2114  host_number_to_chars (where, ri->r_address, 4);
2115  host_number_to_chars (where + 4, ri->r_index, 3);
2116#if WORDS_BIGENDIAN
2117  where[7] = (ri->r_pcrel << 7
2118	      | ri->r_length << 5
2119	      | ri->r_extern << 4
2120	      | ri->r_bsr << 3
2121	      | ri->r_disp << 2
2122	      | ri->r_callj << 1
2123	      | ri->nuthin << 0);
2124#else
2125  where[7] = (ri->r_pcrel << 0
2126	      | ri->r_length << 1
2127	      | ri->r_extern << 3
2128	      | ri->r_bsr << 4
2129	      | ri->r_disp << 5
2130	      | ri->r_callj << 6
2131	      | ri->nuthin << 7);
2132#endif
2133}
2134
2135#endif /* defined(OBJ_AOUT) | defined(OBJ_BOUT) */
2136
2137
2138/* brtab_emit:	generate the fetch-prediction branch table.
2139
2140   See the comments above the declaration of 'br_cnt' for details on
2141   branch-prediction instrumentation.
2142
2143   The code emitted here would be functionally equivalent to the following
2144   example assembler source.
2145
2146  			.data
2147  			.align	2
2148  	   BR_TAB_NAME:
2149  			.word	0		# link to next table
2150  			.word	3		# length of table
2151  			.word	LBRANCH0	# 1st entry in table proper
2152  			.word	LBRANCH1
2153  			.word	LBRANCH2  */
2154
2155void
2156brtab_emit (void)
2157{
2158  int i;
2159  char buf[20];
2160  /* Where the binary was output to.  */
2161  char *p;
2162  /* Pointer to description of deferred address fixup.  */
2163  fixS *fixP;
2164
2165  if (!instrument_branches)
2166    return;
2167
2168  subseg_set (data_section, 0);	/*      .data */
2169  frag_align (2, 0, 0);		/*      .align 2 */
2170  record_alignment (now_seg, 2);
2171  colon (BR_TAB_NAME);		/* BR_TAB_NAME: */
2172  emit (0);			/*      .word 0 #link to next table */
2173  emit (br_cnt);		/*      .word n #length of table */
2174
2175  for (i = 0; i < br_cnt; i++)
2176    {
2177      sprintf (buf, "%s%d", BR_LABEL_BASE, i);
2178      p = emit (0);
2179      fixP = fix_new (frag_now,
2180		      p - frag_now->fr_literal,
2181		      4, symbol_find (buf), 0, 0, NO_RELOC);
2182    }
2183}
2184
2185/* s_leafproc:	process .leafproc pseudo-op
2186
2187  	.leafproc takes two arguments, the second one is optional:
2188  		arg[1]: name of 'call' entry point to leaf procedure
2189  		arg[2]: name of 'bal' entry point to leaf procedure
2190
2191  	If the two arguments are identical, or if the second one is missing,
2192  	the first argument is taken to be the 'bal' entry point.
2193
2194  	If there are 2 distinct arguments, we must make sure that the 'bal'
2195  	entry point immediately follows the 'call' entry point in the linked
2196  	list of symbols.  */
2197
2198static void
2199s_leafproc (int n_ops,		/* Number of operands.  */
2200	    char *args[])	/* args[1]->1st operand, args[2]->2nd operand.  */
2201{
2202  symbolS *callP;		/* Pointer to leafproc 'call' entry point symbol.  */
2203  symbolS *balP;		/* Pointer to leafproc 'bal' entry point symbol.  */
2204
2205  if ((n_ops != 1) && (n_ops != 2))
2206    {
2207      as_bad (_("should have 1 or 2 operands"));
2208      return;
2209    }
2210
2211  /* Find or create symbol for 'call' entry point.  */
2212  callP = symbol_find_or_make (args[1]);
2213
2214  if (TC_S_IS_CALLNAME (callP))
2215    as_warn (_("Redefining leafproc %s"), S_GET_NAME (callP));
2216
2217  /* If that was the only argument, use it as the 'bal' entry point.
2218     Otherwise, mark it as the 'call' entry point and find or create
2219     another symbol for the 'bal' entry point.  */
2220  if ((n_ops == 1) || !strcmp (args[1], args[2]))
2221    {
2222      TC_S_FORCE_TO_BALNAME (callP);
2223    }
2224  else
2225    {
2226      TC_S_FORCE_TO_CALLNAME (callP);
2227
2228      balP = symbol_find_or_make (args[2]);
2229      if (TC_S_IS_CALLNAME (balP))
2230	as_warn (_("Redefining leafproc %s"), S_GET_NAME (balP));
2231
2232      TC_S_FORCE_TO_BALNAME (balP);
2233
2234#ifndef OBJ_ELF
2235      tc_set_bal_of_call (callP, balP);
2236#endif
2237    }
2238}
2239
2240/* s_sysproc: process .sysproc pseudo-op
2241
2242   .sysproc takes two arguments:
2243     arg[1]: name of entry point to system procedure
2244     arg[2]: 'entry_num' (index) of system procedure in the range
2245     [0,31] inclusive.
2246
2247   For [ab].out, we store the 'entrynum' in the 'n_other' field of
2248   the symbol.  Since that entry is normally 0, we bias 'entrynum'
2249   by adding 1 to it.  It must be unbiased before it is used.  */
2250
2251static void
2252s_sysproc (int n_ops,		/* Number of operands.  */
2253	   char *args[])	/* args[1]->1st operand, args[2]->2nd operand.  */
2254{
2255  expressionS exp;
2256  symbolS *symP;
2257
2258  if (n_ops != 2)
2259    {
2260      as_bad (_("should have two operands"));
2261      return;
2262    }
2263
2264  /* Parse "entry_num" argument and check it for validity.  */
2265  parse_expr (args[2], &exp);
2266  if (exp.X_op != O_constant
2267      || (offs (exp) < 0)
2268      || (offs (exp) > 31))
2269    {
2270      as_bad (_("'entry_num' must be absolute number in [0,31]"));
2271      return;
2272    }
2273
2274  /* Find/make symbol and stick entry number (biased by +1) into it.  */
2275  symP = symbol_find_or_make (args[1]);
2276
2277  if (TC_S_IS_SYSPROC (symP))
2278    as_warn (_("Redefining entrynum for sysproc %s"), S_GET_NAME (symP));
2279
2280  TC_S_SET_SYSPROC (symP, offs (exp));	/* Encode entry number.  */
2281  TC_S_FORCE_TO_SYSPROC (symP);
2282}
2283
2284/* parse_po:	parse machine-dependent pseudo-op
2285
2286   This is a top-level routine for machine-dependent pseudo-ops.  It slurps
2287   up the rest of the input line, breaks out the individual arguments,
2288   and dispatches them to the correct handler.  */
2289
2290static void
2291parse_po (int po_num)	/* Pseudo-op number:  currently S_LEAFPROC or S_SYSPROC.  */
2292{
2293  /* Pointers operands, with no embedded whitespace.
2294     arg[0] unused, arg[1-3]->operands.  */
2295  char *args[4];
2296  int n_ops;			/* Number of operands.  */
2297  char *p;			/* Pointer to beginning of unparsed argument string.  */
2298  char eol;			/* Character that indicated end of line.  */
2299
2300  extern char is_end_of_line[];
2301
2302  /* Advance input pointer to end of line.  */
2303  p = input_line_pointer;
2304  while (!is_end_of_line[(unsigned char) *input_line_pointer])
2305    input_line_pointer++;
2306
2307  eol = *input_line_pointer;	/* Save end-of-line char.  */
2308  *input_line_pointer = '\0';	/* Terminate argument list.  */
2309
2310  /* Parse out operands.  */
2311  n_ops = get_args (p, args);
2312  if (n_ops == -1)
2313    return;
2314
2315  /* Dispatch to correct handler.  */
2316  switch (po_num)
2317    {
2318    case S_SYSPROC:
2319      s_sysproc (n_ops, args);
2320      break;
2321    case S_LEAFPROC:
2322      s_leafproc (n_ops, args);
2323      break;
2324    default:
2325      BAD_CASE (po_num);
2326      break;
2327    }
2328
2329  /* Restore eol, so line numbers get updated correctly.  Base
2330     assembler assumes we leave input pointer pointing at char
2331     following the eol.  */
2332  *input_line_pointer++ = eol;
2333}
2334
2335/* reloc_callj:	Relocate a 'callj' instruction
2336
2337  	This is a "non-(GNU)-standard" machine-dependent hook.  The base
2338  	assembler calls it when it decides it can relocate an address at
2339  	assembly time instead of emitting a relocation directive.
2340
2341  	Check to see if the relocation involves a 'callj' instruction to a:
2342  	    sysproc:	Replace the default 'call' instruction with a 'calls'
2343  	    leafproc:	Replace the default 'call' instruction with a 'bal'.
2344  	    other proc:	Do nothing.
2345
2346  	See b.out.h for details on the 'n_other' field in a symbol structure.
2347
2348   IMPORTANT!:
2349  	Assumes the caller has already figured out, in the case of a leafproc,
2350  	to use the 'bal' entry point, and has substituted that symbol into the
2351  	passed fixup structure.  */
2352
2353int
2354reloc_callj (fixS *fixP)  /* Relocation that can be done at assembly time.  */
2355{
2356  /* Points to the binary for the instruction being relocated.  */
2357  char *where;
2358
2359  if (!fixP->fx_tcbit)
2360    /* This wasn't a callj instruction in the first place.  */
2361    return 0;
2362
2363  where = fixP->fx_frag->fr_literal + fixP->fx_where;
2364
2365  if (TC_S_IS_SYSPROC (fixP->fx_addsy))
2366    {
2367      /* Symbol is a .sysproc: replace 'call' with 'calls'.  System
2368         procedure number is (other-1).  */
2369      md_number_to_chars (where, CALLS | TC_S_GET_SYSPROC (fixP->fx_addsy), 4);
2370
2371      /* Nothing else needs to be done for this instruction.  Make
2372         sure 'md_number_to_field()' will perform a no-op.  */
2373      fixP->fx_bit_fixP = (bit_fixS *) 1;
2374    }
2375  else if (TC_S_IS_CALLNAME (fixP->fx_addsy))
2376    {
2377      /* Should not happen: see block comment above.  */
2378      as_fatal (_("Trying to 'bal' to %s"), S_GET_NAME (fixP->fx_addsy));
2379    }
2380  else if (TC_S_IS_BALNAME (fixP->fx_addsy))
2381    {
2382      /* Replace 'call' with 'bal'; both instructions have the same
2383         format, so calling code should complete relocation as if
2384         nothing happened here.  */
2385      md_number_to_chars (where, BAL, 4);
2386    }
2387  else if (TC_S_IS_BADPROC (fixP->fx_addsy))
2388    as_bad (_("Looks like a proc, but can't tell what kind.\n"));
2389
2390  /* Otherwise Symbol is neither a sysproc nor a leafproc.  */
2391  return 0;
2392}
2393
2394/* Handle the MRI .endian pseudo-op.  */
2395
2396static void
2397s_endian (int ignore ATTRIBUTE_UNUSED)
2398{
2399  char *name;
2400  char c;
2401
2402  name = input_line_pointer;
2403  c = get_symbol_end ();
2404  if (strcasecmp (name, "little") == 0)
2405    ;
2406  else if (strcasecmp (name, "big") == 0)
2407    as_bad (_("big endian mode is not supported"));
2408  else
2409    as_warn (_("ignoring unrecognized .endian type `%s'"), name);
2410
2411  *input_line_pointer = c;
2412
2413  demand_empty_rest_of_line ();
2414}
2415
2416/* We have no need to default values of symbols.  */
2417
2418symbolS *
2419md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
2420{
2421  return 0;
2422}
2423
2424/* Exactly what point is a PC-relative offset relative TO?
2425   On the i960, they're relative to the address of the instruction,
2426   which we have set up as the address of the fixup too.  */
2427long
2428md_pcrel_from (fixS *fixP)
2429{
2430  return fixP->fx_where + fixP->fx_frag->fr_address;
2431}
2432
2433void
2434md_apply_fix (fixS *fixP,
2435	       valueT *valP,
2436	       segT seg ATTRIBUTE_UNUSED)
2437{
2438  long val = *valP;
2439  char *place = fixP->fx_where + fixP->fx_frag->fr_literal;
2440
2441  if (!fixP->fx_bit_fixP)
2442    {
2443      md_number_to_imm (place, val, fixP->fx_size);
2444    }
2445  else if ((int) (size_t) fixP->fx_bit_fixP == 13
2446	   && fixP->fx_addsy != NULL
2447	   && S_GET_SEGMENT (fixP->fx_addsy) == undefined_section)
2448    {
2449      /* This is a COBR instruction.  They have only a
2450	 13-bit displacement and are only to be used
2451	 for local branches: flag as error, don't generate
2452	 relocation.  */
2453      as_bad_where (fixP->fx_file, fixP->fx_line,
2454		    _("can't use COBR format with external label"));
2455      fixP->fx_addsy = NULL;
2456    }
2457  else
2458    md_number_to_field (place, val, fixP->fx_bit_fixP);
2459
2460  if (fixP->fx_addsy == NULL)
2461    fixP->fx_done = 1;
2462}
2463
2464#if defined(OBJ_AOUT) | defined(OBJ_BOUT)
2465void
2466tc_bout_fix_to_chars (char *where,
2467		      fixS *fixP,
2468		      relax_addressT segment_address_in_file)
2469{
2470  static const unsigned char nbytes_r_length[] = {42, 0, 1, 42, 2};
2471  struct relocation_info ri;
2472  symbolS *symbolP;
2473
2474  memset ((char *) &ri, '\0', sizeof (ri));
2475  symbolP = fixP->fx_addsy;
2476  know (symbolP != 0 || fixP->fx_r_type != NO_RELOC);
2477  ri.r_bsr = fixP->fx_bsr;	/*SAC LD RELAX HACK */
2478  /* These two 'cuz of NS32K */
2479  ri.r_callj = fixP->fx_tcbit;
2480  if (fixP->fx_bit_fixP)
2481    ri.r_length = 2;
2482  else
2483    ri.r_length = nbytes_r_length[fixP->fx_size];
2484  ri.r_pcrel = fixP->fx_pcrel;
2485  ri.r_address = fixP->fx_frag->fr_address + fixP->fx_where - segment_address_in_file;
2486
2487  if (fixP->fx_r_type != NO_RELOC)
2488    {
2489      switch (fixP->fx_r_type)
2490	{
2491	case rs_align:
2492	  ri.r_index = -2;
2493	  ri.r_pcrel = 1;
2494	  ri.r_length = fixP->fx_size - 1;
2495	  break;
2496	case rs_org:
2497	  ri.r_index = -2;
2498	  ri.r_pcrel = 0;
2499	  break;
2500	case rs_fill:
2501	  ri.r_index = -1;
2502	  break;
2503	default:
2504	  abort ();
2505	}
2506      ri.r_extern = 0;
2507    }
2508  else if (linkrelax || !S_IS_DEFINED (symbolP) || fixP->fx_bsr)
2509    {
2510      ri.r_extern = 1;
2511      ri.r_index = symbolP->sy_number;
2512    }
2513  else
2514    {
2515      ri.r_extern = 0;
2516      ri.r_index = S_GET_TYPE (symbolP);
2517    }
2518
2519  /* Output the relocation information in machine-dependent form.  */
2520  md_ri_to_chars (where, &ri);
2521}
2522
2523#endif /* OBJ_AOUT or OBJ_BOUT */
2524
2525/* Align an address by rounding it up to the specified boundary.  */
2526
2527valueT
2528md_section_align (segT seg,
2529		  valueT addr)		/* Address to be rounded up.  */
2530{
2531  int align;
2532
2533  align = bfd_get_section_alignment (stdoutput, seg);
2534  return (addr + (1 << align) - 1) & (-1 << align);
2535}
2536
2537extern int coff_flags;
2538
2539/* For aout or bout, the bal immediately follows the call.
2540
2541   For coff, we cheat and store a pointer to the bal symbol in the
2542   second aux entry of the call.  */
2543
2544#undef OBJ_ABOUT
2545#ifdef OBJ_AOUT
2546#define OBJ_ABOUT
2547#endif
2548#ifdef OBJ_BOUT
2549#define OBJ_ABOUT
2550#endif
2551
2552void
2553tc_set_bal_of_call (symbolS *callP ATTRIBUTE_UNUSED,
2554		    symbolS *balP ATTRIBUTE_UNUSED)
2555{
2556  know (TC_S_IS_CALLNAME (callP));
2557  know (TC_S_IS_BALNAME (balP));
2558
2559#ifdef OBJ_COFF
2560
2561  callP->sy_tc = balP;
2562  S_SET_NUMBER_AUXILIARY (callP, 2);
2563
2564#else /* ! OBJ_COFF */
2565#ifdef OBJ_ABOUT
2566
2567  /* If the 'bal' entry doesn't immediately follow the 'call'
2568     symbol, unlink it from the symbol list and re-insert it.  */
2569  if (symbol_next (callP) != balP)
2570    {
2571      symbol_remove (balP, &symbol_rootP, &symbol_lastP);
2572      symbol_append (balP, callP, &symbol_rootP, &symbol_lastP);
2573    }				/* if not in order */
2574
2575#else /* ! OBJ_ABOUT */
2576  as_fatal ("Only supported for a.out, b.out, or COFF");
2577#endif /* ! OBJ_ABOUT */
2578#endif /* ! OBJ_COFF */
2579}
2580
2581symbolS *
2582tc_get_bal_of_call (symbolS *callP ATTRIBUTE_UNUSED)
2583{
2584  symbolS *retval;
2585
2586  know (TC_S_IS_CALLNAME (callP));
2587
2588#ifdef OBJ_COFF
2589  retval = callP->sy_tc;
2590#else
2591#ifdef OBJ_ABOUT
2592  retval = symbol_next (callP);
2593#else
2594  as_fatal ("Only supported for a.out, b.out, or COFF");
2595#endif /* ! OBJ_ABOUT */
2596#endif /* ! OBJ_COFF */
2597
2598  know (TC_S_IS_BALNAME (retval));
2599  return retval;
2600}
2601
2602#ifdef OBJ_COFF
2603void
2604tc_coff_symbol_emit_hook (symbolS *symbolP ATTRIBUTE_UNUSED)
2605{
2606  if (TC_S_IS_CALLNAME (symbolP))
2607    {
2608      symbolS *balP = tc_get_bal_of_call (symbolP);
2609
2610      symbolP->sy_symbol.ost_auxent[1].x_bal.x_balntry = S_GET_VALUE (balP);
2611      if (S_GET_STORAGE_CLASS (symbolP) == C_EXT)
2612	S_SET_STORAGE_CLASS (symbolP, C_LEAFEXT);
2613      else
2614	S_SET_STORAGE_CLASS (symbolP, C_LEAFSTAT);
2615      S_SET_DATA_TYPE (symbolP, S_GET_DATA_TYPE (symbolP) | (DT_FCN << N_BTSHFT));
2616      /* Fix up the bal symbol.  */
2617      S_SET_STORAGE_CLASS (balP, C_LABEL);
2618    }
2619}
2620#endif /* OBJ_COFF */
2621
2622void
2623i960_handle_align (fragS *fragp ATTRIBUTE_UNUSED)
2624{
2625  if (!linkrelax)
2626    return;
2627
2628#ifndef OBJ_BOUT
2629  as_bad (_("option --link-relax is only supported in b.out format"));
2630  linkrelax = 0;
2631  return;
2632#else
2633
2634  /* The text section "ends" with another alignment reloc, to which we
2635     aren't adding padding.  */
2636  if (fragp->fr_next == text_last_frag
2637      || fragp->fr_next == data_last_frag)
2638    return;
2639
2640  /* alignment directive */
2641  fix_new (fragp, fragp->fr_fix, fragp->fr_offset, 0, 0, 0,
2642	   (int) fragp->fr_type);
2643#endif /* OBJ_BOUT */
2644}
2645
2646int
2647i960_validate_fix (fixS *fixP, segT this_segment_type ATTRIBUTE_UNUSED)
2648{
2649  if (fixP->fx_tcbit && TC_S_IS_CALLNAME (fixP->fx_addsy))
2650    {
2651      /* Relocation should be done via the associated 'bal'
2652         entry point symbol.  */
2653      if (!TC_S_IS_BALNAME (tc_get_bal_of_call (fixP->fx_addsy)))
2654	{
2655	  as_bad_where (fixP->fx_file, fixP->fx_line,
2656			_("No 'bal' entry point for leafproc %s"),
2657			S_GET_NAME (fixP->fx_addsy));
2658	  return 0;
2659	}
2660      fixP->fx_addsy = tc_get_bal_of_call (fixP->fx_addsy);
2661    }
2662
2663  return 1;
2664}
2665
2666/* From cgen.c:  */
2667
2668static short
2669tc_bfd_fix2rtype (fixS *fixP)
2670{
2671  if (fixP->fx_pcrel == 0 && fixP->fx_size == 4)
2672    return BFD_RELOC_32;
2673
2674  if (fixP->fx_pcrel != 0 && fixP->fx_size == 4)
2675    return BFD_RELOC_24_PCREL;
2676
2677  abort ();
2678  return 0;
2679}
2680
2681/* Translate internal representation of relocation info to BFD target
2682   format.
2683
2684   FIXME: To what extent can we get all relevant targets to use this?  */
2685
2686arelent *
2687tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixP)
2688{
2689  arelent * reloc;
2690
2691  reloc = xmalloc (sizeof (arelent));
2692
2693  /* HACK: Is this right?  */
2694  fixP->fx_r_type = tc_bfd_fix2rtype (fixP);
2695
2696  reloc->howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
2697  if (reloc->howto == NULL)
2698    {
2699      as_bad_where (fixP->fx_file, fixP->fx_line,
2700		    "internal error: can't export reloc type %d (`%s')",
2701		    fixP->fx_r_type,
2702		    bfd_get_reloc_code_name (fixP->fx_r_type));
2703      return NULL;
2704    }
2705
2706  assert (!fixP->fx_pcrel == !reloc->howto->pc_relative);
2707
2708  reloc->sym_ptr_ptr = xmalloc (sizeof (asymbol *));
2709  *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixP->fx_addsy);
2710  reloc->address = fixP->fx_frag->fr_address + fixP->fx_where;
2711  reloc->addend = fixP->fx_addnumber;
2712
2713  return reloc;
2714}
2715
2716/* end from cgen.c */
2717
2718const pseudo_typeS md_pseudo_table[] =
2719{
2720  {"bss", s_lcomm, 1},
2721  {"endian", s_endian, 0},
2722  {"extended", float_cons, 't'},
2723  {"leafproc", parse_po, S_LEAFPROC},
2724  {"sysproc", parse_po, S_SYSPROC},
2725
2726  {"word", cons, 4},
2727  {"quad", cons, 16},
2728
2729  {0, 0, 0}
2730};
2731