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