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