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