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