`.arch cpu_type' pseudo for x86.
[external/binutils.git] / gas / config / tc-i386.c
1 /* i386.c -- Assemble code for the Intel 80386
2    Copyright (C) 1989, 91, 92, 93, 94, 95, 96, 97, 98, 99, 2000
3    Free Software Foundation.
4
5    This file is part of GAS, the GNU Assembler.
6
7    GAS is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    GAS is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GAS; see the file COPYING.  If not, write to the Free
19    Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20    02111-1307, USA.  */
21
22 /*
23   Intel 80386 machine specific gas.
24   Written by Eliot Dresselhaus (eliot@mgm.mit.edu).
25   Bugs & suggestions are completely welcome.  This is free software.
26   Please help us make it better.
27   */
28
29 #include <ctype.h>
30
31 #include "as.h"
32 #include "subsegs.h"
33 #include "opcode/i386.h"
34
35 #ifndef REGISTER_WARNINGS
36 #define REGISTER_WARNINGS 1
37 #endif
38
39 #ifndef INFER_ADDR_PREFIX
40 #define INFER_ADDR_PREFIX 1
41 #endif
42
43 #ifndef SCALE1_WHEN_NO_INDEX
44 /* Specifying a scale factor besides 1 when there is no index is
45    futile.  eg. `mov (%ebx,2),%al' does exactly the same as
46    `mov (%ebx),%al'.  To slavishly follow what the programmer
47    specified, set SCALE1_WHEN_NO_INDEX to 0.  */
48 #define SCALE1_WHEN_NO_INDEX 1
49 #endif
50
51 #define true 1
52 #define false 0
53
54 static unsigned int mode_from_disp_size PARAMS ((unsigned int));
55 static int fits_in_signed_byte PARAMS ((offsetT));
56 static int fits_in_unsigned_byte PARAMS ((offsetT));
57 static int fits_in_unsigned_word PARAMS ((offsetT));
58 static int fits_in_signed_word PARAMS ((offsetT));
59 static int smallest_imm_type PARAMS ((offsetT));
60 static offsetT offset_in_range PARAMS ((offsetT, int));
61 static int add_prefix PARAMS ((unsigned int));
62 static void set_16bit_code_flag PARAMS ((int));
63 static void set_16bit_gcc_code_flag PARAMS((int));
64 static void set_intel_syntax PARAMS ((int));
65 static void set_cpu_arch PARAMS ((int));
66
67 #ifdef BFD_ASSEMBLER
68 static bfd_reloc_code_real_type reloc
69   PARAMS ((int, int, bfd_reloc_code_real_type));
70 #endif
71
72 /* 'md_assemble ()' gathers together information and puts it into a
73    i386_insn. */
74
75 union i386_op
76   {
77     expressionS *disps;
78     expressionS *imms;
79     const reg_entry *regs;
80   };
81
82 struct _i386_insn
83   {
84     /* TM holds the template for the insn were currently assembling. */
85     template tm;
86
87     /* SUFFIX holds the instruction mnemonic suffix if given.
88        (e.g. 'l' for 'movl')  */
89     char suffix;
90
91     /* OPERANDS gives the number of given operands. */
92     unsigned int operands;
93
94     /* REG_OPERANDS, DISP_OPERANDS, MEM_OPERANDS, IMM_OPERANDS give the number
95        of given register, displacement, memory operands and immediate
96        operands. */
97     unsigned int reg_operands, disp_operands, mem_operands, imm_operands;
98
99     /* TYPES [i] is the type (see above #defines) which tells us how to
100        use OP[i] for the corresponding operand.  */
101     unsigned int types[MAX_OPERANDS];
102
103     /* Displacement expression, immediate expression, or register for each
104        operand.  */
105     union i386_op op[MAX_OPERANDS];
106
107     /* Relocation type for operand */
108 #ifdef BFD_ASSEMBLER
109     enum bfd_reloc_code_real disp_reloc[MAX_OPERANDS];
110 #else
111     int disp_reloc[MAX_OPERANDS];
112 #endif
113
114     /* BASE_REG, INDEX_REG, and LOG2_SCALE_FACTOR are used to encode
115        the base index byte below.  */
116     const reg_entry *base_reg;
117     const reg_entry *index_reg;
118     unsigned int log2_scale_factor;
119
120     /* SEG gives the seg_entries of this insn.  They are zero unless
121        explicit segment overrides are given. */
122     const seg_entry *seg[2];    /* segments for memory operands (if given) */
123
124     /* PREFIX holds all the given prefix opcodes (usually null).
125        PREFIXES is the number of prefix opcodes.  */
126     unsigned int prefixes;
127     unsigned char prefix[MAX_PREFIXES];
128
129     /* RM and SIB are the modrm byte and the sib byte where the
130        addressing modes of this insn are encoded.  */
131
132     modrm_byte rm;
133     sib_byte sib;
134   };
135
136 typedef struct _i386_insn i386_insn;
137
138 /* List of chars besides those in app.c:symbol_chars that can start an
139    operand.  Used to prevent the scrubber eating vital white-space.  */
140 #ifdef LEX_AT
141 const char extra_symbol_chars[] = "*%-(@";
142 #else
143 const char extra_symbol_chars[] = "*%-(";
144 #endif
145
146 /* This array holds the chars that always start a comment.  If the
147    pre-processor is disabled, these aren't very useful */
148 #if defined (TE_I386AIX) || ((defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)) && !defined (TE_LINUX) && !defined(TE_FreeBSD))
149 /* Putting '/' here makes it impossible to use the divide operator.
150    However, we need it for compatibility with SVR4 systems.  */
151 const char comment_chars[] = "#/";
152 #define PREFIX_SEPARATOR '\\'
153 #else
154 const char comment_chars[] = "#";
155 #define PREFIX_SEPARATOR '/'
156 #endif
157
158 /* This array holds the chars that only start a comment at the beginning of
159    a line.  If the line seems to have the form '# 123 filename'
160    .line and .file directives will appear in the pre-processed output */
161 /* Note that input_file.c hand checks for '#' at the beginning of the
162    first line of the input file.  This is because the compiler outputs
163    #NO_APP at the beginning of its output. */
164 /* Also note that comments started like this one will always work if
165    '/' isn't otherwise defined.  */
166 #if defined (TE_I386AIX) || ((defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)) && !defined (TE_LINUX) && !defined(TE_FreeBSD))
167 const char line_comment_chars[] = "";
168 #else
169 const char line_comment_chars[] = "/";
170 #endif
171
172 const char line_separator_chars[] = "";
173
174 /* Chars that can be used to separate mant from exp in floating point nums */
175 const char EXP_CHARS[] = "eE";
176
177 /* Chars that mean this number is a floating point constant */
178 /* As in 0f12.456 */
179 /* or    0d1.2345e12 */
180 const char FLT_CHARS[] = "fFdDxX";
181
182 /* tables for lexical analysis */
183 static char mnemonic_chars[256];
184 static char register_chars[256];
185 static char operand_chars[256];
186 static char identifier_chars[256];
187 static char digit_chars[256];
188
189 /* lexical macros */
190 #define is_mnemonic_char(x) (mnemonic_chars[(unsigned char) x])
191 #define is_operand_char(x) (operand_chars[(unsigned char) x])
192 #define is_register_char(x) (register_chars[(unsigned char) x])
193 #define is_space_char(x) ((x) == ' ')
194 #define is_identifier_char(x) (identifier_chars[(unsigned char) x])
195 #define is_digit_char(x) (digit_chars[(unsigned char) x])
196
197 /* put here all non-digit non-letter charcters that may occur in an operand */
198 static char operand_special_chars[] = "%$-+(,)*._~/<>|&^!:[@]";
199
200 /* md_assemble() always leaves the strings it's passed unaltered.  To
201    effect this we maintain a stack of saved characters that we've smashed
202    with '\0's (indicating end of strings for various sub-fields of the
203    assembler instruction). */
204 static char save_stack[32];
205 static char *save_stack_p;      /* stack pointer */
206 #define END_STRING_AND_SAVE(s) \
207         do { *save_stack_p++ = *(s); *(s) = '\0'; } while (0)
208 #define RESTORE_END_STRING(s) \
209         do { *(s) = *--save_stack_p; } while (0)
210
211 /* The instruction we're assembling. */
212 static i386_insn i;
213
214 /* Possible templates for current insn.  */
215 static const templates *current_templates;
216
217 /* Per instruction expressionS buffers: 2 displacements & 2 immediate max. */
218 static expressionS disp_expressions[2], im_expressions[2];
219
220 static int this_operand;          /* Current operand we are working on.  */
221
222 static int flag_do_long_jump;     /* FIXME what does this do?  */
223
224 static int flag_16bit_code;       /* 1 if we're writing 16-bit code,
225                                      0 if 32-bit.  */
226
227 static int intel_syntax = 0;      /* 1 for intel syntax, 0 if att syntax.  */
228
229 static const char *cpu_arch_name = NULL; /* cpu name  */
230
231 static unsigned int cpu_arch_flags = 0;  /* cpu feature flags  */
232
233 static int allow_naked_reg = 0;   /* 1 if register prefix % not required  */
234
235 static char stackop_size = '\0';  /* Used in 16 bit gcc mode to add an l
236                                      suffix to call, ret, enter, leave, push,
237                                      and pop instructions so that gcc has the
238                                      same stack frame as in 32 bit mode.  */
239
240 /* Interface to relax_segment.
241    There are 2 relax states for 386 jump insns: one for conditional &
242    one for unconditional jumps.  This is because these two types of
243    jumps add different sizes to frags when we're figuring out what
244    sort of jump to choose to reach a given label.  */
245
246 /* types */
247 #define COND_JUMP 1             /* conditional jump */
248 #define UNCOND_JUMP 2           /* unconditional jump */
249 /* sizes */
250 #define CODE16  1
251 #define SMALL   0
252 #define SMALL16 (SMALL|CODE16)
253 #define BIG     2
254 #define BIG16   (BIG|CODE16)
255
256 #ifndef INLINE
257 #ifdef __GNUC__
258 #define INLINE __inline__
259 #else
260 #define INLINE
261 #endif
262 #endif
263
264 #define ENCODE_RELAX_STATE(type,size) \
265   ((relax_substateT)((type<<2) | (size)))
266 #define SIZE_FROM_RELAX_STATE(s) \
267     ( (((s) & 0x3) == BIG ? 4 : (((s) & 0x3) == BIG16 ? 2 : 1)) )
268
269 /* This table is used by relax_frag to promote short jumps to long
270    ones where necessary.  SMALL (short) jumps may be promoted to BIG
271    (32 bit long) ones, and SMALL16 jumps to BIG16 (16 bit long).  We
272    don't allow a short jump in a 32 bit code segment to be promoted to
273    a 16 bit offset jump because it's slower (requires data size
274    prefix), and doesn't work, unless the destination is in the bottom
275    64k of the code segment (The top 16 bits of eip are zeroed).  */
276
277 const relax_typeS md_relax_table[] =
278 {
279   /* The fields are:
280      1) most positive reach of this state,
281      2) most negative reach of this state,
282      3) how many bytes this mode will add to the size of the current frag
283      4) which index into the table to try if we can't fit into this one.
284   */
285   {1, 1, 0, 0},
286   {1, 1, 0, 0},
287   {1, 1, 0, 0},
288   {1, 1, 0, 0},
289
290   {127 + 1, -128 + 1, 0, ENCODE_RELAX_STATE (COND_JUMP, BIG)},
291   {127 + 1, -128 + 1, 0, ENCODE_RELAX_STATE (COND_JUMP, BIG16)},
292   /* dword conditionals adds 4 bytes to frag:
293      1 extra opcode byte, 3 extra displacement bytes.  */
294   {0, 0, 4, 0},
295   /* word conditionals add 2 bytes to frag:
296      1 extra opcode byte, 1 extra displacement byte.  */
297   {0, 0, 2, 0},
298
299   {127 + 1, -128 + 1, 0, ENCODE_RELAX_STATE (UNCOND_JUMP, BIG)},
300   {127 + 1, -128 + 1, 0, ENCODE_RELAX_STATE (UNCOND_JUMP, BIG16)},
301   /* dword jmp adds 3 bytes to frag:
302      0 extra opcode bytes, 3 extra displacement bytes.  */
303   {0, 0, 3, 0},
304   /* word jmp adds 1 byte to frag:
305      0 extra opcode bytes, 1 extra displacement byte.  */
306   {0, 0, 1, 0}
307
308 };
309
310 static const arch_entry cpu_arch[] = {
311   {"i8086",     Cpu086 },
312   {"i186",      Cpu086|Cpu186 },
313   {"i286",      Cpu086|Cpu186|Cpu286 },
314   {"i386",      Cpu086|Cpu186|Cpu286|Cpu386 },
315   {"i486",      Cpu086|Cpu186|Cpu286|Cpu386|Cpu486 },
316   {"i586",      Cpu086|Cpu186|Cpu286|Cpu386|Cpu486|Cpu586|CpuMMX },
317   {"i686",      Cpu086|Cpu186|Cpu286|Cpu386|Cpu486|Cpu586|Cpu686|CpuMMX|CpuSSE },
318   {"pentium",   Cpu086|Cpu186|Cpu286|Cpu386|Cpu486|Cpu586|CpuMMX },
319   {"pentiumpro",Cpu086|Cpu186|Cpu286|Cpu386|Cpu486|Cpu586|Cpu686|CpuMMX|CpuSSE },
320   {"k6",        Cpu086|Cpu186|Cpu286|Cpu386|Cpu486|Cpu586|CpuMMX|Cpu3dnow },
321   {"athlon",    Cpu086|Cpu186|Cpu286|Cpu386|Cpu486|Cpu586|Cpu686|CpuMMX|Cpu3dnow },
322   {NULL, 0 }
323 };
324
325
326 void
327 i386_align_code (fragP, count)
328      fragS *fragP;
329      int count;
330 {
331   /* Various efficient no-op patterns for aligning code labels.  */
332   /* Note: Don't try to assemble the instructions in the comments. */
333   /*       0L and 0w are not legal */
334   static const char f32_1[] =
335     {0x90};                                     /* nop                  */
336   static const char f32_2[] =
337     {0x89,0xf6};                                /* movl %esi,%esi       */
338   static const char f32_3[] =
339     {0x8d,0x76,0x00};                           /* leal 0(%esi),%esi    */
340   static const char f32_4[] =
341     {0x8d,0x74,0x26,0x00};                      /* leal 0(%esi,1),%esi  */
342   static const char f32_5[] =
343     {0x90,                                      /* nop                  */
344      0x8d,0x74,0x26,0x00};                      /* leal 0(%esi,1),%esi  */
345   static const char f32_6[] =
346     {0x8d,0xb6,0x00,0x00,0x00,0x00};            /* leal 0L(%esi),%esi   */
347   static const char f32_7[] =
348     {0x8d,0xb4,0x26,0x00,0x00,0x00,0x00};       /* leal 0L(%esi,1),%esi */
349   static const char f32_8[] =
350     {0x90,                                      /* nop                  */
351      0x8d,0xb4,0x26,0x00,0x00,0x00,0x00};       /* leal 0L(%esi,1),%esi */
352   static const char f32_9[] =
353     {0x89,0xf6,                                 /* movl %esi,%esi       */
354      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
355   static const char f32_10[] =
356     {0x8d,0x76,0x00,                            /* leal 0(%esi),%esi    */
357      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
358   static const char f32_11[] =
359     {0x8d,0x74,0x26,0x00,                       /* leal 0(%esi,1),%esi  */
360      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
361   static const char f32_12[] =
362     {0x8d,0xb6,0x00,0x00,0x00,0x00,             /* leal 0L(%esi),%esi   */
363      0x8d,0xbf,0x00,0x00,0x00,0x00};            /* leal 0L(%edi),%edi   */
364   static const char f32_13[] =
365     {0x8d,0xb6,0x00,0x00,0x00,0x00,             /* leal 0L(%esi),%esi   */
366      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
367   static const char f32_14[] =
368     {0x8d,0xb4,0x26,0x00,0x00,0x00,0x00,        /* leal 0L(%esi,1),%esi */
369      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
370   static const char f32_15[] =
371     {0xeb,0x0d,0x90,0x90,0x90,0x90,0x90,        /* jmp .+15; lotsa nops */
372      0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90};
373   static const char f16_3[] =
374     {0x8d,0x74,0x00};                           /* lea 0(%esi),%esi     */
375   static const char f16_4[] =
376     {0x8d,0xb4,0x00,0x00};                      /* lea 0w(%si),%si      */
377   static const char f16_5[] =
378     {0x90,                                      /* nop                  */
379      0x8d,0xb4,0x00,0x00};                      /* lea 0w(%si),%si      */
380   static const char f16_6[] =
381     {0x89,0xf6,                                 /* mov %si,%si          */
382      0x8d,0xbd,0x00,0x00};                      /* lea 0w(%di),%di      */
383   static const char f16_7[] =
384     {0x8d,0x74,0x00,                            /* lea 0(%si),%si       */
385      0x8d,0xbd,0x00,0x00};                      /* lea 0w(%di),%di      */
386   static const char f16_8[] =
387     {0x8d,0xb4,0x00,0x00,                       /* lea 0w(%si),%si      */
388      0x8d,0xbd,0x00,0x00};                      /* lea 0w(%di),%di      */
389   static const char *const f32_patt[] = {
390     f32_1, f32_2, f32_3, f32_4, f32_5, f32_6, f32_7, f32_8,
391     f32_9, f32_10, f32_11, f32_12, f32_13, f32_14, f32_15
392   };
393   static const char *const f16_patt[] = {
394     f32_1, f32_2, f16_3, f16_4, f16_5, f16_6, f16_7, f16_8,
395     f32_15, f32_15, f32_15, f32_15, f32_15, f32_15, f32_15
396   };
397
398   if (count > 0 && count <= 15)
399     {
400       if (flag_16bit_code)
401         {
402           memcpy(fragP->fr_literal + fragP->fr_fix,
403                  f16_patt[count - 1], count);
404           if (count > 8) /* adjust jump offset */
405             fragP->fr_literal[fragP->fr_fix + 1] = count - 2;
406         }
407       else
408         memcpy(fragP->fr_literal + fragP->fr_fix,
409                f32_patt[count - 1], count);
410       fragP->fr_var = count;
411     }
412 }
413
414 static char *output_invalid PARAMS ((int c));
415 static int i386_operand PARAMS ((char *operand_string));
416 static int i386_intel_operand PARAMS ((char *operand_string, int got_a_float));
417 static const reg_entry *parse_register PARAMS ((char *reg_string,
418                                                 char **end_op));
419
420 #ifndef I386COFF
421 static void s_bss PARAMS ((int));
422 #endif
423
424 symbolS *GOT_symbol;            /* Pre-defined "_GLOBAL_OFFSET_TABLE_" */
425
426 static INLINE unsigned int
427 mode_from_disp_size (t)
428      unsigned int t;
429 {
430   return (t & Disp8) ? 1 : (t & (Disp16|Disp32)) ? 2 : 0;
431 }
432
433 static INLINE int
434 fits_in_signed_byte (num)
435      offsetT num;
436 {
437   return (num >= -128) && (num <= 127);
438 }                               /* fits_in_signed_byte() */
439
440 static INLINE int
441 fits_in_unsigned_byte (num)
442      offsetT num;
443 {
444   return (num & 0xff) == num;
445 }                               /* fits_in_unsigned_byte() */
446
447 static INLINE int
448 fits_in_unsigned_word (num)
449      offsetT num;
450 {
451   return (num & 0xffff) == num;
452 }                               /* fits_in_unsigned_word() */
453
454 static INLINE int
455 fits_in_signed_word (num)
456      offsetT num;
457 {
458   return (-32768 <= num) && (num <= 32767);
459 }                               /* fits_in_signed_word() */
460
461 static int
462 smallest_imm_type (num)
463      offsetT num;
464 {
465   if (cpu_arch_flags != 0
466       && cpu_arch_flags != (Cpu086|Cpu186|Cpu286|Cpu386|Cpu486))
467     {
468       /* This code is disabled on the 486 because all the Imm1 forms
469          in the opcode table are slower on the i486.  They're the
470          versions with the implicitly specified single-position
471          displacement, which has another syntax if you really want to
472          use that form.  */
473       if (num == 1)
474         return Imm1 | Imm8 | Imm8S | Imm16 | Imm32;
475     }
476   return (fits_in_signed_byte (num)
477           ? (Imm8S | Imm8 | Imm16 | Imm32)
478           : fits_in_unsigned_byte (num)
479           ? (Imm8 | Imm16 | Imm32)
480           : (fits_in_signed_word (num) || fits_in_unsigned_word (num))
481           ? (Imm16 | Imm32)
482           : (Imm32));
483 }                               /* smallest_imm_type() */
484
485 static offsetT
486 offset_in_range (val, size)
487      offsetT val;
488      int size;
489 {
490   addressT mask;
491
492   switch (size)
493     {
494     case 1: mask = ((addressT) 1 <<  8) - 1; break;
495     case 2: mask = ((addressT) 1 << 16) - 1; break;
496     case 4: mask = ((addressT) 2 << 31) - 1; break;
497     default: abort();
498     }
499
500   /* If BFD64, sign extend val.  */
501   if ((val & ~ (((addressT) 2 << 31) - 1)) == 0)
502     val = (val ^ ((addressT) 1 << 31)) - ((addressT) 1 << 31);
503
504   if ((val & ~ mask) != 0 && (val & ~ mask) != ~ mask)
505     {
506       char buf1[40], buf2[40];
507
508       sprint_value (buf1, val);
509       sprint_value (buf2, val & mask);
510       as_warn (_("%s shortened to %s"), buf1, buf2);
511     }
512   return val & mask;
513 }
514
515 /* Returns 0 if attempting to add a prefix where one from the same
516    class already exists, 1 if non rep/repne added, 2 if rep/repne
517    added.  */
518 static int
519 add_prefix (prefix)
520      unsigned int prefix;
521 {
522   int ret = 1;
523   int q;
524
525   switch (prefix)
526     {
527     default:
528       abort ();
529
530     case CS_PREFIX_OPCODE:
531     case DS_PREFIX_OPCODE:
532     case ES_PREFIX_OPCODE:
533     case FS_PREFIX_OPCODE:
534     case GS_PREFIX_OPCODE:
535     case SS_PREFIX_OPCODE:
536       q = SEG_PREFIX;
537       break;
538
539     case REPNE_PREFIX_OPCODE:
540     case REPE_PREFIX_OPCODE:
541       ret = 2;
542       /* fall thru */
543     case LOCK_PREFIX_OPCODE:
544       q = LOCKREP_PREFIX;
545       break;
546
547     case FWAIT_OPCODE:
548       q = WAIT_PREFIX;
549       break;
550
551     case ADDR_PREFIX_OPCODE:
552       q = ADDR_PREFIX;
553       break;
554
555     case DATA_PREFIX_OPCODE:
556       q = DATA_PREFIX;
557       break;
558     }
559
560   if (i.prefix[q])
561     {
562       as_bad (_("same type of prefix used twice"));
563       return 0;
564     }
565
566   i.prefixes += 1;
567   i.prefix[q] = prefix;
568   return ret;
569 }
570
571 static void
572 set_16bit_code_flag (new_16bit_code_flag)
573      int new_16bit_code_flag;
574 {
575   flag_16bit_code = new_16bit_code_flag;
576   stackop_size = '\0';
577 }
578
579 static void
580 set_16bit_gcc_code_flag (new_16bit_code_flag)
581      int new_16bit_code_flag;
582 {
583   flag_16bit_code = new_16bit_code_flag;
584   stackop_size = new_16bit_code_flag ? 'l' : '\0';
585 }
586
587 static void
588 set_intel_syntax (syntax_flag)
589      int syntax_flag;
590 {
591   /* Find out if register prefixing is specified.  */
592   int ask_naked_reg = 0;
593
594   SKIP_WHITESPACE ();
595   if (! is_end_of_line[(unsigned char) *input_line_pointer])
596     {
597       char *string = input_line_pointer;
598       int e = get_symbol_end ();
599
600       if (strcmp(string, "prefix") == 0)
601         ask_naked_reg = 1;
602       else if (strcmp(string, "noprefix") == 0)
603         ask_naked_reg = -1;
604       else
605         as_bad (_("bad argument to syntax directive."));
606       *input_line_pointer = e;
607     }
608   demand_empty_rest_of_line ();
609
610   intel_syntax = syntax_flag;
611
612   if (ask_naked_reg == 0)
613     {
614 #ifdef BFD_ASSEMBLER
615       allow_naked_reg = (intel_syntax
616                          && (bfd_get_symbol_leading_char (stdoutput) != '\0'));
617 #else
618       allow_naked_reg = 0; /* conservative default */
619 #endif
620     }
621   else
622     allow_naked_reg = (ask_naked_reg < 0);
623 }
624
625 static void
626 set_cpu_arch (dummy)
627     int dummy ATTRIBUTE_UNUSED;
628 {
629   SKIP_WHITESPACE();
630
631   if (! is_end_of_line[(unsigned char) *input_line_pointer])
632     {
633       char *string = input_line_pointer;
634       int e = get_symbol_end ();
635       int i;
636
637       for (i = 0; cpu_arch[i].name; i++)
638         {
639           if (strcmp (string, cpu_arch[i].name) == 0)
640             {
641               cpu_arch_name = cpu_arch[i].name;
642               cpu_arch_flags = cpu_arch[i].flags;
643               break;
644             }
645         }
646       if (!cpu_arch[i].name)
647         as_bad (_("no such architecture: `%s'"), string);
648
649       *input_line_pointer = e;
650     }
651   else
652     as_bad (_("missing cpu architecture"));
653
654   demand_empty_rest_of_line ();
655 }
656
657 const pseudo_typeS md_pseudo_table[] =
658 {
659 #if !defined(OBJ_AOUT) && !defined(USE_ALIGN_PTWO)
660   {"align", s_align_bytes, 0},
661 #else
662   {"align", s_align_ptwo, 0},
663 #endif
664   {"arch", set_cpu_arch, 0},
665 #ifndef I386COFF
666   {"bss", s_bss, 0},
667 #endif
668   {"ffloat", float_cons, 'f'},
669   {"dfloat", float_cons, 'd'},
670   {"tfloat", float_cons, 'x'},
671   {"value", cons, 2},
672   {"noopt", s_ignore, 0},
673   {"optim", s_ignore, 0},
674   {"code16gcc", set_16bit_gcc_code_flag, 1},
675   {"code16", set_16bit_code_flag, 1},
676   {"code32", set_16bit_code_flag, 0},
677   {"intel_syntax", set_intel_syntax, 1},
678   {"att_syntax", set_intel_syntax, 0},
679   {0, 0, 0}
680 };
681
682 /* for interface with expression () */
683 extern char *input_line_pointer;
684
685 /* hash table for instruction mnemonic lookup */
686 static struct hash_control *op_hash;
687 /* hash table for register lookup */
688 static struct hash_control *reg_hash;
689 \f
690
691 void
692 md_begin ()
693 {
694   const char *hash_err;
695
696   /* initialize op_hash hash table */
697   op_hash = hash_new ();
698
699   {
700     register const template *optab;
701     register templates *core_optab;
702
703     optab = i386_optab;         /* setup for loop */
704     core_optab = (templates *) xmalloc (sizeof (templates));
705     core_optab->start = optab;
706
707     while (1)
708       {
709         ++optab;
710         if (optab->name == NULL
711             || strcmp (optab->name, (optab - 1)->name) != 0)
712           {
713             /* different name --> ship out current template list;
714                add to hash table; & begin anew */
715             core_optab->end = optab;
716             hash_err = hash_insert (op_hash,
717                                     (optab - 1)->name,
718                                     (PTR) core_optab);
719             if (hash_err)
720               {
721               hash_error:
722                 as_fatal (_("Internal Error:  Can't hash %s: %s"),
723                           (optab - 1)->name,
724                           hash_err);
725               }
726             if (optab->name == NULL)
727               break;
728             core_optab = (templates *) xmalloc (sizeof (templates));
729             core_optab->start = optab;
730           }
731       }
732   }
733
734   /* initialize reg_hash hash table */
735   reg_hash = hash_new ();
736   {
737     register const reg_entry *regtab;
738
739     for (regtab = i386_regtab;
740          regtab < i386_regtab + sizeof (i386_regtab) / sizeof (i386_regtab[0]);
741          regtab++)
742       {
743         hash_err = hash_insert (reg_hash, regtab->reg_name, (PTR) regtab);
744         if (hash_err)
745           goto hash_error;
746       }
747   }
748
749   /* fill in lexical tables:  mnemonic_chars, operand_chars.  */
750   {
751     register int c;
752     register char *p;
753
754     for (c = 0; c < 256; c++)
755       {
756         if (isdigit (c))
757           {
758             digit_chars[c] = c;
759             mnemonic_chars[c] = c;
760             register_chars[c] = c;
761             operand_chars[c] = c;
762           }
763         else if (islower (c))
764           {
765             mnemonic_chars[c] = c;
766             register_chars[c] = c;
767             operand_chars[c] = c;
768           }
769         else if (isupper (c))
770           {
771             mnemonic_chars[c] = tolower (c);
772             register_chars[c] = mnemonic_chars[c];
773             operand_chars[c] = c;
774           }
775
776         if (isalpha (c) || isdigit (c))
777           identifier_chars[c] = c;
778         else if (c >= 128)
779           {
780             identifier_chars[c] = c;
781             operand_chars[c] = c;
782           }
783       }
784
785 #ifdef LEX_AT
786     identifier_chars['@'] = '@';
787 #endif
788     digit_chars['-'] = '-';
789     identifier_chars['_'] = '_';
790     identifier_chars['.'] = '.';
791
792     for (p = operand_special_chars; *p != '\0'; p++)
793       operand_chars[(unsigned char) *p] = *p;
794   }
795
796 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
797   if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
798     {
799       record_alignment (text_section, 2);
800       record_alignment (data_section, 2);
801       record_alignment (bss_section, 2);
802     }
803 #endif
804 }
805
806 void
807 i386_print_statistics (file)
808      FILE *file;
809 {
810   hash_print_statistics (file, "i386 opcode", op_hash);
811   hash_print_statistics (file, "i386 register", reg_hash);
812 }
813 \f
814
815 #ifdef DEBUG386
816
817 /* debugging routines for md_assemble */
818 static void pi PARAMS ((char *, i386_insn *));
819 static void pte PARAMS ((template *));
820 static void pt PARAMS ((unsigned int));
821 static void pe PARAMS ((expressionS *));
822 static void ps PARAMS ((symbolS *));
823
824 static void
825 pi (line, x)
826      char *line;
827      i386_insn *x;
828 {
829   register template *p;
830   int i;
831
832   fprintf (stdout, "%s: template ", line);
833   pte (&x->tm);
834   fprintf (stdout, "  modrm:  mode %x  reg %x  reg/mem %x",
835            x->rm.mode, x->rm.reg, x->rm.regmem);
836   fprintf (stdout, " base %x  index %x  scale %x\n",
837            x->bi.base, x->bi.index, x->bi.scale);
838   for (i = 0; i < x->operands; i++)
839     {
840       fprintf (stdout, "    #%d:  ", i + 1);
841       pt (x->types[i]);
842       fprintf (stdout, "\n");
843       if (x->types[i]
844           & (Reg | SReg2 | SReg3 | Control | Debug | Test | RegMMX | RegXMM))
845         fprintf (stdout, "%s\n", x->op[i].regs->reg_name);
846       if (x->types[i] & Imm)
847         pe (x->op[i].imms);
848       if (x->types[i] & Disp)
849         pe (x->op[i].disps);
850     }
851 }
852
853 static void
854 pte (t)
855      template *t;
856 {
857   int i;
858   fprintf (stdout, " %d operands ", t->operands);
859   fprintf (stdout, "opcode %x ",
860            t->base_opcode);
861   if (t->extension_opcode != None)
862     fprintf (stdout, "ext %x ", t->extension_opcode);
863   if (t->opcode_modifier & D)
864     fprintf (stdout, "D");
865   if (t->opcode_modifier & W)
866     fprintf (stdout, "W");
867   fprintf (stdout, "\n");
868   for (i = 0; i < t->operands; i++)
869     {
870       fprintf (stdout, "    #%d type ", i + 1);
871       pt (t->operand_types[i]);
872       fprintf (stdout, "\n");
873     }
874 }
875
876 static void
877 pe (e)
878      expressionS *e;
879 {
880   fprintf (stdout, "    operation     %d\n", e->X_op);
881   fprintf (stdout, "    add_number    %ld (%lx)\n",
882            (long) e->X_add_number, (long) e->X_add_number);
883   if (e->X_add_symbol)
884     {
885       fprintf (stdout, "    add_symbol    ");
886       ps (e->X_add_symbol);
887       fprintf (stdout, "\n");
888     }
889   if (e->X_op_symbol)
890     {
891       fprintf (stdout, "    op_symbol    ");
892       ps (e->X_op_symbol);
893       fprintf (stdout, "\n");
894     }
895 }
896
897 static void
898 ps (s)
899      symbolS *s;
900 {
901   fprintf (stdout, "%s type %s%s",
902            S_GET_NAME (s),
903            S_IS_EXTERNAL (s) ? "EXTERNAL " : "",
904            segment_name (S_GET_SEGMENT (s)));
905 }
906
907 struct type_name
908   {
909     unsigned int mask;
910     char *tname;
911   }
912
913 type_names[] =
914 {
915   { Reg8, "r8" },
916   { Reg16, "r16" },
917   { Reg32, "r32" },
918   { Imm8, "i8" },
919   { Imm8S, "i8s" },
920   { Imm16, "i16" },
921   { Imm32, "i32" },
922   { Imm1, "i1" },
923   { BaseIndex, "BaseIndex" },
924   { Disp8, "d8" },
925   { Disp16, "d16" },
926   { Disp32, "d32" },
927   { InOutPortReg, "InOutPortReg" },
928   { ShiftCount, "ShiftCount" },
929   { Control, "control reg" },
930   { Test, "test reg" },
931   { Debug, "debug reg" },
932   { FloatReg, "FReg" },
933   { FloatAcc, "FAcc" },
934   { SReg2, "SReg2" },
935   { SReg3, "SReg3" },
936   { Acc, "Acc" },
937   { JumpAbsolute, "Jump Absolute" },
938   { RegMMX, "rMMX" },
939   { RegXMM, "rXMM" },
940   { EsSeg, "es" },
941   { 0, "" }
942 };
943
944 static void
945 pt (t)
946      unsigned int t;
947 {
948   register struct type_name *ty;
949
950   if (t == Unknown)
951     {
952       fprintf (stdout, _("Unknown"));
953     }
954   else
955     {
956       for (ty = type_names; ty->mask; ty++)
957         if (t & ty->mask)
958           fprintf (stdout, "%s, ", ty->tname);
959     }
960   fflush (stdout);
961 }
962
963 #endif /* DEBUG386 */
964 \f
965 int
966 tc_i386_force_relocation (fixp)
967      struct fix *fixp;
968 {
969 #ifdef BFD_ASSEMBLER
970   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
971       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
972     return 1;
973   return 0;
974 #else
975   /* For COFF */
976   return fixp->fx_r_type == 7;
977 #endif
978 }
979
980 #ifdef BFD_ASSEMBLER
981 static bfd_reloc_code_real_type reloc
982   PARAMS ((int, int, bfd_reloc_code_real_type));
983
984 static bfd_reloc_code_real_type
985 reloc (size, pcrel, other)
986      int size;
987      int pcrel;
988      bfd_reloc_code_real_type other;
989 {
990   if (other != NO_RELOC) return other;
991
992   if (pcrel)
993     {
994       switch (size)
995         {
996         case 1: return BFD_RELOC_8_PCREL;
997         case 2: return BFD_RELOC_16_PCREL;
998         case 4: return BFD_RELOC_32_PCREL;
999         }
1000       as_bad (_("can not do %d byte pc-relative relocation"), size);
1001     }
1002   else
1003     {
1004       switch (size)
1005         {
1006         case 1: return BFD_RELOC_8;
1007         case 2: return BFD_RELOC_16;
1008         case 4: return BFD_RELOC_32;
1009         }
1010       as_bad (_("can not do %d byte relocation"), size);
1011     }
1012
1013   return BFD_RELOC_NONE;
1014 }
1015
1016 /*
1017  * Here we decide which fixups can be adjusted to make them relative to
1018  * the beginning of the section instead of the symbol.  Basically we need
1019  * to make sure that the dynamic relocations are done correctly, so in
1020  * some cases we force the original symbol to be used.
1021  */
1022 int
1023 tc_i386_fix_adjustable (fixP)
1024      fixS *fixP;
1025 {
1026 #if defined (OBJ_ELF) || defined (TE_PE)
1027   /* Prevent all adjustments to global symbols, or else dynamic
1028      linking will not work correctly.  */
1029   if (S_IS_EXTERN (fixP->fx_addsy))
1030     return 0;
1031   if (S_IS_WEAK (fixP->fx_addsy))
1032     return 0;
1033 #endif
1034   /* adjust_reloc_syms doesn't know about the GOT */
1035   if (fixP->fx_r_type == BFD_RELOC_386_GOTOFF
1036       || fixP->fx_r_type == BFD_RELOC_386_PLT32
1037       || fixP->fx_r_type == BFD_RELOC_386_GOT32
1038       || fixP->fx_r_type == BFD_RELOC_RVA
1039       || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
1040       || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
1041     return 0;
1042   return 1;
1043 }
1044 #else
1045 #define reloc(SIZE,PCREL,OTHER) 0
1046 #define BFD_RELOC_16            0
1047 #define BFD_RELOC_32            0
1048 #define BFD_RELOC_16_PCREL      0
1049 #define BFD_RELOC_32_PCREL      0
1050 #define BFD_RELOC_386_PLT32     0
1051 #define BFD_RELOC_386_GOT32     0
1052 #define BFD_RELOC_386_GOTOFF    0
1053 #endif
1054
1055 static int
1056 intel_float_operand PARAMS ((char *mnemonic));
1057
1058 static int
1059 intel_float_operand (mnemonic)
1060      char *mnemonic;
1061 {
1062   if (mnemonic[0] == 'f' && mnemonic[1] =='i')
1063     return 2;
1064
1065   if (mnemonic[0] == 'f')
1066     return 1;
1067
1068   return 0;
1069 }
1070
1071 /* This is the guts of the machine-dependent assembler.  LINE points to a
1072    machine dependent instruction.  This function is supposed to emit
1073    the frags/bytes it assembles to.  */
1074
1075 void
1076 md_assemble (line)
1077      char *line;
1078 {
1079   /* Points to template once we've found it. */
1080   const template *t;
1081
1082   /* Count the size of the instruction generated.  */
1083   int insn_size = 0;
1084
1085   int j;
1086
1087   char mnemonic[MAX_MNEM_SIZE];
1088
1089   /* Initialize globals. */
1090   memset (&i, '\0', sizeof (i));
1091   for (j = 0; j < MAX_OPERANDS; j++)
1092     i.disp_reloc[j] = NO_RELOC;
1093   memset (disp_expressions, '\0', sizeof (disp_expressions));
1094   memset (im_expressions, '\0', sizeof (im_expressions));
1095   save_stack_p = save_stack;    /* reset stack pointer */
1096
1097   /* First parse an instruction mnemonic & call i386_operand for the operands.
1098      We assume that the scrubber has arranged it so that line[0] is the valid
1099      start of a (possibly prefixed) mnemonic. */
1100   {
1101     char *l = line;
1102     char *token_start = l;
1103     char *mnem_p;
1104
1105     /* Non-zero if we found a prefix only acceptable with string insns. */
1106     const char *expecting_string_instruction = NULL;
1107
1108     while (1)
1109       {
1110         mnem_p = mnemonic;
1111         while ((*mnem_p = mnemonic_chars[(unsigned char) *l]) != 0)
1112           {
1113             mnem_p++;
1114             if (mnem_p >= mnemonic + sizeof (mnemonic))
1115               {
1116                 as_bad (_("no such instruction: `%s'"), token_start);
1117                 return;
1118               }
1119             l++;
1120           }
1121         if (!is_space_char (*l)
1122             && *l != END_OF_INSN
1123             && *l != PREFIX_SEPARATOR)
1124           {
1125             as_bad (_("invalid character %s in mnemonic"),
1126                     output_invalid (*l));
1127             return;
1128           }
1129         if (token_start == l)
1130           {
1131             if (*l == PREFIX_SEPARATOR)
1132               as_bad (_("expecting prefix; got nothing"));
1133             else
1134               as_bad (_("expecting mnemonic; got nothing"));
1135             return;
1136           }
1137
1138         /* Look up instruction (or prefix) via hash table.  */
1139         current_templates = hash_find (op_hash, mnemonic);
1140
1141         if (*l != END_OF_INSN
1142             && (! is_space_char (*l) || l[1] != END_OF_INSN)
1143             && current_templates
1144             && (current_templates->start->opcode_modifier & IsPrefix))
1145           {
1146             /* If we are in 16-bit mode, do not allow addr16 or data16.
1147                Similarly, in 32-bit mode, do not allow addr32 or data32.  */
1148             if ((current_templates->start->opcode_modifier & (Size16 | Size32))
1149                 && (((current_templates->start->opcode_modifier & Size32) != 0)
1150                     ^ flag_16bit_code))
1151               {
1152                 as_bad (_("redundant %s prefix"),
1153                         current_templates->start->name);
1154                 return;
1155               }
1156             /* Add prefix, checking for repeated prefixes.  */
1157             switch (add_prefix (current_templates->start->base_opcode))
1158               {
1159               case 0:
1160                 return;
1161               case 2:
1162                 expecting_string_instruction =
1163                   current_templates->start->name;
1164                 break;
1165               }
1166             /* Skip past PREFIX_SEPARATOR and reset token_start.  */
1167             token_start = ++l;
1168           }
1169         else
1170           break;
1171       }
1172
1173     if (!current_templates)
1174       {
1175         /* See if we can get a match by trimming off a suffix.  */
1176         switch (mnem_p[-1])
1177           {
1178           case WORD_MNEM_SUFFIX:
1179           case BYTE_MNEM_SUFFIX:
1180           case SHORT_MNEM_SUFFIX:
1181           case LONG_MNEM_SUFFIX:
1182             i.suffix = mnem_p[-1];
1183             mnem_p[-1] = '\0';
1184             current_templates = hash_find (op_hash, mnemonic);
1185             break;
1186
1187           /* Intel Syntax */
1188           case DWORD_MNEM_SUFFIX:
1189             if (intel_syntax)
1190               {
1191                 i.suffix = mnem_p[-1];
1192                 mnem_p[-1] = '\0';
1193                 current_templates = hash_find (op_hash, mnemonic);
1194                 break;
1195               }
1196           }
1197         if (!current_templates)
1198           {
1199             as_bad (_("no such instruction: `%s'"), token_start);
1200             return;
1201           }
1202       }
1203
1204     /* Check if instruction is supported on specified architecture.  */
1205     if (cpu_arch_flags != 0)
1206       {
1207         if (current_templates->start->cpu_flags & ~ cpu_arch_flags)
1208           {
1209             as_warn (_("`%s' is not supported on `%s'"),
1210                      current_templates->start->name, cpu_arch_name);
1211           }
1212         else if ((Cpu386 & ~ cpu_arch_flags) && !flag_16bit_code)
1213           {
1214             as_warn (_("use .code16 to ensure correct addressing mode"));
1215           }
1216       }
1217
1218     /* check for rep/repne without a string instruction */
1219     if (expecting_string_instruction
1220         && !(current_templates->start->opcode_modifier & IsString))
1221       {
1222         as_bad (_("expecting string instruction after `%s'"),
1223                 expecting_string_instruction);
1224         return;
1225       }
1226
1227     /* There may be operands to parse. */
1228     if (*l != END_OF_INSN)
1229       {
1230         /* parse operands */
1231
1232         /* 1 if operand is pending after ','. */
1233         unsigned int expecting_operand = 0;
1234
1235         /* Non-zero if operand parens not balanced. */
1236         unsigned int paren_not_balanced;
1237
1238         do
1239           {
1240             /* skip optional white space before operand */
1241             if (is_space_char (*l))
1242               ++l;
1243             if (!is_operand_char (*l) && *l != END_OF_INSN)
1244               {
1245                 as_bad (_("invalid character %s before operand %d"),
1246                         output_invalid (*l),
1247                         i.operands + 1);
1248                 return;
1249               }
1250             token_start = l;    /* after white space */
1251             paren_not_balanced = 0;
1252             while (paren_not_balanced || *l != ',')
1253               {
1254                 if (*l == END_OF_INSN)
1255                   {
1256                     if (paren_not_balanced)
1257                       {
1258                         if (!intel_syntax)
1259                           as_bad (_("unbalanced parenthesis in operand %d."),
1260                                   i.operands + 1);
1261                         else
1262                           as_bad (_("unbalanced brackets in operand %d."),
1263                                   i.operands + 1);
1264                         return;
1265                       }
1266                     else
1267                       break;    /* we are done */
1268                   }
1269                 else if (!is_operand_char (*l) && !is_space_char (*l))
1270                   {
1271                     as_bad (_("invalid character %s in operand %d"),
1272                             output_invalid (*l),
1273                             i.operands + 1);
1274                     return;
1275                   }
1276                 if (!intel_syntax)
1277                   {
1278                     if (*l == '(')
1279                       ++paren_not_balanced;
1280                     if (*l == ')')
1281                       --paren_not_balanced;
1282                   }
1283                 else
1284                   {
1285                     if (*l == '[')
1286                       ++paren_not_balanced;
1287                     if (*l == ']')
1288                       --paren_not_balanced;
1289                   }
1290                 l++;
1291               }
1292             if (l != token_start)
1293               {                 /* yes, we've read in another operand */
1294                 unsigned int operand_ok;
1295                 this_operand = i.operands++;
1296                 if (i.operands > MAX_OPERANDS)
1297                   {
1298                     as_bad (_("spurious operands; (%d operands/instruction max)"),
1299                             MAX_OPERANDS);
1300                     return;
1301                   }
1302                 /* now parse operand adding info to 'i' as we go along */
1303                 END_STRING_AND_SAVE (l);
1304
1305                 if (intel_syntax)
1306                   operand_ok = i386_intel_operand (token_start, intel_float_operand (mnemonic));
1307                 else
1308                   operand_ok = i386_operand (token_start);
1309
1310                 RESTORE_END_STRING (l); /* restore old contents */
1311                 if (!operand_ok)
1312                   return;
1313               }
1314             else
1315               {
1316                 if (expecting_operand)
1317                   {
1318                   expecting_operand_after_comma:
1319                     as_bad (_("expecting operand after ','; got nothing"));
1320                     return;
1321                   }
1322                 if (*l == ',')
1323                   {
1324                     as_bad (_("expecting operand before ','; got nothing"));
1325                     return;
1326                   }
1327               }
1328
1329             /* now *l must be either ',' or END_OF_INSN */
1330             if (*l == ',')
1331               {
1332                 if (*++l == END_OF_INSN)
1333                   {             /* just skip it, if it's \n complain */
1334                     goto expecting_operand_after_comma;
1335                   }
1336                 expecting_operand = 1;
1337               }
1338           }
1339         while (*l != END_OF_INSN);      /* until we get end of insn */
1340       }
1341   }
1342
1343   /* Now we've parsed the mnemonic into a set of templates, and have the
1344      operands at hand.
1345
1346      Next, we find a template that matches the given insn,
1347      making sure the overlap of the given operands types is consistent
1348      with the template operand types. */
1349
1350 #define MATCH(overlap, given, template) \
1351   ((overlap & ~JumpAbsolute) \
1352    && ((given) & (BaseIndex|JumpAbsolute)) == ((overlap) & (BaseIndex|JumpAbsolute)))
1353
1354   /* If given types r0 and r1 are registers they must be of the same type
1355      unless the expected operand type register overlap is null.
1356      Note that Acc in a template matches every size of reg.  */
1357 #define CONSISTENT_REGISTER_MATCH(m0, g0, t0, m1, g1, t1) \
1358   ( ((g0) & Reg) == 0 || ((g1) & Reg) == 0 || \
1359     ((g0) & Reg) == ((g1) & Reg) || \
1360     ((((m0) & Acc) ? Reg : (t0)) & (((m1) & Acc) ? Reg : (t1)) & Reg) == 0 )
1361
1362   {
1363     register unsigned int overlap0, overlap1;
1364     unsigned int overlap2;
1365     unsigned int found_reverse_match;
1366     int suffix_check;
1367
1368     /* All intel opcodes have reversed operands except for "bound" and
1369        "enter".  We also don't reverse intersegment "jmp" and "call"
1370        instructions with 2 immediate operands so that the immediate segment
1371        precedes the offset, as it does when in AT&T mode.  "enter" and the
1372        intersegment "jmp" and "call" instructions are the only ones that
1373        have two immediate operands.  */
1374     if (intel_syntax && i.operands > 1
1375         && (strcmp (mnemonic, "bound") != 0)
1376         && !((i.types[0] & Imm) && (i.types[1] & Imm)))
1377       {
1378         union i386_op temp_op;
1379         unsigned int temp_type;
1380         int xchg1 = 0;
1381         int xchg2 = 0;
1382
1383         if (i.operands == 2)
1384           {
1385             xchg1 = 0;
1386             xchg2 = 1;
1387           }
1388         else if (i.operands == 3)
1389           {
1390             xchg1 = 0;
1391             xchg2 = 2;
1392           }
1393         temp_type = i.types[xchg2];
1394         i.types[xchg2] = i.types[xchg1];
1395         i.types[xchg1] = temp_type;
1396         temp_op = i.op[xchg2];
1397         i.op[xchg2] = i.op[xchg1];
1398         i.op[xchg1] = temp_op;
1399
1400         if (i.mem_operands == 2)
1401           {
1402             const seg_entry *temp_seg;
1403             temp_seg = i.seg[0];
1404             i.seg[0] = i.seg[1];
1405             i.seg[1] = temp_seg;
1406           }
1407       }
1408
1409     if (i.imm_operands)
1410       {
1411         /* Try to ensure constant immediates are represented in the smallest
1412            opcode possible.  */
1413         char guess_suffix = 0;
1414         int op;
1415
1416         if (i.suffix)
1417           guess_suffix = i.suffix;
1418         else if (i.reg_operands)
1419           {
1420             /* Figure out a suffix from the last register operand specified.
1421                We can't do this properly yet, ie. excluding InOutPortReg,
1422                but the following works for instructions with immediates.
1423                In any case, we can't set i.suffix yet.  */
1424             for (op = i.operands; --op >= 0; )
1425               if (i.types[op] & Reg)
1426                 {
1427                   if (i.types[op] & Reg8)
1428                     guess_suffix = BYTE_MNEM_SUFFIX;
1429                   else if (i.types[op] & Reg16)
1430                     guess_suffix = WORD_MNEM_SUFFIX;
1431                   break;
1432                 }
1433           }
1434         else if (flag_16bit_code ^ (i.prefix[DATA_PREFIX] != 0))
1435           guess_suffix = WORD_MNEM_SUFFIX;
1436
1437         for (op = i.operands; --op >= 0; )
1438           if ((i.types[op] & Imm)
1439               && i.op[op].imms->X_op == O_constant)
1440             {
1441               /* If a suffix is given, this operand may be shortened.  */
1442               switch (guess_suffix)
1443                 {
1444                 case WORD_MNEM_SUFFIX:
1445                   i.types[op] |= Imm16;
1446                   break;
1447                 case BYTE_MNEM_SUFFIX:
1448                   i.types[op] |= Imm16 | Imm8 | Imm8S;
1449                   break;
1450                 }
1451
1452               /* If this operand is at most 16 bits, convert it to a
1453                  signed 16 bit number before trying to see whether it will
1454                  fit in an even smaller size.  This allows a 16-bit operand
1455                  such as $0xffe0 to be recognised as within Imm8S range.  */
1456               if ((i.types[op] & Imm16)
1457                   && (i.op[op].imms->X_add_number & ~(offsetT)0xffff) == 0)
1458                 {
1459                   i.op[op].imms->X_add_number =
1460                     (((i.op[op].imms->X_add_number & 0xffff) ^ 0x8000) - 0x8000);
1461                 }
1462               i.types[op] |= smallest_imm_type ((long) i.op[op].imms->X_add_number);
1463             }
1464       }
1465
1466     overlap0 = 0;
1467     overlap1 = 0;
1468     overlap2 = 0;
1469     found_reverse_match = 0;
1470     suffix_check = (i.suffix == BYTE_MNEM_SUFFIX
1471                     ? No_bSuf
1472                     : (i.suffix == WORD_MNEM_SUFFIX
1473                        ? No_wSuf
1474                        : (i.suffix == SHORT_MNEM_SUFFIX
1475                           ? No_sSuf
1476                           : (i.suffix == LONG_MNEM_SUFFIX
1477                              ? No_lSuf
1478                              : (i.suffix == DWORD_MNEM_SUFFIX
1479                                 ? No_dSuf
1480                                 : (i.suffix == LONG_DOUBLE_MNEM_SUFFIX ? No_xSuf : 0))))));
1481
1482     for (t = current_templates->start;
1483          t < current_templates->end;
1484          t++)
1485       {
1486         /* Must have right number of operands. */
1487         if (i.operands != t->operands)
1488           continue;
1489
1490         /* Check the suffix, except for some instructions in intel mode.  */
1491         if ((t->opcode_modifier & suffix_check)
1492             && !(intel_syntax
1493                  && t->base_opcode == 0xd9
1494                  && (t->extension_opcode == 5   /* 0xd9,5 "fldcw"  */
1495                      || t->extension_opcode == 7))) /* 0xd9,7 "f{n}stcw"  */
1496           continue;
1497
1498         else if (!t->operands)
1499           break;                /* 0 operands always matches */
1500
1501         overlap0 = i.types[0] & t->operand_types[0];
1502         switch (t->operands)
1503           {
1504           case 1:
1505             if (!MATCH (overlap0, i.types[0], t->operand_types[0]))
1506               continue;
1507             break;
1508           case 2:
1509           case 3:
1510             overlap1 = i.types[1] & t->operand_types[1];
1511             if (!MATCH (overlap0, i.types[0], t->operand_types[0])
1512                 || !MATCH (overlap1, i.types[1], t->operand_types[1])
1513                 || !CONSISTENT_REGISTER_MATCH (overlap0, i.types[0],
1514                                                t->operand_types[0],
1515                                                overlap1, i.types[1],
1516                                                t->operand_types[1]))
1517               {
1518
1519                 /* check if other direction is valid ... */
1520                 if ((t->opcode_modifier & (D|FloatD)) == 0)
1521                   continue;
1522
1523                 /* try reversing direction of operands */
1524                 overlap0 = i.types[0] & t->operand_types[1];
1525                 overlap1 = i.types[1] & t->operand_types[0];
1526                 if (!MATCH (overlap0, i.types[0], t->operand_types[1])
1527                     || !MATCH (overlap1, i.types[1], t->operand_types[0])
1528                     || !CONSISTENT_REGISTER_MATCH (overlap0, i.types[0],
1529                                                    t->operand_types[1],
1530                                                    overlap1, i.types[1],
1531                                                    t->operand_types[0]))
1532                   {
1533                     /* does not match either direction */
1534                     continue;
1535                   }
1536                 /* found_reverse_match holds which of D or FloatDR
1537                    we've found.  */
1538                 found_reverse_match = t->opcode_modifier & (D|FloatDR);
1539                 break;
1540               }
1541             /* found a forward 2 operand match here */
1542             if (t->operands == 3)
1543               {
1544                 /* Here we make use of the fact that there are no
1545                    reverse match 3 operand instructions, and all 3
1546                    operand instructions only need to be checked for
1547                    register consistency between operands 2 and 3.  */
1548                 overlap2 = i.types[2] & t->operand_types[2];
1549                 if (!MATCH (overlap2, i.types[2], t->operand_types[2])
1550                     || !CONSISTENT_REGISTER_MATCH (overlap1, i.types[1],
1551                                                    t->operand_types[1],
1552                                                    overlap2, i.types[2],
1553                                                    t->operand_types[2]))
1554
1555                   continue;
1556               }
1557             /* found either forward/reverse 2 or 3 operand match here:
1558                slip through to break */
1559           }
1560         break;                  /* we've found a match; break out of loop */
1561       }                         /* for (t = ... */
1562     if (t == current_templates->end)
1563       {                         /* we found no match */
1564         as_bad (_("suffix or operands invalid for `%s'"),
1565                 current_templates->start->name);
1566         return;
1567       }
1568
1569     if (!intel_syntax
1570         && (i.types[0] & JumpAbsolute) != (t->operand_types[0] & JumpAbsolute))
1571       {
1572         as_warn (_("indirect %s without `*'"), t->name);
1573       }
1574
1575     if ((t->opcode_modifier & (IsPrefix|IgnoreSize)) == (IsPrefix|IgnoreSize))
1576       {
1577         /* Warn them that a data or address size prefix doesn't affect
1578            assembly of the next line of code.  */
1579         as_warn (_("stand-alone `%s' prefix"), t->name);
1580       }
1581
1582     /* Copy the template we found.  */
1583     i.tm = *t;
1584     if (found_reverse_match)
1585       {
1586         /* If we found a reverse match we must alter the opcode
1587            direction bit.  found_reverse_match holds bits to change
1588            (different for int & float insns).  */
1589
1590         i.tm.base_opcode ^= found_reverse_match;
1591
1592         i.tm.operand_types[0] = t->operand_types[1];
1593         i.tm.operand_types[1] = t->operand_types[0];
1594       }
1595
1596     /* Undo SYSV386_COMPAT brokenness when in Intel mode.  See i386.h  */
1597      if (SYSV386_COMPAT
1598          && intel_syntax
1599          && (i.tm.base_opcode & 0xfffffde0) == 0xdce0)
1600        i.tm.base_opcode ^= FloatR;
1601
1602     if (i.tm.opcode_modifier & FWait)
1603       if (! add_prefix (FWAIT_OPCODE))
1604         return;
1605
1606     /* Check string instruction segment overrides */
1607     if ((i.tm.opcode_modifier & IsString) != 0 && i.mem_operands != 0)
1608       {
1609         int mem_op = (i.types[0] & AnyMem) ? 0 : 1;
1610         if ((i.tm.operand_types[mem_op] & EsSeg) != 0)
1611           {
1612             if (i.seg[0] != NULL && i.seg[0] != &es)
1613               {
1614                 as_bad (_("`%s' operand %d must use `%%es' segment"),
1615                         i.tm.name,
1616                         mem_op + 1);
1617                 return;
1618               }
1619             /* There's only ever one segment override allowed per instruction.
1620                This instruction possibly has a legal segment override on the
1621                second operand, so copy the segment to where non-string
1622                instructions store it, allowing common code.  */
1623             i.seg[0] = i.seg[1];
1624           }
1625         else if ((i.tm.operand_types[mem_op + 1] & EsSeg) != 0)
1626           {
1627             if (i.seg[1] != NULL && i.seg[1] != &es)
1628               {
1629                 as_bad (_("`%s' operand %d must use `%%es' segment"),
1630                         i.tm.name,
1631                         mem_op + 2);
1632                 return;
1633               }
1634           }
1635       }
1636
1637     /* If matched instruction specifies an explicit instruction mnemonic
1638        suffix, use it.  */
1639     if (i.tm.opcode_modifier & (Size16 | Size32))
1640       {
1641         if (i.tm.opcode_modifier & Size16)
1642           i.suffix = WORD_MNEM_SUFFIX;
1643         else
1644           i.suffix = LONG_MNEM_SUFFIX;
1645       }
1646     else if (i.reg_operands)
1647       {
1648         /* If there's no instruction mnemonic suffix we try to invent one
1649            based on register operands. */
1650         if (!i.suffix)
1651           {
1652             /* We take i.suffix from the last register operand specified,
1653                Destination register type is more significant than source
1654                register type.  */
1655             int op;
1656             for (op = i.operands; --op >= 0; )
1657               if ((i.types[op] & Reg)
1658                   && !(i.tm.operand_types[op] & InOutPortReg))
1659                 {
1660                   i.suffix = ((i.types[op] & Reg8) ? BYTE_MNEM_SUFFIX :
1661                               (i.types[op] & Reg16) ? WORD_MNEM_SUFFIX :
1662                               LONG_MNEM_SUFFIX);
1663                   break;
1664                 }
1665           }
1666         else if (i.suffix == BYTE_MNEM_SUFFIX)
1667           {
1668             int op;
1669             for (op = i.operands; --op >= 0; )
1670               {
1671                 /* If this is an eight bit register, it's OK.  If it's
1672                    the 16 or 32 bit version of an eight bit register,
1673                    we will just use the low portion, and that's OK too. */
1674                 if (i.types[op] & Reg8)
1675                   continue;
1676
1677                 /* movzx and movsx should not generate this warning. */
1678                 if (intel_syntax
1679                     && (i.tm.base_opcode == 0xfb7
1680                         || i.tm.base_opcode == 0xfb6
1681                         || i.tm.base_opcode == 0xfbe
1682                         || i.tm.base_opcode == 0xfbf))
1683                   continue;
1684
1685                 if ((i.types[op] & WordReg) && i.op[op].regs->reg_num < 4
1686 #if 0
1687                     /* Check that the template allows eight bit regs
1688                        This kills insns such as `orb $1,%edx', which
1689                        maybe should be allowed.  */
1690                     && (i.tm.operand_types[op] & (Reg8|InOutPortReg))
1691 #endif
1692                     )
1693                   {
1694 #if REGISTER_WARNINGS
1695                     if ((i.tm.operand_types[op] & InOutPortReg) == 0)
1696                       as_warn (_("using `%%%s' instead of `%%%s' due to `%c' suffix"),
1697                                (i.op[op].regs - (i.types[op] & Reg16 ? 8 : 16))->reg_name,
1698                                i.op[op].regs->reg_name,
1699                                i.suffix);
1700 #endif
1701                     continue;
1702                   }
1703                 /* Any other register is bad */
1704                 if (i.types[op] & (Reg | RegMMX | RegXMM
1705                                    | SReg2 | SReg3
1706                                    | Control | Debug | Test
1707                                    | FloatReg | FloatAcc))
1708                   {
1709                     as_bad (_("`%%%s' not allowed with `%s%c'"),
1710                             i.op[op].regs->reg_name,
1711                             i.tm.name,
1712                             i.suffix);
1713                     return;
1714                   }
1715               }
1716           }
1717         else if (i.suffix == LONG_MNEM_SUFFIX)
1718           {
1719             int op;
1720             for (op = i.operands; --op >= 0; )
1721               /* Reject eight bit registers, except where the template
1722                  requires them. (eg. movzb)  */
1723               if ((i.types[op] & Reg8) != 0
1724                   && (i.tm.operand_types[op] & (Reg16|Reg32|Acc)) != 0)
1725                 {
1726                   as_bad (_("`%%%s' not allowed with `%s%c'"),
1727                           i.op[op].regs->reg_name,
1728                           i.tm.name,
1729                           i.suffix);
1730                   return;
1731                 }
1732 #if REGISTER_WARNINGS
1733               /* Warn if the e prefix on a general reg is missing.  */
1734               else if ((i.types[op] & Reg16) != 0
1735                        && (i.tm.operand_types[op] & (Reg32|Acc)) != 0)
1736                 {
1737                   as_warn (_("using `%%%s' instead of `%%%s' due to `%c' suffix"),
1738                            (i.op[op].regs + 8)->reg_name,
1739                            i.op[op].regs->reg_name,
1740                            i.suffix);
1741                 }
1742 #endif
1743           }
1744         else if (i.suffix == WORD_MNEM_SUFFIX)
1745           {
1746             int op;
1747             for (op = i.operands; --op >= 0; )
1748               /* Reject eight bit registers, except where the template
1749                  requires them. (eg. movzb)  */
1750               if ((i.types[op] & Reg8) != 0
1751                   && (i.tm.operand_types[op] & (Reg16|Reg32|Acc)) != 0)
1752                 {
1753                   as_bad (_("`%%%s' not allowed with `%s%c'"),
1754                           i.op[op].regs->reg_name,
1755                           i.tm.name,
1756                           i.suffix);
1757                   return;
1758                 }
1759 #if REGISTER_WARNINGS
1760               /* Warn if the e prefix on a general reg is present.  */
1761               else if ((i.types[op] & Reg32) != 0
1762                        && (i.tm.operand_types[op] & (Reg16|Acc)) != 0)
1763                 {
1764                   as_warn (_("using `%%%s' instead of `%%%s' due to `%c' suffix"),
1765                            (i.op[op].regs - 8)->reg_name,
1766                            i.op[op].regs->reg_name,
1767                            i.suffix);
1768                 }
1769 #endif
1770           }
1771         else
1772           abort();
1773       }
1774     else if ((i.tm.opcode_modifier & DefaultSize) && !i.suffix)
1775       {
1776         i.suffix = stackop_size;
1777       }
1778
1779     /* Make still unresolved immediate matches conform to size of immediate
1780        given in i.suffix.  Note: overlap2 cannot be an immediate!  */
1781     if ((overlap0 & (Imm8 | Imm8S | Imm16 | Imm32))
1782         && overlap0 != Imm8 && overlap0 != Imm8S
1783         && overlap0 != Imm16 && overlap0 != Imm32)
1784       {
1785         if (i.suffix)
1786           {
1787             overlap0 &= (i.suffix == BYTE_MNEM_SUFFIX ? (Imm8 | Imm8S) :
1788                          (i.suffix == WORD_MNEM_SUFFIX ? Imm16 : Imm32));
1789           }
1790         else if (overlap0 == (Imm16 | Imm32))
1791           {
1792             overlap0 =
1793               (flag_16bit_code ^ (i.prefix[DATA_PREFIX] != 0)) ? Imm16 : Imm32;
1794           }
1795         else
1796           {
1797             as_bad (_("no instruction mnemonic suffix given; can't determine immediate size"));
1798             return;
1799           }
1800       }
1801     if ((overlap1 & (Imm8 | Imm8S | Imm16 | Imm32))
1802         && overlap1 != Imm8 && overlap1 != Imm8S
1803         && overlap1 != Imm16 && overlap1 != Imm32)
1804       {
1805         if (i.suffix)
1806           {
1807             overlap1 &= (i.suffix == BYTE_MNEM_SUFFIX ? (Imm8 | Imm8S) :
1808                          (i.suffix == WORD_MNEM_SUFFIX ? Imm16 : Imm32));
1809           }
1810         else if (overlap1 == (Imm16 | Imm32))
1811           {
1812             overlap1 =
1813               (flag_16bit_code ^ (i.prefix[DATA_PREFIX] != 0)) ? Imm16 : Imm32;
1814           }
1815         else
1816           {
1817             as_bad (_("no instruction mnemonic suffix given; can't determine immediate size"));
1818             return;
1819           }
1820       }
1821     assert ((overlap2 & Imm) == 0);
1822
1823     i.types[0] = overlap0;
1824     if (overlap0 & ImplicitRegister)
1825       i.reg_operands--;
1826     if (overlap0 & Imm1)
1827       i.imm_operands = 0;       /* kludge for shift insns */
1828
1829     i.types[1] = overlap1;
1830     if (overlap1 & ImplicitRegister)
1831       i.reg_operands--;
1832
1833     i.types[2] = overlap2;
1834     if (overlap2 & ImplicitRegister)
1835       i.reg_operands--;
1836
1837     /* Finalize opcode.  First, we change the opcode based on the operand
1838        size given by i.suffix:  We need not change things for byte insns.  */
1839
1840     if (!i.suffix && (i.tm.opcode_modifier & W))
1841       {
1842         as_bad (_("no instruction mnemonic suffix given and no register operands; can't size instruction"));
1843         return;
1844       }
1845
1846     /* For movzx and movsx, need to check the register type */
1847     if (intel_syntax
1848         && (i.tm.base_opcode == 0xfb6 || i.tm.base_opcode == 0xfbe))
1849       if (i.suffix && i.suffix == BYTE_MNEM_SUFFIX)
1850         {
1851           unsigned int prefix = DATA_PREFIX_OPCODE;
1852
1853           if ((i.op[1].regs->reg_type & Reg16) != 0)
1854             if (!add_prefix (prefix))
1855               return;
1856         }
1857
1858     if (i.suffix && i.suffix != BYTE_MNEM_SUFFIX)
1859       {
1860         /* It's not a byte, select word/dword operation.  */
1861         if (i.tm.opcode_modifier & W)
1862           {
1863             if (i.tm.opcode_modifier & ShortForm)
1864               i.tm.base_opcode |= 8;
1865             else
1866               i.tm.base_opcode |= 1;
1867           }
1868         /* Now select between word & dword operations via the operand
1869            size prefix, except for instructions that will ignore this
1870            prefix anyway.  */
1871         if (((intel_syntax && (i.suffix == DWORD_MNEM_SUFFIX))
1872              || i.suffix == LONG_MNEM_SUFFIX) == flag_16bit_code
1873             && !(i.tm.opcode_modifier & IgnoreSize))
1874           {
1875             unsigned int prefix = DATA_PREFIX_OPCODE;
1876             if (i.tm.opcode_modifier & JumpByte) /* jcxz, loop */
1877               prefix = ADDR_PREFIX_OPCODE;
1878
1879             if (! add_prefix (prefix))
1880               return;
1881           }
1882         /* Size floating point instruction.  */
1883         if (i.suffix == LONG_MNEM_SUFFIX
1884             || (intel_syntax && i.suffix == DWORD_MNEM_SUFFIX))
1885           {
1886             if (i.tm.opcode_modifier & FloatMF)
1887               i.tm.base_opcode ^= 4;
1888           }
1889       }
1890
1891     if (i.tm.opcode_modifier & ImmExt)
1892       {
1893         /* These AMD 3DNow! and Intel Katmai New Instructions have an
1894            opcode suffix which is coded in the same place as an 8-bit
1895            immediate field would be.  Here we fake an 8-bit immediate
1896            operand from the opcode suffix stored in tm.extension_opcode.  */
1897
1898         expressionS *exp;
1899
1900         assert(i.imm_operands == 0 && i.operands <= 2 && 2 < MAX_OPERANDS);
1901
1902         exp = &im_expressions[i.imm_operands++];
1903         i.op[i.operands].imms = exp;
1904         i.types[i.operands++] = Imm8;
1905         exp->X_op = O_constant;
1906         exp->X_add_number = i.tm.extension_opcode;
1907         i.tm.extension_opcode = None;
1908       }
1909
1910     /* For insns with operands there are more diddles to do to the opcode. */
1911     if (i.operands)
1912       {
1913         /* Default segment register this instruction will use
1914            for memory accesses.  0 means unknown.
1915            This is only for optimizing out unnecessary segment overrides.  */
1916         const seg_entry *default_seg = 0;
1917
1918         /* The imul $imm, %reg instruction is converted into
1919            imul $imm, %reg, %reg, and the clr %reg instruction
1920            is converted into xor %reg, %reg.  */
1921         if (i.tm.opcode_modifier & regKludge)
1922           {
1923             unsigned int first_reg_op = (i.types[0] & Reg) ? 0 : 1;
1924             /* Pretend we saw the extra register operand. */
1925             assert (i.op[first_reg_op+1].regs == 0);
1926             i.op[first_reg_op+1].regs = i.op[first_reg_op].regs;
1927             i.types[first_reg_op+1] = i.types[first_reg_op];
1928             i.reg_operands = 2;
1929           }
1930
1931         if (i.tm.opcode_modifier & ShortForm)
1932           {
1933             /* The register or float register operand is in operand 0 or 1. */
1934             unsigned int op = (i.types[0] & (Reg | FloatReg)) ? 0 : 1;
1935             /* Register goes in low 3 bits of opcode. */
1936             i.tm.base_opcode |= i.op[op].regs->reg_num;
1937             if ((i.tm.opcode_modifier & Ugh) != 0)
1938               {
1939                 /* Warn about some common errors, but press on regardless.
1940                    The first case can be generated by gcc (<= 2.8.1).  */
1941                 if (i.operands == 2)
1942                   {
1943                     /* reversed arguments on faddp, fsubp, etc. */
1944                     as_warn (_("translating to `%s %%%s,%%%s'"), i.tm.name,
1945                              i.op[1].regs->reg_name,
1946                              i.op[0].regs->reg_name);
1947                   }
1948                 else
1949                   {
1950                     /* extraneous `l' suffix on fp insn */
1951                     as_warn (_("translating to `%s %%%s'"), i.tm.name,
1952                              i.op[0].regs->reg_name);
1953                   }
1954               }
1955           }
1956         else if (i.tm.opcode_modifier & Modrm)
1957           {
1958             /* The opcode is completed (modulo i.tm.extension_opcode which
1959                must be put into the modrm byte).
1960                Now, we make the modrm & index base bytes based on all the
1961                info we've collected. */
1962
1963             /* i.reg_operands MUST be the number of real register operands;
1964                implicit registers do not count. */
1965             if (i.reg_operands == 2)
1966               {
1967                 unsigned int source, dest;
1968                 source = ((i.types[0]
1969                            & (Reg | RegMMX | RegXMM
1970                               | SReg2 | SReg3
1971                               | Control | Debug | Test))
1972                           ? 0 : 1);
1973                 dest = source + 1;
1974
1975                 i.rm.mode = 3;
1976                 /* One of the register operands will be encoded in the
1977                    i.tm.reg field, the other in the combined i.tm.mode
1978                    and i.tm.regmem fields.  If no form of this
1979                    instruction supports a memory destination operand,
1980                    then we assume the source operand may sometimes be
1981                    a memory operand and so we need to store the
1982                    destination in the i.rm.reg field.  */
1983                 if ((i.tm.operand_types[dest] & AnyMem) == 0)
1984                   {
1985                     i.rm.reg = i.op[dest].regs->reg_num;
1986                     i.rm.regmem = i.op[source].regs->reg_num;
1987                   }
1988                 else
1989                   {
1990                     i.rm.reg = i.op[source].regs->reg_num;
1991                     i.rm.regmem = i.op[dest].regs->reg_num;
1992                   }
1993               }
1994             else
1995               {                 /* if it's not 2 reg operands... */
1996                 if (i.mem_operands)
1997                   {
1998                     unsigned int fake_zero_displacement = 0;
1999                     unsigned int op = ((i.types[0] & AnyMem)
2000                                        ? 0
2001                                        : (i.types[1] & AnyMem) ? 1 : 2);
2002
2003                     default_seg = &ds;
2004
2005                     if (! i.base_reg)
2006                       {
2007                         i.rm.mode = 0;
2008                         if (! i.disp_operands)
2009                           fake_zero_displacement = 1;
2010                         if (! i.index_reg)
2011                           {
2012                             /* Operand is just <disp> */
2013                             if (flag_16bit_code ^ (i.prefix[ADDR_PREFIX] != 0))
2014                               {
2015                                 i.rm.regmem = NO_BASE_REGISTER_16;
2016                                 i.types[op] &= ~Disp;
2017                                 i.types[op] |= Disp16;
2018                               }
2019                             else
2020                               {
2021                                 i.rm.regmem = NO_BASE_REGISTER;
2022                                 i.types[op] &= ~Disp;
2023                                 i.types[op] |= Disp32;
2024                               }
2025                           }
2026                         else /* ! i.base_reg && i.index_reg */
2027                           {
2028                             i.sib.index = i.index_reg->reg_num;
2029                             i.sib.base = NO_BASE_REGISTER;
2030                             i.sib.scale = i.log2_scale_factor;
2031                             i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
2032                             i.types[op] &= ~Disp;
2033                             i.types[op] |= Disp32;      /* Must be 32 bit */
2034                           }
2035                       }
2036                     else if (i.base_reg->reg_type & Reg16)
2037                       {
2038                         switch (i.base_reg->reg_num)
2039                           {
2040                           case 3: /* (%bx) */
2041                             if (! i.index_reg)
2042                               i.rm.regmem = 7;
2043                             else /* (%bx,%si) -> 0, or (%bx,%di) -> 1 */
2044                               i.rm.regmem = i.index_reg->reg_num - 6;
2045                             break;
2046                           case 5: /* (%bp) */
2047                             default_seg = &ss;
2048                             if (! i.index_reg)
2049                               {
2050                                 i.rm.regmem = 6;
2051                                 if ((i.types[op] & Disp) == 0)
2052                                   {
2053                                     /* fake (%bp) into 0(%bp) */
2054                                     i.types[op] |= Disp8;
2055                                     fake_zero_displacement = 1;
2056                                   }
2057                               }
2058                             else /* (%bp,%si) -> 2, or (%bp,%di) -> 3 */
2059                               i.rm.regmem = i.index_reg->reg_num - 6 + 2;
2060                             break;
2061                           default: /* (%si) -> 4 or (%di) -> 5 */
2062                             i.rm.regmem = i.base_reg->reg_num - 6 + 4;
2063                           }
2064                         i.rm.mode = mode_from_disp_size (i.types[op]);
2065                       }
2066                     else /* i.base_reg and 32 bit mode */
2067                       {
2068                         i.rm.regmem = i.base_reg->reg_num;
2069                         i.sib.base = i.base_reg->reg_num;
2070                         if (i.base_reg->reg_num == EBP_REG_NUM)
2071                           {
2072                             default_seg = &ss;
2073                             if (i.disp_operands == 0)
2074                               {
2075                                 fake_zero_displacement = 1;
2076                                 i.types[op] |= Disp8;
2077                               }
2078                           }
2079                         else if (i.base_reg->reg_num == ESP_REG_NUM)
2080                           {
2081                             default_seg = &ss;
2082                           }
2083                         i.sib.scale = i.log2_scale_factor;
2084                         if (! i.index_reg)
2085                           {
2086                             /* <disp>(%esp) becomes two byte modrm
2087                                with no index register.  We've already
2088                                stored the code for esp in i.rm.regmem
2089                                ie. ESCAPE_TO_TWO_BYTE_ADDRESSING.  Any
2090                                base register besides %esp will not use
2091                                the extra modrm byte.  */
2092                             i.sib.index = NO_INDEX_REGISTER;
2093 #if ! SCALE1_WHEN_NO_INDEX
2094                             /* Another case where we force the second
2095                                modrm byte.  */
2096                             if (i.log2_scale_factor)
2097                               i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
2098 #endif
2099                           }
2100                         else
2101                           {
2102                             i.sib.index = i.index_reg->reg_num;
2103                             i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
2104                           }
2105                         i.rm.mode = mode_from_disp_size (i.types[op]);
2106                       }
2107
2108                     if (fake_zero_displacement)
2109                       {
2110                         /* Fakes a zero displacement assuming that i.types[op]
2111                            holds the correct displacement size. */
2112                         expressionS *exp;
2113
2114                         assert (i.op[op].disps == 0);
2115                         exp = &disp_expressions[i.disp_operands++];
2116                         i.op[op].disps = exp;
2117                         exp->X_op = O_constant;
2118                         exp->X_add_number = 0;
2119                         exp->X_add_symbol = (symbolS *) 0;
2120                         exp->X_op_symbol = (symbolS *) 0;
2121                       }
2122                   }
2123
2124                 /* Fill in i.rm.reg or i.rm.regmem field with register
2125                    operand (if any) based on i.tm.extension_opcode.
2126                    Again, we must be careful to make sure that
2127                    segment/control/debug/test/MMX registers are coded
2128                    into the i.rm.reg field. */
2129                 if (i.reg_operands)
2130                   {
2131                     unsigned int op =
2132                       ((i.types[0]
2133                         & (Reg | RegMMX | RegXMM
2134                            | SReg2 | SReg3
2135                            | Control | Debug | Test))
2136                        ? 0
2137                        : ((i.types[1]
2138                            & (Reg | RegMMX | RegXMM
2139                               | SReg2 | SReg3
2140                               | Control | Debug | Test))
2141                           ? 1
2142                           : 2));
2143                     /* If there is an extension opcode to put here, the
2144                        register number must be put into the regmem field. */
2145                     if (i.tm.extension_opcode != None)
2146                       i.rm.regmem = i.op[op].regs->reg_num;
2147                     else
2148                       i.rm.reg = i.op[op].regs->reg_num;
2149
2150                     /* Now, if no memory operand has set i.rm.mode = 0, 1, 2
2151                        we must set it to 3 to indicate this is a register
2152                        operand in the regmem field.  */
2153                     if (!i.mem_operands)
2154                       i.rm.mode = 3;
2155                   }
2156
2157                 /* Fill in i.rm.reg field with extension opcode (if any). */
2158                 if (i.tm.extension_opcode != None)
2159                   i.rm.reg = i.tm.extension_opcode;
2160               }
2161           }
2162         else if (i.tm.opcode_modifier & (Seg2ShortForm | Seg3ShortForm))
2163           {
2164             if (i.tm.base_opcode == POP_SEG_SHORT && i.op[0].regs->reg_num == 1)
2165               {
2166                 as_bad (_("you can't `pop %%cs'"));
2167                 return;
2168               }
2169             i.tm.base_opcode |= (i.op[0].regs->reg_num << 3);
2170           }
2171         else if ((i.tm.base_opcode & ~(D|W)) == MOV_AX_DISP32)
2172           {
2173             default_seg = &ds;
2174           }
2175         else if ((i.tm.opcode_modifier & IsString) != 0)
2176           {
2177             /* For the string instructions that allow a segment override
2178                on one of their operands, the default segment is ds.  */
2179             default_seg = &ds;
2180           }
2181
2182         /* If a segment was explicitly specified,
2183            and the specified segment is not the default,
2184            use an opcode prefix to select it.
2185            If we never figured out what the default segment is,
2186            then default_seg will be zero at this point,
2187            and the specified segment prefix will always be used.  */
2188         if ((i.seg[0]) && (i.seg[0] != default_seg))
2189           {
2190             if (! add_prefix (i.seg[0]->seg_prefix))
2191               return;
2192           }
2193       }
2194     else if ((i.tm.opcode_modifier & Ugh) != 0)
2195       {
2196         /* UnixWare fsub no args is alias for fsubp, fadd -> faddp, etc.  */
2197         as_warn (_("translating to `%sp'"), i.tm.name);
2198       }
2199   }
2200
2201   /* Handle conversion of 'int $3' --> special int3 insn. */
2202   if (i.tm.base_opcode == INT_OPCODE && i.op[0].imms->X_add_number == 3)
2203     {
2204       i.tm.base_opcode = INT3_OPCODE;
2205       i.imm_operands = 0;
2206     }
2207
2208   if ((i.tm.opcode_modifier & (Jump | JumpByte | JumpDword))
2209       && i.op[0].disps->X_op == O_constant)
2210     {
2211       /* Convert "jmp constant" (and "call constant") to a jump (call) to
2212          the absolute address given by the constant.  Since ix86 jumps and
2213          calls are pc relative, we need to generate a reloc.  */
2214       i.op[0].disps->X_add_symbol = &abs_symbol;
2215       i.op[0].disps->X_op = O_symbol;
2216     }
2217
2218   /* We are ready to output the insn. */
2219   {
2220     register char *p;
2221
2222     /* Output jumps. */
2223     if (i.tm.opcode_modifier & Jump)
2224       {
2225         int size;
2226         int code16;
2227         int prefix;
2228
2229         code16 = 0;
2230         if (flag_16bit_code)
2231           code16 = CODE16;
2232
2233         prefix = 0;
2234         if (i.prefix[DATA_PREFIX])
2235           {
2236             prefix = 1;
2237             i.prefixes -= 1;
2238             code16 ^= CODE16;
2239           }
2240
2241         size = 4;
2242         if (code16)
2243           size = 2;
2244
2245         if (i.prefixes != 0 && !intel_syntax)
2246           as_warn (_("skipping prefixes on this instruction"));
2247
2248         /* It's always a symbol;  End frag & setup for relax.
2249            Make sure there is enough room in this frag for the largest
2250            instruction we may generate in md_convert_frag.  This is 2
2251            bytes for the opcode and room for the prefix and largest
2252            displacement.  */
2253         frag_grow (prefix + 2 + size);
2254         insn_size += prefix + 1;
2255         /* Prefix and 1 opcode byte go in fr_fix.  */
2256         p = frag_more (prefix + 1);
2257         if (prefix)
2258           *p++ = DATA_PREFIX_OPCODE;
2259         *p = i.tm.base_opcode;
2260         /* 1 possible extra opcode + displacement go in fr_var.  */
2261         frag_var (rs_machine_dependent,
2262                   1 + size,
2263                   1,
2264                   ((unsigned char) *p == JUMP_PC_RELATIVE
2265                    ? ENCODE_RELAX_STATE (UNCOND_JUMP, SMALL) | code16
2266                    : ENCODE_RELAX_STATE (COND_JUMP, SMALL) | code16),
2267                   i.op[0].disps->X_add_symbol,
2268                   i.op[0].disps->X_add_number,
2269                   p);
2270       }
2271     else if (i.tm.opcode_modifier & (JumpByte | JumpDword))
2272       {
2273         int size;
2274
2275         if (i.tm.opcode_modifier & JumpByte)
2276           {
2277             /* This is a loop or jecxz type instruction.  */
2278             size = 1;
2279             if (i.prefix[ADDR_PREFIX])
2280               {
2281                 insn_size += 1;
2282                 FRAG_APPEND_1_CHAR (ADDR_PREFIX_OPCODE);
2283                 i.prefixes -= 1;
2284               }
2285           }
2286         else
2287           {
2288             int code16;
2289
2290             code16 = 0;
2291             if (flag_16bit_code)
2292               code16 = CODE16;
2293
2294             if (i.prefix[DATA_PREFIX])
2295               {
2296                 insn_size += 1;
2297                 FRAG_APPEND_1_CHAR (DATA_PREFIX_OPCODE);
2298                 i.prefixes -= 1;
2299                 code16 ^= CODE16;
2300               }
2301
2302             size = 4;
2303             if (code16)
2304               size = 2;
2305           }
2306
2307         if (i.prefixes != 0 && !intel_syntax)
2308           as_warn (_("skipping prefixes on this instruction"));
2309
2310         if (fits_in_unsigned_byte (i.tm.base_opcode))
2311           {
2312             insn_size += 1 + size;
2313             p = frag_more (1 + size);
2314           }
2315         else
2316           {
2317             /* opcode can be at most two bytes */
2318             insn_size += 2 + size;
2319             p = frag_more (2 + size);
2320             *p++ = (i.tm.base_opcode >> 8) & 0xff;
2321           }
2322         *p++ = i.tm.base_opcode & 0xff;
2323
2324         fix_new_exp (frag_now, p - frag_now->fr_literal, size,
2325                      i.op[0].disps, 1, reloc (size, 1, i.disp_reloc[0]));
2326       }
2327     else if (i.tm.opcode_modifier & JumpInterSegment)
2328       {
2329         int size;
2330         int prefix;
2331         int code16;
2332
2333         code16 = 0;
2334         if (flag_16bit_code)
2335           code16 = CODE16;
2336
2337         prefix = 0;
2338         if (i.prefix[DATA_PREFIX])
2339           {
2340             prefix = 1;
2341             i.prefixes -= 1;
2342             code16 ^= CODE16;
2343           }
2344
2345         size = 4;
2346         if (code16)
2347           size = 2;
2348
2349         if (i.prefixes != 0 && !intel_syntax)
2350           as_warn (_("skipping prefixes on this instruction"));
2351
2352         insn_size += prefix + 1 + 2 + size;  /* 1 opcode; 2 segment; offset */
2353         p = frag_more (prefix + 1 + 2 + size);
2354         if (prefix)
2355           *p++ = DATA_PREFIX_OPCODE;
2356         *p++ = i.tm.base_opcode;
2357         if (i.op[1].imms->X_op == O_constant)
2358           {
2359             offsetT n = i.op[1].imms->X_add_number;
2360
2361             if (size == 2
2362                 && !fits_in_unsigned_word (n)
2363                 && !fits_in_signed_word (n))
2364               {
2365                 as_bad (_("16-bit jump out of range"));
2366                 return;
2367               }
2368             md_number_to_chars (p, n, size);
2369           }
2370         else
2371           fix_new_exp (frag_now, p - frag_now->fr_literal, size,
2372                        i.op[1].imms, 0, reloc (size, 0, i.disp_reloc[0]));
2373         if (i.op[0].imms->X_op != O_constant)
2374           as_bad (_("can't handle non absolute segment in `%s'"),
2375                   i.tm.name);
2376         md_number_to_chars (p + size, (valueT) i.op[0].imms->X_add_number, 2);
2377       }
2378     else
2379       {
2380         /* Output normal instructions here. */
2381         unsigned char *q;
2382
2383         /* The prefix bytes. */
2384         for (q = i.prefix;
2385              q < i.prefix + sizeof (i.prefix) / sizeof (i.prefix[0]);
2386              q++)
2387           {
2388             if (*q)
2389               {
2390                 insn_size += 1;
2391                 p = frag_more (1);
2392                 md_number_to_chars (p, (valueT) *q, 1);
2393               }
2394           }
2395
2396         /* Now the opcode; be careful about word order here! */
2397         if (fits_in_unsigned_byte (i.tm.base_opcode))
2398           {
2399             insn_size += 1;
2400             FRAG_APPEND_1_CHAR (i.tm.base_opcode);
2401           }
2402         else if (fits_in_unsigned_word (i.tm.base_opcode))
2403           {
2404             insn_size += 2;
2405             p = frag_more (2);
2406             /* put out high byte first: can't use md_number_to_chars! */
2407             *p++ = (i.tm.base_opcode >> 8) & 0xff;
2408             *p = i.tm.base_opcode & 0xff;
2409           }
2410         else
2411           {                     /* opcode is either 3 or 4 bytes */
2412             if (i.tm.base_opcode & 0xff000000)
2413               {
2414                 insn_size += 4;
2415                 p = frag_more (4);
2416                 *p++ = (i.tm.base_opcode >> 24) & 0xff;
2417               }
2418             else
2419               {
2420                 insn_size += 3;
2421                 p = frag_more (3);
2422               }
2423             *p++ = (i.tm.base_opcode >> 16) & 0xff;
2424             *p++ = (i.tm.base_opcode >> 8) & 0xff;
2425             *p = (i.tm.base_opcode) & 0xff;
2426           }
2427
2428         /* Now the modrm byte and sib byte (if present).  */
2429         if (i.tm.opcode_modifier & Modrm)
2430           {
2431             insn_size += 1;
2432             p = frag_more (1);
2433             md_number_to_chars (p,
2434                                 (valueT) (i.rm.regmem << 0
2435                                           | i.rm.reg << 3
2436                                           | i.rm.mode << 6),
2437                                 1);
2438             /* If i.rm.regmem == ESP (4)
2439                && i.rm.mode != (Register mode)
2440                && not 16 bit
2441                ==> need second modrm byte.  */
2442             if (i.rm.regmem == ESCAPE_TO_TWO_BYTE_ADDRESSING
2443                 && i.rm.mode != 3
2444                 && !(i.base_reg && (i.base_reg->reg_type & Reg16) != 0))
2445               {
2446                 insn_size += 1;
2447                 p = frag_more (1);
2448                 md_number_to_chars (p,
2449                                     (valueT) (i.sib.base << 0
2450                                               | i.sib.index << 3
2451                                               | i.sib.scale << 6),
2452                                     1);
2453               }
2454           }
2455
2456         if (i.disp_operands)
2457           {
2458             register unsigned int n;
2459
2460             for (n = 0; n < i.operands; n++)
2461               {
2462                 if (i.types[n] & Disp)
2463                   {
2464                     if (i.op[n].disps->X_op == O_constant)
2465                       {
2466                         int size;
2467                         offsetT val;
2468
2469                         size = 4;
2470                         if (i.types[n] & (Disp8 | Disp16))
2471                           {
2472                             size = 2;
2473                             if (i.types[n] & Disp8)
2474                               size = 1;
2475                           }
2476                         val = offset_in_range (i.op[n].disps->X_add_number,
2477                                                size);
2478                         insn_size += size;
2479                         p = frag_more (size);
2480                         md_number_to_chars (p, val, size);
2481                       }
2482                     else
2483                       {
2484                         int size = 4;
2485
2486                         if (i.types[n] & Disp16)
2487                           size = 2;
2488
2489                         insn_size += size;
2490                         p = frag_more (size);
2491                         fix_new_exp (frag_now, p - frag_now->fr_literal, size,
2492                                      i.op[n].disps, 0,
2493                                      reloc (size, 0, i.disp_reloc[n]));
2494                       }
2495                   }
2496               }
2497           }                     /* end displacement output */
2498
2499         /* output immediate */
2500         if (i.imm_operands)
2501           {
2502             register unsigned int n;
2503
2504             for (n = 0; n < i.operands; n++)
2505               {
2506                 if (i.types[n] & Imm)
2507                   {
2508                     if (i.op[n].imms->X_op == O_constant)
2509                       {
2510                         int size;
2511                         offsetT val;
2512
2513                         size = 4;
2514                         if (i.types[n] & (Imm8 | Imm8S | Imm16))
2515                           {
2516                             size = 2;
2517                             if (i.types[n] & (Imm8 | Imm8S))
2518                               size = 1;
2519                           }
2520                         val = offset_in_range (i.op[n].imms->X_add_number,
2521                                                size);
2522                         insn_size += size;
2523                         p = frag_more (size);
2524                         md_number_to_chars (p, val, size);
2525                       }
2526                     else
2527                       {         /* not absolute_section */
2528                         /* Need a 32-bit fixup (don't support 8bit
2529                            non-absolute imms).  Try to support other
2530                            sizes ... */
2531 #ifdef BFD_ASSEMBLER
2532                         enum bfd_reloc_code_real reloc_type;
2533 #else
2534                         int reloc_type;
2535 #endif
2536                         int size = 4;
2537
2538                         if (i.types[n] & Imm16)
2539                           size = 2;
2540                         else if (i.types[n] & (Imm8 | Imm8S))
2541                           size = 1;
2542
2543                         insn_size += size;
2544                         p = frag_more (size);
2545                         reloc_type = reloc (size, 0, i.disp_reloc[0]);
2546 #ifdef BFD_ASSEMBLER
2547                         if (reloc_type == BFD_RELOC_32
2548                             && GOT_symbol
2549                             && GOT_symbol == i.op[n].imms->X_add_symbol
2550                             && (i.op[n].imms->X_op == O_symbol
2551                                 || (i.op[n].imms->X_op == O_add
2552                                     && ((symbol_get_value_expression
2553                                          (i.op[n].imms->X_op_symbol)->X_op)
2554                                         == O_subtract))))
2555                           {
2556                             reloc_type = BFD_RELOC_386_GOTPC;
2557                             i.op[n].imms->X_add_number += 3;
2558                           }
2559 #endif
2560                         fix_new_exp (frag_now, p - frag_now->fr_literal, size,
2561                                      i.op[n].imms, 0, reloc_type);
2562                       }
2563                   }
2564               }
2565           }                     /* end immediate output */
2566       }
2567
2568 #ifdef DEBUG386
2569     if (flag_debug)
2570       {
2571         pi (line, &i);
2572       }
2573 #endif /* DEBUG386 */
2574   }
2575 }
2576 \f
2577 static int i386_immediate PARAMS ((char *));
2578
2579 static int
2580 i386_immediate (imm_start)
2581      char *imm_start;
2582 {
2583   char *save_input_line_pointer;
2584   segT exp_seg = 0;
2585   expressionS * exp;
2586
2587   if (i.imm_operands == MAX_IMMEDIATE_OPERANDS)
2588     {
2589       as_bad (_("only 1 or 2 immediate operands are allowed"));
2590       return 0;
2591     }
2592
2593   exp = &im_expressions[i.imm_operands++];
2594   i.op[this_operand].imms = exp;
2595
2596   if (is_space_char (*imm_start))
2597     ++imm_start;
2598
2599   save_input_line_pointer = input_line_pointer;
2600   input_line_pointer = imm_start;
2601
2602 #ifndef LEX_AT
2603   {
2604     /*
2605      * We can have operands of the form
2606      *   <symbol>@GOTOFF+<nnn>
2607      * Take the easy way out here and copy everything
2608      * into a temporary buffer...
2609      */
2610     register char *cp;
2611
2612     cp = strchr (input_line_pointer, '@');
2613     if (cp != NULL)
2614       {
2615         char *tmpbuf;
2616         int len = 0;
2617         int first;
2618
2619         /* GOT relocations are not supported in 16 bit mode */
2620         if (flag_16bit_code)
2621           as_bad (_("GOT relocations not supported in 16 bit mode"));
2622
2623         if (GOT_symbol == NULL)
2624           GOT_symbol = symbol_find_or_make (GLOBAL_OFFSET_TABLE_NAME);
2625
2626         if (strncmp (cp + 1, "PLT", 3) == 0)
2627           {
2628             i.disp_reloc[this_operand] = BFD_RELOC_386_PLT32;
2629             len = 3;
2630           }
2631         else if (strncmp (cp + 1, "GOTOFF", 6) == 0)
2632           {
2633             i.disp_reloc[this_operand] = BFD_RELOC_386_GOTOFF;
2634             len = 6;
2635           }
2636         else if (strncmp (cp + 1, "GOT", 3) == 0)
2637           {
2638             i.disp_reloc[this_operand] = BFD_RELOC_386_GOT32;
2639             len = 3;
2640           }
2641         else
2642           as_bad (_("bad reloc specifier in expression"));
2643
2644         /* Replace the relocation token with ' ', so that errors like
2645            foo@GOTOFF1 will be detected.  */
2646         first = cp - input_line_pointer;
2647         tmpbuf = (char *) alloca (strlen(input_line_pointer));
2648         memcpy (tmpbuf, input_line_pointer, first);
2649         tmpbuf[first] = ' ';
2650         strcpy (tmpbuf + first + 1, cp + 1 + len);
2651         input_line_pointer = tmpbuf;
2652       }
2653   }
2654 #endif
2655
2656   exp_seg = expression (exp);
2657
2658   SKIP_WHITESPACE ();
2659   if (*input_line_pointer)
2660     as_bad (_("ignoring junk `%s' after expression"), input_line_pointer);
2661
2662   input_line_pointer = save_input_line_pointer;
2663
2664   if (exp->X_op == O_absent || exp->X_op == O_big)
2665     {
2666       /* missing or bad expr becomes absolute 0 */
2667       as_bad (_("missing or invalid immediate expression `%s' taken as 0"),
2668               imm_start);
2669       exp->X_op = O_constant;
2670       exp->X_add_number = 0;
2671       exp->X_add_symbol = (symbolS *) 0;
2672       exp->X_op_symbol = (symbolS *) 0;
2673     }
2674
2675   if (exp->X_op == O_constant)
2676     {
2677       i.types[this_operand] |= Imm32;   /* Size it properly later.  */
2678     }
2679 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
2680   else if (
2681 #ifdef BFD_ASSEMBLER
2682            OUTPUT_FLAVOR == bfd_target_aout_flavour &&
2683 #endif
2684            exp_seg != text_section
2685            && exp_seg != data_section
2686            && exp_seg != bss_section
2687            && exp_seg != undefined_section
2688 #ifdef BFD_ASSEMBLER
2689            && !bfd_is_com_section (exp_seg)
2690 #endif
2691            )
2692     {
2693 #ifdef BFD_ASSEMBLER
2694       as_bad (_("unimplemented segment %s in operand"), exp_seg->name);
2695 #else
2696       as_bad (_("unimplemented segment type %d in operand"), exp_seg);
2697 #endif
2698       return 0;
2699     }
2700 #endif
2701   else
2702     {
2703       /* This is an address.  The size of the address will be
2704          determined later, depending on destination register,
2705          suffix, or the default for the section.  We exclude
2706          Imm8S here so that `push $foo' and other instructions
2707          with an Imm8S form will use Imm16 or Imm32.  */
2708       i.types[this_operand] |= (Imm8 | Imm16 | Imm32);
2709     }
2710
2711   return 1;
2712 }
2713
2714 static int i386_scale PARAMS ((char *));
2715
2716 static int
2717 i386_scale (scale)
2718      char *scale;
2719 {
2720   if (!isdigit (*scale))
2721     goto bad_scale;
2722
2723   switch (*scale)
2724     {
2725     case '0':
2726     case '1':
2727       i.log2_scale_factor = 0;
2728       break;
2729     case '2':
2730       i.log2_scale_factor = 1;
2731       break;
2732     case '4':
2733       i.log2_scale_factor = 2;
2734       break;
2735     case '8':
2736       i.log2_scale_factor = 3;
2737       break;
2738     default:
2739     bad_scale:
2740       as_bad (_("expecting scale factor of 1, 2, 4, or 8: got `%s'"),
2741               scale);
2742       return 0;
2743     }
2744   if (i.log2_scale_factor != 0 && ! i.index_reg)
2745     {
2746       as_warn (_("scale factor of %d without an index register"),
2747                1 << i.log2_scale_factor);
2748 #if SCALE1_WHEN_NO_INDEX
2749       i.log2_scale_factor = 0;
2750 #endif
2751     }
2752   return 1;
2753 }
2754
2755 static int i386_displacement PARAMS ((char *, char *));
2756
2757 static int
2758 i386_displacement (disp_start, disp_end)
2759      char *disp_start;
2760      char *disp_end;
2761 {
2762   register expressionS *exp;
2763   segT exp_seg = 0;
2764   char *save_input_line_pointer;
2765   int bigdisp = Disp32;
2766
2767   if (flag_16bit_code ^ (i.prefix[ADDR_PREFIX] != 0))
2768     bigdisp = Disp16;
2769   i.types[this_operand] |= bigdisp;
2770
2771   exp = &disp_expressions[i.disp_operands];
2772   i.op[this_operand].disps = exp;
2773   i.disp_operands++;
2774   save_input_line_pointer = input_line_pointer;
2775   input_line_pointer = disp_start;
2776   END_STRING_AND_SAVE (disp_end);
2777
2778 #ifndef GCC_ASM_O_HACK
2779 #define GCC_ASM_O_HACK 0
2780 #endif
2781 #if GCC_ASM_O_HACK
2782   END_STRING_AND_SAVE (disp_end + 1);
2783   if ((i.types[this_operand] & BaseIndex) != 0
2784       && displacement_string_end[-1] == '+')
2785     {
2786       /* This hack is to avoid a warning when using the "o"
2787          constraint within gcc asm statements.
2788          For instance:
2789
2790          #define _set_tssldt_desc(n,addr,limit,type) \
2791          __asm__ __volatile__ ( \
2792          "movw %w2,%0\n\t" \
2793          "movw %w1,2+%0\n\t" \
2794          "rorl $16,%1\n\t" \
2795          "movb %b1,4+%0\n\t" \
2796          "movb %4,5+%0\n\t" \
2797          "movb $0,6+%0\n\t" \
2798          "movb %h1,7+%0\n\t" \
2799          "rorl $16,%1" \
2800          : "=o"(*(n)) : "q" (addr), "ri"(limit), "i"(type))
2801
2802          This works great except that the output assembler ends
2803          up looking a bit weird if it turns out that there is
2804          no offset.  You end up producing code that looks like:
2805
2806          #APP
2807          movw $235,(%eax)
2808          movw %dx,2+(%eax)
2809          rorl $16,%edx
2810          movb %dl,4+(%eax)
2811          movb $137,5+(%eax)
2812          movb $0,6+(%eax)
2813          movb %dh,7+(%eax)
2814          rorl $16,%edx
2815          #NO_APP
2816
2817          So here we provide the missing zero.
2818       */
2819
2820       *displacement_string_end = '0';
2821     }
2822 #endif
2823 #ifndef LEX_AT
2824   {
2825     /*
2826      * We can have operands of the form
2827      *   <symbol>@GOTOFF+<nnn>
2828      * Take the easy way out here and copy everything
2829      * into a temporary buffer...
2830      */
2831     register char *cp;
2832
2833     cp = strchr (input_line_pointer, '@');
2834     if (cp != NULL)
2835       {
2836         char *tmpbuf;
2837         int len = 0;
2838         int first;
2839
2840         /* GOT relocations are not supported in 16 bit mode */
2841         if (flag_16bit_code)
2842           as_bad (_("GOT relocations not supported in 16 bit mode"));
2843
2844         if (GOT_symbol == NULL)
2845           GOT_symbol = symbol_find_or_make (GLOBAL_OFFSET_TABLE_NAME);
2846
2847         if (strncmp (cp + 1, "PLT", 3) == 0)
2848           {
2849             i.disp_reloc[this_operand] = BFD_RELOC_386_PLT32;
2850             len = 3;
2851           }
2852         else if (strncmp (cp + 1, "GOTOFF", 6) == 0)
2853           {
2854             i.disp_reloc[this_operand] = BFD_RELOC_386_GOTOFF;
2855             len = 6;
2856           }
2857         else if (strncmp (cp + 1, "GOT", 3) == 0)
2858           {
2859             i.disp_reloc[this_operand] = BFD_RELOC_386_GOT32;
2860             len = 3;
2861           }
2862         else
2863           as_bad (_("bad reloc specifier in expression"));
2864
2865         /* Replace the relocation token with ' ', so that errors like
2866            foo@GOTOFF1 will be detected.  */
2867         first = cp - input_line_pointer;
2868         tmpbuf = (char *) alloca (strlen(input_line_pointer));
2869         memcpy (tmpbuf, input_line_pointer, first);
2870         tmpbuf[first] = ' ';
2871         strcpy (tmpbuf + first + 1, cp + 1 + len);
2872         input_line_pointer = tmpbuf;
2873       }
2874   }
2875 #endif
2876
2877   exp_seg = expression (exp);
2878
2879 #ifdef BFD_ASSEMBLER
2880   /* We do this to make sure that the section symbol is in
2881      the symbol table.  We will ultimately change the relocation
2882      to be relative to the beginning of the section */
2883   if (i.disp_reloc[this_operand] == BFD_RELOC_386_GOTOFF)
2884     {
2885       if (S_IS_LOCAL(exp->X_add_symbol)
2886           && S_GET_SEGMENT (exp->X_add_symbol) != undefined_section)
2887         section_symbol (S_GET_SEGMENT (exp->X_add_symbol));
2888       assert (exp->X_op == O_symbol);
2889       exp->X_op = O_subtract;
2890       exp->X_op_symbol = GOT_symbol;
2891       i.disp_reloc[this_operand] = BFD_RELOC_32;
2892     }
2893 #endif
2894
2895   SKIP_WHITESPACE ();
2896   if (*input_line_pointer)
2897     as_bad (_("ignoring junk `%s' after expression"),
2898             input_line_pointer);
2899 #if GCC_ASM_O_HACK
2900   RESTORE_END_STRING (disp_end + 1);
2901 #endif
2902   RESTORE_END_STRING (disp_end);
2903   input_line_pointer = save_input_line_pointer;
2904
2905   if (exp->X_op == O_absent || exp->X_op == O_big)
2906     {
2907       /* missing or bad expr becomes absolute 0 */
2908       as_bad (_("missing or invalid displacement expression `%s' taken as 0"),
2909               disp_start);
2910       exp->X_op = O_constant;
2911       exp->X_add_number = 0;
2912       exp->X_add_symbol = (symbolS *) 0;
2913       exp->X_op_symbol = (symbolS *) 0;
2914     }
2915
2916   if (exp->X_op == O_constant)
2917     {
2918       if (i.types[this_operand] & Disp16)
2919         {
2920           /* We know this operand is at most 16 bits, so convert to a
2921              signed 16 bit number before trying to see whether it will
2922              fit in an even smaller size.  */
2923           exp->X_add_number =
2924             (((exp->X_add_number & 0xffff) ^ 0x8000) - 0x8000);
2925         }
2926       if (fits_in_signed_byte (exp->X_add_number))
2927         i.types[this_operand] |= Disp8;
2928     }
2929 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
2930   else if (
2931 #ifdef BFD_ASSEMBLER
2932            OUTPUT_FLAVOR == bfd_target_aout_flavour &&
2933 #endif
2934            exp_seg != text_section
2935            && exp_seg != data_section
2936            && exp_seg != bss_section
2937            && exp_seg != undefined_section)
2938     {
2939 #ifdef BFD_ASSEMBLER
2940       as_bad (_("unimplemented segment %s in operand"), exp_seg->name);
2941 #else
2942       as_bad (_("unimplemented segment type %d in operand"), exp_seg);
2943 #endif
2944       return 0;
2945     }
2946 #endif
2947   return 1;
2948 }
2949
2950 static int i386_operand_modifier PARAMS ((char **, int));
2951
2952 static int
2953 i386_operand_modifier (op_string, got_a_float)
2954      char **op_string;
2955      int got_a_float;
2956 {
2957   if (!strncasecmp (*op_string, "BYTE PTR", 8))
2958     {
2959       i.suffix = BYTE_MNEM_SUFFIX;
2960       *op_string += 8;
2961       return BYTE_PTR;
2962
2963     }
2964   else if (!strncasecmp (*op_string, "WORD PTR", 8))
2965     {
2966       if (got_a_float == 2)     /* "fi..." */
2967         i.suffix = SHORT_MNEM_SUFFIX;
2968       else
2969         i.suffix = WORD_MNEM_SUFFIX;
2970       *op_string += 8;
2971       return WORD_PTR;
2972     }
2973
2974   else if (!strncasecmp (*op_string, "DWORD PTR", 9))
2975     {
2976       if (got_a_float == 1)     /* "f..." */
2977         i.suffix = SHORT_MNEM_SUFFIX;
2978       else
2979         i.suffix = LONG_MNEM_SUFFIX;
2980       *op_string += 9;
2981       return DWORD_PTR;
2982     }
2983
2984   else if (!strncasecmp (*op_string, "QWORD PTR", 9))
2985     {
2986       i.suffix = DWORD_MNEM_SUFFIX;
2987       *op_string += 9;
2988       return QWORD_PTR;
2989     }
2990
2991   else if (!strncasecmp (*op_string, "XWORD PTR", 9))
2992     {
2993       i.suffix = LONG_DOUBLE_MNEM_SUFFIX;
2994       *op_string += 9;
2995       return XWORD_PTR;
2996     }
2997
2998   else if (!strncasecmp (*op_string, "SHORT", 5))
2999     {
3000       *op_string += 5;
3001       return SHORT;
3002     }
3003
3004   else if (!strncasecmp (*op_string, "OFFSET FLAT:", 12))
3005     {
3006       *op_string += 12;
3007       return OFFSET_FLAT;
3008     }
3009
3010   else if (!strncasecmp (*op_string, "FLAT", 4))
3011     {
3012       *op_string += 4;
3013       return FLAT;
3014     }
3015
3016   else return NONE_FOUND;
3017 }
3018
3019 static char * build_displacement_string PARAMS ((int, char *));
3020
3021 static char *
3022 build_displacement_string (initial_disp, op_string)
3023      int initial_disp;
3024      char *op_string;
3025 {
3026   char *temp_string = (char *) malloc (strlen (op_string) + 1);
3027   char *end_of_operand_string;
3028   char *tc;
3029   char *temp_disp;
3030
3031   temp_string[0] = '\0';
3032   tc = end_of_operand_string = strchr (op_string, '[');
3033   if (initial_disp && !end_of_operand_string)
3034     {
3035       strcpy (temp_string, op_string);
3036       return temp_string;
3037     }
3038
3039   /* Build the whole displacement string */
3040   if (initial_disp)
3041     {
3042       strncpy (temp_string, op_string, end_of_operand_string - op_string);
3043       temp_string[end_of_operand_string - op_string] = '\0';
3044       temp_disp = tc;
3045     }
3046   else
3047     temp_disp = op_string;
3048
3049   while (*temp_disp != '\0')
3050     {
3051       char *end_op;
3052       int add_minus = (*temp_disp == '-');
3053
3054       if (*temp_disp == '+' || *temp_disp == '-' || *temp_disp == '[')
3055         temp_disp++;
3056
3057       if (is_space_char (*temp_disp))
3058         temp_disp++;
3059
3060       /* Don't consider registers */
3061       if ( !((*temp_disp == REGISTER_PREFIX || allow_naked_reg)
3062              && parse_register (temp_disp, &end_op)) )
3063         {
3064           char *string_start = temp_disp;
3065
3066           while (*temp_disp != ']'
3067                  && *temp_disp != '+'
3068                  && *temp_disp != '-'
3069                  && *temp_disp != '*')
3070             ++temp_disp;
3071
3072           if (add_minus)
3073             strcat (temp_string, "-");
3074           else
3075             strcat (temp_string, "+");
3076
3077           strncat (temp_string, string_start, temp_disp - string_start);
3078           if (*temp_disp == '+' || *temp_disp == '-')
3079             --temp_disp;
3080         }
3081
3082       while (*temp_disp != '\0'
3083              && *temp_disp != '+'
3084              && *temp_disp != '-')
3085         ++temp_disp;
3086     }
3087
3088   return temp_string;
3089 }
3090
3091 static int i386_parse_seg PARAMS ((char *));
3092
3093 static int
3094 i386_parse_seg (op_string)
3095      char *op_string;
3096 {
3097   if (is_space_char (*op_string))
3098     ++op_string;
3099
3100   /* Should be one of es, cs, ss, ds fs or gs */
3101   switch (*op_string++)
3102     {
3103     case 'e':
3104       i.seg[i.mem_operands] = &es;
3105       break;
3106     case 'c':
3107       i.seg[i.mem_operands] = &cs;
3108       break;
3109     case 's':
3110       i.seg[i.mem_operands] = &ss;
3111       break;
3112     case 'd':
3113       i.seg[i.mem_operands] = &ds;
3114       break;
3115     case 'f':
3116       i.seg[i.mem_operands] = &fs;
3117       break;
3118     case 'g':
3119       i.seg[i.mem_operands] = &gs;
3120       break;
3121     default:
3122       as_bad (_("bad segment name `%s'"), op_string);
3123       return 0;
3124     }
3125
3126   if (*op_string++ != 's')
3127     {
3128       as_bad (_("bad segment name `%s'"), op_string);
3129       return 0;
3130     }
3131
3132   if (is_space_char (*op_string))
3133     ++op_string;
3134
3135   if (*op_string != ':')
3136     {
3137       as_bad (_("bad segment name `%s'"), op_string);
3138       return 0;
3139     }
3140
3141   return 1;
3142
3143 }
3144
3145 static int i386_index_check PARAMS((const char *));
3146
3147 /* Make sure the memory operand we've been dealt is valid.
3148    Returns 1 on success, 0 on a failure.
3149 */
3150 static int
3151 i386_index_check (operand_string)
3152      const char *operand_string;
3153 {
3154 #if INFER_ADDR_PREFIX
3155   int fudged = 0;
3156
3157  tryprefix:
3158 #endif
3159   if (flag_16bit_code ^ (i.prefix[ADDR_PREFIX] != 0)
3160       /* 16 bit mode checks */
3161       ? ((i.base_reg
3162           && ((i.base_reg->reg_type & (Reg16|BaseIndex))
3163               != (Reg16|BaseIndex)))
3164          || (i.index_reg
3165              && (((i.index_reg->reg_type & (Reg16|BaseIndex))
3166                   != (Reg16|BaseIndex))
3167                  || ! (i.base_reg
3168                        && i.base_reg->reg_num < 6
3169                        && i.index_reg->reg_num >= 6
3170                        && i.log2_scale_factor == 0))))
3171       /* 32 bit mode checks */
3172       : ((i.base_reg
3173           && (i.base_reg->reg_type & Reg32) == 0)
3174          || (i.index_reg
3175              && ((i.index_reg->reg_type & (Reg32|BaseIndex))
3176                  != (Reg32|BaseIndex)))))
3177     {
3178 #if INFER_ADDR_PREFIX
3179       if (i.prefix[ADDR_PREFIX] == 0 && stackop_size != '\0')
3180         {
3181           i.prefix[ADDR_PREFIX] = ADDR_PREFIX_OPCODE;
3182           i.prefixes += 1;
3183           /* Change the size of any displacement too.  At most one of
3184              Disp16 or Disp32 is set.
3185              FIXME.  There doesn't seem to be any real need for separate
3186              Disp16 and Disp32 flags.  The same goes for Imm16 and Imm32.
3187              Removing them would probably clean up the code quite a lot.
3188           */
3189           if (i.types[this_operand] & (Disp16|Disp32))
3190              i.types[this_operand] ^= (Disp16|Disp32);
3191           fudged = 1;
3192           goto tryprefix;
3193         }
3194       if (fudged)
3195         as_bad (_("`%s' is not a valid base/index expression"),
3196                 operand_string);
3197       else
3198 #endif
3199         as_bad (_("`%s' is not a valid %s bit base/index expression"),
3200                 operand_string,
3201                 flag_16bit_code ^ (i.prefix[ADDR_PREFIX] != 0) ? "16" : "32");
3202       return 0;
3203     }
3204   return 1;
3205 }
3206
3207 static int i386_intel_memory_operand PARAMS ((char *));
3208
3209 static int
3210 i386_intel_memory_operand (operand_string)
3211      char *operand_string;
3212 {
3213   char *op_string = operand_string;
3214   char *end_of_operand_string;
3215
3216   if ((i.mem_operands == 1
3217        && (current_templates->start->opcode_modifier & IsString) == 0)
3218       || i.mem_operands == 2)
3219     {
3220       as_bad (_("too many memory references for `%s'"),
3221               current_templates->start->name);
3222       return 0;
3223     }
3224
3225   /* First check for a segment override.  */
3226   if (*op_string != '[')
3227     {
3228       char *end_seg;
3229
3230       end_seg = strchr (op_string, ':');
3231       if (end_seg)
3232         {
3233           if (!i386_parse_seg (op_string))
3234             return 0;
3235           op_string = end_seg + 1;
3236         }
3237     }
3238
3239   /* Look for displacement preceding open bracket */
3240   if (*op_string != '[')
3241     {
3242       char *temp_string;
3243
3244       if (i.disp_operands)
3245         return 0;
3246
3247       temp_string = build_displacement_string (true, op_string);
3248
3249       if (!i386_displacement (temp_string, temp_string + strlen (temp_string)))
3250         {
3251           free (temp_string);
3252           return 0;
3253         }
3254       free (temp_string);
3255
3256       end_of_operand_string = strchr (op_string, '[');
3257       if (!end_of_operand_string)
3258         end_of_operand_string = op_string + strlen (op_string);
3259
3260       if (is_space_char (*end_of_operand_string))
3261         --end_of_operand_string;
3262
3263       op_string = end_of_operand_string;
3264     }
3265
3266   if (*op_string == '[')
3267     {
3268       ++op_string;
3269
3270       /* Pick off each component and figure out where it belongs */
3271
3272       end_of_operand_string = op_string;
3273
3274       while (*op_string != ']')
3275         {
3276           const reg_entry *temp_reg;
3277           char *end_op;
3278           char *temp_string;
3279
3280           while (*end_of_operand_string != '+'
3281                  && *end_of_operand_string != '-'
3282                  && *end_of_operand_string != '*'
3283                  && *end_of_operand_string != ']')
3284             end_of_operand_string++;
3285
3286           temp_string = op_string;
3287           if (*temp_string == '+')
3288             {
3289               ++temp_string;
3290               if (is_space_char (*temp_string))
3291                 ++temp_string;
3292             }
3293
3294           if ((*temp_string == REGISTER_PREFIX || allow_naked_reg)
3295               && (temp_reg = parse_register (temp_string, &end_op)) != NULL)
3296             {
3297               if (i.base_reg == NULL)
3298                 i.base_reg = temp_reg;
3299               else
3300                 i.index_reg = temp_reg;
3301
3302               i.types[this_operand] |= BaseIndex;
3303             }
3304           else if (*temp_string == REGISTER_PREFIX)
3305             {
3306               as_bad (_("bad register name `%s'"), temp_string);
3307               return 0;
3308             }
3309           else if (is_digit_char (*op_string)
3310                    || *op_string == '+' || *op_string == '-')
3311             {
3312               char *temp_str;
3313
3314               if (i.disp_operands != 0)
3315                 return 0;
3316
3317               temp_string = build_displacement_string (false, op_string);
3318
3319               temp_str = temp_string;
3320               if (*temp_str == '+')
3321                 ++temp_str;
3322
3323               if (!i386_displacement (temp_str, temp_str + strlen (temp_str)))
3324                 {
3325                   free (temp_string);
3326                   return 0;
3327                 }
3328               free (temp_string);
3329
3330               ++op_string;
3331               end_of_operand_string = op_string;
3332               while (*end_of_operand_string != ']'
3333                      && *end_of_operand_string != '+'
3334                      && *end_of_operand_string != '-'
3335                      && *end_of_operand_string != '*')
3336                 ++end_of_operand_string;
3337             }
3338           else if (*op_string == '*')
3339             {
3340               ++op_string;
3341
3342               if (i.base_reg && !i.index_reg)
3343                 {
3344                   i.index_reg = i.base_reg;
3345                   i.base_reg = 0;
3346                 }
3347
3348               if (!i386_scale (op_string))
3349                 return 0;
3350             }
3351           op_string = end_of_operand_string;
3352           ++end_of_operand_string;
3353         }
3354     }
3355
3356   if (i386_index_check (operand_string) == 0)
3357     return 0;
3358
3359   i.mem_operands++;
3360   return 1;
3361 }
3362
3363 static int
3364 i386_intel_operand (operand_string, got_a_float)
3365      char *operand_string;
3366      int got_a_float;
3367 {
3368   const reg_entry * r;
3369   char *end_op;
3370   char *op_string = operand_string;
3371
3372   int operand_modifier = i386_operand_modifier (&op_string, got_a_float);
3373   if (is_space_char (*op_string))
3374     ++op_string;
3375
3376   switch (operand_modifier)
3377     {
3378     case BYTE_PTR:
3379     case WORD_PTR:
3380     case DWORD_PTR:
3381     case QWORD_PTR:
3382     case XWORD_PTR:
3383       if (!i386_intel_memory_operand (op_string))
3384         return 0;
3385       break;
3386
3387     case FLAT:
3388     case OFFSET_FLAT:
3389       if (!i386_immediate (op_string))
3390         return 0;
3391       break;
3392
3393     case SHORT:
3394     case NONE_FOUND:
3395       /* Should be register or immediate */
3396       if (is_digit_char (*op_string)
3397           && strchr (op_string, '[') == 0)
3398         {
3399           if (!i386_immediate (op_string))
3400             return 0;
3401         }
3402       else if ((*op_string == REGISTER_PREFIX || allow_naked_reg)
3403                && (r = parse_register (op_string, &end_op)) != NULL)
3404         {
3405           /* Check for a segment override by searching for ':' after a
3406              segment register.  */
3407           op_string = end_op;
3408           if (is_space_char (*op_string))
3409             ++op_string;
3410           if (*op_string == ':' && (r->reg_type & (SReg2 | SReg3)))
3411             {
3412               switch (r->reg_num)
3413                 {
3414                 case 0:
3415                   i.seg[i.mem_operands] = &es;
3416                   break;
3417                 case 1:
3418                   i.seg[i.mem_operands] = &cs;
3419                   break;
3420                 case 2:
3421                   i.seg[i.mem_operands] = &ss;
3422                   break;
3423                 case 3:
3424                   i.seg[i.mem_operands] = &ds;
3425                   break;
3426                 case 4:
3427                   i.seg[i.mem_operands] = &fs;
3428                   break;
3429                 case 5:
3430                   i.seg[i.mem_operands] = &gs;
3431                   break;
3432                 }
3433
3434             }
3435           i.types[this_operand] |= r->reg_type & ~BaseIndex;
3436           i.op[this_operand].regs = r;
3437           i.reg_operands++;
3438         }
3439       else if (*op_string == REGISTER_PREFIX)
3440         {
3441           as_bad (_("bad register name `%s'"), op_string);
3442           return 0;
3443         }
3444       else if (!i386_intel_memory_operand (op_string))
3445         return 0;
3446
3447       break;
3448     }  /* end switch */
3449
3450   return 1;
3451 }
3452
3453 /* Parse OPERAND_STRING into the i386_insn structure I.  Returns non-zero
3454    on error. */
3455
3456 static int
3457 i386_operand (operand_string)
3458      char *operand_string;
3459 {
3460   const reg_entry *r;
3461   char *end_op;
3462   char *op_string = operand_string;
3463
3464   if (is_space_char (*op_string))
3465     ++op_string;
3466
3467   /* We check for an absolute prefix (differentiating,
3468      for example, 'jmp pc_relative_label' from 'jmp *absolute_label'. */
3469   if (*op_string == ABSOLUTE_PREFIX)
3470     {
3471       ++op_string;
3472       if (is_space_char (*op_string))
3473         ++op_string;
3474       i.types[this_operand] |= JumpAbsolute;
3475     }
3476
3477   /* Check if operand is a register. */
3478   if ((*op_string == REGISTER_PREFIX || allow_naked_reg)
3479       && (r = parse_register (op_string, &end_op)) != NULL)
3480     {
3481       /* Check for a segment override by searching for ':' after a
3482          segment register.  */
3483       op_string = end_op;
3484       if (is_space_char (*op_string))
3485         ++op_string;
3486       if (*op_string == ':' && (r->reg_type & (SReg2 | SReg3)))
3487         {
3488           switch (r->reg_num)
3489             {
3490             case 0:
3491               i.seg[i.mem_operands] = &es;
3492               break;
3493             case 1:
3494               i.seg[i.mem_operands] = &cs;
3495               break;
3496             case 2:
3497               i.seg[i.mem_operands] = &ss;
3498               break;
3499             case 3:
3500               i.seg[i.mem_operands] = &ds;
3501               break;
3502             case 4:
3503               i.seg[i.mem_operands] = &fs;
3504               break;
3505             case 5:
3506               i.seg[i.mem_operands] = &gs;
3507               break;
3508             }
3509
3510           /* Skip the ':' and whitespace.  */
3511           ++op_string;
3512           if (is_space_char (*op_string))
3513             ++op_string;
3514
3515           if (!is_digit_char (*op_string)
3516               && !is_identifier_char (*op_string)
3517               && *op_string != '('
3518               && *op_string != ABSOLUTE_PREFIX)
3519             {
3520               as_bad (_("bad memory operand `%s'"), op_string);
3521               return 0;
3522             }
3523           /* Handle case of %es:*foo. */
3524           if (*op_string == ABSOLUTE_PREFIX)
3525             {
3526               ++op_string;
3527               if (is_space_char (*op_string))
3528                 ++op_string;
3529               i.types[this_operand] |= JumpAbsolute;
3530             }
3531           goto do_memory_reference;
3532         }
3533       if (*op_string)
3534         {
3535           as_bad (_("junk `%s' after register"), op_string);
3536           return 0;
3537         }
3538       i.types[this_operand] |= r->reg_type & ~BaseIndex;
3539       i.op[this_operand].regs = r;
3540       i.reg_operands++;
3541     }
3542   else if (*op_string == REGISTER_PREFIX)
3543     {
3544       as_bad (_("bad register name `%s'"), op_string);
3545       return 0;
3546     }
3547   else if (*op_string == IMMEDIATE_PREFIX)
3548     {                           /* ... or an immediate */
3549       ++op_string;
3550       if (i.types[this_operand] & JumpAbsolute)
3551         {
3552           as_bad (_("immediate operand illegal with absolute jump"));
3553           return 0;
3554         }
3555       if (!i386_immediate (op_string))
3556         return 0;
3557     }
3558   else if (is_digit_char (*op_string)
3559            || is_identifier_char (*op_string)
3560            || *op_string == '(' )
3561     {
3562       /* This is a memory reference of some sort. */
3563       char *base_string;
3564
3565       /* Start and end of displacement string expression (if found). */
3566       char *displacement_string_start;
3567       char *displacement_string_end;
3568
3569     do_memory_reference:
3570       if ((i.mem_operands == 1
3571            && (current_templates->start->opcode_modifier & IsString) == 0)
3572           || i.mem_operands == 2)
3573         {
3574           as_bad (_("too many memory references for `%s'"),
3575                   current_templates->start->name);
3576           return 0;
3577         }
3578
3579       /* Check for base index form.  We detect the base index form by
3580          looking for an ')' at the end of the operand, searching
3581          for the '(' matching it, and finding a REGISTER_PREFIX or ','
3582          after the '('.  */
3583       base_string = op_string + strlen (op_string);
3584
3585       --base_string;
3586       if (is_space_char (*base_string))
3587         --base_string;
3588
3589       /* If we only have a displacement, set-up for it to be parsed later. */
3590       displacement_string_start = op_string;
3591       displacement_string_end = base_string + 1;
3592
3593       if (*base_string == ')')
3594         {
3595           char *temp_string;
3596           unsigned int parens_balanced = 1;
3597           /* We've already checked that the number of left & right ()'s are
3598              equal, so this loop will not be infinite. */
3599           do
3600             {
3601               base_string--;
3602               if (*base_string == ')')
3603                 parens_balanced++;
3604               if (*base_string == '(')
3605                 parens_balanced--;
3606             }
3607           while (parens_balanced);
3608
3609           temp_string = base_string;
3610
3611           /* Skip past '(' and whitespace.  */
3612           ++base_string;
3613           if (is_space_char (*base_string))
3614             ++base_string;
3615
3616           if (*base_string == ','
3617               || ((*base_string == REGISTER_PREFIX || allow_naked_reg)
3618                   && (i.base_reg = parse_register (base_string, &end_op)) != NULL))
3619             {
3620               displacement_string_end = temp_string;
3621
3622               i.types[this_operand] |= BaseIndex;
3623
3624               if (i.base_reg)
3625                 {
3626                   base_string = end_op;
3627                   if (is_space_char (*base_string))
3628                     ++base_string;
3629                 }
3630
3631               /* There may be an index reg or scale factor here.  */
3632               if (*base_string == ',')
3633                 {
3634                   ++base_string;
3635                   if (is_space_char (*base_string))
3636                     ++base_string;
3637
3638                   if ((*base_string == REGISTER_PREFIX || allow_naked_reg)
3639                       && (i.index_reg = parse_register (base_string, &end_op)) != NULL)
3640                     {
3641                       base_string = end_op;
3642                       if (is_space_char (*base_string))
3643                         ++base_string;
3644                       if (*base_string == ',')
3645                         {
3646                           ++base_string;
3647                           if (is_space_char (*base_string))
3648                             ++base_string;
3649                         }
3650                       else if (*base_string != ')' )
3651                         {
3652                           as_bad (_("expecting `,' or `)' after index register in `%s'"),
3653                                   operand_string);
3654                           return 0;
3655                         }
3656                     }
3657                   else if (*base_string == REGISTER_PREFIX)
3658                     {
3659                       as_bad (_("bad register name `%s'"), base_string);
3660                       return 0;
3661                     }
3662
3663                   /* Check for scale factor. */
3664                   if (isdigit ((unsigned char) *base_string))
3665                     {
3666                       if (!i386_scale (base_string))
3667                         return 0;
3668
3669                       ++base_string;
3670                       if (is_space_char (*base_string))
3671                         ++base_string;
3672                       if (*base_string != ')')
3673                         {
3674                           as_bad (_("expecting `)' after scale factor in `%s'"),
3675                                   operand_string);
3676                           return 0;
3677                         }
3678                     }
3679                   else if (!i.index_reg)
3680                     {
3681                       as_bad (_("expecting index register or scale factor after `,'; got '%c'"),
3682                               *base_string);
3683                       return 0;
3684                     }
3685                 }
3686               else if (*base_string != ')')
3687                 {
3688                   as_bad (_("expecting `,' or `)' after base register in `%s'"),
3689                           operand_string);
3690                   return 0;
3691                 }
3692             }
3693           else if (*base_string == REGISTER_PREFIX)
3694             {
3695               as_bad (_("bad register name `%s'"), base_string);
3696               return 0;
3697             }
3698         }
3699
3700       /* If there's an expression beginning the operand, parse it,
3701          assuming displacement_string_start and
3702          displacement_string_end are meaningful.  */
3703       if (displacement_string_start != displacement_string_end)
3704         {
3705           if (!i386_displacement (displacement_string_start,
3706                                   displacement_string_end))
3707             return 0;
3708         }
3709
3710       /* Special case for (%dx) while doing input/output op.  */
3711       if (i.base_reg
3712           && i.base_reg->reg_type == (Reg16 | InOutPortReg)
3713           && i.index_reg == 0
3714           && i.log2_scale_factor == 0
3715           && i.seg[i.mem_operands] == 0
3716           && (i.types[this_operand] & Disp) == 0)
3717         {
3718           i.types[this_operand] = InOutPortReg;
3719           return 1;
3720         }
3721
3722       if (i386_index_check (operand_string) == 0)
3723         return 0;
3724       i.mem_operands++;
3725     }
3726   else
3727     {                           /* it's not a memory operand; argh! */
3728       as_bad (_("invalid char %s beginning operand %d `%s'"),
3729               output_invalid (*op_string),
3730               this_operand + 1,
3731               op_string);
3732       return 0;
3733     }
3734   return 1;                     /* normal return */
3735 }
3736 \f
3737 /*
3738  * md_estimate_size_before_relax()
3739  *
3740  * Called just before relax().
3741  * Any symbol that is now undefined will not become defined.
3742  * Return the correct fr_subtype in the frag.
3743  * Return the initial "guess for fr_var" to caller.
3744  * The guess for fr_var is ACTUALLY the growth beyond fr_fix.
3745  * Whatever we do to grow fr_fix or fr_var contributes to our returned value.
3746  * Although it may not be explicit in the frag, pretend fr_var starts with a
3747  * 0 value.
3748  */
3749 int
3750 md_estimate_size_before_relax (fragP, segment)
3751      register fragS *fragP;
3752      register segT segment;
3753 {
3754   register unsigned char *opcode;
3755   register int old_fr_fix;
3756
3757   old_fr_fix = fragP->fr_fix;
3758   opcode = (unsigned char *) fragP->fr_opcode;
3759   /* We've already got fragP->fr_subtype right;  all we have to do is
3760      check for un-relaxable symbols.  */
3761   if (S_GET_SEGMENT (fragP->fr_symbol) != segment)
3762     {
3763       /* symbol is undefined in this segment */
3764       int code16 = fragP->fr_subtype & CODE16;
3765       int size = code16 ? 2 : 4;
3766 #ifdef BFD_ASSEMBLER
3767       enum bfd_reloc_code_real reloc_type;
3768 #else
3769       int reloc_type;
3770 #endif
3771
3772       if (GOT_symbol /* Not quite right - we should switch on presence of
3773                         @PLT, but I cannot see how to get to that from
3774                         here.  We should have done this in md_assemble to
3775                         really get it right all of the time, but I think it
3776                         does not matter that much, as this will be right
3777                         most of the time. ERY  */
3778           && S_GET_SEGMENT(fragP->fr_symbol) == undefined_section)
3779         reloc_type = BFD_RELOC_386_PLT32;
3780       else if (code16)
3781         reloc_type = BFD_RELOC_16_PCREL;
3782       else
3783         reloc_type = BFD_RELOC_32_PCREL;
3784
3785       switch (opcode[0])
3786         {
3787         case JUMP_PC_RELATIVE:  /* make jmp (0xeb) a dword displacement jump */
3788           opcode[0] = 0xe9;     /* dword disp jmp */
3789           fragP->fr_fix += size;
3790           fix_new (fragP, old_fr_fix, size,
3791                    fragP->fr_symbol,
3792                    fragP->fr_offset, 1,
3793                    reloc_type);
3794           break;
3795
3796         default:
3797           /* This changes the byte-displacement jump 0x7N
3798              to the dword-displacement jump 0x0f,0x8N.  */
3799           opcode[1] = opcode[0] + 0x10;
3800           opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
3801           fragP->fr_fix += 1 + size;    /* we've added an opcode byte */
3802           fix_new (fragP, old_fr_fix + 1, size,
3803                    fragP->fr_symbol,
3804                    fragP->fr_offset, 1,
3805                    reloc_type);
3806           break;
3807         }
3808       frag_wane (fragP);
3809     }
3810   return (fragP->fr_var + fragP->fr_fix - old_fr_fix);
3811 }                               /* md_estimate_size_before_relax() */
3812 \f
3813 /*
3814  *                      md_convert_frag();
3815  *
3816  * Called after relax() is finished.
3817  * In:  Address of frag.
3818  *      fr_type == rs_machine_dependent.
3819  *      fr_subtype is what the address relaxed to.
3820  *
3821  * Out: Any fixSs and constants are set up.
3822  *      Caller will turn frag into a ".space 0".
3823  */
3824 #ifndef BFD_ASSEMBLER
3825 void
3826 md_convert_frag (headers, sec, fragP)
3827      object_headers *headers ATTRIBUTE_UNUSED;
3828      segT sec ATTRIBUTE_UNUSED;
3829      register fragS *fragP;
3830 #else
3831 void
3832 md_convert_frag (abfd, sec, fragP)
3833      bfd *abfd ATTRIBUTE_UNUSED;
3834      segT sec ATTRIBUTE_UNUSED;
3835      register fragS *fragP;
3836 #endif
3837 {
3838   register unsigned char *opcode;
3839   unsigned char *where_to_put_displacement = NULL;
3840   offsetT target_address;
3841   offsetT opcode_address;
3842   unsigned int extension = 0;
3843   offsetT displacement_from_opcode_start;
3844
3845   opcode = (unsigned char *) fragP->fr_opcode;
3846
3847   /* Address we want to reach in file space. */
3848   target_address = S_GET_VALUE (fragP->fr_symbol) + fragP->fr_offset;
3849 #ifdef BFD_ASSEMBLER /* not needed otherwise? */
3850   target_address += symbol_get_frag (fragP->fr_symbol)->fr_address;
3851 #endif
3852
3853   /* Address opcode resides at in file space. */
3854   opcode_address = fragP->fr_address + fragP->fr_fix;
3855
3856   /* Displacement from opcode start to fill into instruction. */
3857   displacement_from_opcode_start = target_address - opcode_address;
3858
3859   switch (fragP->fr_subtype)
3860     {
3861     case ENCODE_RELAX_STATE (COND_JUMP, SMALL):
3862     case ENCODE_RELAX_STATE (COND_JUMP, SMALL16):
3863     case ENCODE_RELAX_STATE (UNCOND_JUMP, SMALL):
3864     case ENCODE_RELAX_STATE (UNCOND_JUMP, SMALL16):
3865       /* don't have to change opcode */
3866       extension = 1;            /* 1 opcode + 1 displacement */
3867       where_to_put_displacement = &opcode[1];
3868       break;
3869
3870     case ENCODE_RELAX_STATE (COND_JUMP, BIG):
3871       extension = 5;            /* 2 opcode + 4 displacement */
3872       opcode[1] = opcode[0] + 0x10;
3873       opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
3874       where_to_put_displacement = &opcode[2];
3875       break;
3876
3877     case ENCODE_RELAX_STATE (UNCOND_JUMP, BIG):
3878       extension = 4;            /* 1 opcode + 4 displacement */
3879       opcode[0] = 0xe9;
3880       where_to_put_displacement = &opcode[1];
3881       break;
3882
3883     case ENCODE_RELAX_STATE (COND_JUMP, BIG16):
3884       extension = 3;            /* 2 opcode + 2 displacement */
3885       opcode[1] = opcode[0] + 0x10;
3886       opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
3887       where_to_put_displacement = &opcode[2];
3888       break;
3889
3890     case ENCODE_RELAX_STATE (UNCOND_JUMP, BIG16):
3891       extension = 2;            /* 1 opcode + 2 displacement */
3892       opcode[0] = 0xe9;
3893       where_to_put_displacement = &opcode[1];
3894       break;
3895
3896     default:
3897       BAD_CASE (fragP->fr_subtype);
3898       break;
3899     }
3900   /* now put displacement after opcode */
3901   md_number_to_chars ((char *) where_to_put_displacement,
3902                       (valueT) (displacement_from_opcode_start - extension),
3903                       SIZE_FROM_RELAX_STATE (fragP->fr_subtype));
3904   fragP->fr_fix += extension;
3905 }
3906 \f
3907
3908 int md_short_jump_size = 2;     /* size of byte displacement jmp */
3909 int md_long_jump_size = 5;      /* size of dword displacement jmp */
3910 const int md_reloc_size = 8;    /* Size of relocation record */
3911
3912 void
3913 md_create_short_jump (ptr, from_addr, to_addr, frag, to_symbol)
3914      char *ptr;
3915      addressT from_addr, to_addr;
3916      fragS *frag ATTRIBUTE_UNUSED;
3917      symbolS *to_symbol ATTRIBUTE_UNUSED;
3918 {
3919   offsetT offset;
3920
3921   offset = to_addr - (from_addr + 2);
3922   md_number_to_chars (ptr, (valueT) 0xeb, 1);   /* opcode for byte-disp jump */
3923   md_number_to_chars (ptr + 1, (valueT) offset, 1);
3924 }
3925
3926 void
3927 md_create_long_jump (ptr, from_addr, to_addr, frag, to_symbol)
3928      char *ptr;
3929      addressT from_addr, to_addr;
3930      fragS *frag;
3931      symbolS *to_symbol;
3932 {
3933   offsetT offset;
3934
3935   if (flag_do_long_jump)
3936     {
3937       offset = to_addr - S_GET_VALUE (to_symbol);
3938       md_number_to_chars (ptr, (valueT) 0xe9, 1);/* opcode for long jmp */
3939       md_number_to_chars (ptr + 1, (valueT) offset, 4);
3940       fix_new (frag, (ptr + 1) - frag->fr_literal, 4,
3941                to_symbol, (offsetT) 0, 0, BFD_RELOC_32);
3942     }
3943   else
3944     {
3945       offset = to_addr - (from_addr + 5);
3946       md_number_to_chars (ptr, (valueT) 0xe9, 1);
3947       md_number_to_chars (ptr + 1, (valueT) offset, 4);
3948     }
3949 }
3950 \f
3951 /* Apply a fixup (fixS) to segment data, once it has been determined
3952    by our caller that we have all the info we need to fix it up.
3953
3954    On the 386, immediates, displacements, and data pointers are all in
3955    the same (little-endian) format, so we don't need to care about which
3956    we are handling.  */
3957
3958 int
3959 md_apply_fix3 (fixP, valp, seg)
3960      fixS *fixP;                /* The fix we're to put in.  */
3961      valueT *valp;              /* Pointer to the value of the bits.  */
3962      segT seg ATTRIBUTE_UNUSED; /* Segment fix is from.  */
3963 {
3964   register char *p = fixP->fx_where + fixP->fx_frag->fr_literal;
3965   valueT value = *valp;
3966
3967 #if defined (BFD_ASSEMBLER) && !defined (TE_Mach)
3968   if (fixP->fx_pcrel)
3969     {
3970       switch (fixP->fx_r_type)
3971         {
3972         default:
3973           break;
3974
3975         case BFD_RELOC_32:
3976           fixP->fx_r_type = BFD_RELOC_32_PCREL;
3977           break;
3978         case BFD_RELOC_16:
3979           fixP->fx_r_type = BFD_RELOC_16_PCREL;
3980           break;
3981         case BFD_RELOC_8:
3982           fixP->fx_r_type = BFD_RELOC_8_PCREL;
3983           break;
3984         }
3985     }
3986
3987   /* This is a hack.  There should be a better way to handle this.
3988      This covers for the fact that bfd_install_relocation will
3989      subtract the current location (for partial_inplace, PC relative
3990      relocations); see more below.  */
3991   if ((fixP->fx_r_type == BFD_RELOC_32_PCREL
3992        || fixP->fx_r_type == BFD_RELOC_16_PCREL
3993        || fixP->fx_r_type == BFD_RELOC_8_PCREL)
3994       && fixP->fx_addsy)
3995     {
3996 #ifndef OBJ_AOUT
3997       if (OUTPUT_FLAVOR == bfd_target_elf_flavour
3998 #ifdef TE_PE
3999           || OUTPUT_FLAVOR == bfd_target_coff_flavour
4000 #endif
4001           )
4002         value += fixP->fx_where + fixP->fx_frag->fr_address;
4003 #endif
4004 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
4005       if (OUTPUT_FLAVOR == bfd_target_elf_flavour)
4006         {
4007           segT fseg = S_GET_SEGMENT (fixP->fx_addsy);
4008
4009           if ((fseg == seg
4010                || (symbol_section_p (fixP->fx_addsy)
4011                    && fseg != absolute_section))
4012               && ! S_IS_EXTERNAL (fixP->fx_addsy)
4013               && ! S_IS_WEAK (fixP->fx_addsy)
4014               && S_IS_DEFINED (fixP->fx_addsy)
4015               && ! S_IS_COMMON (fixP->fx_addsy))
4016             {
4017               /* Yes, we add the values in twice.  This is because
4018                  bfd_perform_relocation subtracts them out again.  I think
4019                  bfd_perform_relocation is broken, but I don't dare change
4020                  it.  FIXME.  */
4021               value += fixP->fx_where + fixP->fx_frag->fr_address;
4022             }
4023         }
4024 #endif
4025 #if defined (OBJ_COFF) && defined (TE_PE)
4026       /* For some reason, the PE format does not store a section
4027          address offset for a PC relative symbol.  */
4028       if (S_GET_SEGMENT (fixP->fx_addsy) != seg)
4029         value += md_pcrel_from (fixP);
4030       else if (S_IS_EXTERNAL (fixP->fx_addsy)
4031                || S_IS_WEAK (fixP->fx_addsy))
4032         {
4033           /* We are generating an external relocation for this defined
4034              symbol.  We add the address, because
4035              bfd_install_relocation will subtract it.  VALUE already
4036              holds the symbol value, because fixup_segment added it
4037              in.  We subtract it out, and then we subtract it out
4038              again because bfd_install_relocation will add it in
4039              again.  */
4040           value += md_pcrel_from (fixP);
4041           value -= 2 * S_GET_VALUE (fixP->fx_addsy);
4042         }
4043 #endif
4044     }
4045 #ifdef TE_PE
4046   else if (fixP->fx_addsy != NULL
4047            && S_IS_DEFINED (fixP->fx_addsy)
4048            && (S_IS_EXTERNAL (fixP->fx_addsy)
4049                || S_IS_WEAK (fixP->fx_addsy)))
4050     {
4051       /* We are generating an external relocation for this defined
4052          symbol.  VALUE already holds the symbol value, and
4053          bfd_install_relocation will add it in again.  We don't want
4054          either addition.  */
4055       value -= 2 * S_GET_VALUE (fixP->fx_addsy);
4056     }
4057 #endif
4058
4059   /* Fix a few things - the dynamic linker expects certain values here,
4060      and we must not dissappoint it. */
4061 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
4062   if (OUTPUT_FLAVOR == bfd_target_elf_flavour
4063       && fixP->fx_addsy)
4064     switch (fixP->fx_r_type) {
4065     case BFD_RELOC_386_PLT32:
4066       /* Make the jump instruction point to the address of the operand.  At
4067          runtime we merely add the offset to the actual PLT entry. */
4068       value = -4;
4069       break;
4070     case BFD_RELOC_386_GOTPC:
4071 /*
4072  *   This is tough to explain.  We end up with this one if we have
4073  * operands that look like "_GLOBAL_OFFSET_TABLE_+[.-.L284]".  The goal
4074  * here is to obtain the absolute address of the GOT, and it is strongly
4075  * preferable from a performance point of view to avoid using a runtime
4076  * relocation for this.  The actual sequence of instructions often look
4077  * something like:
4078  *
4079  *      call    .L66
4080  * .L66:
4081  *      popl    %ebx
4082  *      addl    $_GLOBAL_OFFSET_TABLE_+[.-.L66],%ebx
4083  *
4084  *   The call and pop essentially return the absolute address of
4085  * the label .L66 and store it in %ebx.  The linker itself will
4086  * ultimately change the first operand of the addl so that %ebx points to
4087  * the GOT, but to keep things simple, the .o file must have this operand
4088  * set so that it generates not the absolute address of .L66, but the
4089  * absolute address of itself.  This allows the linker itself simply
4090  * treat a GOTPC relocation as asking for a pcrel offset to the GOT to be
4091  * added in, and the addend of the relocation is stored in the operand
4092  * field for the instruction itself.
4093  *
4094  *   Our job here is to fix the operand so that it would add the correct
4095  * offset so that %ebx would point to itself.  The thing that is tricky is
4096  * that .-.L66 will point to the beginning of the instruction, so we need
4097  * to further modify the operand so that it will point to itself.
4098  * There are other cases where you have something like:
4099  *
4100  *      .long   $_GLOBAL_OFFSET_TABLE_+[.-.L66]
4101  *
4102  * and here no correction would be required.  Internally in the assembler
4103  * we treat operands of this form as not being pcrel since the '.' is
4104  * explicitly mentioned, and I wonder whether it would simplify matters
4105  * to do it this way.  Who knows.  In earlier versions of the PIC patches,
4106  * the pcrel_adjust field was used to store the correction, but since the
4107  * expression is not pcrel, I felt it would be confusing to do it this way.
4108  */
4109       value -= 1;
4110       break;
4111     case BFD_RELOC_386_GOT32:
4112       value = 0; /* Fully resolved at runtime.  No addend.  */
4113       break;
4114     case BFD_RELOC_386_GOTOFF:
4115       break;
4116
4117     case BFD_RELOC_VTABLE_INHERIT:
4118     case BFD_RELOC_VTABLE_ENTRY:
4119       fixP->fx_done = 0;
4120       return 1;
4121
4122     default:
4123       break;
4124     }
4125 #endif /* defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) */
4126   *valp = value;
4127 #endif /* defined (BFD_ASSEMBLER) && !defined (TE_Mach) */
4128   md_number_to_chars (p, value, fixP->fx_size);
4129
4130   return 1;
4131 }
4132 \f
4133
4134 #define MAX_LITTLENUMS 6
4135
4136 /* Turn the string pointed to by litP into a floating point constant of type
4137    type, and emit the appropriate bytes.  The number of LITTLENUMS emitted
4138    is stored in *sizeP .  An error message is returned, or NULL on OK.  */
4139 char *
4140 md_atof (type, litP, sizeP)
4141      int type;
4142      char *litP;
4143      int *sizeP;
4144 {
4145   int prec;
4146   LITTLENUM_TYPE words[MAX_LITTLENUMS];
4147   LITTLENUM_TYPE *wordP;
4148   char *t;
4149
4150   switch (type)
4151     {
4152     case 'f':
4153     case 'F':
4154       prec = 2;
4155       break;
4156
4157     case 'd':
4158     case 'D':
4159       prec = 4;
4160       break;
4161
4162     case 'x':
4163     case 'X':
4164       prec = 5;
4165       break;
4166
4167     default:
4168       *sizeP = 0;
4169       return _("Bad call to md_atof ()");
4170     }
4171   t = atof_ieee (input_line_pointer, type, words);
4172   if (t)
4173     input_line_pointer = t;
4174
4175   *sizeP = prec * sizeof (LITTLENUM_TYPE);
4176   /* This loops outputs the LITTLENUMs in REVERSE order; in accord with
4177      the bigendian 386.  */
4178   for (wordP = words + prec - 1; prec--;)
4179     {
4180       md_number_to_chars (litP, (valueT) (*wordP--), sizeof (LITTLENUM_TYPE));
4181       litP += sizeof (LITTLENUM_TYPE);
4182     }
4183   return 0;
4184 }
4185 \f
4186 char output_invalid_buf[8];
4187
4188 static char *
4189 output_invalid (c)
4190      int c;
4191 {
4192   if (isprint (c))
4193     sprintf (output_invalid_buf, "'%c'", c);
4194   else
4195     sprintf (output_invalid_buf, "(0x%x)", (unsigned) c);
4196   return output_invalid_buf;
4197 }
4198
4199
4200 /* REG_STRING starts *before* REGISTER_PREFIX.  */
4201
4202 static const reg_entry *
4203 parse_register (reg_string, end_op)
4204      char *reg_string;
4205      char **end_op;
4206 {
4207   char *s = reg_string;
4208   char *p;
4209   char reg_name_given[MAX_REG_NAME_SIZE + 1];
4210   const reg_entry *r;
4211
4212   /* Skip possible REGISTER_PREFIX and possible whitespace.  */
4213   if (*s == REGISTER_PREFIX)
4214     ++s;
4215
4216   if (is_space_char (*s))
4217     ++s;
4218
4219   p = reg_name_given;
4220   while ((*p++ = register_chars[(unsigned char) *s]) != '\0')
4221     {
4222       if (p >= reg_name_given + MAX_REG_NAME_SIZE)
4223         return (const reg_entry *) NULL;
4224       s++;
4225     }
4226
4227   *end_op = s;
4228
4229   r = (const reg_entry *) hash_find (reg_hash, reg_name_given);
4230
4231   /* Handle floating point regs, allowing spaces in the (i) part.  */
4232   if (r == i386_regtab /* %st is first entry of table */)
4233     {
4234       if (is_space_char (*s))
4235         ++s;
4236       if (*s == '(')
4237         {
4238           ++s;
4239           if (is_space_char (*s))
4240             ++s;
4241           if (*s >= '0' && *s <= '7')
4242             {
4243               r = &i386_float_regtab[*s - '0'];
4244               ++s;
4245               if (is_space_char (*s))
4246                 ++s;
4247               if (*s == ')')
4248                 {
4249                   *end_op = s + 1;
4250                   return r;
4251                 }
4252             }
4253           /* We have "%st(" then garbage */
4254           return (const reg_entry *) NULL;
4255         }
4256     }
4257
4258   return r;
4259 }
4260 \f
4261 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
4262 CONST char *md_shortopts = "kmVQ:sq";
4263 #else
4264 CONST char *md_shortopts = "m";
4265 #endif
4266 struct option md_longopts[] = {
4267   {NULL, no_argument, NULL, 0}
4268 };
4269 size_t md_longopts_size = sizeof (md_longopts);
4270
4271 int
4272 md_parse_option (c, arg)
4273      int c;
4274      char *arg ATTRIBUTE_UNUSED;
4275 {
4276   switch (c)
4277     {
4278     case 'm':
4279       flag_do_long_jump = 1;
4280       break;
4281
4282 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
4283       /* -k: Ignore for FreeBSD compatibility.  */
4284     case 'k':
4285       break;
4286
4287       /* -V: SVR4 argument to print version ID.  */
4288     case 'V':
4289       print_version_id ();
4290       break;
4291
4292       /* -Qy, -Qn: SVR4 arguments controlling whether a .comment section
4293          should be emitted or not.  FIXME: Not implemented.  */
4294     case 'Q':
4295       break;
4296
4297     case 's':
4298       /* -s: On i386 Solaris, this tells the native assembler to use
4299          .stab instead of .stab.excl.  We always use .stab anyhow.  */
4300       break;
4301
4302     case 'q':
4303       /* -q: On i386 Solaris, this tells the native assembler to do
4304          fewer checks.  */
4305       break;
4306 #endif
4307
4308     default:
4309       return 0;
4310     }
4311   return 1;
4312 }
4313
4314 void
4315 md_show_usage (stream)
4316      FILE *stream;
4317 {
4318   fprintf (stream, _("\
4319   -m                      do long jump\n"));
4320 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
4321   fprintf (stream, _("\
4322   -V                      print assembler version number\n\
4323   -k                      ignored\n\
4324   -Qy, -Qn                ignored\n\
4325   -q                      ignored\n\
4326   -s                      ignored\n"));
4327 #endif
4328 }
4329
4330 #ifdef BFD_ASSEMBLER
4331 #if ((defined (OBJ_MAYBE_ELF) && defined (OBJ_MAYBE_COFF)) \
4332      || (defined (OBJ_MAYBE_ELF) && defined (OBJ_MAYBE_AOUT)) \
4333      || (defined (OBJ_MAYBE_COFF) && defined (OBJ_MAYBE_AOUT)))
4334
4335 /* Pick the target format to use.  */
4336
4337 const char  *
4338 i386_target_format ()
4339 {
4340   switch (OUTPUT_FLAVOR)
4341     {
4342 #ifdef OBJ_MAYBE_AOUT
4343     case bfd_target_aout_flavour:
4344      return AOUT_TARGET_FORMAT;
4345 #endif
4346 #ifdef OBJ_MAYBE_COFF
4347     case bfd_target_coff_flavour:
4348       return "coff-i386";
4349 #endif
4350 #ifdef OBJ_MAYBE_ELF
4351     case bfd_target_elf_flavour:
4352       return "elf32-i386";
4353 #endif
4354     default:
4355       abort ();
4356       return NULL;
4357     }
4358 }
4359
4360 #endif /* OBJ_MAYBE_ more than one */
4361 #endif /* BFD_ASSEMBLER */
4362 \f
4363 symbolS *
4364 md_undefined_symbol (name)
4365      char *name;
4366 {
4367   if (name[0] == GLOBAL_OFFSET_TABLE_NAME[0]
4368       && name[1] == GLOBAL_OFFSET_TABLE_NAME[1]
4369       && name[2] == GLOBAL_OFFSET_TABLE_NAME[2]
4370       && strcmp (name, GLOBAL_OFFSET_TABLE_NAME) == 0)
4371     {
4372       if (!GOT_symbol)
4373         {
4374           if (symbol_find (name))
4375             as_bad (_("GOT already in symbol table"));
4376           GOT_symbol = symbol_new (name, undefined_section,
4377                                    (valueT) 0, &zero_address_frag);
4378         };
4379       return GOT_symbol;
4380     }
4381   return 0;
4382 }
4383
4384 /* Round up a section size to the appropriate boundary.  */
4385 valueT
4386 md_section_align (segment, size)
4387      segT segment ATTRIBUTE_UNUSED;
4388      valueT size;
4389 {
4390 #ifdef BFD_ASSEMBLER
4391 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
4392   if (OUTPUT_FLAVOR == bfd_target_aout_flavour)
4393     {
4394       /* For a.out, force the section size to be aligned.  If we don't do
4395          this, BFD will align it for us, but it will not write out the
4396          final bytes of the section.  This may be a bug in BFD, but it is
4397          easier to fix it here since that is how the other a.out targets
4398          work.  */
4399       int align;
4400
4401       align = bfd_get_section_alignment (stdoutput, segment);
4402       size = ((size + (1 << align) - 1) & ((valueT) -1 << align));
4403     }
4404 #endif
4405 #endif
4406
4407   return size;
4408 }
4409
4410 /* On the i386, PC-relative offsets are relative to the start of the
4411    next instruction.  That is, the address of the offset, plus its
4412    size, since the offset is always the last part of the insn.  */
4413
4414 long
4415 md_pcrel_from (fixP)
4416      fixS *fixP;
4417 {
4418   return fixP->fx_size + fixP->fx_where + fixP->fx_frag->fr_address;
4419 }
4420
4421 #ifndef I386COFF
4422
4423 static void
4424 s_bss (ignore)
4425      int ignore ATTRIBUTE_UNUSED;
4426 {
4427   register int temp;
4428
4429   temp = get_absolute_expression ();
4430   subseg_set (bss_section, (subsegT) temp);
4431   demand_empty_rest_of_line ();
4432 }
4433
4434 #endif
4435
4436
4437 #ifdef BFD_ASSEMBLER
4438
4439 void
4440 i386_validate_fix (fixp)
4441      fixS *fixp;
4442 {
4443   if (fixp->fx_subsy && fixp->fx_subsy == GOT_symbol)
4444     {
4445       fixp->fx_r_type = BFD_RELOC_386_GOTOFF;
4446       fixp->fx_subsy = 0;
4447     }
4448 }
4449
4450 arelent *
4451 tc_gen_reloc (section, fixp)
4452      asection *section ATTRIBUTE_UNUSED;
4453      fixS *fixp;
4454 {
4455   arelent *rel;
4456   bfd_reloc_code_real_type code;
4457
4458   switch (fixp->fx_r_type)
4459     {
4460     case BFD_RELOC_386_PLT32:
4461     case BFD_RELOC_386_GOT32:
4462     case BFD_RELOC_386_GOTOFF:
4463     case BFD_RELOC_386_GOTPC:
4464     case BFD_RELOC_RVA:
4465     case BFD_RELOC_VTABLE_ENTRY:
4466     case BFD_RELOC_VTABLE_INHERIT:
4467       code = fixp->fx_r_type;
4468       break;
4469     default:
4470       if (fixp->fx_pcrel)
4471         {
4472           switch (fixp->fx_size)
4473             {
4474             default:
4475               as_bad (_("can not do %d byte pc-relative relocation"),
4476                       fixp->fx_size);
4477               code = BFD_RELOC_32_PCREL;
4478               break;
4479             case 1: code = BFD_RELOC_8_PCREL;  break;
4480             case 2: code = BFD_RELOC_16_PCREL; break;
4481             case 4: code = BFD_RELOC_32_PCREL; break;
4482             }
4483         }
4484       else
4485         {
4486           switch (fixp->fx_size)
4487             {
4488             default:
4489               as_bad (_("can not do %d byte relocation"), fixp->fx_size);
4490               code = BFD_RELOC_32;
4491               break;
4492             case 1: code = BFD_RELOC_8;  break;
4493             case 2: code = BFD_RELOC_16; break;
4494             case 4: code = BFD_RELOC_32; break;
4495             }
4496         }
4497       break;
4498     }
4499
4500   if (code == BFD_RELOC_32
4501       && GOT_symbol
4502       && fixp->fx_addsy == GOT_symbol)
4503     code = BFD_RELOC_386_GOTPC;
4504
4505   rel = (arelent *) xmalloc (sizeof (arelent));
4506   rel->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
4507   *rel->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
4508
4509   rel->address = fixp->fx_frag->fr_address + fixp->fx_where;
4510   /* HACK: Since i386 ELF uses Rel instead of Rela, encode the
4511      vtable entry to be used in the relocation's section offset.  */
4512   if (fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
4513     rel->address = fixp->fx_offset;
4514
4515   if (fixp->fx_pcrel)
4516     rel->addend = fixp->fx_addnumber;
4517   else
4518     rel->addend = 0;
4519
4520   rel->howto = bfd_reloc_type_lookup (stdoutput, code);
4521   if (rel->howto == NULL)
4522     {
4523       as_bad_where (fixp->fx_file, fixp->fx_line,
4524                     _("cannot represent relocation type %s"),
4525                     bfd_get_reloc_code_name (code));
4526       /* Set howto to a garbage value so that we can keep going.  */
4527       rel->howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_32);
4528       assert (rel->howto != NULL);
4529     }
4530
4531   return rel;
4532 }
4533
4534 #else /* ! BFD_ASSEMBLER */
4535
4536 #if (defined(OBJ_AOUT) | defined(OBJ_BOUT))
4537 void
4538 tc_aout_fix_to_chars (where, fixP, segment_address_in_file)
4539      char *where;
4540      fixS *fixP;
4541      relax_addressT segment_address_in_file;
4542 {
4543   /*
4544    * In: length of relocation (or of address) in chars: 1, 2 or 4.
4545    * Out: GNU LD relocation length code: 0, 1, or 2.
4546    */
4547
4548   static const unsigned char nbytes_r_length[] = {42, 0, 1, 42, 2};
4549   long r_symbolnum;
4550
4551   know (fixP->fx_addsy != NULL);
4552
4553   md_number_to_chars (where,
4554                       (valueT) (fixP->fx_frag->fr_address
4555                                 + fixP->fx_where - segment_address_in_file),
4556                       4);
4557
4558   r_symbolnum = (S_IS_DEFINED (fixP->fx_addsy)
4559                  ? S_GET_TYPE (fixP->fx_addsy)
4560                  : fixP->fx_addsy->sy_number);
4561
4562   where[6] = (r_symbolnum >> 16) & 0x0ff;
4563   where[5] = (r_symbolnum >> 8) & 0x0ff;
4564   where[4] = r_symbolnum & 0x0ff;
4565   where[7] = ((((!S_IS_DEFINED (fixP->fx_addsy)) << 3) & 0x08)
4566               | ((nbytes_r_length[fixP->fx_size] << 1) & 0x06)
4567               | (((fixP->fx_pcrel << 0) & 0x01) & 0x0f));
4568 }
4569
4570 #endif /* OBJ_AOUT or OBJ_BOUT */
4571
4572 #if defined (I386COFF)
4573
4574 short
4575 tc_coff_fix2rtype (fixP)
4576      fixS *fixP;
4577 {
4578   if (fixP->fx_r_type == R_IMAGEBASE)
4579     return R_IMAGEBASE;
4580
4581   return (fixP->fx_pcrel ?
4582           (fixP->fx_size == 1 ? R_PCRBYTE :
4583            fixP->fx_size == 2 ? R_PCRWORD :
4584            R_PCRLONG) :
4585           (fixP->fx_size == 1 ? R_RELBYTE :
4586            fixP->fx_size == 2 ? R_RELWORD :
4587            R_DIR32));
4588 }
4589
4590 int
4591 tc_coff_sizemachdep (frag)
4592      fragS *frag;
4593 {
4594   if (frag->fr_next)
4595     return (frag->fr_next->fr_address - frag->fr_address);
4596   else
4597     return 0;
4598 }
4599
4600 #endif /* I386COFF */
4601
4602 #endif /* ! BFD_ASSEMBLER */
4603 \f
4604 /* end of tc-i386.c */