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