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