gas/
[platform/upstream/binutils.git] / gas / config / tc-i386.c
1 /* tc-i386.c -- Assemble code for the Intel 80386
2    Copyright 1989, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
3    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007
4    Free Software Foundation, Inc.
5
6    This file is part of GAS, the GNU Assembler.
7
8    GAS is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3, or (at your option)
11    any later version.
12
13    GAS is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GAS; see the file COPYING.  If not, write to the Free
20    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
21    02110-1301, USA.  */
22
23 /* Intel 80386 machine specific gas.
24    Written by Eliot Dresselhaus (eliot@mgm.mit.edu).
25    x86_64 support by Jan Hubicka (jh@suse.cz)
26    VIA PadLock support by Michal Ludvig (mludvig@suse.cz)
27    Bugs & suggestions are completely welcome.  This is free software.
28    Please help us make it better.  */
29
30 #include "as.h"
31 #include "safe-ctype.h"
32 #include "subsegs.h"
33 #include "dwarf2dbg.h"
34 #include "dw2gencfi.h"
35 #include "elf/x86-64.h"
36 #include "opcodes/i386-init.h"
37
38 #ifndef REGISTER_WARNINGS
39 #define REGISTER_WARNINGS 1
40 #endif
41
42 #ifndef INFER_ADDR_PREFIX
43 #define INFER_ADDR_PREFIX 1
44 #endif
45
46 #ifndef DEFAULT_ARCH
47 #define DEFAULT_ARCH "i386"
48 #endif
49
50 #ifndef INLINE
51 #if __GNUC__ >= 2
52 #define INLINE __inline__
53 #else
54 #define INLINE
55 #endif
56 #endif
57
58 static void set_code_flag (int);
59 static void set_16bit_gcc_code_flag (int);
60 static void set_intel_syntax (int);
61 static void set_allow_index_reg (int);
62 static void set_cpu_arch (int);
63 #ifdef TE_PE
64 static void pe_directive_secrel (int);
65 #endif
66 static void signed_cons (int);
67 static char *output_invalid (int c);
68 static int i386_operand (char *);
69 static int i386_intel_operand (char *, int);
70 static const reg_entry *parse_register (char *, char **);
71 static char *parse_insn (char *, char *);
72 static char *parse_operands (char *, const char *);
73 static void swap_operands (void);
74 static void swap_2_operands (int, int);
75 static void optimize_imm (void);
76 static void optimize_disp (void);
77 static int match_template (void);
78 static int check_string (void);
79 static int process_suffix (void);
80 static int check_byte_reg (void);
81 static int check_long_reg (void);
82 static int check_qword_reg (void);
83 static int check_word_reg (void);
84 static int finalize_imm (void);
85 static void process_drex (void);
86 static int process_operands (void);
87 static const seg_entry *build_modrm_byte (void);
88 static void output_insn (void);
89 static void output_imm (fragS *, offsetT);
90 static void output_disp (fragS *, offsetT);
91 #ifndef I386COFF
92 static void s_bss (int);
93 #endif
94 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
95 static void handle_large_common (int small ATTRIBUTE_UNUSED);
96 #endif
97
98 static const char *default_arch = DEFAULT_ARCH;
99
100 /* 'md_assemble ()' gathers together information and puts it into a
101    i386_insn.  */
102
103 union i386_op
104   {
105     expressionS *disps;
106     expressionS *imms;
107     const reg_entry *regs;
108   };
109
110 struct _i386_insn
111   {
112     /* TM holds the template for the insn were currently assembling.  */
113     template tm;
114
115     /* SUFFIX holds the instruction mnemonic suffix if given.
116        (e.g. 'l' for 'movl')  */
117     char suffix;
118
119     /* OPERANDS gives the number of given operands.  */
120     unsigned int operands;
121
122     /* REG_OPERANDS, DISP_OPERANDS, MEM_OPERANDS, IMM_OPERANDS give the number
123        of given register, displacement, memory operands and immediate
124        operands.  */
125     unsigned int reg_operands, disp_operands, mem_operands, imm_operands;
126
127     /* TYPES [i] is the type (see above #defines) which tells us how to
128        use OP[i] for the corresponding operand.  */
129     i386_operand_type types[MAX_OPERANDS];
130
131     /* Displacement expression, immediate expression, or register for each
132        operand.  */
133     union i386_op op[MAX_OPERANDS];
134
135     /* Flags for operands.  */
136     unsigned int flags[MAX_OPERANDS];
137 #define Operand_PCrel 1
138
139     /* Relocation type for operand */
140     enum bfd_reloc_code_real reloc[MAX_OPERANDS];
141
142     /* BASE_REG, INDEX_REG, and LOG2_SCALE_FACTOR are used to encode
143        the base index byte below.  */
144     const reg_entry *base_reg;
145     const reg_entry *index_reg;
146     unsigned int log2_scale_factor;
147
148     /* SEG gives the seg_entries of this insn.  They are zero unless
149        explicit segment overrides are given.  */
150     const seg_entry *seg[2];
151
152     /* PREFIX holds all the given prefix opcodes (usually null).
153        PREFIXES is the number of prefix opcodes.  */
154     unsigned int prefixes;
155     unsigned char prefix[MAX_PREFIXES];
156
157     /* RM and SIB are the modrm byte and the sib byte where the
158        addressing modes of this insn are encoded.  DREX is the byte
159        added by the SSE5 instructions.  */
160
161     modrm_byte rm;
162     rex_byte rex;
163     sib_byte sib;
164     drex_byte drex;
165   };
166
167 typedef struct _i386_insn i386_insn;
168
169 /* List of chars besides those in app.c:symbol_chars that can start an
170    operand.  Used to prevent the scrubber eating vital white-space.  */
171 const char extra_symbol_chars[] = "*%-(["
172 #ifdef LEX_AT
173         "@"
174 #endif
175 #ifdef LEX_QM
176         "?"
177 #endif
178         ;
179
180 #if (defined (TE_I386AIX)                               \
181      || ((defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)) \
182          && !defined (TE_GNU)                           \
183          && !defined (TE_LINUX)                         \
184          && !defined (TE_NETWARE)                       \
185          && !defined (TE_FreeBSD)                       \
186          && !defined (TE_NetBSD)))
187 /* This array holds the chars that always start a comment.  If the
188    pre-processor is disabled, these aren't very useful.  The option
189    --divide will remove '/' from this list.  */
190 const char *i386_comment_chars = "#/";
191 #define SVR4_COMMENT_CHARS 1
192 #define PREFIX_SEPARATOR '\\'
193
194 #else
195 const char *i386_comment_chars = "#";
196 #define PREFIX_SEPARATOR '/'
197 #endif
198
199 /* This array holds the chars that only start a comment at the beginning of
200    a line.  If the line seems to have the form '# 123 filename'
201    .line and .file directives will appear in the pre-processed output.
202    Note that input_file.c hand checks for '#' at the beginning of the
203    first line of the input file.  This is because the compiler outputs
204    #NO_APP at the beginning of its output.
205    Also note that comments started like this one will always work if
206    '/' isn't otherwise defined.  */
207 const char line_comment_chars[] = "#/";
208
209 const char line_separator_chars[] = ";";
210
211 /* Chars that can be used to separate mant from exp in floating point
212    nums.  */
213 const char EXP_CHARS[] = "eE";
214
215 /* Chars that mean this number is a floating point constant
216    As in 0f12.456
217    or    0d1.2345e12.  */
218 const char FLT_CHARS[] = "fFdDxX";
219
220 /* Tables for lexical analysis.  */
221 static char mnemonic_chars[256];
222 static char register_chars[256];
223 static char operand_chars[256];
224 static char identifier_chars[256];
225 static char digit_chars[256];
226
227 /* Lexical macros.  */
228 #define is_mnemonic_char(x) (mnemonic_chars[(unsigned char) x])
229 #define is_operand_char(x) (operand_chars[(unsigned char) x])
230 #define is_register_char(x) (register_chars[(unsigned char) x])
231 #define is_space_char(x) ((x) == ' ')
232 #define is_identifier_char(x) (identifier_chars[(unsigned char) x])
233 #define is_digit_char(x) (digit_chars[(unsigned char) x])
234
235 /* All non-digit non-letter characters that may occur in an operand.  */
236 static char operand_special_chars[] = "%$-+(,)*._~/<>|&^!:[@]";
237
238 /* md_assemble() always leaves the strings it's passed unaltered.  To
239    effect this we maintain a stack of saved characters that we've smashed
240    with '\0's (indicating end of strings for various sub-fields of the
241    assembler instruction).  */
242 static char save_stack[32];
243 static char *save_stack_p;
244 #define END_STRING_AND_SAVE(s) \
245         do { *save_stack_p++ = *(s); *(s) = '\0'; } while (0)
246 #define RESTORE_END_STRING(s) \
247         do { *(s) = *--save_stack_p; } while (0)
248
249 /* The instruction we're assembling.  */
250 static i386_insn i;
251
252 /* Possible templates for current insn.  */
253 static const templates *current_templates;
254
255 /* Per instruction expressionS buffers: max displacements & immediates.  */
256 static expressionS disp_expressions[MAX_MEMORY_OPERANDS];
257 static expressionS im_expressions[MAX_IMMEDIATE_OPERANDS];
258
259 /* Current operand we are working on.  */
260 static int this_operand;
261
262 /* We support four different modes.  FLAG_CODE variable is used to distinguish
263    these.  */
264
265 enum flag_code {
266         CODE_32BIT,
267         CODE_16BIT,
268         CODE_64BIT };
269
270 static enum flag_code flag_code;
271 static unsigned int object_64bit;
272 static int use_rela_relocations = 0;
273
274 /* The names used to print error messages.  */
275 static const char *flag_code_names[] =
276   {
277     "32",
278     "16",
279     "64"
280   };
281
282 /* 1 for intel syntax,
283    0 if att syntax.  */
284 static int intel_syntax = 0;
285
286 /* 1 if register prefix % not required.  */
287 static int allow_naked_reg = 0;
288
289 /* 1 if fake index register, eiz/riz, is allowed .  */
290 static int allow_index_reg = 0;
291
292 /* Register prefix used for error message.  */
293 static const char *register_prefix = "%";
294
295 /* Used in 16 bit gcc mode to add an l suffix to call, ret, enter,
296    leave, push, and pop instructions so that gcc has the same stack
297    frame as in 32 bit mode.  */
298 static char stackop_size = '\0';
299
300 /* Non-zero to optimize code alignment.  */
301 int optimize_align_code = 1;
302
303 /* Non-zero to quieten some warnings.  */
304 static int quiet_warnings = 0;
305
306 /* CPU name.  */
307 static const char *cpu_arch_name = NULL;
308 static const char *cpu_sub_arch_name = NULL;
309
310 /* CPU feature flags.  */
311 static i386_cpu_flags cpu_arch_flags = CPU_UNKNOWN_FLAGS;
312
313 /* Bitwise NOT of cpu_arch_flags.  */
314 static i386_cpu_flags cpu_arch_flags_not;
315
316 /* If we have selected a cpu we are generating instructions for.  */
317 static int cpu_arch_tune_set = 0;
318
319 /* Cpu we are generating instructions for.  */
320 static enum processor_type cpu_arch_tune = PROCESSOR_UNKNOWN;
321
322 /* CPU feature flags of cpu we are generating instructions for.  */
323 static i386_cpu_flags cpu_arch_tune_flags;
324
325 /* CPU instruction set architecture used.  */
326 static enum processor_type cpu_arch_isa = PROCESSOR_UNKNOWN;
327
328 /* CPU feature flags of instruction set architecture used.  */
329 static i386_cpu_flags cpu_arch_isa_flags;
330
331 /* If set, conditional jumps are not automatically promoted to handle
332    larger than a byte offset.  */
333 static unsigned int no_cond_jump_promotion = 0;
334
335 /* Pre-defined "_GLOBAL_OFFSET_TABLE_".  */
336 static symbolS *GOT_symbol;
337
338 /* The dwarf2 return column, adjusted for 32 or 64 bit.  */
339 unsigned int x86_dwarf2_return_column;
340
341 /* The dwarf2 data alignment, adjusted for 32 or 64 bit.  */
342 int x86_cie_data_alignment;
343
344 /* Interface to relax_segment.
345    There are 3 major relax states for 386 jump insns because the
346    different types of jumps add different sizes to frags when we're
347    figuring out what sort of jump to choose to reach a given label.  */
348
349 /* Types.  */
350 #define UNCOND_JUMP 0
351 #define COND_JUMP 1
352 #define COND_JUMP86 2
353
354 /* Sizes.  */
355 #define CODE16  1
356 #define SMALL   0
357 #define SMALL16 (SMALL | CODE16)
358 #define BIG     2
359 #define BIG16   (BIG | CODE16)
360
361 #ifndef INLINE
362 #ifdef __GNUC__
363 #define INLINE __inline__
364 #else
365 #define INLINE
366 #endif
367 #endif
368
369 #define ENCODE_RELAX_STATE(type, size) \
370   ((relax_substateT) (((type) << 2) | (size)))
371 #define TYPE_FROM_RELAX_STATE(s) \
372   ((s) >> 2)
373 #define DISP_SIZE_FROM_RELAX_STATE(s) \
374     ((((s) & 3) == BIG ? 4 : (((s) & 3) == BIG16 ? 2 : 1)))
375
376 /* This table is used by relax_frag to promote short jumps to long
377    ones where necessary.  SMALL (short) jumps may be promoted to BIG
378    (32 bit long) ones, and SMALL16 jumps to BIG16 (16 bit long).  We
379    don't allow a short jump in a 32 bit code segment to be promoted to
380    a 16 bit offset jump because it's slower (requires data size
381    prefix), and doesn't work, unless the destination is in the bottom
382    64k of the code segment (The top 16 bits of eip are zeroed).  */
383
384 const relax_typeS md_relax_table[] =
385 {
386   /* The fields are:
387      1) most positive reach of this state,
388      2) most negative reach of this state,
389      3) how many bytes this mode will have in the variable part of the frag
390      4) which index into the table to try if we can't fit into this one.  */
391
392   /* UNCOND_JUMP states.  */
393   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (UNCOND_JUMP, BIG)},
394   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (UNCOND_JUMP, BIG16)},
395   /* dword jmp adds 4 bytes to frag:
396      0 extra opcode bytes, 4 displacement bytes.  */
397   {0, 0, 4, 0},
398   /* word jmp adds 2 byte2 to frag:
399      0 extra opcode bytes, 2 displacement bytes.  */
400   {0, 0, 2, 0},
401
402   /* COND_JUMP states.  */
403   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP, BIG)},
404   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP, BIG16)},
405   /* dword conditionals adds 5 bytes to frag:
406      1 extra opcode byte, 4 displacement bytes.  */
407   {0, 0, 5, 0},
408   /* word conditionals add 3 bytes to frag:
409      1 extra opcode byte, 2 displacement bytes.  */
410   {0, 0, 3, 0},
411
412   /* COND_JUMP86 states.  */
413   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP86, BIG)},
414   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP86, BIG16)},
415   /* dword conditionals adds 5 bytes to frag:
416      1 extra opcode byte, 4 displacement bytes.  */
417   {0, 0, 5, 0},
418   /* word conditionals add 4 bytes to frag:
419      1 displacement byte and a 3 byte long branch insn.  */
420   {0, 0, 4, 0}
421 };
422
423 static const arch_entry cpu_arch[] =
424 {
425   {"generic32", PROCESSOR_GENERIC32,
426    CPU_GENERIC32_FLAGS },
427   {"generic64", PROCESSOR_GENERIC64,
428    CPU_GENERIC64_FLAGS },
429   {"i8086", PROCESSOR_UNKNOWN,
430    CPU_NONE_FLAGS },
431   {"i186", PROCESSOR_UNKNOWN,
432    CPU_I186_FLAGS },
433   {"i286", PROCESSOR_UNKNOWN,
434    CPU_I286_FLAGS },
435   {"i386", PROCESSOR_I386,
436    CPU_I386_FLAGS },
437   {"i486", PROCESSOR_I486,
438    CPU_I486_FLAGS },
439   {"i586", PROCESSOR_PENTIUM,
440    CPU_I586_FLAGS },
441   {"i686", PROCESSOR_PENTIUMPRO,
442    CPU_I686_FLAGS },
443   {"pentium", PROCESSOR_PENTIUM,
444    CPU_I586_FLAGS },
445   {"pentiumpro",PROCESSOR_PENTIUMPRO,
446    CPU_I686_FLAGS },
447   {"pentiumii", PROCESSOR_PENTIUMPRO,
448    CPU_P2_FLAGS },
449   {"pentiumiii",PROCESSOR_PENTIUMPRO,
450    CPU_P3_FLAGS },
451   {"pentium4", PROCESSOR_PENTIUM4,
452    CPU_P4_FLAGS },
453   {"prescott", PROCESSOR_NOCONA,
454    CPU_CORE_FLAGS },
455   {"nocona", PROCESSOR_NOCONA,
456    CPU_NOCONA_FLAGS },
457   {"yonah", PROCESSOR_CORE,
458    CPU_CORE_FLAGS },
459   {"core", PROCESSOR_CORE,
460    CPU_CORE_FLAGS },
461   {"merom", PROCESSOR_CORE2,
462    CPU_CORE2_FLAGS },
463   {"core2", PROCESSOR_CORE2,
464    CPU_CORE2_FLAGS },
465   {"k6", PROCESSOR_K6,
466    CPU_K6_FLAGS },
467   {"k6_2", PROCESSOR_K6,
468    CPU_K6_2_FLAGS },
469   {"athlon", PROCESSOR_ATHLON,
470    CPU_ATHLON_FLAGS },
471   {"sledgehammer", PROCESSOR_K8,
472    CPU_K8_FLAGS },
473   {"opteron", PROCESSOR_K8,
474    CPU_K8_FLAGS },
475   {"k8", PROCESSOR_K8,
476    CPU_K8_FLAGS },
477   {"amdfam10", PROCESSOR_AMDFAM10,
478    CPU_AMDFAM10_FLAGS },
479   {".mmx", PROCESSOR_UNKNOWN,
480    CPU_MMX_FLAGS },
481   {".sse", PROCESSOR_UNKNOWN,
482    CPU_SSE_FLAGS },
483   {".sse2", PROCESSOR_UNKNOWN,
484    CPU_SSE2_FLAGS },
485   {".sse3", PROCESSOR_UNKNOWN,
486    CPU_SSE3_FLAGS },
487   {".ssse3", PROCESSOR_UNKNOWN,
488    CPU_SSSE3_FLAGS },
489   {".sse4.1", PROCESSOR_UNKNOWN,
490    CPU_SSE4_1_FLAGS },
491   {".sse4.2", PROCESSOR_UNKNOWN,
492    CPU_SSE4_2_FLAGS },
493   {".sse4", PROCESSOR_UNKNOWN,
494    CPU_SSE4_2_FLAGS },
495   {".3dnow", PROCESSOR_UNKNOWN,
496    CPU_3DNOW_FLAGS },
497   {".3dnowa", PROCESSOR_UNKNOWN,
498    CPU_3DNOWA_FLAGS },
499   {".padlock", PROCESSOR_UNKNOWN,
500    CPU_PADLOCK_FLAGS },
501   {".pacifica", PROCESSOR_UNKNOWN,
502    CPU_SVME_FLAGS },
503   {".svme", PROCESSOR_UNKNOWN,
504    CPU_SVME_FLAGS },
505   {".sse4a", PROCESSOR_UNKNOWN,
506    CPU_SSE4A_FLAGS },
507   {".abm", PROCESSOR_UNKNOWN,
508    CPU_ABM_FLAGS },
509   {".sse5", PROCESSOR_UNKNOWN,
510    CPU_SSE5_FLAGS },
511 };
512
513 const pseudo_typeS md_pseudo_table[] =
514 {
515 #if !defined(OBJ_AOUT) && !defined(USE_ALIGN_PTWO)
516   {"align", s_align_bytes, 0},
517 #else
518   {"align", s_align_ptwo, 0},
519 #endif
520   {"arch", set_cpu_arch, 0},
521 #ifndef I386COFF
522   {"bss", s_bss, 0},
523 #endif
524   {"ffloat", float_cons, 'f'},
525   {"dfloat", float_cons, 'd'},
526   {"tfloat", float_cons, 'x'},
527   {"value", cons, 2},
528   {"slong", signed_cons, 4},
529   {"noopt", s_ignore, 0},
530   {"optim", s_ignore, 0},
531   {"code16gcc", set_16bit_gcc_code_flag, CODE_16BIT},
532   {"code16", set_code_flag, CODE_16BIT},
533   {"code32", set_code_flag, CODE_32BIT},
534   {"code64", set_code_flag, CODE_64BIT},
535   {"intel_syntax", set_intel_syntax, 1},
536   {"att_syntax", set_intel_syntax, 0},
537   {"allow_index_reg", set_allow_index_reg, 1},
538   {"disallow_index_reg", set_allow_index_reg, 0},
539 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
540   {"largecomm", handle_large_common, 0},
541 #else
542   {"file", (void (*) (int)) dwarf2_directive_file, 0},
543   {"loc", dwarf2_directive_loc, 0},
544   {"loc_mark_labels", dwarf2_directive_loc_mark_labels, 0},
545 #endif
546 #ifdef TE_PE
547   {"secrel32", pe_directive_secrel, 0},
548 #endif
549   {0, 0, 0}
550 };
551
552 /* For interface with expression ().  */
553 extern char *input_line_pointer;
554
555 /* Hash table for instruction mnemonic lookup.  */
556 static struct hash_control *op_hash;
557
558 /* Hash table for register lookup.  */
559 static struct hash_control *reg_hash;
560 \f
561 void
562 i386_align_code (fragS *fragP, int count)
563 {
564   /* Various efficient no-op patterns for aligning code labels.
565      Note: Don't try to assemble the instructions in the comments.
566      0L and 0w are not legal.  */
567   static const char f32_1[] =
568     {0x90};                                     /* nop                  */
569   static const char f32_2[] =
570     {0x66,0x90};                                /* xchg %ax,%ax */
571   static const char f32_3[] =
572     {0x8d,0x76,0x00};                           /* leal 0(%esi),%esi    */
573   static const char f32_4[] =
574     {0x8d,0x74,0x26,0x00};                      /* leal 0(%esi,1),%esi  */
575   static const char f32_5[] =
576     {0x90,                                      /* nop                  */
577      0x8d,0x74,0x26,0x00};                      /* leal 0(%esi,1),%esi  */
578   static const char f32_6[] =
579     {0x8d,0xb6,0x00,0x00,0x00,0x00};            /* leal 0L(%esi),%esi   */
580   static const char f32_7[] =
581     {0x8d,0xb4,0x26,0x00,0x00,0x00,0x00};       /* leal 0L(%esi,1),%esi */
582   static const char f32_8[] =
583     {0x90,                                      /* nop                  */
584      0x8d,0xb4,0x26,0x00,0x00,0x00,0x00};       /* leal 0L(%esi,1),%esi */
585   static const char f32_9[] =
586     {0x89,0xf6,                                 /* movl %esi,%esi       */
587      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
588   static const char f32_10[] =
589     {0x8d,0x76,0x00,                            /* leal 0(%esi),%esi    */
590      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
591   static const char f32_11[] =
592     {0x8d,0x74,0x26,0x00,                       /* leal 0(%esi,1),%esi  */
593      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
594   static const char f32_12[] =
595     {0x8d,0xb6,0x00,0x00,0x00,0x00,             /* leal 0L(%esi),%esi   */
596      0x8d,0xbf,0x00,0x00,0x00,0x00};            /* leal 0L(%edi),%edi   */
597   static const char f32_13[] =
598     {0x8d,0xb6,0x00,0x00,0x00,0x00,             /* leal 0L(%esi),%esi   */
599      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
600   static const char f32_14[] =
601     {0x8d,0xb4,0x26,0x00,0x00,0x00,0x00,        /* leal 0L(%esi,1),%esi */
602      0x8d,0xbc,0x27,0x00,0x00,0x00,0x00};       /* leal 0L(%edi,1),%edi */
603   static const char f16_3[] =
604     {0x8d,0x74,0x00};                           /* lea 0(%esi),%esi     */
605   static const char f16_4[] =
606     {0x8d,0xb4,0x00,0x00};                      /* lea 0w(%si),%si      */
607   static const char f16_5[] =
608     {0x90,                                      /* nop                  */
609      0x8d,0xb4,0x00,0x00};                      /* lea 0w(%si),%si      */
610   static const char f16_6[] =
611     {0x89,0xf6,                                 /* mov %si,%si          */
612      0x8d,0xbd,0x00,0x00};                      /* lea 0w(%di),%di      */
613   static const char f16_7[] =
614     {0x8d,0x74,0x00,                            /* lea 0(%si),%si       */
615      0x8d,0xbd,0x00,0x00};                      /* lea 0w(%di),%di      */
616   static const char f16_8[] =
617     {0x8d,0xb4,0x00,0x00,                       /* lea 0w(%si),%si      */
618      0x8d,0xbd,0x00,0x00};                      /* lea 0w(%di),%di      */
619   static const char jump_31[] =
620     {0xeb,0x1d,0x90,0x90,0x90,0x90,0x90,        /* jmp .+31; lotsa nops */
621      0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,
622      0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,
623      0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90};
624   static const char *const f32_patt[] = {
625     f32_1, f32_2, f32_3, f32_4, f32_5, f32_6, f32_7, f32_8,
626     f32_9, f32_10, f32_11, f32_12, f32_13, f32_14
627   };
628   static const char *const f16_patt[] = {
629     f32_1, f32_2, f16_3, f16_4, f16_5, f16_6, f16_7, f16_8
630   };
631   /* nopl (%[re]ax) */
632   static const char alt_3[] =
633     {0x0f,0x1f,0x00};
634   /* nopl 0(%[re]ax) */
635   static const char alt_4[] =
636     {0x0f,0x1f,0x40,0x00};
637   /* nopl 0(%[re]ax,%[re]ax,1) */
638   static const char alt_5[] =
639     {0x0f,0x1f,0x44,0x00,0x00};
640   /* nopw 0(%[re]ax,%[re]ax,1) */
641   static const char alt_6[] =
642     {0x66,0x0f,0x1f,0x44,0x00,0x00};
643   /* nopl 0L(%[re]ax) */
644   static const char alt_7[] =
645     {0x0f,0x1f,0x80,0x00,0x00,0x00,0x00};
646   /* nopl 0L(%[re]ax,%[re]ax,1) */
647   static const char alt_8[] =
648     {0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
649   /* nopw 0L(%[re]ax,%[re]ax,1) */
650   static const char alt_9[] =
651     {0x66,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
652   /* nopw %cs:0L(%[re]ax,%[re]ax,1) */
653   static const char alt_10[] =
654     {0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
655   /* data16
656      nopw %cs:0L(%[re]ax,%[re]ax,1) */
657   static const char alt_long_11[] =
658     {0x66,
659      0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
660   /* data16
661      data16
662      nopw %cs:0L(%[re]ax,%[re]ax,1) */
663   static const char alt_long_12[] =
664     {0x66,
665      0x66,
666      0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
667   /* data16
668      data16
669      data16
670      nopw %cs:0L(%[re]ax,%[re]ax,1) */
671   static const char alt_long_13[] =
672     {0x66,
673      0x66,
674      0x66,
675      0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
676   /* data16
677      data16
678      data16
679      data16
680      nopw %cs:0L(%[re]ax,%[re]ax,1) */
681   static const char alt_long_14[] =
682     {0x66,
683      0x66,
684      0x66,
685      0x66,
686      0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
687   /* data16
688      data16
689      data16
690      data16
691      data16
692      nopw %cs:0L(%[re]ax,%[re]ax,1) */
693   static const char alt_long_15[] =
694     {0x66,
695      0x66,
696      0x66,
697      0x66,
698      0x66,
699      0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
700   /* nopl 0(%[re]ax,%[re]ax,1)
701      nopw 0(%[re]ax,%[re]ax,1) */
702   static const char alt_short_11[] =
703     {0x0f,0x1f,0x44,0x00,0x00,
704      0x66,0x0f,0x1f,0x44,0x00,0x00};
705   /* nopw 0(%[re]ax,%[re]ax,1)
706      nopw 0(%[re]ax,%[re]ax,1) */
707   static const char alt_short_12[] =
708     {0x66,0x0f,0x1f,0x44,0x00,0x00,
709      0x66,0x0f,0x1f,0x44,0x00,0x00};
710   /* nopw 0(%[re]ax,%[re]ax,1)
711      nopl 0L(%[re]ax) */
712   static const char alt_short_13[] =
713     {0x66,0x0f,0x1f,0x44,0x00,0x00,
714      0x0f,0x1f,0x80,0x00,0x00,0x00,0x00};
715   /* nopl 0L(%[re]ax)
716      nopl 0L(%[re]ax) */
717   static const char alt_short_14[] =
718     {0x0f,0x1f,0x80,0x00,0x00,0x00,0x00,
719      0x0f,0x1f,0x80,0x00,0x00,0x00,0x00};
720   /* nopl 0L(%[re]ax)
721      nopl 0L(%[re]ax,%[re]ax,1) */
722   static const char alt_short_15[] =
723     {0x0f,0x1f,0x80,0x00,0x00,0x00,0x00,
724      0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
725   static const char *const alt_short_patt[] = {
726     f32_1, f32_2, alt_3, alt_4, alt_5, alt_6, alt_7, alt_8,
727     alt_9, alt_10, alt_short_11, alt_short_12, alt_short_13,
728     alt_short_14, alt_short_15
729   };
730   static const char *const alt_long_patt[] = {
731     f32_1, f32_2, alt_3, alt_4, alt_5, alt_6, alt_7, alt_8,
732     alt_9, alt_10, alt_long_11, alt_long_12, alt_long_13,
733     alt_long_14, alt_long_15
734   };
735
736   /* Only align for at least a positive non-zero boundary. */
737   if (count <= 0 || count > MAX_MEM_FOR_RS_ALIGN_CODE)
738     return;
739
740   /* We need to decide which NOP sequence to use for 32bit and
741      64bit. When -mtune= is used:
742
743      1. For PROCESSOR_I386, PROCESSOR_I486, PROCESSOR_PENTIUM and
744      PROCESSOR_GENERIC32, f32_patt will be used.
745      2. For PROCESSOR_PENTIUMPRO, PROCESSOR_PENTIUM4, PROCESSOR_NOCONA,
746      PROCESSOR_CORE, PROCESSOR_CORE2, and PROCESSOR_GENERIC64,
747      alt_long_patt will be used.
748      3. For PROCESSOR_ATHLON, PROCESSOR_K6, PROCESSOR_K8 and
749      PROCESSOR_AMDFAM10, alt_short_patt will be used.
750
751      When -mtune= isn't used, alt_long_patt will be used if
752      cpu_arch_isa_flags has Cpu686. Otherwise, f32_patt will
753      be used.
754
755      When -march= or .arch is used, we can't use anything beyond
756      cpu_arch_isa_flags.   */
757
758   if (flag_code == CODE_16BIT)
759     {
760       if (count > 8)
761         {
762           memcpy (fragP->fr_literal + fragP->fr_fix,
763                   jump_31, count);
764           /* Adjust jump offset.  */
765           fragP->fr_literal[fragP->fr_fix + 1] = count - 2;
766         }
767       else
768         memcpy (fragP->fr_literal + fragP->fr_fix,
769                 f16_patt[count - 1], count);
770     }
771   else
772     {
773       const char *const *patt = NULL;
774
775       if (cpu_arch_isa == PROCESSOR_UNKNOWN)
776         {
777           /* PROCESSOR_UNKNOWN means that all ISAs may be used.  */
778           switch (cpu_arch_tune)
779             {
780             case PROCESSOR_UNKNOWN:
781               /* We use cpu_arch_isa_flags to check if we SHOULD
782                  optimize for Cpu686.  */
783               if (cpu_arch_isa_flags.bitfield.cpui686)
784                 patt = alt_long_patt;
785               else
786                 patt = f32_patt;
787               break;
788             case PROCESSOR_PENTIUMPRO:
789             case PROCESSOR_PENTIUM4:
790             case PROCESSOR_NOCONA:
791             case PROCESSOR_CORE:
792             case PROCESSOR_CORE2:
793             case PROCESSOR_GENERIC64:
794               patt = alt_long_patt;
795               break;
796             case PROCESSOR_K6:
797             case PROCESSOR_ATHLON:
798             case PROCESSOR_K8:
799             case PROCESSOR_AMDFAM10:
800               patt = alt_short_patt;
801               break;
802             case PROCESSOR_I386:
803             case PROCESSOR_I486:
804             case PROCESSOR_PENTIUM:
805             case PROCESSOR_GENERIC32:
806               patt = f32_patt;
807               break;
808             }
809         }
810       else
811         {
812           switch (cpu_arch_tune)
813             {
814             case PROCESSOR_UNKNOWN:
815               /* When cpu_arch_isa is net, cpu_arch_tune shouldn't be
816                  PROCESSOR_UNKNOWN.  */
817               abort ();
818               break;
819
820             case PROCESSOR_I386:
821             case PROCESSOR_I486:
822             case PROCESSOR_PENTIUM:
823             case PROCESSOR_K6:
824             case PROCESSOR_ATHLON:
825             case PROCESSOR_K8:
826             case PROCESSOR_AMDFAM10:
827             case PROCESSOR_GENERIC32:
828               /* We use cpu_arch_isa_flags to check if we CAN optimize
829                  for Cpu686.  */
830               if (cpu_arch_isa_flags.bitfield.cpui686)
831                 patt = alt_short_patt;
832               else
833                 patt = f32_patt;
834               break;
835             case PROCESSOR_PENTIUMPRO:
836             case PROCESSOR_PENTIUM4:
837             case PROCESSOR_NOCONA:
838             case PROCESSOR_CORE:
839             case PROCESSOR_CORE2:
840               if (cpu_arch_isa_flags.bitfield.cpui686)
841                 patt = alt_long_patt;
842               else
843                 patt = f32_patt;
844               break;
845             case PROCESSOR_GENERIC64:
846               patt = alt_long_patt;
847               break;
848             }
849         }
850
851       if (patt == f32_patt)
852         {
853           /* If the padding is less than 15 bytes, we use the normal
854              ones.  Otherwise, we use a jump instruction and adjust
855              its offset.  */
856           if (count < 15)
857             memcpy (fragP->fr_literal + fragP->fr_fix,
858                     patt[count - 1], count);
859           else
860             {
861               memcpy (fragP->fr_literal + fragP->fr_fix,
862                       jump_31, count);
863               /* Adjust jump offset.  */
864               fragP->fr_literal[fragP->fr_fix + 1] = count - 2;
865             }
866         }
867       else
868         {
869           /* Maximum length of an instruction is 15 byte.  If the
870              padding is greater than 15 bytes and we don't use jump,
871              we have to break it into smaller pieces.  */
872           int padding = count;
873           while (padding > 15)
874             {
875               padding -= 15;
876               memcpy (fragP->fr_literal + fragP->fr_fix + padding,
877                       patt [14], 15);
878             }
879
880           if (padding)
881             memcpy (fragP->fr_literal + fragP->fr_fix,
882                     patt [padding - 1], padding);
883         }
884     }
885   fragP->fr_var = count;
886 }
887
888 static INLINE int
889 uints_all_zero (const unsigned int *x, unsigned int size)
890 {
891   switch (size)
892     {
893     case 3:
894       if (x[2])
895         return 0;
896     case 2:
897       if (x[1])
898         return 0;
899     case 1:
900       return !x[0];
901     default:
902       abort ();
903     }
904 }
905
906 static INLINE void
907 uints_set (unsigned int *x, unsigned int v, unsigned int size)
908 {
909   switch (size)
910     {
911     case 3:
912       x[2] = v;
913     case 2:
914       x[1] = v;
915     case 1:
916       x[0] = v;
917       break;
918     default:
919       abort ();
920     }
921 }
922
923 static INLINE int
924 uints_equal (const unsigned int *x, const unsigned int *y,
925              unsigned int size)
926 {
927   switch (size)
928     {
929     case 3:
930       if (x[2] != y [2])
931         return 0;
932     case 2:
933       if (x[1] != y [1])
934         return 0;
935     case 1:
936       return x[0] == y [0];
937       break;
938     default:
939       abort ();
940     }
941 }
942
943 #define UINTS_ALL_ZERO(x) \
944   uints_all_zero ((x).array, ARRAY_SIZE ((x).array))
945 #define UINTS_SET(x, v) \
946   uints_set ((x).array, v, ARRAY_SIZE ((x).array))
947 #define UINTS_CLEAR(x) \
948   uints_set ((x).array, 0, ARRAY_SIZE ((x).array))
949 #define UINTS_EQUAL(x, y) \
950   uints_equal ((x).array, (y).array, ARRAY_SIZE ((x).array))
951
952 static INLINE int
953 cpu_flags_check_cpu64 (i386_cpu_flags f)
954 {
955   return !((flag_code == CODE_64BIT && f.bitfield.cpuno64)
956            || (flag_code != CODE_64BIT && f.bitfield.cpu64));
957 }
958
959 static INLINE i386_cpu_flags
960 cpu_flags_not (i386_cpu_flags x)
961 {
962   switch (ARRAY_SIZE (x.array))
963     {
964     case 3:
965       x.array [2] = ~x.array [2];
966     case 2:
967       x.array [1] = ~x.array [1];
968     case 1:
969       x.array [0] = ~x.array [0];
970       break;
971     default:
972       abort ();
973     }
974
975 #ifdef CpuUnused
976   x.bitfield.unused = 0;
977 #endif
978
979   return x;
980 }
981
982 static INLINE i386_cpu_flags
983 cpu_flags_and (i386_cpu_flags x, i386_cpu_flags y)
984 {
985   switch (ARRAY_SIZE (x.array))
986     {
987     case 3:
988       x.array [2] &= y.array [2];
989     case 2:
990       x.array [1] &= y.array [1];
991     case 1:
992       x.array [0] &= y.array [0];
993       break;
994     default:
995       abort ();
996     }
997   return x;
998 }
999
1000 static INLINE i386_cpu_flags
1001 cpu_flags_or (i386_cpu_flags x, i386_cpu_flags y)
1002 {
1003   switch (ARRAY_SIZE (x.array))
1004     {
1005     case 3:
1006       x.array [2] |= y.array [2];
1007     case 2:
1008       x.array [1] |= y.array [1];
1009     case 1:
1010       x.array [0] |= y.array [0];
1011       break;
1012     default:
1013       abort ();
1014     }
1015   return x;
1016 }
1017
1018 static int
1019 cpu_flags_match (i386_cpu_flags x)
1020 {
1021   i386_cpu_flags not = cpu_arch_flags_not;
1022
1023   not.bitfield.cpu64 = 1;
1024   not.bitfield.cpuno64 = 1;
1025
1026   x.bitfield.cpu64 = 0;
1027   x.bitfield.cpuno64 = 0;
1028
1029   not = cpu_flags_and (x, not);
1030   return UINTS_ALL_ZERO (not);
1031 }
1032
1033 static INLINE i386_operand_type
1034 operand_type_and (i386_operand_type x, i386_operand_type y)
1035 {
1036   switch (ARRAY_SIZE (x.array))
1037     {
1038     case 3:
1039       x.array [2] &= y.array [2];
1040     case 2:
1041       x.array [1] &= y.array [1];
1042     case 1:
1043       x.array [0] &= y.array [0];
1044       break;
1045     default:
1046       abort ();
1047     }
1048   return x;
1049 }
1050
1051 static INLINE i386_operand_type
1052 operand_type_or (i386_operand_type x, i386_operand_type y)
1053 {
1054   switch (ARRAY_SIZE (x.array))
1055     {
1056     case 3:
1057       x.array [2] |= y.array [2];
1058     case 2:
1059       x.array [1] |= y.array [1];
1060     case 1:
1061       x.array [0] |= y.array [0];
1062       break;
1063     default:
1064       abort ();
1065     }
1066   return x;
1067 }
1068
1069 static INLINE i386_operand_type
1070 operand_type_xor (i386_operand_type x, i386_operand_type y)
1071 {
1072   switch (ARRAY_SIZE (x.array))
1073     {
1074     case 3:
1075       x.array [2] ^= y.array [2];
1076     case 2:
1077       x.array [1] ^= y.array [1];
1078     case 1:
1079       x.array [0] ^= y.array [0];
1080       break;
1081     default:
1082       abort ();
1083     }
1084   return x;
1085 }
1086
1087 static const i386_operand_type acc32 = OPERAND_TYPE_ACC32;
1088 static const i386_operand_type acc64 = OPERAND_TYPE_ACC64;
1089 static const i386_operand_type control = OPERAND_TYPE_CONTROL;
1090 static const i386_operand_type reg16_inoutportreg
1091   = OPERAND_TYPE_REG16_INOUTPORTREG;
1092 static const i386_operand_type disp16 = OPERAND_TYPE_DISP16;
1093 static const i386_operand_type disp32 = OPERAND_TYPE_DISP32;
1094 static const i386_operand_type disp32s = OPERAND_TYPE_DISP32S;
1095 static const i386_operand_type disp16_32 = OPERAND_TYPE_DISP16_32;
1096 static const i386_operand_type anydisp
1097   = OPERAND_TYPE_ANYDISP;
1098 static const i386_operand_type regxmm = OPERAND_TYPE_REGXMM;
1099 static const i386_operand_type imm8 = OPERAND_TYPE_IMM8;
1100 static const i386_operand_type imm8s = OPERAND_TYPE_IMM8S;
1101 static const i386_operand_type imm16 = OPERAND_TYPE_IMM16;
1102 static const i386_operand_type imm32 = OPERAND_TYPE_IMM32;
1103 static const i386_operand_type imm32s = OPERAND_TYPE_IMM32S;
1104 static const i386_operand_type imm64 = OPERAND_TYPE_IMM64;
1105 static const i386_operand_type imm16_32 = OPERAND_TYPE_IMM16_32;
1106 static const i386_operand_type imm16_32s = OPERAND_TYPE_IMM16_32S;
1107 static const i386_operand_type imm16_32_32s = OPERAND_TYPE_IMM16_32_32S;
1108
1109 enum operand_type
1110 {
1111   reg,
1112   imm,
1113   disp,
1114   anymem
1115 };
1116
1117 static INLINE int
1118 operand_type_check (i386_operand_type t, enum operand_type c)
1119 {
1120   switch (c)
1121     {
1122     case reg:
1123       return (t.bitfield.reg8
1124               || t.bitfield.reg16
1125               || t.bitfield.reg32
1126               || t.bitfield.reg64);
1127
1128     case imm:
1129       return (t.bitfield.imm8
1130               || t.bitfield.imm8s
1131               || t.bitfield.imm16
1132               || t.bitfield.imm32
1133               || t.bitfield.imm32s
1134               || t.bitfield.imm64);
1135
1136     case disp:
1137       return (t.bitfield.disp8
1138               || t.bitfield.disp16
1139               || t.bitfield.disp32
1140               || t.bitfield.disp32s
1141               || t.bitfield.disp64);
1142
1143     case anymem:
1144       return (t.bitfield.disp8
1145               || t.bitfield.disp16
1146               || t.bitfield.disp32
1147               || t.bitfield.disp32s
1148               || t.bitfield.disp64
1149               || t.bitfield.baseindex);
1150
1151     default:
1152       abort ();
1153     }
1154 }
1155
1156 static INLINE int
1157 operand_type_match (i386_operand_type overlap,
1158                     i386_operand_type given)
1159 {
1160   i386_operand_type temp = overlap;
1161
1162   temp.bitfield.jumpabsolute = 0;
1163   if (UINTS_ALL_ZERO (temp))
1164     return 0;
1165
1166   return (given.bitfield.baseindex == overlap.bitfield.baseindex
1167           && given.bitfield.jumpabsolute == overlap.bitfield.jumpabsolute);
1168 }
1169
1170 /* If given types r0 and r1 are registers they must be of the same type
1171    unless the expected operand type register overlap is null.
1172    Note that Acc in a template matches every size of reg.  */
1173
1174 static INLINE int
1175 operand_type_register_match (i386_operand_type m0,
1176                              i386_operand_type g0,
1177                              i386_operand_type t0,
1178                              i386_operand_type m1,
1179                              i386_operand_type g1,
1180                              i386_operand_type t1)
1181 {
1182   if (!operand_type_check (g0, reg))
1183     return 1;
1184
1185   if (!operand_type_check (g1, reg))
1186     return 1;
1187
1188   if (g0.bitfield.reg8 == g1.bitfield.reg8
1189       && g0.bitfield.reg16 == g1.bitfield.reg16
1190       && g0.bitfield.reg32 == g1.bitfield.reg32
1191       && g0.bitfield.reg64 == g1.bitfield.reg64)
1192     return 1;
1193
1194   if (m0.bitfield.acc)
1195     {
1196       t0.bitfield.reg8 = 1;
1197       t0.bitfield.reg16 = 1;
1198       t0.bitfield.reg32 = 1;
1199       t0.bitfield.reg64 = 1;
1200     }
1201
1202   if (m1.bitfield.acc)
1203     {
1204       t1.bitfield.reg8 = 1;
1205       t1.bitfield.reg16 = 1;
1206       t1.bitfield.reg32 = 1;
1207       t1.bitfield.reg64 = 1;
1208     }
1209
1210   return (!(t0.bitfield.reg8 & t1.bitfield.reg8)
1211           && !(t0.bitfield.reg16 & t1.bitfield.reg16)
1212           && !(t0.bitfield.reg32 & t1.bitfield.reg32)
1213           && !(t0.bitfield.reg64 & t1.bitfield.reg64));
1214 }
1215
1216 static INLINE unsigned int
1217 mode_from_disp_size (i386_operand_type t)
1218 {
1219   if (t.bitfield.disp8)
1220     return 1;
1221   else if (t.bitfield.disp16
1222            || t.bitfield.disp32
1223            || t.bitfield.disp32s)
1224     return 2;
1225   else
1226     return 0;
1227 }
1228
1229 static INLINE int
1230 fits_in_signed_byte (offsetT num)
1231 {
1232   return (num >= -128) && (num <= 127);
1233 }
1234
1235 static INLINE int
1236 fits_in_unsigned_byte (offsetT num)
1237 {
1238   return (num & 0xff) == num;
1239 }
1240
1241 static INLINE int
1242 fits_in_unsigned_word (offsetT num)
1243 {
1244   return (num & 0xffff) == num;
1245 }
1246
1247 static INLINE int
1248 fits_in_signed_word (offsetT num)
1249 {
1250   return (-32768 <= num) && (num <= 32767);
1251 }
1252
1253 static INLINE int
1254 fits_in_signed_long (offsetT num ATTRIBUTE_UNUSED)
1255 {
1256 #ifndef BFD64
1257   return 1;
1258 #else
1259   return (!(((offsetT) -1 << 31) & num)
1260           || (((offsetT) -1 << 31) & num) == ((offsetT) -1 << 31));
1261 #endif
1262 }                               /* fits_in_signed_long() */
1263
1264 static INLINE int
1265 fits_in_unsigned_long (offsetT num ATTRIBUTE_UNUSED)
1266 {
1267 #ifndef BFD64
1268   return 1;
1269 #else
1270   return (num & (((offsetT) 2 << 31) - 1)) == num;
1271 #endif
1272 }                               /* fits_in_unsigned_long() */
1273
1274 static i386_operand_type
1275 smallest_imm_type (offsetT num)
1276 {
1277   i386_operand_type t;
1278  
1279   UINTS_CLEAR (t);
1280   t.bitfield.imm64 = 1;
1281
1282   if (cpu_arch_tune != PROCESSOR_I486 && num == 1)
1283     {
1284       /* This code is disabled on the 486 because all the Imm1 forms
1285          in the opcode table are slower on the i486.  They're the
1286          versions with the implicitly specified single-position
1287          displacement, which has another syntax if you really want to
1288          use that form.  */
1289       t.bitfield.imm1 = 1;
1290       t.bitfield.imm8 = 1;
1291       t.bitfield.imm8s = 1;
1292       t.bitfield.imm16 = 1;
1293       t.bitfield.imm32 = 1;
1294       t.bitfield.imm32s = 1;
1295     }
1296   else if (fits_in_signed_byte (num))
1297     {
1298       t.bitfield.imm8 = 1;
1299       t.bitfield.imm8s = 1;
1300       t.bitfield.imm16 = 1;
1301       t.bitfield.imm32 = 1;
1302       t.bitfield.imm32s = 1;
1303     }
1304   else if (fits_in_unsigned_byte (num))
1305     {
1306       t.bitfield.imm8 = 1;
1307       t.bitfield.imm16 = 1;
1308       t.bitfield.imm32 = 1;
1309       t.bitfield.imm32s = 1;
1310     }
1311   else if (fits_in_signed_word (num) || fits_in_unsigned_word (num))
1312     {
1313       t.bitfield.imm16 = 1;
1314       t.bitfield.imm32 = 1;
1315       t.bitfield.imm32s = 1;
1316     }
1317   else if (fits_in_signed_long (num))
1318     {
1319       t.bitfield.imm32 = 1;
1320       t.bitfield.imm32s = 1;
1321     }
1322   else if (fits_in_unsigned_long (num))
1323     t.bitfield.imm32 = 1;
1324
1325   return t;
1326 }
1327
1328 static offsetT
1329 offset_in_range (offsetT val, int size)
1330 {
1331   addressT mask;
1332
1333   switch (size)
1334     {
1335     case 1: mask = ((addressT) 1 <<  8) - 1; break;
1336     case 2: mask = ((addressT) 1 << 16) - 1; break;
1337     case 4: mask = ((addressT) 2 << 31) - 1; break;
1338 #ifdef BFD64
1339     case 8: mask = ((addressT) 2 << 63) - 1; break;
1340 #endif
1341     default: abort ();
1342     }
1343
1344   /* If BFD64, sign extend val.  */
1345   if (!use_rela_relocations)
1346     if ((val & ~(((addressT) 2 << 31) - 1)) == 0)
1347       val = (val ^ ((addressT) 1 << 31)) - ((addressT) 1 << 31);
1348
1349   if ((val & ~mask) != 0 && (val & ~mask) != ~mask)
1350     {
1351       char buf1[40], buf2[40];
1352
1353       sprint_value (buf1, val);
1354       sprint_value (buf2, val & mask);
1355       as_warn (_("%s shortened to %s"), buf1, buf2);
1356     }
1357   return val & mask;
1358 }
1359
1360 /* Returns 0 if attempting to add a prefix where one from the same
1361    class already exists, 1 if non rep/repne added, 2 if rep/repne
1362    added.  */
1363 static int
1364 add_prefix (unsigned int prefix)
1365 {
1366   int ret = 1;
1367   unsigned int q;
1368
1369   if (prefix >= REX_OPCODE && prefix < REX_OPCODE + 16
1370       && flag_code == CODE_64BIT)
1371     {
1372       if ((i.prefix[REX_PREFIX] & prefix & REX_W)
1373           || ((i.prefix[REX_PREFIX] & (REX_R | REX_X | REX_B))
1374               && (prefix & (REX_R | REX_X | REX_B))))
1375         ret = 0;
1376       q = REX_PREFIX;
1377     }
1378   else
1379     {
1380       switch (prefix)
1381         {
1382         default:
1383           abort ();
1384
1385         case CS_PREFIX_OPCODE:
1386         case DS_PREFIX_OPCODE:
1387         case ES_PREFIX_OPCODE:
1388         case FS_PREFIX_OPCODE:
1389         case GS_PREFIX_OPCODE:
1390         case SS_PREFIX_OPCODE:
1391           q = SEG_PREFIX;
1392           break;
1393
1394         case REPNE_PREFIX_OPCODE:
1395         case REPE_PREFIX_OPCODE:
1396           ret = 2;
1397           /* fall thru */
1398         case LOCK_PREFIX_OPCODE:
1399           q = LOCKREP_PREFIX;
1400           break;
1401
1402         case FWAIT_OPCODE:
1403           q = WAIT_PREFIX;
1404           break;
1405
1406         case ADDR_PREFIX_OPCODE:
1407           q = ADDR_PREFIX;
1408           break;
1409
1410         case DATA_PREFIX_OPCODE:
1411           q = DATA_PREFIX;
1412           break;
1413         }
1414       if (i.prefix[q] != 0)
1415         ret = 0;
1416     }
1417
1418   if (ret)
1419     {
1420       if (!i.prefix[q])
1421         ++i.prefixes;
1422       i.prefix[q] |= prefix;
1423     }
1424   else
1425     as_bad (_("same type of prefix used twice"));
1426
1427   return ret;
1428 }
1429
1430 static void
1431 set_code_flag (int value)
1432 {
1433   flag_code = value;
1434   if (flag_code == CODE_64BIT)
1435     {
1436       cpu_arch_flags.bitfield.cpu64 = 1;
1437       cpu_arch_flags.bitfield.cpuno64 = 0;
1438       cpu_arch_flags_not.bitfield.cpu64 = 0;
1439       cpu_arch_flags_not.bitfield.cpuno64 = 1;
1440     }
1441   else
1442     {
1443       cpu_arch_flags.bitfield.cpu64 = 0;
1444       cpu_arch_flags.bitfield.cpuno64 = 1;
1445       cpu_arch_flags_not.bitfield.cpu64 = 1;
1446       cpu_arch_flags_not.bitfield.cpuno64 = 0;
1447     }
1448   if (value == CODE_64BIT && !cpu_arch_flags.bitfield.cpulm )
1449     {
1450       as_bad (_("64bit mode not supported on this CPU."));
1451     }
1452   if (value == CODE_32BIT && !cpu_arch_flags.bitfield.cpui386)
1453     {
1454       as_bad (_("32bit mode not supported on this CPU."));
1455     }
1456   stackop_size = '\0';
1457 }
1458
1459 static void
1460 set_16bit_gcc_code_flag (int new_code_flag)
1461 {
1462   flag_code = new_code_flag;
1463   if (flag_code != CODE_16BIT)
1464     abort ();
1465   cpu_arch_flags.bitfield.cpu64 = 0;
1466   cpu_arch_flags.bitfield.cpuno64 = 1;
1467   cpu_arch_flags_not.bitfield.cpu64 = 1;
1468   cpu_arch_flags_not.bitfield.cpuno64 = 0;
1469   stackop_size = LONG_MNEM_SUFFIX;
1470 }
1471
1472 static void
1473 set_intel_syntax (int syntax_flag)
1474 {
1475   /* Find out if register prefixing is specified.  */
1476   int ask_naked_reg = 0;
1477
1478   SKIP_WHITESPACE ();
1479   if (!is_end_of_line[(unsigned char) *input_line_pointer])
1480     {
1481       char *string = input_line_pointer;
1482       int e = get_symbol_end ();
1483
1484       if (strcmp (string, "prefix") == 0)
1485         ask_naked_reg = 1;
1486       else if (strcmp (string, "noprefix") == 0)
1487         ask_naked_reg = -1;
1488       else
1489         as_bad (_("bad argument to syntax directive."));
1490       *input_line_pointer = e;
1491     }
1492   demand_empty_rest_of_line ();
1493
1494   intel_syntax = syntax_flag;
1495
1496   if (ask_naked_reg == 0)
1497     allow_naked_reg = (intel_syntax
1498                        && (bfd_get_symbol_leading_char (stdoutput) != '\0'));
1499   else
1500     allow_naked_reg = (ask_naked_reg < 0);
1501
1502   identifier_chars['%'] = intel_syntax && allow_naked_reg ? '%' : 0;
1503   identifier_chars['$'] = intel_syntax ? '$' : 0;
1504   register_prefix = allow_naked_reg ? "" : "%";
1505 }
1506
1507 static void
1508 set_allow_index_reg (int flag)
1509 {
1510   allow_index_reg = flag;
1511 }
1512
1513 static void
1514 set_cpu_arch (int dummy ATTRIBUTE_UNUSED)
1515 {
1516   SKIP_WHITESPACE ();
1517
1518   if (!is_end_of_line[(unsigned char) *input_line_pointer])
1519     {
1520       char *string = input_line_pointer;
1521       int e = get_symbol_end ();
1522       unsigned int i;
1523       i386_cpu_flags flags;
1524
1525       for (i = 0; i < ARRAY_SIZE (cpu_arch); i++)
1526         {
1527           if (strcmp (string, cpu_arch[i].name) == 0)
1528             {
1529               if (*string != '.')
1530                 {
1531                   cpu_arch_name = cpu_arch[i].name;
1532                   cpu_sub_arch_name = NULL;
1533                   cpu_arch_flags = cpu_arch[i].flags;
1534                   if (flag_code == CODE_64BIT)
1535                     {
1536                       cpu_arch_flags.bitfield.cpu64 = 1;
1537                       cpu_arch_flags.bitfield.cpuno64 = 0;
1538                     }
1539                   else
1540                     {
1541                       cpu_arch_flags.bitfield.cpu64 = 0;
1542                       cpu_arch_flags.bitfield.cpuno64 = 1;
1543                     }
1544                   cpu_arch_flags_not = cpu_flags_not (cpu_arch_flags);
1545                   cpu_arch_isa = cpu_arch[i].type;
1546                   cpu_arch_isa_flags = cpu_arch[i].flags;
1547                   if (!cpu_arch_tune_set)
1548                     {
1549                       cpu_arch_tune = cpu_arch_isa;
1550                       cpu_arch_tune_flags = cpu_arch_isa_flags;
1551                     }
1552                   break;
1553                 }
1554
1555               flags = cpu_flags_or (cpu_arch_flags,
1556                                     cpu_arch[i].flags);
1557               if (!UINTS_EQUAL (flags, cpu_arch_flags))
1558                 {
1559                   cpu_sub_arch_name = cpu_arch[i].name;
1560                   cpu_arch_flags = flags;
1561                   cpu_arch_flags_not = cpu_flags_not (cpu_arch_flags);
1562                 }
1563               *input_line_pointer = e;
1564               demand_empty_rest_of_line ();
1565               return;
1566             }
1567         }
1568       if (i >= ARRAY_SIZE (cpu_arch))
1569         as_bad (_("no such architecture: `%s'"), string);
1570
1571       *input_line_pointer = e;
1572     }
1573   else
1574     as_bad (_("missing cpu architecture"));
1575
1576   no_cond_jump_promotion = 0;
1577   if (*input_line_pointer == ','
1578       && !is_end_of_line[(unsigned char) input_line_pointer[1]])
1579     {
1580       char *string = ++input_line_pointer;
1581       int e = get_symbol_end ();
1582
1583       if (strcmp (string, "nojumps") == 0)
1584         no_cond_jump_promotion = 1;
1585       else if (strcmp (string, "jumps") == 0)
1586         ;
1587       else
1588         as_bad (_("no such architecture modifier: `%s'"), string);
1589
1590       *input_line_pointer = e;
1591     }
1592
1593   demand_empty_rest_of_line ();
1594 }
1595
1596 unsigned long
1597 i386_mach ()
1598 {
1599   if (!strcmp (default_arch, "x86_64"))
1600     return bfd_mach_x86_64;
1601   else if (!strcmp (default_arch, "i386"))
1602     return bfd_mach_i386_i386;
1603   else
1604     as_fatal (_("Unknown architecture"));
1605 }
1606 \f
1607 void
1608 md_begin ()
1609 {
1610   const char *hash_err;
1611
1612   cpu_arch_flags_not = cpu_flags_not (cpu_arch_flags);
1613
1614   /* Initialize op_hash hash table.  */
1615   op_hash = hash_new ();
1616
1617   {
1618     const template *optab;
1619     templates *core_optab;
1620
1621     /* Setup for loop.  */
1622     optab = i386_optab;
1623     core_optab = (templates *) xmalloc (sizeof (templates));
1624     core_optab->start = optab;
1625
1626     while (1)
1627       {
1628         ++optab;
1629         if (optab->name == NULL
1630             || strcmp (optab->name, (optab - 1)->name) != 0)
1631           {
1632             /* different name --> ship out current template list;
1633                add to hash table; & begin anew.  */
1634             core_optab->end = optab;
1635             hash_err = hash_insert (op_hash,
1636                                     (optab - 1)->name,
1637                                     (PTR) core_optab);
1638             if (hash_err)
1639               {
1640                 as_fatal (_("Internal Error:  Can't hash %s: %s"),
1641                           (optab - 1)->name,
1642                           hash_err);
1643               }
1644             if (optab->name == NULL)
1645               break;
1646             core_optab = (templates *) xmalloc (sizeof (templates));
1647             core_optab->start = optab;
1648           }
1649       }
1650   }
1651
1652   /* Initialize reg_hash hash table.  */
1653   reg_hash = hash_new ();
1654   {
1655     const reg_entry *regtab;
1656     unsigned int regtab_size = i386_regtab_size;
1657
1658     for (regtab = i386_regtab; regtab_size--; regtab++)
1659       {
1660         hash_err = hash_insert (reg_hash, regtab->reg_name, (PTR) regtab);
1661         if (hash_err)
1662           as_fatal (_("Internal Error:  Can't hash %s: %s"),
1663                     regtab->reg_name,
1664                     hash_err);
1665       }
1666   }
1667
1668   /* Fill in lexical tables:  mnemonic_chars, operand_chars.  */
1669   {
1670     int c;
1671     char *p;
1672
1673     for (c = 0; c < 256; c++)
1674       {
1675         if (ISDIGIT (c))
1676           {
1677             digit_chars[c] = c;
1678             mnemonic_chars[c] = c;
1679             register_chars[c] = c;
1680             operand_chars[c] = c;
1681           }
1682         else if (ISLOWER (c))
1683           {
1684             mnemonic_chars[c] = c;
1685             register_chars[c] = c;
1686             operand_chars[c] = c;
1687           }
1688         else if (ISUPPER (c))
1689           {
1690             mnemonic_chars[c] = TOLOWER (c);
1691             register_chars[c] = mnemonic_chars[c];
1692             operand_chars[c] = c;
1693           }
1694
1695         if (ISALPHA (c) || ISDIGIT (c))
1696           identifier_chars[c] = c;
1697         else if (c >= 128)
1698           {
1699             identifier_chars[c] = c;
1700             operand_chars[c] = c;
1701           }
1702       }
1703
1704 #ifdef LEX_AT
1705     identifier_chars['@'] = '@';
1706 #endif
1707 #ifdef LEX_QM
1708     identifier_chars['?'] = '?';
1709     operand_chars['?'] = '?';
1710 #endif
1711     digit_chars['-'] = '-';
1712     mnemonic_chars['-'] = '-';
1713     mnemonic_chars['.'] = '.';
1714     identifier_chars['_'] = '_';
1715     identifier_chars['.'] = '.';
1716
1717     for (p = operand_special_chars; *p != '\0'; p++)
1718       operand_chars[(unsigned char) *p] = *p;
1719   }
1720
1721 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
1722   if (IS_ELF)
1723     {
1724       record_alignment (text_section, 2);
1725       record_alignment (data_section, 2);
1726       record_alignment (bss_section, 2);
1727     }
1728 #endif
1729
1730   if (flag_code == CODE_64BIT)
1731     {
1732       x86_dwarf2_return_column = 16;
1733       x86_cie_data_alignment = -8;
1734     }
1735   else
1736     {
1737       x86_dwarf2_return_column = 8;
1738       x86_cie_data_alignment = -4;
1739     }
1740 }
1741
1742 void
1743 i386_print_statistics (FILE *file)
1744 {
1745   hash_print_statistics (file, "i386 opcode", op_hash);
1746   hash_print_statistics (file, "i386 register", reg_hash);
1747 }
1748 \f
1749 #ifdef DEBUG386
1750
1751 /* Debugging routines for md_assemble.  */
1752 static void pte (template *);
1753 static void pt (i386_operand_type);
1754 static void pe (expressionS *);
1755 static void ps (symbolS *);
1756
1757 static void
1758 pi (char *line, i386_insn *x)
1759 {
1760   unsigned int i;
1761
1762   fprintf (stdout, "%s: template ", line);
1763   pte (&x->tm);
1764   fprintf (stdout, "  address: base %s  index %s  scale %x\n",
1765            x->base_reg ? x->base_reg->reg_name : "none",
1766            x->index_reg ? x->index_reg->reg_name : "none",
1767            x->log2_scale_factor);
1768   fprintf (stdout, "  modrm:  mode %x  reg %x  reg/mem %x\n",
1769            x->rm.mode, x->rm.reg, x->rm.regmem);
1770   fprintf (stdout, "  sib:  base %x  index %x  scale %x\n",
1771            x->sib.base, x->sib.index, x->sib.scale);
1772   fprintf (stdout, "  rex: 64bit %x  extX %x  extY %x  extZ %x\n",
1773            (x->rex & REX_W) != 0,
1774            (x->rex & REX_R) != 0,
1775            (x->rex & REX_X) != 0,
1776            (x->rex & REX_B) != 0);
1777   fprintf (stdout, "  drex:  reg %d rex 0x%x\n", 
1778            x->drex.reg, x->drex.rex);
1779   for (i = 0; i < x->operands; i++)
1780     {
1781       fprintf (stdout, "    #%d:  ", i + 1);
1782       pt (x->types[i]);
1783       fprintf (stdout, "\n");
1784       if (x->types[i].bitfield.reg8
1785           || x->types[i].bitfield.reg16
1786           || x->types[i].bitfield.reg32
1787           || x->types[i].bitfield.reg64
1788           || x->types[i].bitfield.regmmx
1789           || x->types[i].bitfield.regxmm
1790           || x->types[i].bitfield.sreg2
1791           || x->types[i].bitfield.sreg3
1792           || x->types[i].bitfield.control
1793           || x->types[i].bitfield.debug
1794           || x->types[i].bitfield.test)
1795         fprintf (stdout, "%s\n", x->op[i].regs->reg_name);
1796       if (operand_type_check (x->types[i], imm))
1797         pe (x->op[i].imms);
1798       if (operand_type_check (x->types[i], disp))
1799         pe (x->op[i].disps);
1800     }
1801 }
1802
1803 static void
1804 pte (template *t)
1805 {
1806   unsigned int i;
1807   fprintf (stdout, " %d operands ", t->operands);
1808   fprintf (stdout, "opcode %x ", t->base_opcode);
1809   if (t->extension_opcode != None)
1810     fprintf (stdout, "ext %x ", t->extension_opcode);
1811   if (t->opcode_modifier.d)
1812     fprintf (stdout, "D");
1813   if (t->opcode_modifier.w)
1814     fprintf (stdout, "W");
1815   fprintf (stdout, "\n");
1816   for (i = 0; i < t->operands; i++)
1817     {
1818       fprintf (stdout, "    #%d type ", i + 1);
1819       pt (t->operand_types[i]);
1820       fprintf (stdout, "\n");
1821     }
1822 }
1823
1824 static void
1825 pe (expressionS *e)
1826 {
1827   fprintf (stdout, "    operation     %d\n", e->X_op);
1828   fprintf (stdout, "    add_number    %ld (%lx)\n",
1829            (long) e->X_add_number, (long) e->X_add_number);
1830   if (e->X_add_symbol)
1831     {
1832       fprintf (stdout, "    add_symbol    ");
1833       ps (e->X_add_symbol);
1834       fprintf (stdout, "\n");
1835     }
1836   if (e->X_op_symbol)
1837     {
1838       fprintf (stdout, "    op_symbol    ");
1839       ps (e->X_op_symbol);
1840       fprintf (stdout, "\n");
1841     }
1842 }
1843
1844 static void
1845 ps (symbolS *s)
1846 {
1847   fprintf (stdout, "%s type %s%s",
1848            S_GET_NAME (s),
1849            S_IS_EXTERNAL (s) ? "EXTERNAL " : "",
1850            segment_name (S_GET_SEGMENT (s)));
1851 }
1852
1853 static struct type_name
1854   {
1855     i386_operand_type mask;
1856     const char *name;
1857   }
1858 const type_names[] =
1859 {
1860   { OPERAND_TYPE_REG8, "r8" },
1861   { OPERAND_TYPE_REG16, "r16" },
1862   { OPERAND_TYPE_REG32, "r32" },
1863   { OPERAND_TYPE_REG64, "r64" },
1864   { OPERAND_TYPE_IMM8, "i8" },
1865   { OPERAND_TYPE_IMM8, "i8s" },
1866   { OPERAND_TYPE_IMM16, "i16" },
1867   { OPERAND_TYPE_IMM32, "i32" },
1868   { OPERAND_TYPE_IMM32S, "i32s" },
1869   { OPERAND_TYPE_IMM64, "i64" },
1870   { OPERAND_TYPE_IMM1, "i1" },
1871   { OPERAND_TYPE_BASEINDEX, "BaseIndex" },
1872   { OPERAND_TYPE_DISP8, "d8" },
1873   { OPERAND_TYPE_DISP16, "d16" },
1874   { OPERAND_TYPE_DISP32, "d32" },
1875   { OPERAND_TYPE_DISP32S, "d32s" },
1876   { OPERAND_TYPE_DISP64, "d64" },
1877   { OPERAND_TYPE_INOUTPORTREG, "InOutPortReg" },
1878   { OPERAND_TYPE_SHIFTCOUNT, "ShiftCount" },
1879   { OPERAND_TYPE_CONTROL, "control reg" },
1880   { OPERAND_TYPE_TEST, "test reg" },
1881   { OPERAND_TYPE_DEBUG, "debug reg" },
1882   { OPERAND_TYPE_FLOATREG, "FReg" },
1883   { OPERAND_TYPE_FLOATACC, "FAcc" },
1884   { OPERAND_TYPE_SREG2, "SReg2" },
1885   { OPERAND_TYPE_SREG3, "SReg3" },
1886   { OPERAND_TYPE_ACC, "Acc" },
1887   { OPERAND_TYPE_JUMPABSOLUTE, "Jump Absolute" },
1888   { OPERAND_TYPE_REGMMX, "rMMX" },
1889   { OPERAND_TYPE_REGXMM, "rXMM" },
1890   { OPERAND_TYPE_ESSEG, "es" },
1891 };
1892
1893 static void
1894 pt (i386_operand_type t)
1895 {
1896   unsigned int j;
1897   i386_operand_type a;
1898
1899   for (j = 0; j < ARRAY_SIZE (type_names); j++)
1900     {
1901       a = operand_type_and (t, type_names[j].mask);
1902       if (!UINTS_ALL_ZERO (a))
1903         fprintf (stdout, "%s, ",  type_names[j].name);
1904     }
1905   fflush (stdout);
1906 }
1907
1908 #endif /* DEBUG386 */
1909 \f
1910 static bfd_reloc_code_real_type
1911 reloc (unsigned int size,
1912        int pcrel,
1913        int sign,
1914        bfd_reloc_code_real_type other)
1915 {
1916   if (other != NO_RELOC)
1917     {
1918       reloc_howto_type *reloc;
1919
1920       if (size == 8)
1921         switch (other)
1922           {
1923           case BFD_RELOC_X86_64_GOT32:
1924             return BFD_RELOC_X86_64_GOT64;
1925             break;
1926           case BFD_RELOC_X86_64_PLTOFF64:
1927             return BFD_RELOC_X86_64_PLTOFF64;
1928             break;
1929           case BFD_RELOC_X86_64_GOTPC32:
1930             other = BFD_RELOC_X86_64_GOTPC64;
1931             break;
1932           case BFD_RELOC_X86_64_GOTPCREL:
1933             other = BFD_RELOC_X86_64_GOTPCREL64;
1934             break;
1935           case BFD_RELOC_X86_64_TPOFF32:
1936             other = BFD_RELOC_X86_64_TPOFF64;
1937             break;
1938           case BFD_RELOC_X86_64_DTPOFF32:
1939             other = BFD_RELOC_X86_64_DTPOFF64;
1940             break;
1941           default:
1942             break;
1943           }
1944
1945       /* Sign-checking 4-byte relocations in 16-/32-bit code is pointless.  */
1946       if (size == 4 && flag_code != CODE_64BIT)
1947         sign = -1;
1948
1949       reloc = bfd_reloc_type_lookup (stdoutput, other);
1950       if (!reloc)
1951         as_bad (_("unknown relocation (%u)"), other);
1952       else if (size != bfd_get_reloc_size (reloc))
1953         as_bad (_("%u-byte relocation cannot be applied to %u-byte field"),
1954                 bfd_get_reloc_size (reloc),
1955                 size);
1956       else if (pcrel && !reloc->pc_relative)
1957         as_bad (_("non-pc-relative relocation for pc-relative field"));
1958       else if ((reloc->complain_on_overflow == complain_overflow_signed
1959                 && !sign)
1960                || (reloc->complain_on_overflow == complain_overflow_unsigned
1961                    && sign > 0))
1962         as_bad (_("relocated field and relocation type differ in signedness"));
1963       else
1964         return other;
1965       return NO_RELOC;
1966     }
1967
1968   if (pcrel)
1969     {
1970       if (!sign)
1971         as_bad (_("there are no unsigned pc-relative relocations"));
1972       switch (size)
1973         {
1974         case 1: return BFD_RELOC_8_PCREL;
1975         case 2: return BFD_RELOC_16_PCREL;
1976         case 4: return BFD_RELOC_32_PCREL;
1977         case 8: return BFD_RELOC_64_PCREL;
1978         }
1979       as_bad (_("cannot do %u byte pc-relative relocation"), size);
1980     }
1981   else
1982     {
1983       if (sign > 0)
1984         switch (size)
1985           {
1986           case 4: return BFD_RELOC_X86_64_32S;
1987           }
1988       else
1989         switch (size)
1990           {
1991           case 1: return BFD_RELOC_8;
1992           case 2: return BFD_RELOC_16;
1993           case 4: return BFD_RELOC_32;
1994           case 8: return BFD_RELOC_64;
1995           }
1996       as_bad (_("cannot do %s %u byte relocation"),
1997               sign > 0 ? "signed" : "unsigned", size);
1998     }
1999
2000   abort ();
2001   return BFD_RELOC_NONE;
2002 }
2003
2004 /* Here we decide which fixups can be adjusted to make them relative to
2005    the beginning of the section instead of the symbol.  Basically we need
2006    to make sure that the dynamic relocations are done correctly, so in
2007    some cases we force the original symbol to be used.  */
2008
2009 int
2010 tc_i386_fix_adjustable (fixS *fixP ATTRIBUTE_UNUSED)
2011 {
2012 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
2013   if (!IS_ELF)
2014     return 1;
2015
2016   /* Don't adjust pc-relative references to merge sections in 64-bit
2017      mode.  */
2018   if (use_rela_relocations
2019       && (S_GET_SEGMENT (fixP->fx_addsy)->flags & SEC_MERGE) != 0
2020       && fixP->fx_pcrel)
2021     return 0;
2022
2023   /* The x86_64 GOTPCREL are represented as 32bit PCrel relocations
2024      and changed later by validate_fix.  */
2025   if (GOT_symbol && fixP->fx_subsy == GOT_symbol
2026       && fixP->fx_r_type == BFD_RELOC_32_PCREL)
2027     return 0;
2028
2029   /* adjust_reloc_syms doesn't know about the GOT.  */
2030   if (fixP->fx_r_type == BFD_RELOC_386_GOTOFF
2031       || fixP->fx_r_type == BFD_RELOC_386_PLT32
2032       || fixP->fx_r_type == BFD_RELOC_386_GOT32
2033       || fixP->fx_r_type == BFD_RELOC_386_TLS_GD
2034       || fixP->fx_r_type == BFD_RELOC_386_TLS_LDM
2035       || fixP->fx_r_type == BFD_RELOC_386_TLS_LDO_32
2036       || fixP->fx_r_type == BFD_RELOC_386_TLS_IE_32
2037       || fixP->fx_r_type == BFD_RELOC_386_TLS_IE
2038       || fixP->fx_r_type == BFD_RELOC_386_TLS_GOTIE
2039       || fixP->fx_r_type == BFD_RELOC_386_TLS_LE_32
2040       || fixP->fx_r_type == BFD_RELOC_386_TLS_LE
2041       || fixP->fx_r_type == BFD_RELOC_386_TLS_GOTDESC
2042       || fixP->fx_r_type == BFD_RELOC_386_TLS_DESC_CALL
2043       || fixP->fx_r_type == BFD_RELOC_X86_64_PLT32
2044       || fixP->fx_r_type == BFD_RELOC_X86_64_GOT32
2045       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTPCREL
2046       || fixP->fx_r_type == BFD_RELOC_X86_64_TLSGD
2047       || fixP->fx_r_type == BFD_RELOC_X86_64_TLSLD
2048       || fixP->fx_r_type == BFD_RELOC_X86_64_DTPOFF32
2049       || fixP->fx_r_type == BFD_RELOC_X86_64_DTPOFF64
2050       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTTPOFF
2051       || fixP->fx_r_type == BFD_RELOC_X86_64_TPOFF32
2052       || fixP->fx_r_type == BFD_RELOC_X86_64_TPOFF64
2053       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTOFF64
2054       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTPC32_TLSDESC
2055       || fixP->fx_r_type == BFD_RELOC_X86_64_TLSDESC_CALL
2056       || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
2057       || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
2058     return 0;
2059 #endif
2060   return 1;
2061 }
2062
2063 static int
2064 intel_float_operand (const char *mnemonic)
2065 {
2066   /* Note that the value returned is meaningful only for opcodes with (memory)
2067      operands, hence the code here is free to improperly handle opcodes that
2068      have no operands (for better performance and smaller code). */
2069
2070   if (mnemonic[0] != 'f')
2071     return 0; /* non-math */
2072
2073   switch (mnemonic[1])
2074     {
2075     /* fclex, fdecstp, fdisi, femms, feni, fincstp, finit, fsetpm, and
2076        the fs segment override prefix not currently handled because no
2077        call path can make opcodes without operands get here */
2078     case 'i':
2079       return 2 /* integer op */;
2080     case 'l':
2081       if (mnemonic[2] == 'd' && (mnemonic[3] == 'c' || mnemonic[3] == 'e'))
2082         return 3; /* fldcw/fldenv */
2083       break;
2084     case 'n':
2085       if (mnemonic[2] != 'o' /* fnop */)
2086         return 3; /* non-waiting control op */
2087       break;
2088     case 'r':
2089       if (mnemonic[2] == 's')
2090         return 3; /* frstor/frstpm */
2091       break;
2092     case 's':
2093       if (mnemonic[2] == 'a')
2094         return 3; /* fsave */
2095       if (mnemonic[2] == 't')
2096         {
2097           switch (mnemonic[3])
2098             {
2099             case 'c': /* fstcw */
2100             case 'd': /* fstdw */
2101             case 'e': /* fstenv */
2102             case 's': /* fsts[gw] */
2103               return 3;
2104             }
2105         }
2106       break;
2107     case 'x':
2108       if (mnemonic[2] == 'r' || mnemonic[2] == 's')
2109         return 0; /* fxsave/fxrstor are not really math ops */
2110       break;
2111     }
2112
2113   return 1;
2114 }
2115
2116 /* This is the guts of the machine-dependent assembler.  LINE points to a
2117    machine dependent instruction.  This function is supposed to emit
2118    the frags/bytes it assembles to.  */
2119
2120 void
2121 md_assemble (line)
2122      char *line;
2123 {
2124   unsigned int j;
2125   char mnemonic[MAX_MNEM_SIZE];
2126
2127   /* Initialize globals.  */
2128   memset (&i, '\0', sizeof (i));
2129   for (j = 0; j < MAX_OPERANDS; j++)
2130     i.reloc[j] = NO_RELOC;
2131   memset (disp_expressions, '\0', sizeof (disp_expressions));
2132   memset (im_expressions, '\0', sizeof (im_expressions));
2133   save_stack_p = save_stack;
2134
2135   /* First parse an instruction mnemonic & call i386_operand for the operands.
2136      We assume that the scrubber has arranged it so that line[0] is the valid
2137      start of a (possibly prefixed) mnemonic.  */
2138
2139   line = parse_insn (line, mnemonic);
2140   if (line == NULL)
2141     return;
2142
2143   line = parse_operands (line, mnemonic);
2144   if (line == NULL)
2145     return;
2146
2147   /* Now we've parsed the mnemonic into a set of templates, and have the
2148      operands at hand.  */
2149
2150   /* All intel opcodes have reversed operands except for "bound" and
2151      "enter".  We also don't reverse intersegment "jmp" and "call"
2152      instructions with 2 immediate operands so that the immediate segment
2153      precedes the offset, as it does when in AT&T mode. */
2154   if (intel_syntax
2155       && i.operands > 1
2156       && (strcmp (mnemonic, "bound") != 0)
2157       && (strcmp (mnemonic, "invlpga") != 0)
2158       && !(operand_type_check (i.types[0], imm)
2159            && operand_type_check (i.types[1], imm)))
2160     swap_operands ();
2161
2162   /* The order of the immediates should be reversed
2163      for 2 immediates extrq and insertq instructions */
2164   if (i.imm_operands == 2
2165       && (strcmp (mnemonic, "extrq") == 0
2166           || strcmp (mnemonic, "insertq") == 0))
2167       swap_2_operands (0, 1);
2168
2169   if (i.imm_operands)
2170     optimize_imm ();
2171
2172   /* Don't optimize displacement for movabs since it only takes 64bit
2173      displacement.  */
2174   if (i.disp_operands
2175       && (flag_code != CODE_64BIT
2176           || strcmp (mnemonic, "movabs") != 0))
2177     optimize_disp ();
2178
2179   /* Next, we find a template that matches the given insn,
2180      making sure the overlap of the given operands types is consistent
2181      with the template operand types.  */
2182
2183   if (!match_template ())
2184     return;
2185
2186   if (intel_syntax)
2187     {
2188       /* Undo SYSV386_COMPAT brokenness when in Intel mode.  See i386.h  */
2189       if (SYSV386_COMPAT
2190           && (i.tm.base_opcode & 0xfffffde0) == 0xdce0)
2191         i.tm.base_opcode ^= Opcode_FloatR;
2192
2193       /* Zap movzx and movsx suffix.  The suffix may have been set from
2194          "word ptr" or "byte ptr" on the source operand, but we'll use
2195          the suffix later to choose the destination register.  */
2196       if ((i.tm.base_opcode & ~9) == 0x0fb6)
2197         {
2198           if (i.reg_operands < 2
2199               && !i.suffix
2200               && (!i.tm.opcode_modifier.no_bsuf
2201                   || !i.tm.opcode_modifier.no_wsuf
2202                   || !i.tm.opcode_modifier.no_lsuf
2203                   || !i.tm.opcode_modifier.no_ssuf
2204                   || !i.tm.opcode_modifier.no_xsuf
2205                   || !i.tm.opcode_modifier.no_qsuf))
2206             as_bad (_("ambiguous operand size for `%s'"), i.tm.name);
2207
2208           i.suffix = 0;
2209         }
2210     }
2211
2212   if (i.tm.opcode_modifier.fwait)
2213     if (!add_prefix (FWAIT_OPCODE))
2214       return;
2215
2216   /* Check string instruction segment overrides.  */
2217   if (i.tm.opcode_modifier.isstring && i.mem_operands != 0)
2218     {
2219       if (!check_string ())
2220         return;
2221     }
2222
2223   if (!process_suffix ())
2224     return;
2225
2226   /* Make still unresolved immediate matches conform to size of immediate
2227      given in i.suffix.  */
2228   if (!finalize_imm ())
2229     return;
2230
2231   if (i.types[0].bitfield.imm1)
2232     i.imm_operands = 0; /* kludge for shift insns.  */
2233
2234   for (j = 0; j < 3; j++)
2235     if (i.types[j].bitfield.inoutportreg
2236         || i.types[j].bitfield.shiftcount
2237         || i.types[j].bitfield.acc
2238         || i.types[j].bitfield.floatacc)
2239       i.reg_operands--;
2240
2241   if (i.tm.opcode_modifier.immext)
2242     {
2243       expressionS *exp;
2244
2245       if (i.tm.cpu_flags.bitfield.cpusse3 && i.operands > 0)
2246         {
2247           /* Streaming SIMD extensions 3 Instructions have the fixed
2248              operands with an opcode suffix which is coded in the same
2249              place as an 8-bit immediate field would be. Here we check
2250              those operands and remove them afterwards.  */
2251           unsigned int x;
2252
2253           for (x = 0; x < i.operands; x++)
2254             if (i.op[x].regs->reg_num != x)
2255               as_bad (_("can't use register '%s%s' as operand %d in '%s'."),
2256                       register_prefix,
2257                       i.op[x].regs->reg_name,
2258                       x + 1,
2259                       i.tm.name);
2260           i.operands = 0;
2261         }
2262
2263       /* These AMD 3DNow! and Intel Katmai New Instructions have an
2264          opcode suffix which is coded in the same place as an 8-bit
2265          immediate field would be.  Here we fake an 8-bit immediate
2266          operand from the opcode suffix stored in tm.extension_opcode.
2267          SSE5 also uses this encoding, for some of its 3 argument
2268          instructions.  */
2269
2270       assert (i.imm_operands == 0
2271               && (i.operands <= 2
2272                   || (i.tm.cpu_flags.bitfield.cpusse5
2273                       && i.operands <= 3)));
2274
2275       exp = &im_expressions[i.imm_operands++];
2276       i.op[i.operands].imms = exp;
2277       UINTS_CLEAR (i.types[i.operands]);
2278       i.types[i.operands].bitfield.imm8 = 1;
2279       i.operands++;
2280       exp->X_op = O_constant;
2281       exp->X_add_number = i.tm.extension_opcode;
2282       i.tm.extension_opcode = None;
2283     }
2284
2285   /* For insns with operands there are more diddles to do to the opcode.  */
2286   if (i.operands)
2287     {
2288       if (!process_operands ())
2289         return;
2290     }
2291   else if (!quiet_warnings && i.tm.opcode_modifier.ugh)
2292     {
2293       /* UnixWare fsub no args is alias for fsubp, fadd -> faddp, etc.  */
2294       as_warn (_("translating to `%sp'"), i.tm.name);
2295     }
2296
2297   /* Handle conversion of 'int $3' --> special int3 insn.  */
2298   if (i.tm.base_opcode == INT_OPCODE && i.op[0].imms->X_add_number == 3)
2299     {
2300       i.tm.base_opcode = INT3_OPCODE;
2301       i.imm_operands = 0;
2302     }
2303
2304   if ((i.tm.opcode_modifier.jump
2305        || i.tm.opcode_modifier.jumpbyte
2306        || i.tm.opcode_modifier.jumpdword)
2307       && i.op[0].disps->X_op == O_constant)
2308     {
2309       /* Convert "jmp constant" (and "call constant") to a jump (call) to
2310          the absolute address given by the constant.  Since ix86 jumps and
2311          calls are pc relative, we need to generate a reloc.  */
2312       i.op[0].disps->X_add_symbol = &abs_symbol;
2313       i.op[0].disps->X_op = O_symbol;
2314     }
2315
2316   if (i.tm.opcode_modifier.rex64)
2317     i.rex |= REX_W;
2318
2319   /* For 8 bit registers we need an empty rex prefix.  Also if the
2320      instruction already has a prefix, we need to convert old
2321      registers to new ones.  */
2322
2323   if ((i.types[0].bitfield.reg8
2324        && (i.op[0].regs->reg_flags & RegRex64) != 0)
2325       || (i.types[1].bitfield.reg8
2326           && (i.op[1].regs->reg_flags & RegRex64) != 0)
2327       || ((i.types[0].bitfield.reg8
2328            || i.types[1].bitfield.reg8)
2329           && i.rex != 0))
2330     {
2331       int x;
2332
2333       i.rex |= REX_OPCODE;
2334       for (x = 0; x < 2; x++)
2335         {
2336           /* Look for 8 bit operand that uses old registers.  */
2337           if (i.types[x].bitfield.reg8
2338               && (i.op[x].regs->reg_flags & RegRex64) == 0)
2339             {
2340               /* In case it is "hi" register, give up.  */
2341               if (i.op[x].regs->reg_num > 3)
2342                 as_bad (_("can't encode register '%s%s' in an "
2343                           "instruction requiring REX prefix."),
2344                         register_prefix, i.op[x].regs->reg_name);
2345
2346               /* Otherwise it is equivalent to the extended register.
2347                  Since the encoding doesn't change this is merely
2348                  cosmetic cleanup for debug output.  */
2349
2350               i.op[x].regs = i.op[x].regs + 8;
2351             }
2352         }
2353     }
2354
2355   /* If the instruction has the DREX attribute (aka SSE5), don't emit a
2356      REX prefix.  */
2357   if (i.tm.opcode_modifier.drex || i.tm.opcode_modifier.drexc)
2358     {
2359       i.drex.rex = i.rex;
2360       i.rex = 0;
2361     }
2362   else if (i.rex != 0)
2363     add_prefix (REX_OPCODE | i.rex);
2364
2365   /* We are ready to output the insn.  */
2366   output_insn ();
2367 }
2368
2369 static char *
2370 parse_insn (char *line, char *mnemonic)
2371 {
2372   char *l = line;
2373   char *token_start = l;
2374   char *mnem_p;
2375   int supported;
2376   const template *t;
2377
2378   /* Non-zero if we found a prefix only acceptable with string insns.  */
2379   const char *expecting_string_instruction = NULL;
2380
2381   while (1)
2382     {
2383       mnem_p = mnemonic;
2384       while ((*mnem_p = mnemonic_chars[(unsigned char) *l]) != 0)
2385         {
2386           mnem_p++;
2387           if (mnem_p >= mnemonic + MAX_MNEM_SIZE)
2388             {
2389               as_bad (_("no such instruction: `%s'"), token_start);
2390               return NULL;
2391             }
2392           l++;
2393         }
2394       if (!is_space_char (*l)
2395           && *l != END_OF_INSN
2396           && (intel_syntax
2397               || (*l != PREFIX_SEPARATOR
2398                   && *l != ',')))
2399         {
2400           as_bad (_("invalid character %s in mnemonic"),
2401                   output_invalid (*l));
2402           return NULL;
2403         }
2404       if (token_start == l)
2405         {
2406           if (!intel_syntax && *l == PREFIX_SEPARATOR)
2407             as_bad (_("expecting prefix; got nothing"));
2408           else
2409             as_bad (_("expecting mnemonic; got nothing"));
2410           return NULL;
2411         }
2412
2413       /* Look up instruction (or prefix) via hash table.  */
2414       current_templates = hash_find (op_hash, mnemonic);
2415
2416       if (*l != END_OF_INSN
2417           && (!is_space_char (*l) || l[1] != END_OF_INSN)
2418           && current_templates
2419           && current_templates->start->opcode_modifier.isprefix)
2420         {
2421           if (!cpu_flags_check_cpu64 (current_templates->start->cpu_flags))
2422             {
2423               as_bad ((flag_code != CODE_64BIT
2424                        ? _("`%s' is only supported in 64-bit mode")
2425                        : _("`%s' is not supported in 64-bit mode")),
2426                       current_templates->start->name);
2427               return NULL;
2428             }
2429           /* If we are in 16-bit mode, do not allow addr16 or data16.
2430              Similarly, in 32-bit mode, do not allow addr32 or data32.  */
2431           if ((current_templates->start->opcode_modifier.size16
2432                || current_templates->start->opcode_modifier.size32)
2433               && flag_code != CODE_64BIT
2434               && (current_templates->start->opcode_modifier.size32
2435                   ^ (flag_code == CODE_16BIT)))
2436             {
2437               as_bad (_("redundant %s prefix"),
2438                       current_templates->start->name);
2439               return NULL;
2440             }
2441           /* Add prefix, checking for repeated prefixes.  */
2442           switch (add_prefix (current_templates->start->base_opcode))
2443             {
2444             case 0:
2445               return NULL;
2446             case 2:
2447               expecting_string_instruction = current_templates->start->name;
2448               break;
2449             }
2450           /* Skip past PREFIX_SEPARATOR and reset token_start.  */
2451           token_start = ++l;
2452         }
2453       else
2454         break;
2455     }
2456
2457   if (!current_templates)
2458     {
2459       /* See if we can get a match by trimming off a suffix.  */
2460       switch (mnem_p[-1])
2461         {
2462         case WORD_MNEM_SUFFIX:
2463           if (intel_syntax && (intel_float_operand (mnemonic) & 2))
2464             i.suffix = SHORT_MNEM_SUFFIX;
2465           else
2466         case BYTE_MNEM_SUFFIX:
2467         case QWORD_MNEM_SUFFIX:
2468           i.suffix = mnem_p[-1];
2469           mnem_p[-1] = '\0';
2470           current_templates = hash_find (op_hash, mnemonic);
2471           break;
2472         case SHORT_MNEM_SUFFIX:
2473         case LONG_MNEM_SUFFIX:
2474           if (!intel_syntax)
2475             {
2476               i.suffix = mnem_p[-1];
2477               mnem_p[-1] = '\0';
2478               current_templates = hash_find (op_hash, mnemonic);
2479             }
2480           break;
2481
2482           /* Intel Syntax.  */
2483         case 'd':
2484           if (intel_syntax)
2485             {
2486               if (intel_float_operand (mnemonic) == 1)
2487                 i.suffix = SHORT_MNEM_SUFFIX;
2488               else
2489                 i.suffix = LONG_MNEM_SUFFIX;
2490               mnem_p[-1] = '\0';
2491               current_templates = hash_find (op_hash, mnemonic);
2492             }
2493           break;
2494         }
2495       if (!current_templates)
2496         {
2497           as_bad (_("no such instruction: `%s'"), token_start);
2498           return NULL;
2499         }
2500     }
2501
2502   if (current_templates->start->opcode_modifier.jump
2503       || current_templates->start->opcode_modifier.jumpbyte)
2504     {
2505       /* Check for a branch hint.  We allow ",pt" and ",pn" for
2506          predict taken and predict not taken respectively.
2507          I'm not sure that branch hints actually do anything on loop
2508          and jcxz insns (JumpByte) for current Pentium4 chips.  They
2509          may work in the future and it doesn't hurt to accept them
2510          now.  */
2511       if (l[0] == ',' && l[1] == 'p')
2512         {
2513           if (l[2] == 't')
2514             {
2515               if (!add_prefix (DS_PREFIX_OPCODE))
2516                 return NULL;
2517               l += 3;
2518             }
2519           else if (l[2] == 'n')
2520             {
2521               if (!add_prefix (CS_PREFIX_OPCODE))
2522                 return NULL;
2523               l += 3;
2524             }
2525         }
2526     }
2527   /* Any other comma loses.  */
2528   if (*l == ',')
2529     {
2530       as_bad (_("invalid character %s in mnemonic"),
2531               output_invalid (*l));
2532       return NULL;
2533     }
2534
2535   /* Check if instruction is supported on specified architecture.  */
2536   supported = 0;
2537   for (t = current_templates->start; t < current_templates->end; ++t)
2538     {
2539       if (cpu_flags_match (t->cpu_flags))
2540         supported |= 1;
2541       if (cpu_flags_check_cpu64 (t->cpu_flags))
2542         supported |= 2;
2543     }
2544   if (!(supported & 2))
2545     {
2546       as_bad (flag_code == CODE_64BIT
2547               ? _("`%s' is not supported in 64-bit mode")
2548               : _("`%s' is only supported in 64-bit mode"),
2549               current_templates->start->name);
2550       return NULL;
2551     }
2552   if (!(supported & 1))
2553     {
2554       as_warn (_("`%s' is not supported on `%s%s'"),
2555                current_templates->start->name,
2556                cpu_arch_name,
2557                cpu_sub_arch_name ? cpu_sub_arch_name : "");
2558     }
2559   else if (!cpu_arch_flags.bitfield.cpui386
2560            && (flag_code != CODE_16BIT))
2561     {
2562       as_warn (_("use .code16 to ensure correct addressing mode"));
2563     }
2564
2565   /* Check for rep/repne without a string instruction.  */
2566   if (expecting_string_instruction)
2567     {
2568       static templates override;
2569
2570       for (t = current_templates->start; t < current_templates->end; ++t)
2571         if (t->opcode_modifier.isstring)
2572           break;
2573       if (t >= current_templates->end)
2574         {
2575           as_bad (_("expecting string instruction after `%s'"),
2576                   expecting_string_instruction);
2577           return NULL;
2578         }
2579       for (override.start = t; t < current_templates->end; ++t)
2580         if (!t->opcode_modifier.isstring)
2581           break;
2582       override.end = t;
2583       current_templates = &override;
2584     }
2585
2586   return l;
2587 }
2588
2589 static char *
2590 parse_operands (char *l, const char *mnemonic)
2591 {
2592   char *token_start;
2593
2594   /* 1 if operand is pending after ','.  */
2595   unsigned int expecting_operand = 0;
2596
2597   /* Non-zero if operand parens not balanced.  */
2598   unsigned int paren_not_balanced;
2599
2600   while (*l != END_OF_INSN)
2601     {
2602       /* Skip optional white space before operand.  */
2603       if (is_space_char (*l))
2604         ++l;
2605       if (!is_operand_char (*l) && *l != END_OF_INSN)
2606         {
2607           as_bad (_("invalid character %s before operand %d"),
2608                   output_invalid (*l),
2609                   i.operands + 1);
2610           return NULL;
2611         }
2612       token_start = l;  /* after white space */
2613       paren_not_balanced = 0;
2614       while (paren_not_balanced || *l != ',')
2615         {
2616           if (*l == END_OF_INSN)
2617             {
2618               if (paren_not_balanced)
2619                 {
2620                   if (!intel_syntax)
2621                     as_bad (_("unbalanced parenthesis in operand %d."),
2622                             i.operands + 1);
2623                   else
2624                     as_bad (_("unbalanced brackets in operand %d."),
2625                             i.operands + 1);
2626                   return NULL;
2627                 }
2628               else
2629                 break;  /* we are done */
2630             }
2631           else if (!is_operand_char (*l) && !is_space_char (*l))
2632             {
2633               as_bad (_("invalid character %s in operand %d"),
2634                       output_invalid (*l),
2635                       i.operands + 1);
2636               return NULL;
2637             }
2638           if (!intel_syntax)
2639             {
2640               if (*l == '(')
2641                 ++paren_not_balanced;
2642               if (*l == ')')
2643                 --paren_not_balanced;
2644             }
2645           else
2646             {
2647               if (*l == '[')
2648                 ++paren_not_balanced;
2649               if (*l == ']')
2650                 --paren_not_balanced;
2651             }
2652           l++;
2653         }
2654       if (l != token_start)
2655         {                       /* Yes, we've read in another operand.  */
2656           unsigned int operand_ok;
2657           this_operand = i.operands++;
2658           if (i.operands > MAX_OPERANDS)
2659             {
2660               as_bad (_("spurious operands; (%d operands/instruction max)"),
2661                       MAX_OPERANDS);
2662               return NULL;
2663             }
2664           /* Now parse operand adding info to 'i' as we go along.  */
2665           END_STRING_AND_SAVE (l);
2666
2667           if (intel_syntax)
2668             operand_ok =
2669               i386_intel_operand (token_start,
2670                                   intel_float_operand (mnemonic));
2671           else
2672             operand_ok = i386_operand (token_start);
2673
2674           RESTORE_END_STRING (l);
2675           if (!operand_ok)
2676             return NULL;
2677         }
2678       else
2679         {
2680           if (expecting_operand)
2681             {
2682             expecting_operand_after_comma:
2683               as_bad (_("expecting operand after ','; got nothing"));
2684               return NULL;
2685             }
2686           if (*l == ',')
2687             {
2688               as_bad (_("expecting operand before ','; got nothing"));
2689               return NULL;
2690             }
2691         }
2692
2693       /* Now *l must be either ',' or END_OF_INSN.  */
2694       if (*l == ',')
2695         {
2696           if (*++l == END_OF_INSN)
2697             {
2698               /* Just skip it, if it's \n complain.  */
2699               goto expecting_operand_after_comma;
2700             }
2701           expecting_operand = 1;
2702         }
2703     }
2704   return l;
2705 }
2706
2707 static void
2708 swap_2_operands (int xchg1, int xchg2)
2709 {
2710   union i386_op temp_op;
2711   i386_operand_type temp_type;
2712   enum bfd_reloc_code_real temp_reloc;
2713
2714   temp_type = i.types[xchg2];
2715   i.types[xchg2] = i.types[xchg1];
2716   i.types[xchg1] = temp_type;
2717   temp_op = i.op[xchg2];
2718   i.op[xchg2] = i.op[xchg1];
2719   i.op[xchg1] = temp_op;
2720   temp_reloc = i.reloc[xchg2];
2721   i.reloc[xchg2] = i.reloc[xchg1];
2722   i.reloc[xchg1] = temp_reloc;
2723 }
2724
2725 static void
2726 swap_operands (void)
2727 {
2728   switch (i.operands)
2729     {
2730     case 4:
2731       swap_2_operands (1, i.operands - 2);
2732     case 3:
2733     case 2:
2734       swap_2_operands (0, i.operands - 1);
2735       break;
2736     default:
2737       abort ();
2738     }
2739
2740   if (i.mem_operands == 2)
2741     {
2742       const seg_entry *temp_seg;
2743       temp_seg = i.seg[0];
2744       i.seg[0] = i.seg[1];
2745       i.seg[1] = temp_seg;
2746     }
2747 }
2748
2749 /* Try to ensure constant immediates are represented in the smallest
2750    opcode possible.  */
2751 static void
2752 optimize_imm (void)
2753 {
2754   char guess_suffix = 0;
2755   int op;
2756
2757   if (i.suffix)
2758     guess_suffix = i.suffix;
2759   else if (i.reg_operands)
2760     {
2761       /* Figure out a suffix from the last register operand specified.
2762          We can't do this properly yet, ie. excluding InOutPortReg,
2763          but the following works for instructions with immediates.
2764          In any case, we can't set i.suffix yet.  */
2765       for (op = i.operands; --op >= 0;)
2766         if (i.types[op].bitfield.reg8)
2767           { 
2768             guess_suffix = BYTE_MNEM_SUFFIX;
2769             break;
2770           }
2771         else if (i.types[op].bitfield.reg16)
2772           {
2773             guess_suffix = WORD_MNEM_SUFFIX;
2774             break;
2775           }
2776         else if (i.types[op].bitfield.reg32)
2777           {
2778             guess_suffix = LONG_MNEM_SUFFIX;
2779             break;
2780           }
2781         else if (i.types[op].bitfield.reg64)
2782           {
2783             guess_suffix = QWORD_MNEM_SUFFIX;
2784             break;
2785           }
2786     }
2787   else if ((flag_code == CODE_16BIT) ^ (i.prefix[DATA_PREFIX] != 0))
2788     guess_suffix = WORD_MNEM_SUFFIX;
2789
2790   for (op = i.operands; --op >= 0;)
2791     if (operand_type_check (i.types[op], imm))
2792       {
2793         switch (i.op[op].imms->X_op)
2794           {
2795           case O_constant:
2796             /* If a suffix is given, this operand may be shortened.  */
2797             switch (guess_suffix)
2798               {
2799               case LONG_MNEM_SUFFIX:
2800                 i.types[op].bitfield.imm32 = 1;
2801                 i.types[op].bitfield.imm64 = 1;
2802                 break;
2803               case WORD_MNEM_SUFFIX:
2804                 i.types[op].bitfield.imm16 = 1;
2805                 i.types[op].bitfield.imm32 = 1;
2806                 i.types[op].bitfield.imm32s = 1;
2807                 i.types[op].bitfield.imm64 = 1;
2808                 break;
2809               case BYTE_MNEM_SUFFIX:
2810                 i.types[op].bitfield.imm8 = 1;
2811                 i.types[op].bitfield.imm8s = 1;
2812                 i.types[op].bitfield.imm16 = 1;
2813                 i.types[op].bitfield.imm32 = 1;
2814                 i.types[op].bitfield.imm32s = 1;
2815                 i.types[op].bitfield.imm64 = 1;
2816                 break;
2817               }
2818
2819             /* If this operand is at most 16 bits, convert it
2820                to a signed 16 bit number before trying to see
2821                whether it will fit in an even smaller size.
2822                This allows a 16-bit operand such as $0xffe0 to
2823                be recognised as within Imm8S range.  */
2824             if ((i.types[op].bitfield.imm16)
2825                 && (i.op[op].imms->X_add_number & ~(offsetT) 0xffff) == 0)
2826               {
2827                 i.op[op].imms->X_add_number =
2828                   (((i.op[op].imms->X_add_number & 0xffff) ^ 0x8000) - 0x8000);
2829               }
2830             if ((i.types[op].bitfield.imm32)
2831                 && ((i.op[op].imms->X_add_number & ~(((offsetT) 2 << 31) - 1))
2832                     == 0))
2833               {
2834                 i.op[op].imms->X_add_number = ((i.op[op].imms->X_add_number
2835                                                 ^ ((offsetT) 1 << 31))
2836                                                - ((offsetT) 1 << 31));
2837               }
2838             i.types[op]
2839               = operand_type_or (i.types[op],
2840                                  smallest_imm_type (i.op[op].imms->X_add_number));
2841
2842             /* We must avoid matching of Imm32 templates when 64bit
2843                only immediate is available.  */
2844             if (guess_suffix == QWORD_MNEM_SUFFIX)
2845               i.types[op].bitfield.imm32 = 0;
2846             break;
2847
2848           case O_absent:
2849           case O_register:
2850             abort ();
2851
2852             /* Symbols and expressions.  */
2853           default:
2854             /* Convert symbolic operand to proper sizes for matching, but don't
2855                prevent matching a set of insns that only supports sizes other
2856                than those matching the insn suffix.  */
2857             {
2858               i386_operand_type mask, allowed;
2859               const template *t;
2860
2861               UINTS_CLEAR (mask);
2862               UINTS_CLEAR (allowed);
2863
2864               for (t = current_templates->start;
2865                    t < current_templates->end;
2866                    ++t)
2867                 allowed = operand_type_or (allowed,
2868                                            t->operand_types[op]);
2869               switch (guess_suffix)
2870                 {
2871                 case QWORD_MNEM_SUFFIX:
2872                   mask.bitfield.imm64 = 1;
2873                   mask.bitfield.imm32s = 1;
2874                   break;
2875                 case LONG_MNEM_SUFFIX:
2876                   mask.bitfield.imm32 = 1;
2877                   break;
2878                 case WORD_MNEM_SUFFIX:
2879                   mask.bitfield.imm16 = 1;
2880                   break;
2881                 case BYTE_MNEM_SUFFIX:
2882                   mask.bitfield.imm8 = 1;
2883                   break;
2884                 default:
2885                   break;
2886                 }
2887               allowed = operand_type_and (mask, allowed);
2888               if (!UINTS_ALL_ZERO (allowed))
2889                 i.types[op] = operand_type_and (i.types[op], mask);
2890             }
2891             break;
2892           }
2893       }
2894 }
2895
2896 /* Try to use the smallest displacement type too.  */
2897 static void
2898 optimize_disp (void)
2899 {
2900   int op;
2901
2902   for (op = i.operands; --op >= 0;)
2903     if (operand_type_check (i.types[op], disp))
2904       {
2905         if (i.op[op].disps->X_op == O_constant)
2906           {
2907             offsetT disp = i.op[op].disps->X_add_number;
2908
2909             if (i.types[op].bitfield.disp16
2910                 && (disp & ~(offsetT) 0xffff) == 0)
2911               {
2912                 /* If this operand is at most 16 bits, convert
2913                    to a signed 16 bit number and don't use 64bit
2914                    displacement.  */
2915                 disp = (((disp & 0xffff) ^ 0x8000) - 0x8000);
2916                 i.types[op].bitfield.disp64 = 0;
2917               }
2918             if (i.types[op].bitfield.disp32
2919                 && (disp & ~(((offsetT) 2 << 31) - 1)) == 0)
2920               {
2921                 /* If this operand is at most 32 bits, convert
2922                    to a signed 32 bit number and don't use 64bit
2923                    displacement.  */
2924                 disp &= (((offsetT) 2 << 31) - 1);
2925                 disp = (disp ^ ((offsetT) 1 << 31)) - ((addressT) 1 << 31);
2926                 i.types[op].bitfield.disp64 = 0;
2927               }
2928             if (!disp && i.types[op].bitfield.baseindex)
2929               {
2930                 i.types[op].bitfield.disp8 = 0;
2931                 i.types[op].bitfield.disp16 = 0;
2932                 i.types[op].bitfield.disp32 = 0;
2933                 i.types[op].bitfield.disp32s = 0;
2934                 i.types[op].bitfield.disp64 = 0;
2935                 i.op[op].disps = 0;
2936                 i.disp_operands--;
2937               }
2938             else if (flag_code == CODE_64BIT)
2939               {
2940                 if (fits_in_signed_long (disp))
2941                   {
2942                     i.types[op].bitfield.disp64 = 0;
2943                     i.types[op].bitfield.disp32s = 1;
2944                   }
2945                 if (fits_in_unsigned_long (disp))
2946                   i.types[op].bitfield.disp32 = 1;
2947               }
2948             if ((i.types[op].bitfield.disp32
2949                  || i.types[op].bitfield.disp32s
2950                  || i.types[op].bitfield.disp16)
2951                 && fits_in_signed_byte (disp))
2952               i.types[op].bitfield.disp8 = 1;
2953           }
2954         else if (i.reloc[op] == BFD_RELOC_386_TLS_DESC_CALL
2955                  || i.reloc[op] == BFD_RELOC_X86_64_TLSDESC_CALL)
2956           {
2957             fix_new_exp (frag_now, frag_more (0) - frag_now->fr_literal, 0,
2958                          i.op[op].disps, 0, i.reloc[op]);
2959             i.types[op].bitfield.disp8 = 0;
2960             i.types[op].bitfield.disp16 = 0;
2961             i.types[op].bitfield.disp32 = 0;
2962             i.types[op].bitfield.disp32s = 0;
2963             i.types[op].bitfield.disp64 = 0;
2964           }
2965         else
2966           /* We only support 64bit displacement on constants.  */
2967           i.types[op].bitfield.disp64 = 0;
2968       }
2969 }
2970
2971 static int
2972 match_template (void)
2973 {
2974   /* Points to template once we've found it.  */
2975   const template *t;
2976   i386_operand_type overlap0, overlap1, overlap2, overlap3;
2977   unsigned int found_reverse_match;
2978   i386_opcode_modifier suffix_check;
2979   i386_operand_type operand_types [MAX_OPERANDS];
2980   int addr_prefix_disp;
2981   unsigned int j;
2982   i386_cpu_flags overlap;
2983
2984 #if MAX_OPERANDS != 4
2985 # error "MAX_OPERANDS must be 4."
2986 #endif
2987
2988   found_reverse_match = 0;
2989   addr_prefix_disp = -1;
2990
2991   memset (&suffix_check, 0, sizeof (suffix_check));
2992   if (i.suffix == BYTE_MNEM_SUFFIX)
2993     suffix_check.no_bsuf = 1;
2994   else if (i.suffix == WORD_MNEM_SUFFIX)
2995     suffix_check.no_wsuf = 1;
2996   else if (i.suffix == SHORT_MNEM_SUFFIX)
2997     suffix_check.no_ssuf = 1;
2998   else if (i.suffix == LONG_MNEM_SUFFIX)
2999     suffix_check.no_lsuf = 1;
3000   else if (i.suffix == QWORD_MNEM_SUFFIX)
3001     suffix_check.no_qsuf = 1;
3002   else if (i.suffix == LONG_DOUBLE_MNEM_SUFFIX)
3003     suffix_check.no_xsuf = 1;
3004
3005   for (t = current_templates->start; t < current_templates->end; t++)
3006     {
3007       addr_prefix_disp = -1;
3008
3009       /* Must have right number of operands.  */
3010       if (i.operands != t->operands)
3011         continue;
3012
3013       /* Check the suffix, except for some instructions in intel mode.  */
3014       if (((t->opcode_modifier.no_bsuf & suffix_check.no_bsuf)
3015            || (t->opcode_modifier.no_wsuf & suffix_check.no_wsuf)
3016            || (t->opcode_modifier.no_lsuf & suffix_check.no_lsuf)
3017            || (t->opcode_modifier.no_ssuf & suffix_check.no_ssuf)
3018            || (t->opcode_modifier.no_qsuf & suffix_check.no_qsuf)
3019            || (t->opcode_modifier.no_xsuf & suffix_check.no_xsuf))
3020           && !(intel_syntax && t->opcode_modifier.ignoresize))
3021         continue;
3022
3023       for (j = 0; j < MAX_OPERANDS; j++)
3024         operand_types [j] = t->operand_types [j];
3025
3026       /* In general, don't allow 64-bit operands in 32-bit mode.  */
3027       if (i.suffix == QWORD_MNEM_SUFFIX
3028           && flag_code != CODE_64BIT
3029           && (intel_syntax
3030               ? (!t->opcode_modifier.ignoresize
3031                  && !intel_float_operand (t->name))
3032               : intel_float_operand (t->name) != 2)
3033           && ((!operand_types[0].bitfield.regmmx
3034                && !operand_types[0].bitfield.regxmm)
3035               || (!operand_types[t->operands > 1].bitfield.regmmx
3036                   && !!operand_types[t->operands > 1].bitfield.regxmm))
3037           && (t->base_opcode != 0x0fc7
3038               || t->extension_opcode != 1 /* cmpxchg8b */))
3039         continue;
3040
3041       /* Do not verify operands when there are none.  */
3042       else 
3043         {
3044           overlap = cpu_flags_and (t->cpu_flags, cpu_arch_flags_not);
3045           if (!t->operands)
3046             {
3047               if (!UINTS_ALL_ZERO (overlap))
3048                 continue;
3049               /* We've found a match; break out of loop.  */
3050               break;
3051             }
3052         }
3053
3054       /* Address size prefix will turn Disp64/Disp32/Disp16 operand
3055          into Disp32/Disp16/Disp32 operand.  */
3056       if (i.prefix[ADDR_PREFIX] != 0)
3057           {
3058             /* There should be only one Disp operand.  */
3059             switch (flag_code)
3060             {
3061             case CODE_16BIT:
3062               for (j = 0; j < MAX_OPERANDS; j++)
3063                 {
3064                   if (operand_types[j].bitfield.disp16)
3065                     {
3066                       addr_prefix_disp = j;
3067                       operand_types[j].bitfield.disp32 = 1;
3068                       operand_types[j].bitfield.disp16 = 0;
3069                       break;
3070                     }
3071                 }
3072               break;
3073             case CODE_32BIT:
3074               for (j = 0; j < MAX_OPERANDS; j++)
3075                 {
3076                   if (operand_types[j].bitfield.disp32)
3077                     {
3078                       addr_prefix_disp = j;
3079                       operand_types[j].bitfield.disp32 = 0;
3080                       operand_types[j].bitfield.disp16 = 1;
3081                       break;
3082                     }
3083                 }
3084               break;
3085             case CODE_64BIT:
3086               for (j = 0; j < MAX_OPERANDS; j++)
3087                 {
3088                   if (operand_types[j].bitfield.disp64)
3089                     {
3090                       addr_prefix_disp = j;
3091                       operand_types[j].bitfield.disp64 = 0;
3092                       operand_types[j].bitfield.disp32 = 1;
3093                       break;
3094                     }
3095                 }
3096               break;
3097             }
3098           }
3099
3100       overlap0 = operand_type_and (i.types[0], operand_types[0]);
3101       switch (t->operands)
3102         {
3103         case 1:
3104           if (!operand_type_match (overlap0, i.types[0]))
3105             continue;
3106           break;
3107         case 2:
3108           /* xchg %eax, %eax is a special case. It is an aliase for nop
3109              only in 32bit mode and we can use opcode 0x90.  In 64bit
3110              mode, we can't use 0x90 for xchg %eax, %eax since it should
3111              zero-extend %eax to %rax.  */
3112           if (flag_code == CODE_64BIT
3113               && t->base_opcode == 0x90
3114               && UINTS_EQUAL (i.types [0], acc32)
3115               && UINTS_EQUAL (i.types [1], acc32))
3116             continue;
3117         case 3:
3118         case 4:
3119           overlap1 = operand_type_and (i.types[1], operand_types[1]);
3120           if (!operand_type_match (overlap0, i.types[0])
3121               || !operand_type_match (overlap1, i.types[1])
3122               /* monitor in SSE3 is a very special case.  The first
3123                  register and the second register may have different
3124                  sizes.  The same applies to crc32 in SSE4.2.  It is
3125                  also true for invlpga, vmload, vmrun and vmsave in
3126                  SVME.  */
3127               || !((t->base_opcode == 0x0f01
3128                     && (t->extension_opcode == 0xc8
3129                         || t->extension_opcode == 0xd8
3130                         || t->extension_opcode == 0xda
3131                         || t->extension_opcode == 0xdb
3132                         || t->extension_opcode == 0xdf))
3133                    || t->base_opcode == 0xf20f38f1
3134                    || operand_type_register_match (overlap0, i.types[0],
3135                                                    operand_types[0],
3136                                                    overlap1, i.types[1],
3137                                                    operand_types[1])))
3138             {
3139               /* Check if other direction is valid ...  */
3140               if (!t->opcode_modifier.d && !t->opcode_modifier.floatd)
3141                 continue;
3142
3143               /* Try reversing direction of operands.  */
3144               overlap0 = operand_type_and (i.types[0], operand_types[1]);
3145               overlap1 = operand_type_and (i.types[1], operand_types[0]);
3146               if (!operand_type_match (overlap0, i.types[0])
3147                   || !operand_type_match (overlap1, i.types[1])
3148                   || !operand_type_register_match (overlap0, i.types[0],
3149                                                    operand_types[1],
3150                                                    overlap1, i.types[1],
3151                                                    operand_types[0]))
3152                 {
3153                   /* Does not match either direction.  */
3154                   continue;
3155                 }
3156               /* found_reverse_match holds which of D or FloatDR
3157                  we've found.  */
3158               if (t->opcode_modifier.d)
3159                 found_reverse_match = Opcode_D;
3160               else if (t->opcode_modifier.floatd)
3161                 found_reverse_match = Opcode_FloatD;
3162               else
3163                 found_reverse_match = 0;
3164               if (t->opcode_modifier.floatr)
3165                 found_reverse_match |= Opcode_FloatR;
3166             }
3167           else
3168             {
3169               /* Found a forward 2 operand match here.  */
3170               switch (t->operands)
3171                 {
3172                 case 4:
3173                   overlap3 = operand_type_and (i.types[3],
3174                                                operand_types[3]);
3175                 case 3:
3176                   overlap2 = operand_type_and (i.types[2],
3177                                                operand_types[2]);
3178                   break;
3179                 }
3180
3181               switch (t->operands)
3182                 {
3183                 case 4:
3184                   if (!operand_type_match (overlap3, i.types[3])
3185                       || !operand_type_register_match (overlap2,
3186                                                        i.types[2],
3187                                                        operand_types[2],
3188                                                        overlap3,
3189                                                        i.types[3],
3190                                                        operand_types[3]))
3191                     continue;
3192                 case 3:
3193                   /* Here we make use of the fact that there are no
3194                      reverse match 3 operand instructions, and all 3
3195                      operand instructions only need to be checked for
3196                      register consistency between operands 2 and 3.  */
3197                   if (!operand_type_match (overlap2, i.types[2])
3198                       || !operand_type_register_match (overlap1,
3199                                                        i.types[1],
3200                                                        operand_types[1],
3201                                                        overlap2,
3202                                                        i.types[2],
3203                                                        operand_types[2]))
3204                     continue;
3205                   break;
3206                 }
3207             }
3208           /* Found either forward/reverse 2, 3 or 4 operand match here:
3209              slip through to break.  */
3210         }
3211       if (!UINTS_ALL_ZERO (overlap))
3212         {
3213           found_reverse_match = 0;
3214           continue;
3215         }
3216       /* We've found a match; break out of loop.  */
3217       break;
3218     }
3219
3220   if (t == current_templates->end)
3221     {
3222       /* We found no match.  */
3223       as_bad (_("suffix or operands invalid for `%s'"),
3224               current_templates->start->name);
3225       return 0;
3226     }
3227
3228   if (!quiet_warnings)
3229     {
3230       if (!intel_syntax
3231           && (i.types[0].bitfield.jumpabsolute
3232               != operand_types[0].bitfield.jumpabsolute))
3233         {
3234           as_warn (_("indirect %s without `*'"), t->name);
3235         }
3236
3237       if (t->opcode_modifier.isprefix
3238           && t->opcode_modifier.ignoresize)
3239         {
3240           /* Warn them that a data or address size prefix doesn't
3241              affect assembly of the next line of code.  */
3242           as_warn (_("stand-alone `%s' prefix"), t->name);
3243         }
3244     }
3245
3246   /* Copy the template we found.  */
3247   i.tm = *t;
3248
3249   if (addr_prefix_disp != -1)
3250     i.tm.operand_types[addr_prefix_disp]
3251       = operand_types[addr_prefix_disp];
3252
3253   if (found_reverse_match)
3254     {
3255       /* If we found a reverse match we must alter the opcode
3256          direction bit.  found_reverse_match holds bits to change
3257          (different for int & float insns).  */
3258
3259       i.tm.base_opcode ^= found_reverse_match;
3260
3261       i.tm.operand_types[0] = operand_types[1];
3262       i.tm.operand_types[1] = operand_types[0];
3263     }
3264
3265   return 1;
3266 }
3267
3268 static int
3269 check_string (void)
3270 {
3271   int mem_op = operand_type_check (i.types[0], anymem) ? 0 : 1;
3272   if (i.tm.operand_types[mem_op].bitfield.esseg)
3273     {
3274       if (i.seg[0] != NULL && i.seg[0] != &es)
3275         {
3276           as_bad (_("`%s' operand %d must use `%%es' segment"),
3277                   i.tm.name,
3278                   mem_op + 1);
3279           return 0;
3280         }
3281       /* There's only ever one segment override allowed per instruction.
3282          This instruction possibly has a legal segment override on the
3283          second operand, so copy the segment to where non-string
3284          instructions store it, allowing common code.  */
3285       i.seg[0] = i.seg[1];
3286     }
3287   else if (i.tm.operand_types[mem_op + 1].bitfield.esseg)
3288     {
3289       if (i.seg[1] != NULL && i.seg[1] != &es)
3290         {
3291           as_bad (_("`%s' operand %d must use `%%es' segment"),
3292                   i.tm.name,
3293                   mem_op + 2);
3294           return 0;
3295         }
3296     }
3297   return 1;
3298 }
3299
3300 static int
3301 process_suffix (void)
3302 {
3303   /* If matched instruction specifies an explicit instruction mnemonic
3304      suffix, use it.  */
3305   if (i.tm.opcode_modifier.size16)
3306     i.suffix = WORD_MNEM_SUFFIX;
3307   else if (i.tm.opcode_modifier.size32)
3308     i.suffix = LONG_MNEM_SUFFIX;
3309   else if (i.tm.opcode_modifier.size64)
3310     i.suffix = QWORD_MNEM_SUFFIX;
3311   else if (i.reg_operands)
3312     {
3313       /* If there's no instruction mnemonic suffix we try to invent one
3314          based on register operands.  */
3315       if (!i.suffix)
3316         {
3317           /* We take i.suffix from the last register operand specified,
3318              Destination register type is more significant than source
3319              register type.  crc32 in SSE4.2 prefers source register
3320              type. */
3321           if (i.tm.base_opcode == 0xf20f38f1)
3322             {
3323               if (i.types[0].bitfield.reg16)
3324                 i.suffix = WORD_MNEM_SUFFIX;
3325               else if (i.types[0].bitfield.reg32)
3326                 i.suffix = LONG_MNEM_SUFFIX;
3327               else if (i.types[0].bitfield.reg64)
3328                 i.suffix = QWORD_MNEM_SUFFIX;
3329             }
3330           else if (i.tm.base_opcode == 0xf20f38f0)
3331             {
3332               if (i.types[0].bitfield.reg8)
3333                 i.suffix = BYTE_MNEM_SUFFIX;
3334             }
3335
3336           if (!i.suffix)
3337             {
3338               int op;
3339
3340               if (i.tm.base_opcode == 0xf20f38f1
3341                   || i.tm.base_opcode == 0xf20f38f0)
3342                 {
3343                   /* We have to know the operand size for crc32.  */
3344                   as_bad (_("ambiguous memory operand size for `%s`"),
3345                           i.tm.name);
3346                   return 0;
3347                 }
3348
3349               for (op = i.operands; --op >= 0;)
3350                 if (!i.tm.operand_types[op].bitfield.inoutportreg)
3351                   {
3352                     if (i.types[op].bitfield.reg8)
3353                       {
3354                         i.suffix = BYTE_MNEM_SUFFIX;
3355                         break;
3356                       }
3357                     else if (i.types[op].bitfield.reg16)
3358                       {
3359                         i.suffix = WORD_MNEM_SUFFIX;
3360                         break;
3361                       }
3362                     else if (i.types[op].bitfield.reg32)
3363                       {
3364                         i.suffix = LONG_MNEM_SUFFIX;
3365                         break;
3366                       }
3367                     else if (i.types[op].bitfield.reg64)
3368                       {
3369                         i.suffix = QWORD_MNEM_SUFFIX;
3370                         break;
3371                       }
3372                   }
3373             }
3374         }
3375       else if (i.suffix == BYTE_MNEM_SUFFIX)
3376         {
3377           if (!check_byte_reg ())
3378             return 0;
3379         }
3380       else if (i.suffix == LONG_MNEM_SUFFIX)
3381         {
3382           if (!check_long_reg ())
3383             return 0;
3384         }
3385       else if (i.suffix == QWORD_MNEM_SUFFIX)
3386         {
3387           if (!check_qword_reg ())
3388             return 0;
3389         }
3390       else if (i.suffix == WORD_MNEM_SUFFIX)
3391         {
3392           if (!check_word_reg ())
3393             return 0;
3394         }
3395       else if (intel_syntax && i.tm.opcode_modifier.ignoresize)
3396         /* Do nothing if the instruction is going to ignore the prefix.  */
3397         ;
3398       else
3399         abort ();
3400     }
3401   else if (i.tm.opcode_modifier.defaultsize
3402            && !i.suffix
3403            /* exclude fldenv/frstor/fsave/fstenv */
3404            && i.tm.opcode_modifier.no_ssuf)
3405     {
3406       i.suffix = stackop_size;
3407     }
3408   else if (intel_syntax
3409            && !i.suffix
3410            && (i.tm.operand_types[0].bitfield.jumpabsolute
3411                || i.tm.opcode_modifier.jumpbyte
3412                || i.tm.opcode_modifier.jumpintersegment
3413                || (i.tm.base_opcode == 0x0f01 /* [ls][gi]dt */
3414                    && i.tm.extension_opcode <= 3)))
3415     {
3416       switch (flag_code)
3417         {
3418         case CODE_64BIT:
3419           if (!i.tm.opcode_modifier.no_qsuf)
3420             {
3421               i.suffix = QWORD_MNEM_SUFFIX;
3422               break;
3423             }
3424         case CODE_32BIT:
3425           if (!i.tm.opcode_modifier.no_lsuf)
3426             i.suffix = LONG_MNEM_SUFFIX;
3427           break;
3428         case CODE_16BIT:
3429           if (!i.tm.opcode_modifier.no_wsuf)
3430             i.suffix = WORD_MNEM_SUFFIX;
3431           break;
3432         }
3433     }
3434
3435   if (!i.suffix)
3436     {
3437       if (!intel_syntax)
3438         {
3439           if (i.tm.opcode_modifier.w)
3440             {
3441               as_bad (_("no instruction mnemonic suffix given and "
3442                         "no register operands; can't size instruction"));
3443               return 0;
3444             }
3445         }
3446       else
3447         {
3448           unsigned int suffixes;
3449           
3450           suffixes = !i.tm.opcode_modifier.no_bsuf;
3451           if (!i.tm.opcode_modifier.no_wsuf)
3452             suffixes |= 1 << 1;
3453           if (!i.tm.opcode_modifier.no_lsuf)
3454             suffixes |= 1 << 2;
3455           if (!i.tm.opcode_modifier.no_lsuf)
3456             suffixes |= 1 << 3;
3457           if (!i.tm.opcode_modifier.no_ssuf)
3458             suffixes |= 1 << 4;
3459           if (!i.tm.opcode_modifier.no_qsuf)
3460             suffixes |= 1 << 5;
3461
3462           /* There are more than suffix matches.  */
3463           if (i.tm.opcode_modifier.w
3464               || ((suffixes & (suffixes - 1))
3465                   && !i.tm.opcode_modifier.defaultsize
3466                   && !i.tm.opcode_modifier.ignoresize))
3467             {
3468               as_bad (_("ambiguous operand size for `%s'"), i.tm.name);
3469               return 0;
3470             }
3471         }
3472     }
3473
3474   /* Change the opcode based on the operand size given by i.suffix;
3475      We don't need to change things for byte insns.  */
3476
3477   if (i.suffix && i.suffix != BYTE_MNEM_SUFFIX)
3478     {
3479       /* It's not a byte, select word/dword operation.  */
3480       if (i.tm.opcode_modifier.w)
3481         {
3482           if (i.tm.opcode_modifier.shortform)
3483             i.tm.base_opcode |= 8;
3484           else
3485             i.tm.base_opcode |= 1;
3486         }
3487
3488       /* Now select between word & dword operations via the operand
3489          size prefix, except for instructions that will ignore this
3490          prefix anyway.  */
3491       if (i.tm.base_opcode == 0x0f01
3492            && (i.tm.extension_opcode == 0xc8
3493                || i.tm.extension_opcode == 0xd8
3494                || i.tm.extension_opcode == 0xda
3495                || i.tm.extension_opcode == 0xdb
3496                || i.tm.extension_opcode == 0xdf))
3497         {
3498           /* monitor in SSE3 is a very special case. The default size
3499              of AX is the size of mode. The address size override
3500              prefix will change the size of AX.  It is also true for
3501              invlpga, vmload, vmrun and vmsave in SVME.  */
3502           if ((flag_code == CODE_32BIT
3503                && i.op->regs[0].reg_type.bitfield.reg16)
3504               || (flag_code != CODE_32BIT
3505                   && i.op->regs[0].reg_type.bitfield.reg32))
3506             if (!add_prefix (ADDR_PREFIX_OPCODE))
3507               return 0;
3508         }
3509       else if (i.suffix != QWORD_MNEM_SUFFIX
3510                && i.suffix != LONG_DOUBLE_MNEM_SUFFIX
3511                && !i.tm.opcode_modifier.ignoresize
3512                && !i.tm.opcode_modifier.floatmf
3513                && ((i.suffix == LONG_MNEM_SUFFIX) == (flag_code == CODE_16BIT)
3514                    || (flag_code == CODE_64BIT
3515                        && i.tm.opcode_modifier.jumpbyte)))
3516         {
3517           unsigned int prefix = DATA_PREFIX_OPCODE;
3518
3519           if (i.tm.opcode_modifier.jumpbyte) /* jcxz, loop */
3520             prefix = ADDR_PREFIX_OPCODE;
3521
3522           if (!add_prefix (prefix))
3523             return 0;
3524         }
3525
3526       /* Set mode64 for an operand.  */
3527       if (i.suffix == QWORD_MNEM_SUFFIX
3528           && flag_code == CODE_64BIT
3529           && !i.tm.opcode_modifier.norex64)
3530         {
3531           /* Special case for xchg %rax,%rax.  It is NOP and doesn't
3532              need rex64.  cmpxchg8b is also a special case. */
3533           if (! (i.operands == 2
3534                  && i.tm.base_opcode == 0x90
3535                  && i.tm.extension_opcode == None
3536                  && UINTS_EQUAL (i.types [0], acc64)
3537                  && UINTS_EQUAL (i.types [1], acc64))
3538               && ! (i.operands == 1
3539                     && i.tm.base_opcode == 0xfc7
3540                     && i.tm.extension_opcode == 1
3541                     && !operand_type_check (i.types [0], reg)
3542                     && operand_type_check (i.types [0], anymem)))
3543             i.rex |= REX_W;
3544         }
3545
3546       /* Size floating point instruction.  */
3547       if (i.suffix == LONG_MNEM_SUFFIX)
3548         if (i.tm.opcode_modifier.floatmf)
3549           i.tm.base_opcode ^= 4;
3550     }
3551
3552   return 1;
3553 }
3554
3555 static int
3556 check_byte_reg (void)
3557 {
3558   int op;
3559
3560   for (op = i.operands; --op >= 0;)
3561     {
3562       /* If this is an eight bit register, it's OK.  If it's the 16 or
3563          32 bit version of an eight bit register, we will just use the
3564          low portion, and that's OK too.  */
3565       if (i.types[op].bitfield.reg8)
3566         continue;
3567
3568       /* movzx, movsx, pextrb and pinsrb should not generate this
3569          warning.  */
3570       if (intel_syntax
3571           && (i.tm.base_opcode == 0xfb7
3572               || i.tm.base_opcode == 0xfb6
3573               || i.tm.base_opcode == 0x63
3574               || i.tm.base_opcode == 0xfbe
3575               || i.tm.base_opcode == 0xfbf
3576               || i.tm.base_opcode == 0x660f3a14
3577               || i.tm.base_opcode == 0x660f3a20))
3578         continue;
3579
3580       /* crc32 doesn't generate this warning.  */
3581       if (i.tm.base_opcode == 0xf20f38f0)
3582         continue;
3583
3584       if ((i.types[op].bitfield.reg16
3585            || i.types[op].bitfield.reg32
3586            || i.types[op].bitfield.reg64)
3587           && i.op[op].regs->reg_num < 4)
3588         {
3589           /* Prohibit these changes in the 64bit mode, since the
3590              lowering is more complicated.  */
3591           if (flag_code == CODE_64BIT
3592               && !i.tm.operand_types[op].bitfield.inoutportreg)
3593             {
3594               as_bad (_("Incorrect register `%s%s' used with `%c' suffix"),
3595                       register_prefix, i.op[op].regs->reg_name,
3596                       i.suffix);
3597               return 0;
3598             }
3599 #if REGISTER_WARNINGS
3600           if (!quiet_warnings
3601               && !i.tm.operand_types[op].bitfield.inoutportreg)
3602             as_warn (_("using `%s%s' instead of `%s%s' due to `%c' suffix"),
3603                      register_prefix,
3604                      (i.op[op].regs + (i.types[op].bitfield.reg16
3605                                        ? REGNAM_AL - REGNAM_AX
3606                                        : REGNAM_AL - REGNAM_EAX))->reg_name,
3607                      register_prefix,
3608                      i.op[op].regs->reg_name,
3609                      i.suffix);
3610 #endif
3611           continue;
3612         }
3613       /* Any other register is bad.  */
3614       if (i.types[op].bitfield.reg16
3615           || i.types[op].bitfield.reg32
3616           || i.types[op].bitfield.reg64
3617           || i.types[op].bitfield.regmmx
3618           || i.types[op].bitfield.regxmm
3619           || i.types[op].bitfield.sreg2
3620           || i.types[op].bitfield.sreg3
3621           || i.types[op].bitfield.control
3622           || i.types[op].bitfield.debug
3623           || i.types[op].bitfield.test
3624           || i.types[op].bitfield.floatreg
3625           || i.types[op].bitfield.floatacc)
3626         {
3627           as_bad (_("`%s%s' not allowed with `%s%c'"),
3628                   register_prefix,
3629                   i.op[op].regs->reg_name,
3630                   i.tm.name,
3631                   i.suffix);
3632           return 0;
3633         }
3634     }
3635   return 1;
3636 }
3637
3638 static int
3639 check_long_reg (void)
3640 {
3641   int op;
3642
3643   for (op = i.operands; --op >= 0;)
3644     /* Reject eight bit registers, except where the template requires
3645        them. (eg. movzb)  */
3646     if (i.types[op].bitfield.reg8
3647         && (i.tm.operand_types[op].bitfield.reg16
3648             || i.tm.operand_types[op].bitfield.reg32
3649             || i.tm.operand_types[op].bitfield.acc))
3650       {
3651         as_bad (_("`%s%s' not allowed with `%s%c'"),
3652                 register_prefix,
3653                 i.op[op].regs->reg_name,
3654                 i.tm.name,
3655                 i.suffix);
3656         return 0;
3657       }
3658   /* Warn if the e prefix on a general reg is missing.  */
3659     else if ((!quiet_warnings || flag_code == CODE_64BIT)
3660              && i.types[op].bitfield.reg16
3661              && (i.tm.operand_types[op].bitfield.reg32
3662                  || i.tm.operand_types[op].bitfield.acc))
3663       {
3664         /* Prohibit these changes in the 64bit mode, since the
3665            lowering is more complicated.  */
3666         if (flag_code == CODE_64BIT)
3667           {
3668             as_bad (_("Incorrect register `%s%s' used with `%c' suffix"),
3669                     register_prefix, i.op[op].regs->reg_name,
3670                     i.suffix);
3671             return 0;
3672           }
3673 #if REGISTER_WARNINGS
3674         else
3675           as_warn (_("using `%s%s' instead of `%s%s' due to `%c' suffix"),
3676                    register_prefix,
3677                    (i.op[op].regs + REGNAM_EAX - REGNAM_AX)->reg_name,
3678                    register_prefix,
3679                    i.op[op].regs->reg_name,
3680                    i.suffix);
3681 #endif
3682       }
3683   /* Warn if the r prefix on a general reg is missing.  */
3684     else if (i.types[op].bitfield.reg64
3685              && (i.tm.operand_types[op].bitfield.reg32
3686                  || i.tm.operand_types[op].bitfield.acc))
3687       {
3688         if (intel_syntax
3689             && i.tm.base_opcode == 0xf30f2d
3690             && !i.types[0].bitfield.regxmm)
3691           {
3692             /* cvtss2si converts DWORD memory to Reg64.  We want
3693                REX byte. */
3694             i.suffix = QWORD_MNEM_SUFFIX;
3695           }
3696         else
3697           {
3698             as_bad (_("Incorrect register `%s%s' used with `%c' suffix"),
3699                     register_prefix, i.op[op].regs->reg_name,
3700                     i.suffix);
3701             return 0;
3702           }
3703       }
3704   return 1;
3705 }
3706
3707 static int
3708 check_qword_reg (void)
3709 {
3710   int op;
3711
3712   for (op = i.operands; --op >= 0; )
3713     /* Reject eight bit registers, except where the template requires
3714        them. (eg. movzb)  */
3715     if (i.types[op].bitfield.reg8
3716         && (i.tm.operand_types[op].bitfield.reg16
3717             || i.tm.operand_types[op].bitfield.reg32
3718             || i.tm.operand_types[op].bitfield.acc))
3719       {
3720         as_bad (_("`%s%s' not allowed with `%s%c'"),
3721                 register_prefix,
3722                 i.op[op].regs->reg_name,
3723                 i.tm.name,
3724                 i.suffix);
3725         return 0;
3726       }
3727   /* Warn if the e prefix on a general reg is missing.  */
3728     else if ((i.types[op].bitfield.reg16
3729               || i.types[op].bitfield.reg32)
3730              && (i.tm.operand_types[op].bitfield.reg32
3731                  || i.tm.operand_types[op].bitfield.acc))
3732       {
3733         /* Prohibit these changes in the 64bit mode, since the
3734            lowering is more complicated.  */
3735         if (intel_syntax
3736             && i.tm.base_opcode == 0xf20f2d
3737             && !i.types[0].bitfield.regxmm)
3738           {
3739             /* cvtsd2si converts QWORD memory to Reg32.  We don't want
3740                REX byte. */
3741             i.suffix = LONG_MNEM_SUFFIX;
3742           }
3743         else
3744           {
3745             as_bad (_("Incorrect register `%s%s' used with `%c' suffix"),
3746                     register_prefix, i.op[op].regs->reg_name,
3747                     i.suffix);
3748             return 0;
3749           }
3750       }
3751   return 1;
3752 }
3753
3754 static int
3755 check_word_reg (void)
3756 {
3757   int op;
3758   for (op = i.operands; --op >= 0;)
3759     /* Reject eight bit registers, except where the template requires
3760        them. (eg. movzb)  */
3761     if (i.types[op].bitfield.reg8
3762         && (i.tm.operand_types[op].bitfield.reg16
3763             || i.tm.operand_types[op].bitfield.reg32
3764             || i.tm.operand_types[op].bitfield.acc))
3765       {
3766         as_bad (_("`%s%s' not allowed with `%s%c'"),
3767                 register_prefix,
3768                 i.op[op].regs->reg_name,
3769                 i.tm.name,
3770                 i.suffix);
3771         return 0;
3772       }
3773   /* Warn if the e prefix on a general reg is present.  */
3774     else if ((!quiet_warnings || flag_code == CODE_64BIT)
3775              && i.types[op].bitfield.reg32
3776              && (i.tm.operand_types[op].bitfield.reg16
3777                  || i.tm.operand_types[op].bitfield.acc))
3778       {
3779         /* Prohibit these changes in the 64bit mode, since the
3780            lowering is more complicated.  */
3781         if (flag_code == CODE_64BIT)
3782           {
3783             as_bad (_("Incorrect register `%s%s' used with `%c' suffix"),
3784                     register_prefix, i.op[op].regs->reg_name,
3785                     i.suffix);
3786             return 0;
3787           }
3788         else
3789 #if REGISTER_WARNINGS
3790           as_warn (_("using `%s%s' instead of `%s%s' due to `%c' suffix"),
3791                    register_prefix,
3792                    (i.op[op].regs + REGNAM_AX - REGNAM_EAX)->reg_name,
3793                    register_prefix,
3794                    i.op[op].regs->reg_name,
3795                    i.suffix);
3796 #endif
3797       }
3798   return 1;
3799 }
3800
3801 static int
3802 update_imm (unsigned int j)
3803 {
3804   i386_operand_type overlap;
3805
3806   overlap = operand_type_and (i.types[j], i.tm.operand_types[j]);
3807   if ((overlap.bitfield.imm8
3808        || overlap.bitfield.imm8s
3809        || overlap.bitfield.imm16
3810        || overlap.bitfield.imm32
3811        || overlap.bitfield.imm32s
3812        || overlap.bitfield.imm64)
3813       && !UINTS_EQUAL (overlap, imm8)
3814       && !UINTS_EQUAL (overlap, imm8s)
3815       && !UINTS_EQUAL (overlap, imm16)
3816       && !UINTS_EQUAL (overlap, imm32)
3817       && !UINTS_EQUAL (overlap, imm32s)
3818       && !UINTS_EQUAL (overlap, imm64))
3819     {
3820       if (i.suffix)
3821         {
3822           i386_operand_type temp;
3823
3824           UINTS_CLEAR (temp);
3825           if (i.suffix == BYTE_MNEM_SUFFIX) 
3826             {
3827               temp.bitfield.imm8 = overlap.bitfield.imm8;
3828               temp.bitfield.imm8s = overlap.bitfield.imm8s;
3829             }
3830           else if (i.suffix == WORD_MNEM_SUFFIX)
3831             temp.bitfield.imm16 = overlap.bitfield.imm16;
3832           else if (i.suffix == QWORD_MNEM_SUFFIX)
3833             {
3834               temp.bitfield.imm64 = overlap.bitfield.imm64;
3835               temp.bitfield.imm32s = overlap.bitfield.imm32s;
3836             }
3837           else
3838             temp.bitfield.imm32 = overlap.bitfield.imm32;
3839           overlap = temp;
3840         }
3841       else if (UINTS_EQUAL (overlap, imm16_32_32s)
3842                || UINTS_EQUAL (overlap, imm16_32)
3843                || UINTS_EQUAL (overlap, imm16_32s))
3844         {
3845           UINTS_CLEAR (overlap);
3846           if ((flag_code == CODE_16BIT) ^ (i.prefix[DATA_PREFIX] != 0))
3847             overlap.bitfield.imm16 = 1;
3848           else
3849             overlap.bitfield.imm32s = 1;
3850         }
3851       if (!UINTS_EQUAL (overlap, imm8)
3852           && !UINTS_EQUAL (overlap, imm8s)
3853           && !UINTS_EQUAL (overlap, imm16)
3854           && !UINTS_EQUAL (overlap, imm32)
3855           && !UINTS_EQUAL (overlap, imm32s)
3856           && !UINTS_EQUAL (overlap, imm64))
3857         {
3858           as_bad (_("no instruction mnemonic suffix given; "
3859                     "can't determine immediate size"));
3860           return 0;
3861         }
3862     }
3863   i.types[j] = overlap;
3864
3865   return 1;
3866 }
3867
3868 static int
3869 finalize_imm (void)
3870 {
3871   unsigned int j;
3872
3873   for (j = 0; j < 2; j++)
3874     if (update_imm (j) == 0)
3875       return 0;
3876
3877   i.types[2] = operand_type_and (i.types[2], i.tm.operand_types[2]);
3878   assert (operand_type_check (i.types[2], imm) == 0);
3879
3880   return 1;
3881 }
3882
3883 static void
3884 process_drex (void)
3885 {
3886   i.drex.modrm_reg = None;
3887   i.drex.modrm_regmem = None;
3888
3889   /* SSE5 4 operand instructions must have the destination the same as 
3890      one of the inputs.  Figure out the destination register and cache
3891      it away in the drex field, and remember which fields to use for 
3892      the modrm byte.  */
3893   if (i.tm.opcode_modifier.drex 
3894       && i.tm.opcode_modifier.drexv 
3895       && i.operands == 4)
3896     {
3897       i.tm.extension_opcode = None;
3898
3899       /* Case 1: 4 operand insn, dest = src1, src3 = register.  */
3900       if (i.types[0].bitfield.regxmm != 0
3901           && i.types[1].bitfield.regxmm != 0
3902           && i.types[2].bitfield.regxmm != 0
3903           && i.types[3].bitfield.regxmm != 0
3904           && i.op[0].regs->reg_num == i.op[3].regs->reg_num
3905           && i.op[0].regs->reg_flags == i.op[3].regs->reg_flags)
3906         {
3907           /* Clear the arguments that are stored in drex.  */
3908           UINTS_CLEAR (i.types[0]); 
3909           UINTS_CLEAR (i.types[3]);
3910           i.reg_operands -= 2;
3911
3912           /* There are two different ways to encode a 4 operand 
3913              instruction with all registers that uses OC1 set to 
3914              0 or 1.  Favor setting OC1 to 0 since this mimics the 
3915              actions of other SSE5 assemblers.  Use modrm encoding 2 
3916              for register/register.  Include the high order bit that 
3917              is normally stored in the REX byte in the register
3918              field.  */
3919           i.tm.extension_opcode = DREX_X1_XMEM_X2_X1;
3920           i.drex.modrm_reg = 2;
3921           i.drex.modrm_regmem = 1;
3922           i.drex.reg = (i.op[3].regs->reg_num
3923                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
3924         }
3925
3926       /* Case 2: 4 operand insn, dest = src1, src3 = memory.  */
3927       else if (i.types[0].bitfield.regxmm != 0
3928                && i.types[1].bitfield.regxmm != 0
3929                && (i.types[2].bitfield.regxmm 
3930                    || operand_type_check (i.types[2], anymem))
3931                && i.types[3].bitfield.regxmm != 0
3932                && i.op[0].regs->reg_num == i.op[3].regs->reg_num
3933                && i.op[0].regs->reg_flags == i.op[3].regs->reg_flags)
3934         {
3935           /* clear the arguments that are stored in drex */
3936           UINTS_CLEAR (i.types[0]);
3937           UINTS_CLEAR (i.types[3]);
3938           i.reg_operands -= 2;
3939
3940           /* Specify the modrm encoding for memory addressing.  Include 
3941              the high order bit that is normally stored in the REX byte
3942              in the register field.  */
3943           i.tm.extension_opcode = DREX_X1_X2_XMEM_X1;
3944           i.drex.modrm_reg = 1;
3945           i.drex.modrm_regmem = 2;
3946           i.drex.reg = (i.op[3].regs->reg_num
3947                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
3948         }
3949
3950       /* Case 3: 4 operand insn, dest = src1, src2 = memory.  */
3951       else if (i.types[0].bitfield.regxmm != 0
3952                && operand_type_check (i.types[1], anymem) != 0
3953                && i.types[2].bitfield.regxmm != 0
3954                && i.types[3].bitfield.regxmm != 0
3955                && i.op[0].regs->reg_num == i.op[3].regs->reg_num
3956                && i.op[0].regs->reg_flags == i.op[3].regs->reg_flags)
3957         {
3958           /* Clear the arguments that are stored in drex.  */
3959           UINTS_CLEAR (i.types[0]);
3960           UINTS_CLEAR (i.types[3]);
3961           i.reg_operands -= 2;
3962
3963           /* Specify the modrm encoding for memory addressing.  Include
3964              the high order bit that is normally stored in the REX byte 
3965              in the register field.  */
3966           i.tm.extension_opcode = DREX_X1_XMEM_X2_X1;
3967           i.drex.modrm_reg = 2;
3968           i.drex.modrm_regmem = 1;
3969           i.drex.reg = (i.op[3].regs->reg_num
3970                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
3971         }
3972
3973       /* Case 4: 4 operand insn, dest = src3, src2 = register. */
3974       else if (i.types[0].bitfield.regxmm != 0
3975                && i.types[1].bitfield.regxmm != 0
3976                && i.types[2].bitfield.regxmm != 0
3977                && i.types[3].bitfield.regxmm != 0
3978                && i.op[2].regs->reg_num == i.op[3].regs->reg_num
3979                && i.op[2].regs->reg_flags == i.op[3].regs->reg_flags)
3980         {
3981           /* clear the arguments that are stored in drex */
3982           UINTS_CLEAR (i.types[2]);
3983           UINTS_CLEAR (i.types[3]);
3984           i.reg_operands -= 2;
3985
3986           /* There are two different ways to encode a 4 operand 
3987              instruction with all registers that uses OC1 set to 
3988              0 or 1.  Favor setting OC1 to 0 since this mimics the 
3989              actions of other SSE5 assemblers.  Use modrm encoding 
3990              2 for register/register.  Include the high order bit that 
3991              is normally stored in the REX byte in the register 
3992              field.  */
3993           i.tm.extension_opcode = DREX_XMEM_X1_X2_X2;
3994           i.drex.modrm_reg = 1;
3995           i.drex.modrm_regmem = 0;
3996
3997           /* Remember the register, including the upper bits */
3998           i.drex.reg = (i.op[3].regs->reg_num
3999                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
4000         }
4001
4002       /* Case 5: 4 operand insn, dest = src3, src2 = memory.  */
4003       else if (i.types[0].bitfield.regxmm != 0
4004                && (i.types[1].bitfield.regxmm 
4005                    || operand_type_check (i.types[1], anymem)) 
4006                && i.types[2].bitfield.regxmm != 0
4007                && i.types[3].bitfield.regxmm != 0
4008                && i.op[2].regs->reg_num == i.op[3].regs->reg_num
4009                && i.op[2].regs->reg_flags == i.op[3].regs->reg_flags)
4010         {
4011           /* Clear the arguments that are stored in drex.  */
4012           UINTS_CLEAR (i.types[2]);
4013           UINTS_CLEAR (i.types[3]);
4014           i.reg_operands -= 2;
4015
4016           /* Specify the modrm encoding and remember the register 
4017              including the bits normally stored in the REX byte. */
4018           i.tm.extension_opcode = DREX_X1_XMEM_X2_X2;
4019           i.drex.modrm_reg = 0;
4020           i.drex.modrm_regmem = 1;
4021           i.drex.reg = (i.op[3].regs->reg_num
4022                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
4023         }
4024
4025       /* Case 6: 4 operand insn, dest = src3, src1 = memory.  */
4026       else if (operand_type_check (i.types[0], anymem) != 0
4027                && i.types[1].bitfield.regxmm != 0
4028                && i.types[2].bitfield.regxmm != 0
4029                && i.types[3].bitfield.regxmm != 0
4030                && i.op[2].regs->reg_num == i.op[3].regs->reg_num
4031                && i.op[2].regs->reg_flags == i.op[3].regs->reg_flags)
4032         {
4033           /* clear the arguments that are stored in drex */
4034           UINTS_CLEAR (i.types[2]);
4035           UINTS_CLEAR (i.types[3]);
4036           i.reg_operands -= 2;
4037
4038           /* Specify the modrm encoding and remember the register 
4039              including the bits normally stored in the REX byte. */
4040           i.tm.extension_opcode = DREX_XMEM_X1_X2_X2;
4041           i.drex.modrm_reg = 1;
4042           i.drex.modrm_regmem = 0;
4043           i.drex.reg = (i.op[3].regs->reg_num
4044                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
4045         }
4046
4047       else
4048         as_bad (_("Incorrect operands for the '%s' instruction"), 
4049                 i.tm.name);
4050     }
4051
4052   /* SSE5 instructions with the DREX byte where the only memory operand 
4053      is in the 2nd argument, and the first and last xmm register must 
4054      match, and is encoded in the DREX byte. */
4055   else if (i.tm.opcode_modifier.drex 
4056            && !i.tm.opcode_modifier.drexv 
4057            && i.operands == 4)
4058     {
4059       /* Case 1: 4 operand insn, dest = src1, src3 = reg/mem.  */
4060       if (i.types[0].bitfield.regxmm != 0
4061           && (i.types[1].bitfield.regxmm 
4062               || operand_type_check(i.types[1], anymem)) 
4063           && i.types[2].bitfield.regxmm != 0
4064           && i.types[3].bitfield.regxmm != 0
4065           && i.op[0].regs->reg_num == i.op[3].regs->reg_num
4066           && i.op[0].regs->reg_flags == i.op[3].regs->reg_flags)
4067         {
4068           /* clear the arguments that are stored in drex */
4069           UINTS_CLEAR (i.types[0]);
4070           UINTS_CLEAR (i.types[3]);
4071           i.reg_operands -= 2;
4072
4073           /* Specify the modrm encoding and remember the register 
4074              including the high bit normally stored in the REX 
4075              byte.  */
4076           i.drex.modrm_reg = 2;
4077           i.drex.modrm_regmem = 1;
4078           i.drex.reg = (i.op[3].regs->reg_num
4079                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
4080         }
4081
4082       else
4083         as_bad (_("Incorrect operands for the '%s' instruction"), 
4084                 i.tm.name);
4085     }
4086
4087   /* SSE5 3 operand instructions that the result is a register, being 
4088      either operand can be a memory operand, using OC0 to note which 
4089      one is the memory.  */
4090   else if (i.tm.opcode_modifier.drex 
4091            && i.tm.opcode_modifier.drexv
4092            && i.operands == 3)
4093     {
4094       i.tm.extension_opcode = None;
4095
4096       /* Case 1: 3 operand insn, src1 = register.  */
4097       if (i.types[0].bitfield.regxmm != 0
4098           && i.types[1].bitfield.regxmm != 0
4099           && i.types[2].bitfield.regxmm != 0)
4100         {
4101           /* Clear the arguments that are stored in drex.  */
4102           UINTS_CLEAR (i.types[2]);
4103           i.reg_operands--;
4104
4105           /* Specify the modrm encoding and remember the register 
4106              including the high bit normally stored in the REX byte.  */
4107           i.tm.extension_opcode = DREX_XMEM_X1_X2;
4108           i.drex.modrm_reg = 1;
4109           i.drex.modrm_regmem = 0;
4110           i.drex.reg = (i.op[2].regs->reg_num
4111                         + ((i.op[2].regs->reg_flags & RegRex) ? 8 : 0));
4112         }
4113
4114       /* Case 2: 3 operand insn, src1 = memory.  */
4115       else if (operand_type_check (i.types[0], anymem) != 0
4116                && i.types[1].bitfield.regxmm != 0
4117                && i.types[2].bitfield.regxmm != 0)
4118         {
4119           /* Clear the arguments that are stored in drex.  */
4120           UINTS_CLEAR (i.types[2]);
4121           i.reg_operands--;
4122
4123           /* Specify the modrm encoding and remember the register 
4124              including the high bit normally stored in the REX 
4125              byte.  */
4126           i.tm.extension_opcode = DREX_XMEM_X1_X2;
4127           i.drex.modrm_reg = 1;
4128           i.drex.modrm_regmem = 0;
4129           i.drex.reg = (i.op[2].regs->reg_num
4130                         + ((i.op[2].regs->reg_flags & RegRex) ? 8 : 0));
4131         }
4132
4133       /* Case 3: 3 operand insn, src2 = memory.  */
4134       else if (i.types[0].bitfield.regxmm != 0
4135                && operand_type_check (i.types[1], anymem) != 0
4136                && i.types[2].bitfield.regxmm != 0)
4137         {
4138           /* Clear the arguments that are stored in drex.  */
4139           UINTS_CLEAR (i.types[2]);
4140           i.reg_operands--;
4141
4142           /* Specify the modrm encoding and remember the register 
4143              including the high bit normally stored in the REX byte.  */
4144           i.tm.extension_opcode = DREX_X1_XMEM_X2;
4145           i.drex.modrm_reg = 0;
4146           i.drex.modrm_regmem = 1;
4147           i.drex.reg = (i.op[2].regs->reg_num
4148                         + ((i.op[2].regs->reg_flags & RegRex) ? 8 : 0));
4149         }
4150
4151       else
4152         as_bad (_("Incorrect operands for the '%s' instruction"), 
4153                 i.tm.name);
4154     }
4155
4156   /* SSE5 4 operand instructions that are the comparison instructions 
4157      where the first operand is the immediate value of the comparison 
4158      to be done.  */
4159   else if (i.tm.opcode_modifier.drexc != 0 && i.operands == 4)
4160     {
4161       /* Case 1: 4 operand insn, src1 = reg/memory. */
4162       if (operand_type_check (i.types[0], imm) != 0
4163           && (i.types[1].bitfield.regxmm 
4164               || operand_type_check (i.types[1], anymem)) 
4165           && i.types[2].bitfield.regxmm != 0
4166           && i.types[3].bitfield.regxmm != 0)
4167         {
4168           /* clear the arguments that are stored in drex */
4169           UINTS_CLEAR (i.types[3]);
4170           i.reg_operands--;
4171
4172           /* Specify the modrm encoding and remember the register 
4173              including the high bit normally stored in the REX byte.  */
4174           i.drex.modrm_reg = 2;
4175           i.drex.modrm_regmem = 1;
4176           i.drex.reg = (i.op[3].regs->reg_num
4177                         + ((i.op[3].regs->reg_flags & RegRex) ? 8 : 0));
4178         }
4179
4180       /* Case 2: 3 operand insn with ImmExt that places the 
4181          opcode_extension as an immediate argument.  This is used for 
4182          all of the varients of comparison that supplies the appropriate
4183          value as part of the instruction.  */
4184       else if ((i.types[0].bitfield.regxmm
4185                 || operand_type_check (i.types[0], anymem)) 
4186                && i.types[1].bitfield.regxmm != 0
4187                && i.types[2].bitfield.regxmm != 0
4188                && operand_type_check (i.types[3], imm) != 0)
4189         {
4190           /* clear the arguments that are stored in drex */
4191           UINTS_CLEAR (i.types[2]);
4192           i.reg_operands--;
4193
4194           /* Specify the modrm encoding and remember the register 
4195              including the high bit normally stored in the REX byte.  */
4196           i.drex.modrm_reg = 1;
4197           i.drex.modrm_regmem = 0;
4198           i.drex.reg = (i.op[2].regs->reg_num
4199                         + ((i.op[2].regs->reg_flags & RegRex) ? 8 : 0));
4200         }
4201
4202       else
4203         as_bad (_("Incorrect operands for the '%s' instruction"), 
4204                 i.tm.name);
4205     }
4206
4207   else if (i.tm.opcode_modifier.drex 
4208            || i.tm.opcode_modifier.drexv 
4209            || i.tm.opcode_modifier.drexc)
4210     as_bad (_("Internal error for the '%s' instruction"), i.tm.name);
4211 }
4212
4213 static int
4214 process_operands (void)
4215 {
4216   /* Default segment register this instruction will use for memory
4217      accesses.  0 means unknown.  This is only for optimizing out
4218      unnecessary segment overrides.  */
4219   const seg_entry *default_seg = 0;
4220
4221   /* Handle all of the DREX munging that SSE5 needs.  */
4222   if (i.tm.opcode_modifier.drex 
4223       || i.tm.opcode_modifier.drexv 
4224       || i.tm.opcode_modifier.drexc)
4225     process_drex ();
4226
4227   /* The imul $imm, %reg instruction is converted into
4228      imul $imm, %reg, %reg, and the clr %reg instruction
4229      is converted into xor %reg, %reg.  */
4230   if (i.tm.opcode_modifier.regkludge)
4231     {
4232        if (i.tm.cpu_flags.bitfield.cpusse4_1)
4233          {
4234            /* The first operand in instruction blendvpd, blendvps and
4235               pblendvb in SSE4.1 is implicit and must be xmm0.  */
4236            assert (i.operands == 3
4237                    && i.reg_operands >= 2
4238                    && UINTS_EQUAL (i.types[0], regxmm));
4239            if (i.op[0].regs->reg_num != 0)
4240              {
4241                if (intel_syntax)
4242                  as_bad (_("the last operand of `%s' must be `%sxmm0'"),
4243                          i.tm.name, register_prefix);
4244                else
4245                  as_bad (_("the first operand of `%s' must be `%sxmm0'"),
4246                          i.tm.name, register_prefix);
4247                return 0;
4248              }
4249            i.op[0] = i.op[1];
4250            i.op[1] = i.op[2];
4251            i.types[0] = i.types[1];
4252            i.types[1] = i.types[2];
4253            i.operands--;
4254            i.reg_operands--;
4255
4256            /* We need to adjust fields in i.tm since they are used by
4257               build_modrm_byte.  */
4258            i.tm.operand_types [0] = i.tm.operand_types [1];
4259            i.tm.operand_types [1] = i.tm.operand_types [2];
4260            i.tm.operands--;
4261          }
4262        else
4263          {
4264            unsigned int first_reg_op;
4265            
4266            if (operand_type_check (i.types[0], reg))
4267              first_reg_op = 0;
4268            else
4269              first_reg_op = 1;
4270            /* Pretend we saw the extra register operand.  */
4271            assert (i.reg_operands == 1
4272                    && i.op[first_reg_op + 1].regs == 0);
4273            i.op[first_reg_op + 1].regs = i.op[first_reg_op].regs;
4274            i.types[first_reg_op + 1] = i.types[first_reg_op];
4275            i.operands++;
4276            i.reg_operands++;
4277          }
4278     }
4279
4280   if (i.tm.opcode_modifier.shortform)
4281     {
4282       if (i.types[0].bitfield.sreg2
4283           || i.types[0].bitfield.sreg3)
4284         {
4285           if (i.tm.base_opcode == POP_SEG_SHORT
4286               && i.op[0].regs->reg_num == 1)
4287             {
4288               as_bad (_("you can't `pop %%cs'"));
4289               return 0;
4290             }
4291           i.tm.base_opcode |= (i.op[0].regs->reg_num << 3);
4292           if ((i.op[0].regs->reg_flags & RegRex) != 0)
4293             i.rex |= REX_B;
4294         }
4295       else
4296         {
4297           /* The register or float register operand is in operand 
4298              0 or 1.  */
4299           unsigned int op;
4300           
4301            if (i.types[0].bitfield.floatreg
4302                || operand_type_check (i.types[0], reg))
4303              op = 0;
4304            else
4305              op = 1;
4306           /* Register goes in low 3 bits of opcode.  */
4307           i.tm.base_opcode |= i.op[op].regs->reg_num;
4308           if ((i.op[op].regs->reg_flags & RegRex) != 0)
4309             i.rex |= REX_B;
4310           if (!quiet_warnings && i.tm.opcode_modifier.ugh)
4311             {
4312               /* Warn about some common errors, but press on regardless.
4313                  The first case can be generated by gcc (<= 2.8.1).  */
4314               if (i.operands == 2)
4315                 {
4316                   /* Reversed arguments on faddp, fsubp, etc.  */
4317                   as_warn (_("translating to `%s %s%s,%s%s'"), i.tm.name,
4318                            register_prefix, i.op[1].regs->reg_name,
4319                            register_prefix, i.op[0].regs->reg_name);
4320                 }
4321               else
4322                 {
4323                   /* Extraneous `l' suffix on fp insn.  */
4324                   as_warn (_("translating to `%s %s%s'"), i.tm.name,
4325                            register_prefix, i.op[0].regs->reg_name);
4326                 }
4327             }
4328         }
4329     }
4330   else if (i.tm.opcode_modifier.modrm)
4331     {
4332       /* The opcode is completed (modulo i.tm.extension_opcode which
4333          must be put into the modrm byte).  Now, we make the modrm and
4334          index base bytes based on all the info we've collected.  */
4335
4336       default_seg = build_modrm_byte ();
4337     }
4338   else if ((i.tm.base_opcode & ~0x3) == MOV_AX_DISP32)
4339     {
4340       default_seg = &ds;
4341     }
4342   else if (i.tm.opcode_modifier.isstring)
4343     {
4344       /* For the string instructions that allow a segment override
4345          on one of their operands, the default segment is ds.  */
4346       default_seg = &ds;
4347     }
4348
4349   if (i.tm.base_opcode == 0x8d /* lea */
4350       && i.seg[0]
4351       && !quiet_warnings)
4352     as_warn (_("segment override on `%s' is ineffectual"), i.tm.name);
4353
4354   /* If a segment was explicitly specified, and the specified segment
4355      is not the default, use an opcode prefix to select it.  If we
4356      never figured out what the default segment is, then default_seg
4357      will be zero at this point, and the specified segment prefix will
4358      always be used.  */
4359   if ((i.seg[0]) && (i.seg[0] != default_seg))
4360     {
4361       if (!add_prefix (i.seg[0]->seg_prefix))
4362         return 0;
4363     }
4364   return 1;
4365 }
4366
4367 static const seg_entry *
4368 build_modrm_byte (void)
4369 {
4370   const seg_entry *default_seg = 0;
4371
4372   /* SSE5 4 operand instructions are encoded in such a way that one of 
4373      the inputs must match the destination register.  Process_drex hides
4374      the 3rd argument in the drex field, so that by the time we get 
4375      here, it looks to GAS as if this is a 2 operand instruction.  */
4376   if ((i.tm.opcode_modifier.drex 
4377        || i.tm.opcode_modifier.drexv 
4378        || i.tm.opcode_modifier.drexc)
4379       && i.reg_operands == 2)
4380     {
4381       const reg_entry *reg = i.op[i.drex.modrm_reg].regs;
4382       const reg_entry *regmem = i.op[i.drex.modrm_regmem].regs;
4383
4384       i.rm.reg = reg->reg_num;
4385       i.rm.regmem = regmem->reg_num;
4386       i.rm.mode = 3;
4387       if ((reg->reg_flags & RegRex) != 0)
4388         i.rex |= REX_R;
4389       if ((regmem->reg_flags & RegRex) != 0)
4390         i.rex |= REX_B;
4391     }
4392
4393   /* i.reg_operands MUST be the number of real register operands;
4394      implicit registers do not count.  */
4395   else if (i.reg_operands == 2)
4396     {
4397       unsigned int source, dest;
4398
4399       switch (i.operands)
4400         {
4401         case 2:
4402           source = 0;
4403           break;
4404         case 3:
4405           /* When there are 3 operands, one of them may be immediate,
4406              which may be the first or the last operand.  Otherwise,
4407              the first operand must be shift count register (cl). */
4408           assert (i.imm_operands == 1
4409                   || (i.imm_operands == 0
4410                       && i.types[0].bitfield.shiftcount));
4411           if (operand_type_check (i.types[0], imm)
4412               || i.types[0].bitfield.shiftcount)
4413             source = 1;
4414           else
4415             source = 0;
4416           break;
4417         case 4:
4418           /* When there are 4 operands, the first two must be immediate
4419              operands. The source operand will be the 3rd one.  */
4420           assert (i.imm_operands == 2
4421                   && operand_type_check (i.types[0], imm)
4422                   && operand_type_check (i.types[1], imm));
4423           source = 2;
4424           break;
4425         default:
4426           abort ();
4427         }
4428
4429       dest = source + 1;
4430
4431       i.rm.mode = 3;
4432       /* One of the register operands will be encoded in the i.tm.reg
4433          field, the other in the combined i.tm.mode and i.tm.regmem
4434          fields.  If no form of this instruction supports a memory
4435          destination operand, then we assume the source operand may
4436          sometimes be a memory operand and so we need to store the
4437          destination in the i.rm.reg field.  */
4438       if (!i.tm.operand_types[dest].bitfield.regmem
4439           && operand_type_check (i.tm.operand_types[dest], anymem) == 0)
4440         {
4441           i.rm.reg = i.op[dest].regs->reg_num;
4442           i.rm.regmem = i.op[source].regs->reg_num;
4443           if ((i.op[dest].regs->reg_flags & RegRex) != 0)
4444             i.rex |= REX_R;
4445           if ((i.op[source].regs->reg_flags & RegRex) != 0)
4446             i.rex |= REX_B;
4447         }
4448       else
4449         {
4450           i.rm.reg = i.op[source].regs->reg_num;
4451           i.rm.regmem = i.op[dest].regs->reg_num;
4452           if ((i.op[dest].regs->reg_flags & RegRex) != 0)
4453             i.rex |= REX_B;
4454           if ((i.op[source].regs->reg_flags & RegRex) != 0)
4455             i.rex |= REX_R;
4456         }
4457       if (flag_code != CODE_64BIT && (i.rex & (REX_R | REX_B)))
4458         {
4459           if (!i.types[0].bitfield.control
4460               && !i.types[1].bitfield.control)
4461             abort ();
4462           i.rex &= ~(REX_R | REX_B);
4463           add_prefix (LOCK_PREFIX_OPCODE);
4464         }
4465     }
4466   else
4467     {                   /* If it's not 2 reg operands...  */
4468       if (i.mem_operands)
4469         {
4470           unsigned int fake_zero_displacement = 0;
4471           unsigned int op;
4472
4473           /* This has been precalculated for SSE5 instructions 
4474              that have a DREX field earlier in process_drex.  */
4475           if (i.tm.opcode_modifier.drex 
4476               || i.tm.opcode_modifier.drexv 
4477               || i.tm.opcode_modifier.drexc)
4478             op = i.drex.modrm_regmem;
4479           else
4480             {
4481               for (op = 0; op < i.operands; op++)
4482                 if (operand_type_check (i.types[op], anymem))
4483                   break;
4484               assert (op < i.operands);
4485             }
4486
4487           default_seg = &ds;
4488
4489           if (i.base_reg == 0)
4490             {
4491               i.rm.mode = 0;
4492               if (!i.disp_operands)
4493                 fake_zero_displacement = 1;
4494               if (i.index_reg == 0)
4495                 {
4496                   /* Operand is just <disp>  */
4497                   if (flag_code == CODE_64BIT)
4498                     {
4499                       /* 64bit mode overwrites the 32bit absolute
4500                          addressing by RIP relative addressing and
4501                          absolute addressing is encoded by one of the
4502                          redundant SIB forms.  */
4503                       i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
4504                       i.sib.base = NO_BASE_REGISTER;
4505                       i.sib.index = NO_INDEX_REGISTER;
4506                       i.types[op] = ((i.prefix[ADDR_PREFIX] == 0)
4507                                      ? disp32s : disp32);
4508                     }
4509                   else if ((flag_code == CODE_16BIT)
4510                            ^ (i.prefix[ADDR_PREFIX] != 0))
4511                     {
4512                       i.rm.regmem = NO_BASE_REGISTER_16;
4513                       i.types[op] = disp16;
4514                     }
4515                   else
4516                     {
4517                       i.rm.regmem = NO_BASE_REGISTER;
4518                       i.types[op] = disp32;
4519                     }
4520                 }
4521               else /* !i.base_reg && i.index_reg  */
4522                 {
4523                   if (i.index_reg->reg_num == RegEiz
4524                       || i.index_reg->reg_num == RegRiz)
4525                     i.sib.index = NO_INDEX_REGISTER;
4526                   else
4527                     i.sib.index = i.index_reg->reg_num;
4528                   i.sib.base = NO_BASE_REGISTER;
4529                   i.sib.scale = i.log2_scale_factor;
4530                   i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
4531                   i.types[op].bitfield.disp8 = 0;
4532                   i.types[op].bitfield.disp16 = 0;
4533                   i.types[op].bitfield.disp64 = 0;
4534                   if (flag_code != CODE_64BIT)
4535                     {
4536                       /* Must be 32 bit */
4537                       i.types[op].bitfield.disp32 = 1;
4538                       i.types[op].bitfield.disp32s = 0;
4539                     }
4540                   else
4541                     {
4542                       i.types[op].bitfield.disp32 = 0;
4543                       i.types[op].bitfield.disp32s = 1;
4544                     }
4545                   if ((i.index_reg->reg_flags & RegRex) != 0)
4546                     i.rex |= REX_X;
4547                 }
4548             }
4549           /* RIP addressing for 64bit mode.  */
4550           else if (i.base_reg->reg_num == RegRip)
4551             {
4552               i.rm.regmem = NO_BASE_REGISTER;
4553               i.types[op].bitfield.disp8 = 0;
4554               i.types[op].bitfield.disp16 = 0;
4555               i.types[op].bitfield.disp32 = 0;
4556               i.types[op].bitfield.disp32s = 1;
4557               i.types[op].bitfield.disp64 = 0;
4558               i.flags[op] |= Operand_PCrel;
4559               if (! i.disp_operands)
4560                 fake_zero_displacement = 1;
4561             }
4562           else if (i.base_reg->reg_type.bitfield.reg16)
4563             {
4564               switch (i.base_reg->reg_num)
4565                 {
4566                 case 3: /* (%bx)  */
4567                   if (i.index_reg == 0)
4568                     i.rm.regmem = 7;
4569                   else /* (%bx,%si) -> 0, or (%bx,%di) -> 1  */
4570                     i.rm.regmem = i.index_reg->reg_num - 6;
4571                   break;
4572                 case 5: /* (%bp)  */
4573                   default_seg = &ss;
4574                   if (i.index_reg == 0)
4575                     {
4576                       i.rm.regmem = 6;
4577                       if (operand_type_check (i.types[op], disp) == 0)
4578                         {
4579                           /* fake (%bp) into 0(%bp)  */
4580                           i.types[op].bitfield.disp8 = 1;
4581                           fake_zero_displacement = 1;
4582                         }
4583                     }
4584                   else /* (%bp,%si) -> 2, or (%bp,%di) -> 3  */
4585                     i.rm.regmem = i.index_reg->reg_num - 6 + 2;
4586                   break;
4587                 default: /* (%si) -> 4 or (%di) -> 5  */
4588                   i.rm.regmem = i.base_reg->reg_num - 6 + 4;
4589                 }
4590               i.rm.mode = mode_from_disp_size (i.types[op]);
4591             }
4592           else /* i.base_reg and 32/64 bit mode  */
4593             {
4594               if (flag_code == CODE_64BIT
4595                   && operand_type_check (i.types[op], disp))
4596                 {
4597                   i386_operand_type temp;
4598                   UINTS_CLEAR (temp);
4599                   temp.bitfield.disp8 = i.types[op].bitfield.disp8;
4600                   i.types[op] = temp;
4601                   if (i.prefix[ADDR_PREFIX] == 0)
4602                     i.types[op].bitfield.disp32s = 1;
4603                   else
4604                     i.types[op].bitfield.disp32 = 1;
4605                 }
4606
4607               i.rm.regmem = i.base_reg->reg_num;
4608               if ((i.base_reg->reg_flags & RegRex) != 0)
4609                 i.rex |= REX_B;
4610               i.sib.base = i.base_reg->reg_num;
4611               /* x86-64 ignores REX prefix bit here to avoid decoder
4612                  complications.  */
4613               if ((i.base_reg->reg_num & 7) == EBP_REG_NUM)
4614                 {
4615                   default_seg = &ss;
4616                   if (i.disp_operands == 0)
4617                     {
4618                       fake_zero_displacement = 1;
4619                       i.types[op].bitfield.disp8 = 1;
4620                     }
4621                 }
4622               else if (i.base_reg->reg_num == ESP_REG_NUM)
4623                 {
4624                   default_seg = &ss;
4625                 }
4626               i.sib.scale = i.log2_scale_factor;
4627               if (i.index_reg == 0)
4628                 {
4629                   /* <disp>(%esp) becomes two byte modrm with no index
4630                      register.  We've already stored the code for esp
4631                      in i.rm.regmem ie. ESCAPE_TO_TWO_BYTE_ADDRESSING.
4632                      Any base register besides %esp will not use the
4633                      extra modrm byte.  */
4634                   i.sib.index = NO_INDEX_REGISTER;
4635                 }
4636               else
4637                 {
4638                   if (i.index_reg->reg_num == RegEiz
4639                       || i.index_reg->reg_num == RegRiz)
4640                     i.sib.index = NO_INDEX_REGISTER;
4641                   else
4642                     i.sib.index = i.index_reg->reg_num;
4643                   i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
4644                   if ((i.index_reg->reg_flags & RegRex) != 0)
4645                     i.rex |= REX_X;
4646                 }
4647
4648               if (i.disp_operands
4649                   && (i.reloc[op] == BFD_RELOC_386_TLS_DESC_CALL
4650                       || i.reloc[op] == BFD_RELOC_X86_64_TLSDESC_CALL))
4651                 i.rm.mode = 0;
4652               else
4653                 i.rm.mode = mode_from_disp_size (i.types[op]);
4654             }
4655
4656           if (fake_zero_displacement)
4657             {
4658               /* Fakes a zero displacement assuming that i.types[op]
4659                  holds the correct displacement size.  */
4660               expressionS *exp;
4661
4662               assert (i.op[op].disps == 0);
4663               exp = &disp_expressions[i.disp_operands++];
4664               i.op[op].disps = exp;
4665               exp->X_op = O_constant;
4666               exp->X_add_number = 0;
4667               exp->X_add_symbol = (symbolS *) 0;
4668               exp->X_op_symbol = (symbolS *) 0;
4669             }
4670         }
4671
4672       /* Fill in i.rm.reg or i.rm.regmem field with register operand
4673          (if any) based on i.tm.extension_opcode.  Again, we must be
4674          careful to make sure that segment/control/debug/test/MMX
4675          registers are coded into the i.rm.reg field.  */
4676       if (i.reg_operands)
4677         {
4678           unsigned int op;
4679
4680           /* This has been precalculated for SSE5 instructions 
4681              that have a DREX field earlier in process_drex.  */
4682           if (i.tm.opcode_modifier.drex 
4683               || i.tm.opcode_modifier.drexv 
4684               || i.tm.opcode_modifier.drexc)
4685             {
4686               op = i.drex.modrm_reg;
4687               i.rm.reg = i.op[op].regs->reg_num;
4688               if ((i.op[op].regs->reg_flags & RegRex) != 0)
4689                 i.rex |= REX_R;
4690             }
4691           else
4692             {
4693               for (op = 0; op < i.operands; op++)
4694                 if (i.types[op].bitfield.reg8
4695                     || i.types[op].bitfield.reg16
4696                     || i.types[op].bitfield.reg32
4697                     || i.types[op].bitfield.reg64
4698                     || i.types[op].bitfield.regmmx
4699                     || i.types[op].bitfield.regxmm
4700                     || i.types[op].bitfield.sreg2
4701                     || i.types[op].bitfield.sreg3
4702                     || i.types[op].bitfield.control
4703                     || i.types[op].bitfield.debug
4704                     || i.types[op].bitfield.test)
4705                   break;
4706
4707               assert (op < i.operands);
4708
4709               /* If there is an extension opcode to put here, the 
4710                  register number must be put into the regmem field.  */
4711               if (i.tm.extension_opcode != None)
4712                 {
4713                   i.rm.regmem = i.op[op].regs->reg_num;
4714                   if ((i.op[op].regs->reg_flags & RegRex) != 0)
4715                     i.rex |= REX_B;
4716                 }
4717               else
4718                 {
4719                   i.rm.reg = i.op[op].regs->reg_num;
4720                   if ((i.op[op].regs->reg_flags & RegRex) != 0)
4721                     i.rex |= REX_R;
4722                 }
4723             }
4724
4725           /* Now, if no memory operand has set i.rm.mode = 0, 1, 2 we
4726              must set it to 3 to indicate this is a register operand
4727              in the regmem field.  */
4728           if (!i.mem_operands)
4729             i.rm.mode = 3;
4730         }
4731
4732       /* Fill in i.rm.reg field with extension opcode (if any).  */
4733       if (i.tm.extension_opcode != None
4734           && !(i.tm.opcode_modifier.drex 
4735               || i.tm.opcode_modifier.drexv 
4736               || i.tm.opcode_modifier.drexc))
4737         i.rm.reg = i.tm.extension_opcode;
4738     }
4739   return default_seg;
4740 }
4741
4742 static void
4743 output_branch (void)
4744 {
4745   char *p;
4746   int code16;
4747   int prefix;
4748   relax_substateT subtype;
4749   symbolS *sym;
4750   offsetT off;
4751
4752   code16 = 0;
4753   if (flag_code == CODE_16BIT)
4754     code16 = CODE16;
4755
4756   prefix = 0;
4757   if (i.prefix[DATA_PREFIX] != 0)
4758     {
4759       prefix = 1;
4760       i.prefixes -= 1;
4761       code16 ^= CODE16;
4762     }
4763   /* Pentium4 branch hints.  */
4764   if (i.prefix[SEG_PREFIX] == CS_PREFIX_OPCODE /* not taken */
4765       || i.prefix[SEG_PREFIX] == DS_PREFIX_OPCODE /* taken */)
4766     {
4767       prefix++;
4768       i.prefixes--;
4769     }
4770   if (i.prefix[REX_PREFIX] != 0)
4771     {
4772       prefix++;
4773       i.prefixes--;
4774     }
4775
4776   if (i.prefixes != 0 && !intel_syntax)
4777     as_warn (_("skipping prefixes on this instruction"));
4778
4779   /* It's always a symbol;  End frag & setup for relax.
4780      Make sure there is enough room in this frag for the largest
4781      instruction we may generate in md_convert_frag.  This is 2
4782      bytes for the opcode and room for the prefix and largest
4783      displacement.  */
4784   frag_grow (prefix + 2 + 4);
4785   /* Prefix and 1 opcode byte go in fr_fix.  */
4786   p = frag_more (prefix + 1);
4787   if (i.prefix[DATA_PREFIX] != 0)
4788     *p++ = DATA_PREFIX_OPCODE;
4789   if (i.prefix[SEG_PREFIX] == CS_PREFIX_OPCODE
4790       || i.prefix[SEG_PREFIX] == DS_PREFIX_OPCODE)
4791     *p++ = i.prefix[SEG_PREFIX];
4792   if (i.prefix[REX_PREFIX] != 0)
4793     *p++ = i.prefix[REX_PREFIX];
4794   *p = i.tm.base_opcode;
4795
4796   if ((unsigned char) *p == JUMP_PC_RELATIVE)
4797     subtype = ENCODE_RELAX_STATE (UNCOND_JUMP, SMALL);
4798   else if (cpu_arch_flags.bitfield.cpui386)
4799     subtype = ENCODE_RELAX_STATE (COND_JUMP, SMALL);
4800   else
4801     subtype = ENCODE_RELAX_STATE (COND_JUMP86, SMALL);
4802   subtype |= code16;
4803
4804   sym = i.op[0].disps->X_add_symbol;
4805   off = i.op[0].disps->X_add_number;
4806
4807   if (i.op[0].disps->X_op != O_constant
4808       && i.op[0].disps->X_op != O_symbol)
4809     {
4810       /* Handle complex expressions.  */
4811       sym = make_expr_symbol (i.op[0].disps);
4812       off = 0;
4813     }
4814
4815   /* 1 possible extra opcode + 4 byte displacement go in var part.
4816      Pass reloc in fr_var.  */
4817   frag_var (rs_machine_dependent, 5, i.reloc[0], subtype, sym, off, p);
4818 }
4819
4820 static void
4821 output_jump (void)
4822 {
4823   char *p;
4824   int size;
4825   fixS *fixP;
4826
4827   if (i.tm.opcode_modifier.jumpbyte)
4828     {
4829       /* This is a loop or jecxz type instruction.  */
4830       size = 1;
4831       if (i.prefix[ADDR_PREFIX] != 0)
4832         {
4833           FRAG_APPEND_1_CHAR (ADDR_PREFIX_OPCODE);
4834           i.prefixes -= 1;
4835         }
4836       /* Pentium4 branch hints.  */
4837       if (i.prefix[SEG_PREFIX] == CS_PREFIX_OPCODE /* not taken */
4838           || i.prefix[SEG_PREFIX] == DS_PREFIX_OPCODE /* taken */)
4839         {
4840           FRAG_APPEND_1_CHAR (i.prefix[SEG_PREFIX]);
4841           i.prefixes--;
4842         }
4843     }
4844   else
4845     {
4846       int code16;
4847
4848       code16 = 0;
4849       if (flag_code == CODE_16BIT)
4850         code16 = CODE16;
4851
4852       if (i.prefix[DATA_PREFIX] != 0)
4853         {
4854           FRAG_APPEND_1_CHAR (DATA_PREFIX_OPCODE);
4855           i.prefixes -= 1;
4856           code16 ^= CODE16;
4857         }
4858
4859       size = 4;
4860       if (code16)
4861         size = 2;
4862     }
4863
4864   if (i.prefix[REX_PREFIX] != 0)
4865     {
4866       FRAG_APPEND_1_CHAR (i.prefix[REX_PREFIX]);
4867       i.prefixes -= 1;
4868     }
4869
4870   if (i.prefixes != 0 && !intel_syntax)
4871     as_warn (_("skipping prefixes on this instruction"));
4872
4873   p = frag_more (1 + size);
4874   *p++ = i.tm.base_opcode;
4875
4876   fixP = fix_new_exp (frag_now, p - frag_now->fr_literal, size,
4877                       i.op[0].disps, 1, reloc (size, 1, 1, i.reloc[0]));
4878
4879   /* All jumps handled here are signed, but don't use a signed limit
4880      check for 32 and 16 bit jumps as we want to allow wrap around at
4881      4G and 64k respectively.  */
4882   if (size == 1)
4883     fixP->fx_signed = 1;
4884 }
4885
4886 static void
4887 output_interseg_jump (void)
4888 {
4889   char *p;
4890   int size;
4891   int prefix;
4892   int code16;
4893
4894   code16 = 0;
4895   if (flag_code == CODE_16BIT)
4896     code16 = CODE16;
4897
4898   prefix = 0;
4899   if (i.prefix[DATA_PREFIX] != 0)
4900     {
4901       prefix = 1;
4902       i.prefixes -= 1;
4903       code16 ^= CODE16;
4904     }
4905   if (i.prefix[REX_PREFIX] != 0)
4906     {
4907       prefix++;
4908       i.prefixes -= 1;
4909     }
4910
4911   size = 4;
4912   if (code16)
4913     size = 2;
4914
4915   if (i.prefixes != 0 && !intel_syntax)
4916     as_warn (_("skipping prefixes on this instruction"));
4917
4918   /* 1 opcode; 2 segment; offset  */
4919   p = frag_more (prefix + 1 + 2 + size);
4920
4921   if (i.prefix[DATA_PREFIX] != 0)
4922     *p++ = DATA_PREFIX_OPCODE;
4923
4924   if (i.prefix[REX_PREFIX] != 0)
4925     *p++ = i.prefix[REX_PREFIX];
4926
4927   *p++ = i.tm.base_opcode;
4928   if (i.op[1].imms->X_op == O_constant)
4929     {
4930       offsetT n = i.op[1].imms->X_add_number;
4931
4932       if (size == 2
4933           && !fits_in_unsigned_word (n)
4934           && !fits_in_signed_word (n))
4935         {
4936           as_bad (_("16-bit jump out of range"));
4937           return;
4938         }
4939       md_number_to_chars (p, n, size);
4940     }
4941   else
4942     fix_new_exp (frag_now, p - frag_now->fr_literal, size,
4943                  i.op[1].imms, 0, reloc (size, 0, 0, i.reloc[1]));
4944   if (i.op[0].imms->X_op != O_constant)
4945     as_bad (_("can't handle non absolute segment in `%s'"),
4946             i.tm.name);
4947   md_number_to_chars (p + size, (valueT) i.op[0].imms->X_add_number, 2);
4948 }
4949
4950 static void
4951 output_insn (void)
4952 {
4953   fragS *insn_start_frag;
4954   offsetT insn_start_off;
4955
4956   /* Tie dwarf2 debug info to the address at the start of the insn.
4957      We can't do this after the insn has been output as the current
4958      frag may have been closed off.  eg. by frag_var.  */
4959   dwarf2_emit_insn (0);
4960
4961   insn_start_frag = frag_now;
4962   insn_start_off = frag_now_fix ();
4963
4964   /* Output jumps.  */
4965   if (i.tm.opcode_modifier.jump)
4966     output_branch ();
4967   else if (i.tm.opcode_modifier.jumpbyte
4968            || i.tm.opcode_modifier.jumpdword)
4969     output_jump ();
4970   else if (i.tm.opcode_modifier.jumpintersegment)
4971     output_interseg_jump ();
4972   else
4973     {
4974       /* Output normal instructions here.  */
4975       char *p;
4976       unsigned char *q;
4977       unsigned int prefix;
4978
4979       switch (i.tm.opcode_length)
4980         {
4981         case 3:
4982           if (i.tm.base_opcode & 0xff000000)
4983             {
4984               prefix = (i.tm.base_opcode >> 24) & 0xff;
4985               goto check_prefix;
4986             }
4987           break;
4988         case 2:
4989           if ((i.tm.base_opcode & 0xff0000) != 0)
4990             {
4991               prefix = (i.tm.base_opcode >> 16) & 0xff;
4992               if (i.tm.cpu_flags.bitfield.cpupadlock)
4993                 {
4994 check_prefix:
4995                   if (prefix != REPE_PREFIX_OPCODE
4996                       || i.prefix[LOCKREP_PREFIX] != REPE_PREFIX_OPCODE)
4997                     add_prefix (prefix);
4998                 }
4999               else
5000                 add_prefix (prefix);
5001             }
5002           break;
5003         case 1:
5004           break;
5005         default:
5006           abort ();
5007         }
5008
5009       /* The prefix bytes.  */
5010       for (q = i.prefix;
5011            q < i.prefix + sizeof (i.prefix) / sizeof (i.prefix[0]);
5012            q++)
5013         {
5014           if (*q)
5015             {
5016               p = frag_more (1);
5017               md_number_to_chars (p, (valueT) *q, 1);
5018             }
5019         }
5020
5021       /* Now the opcode; be careful about word order here!  */
5022       if (i.tm.opcode_length == 1)
5023         {
5024           FRAG_APPEND_1_CHAR (i.tm.base_opcode);
5025         }
5026       else
5027         {
5028           switch (i.tm.opcode_length)
5029             {
5030             case 3:
5031               p = frag_more (3);
5032               *p++ = (i.tm.base_opcode >> 16) & 0xff;
5033               break;
5034             case 2:
5035               p = frag_more (2);
5036               break;
5037             default:
5038               abort ();
5039               break;
5040             }
5041
5042           /* Put out high byte first: can't use md_number_to_chars!  */
5043           *p++ = (i.tm.base_opcode >> 8) & 0xff;
5044           *p = i.tm.base_opcode & 0xff;
5045
5046           /* On SSE5, encode the OC1 bit in the DREX field if this 
5047              encoding has multiple formats.  */
5048           if (i.tm.opcode_modifier.drex 
5049               && i.tm.opcode_modifier.drexv 
5050               && DREX_OC1 (i.tm.extension_opcode))
5051             *p |= DREX_OC1_MASK;
5052         }
5053
5054       /* Now the modrm byte and sib byte (if present).  */
5055       if (i.tm.opcode_modifier.modrm)
5056         {
5057           p = frag_more (1);
5058           md_number_to_chars (p,
5059                               (valueT) (i.rm.regmem << 0
5060                                         | i.rm.reg << 3
5061                                         | i.rm.mode << 6),
5062                               1);
5063           /* If i.rm.regmem == ESP (4)
5064              && i.rm.mode != (Register mode)
5065              && not 16 bit
5066              ==> need second modrm byte.  */
5067           if (i.rm.regmem == ESCAPE_TO_TWO_BYTE_ADDRESSING
5068               && i.rm.mode != 3
5069               && !(i.base_reg && i.base_reg->reg_type.bitfield.reg16))
5070             {
5071               p = frag_more (1);
5072               md_number_to_chars (p,
5073                                   (valueT) (i.sib.base << 0
5074                                             | i.sib.index << 3
5075                                             | i.sib.scale << 6),
5076                                   1);
5077             }
5078         }
5079
5080       /* Write the DREX byte if needed.  */
5081       if (i.tm.opcode_modifier.drex || i.tm.opcode_modifier.drexc)
5082         {
5083           p = frag_more (1);
5084           *p = (((i.drex.reg & 0xf) << 4) | (i.drex.rex & 0x7));
5085
5086           /* Encode the OC0 bit if this encoding has multiple 
5087              formats.  */
5088           if ((i.tm.opcode_modifier.drex 
5089                || i.tm.opcode_modifier.drexv) 
5090               && DREX_OC0 (i.tm.extension_opcode))
5091             *p |= DREX_OC0_MASK;
5092         }
5093
5094       if (i.disp_operands)
5095         output_disp (insn_start_frag, insn_start_off);
5096
5097       if (i.imm_operands)
5098         output_imm (insn_start_frag, insn_start_off);
5099     }
5100
5101 #ifdef DEBUG386
5102   if (flag_debug)
5103     {
5104       pi ("" /*line*/, &i);
5105     }
5106 #endif /* DEBUG386  */
5107 }
5108
5109 /* Return the size of the displacement operand N.  */
5110
5111 static int
5112 disp_size (unsigned int n)
5113 {
5114   int size = 4;
5115   if (i.types[n].bitfield.disp64)
5116     size = 8;
5117   else if (i.types[n].bitfield.disp8)
5118     size = 1;
5119   else if (i.types[n].bitfield.disp16)
5120     size = 2;
5121   return size;
5122 }
5123
5124 /* Return the size of the immediate operand N.  */
5125
5126 static int
5127 imm_size (unsigned int n)
5128 {
5129   int size = 4;
5130   if (i.types[n].bitfield.imm64)
5131     size = 8;
5132   else if (i.types[n].bitfield.imm8 || i.types[n].bitfield.imm8s)
5133     size = 1;
5134   else if (i.types[n].bitfield.imm16)
5135     size = 2;
5136   return size;
5137 }
5138
5139 static void
5140 output_disp (fragS *insn_start_frag, offsetT insn_start_off)
5141 {
5142   char *p;
5143   unsigned int n;
5144
5145   for (n = 0; n < i.operands; n++)
5146     {
5147       if (operand_type_check (i.types[n], disp))
5148         {
5149           if (i.op[n].disps->X_op == O_constant)
5150             {
5151               int size = disp_size (n);
5152               offsetT val;
5153
5154               val = offset_in_range (i.op[n].disps->X_add_number,
5155                                      size);
5156               p = frag_more (size);
5157               md_number_to_chars (p, val, size);
5158             }
5159           else
5160             {
5161               enum bfd_reloc_code_real reloc_type;
5162               int size = disp_size (n);
5163               int sign = i.types[n].bitfield.disp32s;
5164               int pcrel = (i.flags[n] & Operand_PCrel) != 0;
5165
5166               /* We can't have 8 bit displacement here.  */
5167               assert (!i.types[n].bitfield.disp8);
5168
5169               /* The PC relative address is computed relative
5170                  to the instruction boundary, so in case immediate
5171                  fields follows, we need to adjust the value.  */
5172               if (pcrel && i.imm_operands)
5173                 {
5174                   unsigned int n1;
5175                   int sz = 0;
5176
5177                   for (n1 = 0; n1 < i.operands; n1++)
5178                     if (operand_type_check (i.types[n1], imm))
5179                       {
5180                         /* Only one immediate is allowed for PC
5181                            relative address.  */
5182                         assert (sz == 0);
5183                         sz = imm_size (n1);
5184                         i.op[n].disps->X_add_number -= sz;
5185                       }
5186                   /* We should find the immediate.  */
5187                   assert (sz != 0);
5188                 }
5189
5190               p = frag_more (size);
5191               reloc_type = reloc (size, pcrel, sign, i.reloc[n]);
5192               if (GOT_symbol
5193                   && GOT_symbol == i.op[n].disps->X_add_symbol
5194                   && (((reloc_type == BFD_RELOC_32
5195                         || reloc_type == BFD_RELOC_X86_64_32S
5196                         || (reloc_type == BFD_RELOC_64
5197                             && object_64bit))
5198                        && (i.op[n].disps->X_op == O_symbol
5199                            || (i.op[n].disps->X_op == O_add
5200                                && ((symbol_get_value_expression
5201                                     (i.op[n].disps->X_op_symbol)->X_op)
5202                                    == O_subtract))))
5203                       || reloc_type == BFD_RELOC_32_PCREL))
5204                 {
5205                   offsetT add;
5206
5207                   if (insn_start_frag == frag_now)
5208                     add = (p - frag_now->fr_literal) - insn_start_off;
5209                   else
5210                     {
5211                       fragS *fr;
5212
5213                       add = insn_start_frag->fr_fix - insn_start_off;
5214                       for (fr = insn_start_frag->fr_next;
5215                            fr && fr != frag_now; fr = fr->fr_next)
5216                         add += fr->fr_fix;
5217                       add += p - frag_now->fr_literal;
5218                     }
5219
5220                   if (!object_64bit)
5221                     {
5222                       reloc_type = BFD_RELOC_386_GOTPC;
5223                       i.op[n].imms->X_add_number += add;
5224                     }
5225                   else if (reloc_type == BFD_RELOC_64)
5226                     reloc_type = BFD_RELOC_X86_64_GOTPC64;
5227                   else
5228                     /* Don't do the adjustment for x86-64, as there
5229                        the pcrel addressing is relative to the _next_
5230                        insn, and that is taken care of in other code.  */
5231                     reloc_type = BFD_RELOC_X86_64_GOTPC32;
5232                 }
5233               fix_new_exp (frag_now, p - frag_now->fr_literal, size,
5234                            i.op[n].disps, pcrel, reloc_type);
5235             }
5236         }
5237     }
5238 }
5239
5240 static void
5241 output_imm (fragS *insn_start_frag, offsetT insn_start_off)
5242 {
5243   char *p;
5244   unsigned int n;
5245
5246   for (n = 0; n < i.operands; n++)
5247     {
5248       if (operand_type_check (i.types[n], imm))
5249         {
5250           if (i.op[n].imms->X_op == O_constant)
5251             {
5252               int size = imm_size (n);
5253               offsetT val;
5254
5255               val = offset_in_range (i.op[n].imms->X_add_number,
5256                                      size);
5257               p = frag_more (size);
5258               md_number_to_chars (p, val, size);
5259             }
5260           else
5261             {
5262               /* Not absolute_section.
5263                  Need a 32-bit fixup (don't support 8bit
5264                  non-absolute imms).  Try to support other
5265                  sizes ...  */
5266               enum bfd_reloc_code_real reloc_type;
5267               int size = imm_size (n);
5268               int sign;
5269
5270               if (i.types[n].bitfield.imm32s
5271                   && (i.suffix == QWORD_MNEM_SUFFIX
5272                       || (!i.suffix && i.tm.opcode_modifier.no_lsuf)))
5273                 sign = 1;
5274               else
5275                 sign = 0;
5276
5277               p = frag_more (size);
5278               reloc_type = reloc (size, 0, sign, i.reloc[n]);
5279
5280               /*   This is tough to explain.  We end up with this one if we
5281                * have operands that look like
5282                * "_GLOBAL_OFFSET_TABLE_+[.-.L284]".  The goal here is to
5283                * obtain the absolute address of the GOT, and it is strongly
5284                * preferable from a performance point of view to avoid using
5285                * a runtime relocation for this.  The actual sequence of
5286                * instructions often look something like:
5287                *
5288                *        call    .L66
5289                * .L66:
5290                *        popl    %ebx
5291                *        addl    $_GLOBAL_OFFSET_TABLE_+[.-.L66],%ebx
5292                *
5293                *   The call and pop essentially return the absolute address
5294                * of the label .L66 and store it in %ebx.  The linker itself
5295                * will ultimately change the first operand of the addl so
5296                * that %ebx points to the GOT, but to keep things simple, the
5297                * .o file must have this operand set so that it generates not
5298                * the absolute address of .L66, but the absolute address of
5299                * itself.  This allows the linker itself simply treat a GOTPC
5300                * relocation as asking for a pcrel offset to the GOT to be
5301                * added in, and the addend of the relocation is stored in the
5302                * operand field for the instruction itself.
5303                *
5304                *   Our job here is to fix the operand so that it would add
5305                * the correct offset so that %ebx would point to itself.  The
5306                * thing that is tricky is that .-.L66 will point to the
5307                * beginning of the instruction, so we need to further modify
5308                * the operand so that it will point to itself.  There are
5309                * other cases where you have something like:
5310                *
5311                *        .long   $_GLOBAL_OFFSET_TABLE_+[.-.L66]
5312                *
5313                * and here no correction would be required.  Internally in
5314                * the assembler we treat operands of this form as not being
5315                * pcrel since the '.' is explicitly mentioned, and I wonder
5316                * whether it would simplify matters to do it this way.  Who
5317                * knows.  In earlier versions of the PIC patches, the
5318                * pcrel_adjust field was used to store the correction, but
5319                * since the expression is not pcrel, I felt it would be
5320                * confusing to do it this way.  */
5321
5322               if ((reloc_type == BFD_RELOC_32
5323                    || reloc_type == BFD_RELOC_X86_64_32S
5324                    || reloc_type == BFD_RELOC_64)
5325                   && GOT_symbol
5326                   && GOT_symbol == i.op[n].imms->X_add_symbol
5327                   && (i.op[n].imms->X_op == O_symbol
5328                       || (i.op[n].imms->X_op == O_add
5329                           && ((symbol_get_value_expression
5330                                (i.op[n].imms->X_op_symbol)->X_op)
5331                               == O_subtract))))
5332                 {
5333                   offsetT add;
5334
5335                   if (insn_start_frag == frag_now)
5336                     add = (p - frag_now->fr_literal) - insn_start_off;
5337                   else
5338                     {
5339                       fragS *fr;
5340
5341                       add = insn_start_frag->fr_fix - insn_start_off;
5342                       for (fr = insn_start_frag->fr_next;
5343                            fr && fr != frag_now; fr = fr->fr_next)
5344                         add += fr->fr_fix;
5345                       add += p - frag_now->fr_literal;
5346                     }
5347
5348                   if (!object_64bit)
5349                     reloc_type = BFD_RELOC_386_GOTPC;
5350                   else if (size == 4)
5351                     reloc_type = BFD_RELOC_X86_64_GOTPC32;
5352                   else if (size == 8)
5353                     reloc_type = BFD_RELOC_X86_64_GOTPC64;
5354                   i.op[n].imms->X_add_number += add;
5355                 }
5356               fix_new_exp (frag_now, p - frag_now->fr_literal, size,
5357                            i.op[n].imms, 0, reloc_type);
5358             }
5359         }
5360     }
5361 }
5362 \f
5363 /* x86_cons_fix_new is called via the expression parsing code when a
5364    reloc is needed.  We use this hook to get the correct .got reloc.  */
5365 static enum bfd_reloc_code_real got_reloc = NO_RELOC;
5366 static int cons_sign = -1;
5367
5368 void
5369 x86_cons_fix_new (fragS *frag, unsigned int off, unsigned int len,
5370                   expressionS *exp)
5371 {
5372   enum bfd_reloc_code_real r = reloc (len, 0, cons_sign, got_reloc);
5373
5374   got_reloc = NO_RELOC;
5375
5376 #ifdef TE_PE
5377   if (exp->X_op == O_secrel)
5378     {
5379       exp->X_op = O_symbol;
5380       r = BFD_RELOC_32_SECREL;
5381     }
5382 #endif
5383
5384   fix_new_exp (frag, off, len, exp, 0, r);
5385 }
5386
5387 #if (!defined (OBJ_ELF) && !defined (OBJ_MAYBE_ELF)) || defined (LEX_AT)
5388 # define lex_got(reloc, adjust, types) NULL
5389 #else
5390 /* Parse operands of the form
5391    <symbol>@GOTOFF+<nnn>
5392    and similar .plt or .got references.
5393
5394    If we find one, set up the correct relocation in RELOC and copy the
5395    input string, minus the `@GOTOFF' into a malloc'd buffer for
5396    parsing by the calling routine.  Return this buffer, and if ADJUST
5397    is non-null set it to the length of the string we removed from the
5398    input line.  Otherwise return NULL.  */
5399 static char *
5400 lex_got (enum bfd_reloc_code_real *reloc,
5401          int *adjust,
5402          i386_operand_type *types)
5403 {
5404   /* Some of the relocations depend on the size of what field is to
5405      be relocated.  But in our callers i386_immediate and i386_displacement
5406      we don't yet know the operand size (this will be set by insn
5407      matching).  Hence we record the word32 relocation here,
5408      and adjust the reloc according to the real size in reloc().  */
5409   static const struct {
5410     const char *str;
5411     const enum bfd_reloc_code_real rel[2];
5412     const i386_operand_type types64;
5413   } gotrel[] = {
5414     { "PLTOFF",   { 0,
5415                     BFD_RELOC_X86_64_PLTOFF64 },
5416       OPERAND_TYPE_IMM64 },
5417     { "PLT",      { BFD_RELOC_386_PLT32,
5418                     BFD_RELOC_X86_64_PLT32    },
5419       OPERAND_TYPE_IMM32_32S_DISP32 },
5420     { "GOTPLT",   { 0,
5421                     BFD_RELOC_X86_64_GOTPLT64 },
5422       OPERAND_TYPE_IMM64_DISP64 },
5423     { "GOTOFF",   { BFD_RELOC_386_GOTOFF,
5424                     BFD_RELOC_X86_64_GOTOFF64 },
5425       OPERAND_TYPE_IMM64_DISP64 },
5426     { "GOTPCREL", { 0,
5427                     BFD_RELOC_X86_64_GOTPCREL },
5428       OPERAND_TYPE_IMM32_32S_DISP32 },
5429     { "TLSGD",    { BFD_RELOC_386_TLS_GD,
5430                     BFD_RELOC_X86_64_TLSGD    },
5431       OPERAND_TYPE_IMM32_32S_DISP32 },
5432     { "TLSLDM",   { BFD_RELOC_386_TLS_LDM,
5433                     0                         },
5434       OPERAND_TYPE_NONE },
5435     { "TLSLD",    { 0,
5436                     BFD_RELOC_X86_64_TLSLD    },
5437       OPERAND_TYPE_IMM32_32S_DISP32 },
5438     { "GOTTPOFF", { BFD_RELOC_386_TLS_IE_32,
5439                     BFD_RELOC_X86_64_GOTTPOFF },
5440       OPERAND_TYPE_IMM32_32S_DISP32 },
5441     { "TPOFF",    { BFD_RELOC_386_TLS_LE_32,
5442                     BFD_RELOC_X86_64_TPOFF32  },
5443       OPERAND_TYPE_IMM32_32S_64_DISP32_64 },
5444     { "NTPOFF",   { BFD_RELOC_386_TLS_LE,
5445                     0                         },
5446       OPERAND_TYPE_NONE },
5447     { "DTPOFF",   { BFD_RELOC_386_TLS_LDO_32,
5448                     BFD_RELOC_X86_64_DTPOFF32 },
5449       
5450       OPERAND_TYPE_IMM32_32S_64_DISP32_64 },
5451     { "GOTNTPOFF",{ BFD_RELOC_386_TLS_GOTIE,
5452                     0                         },
5453       OPERAND_TYPE_NONE },
5454     { "INDNTPOFF",{ BFD_RELOC_386_TLS_IE,
5455                     0                         },
5456       OPERAND_TYPE_NONE },
5457     { "GOT",      { BFD_RELOC_386_GOT32,
5458                     BFD_RELOC_X86_64_GOT32    },
5459       OPERAND_TYPE_IMM32_32S_64_DISP32 },
5460     { "TLSDESC",  { BFD_RELOC_386_TLS_GOTDESC,
5461                     BFD_RELOC_X86_64_GOTPC32_TLSDESC },
5462       OPERAND_TYPE_IMM32_32S_DISP32 },
5463     { "TLSCALL",  { BFD_RELOC_386_TLS_DESC_CALL,
5464                     BFD_RELOC_X86_64_TLSDESC_CALL },
5465       OPERAND_TYPE_IMM32_32S_DISP32 },
5466   };
5467   char *cp;
5468   unsigned int j;
5469
5470   if (!IS_ELF)
5471     return NULL;
5472
5473   for (cp = input_line_pointer; *cp != '@'; cp++)
5474     if (is_end_of_line[(unsigned char) *cp] || *cp == ',')
5475       return NULL;
5476
5477   for (j = 0; j < sizeof (gotrel) / sizeof (gotrel[0]); j++)
5478     {
5479       int len;
5480
5481       len = strlen (gotrel[j].str);
5482       if (strncasecmp (cp + 1, gotrel[j].str, len) == 0)
5483         {
5484           if (gotrel[j].rel[object_64bit] != 0)
5485             {
5486               int first, second;
5487               char *tmpbuf, *past_reloc;
5488
5489               *reloc = gotrel[j].rel[object_64bit];
5490               if (adjust)
5491                 *adjust = len;
5492
5493               if (types)
5494                 {
5495                   if (flag_code != CODE_64BIT)
5496                     {
5497                       types->bitfield.imm32 = 1;
5498                       types->bitfield.disp32 = 1;
5499                     }
5500                   else
5501                     *types = gotrel[j].types64;
5502                 }
5503
5504               if (GOT_symbol == NULL)
5505                 GOT_symbol = symbol_find_or_make (GLOBAL_OFFSET_TABLE_NAME);
5506
5507               /* The length of the first part of our input line.  */
5508               first = cp - input_line_pointer;
5509
5510               /* The second part goes from after the reloc token until
5511                  (and including) an end_of_line char or comma.  */
5512               past_reloc = cp + 1 + len;
5513               cp = past_reloc;
5514               while (!is_end_of_line[(unsigned char) *cp] && *cp != ',')
5515                 ++cp;
5516               second = cp + 1 - past_reloc;
5517
5518               /* Allocate and copy string.  The trailing NUL shouldn't
5519                  be necessary, but be safe.  */
5520               tmpbuf = xmalloc (first + second + 2);
5521               memcpy (tmpbuf, input_line_pointer, first);
5522               if (second != 0 && *past_reloc != ' ')
5523                 /* Replace the relocation token with ' ', so that
5524                    errors like foo@GOTOFF1 will be detected.  */
5525                 tmpbuf[first++] = ' ';
5526               memcpy (tmpbuf + first, past_reloc, second);
5527               tmpbuf[first + second] = '\0';
5528               return tmpbuf;
5529             }
5530
5531           as_bad (_("@%s reloc is not supported with %d-bit output format"),
5532                   gotrel[j].str, 1 << (5 + object_64bit));
5533           return NULL;
5534         }
5535     }
5536
5537   /* Might be a symbol version string.  Don't as_bad here.  */
5538   return NULL;
5539 }
5540
5541 void
5542 x86_cons (expressionS *exp, int size)
5543 {
5544   if (size == 4 || (object_64bit && size == 8))
5545     {
5546       /* Handle @GOTOFF and the like in an expression.  */
5547       char *save;
5548       char *gotfree_input_line;
5549       int adjust;
5550
5551       save = input_line_pointer;
5552       gotfree_input_line = lex_got (&got_reloc, &adjust, NULL);
5553       if (gotfree_input_line)
5554         input_line_pointer = gotfree_input_line;
5555
5556       expression (exp);
5557
5558       if (gotfree_input_line)
5559         {
5560           /* expression () has merrily parsed up to the end of line,
5561              or a comma - in the wrong buffer.  Transfer how far
5562              input_line_pointer has moved to the right buffer.  */
5563           input_line_pointer = (save
5564                                 + (input_line_pointer - gotfree_input_line)
5565                                 + adjust);
5566           free (gotfree_input_line);
5567           if (exp->X_op == O_constant
5568               || exp->X_op == O_absent
5569               || exp->X_op == O_illegal
5570               || exp->X_op == O_register
5571               || exp->X_op == O_big)
5572             {
5573               char c = *input_line_pointer;
5574               *input_line_pointer = 0;
5575               as_bad (_("missing or invalid expression `%s'"), save);
5576               *input_line_pointer = c;
5577             }
5578         }
5579     }
5580   else
5581     expression (exp);
5582 }
5583 #endif
5584
5585 static void signed_cons (int size)
5586 {
5587   if (flag_code == CODE_64BIT)
5588     cons_sign = 1;
5589   cons (size);
5590   cons_sign = -1;
5591 }
5592
5593 #ifdef TE_PE
5594 static void
5595 pe_directive_secrel (dummy)
5596      int dummy ATTRIBUTE_UNUSED;
5597 {
5598   expressionS exp;
5599
5600   do
5601     {
5602       expression (&exp);
5603       if (exp.X_op == O_symbol)
5604         exp.X_op = O_secrel;
5605
5606       emit_expr (&exp, 4);
5607     }
5608   while (*input_line_pointer++ == ',');
5609
5610   input_line_pointer--;
5611   demand_empty_rest_of_line ();
5612 }
5613 #endif
5614
5615 static int
5616 i386_immediate (char *imm_start)
5617 {
5618   char *save_input_line_pointer;
5619   char *gotfree_input_line;
5620   segT exp_seg = 0;
5621   expressionS *exp;
5622   i386_operand_type types;
5623
5624   UINTS_SET (types, ~0);
5625
5626   if (i.imm_operands == MAX_IMMEDIATE_OPERANDS)
5627     {
5628       as_bad (_("at most %d immediate operands are allowed"),
5629               MAX_IMMEDIATE_OPERANDS);
5630       return 0;
5631     }
5632
5633   exp = &im_expressions[i.imm_operands++];
5634   i.op[this_operand].imms = exp;
5635
5636   if (is_space_char (*imm_start))
5637     ++imm_start;
5638
5639   save_input_line_pointer = input_line_pointer;
5640   input_line_pointer = imm_start;
5641
5642   gotfree_input_line = lex_got (&i.reloc[this_operand], NULL, &types);
5643   if (gotfree_input_line)
5644     input_line_pointer = gotfree_input_line;
5645
5646   exp_seg = expression (exp);
5647
5648   SKIP_WHITESPACE ();
5649   if (*input_line_pointer)
5650     as_bad (_("junk `%s' after expression"), input_line_pointer);
5651
5652   input_line_pointer = save_input_line_pointer;
5653   if (gotfree_input_line)
5654     free (gotfree_input_line);
5655
5656   if (exp->X_op == O_absent
5657       || exp->X_op == O_illegal
5658       || exp->X_op == O_big
5659       || (gotfree_input_line
5660           && (exp->X_op == O_constant
5661               || exp->X_op == O_register)))
5662     {
5663       as_bad (_("missing or invalid immediate expression `%s'"),
5664               imm_start);
5665       return 0;
5666     }
5667   else if (exp->X_op == O_constant)
5668     {
5669       /* Size it properly later.  */
5670       i.types[this_operand].bitfield.imm64 = 1;
5671       /* If BFD64, sign extend val.  */
5672       if (!use_rela_relocations
5673           && (exp->X_add_number & ~(((addressT) 2 << 31) - 1)) == 0)
5674         exp->X_add_number
5675           = (exp->X_add_number ^ ((addressT) 1 << 31)) - ((addressT) 1 << 31);
5676     }
5677 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
5678   else if (OUTPUT_FLAVOR == bfd_target_aout_flavour
5679            && exp_seg != absolute_section
5680            && exp_seg != text_section
5681            && exp_seg != data_section
5682            && exp_seg != bss_section
5683            && exp_seg != undefined_section
5684            && !bfd_is_com_section (exp_seg))
5685     {
5686       as_bad (_("unimplemented segment %s in operand"), exp_seg->name);
5687       return 0;
5688     }
5689 #endif
5690   else if (!intel_syntax && exp->X_op == O_register)
5691     {
5692       as_bad (_("illegal immediate register operand %s"), imm_start);
5693       return 0;
5694     }
5695   else
5696     {
5697       /* This is an address.  The size of the address will be
5698          determined later, depending on destination register,
5699          suffix, or the default for the section.  */
5700       i.types[this_operand].bitfield.imm8 = 1;
5701       i.types[this_operand].bitfield.imm16 = 1;
5702       i.types[this_operand].bitfield.imm32 = 1;
5703       i.types[this_operand].bitfield.imm32s = 1;
5704       i.types[this_operand].bitfield.imm64 = 1;
5705       i.types[this_operand] = operand_type_and (i.types[this_operand],
5706                                                 types);
5707     }
5708
5709   return 1;
5710 }
5711
5712 static char *
5713 i386_scale (char *scale)
5714 {
5715   offsetT val;
5716   char *save = input_line_pointer;
5717
5718   input_line_pointer = scale;
5719   val = get_absolute_expression ();
5720
5721   switch (val)
5722     {
5723     case 1:
5724       i.log2_scale_factor = 0;
5725       break;
5726     case 2:
5727       i.log2_scale_factor = 1;
5728       break;
5729     case 4:
5730       i.log2_scale_factor = 2;
5731       break;
5732     case 8:
5733       i.log2_scale_factor = 3;
5734       break;
5735     default:
5736       {
5737         char sep = *input_line_pointer;
5738
5739         *input_line_pointer = '\0';
5740         as_bad (_("expecting scale factor of 1, 2, 4, or 8: got `%s'"),
5741                 scale);
5742         *input_line_pointer = sep;
5743         input_line_pointer = save;
5744         return NULL;
5745       }
5746     }
5747   if (i.log2_scale_factor != 0 && i.index_reg == 0)
5748     {
5749       as_warn (_("scale factor of %d without an index register"),
5750                1 << i.log2_scale_factor);
5751       i.log2_scale_factor = 0;
5752     }
5753   scale = input_line_pointer;
5754   input_line_pointer = save;
5755   return scale;
5756 }
5757
5758 static int
5759 i386_displacement (char *disp_start, char *disp_end)
5760 {
5761   expressionS *exp;
5762   segT exp_seg = 0;
5763   char *save_input_line_pointer;
5764   char *gotfree_input_line;
5765   int override;
5766   i386_operand_type bigdisp, types = anydisp;
5767   int ret;
5768
5769   if (i.disp_operands == MAX_MEMORY_OPERANDS)
5770     {
5771       as_bad (_("at most %d displacement operands are allowed"),
5772               MAX_MEMORY_OPERANDS);
5773       return 0;
5774     }
5775
5776   UINTS_CLEAR (bigdisp);
5777   if ((i.types[this_operand].bitfield.jumpabsolute)
5778       || (!current_templates->start->opcode_modifier.jump
5779           && !current_templates->start->opcode_modifier.jumpdword))
5780     {
5781       bigdisp.bitfield.disp32 = 1;
5782       override = (i.prefix[ADDR_PREFIX] != 0);
5783       if (flag_code == CODE_64BIT)
5784         {
5785           if (!override)
5786             {
5787               bigdisp.bitfield.disp32s = 1;
5788               bigdisp.bitfield.disp64 = 1;
5789             }
5790         }
5791       else if ((flag_code == CODE_16BIT) ^ override)
5792         {
5793           bigdisp.bitfield.disp32 = 0;
5794           bigdisp.bitfield.disp16 = 1;
5795         }
5796     }
5797   else
5798     {
5799       /* For PC-relative branches, the width of the displacement
5800          is dependent upon data size, not address size.  */
5801       override = (i.prefix[DATA_PREFIX] != 0);
5802       if (flag_code == CODE_64BIT)
5803         {
5804           if (override || i.suffix == WORD_MNEM_SUFFIX)
5805             bigdisp.bitfield.disp16 = 1;
5806           else
5807             {
5808               bigdisp.bitfield.disp32 = 1;
5809               bigdisp.bitfield.disp32s = 1;
5810             }
5811         }
5812       else
5813         {
5814           if (!override)
5815             override = (i.suffix == (flag_code != CODE_16BIT
5816                                      ? WORD_MNEM_SUFFIX
5817                                      : LONG_MNEM_SUFFIX));
5818           bigdisp.bitfield.disp32 = 1;
5819           if ((flag_code == CODE_16BIT) ^ override)
5820             {
5821               bigdisp.bitfield.disp32 = 0;
5822               bigdisp.bitfield.disp16 = 1;
5823             }
5824         }
5825     }
5826   i.types[this_operand] = operand_type_or (i.types[this_operand],
5827                                            bigdisp);
5828
5829   exp = &disp_expressions[i.disp_operands];
5830   i.op[this_operand].disps = exp;
5831   i.disp_operands++;
5832   save_input_line_pointer = input_line_pointer;
5833   input_line_pointer = disp_start;
5834   END_STRING_AND_SAVE (disp_end);
5835
5836 #ifndef GCC_ASM_O_HACK
5837 #define GCC_ASM_O_HACK 0
5838 #endif
5839 #if GCC_ASM_O_HACK
5840   END_STRING_AND_SAVE (disp_end + 1);
5841   if (i.types[this_operand].bitfield.baseIndex
5842       && displacement_string_end[-1] == '+')
5843     {
5844       /* This hack is to avoid a warning when using the "o"
5845          constraint within gcc asm statements.
5846          For instance:
5847
5848          #define _set_tssldt_desc(n,addr,limit,type) \
5849          __asm__ __volatile__ ( \
5850          "movw %w2,%0\n\t" \
5851          "movw %w1,2+%0\n\t" \
5852          "rorl $16,%1\n\t" \
5853          "movb %b1,4+%0\n\t" \
5854          "movb %4,5+%0\n\t" \
5855          "movb $0,6+%0\n\t" \
5856          "movb %h1,7+%0\n\t" \
5857          "rorl $16,%1" \
5858          : "=o"(*(n)) : "q" (addr), "ri"(limit), "i"(type))
5859
5860          This works great except that the output assembler ends
5861          up looking a bit weird if it turns out that there is
5862          no offset.  You end up producing code that looks like:
5863
5864          #APP
5865          movw $235,(%eax)
5866          movw %dx,2+(%eax)
5867          rorl $16,%edx
5868          movb %dl,4+(%eax)
5869          movb $137,5+(%eax)
5870          movb $0,6+(%eax)
5871          movb %dh,7+(%eax)
5872          rorl $16,%edx
5873          #NO_APP
5874
5875          So here we provide the missing zero.  */
5876
5877       *displacement_string_end = '0';
5878     }
5879 #endif
5880   gotfree_input_line = lex_got (&i.reloc[this_operand], NULL, &types);
5881   if (gotfree_input_line)
5882     input_line_pointer = gotfree_input_line;
5883
5884   exp_seg = expression (exp);
5885
5886   SKIP_WHITESPACE ();
5887   if (*input_line_pointer)
5888     as_bad (_("junk `%s' after expression"), input_line_pointer);
5889 #if GCC_ASM_O_HACK
5890   RESTORE_END_STRING (disp_end + 1);
5891 #endif
5892   input_line_pointer = save_input_line_pointer;
5893   if (gotfree_input_line)
5894     free (gotfree_input_line);
5895   ret = 1;
5896
5897   /* We do this to make sure that the section symbol is in
5898      the symbol table.  We will ultimately change the relocation
5899      to be relative to the beginning of the section.  */
5900   if (i.reloc[this_operand] == BFD_RELOC_386_GOTOFF
5901       || i.reloc[this_operand] == BFD_RELOC_X86_64_GOTPCREL
5902       || i.reloc[this_operand] == BFD_RELOC_X86_64_GOTOFF64)
5903     {
5904       if (exp->X_op != O_symbol)
5905         goto inv_disp;
5906
5907       if (S_IS_LOCAL (exp->X_add_symbol)
5908           && S_GET_SEGMENT (exp->X_add_symbol) != undefined_section)
5909         section_symbol (S_GET_SEGMENT (exp->X_add_symbol));
5910       exp->X_op = O_subtract;
5911       exp->X_op_symbol = GOT_symbol;
5912       if (i.reloc[this_operand] == BFD_RELOC_X86_64_GOTPCREL)
5913         i.reloc[this_operand] = BFD_RELOC_32_PCREL;
5914       else if (i.reloc[this_operand] == BFD_RELOC_X86_64_GOTOFF64)
5915         i.reloc[this_operand] = BFD_RELOC_64;
5916       else
5917         i.reloc[this_operand] = BFD_RELOC_32;
5918     }
5919
5920   else if (exp->X_op == O_absent
5921            || exp->X_op == O_illegal
5922            || exp->X_op == O_big
5923            || (gotfree_input_line
5924                && (exp->X_op == O_constant
5925                    || exp->X_op == O_register)))
5926     {
5927     inv_disp:
5928       as_bad (_("missing or invalid displacement expression `%s'"),
5929               disp_start);
5930       ret = 0;
5931     }
5932
5933 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
5934   else if (exp->X_op != O_constant
5935            && OUTPUT_FLAVOR == bfd_target_aout_flavour
5936            && exp_seg != absolute_section
5937            && exp_seg != text_section
5938            && exp_seg != data_section
5939            && exp_seg != bss_section
5940            && exp_seg != undefined_section
5941            && !bfd_is_com_section (exp_seg))
5942     {
5943       as_bad (_("unimplemented segment %s in operand"), exp_seg->name);
5944       ret = 0;
5945     }
5946 #endif
5947
5948   RESTORE_END_STRING (disp_end);
5949
5950   /* Check if this is a displacement only operand.  */
5951   bigdisp = i.types[this_operand];
5952   bigdisp.bitfield.disp8 = 0;
5953   bigdisp.bitfield.disp16 = 0;
5954   bigdisp.bitfield.disp32 = 0;
5955   bigdisp.bitfield.disp32s = 0;
5956   bigdisp.bitfield.disp64 = 0;
5957   if (UINTS_ALL_ZERO (bigdisp))
5958     i.types[this_operand] = operand_type_and (i.types[this_operand],
5959                                               types);
5960
5961   return ret;
5962 }
5963
5964 /* Make sure the memory operand we've been dealt is valid.
5965    Return 1 on success, 0 on a failure.  */
5966
5967 static int
5968 i386_index_check (const char *operand_string)
5969 {
5970   int ok;
5971 #if INFER_ADDR_PREFIX
5972   int fudged = 0;
5973
5974  tryprefix:
5975 #endif
5976   ok = 1;
5977   if (flag_code == CODE_64BIT)
5978     {
5979       if ((i.base_reg
5980            && ((i.prefix[ADDR_PREFIX] == 0
5981                 && !i.base_reg->reg_type.bitfield.reg64)
5982                || (i.prefix[ADDR_PREFIX]
5983                    && !i.base_reg->reg_type.bitfield.reg32))
5984            && (i.index_reg
5985                || i.base_reg->reg_num != RegRip))
5986           || (i.index_reg
5987               && (!i.index_reg->reg_type.bitfield.baseindex
5988                   || (i.prefix[ADDR_PREFIX] == 0
5989                       && i.index_reg->reg_num != RegRiz
5990                       && !i.index_reg->reg_type.bitfield.reg64
5991                       )
5992                   || (i.prefix[ADDR_PREFIX]
5993                       && i.index_reg->reg_num != RegEiz
5994                       && !i.index_reg->reg_type.bitfield.reg32))))
5995         ok = 0;
5996     }
5997   else
5998     {
5999       if ((flag_code == CODE_16BIT) ^ (i.prefix[ADDR_PREFIX] != 0))
6000         {
6001           /* 16bit checks.  */
6002           if ((i.base_reg
6003                && (!i.base_reg->reg_type.bitfield.reg16
6004                    || !i.base_reg->reg_type.bitfield.baseindex))
6005               || (i.index_reg
6006                   && (!i.index_reg->reg_type.bitfield.reg16
6007                       || !i.index_reg->reg_type.bitfield.baseindex
6008                       || !(i.base_reg
6009                            && i.base_reg->reg_num < 6
6010                            && i.index_reg->reg_num >= 6
6011                            && i.log2_scale_factor == 0))))
6012             ok = 0;
6013         }
6014       else
6015         {
6016           /* 32bit checks.  */
6017           if ((i.base_reg
6018                && !i.base_reg->reg_type.bitfield.reg32)
6019               || (i.index_reg
6020                   && ((!i.index_reg->reg_type.bitfield.reg32
6021                        && i.index_reg->reg_num != RegEiz)
6022                       || !i.index_reg->reg_type.bitfield.baseindex)))
6023             ok = 0;
6024         }
6025     }
6026   if (!ok)
6027     {
6028 #if INFER_ADDR_PREFIX
6029       if (i.prefix[ADDR_PREFIX] == 0)
6030         {
6031           i.prefix[ADDR_PREFIX] = ADDR_PREFIX_OPCODE;
6032           i.prefixes += 1;
6033           /* Change the size of any displacement too.  At most one of
6034              Disp16 or Disp32 is set.
6035              FIXME.  There doesn't seem to be any real need for separate
6036              Disp16 and Disp32 flags.  The same goes for Imm16 and Imm32.
6037              Removing them would probably clean up the code quite a lot.  */
6038           if (flag_code != CODE_64BIT
6039               && (i.types[this_operand].bitfield.disp16
6040                   || i.types[this_operand].bitfield.disp32))
6041             i.types[this_operand]
6042               = operand_type_xor (i.types[this_operand], disp16_32);
6043           fudged = 1;
6044           goto tryprefix;
6045         }
6046       if (fudged)
6047         as_bad (_("`%s' is not a valid base/index expression"),
6048                 operand_string);
6049       else
6050 #endif
6051         as_bad (_("`%s' is not a valid %s bit base/index expression"),
6052                 operand_string,
6053                 flag_code_names[flag_code]);
6054     }
6055   return ok;
6056 }
6057
6058 /* Parse OPERAND_STRING into the i386_insn structure I.  Returns non-zero
6059    on error.  */
6060
6061 static int
6062 i386_operand (char *operand_string)
6063 {
6064   const reg_entry *r;
6065   char *end_op;
6066   char *op_string = operand_string;
6067
6068   if (is_space_char (*op_string))
6069     ++op_string;
6070
6071   /* We check for an absolute prefix (differentiating,
6072      for example, 'jmp pc_relative_label' from 'jmp *absolute_label'.  */
6073   if (*op_string == ABSOLUTE_PREFIX)
6074     {
6075       ++op_string;
6076       if (is_space_char (*op_string))
6077         ++op_string;
6078       i.types[this_operand].bitfield.jumpabsolute = 1;
6079     }
6080
6081   /* Check if operand is a register.  */
6082   if ((r = parse_register (op_string, &end_op)) != NULL)
6083     {
6084       i386_operand_type temp;
6085
6086       /* Check for a segment override by searching for ':' after a
6087          segment register.  */
6088       op_string = end_op;
6089       if (is_space_char (*op_string))
6090         ++op_string;
6091       if (*op_string == ':'
6092           && (r->reg_type.bitfield.sreg2
6093               || r->reg_type.bitfield.sreg3))
6094         {
6095           switch (r->reg_num)
6096             {
6097             case 0:
6098               i.seg[i.mem_operands] = &es;
6099               break;
6100             case 1:
6101               i.seg[i.mem_operands] = &cs;
6102               break;
6103             case 2:
6104               i.seg[i.mem_operands] = &ss;
6105               break;
6106             case 3:
6107               i.seg[i.mem_operands] = &ds;
6108               break;
6109             case 4:
6110               i.seg[i.mem_operands] = &fs;
6111               break;
6112             case 5:
6113               i.seg[i.mem_operands] = &gs;
6114               break;
6115             }
6116
6117           /* Skip the ':' and whitespace.  */
6118           ++op_string;
6119           if (is_space_char (*op_string))
6120             ++op_string;
6121
6122           if (!is_digit_char (*op_string)
6123               && !is_identifier_char (*op_string)
6124               && *op_string != '('
6125               && *op_string != ABSOLUTE_PREFIX)
6126             {
6127               as_bad (_("bad memory operand `%s'"), op_string);
6128               return 0;
6129             }
6130           /* Handle case of %es:*foo.  */
6131           if (*op_string == ABSOLUTE_PREFIX)
6132             {
6133               ++op_string;
6134               if (is_space_char (*op_string))
6135                 ++op_string;
6136               i.types[this_operand].bitfield.jumpabsolute = 1;
6137             }
6138           goto do_memory_reference;
6139         }
6140       if (*op_string)
6141         {
6142           as_bad (_("junk `%s' after register"), op_string);
6143           return 0;
6144         }
6145       temp = r->reg_type;
6146       temp.bitfield.baseindex = 0;
6147       i.types[this_operand] = operand_type_or (i.types[this_operand],
6148                                                temp);
6149       i.op[this_operand].regs = r;
6150       i.reg_operands++;
6151     }
6152   else if (*op_string == REGISTER_PREFIX)
6153     {
6154       as_bad (_("bad register name `%s'"), op_string);
6155       return 0;
6156     }
6157   else if (*op_string == IMMEDIATE_PREFIX)
6158     {
6159       ++op_string;
6160       if (i.types[this_operand].bitfield.jumpabsolute)
6161         {
6162           as_bad (_("immediate operand illegal with absolute jump"));
6163           return 0;
6164         }
6165       if (!i386_immediate (op_string))
6166         return 0;
6167     }
6168   else if (is_digit_char (*op_string)
6169            || is_identifier_char (*op_string)
6170            || *op_string == '(')
6171     {
6172       /* This is a memory reference of some sort.  */
6173       char *base_string;
6174
6175       /* Start and end of displacement string expression (if found).  */
6176       char *displacement_string_start;
6177       char *displacement_string_end;
6178
6179     do_memory_reference:
6180       if ((i.mem_operands == 1
6181            && !current_templates->start->opcode_modifier.isstring)
6182           || i.mem_operands == 2)
6183         {
6184           as_bad (_("too many memory references for `%s'"),
6185                   current_templates->start->name);
6186           return 0;
6187         }
6188
6189       /* Check for base index form.  We detect the base index form by
6190          looking for an ')' at the end of the operand, searching
6191          for the '(' matching it, and finding a REGISTER_PREFIX or ','
6192          after the '('.  */
6193       base_string = op_string + strlen (op_string);
6194
6195       --base_string;
6196       if (is_space_char (*base_string))
6197         --base_string;
6198
6199       /* If we only have a displacement, set-up for it to be parsed later.  */
6200       displacement_string_start = op_string;
6201       displacement_string_end = base_string + 1;
6202
6203       if (*base_string == ')')
6204         {
6205           char *temp_string;
6206           unsigned int parens_balanced = 1;
6207           /* We've already checked that the number of left & right ()'s are
6208              equal, so this loop will not be infinite.  */
6209           do
6210             {
6211               base_string--;
6212               if (*base_string == ')')
6213                 parens_balanced++;
6214               if (*base_string == '(')
6215                 parens_balanced--;
6216             }
6217           while (parens_balanced);
6218
6219           temp_string = base_string;
6220
6221           /* Skip past '(' and whitespace.  */
6222           ++base_string;
6223           if (is_space_char (*base_string))
6224             ++base_string;
6225
6226           if (*base_string == ','
6227               || ((i.base_reg = parse_register (base_string, &end_op))
6228                   != NULL))
6229             {
6230               displacement_string_end = temp_string;
6231
6232               i.types[this_operand].bitfield.baseindex = 1;
6233
6234               if (i.base_reg)
6235                 {
6236                   base_string = end_op;
6237                   if (is_space_char (*base_string))
6238                     ++base_string;
6239                 }
6240
6241               /* There may be an index reg or scale factor here.  */
6242               if (*base_string == ',')
6243                 {
6244                   ++base_string;
6245                   if (is_space_char (*base_string))
6246                     ++base_string;
6247
6248                   if ((i.index_reg = parse_register (base_string, &end_op))
6249                       != NULL)
6250                     {
6251                       base_string = end_op;
6252                       if (is_space_char (*base_string))
6253                         ++base_string;
6254                       if (*base_string == ',')
6255                         {
6256                           ++base_string;
6257                           if (is_space_char (*base_string))
6258                             ++base_string;
6259                         }
6260                       else if (*base_string != ')')
6261                         {
6262                           as_bad (_("expecting `,' or `)' "
6263                                     "after index register in `%s'"),
6264                                   operand_string);
6265                           return 0;
6266                         }
6267                     }
6268                   else if (*base_string == REGISTER_PREFIX)
6269                     {
6270                       as_bad (_("bad register name `%s'"), base_string);
6271                       return 0;
6272                     }
6273
6274                   /* Check for scale factor.  */
6275                   if (*base_string != ')')
6276                     {
6277                       char *end_scale = i386_scale (base_string);
6278
6279                       if (!end_scale)
6280                         return 0;
6281
6282                       base_string = end_scale;
6283                       if (is_space_char (*base_string))
6284                         ++base_string;
6285                       if (*base_string != ')')
6286                         {
6287                           as_bad (_("expecting `)' "
6288                                     "after scale factor in `%s'"),
6289                                   operand_string);
6290                           return 0;
6291                         }
6292                     }
6293                   else if (!i.index_reg)
6294                     {
6295                       as_bad (_("expecting index register or scale factor "
6296                                 "after `,'; got '%c'"),
6297                               *base_string);
6298                       return 0;
6299                     }
6300                 }
6301               else if (*base_string != ')')
6302                 {
6303                   as_bad (_("expecting `,' or `)' "
6304                             "after base register in `%s'"),
6305                           operand_string);
6306                   return 0;
6307                 }
6308             }
6309           else if (*base_string == REGISTER_PREFIX)
6310             {
6311               as_bad (_("bad register name `%s'"), base_string);
6312               return 0;
6313             }
6314         }
6315
6316       /* If there's an expression beginning the operand, parse it,
6317          assuming displacement_string_start and
6318          displacement_string_end are meaningful.  */
6319       if (displacement_string_start != displacement_string_end)
6320         {
6321           if (!i386_displacement (displacement_string_start,
6322                                   displacement_string_end))
6323             return 0;
6324         }
6325
6326       /* Special case for (%dx) while doing input/output op.  */
6327       if (i.base_reg
6328           && UINTS_EQUAL (i.base_reg->reg_type, reg16_inoutportreg)
6329           && i.index_reg == 0
6330           && i.log2_scale_factor == 0
6331           && i.seg[i.mem_operands] == 0
6332           && !operand_type_check (i.types[this_operand], disp))
6333         {
6334           UINTS_CLEAR (i.types[this_operand]);
6335           i.types[this_operand].bitfield.inoutportreg = 1;
6336           return 1;
6337         }
6338
6339       if (i386_index_check (operand_string) == 0)
6340         return 0;
6341       i.mem_operands++;
6342     }
6343   else
6344     {
6345       /* It's not a memory operand; argh!  */
6346       as_bad (_("invalid char %s beginning operand %d `%s'"),
6347               output_invalid (*op_string),
6348               this_operand + 1,
6349               op_string);
6350       return 0;
6351     }
6352   return 1;                     /* Normal return.  */
6353 }
6354 \f
6355 /* md_estimate_size_before_relax()
6356
6357    Called just before relax() for rs_machine_dependent frags.  The x86
6358    assembler uses these frags to handle variable size jump
6359    instructions.
6360
6361    Any symbol that is now undefined will not become defined.
6362    Return the correct fr_subtype in the frag.
6363    Return the initial "guess for variable size of frag" to caller.
6364    The guess is actually the growth beyond the fixed part.  Whatever
6365    we do to grow the fixed or variable part contributes to our
6366    returned value.  */
6367
6368 int
6369 md_estimate_size_before_relax (fragP, segment)
6370      fragS *fragP;
6371      segT segment;
6372 {
6373   /* We've already got fragP->fr_subtype right;  all we have to do is
6374      check for un-relaxable symbols.  On an ELF system, we can't relax
6375      an externally visible symbol, because it may be overridden by a
6376      shared library.  */
6377   if (S_GET_SEGMENT (fragP->fr_symbol) != segment
6378 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
6379       || (IS_ELF
6380           && (S_IS_EXTERNAL (fragP->fr_symbol)
6381               || S_IS_WEAK (fragP->fr_symbol)))
6382 #endif
6383       )
6384     {
6385       /* Symbol is undefined in this segment, or we need to keep a
6386          reloc so that weak symbols can be overridden.  */
6387       int size = (fragP->fr_subtype & CODE16) ? 2 : 4;
6388       enum bfd_reloc_code_real reloc_type;
6389       unsigned char *opcode;
6390       int old_fr_fix;
6391
6392       if (fragP->fr_var != NO_RELOC)
6393         reloc_type = fragP->fr_var;
6394       else if (size == 2)
6395         reloc_type = BFD_RELOC_16_PCREL;
6396       else
6397         reloc_type = BFD_RELOC_32_PCREL;
6398
6399       old_fr_fix = fragP->fr_fix;
6400       opcode = (unsigned char *) fragP->fr_opcode;
6401
6402       switch (TYPE_FROM_RELAX_STATE (fragP->fr_subtype))
6403         {
6404         case UNCOND_JUMP:
6405           /* Make jmp (0xeb) a (d)word displacement jump.  */
6406           opcode[0] = 0xe9;
6407           fragP->fr_fix += size;
6408           fix_new (fragP, old_fr_fix, size,
6409                    fragP->fr_symbol,
6410                    fragP->fr_offset, 1,
6411                    reloc_type);
6412           break;
6413
6414         case COND_JUMP86:
6415           if (size == 2
6416               && (!no_cond_jump_promotion || fragP->fr_var != NO_RELOC))
6417             {
6418               /* Negate the condition, and branch past an
6419                  unconditional jump.  */
6420               opcode[0] ^= 1;
6421               opcode[1] = 3;
6422               /* Insert an unconditional jump.  */
6423               opcode[2] = 0xe9;
6424               /* We added two extra opcode bytes, and have a two byte
6425                  offset.  */
6426               fragP->fr_fix += 2 + 2;
6427               fix_new (fragP, old_fr_fix + 2, 2,
6428                        fragP->fr_symbol,
6429                        fragP->fr_offset, 1,
6430                        reloc_type);
6431               break;
6432             }
6433           /* Fall through.  */
6434
6435         case COND_JUMP:
6436           if (no_cond_jump_promotion && fragP->fr_var == NO_RELOC)
6437             {
6438               fixS *fixP;
6439
6440               fragP->fr_fix += 1;
6441               fixP = fix_new (fragP, old_fr_fix, 1,
6442                               fragP->fr_symbol,
6443                               fragP->fr_offset, 1,
6444                               BFD_RELOC_8_PCREL);
6445               fixP->fx_signed = 1;
6446               break;
6447             }
6448
6449           /* This changes the byte-displacement jump 0x7N
6450              to the (d)word-displacement jump 0x0f,0x8N.  */
6451           opcode[1] = opcode[0] + 0x10;
6452           opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
6453           /* We've added an opcode byte.  */
6454           fragP->fr_fix += 1 + size;
6455           fix_new (fragP, old_fr_fix + 1, size,
6456                    fragP->fr_symbol,
6457                    fragP->fr_offset, 1,
6458                    reloc_type);
6459           break;
6460
6461         default:
6462           BAD_CASE (fragP->fr_subtype);
6463           break;
6464         }
6465       frag_wane (fragP);
6466       return fragP->fr_fix - old_fr_fix;
6467     }
6468
6469   /* Guess size depending on current relax state.  Initially the relax
6470      state will correspond to a short jump and we return 1, because
6471      the variable part of the frag (the branch offset) is one byte
6472      long.  However, we can relax a section more than once and in that
6473      case we must either set fr_subtype back to the unrelaxed state,
6474      or return the value for the appropriate branch.  */
6475   return md_relax_table[fragP->fr_subtype].rlx_length;
6476 }
6477
6478 /* Called after relax() is finished.
6479
6480    In:  Address of frag.
6481         fr_type == rs_machine_dependent.
6482         fr_subtype is what the address relaxed to.
6483
6484    Out: Any fixSs and constants are set up.
6485         Caller will turn frag into a ".space 0".  */
6486
6487 void
6488 md_convert_frag (abfd, sec, fragP)
6489      bfd *abfd ATTRIBUTE_UNUSED;
6490      segT sec ATTRIBUTE_UNUSED;
6491      fragS *fragP;
6492 {
6493   unsigned char *opcode;
6494   unsigned char *where_to_put_displacement = NULL;
6495   offsetT target_address;
6496   offsetT opcode_address;
6497   unsigned int extension = 0;
6498   offsetT displacement_from_opcode_start;
6499
6500   opcode = (unsigned char *) fragP->fr_opcode;
6501
6502   /* Address we want to reach in file space.  */
6503   target_address = S_GET_VALUE (fragP->fr_symbol) + fragP->fr_offset;
6504
6505   /* Address opcode resides at in file space.  */
6506   opcode_address = fragP->fr_address + fragP->fr_fix;
6507
6508   /* Displacement from opcode start to fill into instruction.  */
6509   displacement_from_opcode_start = target_address - opcode_address;
6510
6511   if ((fragP->fr_subtype & BIG) == 0)
6512     {
6513       /* Don't have to change opcode.  */
6514       extension = 1;            /* 1 opcode + 1 displacement  */
6515       where_to_put_displacement = &opcode[1];
6516     }
6517   else
6518     {
6519       if (no_cond_jump_promotion
6520           && TYPE_FROM_RELAX_STATE (fragP->fr_subtype) != UNCOND_JUMP)
6521         as_warn_where (fragP->fr_file, fragP->fr_line,
6522                        _("long jump required"));
6523
6524       switch (fragP->fr_subtype)
6525         {
6526         case ENCODE_RELAX_STATE (UNCOND_JUMP, BIG):
6527           extension = 4;                /* 1 opcode + 4 displacement  */
6528           opcode[0] = 0xe9;
6529           where_to_put_displacement = &opcode[1];
6530           break;
6531
6532         case ENCODE_RELAX_STATE (UNCOND_JUMP, BIG16):
6533           extension = 2;                /* 1 opcode + 2 displacement  */
6534           opcode[0] = 0xe9;
6535           where_to_put_displacement = &opcode[1];
6536           break;
6537
6538         case ENCODE_RELAX_STATE (COND_JUMP, BIG):
6539         case ENCODE_RELAX_STATE (COND_JUMP86, BIG):
6540           extension = 5;                /* 2 opcode + 4 displacement  */
6541           opcode[1] = opcode[0] + 0x10;
6542           opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
6543           where_to_put_displacement = &opcode[2];
6544           break;
6545
6546         case ENCODE_RELAX_STATE (COND_JUMP, BIG16):
6547           extension = 3;                /* 2 opcode + 2 displacement  */
6548           opcode[1] = opcode[0] + 0x10;
6549           opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
6550           where_to_put_displacement = &opcode[2];
6551           break;
6552
6553         case ENCODE_RELAX_STATE (COND_JUMP86, BIG16):
6554           extension = 4;
6555           opcode[0] ^= 1;
6556           opcode[1] = 3;
6557           opcode[2] = 0xe9;
6558           where_to_put_displacement = &opcode[3];
6559           break;
6560
6561         default:
6562           BAD_CASE (fragP->fr_subtype);
6563           break;
6564         }
6565     }
6566
6567   /* If size if less then four we are sure that the operand fits,
6568      but if it's 4, then it could be that the displacement is larger
6569      then -/+ 2GB.  */
6570   if (DISP_SIZE_FROM_RELAX_STATE (fragP->fr_subtype) == 4
6571       && object_64bit
6572       && ((addressT) (displacement_from_opcode_start - extension
6573                       + ((addressT) 1 << 31))
6574           > (((addressT) 2 << 31) - 1)))
6575     {
6576       as_bad_where (fragP->fr_file, fragP->fr_line,
6577                     _("jump target out of range"));
6578       /* Make us emit 0.  */
6579       displacement_from_opcode_start = extension;
6580     }
6581   /* Now put displacement after opcode.  */
6582   md_number_to_chars ((char *) where_to_put_displacement,
6583                       (valueT) (displacement_from_opcode_start - extension),
6584                       DISP_SIZE_FROM_RELAX_STATE (fragP->fr_subtype));
6585   fragP->fr_fix += extension;
6586 }
6587 \f
6588 /* Size of byte displacement jmp.  */
6589 int md_short_jump_size = 2;
6590
6591 /* Size of dword displacement jmp.  */
6592 int md_long_jump_size = 5;
6593
6594 void
6595 md_create_short_jump (ptr, from_addr, to_addr, frag, to_symbol)
6596      char *ptr;
6597      addressT from_addr, to_addr;
6598      fragS *frag ATTRIBUTE_UNUSED;
6599      symbolS *to_symbol ATTRIBUTE_UNUSED;
6600 {
6601   offsetT offset;
6602
6603   offset = to_addr - (from_addr + 2);
6604   /* Opcode for byte-disp jump.  */
6605   md_number_to_chars (ptr, (valueT) 0xeb, 1);
6606   md_number_to_chars (ptr + 1, (valueT) offset, 1);
6607 }
6608
6609 void
6610 md_create_long_jump (ptr, from_addr, to_addr, frag, to_symbol)
6611      char *ptr;
6612      addressT from_addr, to_addr;
6613      fragS *frag ATTRIBUTE_UNUSED;
6614      symbolS *to_symbol ATTRIBUTE_UNUSED;
6615 {
6616   offsetT offset;
6617
6618   offset = to_addr - (from_addr + 5);
6619   md_number_to_chars (ptr, (valueT) 0xe9, 1);
6620   md_number_to_chars (ptr + 1, (valueT) offset, 4);
6621 }
6622 \f
6623 /* Apply a fixup (fixS) to segment data, once it has been determined
6624    by our caller that we have all the info we need to fix it up.
6625
6626    On the 386, immediates, displacements, and data pointers are all in
6627    the same (little-endian) format, so we don't need to care about which
6628    we are handling.  */
6629
6630 void
6631 md_apply_fix (fixP, valP, seg)
6632      /* The fix we're to put in.  */
6633      fixS *fixP;
6634      /* Pointer to the value of the bits.  */
6635      valueT *valP;
6636      /* Segment fix is from.  */
6637      segT seg ATTRIBUTE_UNUSED;
6638 {
6639   char *p = fixP->fx_where + fixP->fx_frag->fr_literal;
6640   valueT value = *valP;
6641
6642 #if !defined (TE_Mach)
6643   if (fixP->fx_pcrel)
6644     {
6645       switch (fixP->fx_r_type)
6646         {
6647         default:
6648           break;
6649
6650         case BFD_RELOC_64:
6651           fixP->fx_r_type = BFD_RELOC_64_PCREL;
6652           break;
6653         case BFD_RELOC_32:
6654         case BFD_RELOC_X86_64_32S:
6655           fixP->fx_r_type = BFD_RELOC_32_PCREL;
6656           break;
6657         case BFD_RELOC_16:
6658           fixP->fx_r_type = BFD_RELOC_16_PCREL;
6659           break;
6660         case BFD_RELOC_8:
6661           fixP->fx_r_type = BFD_RELOC_8_PCREL;
6662           break;
6663         }
6664     }
6665
6666   if (fixP->fx_addsy != NULL
6667       && (fixP->fx_r_type == BFD_RELOC_32_PCREL
6668           || fixP->fx_r_type == BFD_RELOC_64_PCREL
6669           || fixP->fx_r_type == BFD_RELOC_16_PCREL
6670           || fixP->fx_r_type == BFD_RELOC_8_PCREL)
6671       && !use_rela_relocations)
6672     {
6673       /* This is a hack.  There should be a better way to handle this.
6674          This covers for the fact that bfd_install_relocation will
6675          subtract the current location (for partial_inplace, PC relative
6676          relocations); see more below.  */
6677 #ifndef OBJ_AOUT
6678       if (IS_ELF
6679 #ifdef TE_PE
6680           || OUTPUT_FLAVOR == bfd_target_coff_flavour
6681 #endif
6682           )
6683         value += fixP->fx_where + fixP->fx_frag->fr_address;
6684 #endif
6685 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
6686       if (IS_ELF)
6687         {
6688           segT sym_seg = S_GET_SEGMENT (fixP->fx_addsy);
6689
6690           if ((sym_seg == seg
6691                || (symbol_section_p (fixP->fx_addsy)
6692                    && sym_seg != absolute_section))
6693               && !generic_force_reloc (fixP))
6694             {
6695               /* Yes, we add the values in twice.  This is because
6696                  bfd_install_relocation subtracts them out again.  I think
6697                  bfd_install_relocation is broken, but I don't dare change
6698                  it.  FIXME.  */
6699               value += fixP->fx_where + fixP->fx_frag->fr_address;
6700             }
6701         }
6702 #endif
6703 #if defined (OBJ_COFF) && defined (TE_PE)
6704       /* For some reason, the PE format does not store a
6705          section address offset for a PC relative symbol.  */
6706       if (S_GET_SEGMENT (fixP->fx_addsy) != seg
6707           || S_IS_WEAK (fixP->fx_addsy))
6708         value += md_pcrel_from (fixP);
6709 #endif
6710     }
6711
6712   /* Fix a few things - the dynamic linker expects certain values here,
6713      and we must not disappoint it.  */
6714 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
6715   if (IS_ELF && fixP->fx_addsy)
6716     switch (fixP->fx_r_type)
6717       {
6718       case BFD_RELOC_386_PLT32:
6719       case BFD_RELOC_X86_64_PLT32:
6720         /* Make the jump instruction point to the address of the operand.  At
6721            runtime we merely add the offset to the actual PLT entry.  */
6722         value = -4;
6723         break;
6724
6725       case BFD_RELOC_386_TLS_GD:
6726       case BFD_RELOC_386_TLS_LDM:
6727       case BFD_RELOC_386_TLS_IE_32:
6728       case BFD_RELOC_386_TLS_IE:
6729       case BFD_RELOC_386_TLS_GOTIE:
6730       case BFD_RELOC_386_TLS_GOTDESC:
6731       case BFD_RELOC_X86_64_TLSGD:
6732       case BFD_RELOC_X86_64_TLSLD:
6733       case BFD_RELOC_X86_64_GOTTPOFF:
6734       case BFD_RELOC_X86_64_GOTPC32_TLSDESC:
6735         value = 0; /* Fully resolved at runtime.  No addend.  */
6736         /* Fallthrough */
6737       case BFD_RELOC_386_TLS_LE:
6738       case BFD_RELOC_386_TLS_LDO_32:
6739       case BFD_RELOC_386_TLS_LE_32:
6740       case BFD_RELOC_X86_64_DTPOFF32:
6741       case BFD_RELOC_X86_64_DTPOFF64:
6742       case BFD_RELOC_X86_64_TPOFF32:
6743       case BFD_RELOC_X86_64_TPOFF64:
6744         S_SET_THREAD_LOCAL (fixP->fx_addsy);
6745         break;
6746
6747       case BFD_RELOC_386_TLS_DESC_CALL:
6748       case BFD_RELOC_X86_64_TLSDESC_CALL:
6749         value = 0; /* Fully resolved at runtime.  No addend.  */
6750         S_SET_THREAD_LOCAL (fixP->fx_addsy);
6751         fixP->fx_done = 0;
6752         return;
6753
6754       case BFD_RELOC_386_GOT32:
6755       case BFD_RELOC_X86_64_GOT32:
6756         value = 0; /* Fully resolved at runtime.  No addend.  */
6757         break;
6758
6759       case BFD_RELOC_VTABLE_INHERIT:
6760       case BFD_RELOC_VTABLE_ENTRY:
6761         fixP->fx_done = 0;
6762         return;
6763
6764       default:
6765         break;
6766       }
6767 #endif /* defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)  */
6768   *valP = value;
6769 #endif /* !defined (TE_Mach)  */
6770
6771   /* Are we finished with this relocation now?  */
6772   if (fixP->fx_addsy == NULL)
6773     fixP->fx_done = 1;
6774   else if (use_rela_relocations)
6775     {
6776       fixP->fx_no_overflow = 1;
6777       /* Remember value for tc_gen_reloc.  */
6778       fixP->fx_addnumber = value;
6779       value = 0;
6780     }
6781
6782   md_number_to_chars (p, value, fixP->fx_size);
6783 }
6784 \f
6785 #define MAX_LITTLENUMS 6
6786
6787 /* Turn the string pointed to by litP into a floating point constant
6788    of type TYPE, and emit the appropriate bytes.  The number of
6789    LITTLENUMS emitted is stored in *SIZEP.  An error message is
6790    returned, or NULL on OK.  */
6791
6792 char *
6793 md_atof (type, litP, sizeP)
6794      int type;
6795      char *litP;
6796      int *sizeP;
6797 {
6798   int prec;
6799   LITTLENUM_TYPE words[MAX_LITTLENUMS];
6800   LITTLENUM_TYPE *wordP;
6801   char *t;
6802
6803   switch (type)
6804     {
6805     case 'f':
6806     case 'F':
6807       prec = 2;
6808       break;
6809
6810     case 'd':
6811     case 'D':
6812       prec = 4;
6813       break;
6814
6815     case 'x':
6816     case 'X':
6817       prec = 5;
6818       break;
6819
6820     default:
6821       *sizeP = 0;
6822       return _("Bad call to md_atof ()");
6823     }
6824   t = atof_ieee (input_line_pointer, type, words);
6825   if (t)
6826     input_line_pointer = t;
6827
6828   *sizeP = prec * sizeof (LITTLENUM_TYPE);
6829   /* This loops outputs the LITTLENUMs in REVERSE order; in accord with
6830      the bigendian 386.  */
6831   for (wordP = words + prec - 1; prec--;)
6832     {
6833       md_number_to_chars (litP, (valueT) (*wordP--), sizeof (LITTLENUM_TYPE));
6834       litP += sizeof (LITTLENUM_TYPE);
6835     }
6836   return 0;
6837 }
6838 \f
6839 static char output_invalid_buf[sizeof (unsigned char) * 2 + 6];
6840
6841 static char *
6842 output_invalid (int c)
6843 {
6844   if (ISPRINT (c))
6845     snprintf (output_invalid_buf, sizeof (output_invalid_buf),
6846               "'%c'", c);
6847   else
6848     snprintf (output_invalid_buf, sizeof (output_invalid_buf),
6849               "(0x%x)", (unsigned char) c);
6850   return output_invalid_buf;
6851 }
6852
6853 /* REG_STRING starts *before* REGISTER_PREFIX.  */
6854
6855 static const reg_entry *
6856 parse_real_register (char *reg_string, char **end_op)
6857 {
6858   char *s = reg_string;
6859   char *p;
6860   char reg_name_given[MAX_REG_NAME_SIZE + 1];
6861   const reg_entry *r;
6862
6863   /* Skip possible REGISTER_PREFIX and possible whitespace.  */
6864   if (*s == REGISTER_PREFIX)
6865     ++s;
6866
6867   if (is_space_char (*s))
6868     ++s;
6869
6870   p = reg_name_given;
6871   while ((*p++ = register_chars[(unsigned char) *s]) != '\0')
6872     {
6873       if (p >= reg_name_given + MAX_REG_NAME_SIZE)
6874         return (const reg_entry *) NULL;
6875       s++;
6876     }
6877
6878   /* For naked regs, make sure that we are not dealing with an identifier.
6879      This prevents confusing an identifier like `eax_var' with register
6880      `eax'.  */
6881   if (allow_naked_reg && identifier_chars[(unsigned char) *s])
6882     return (const reg_entry *) NULL;
6883
6884   *end_op = s;
6885
6886   r = (const reg_entry *) hash_find (reg_hash, reg_name_given);
6887
6888   /* Handle floating point regs, allowing spaces in the (i) part.  */
6889   if (r == i386_regtab /* %st is first entry of table  */)
6890     {
6891       if (is_space_char (*s))
6892         ++s;
6893       if (*s == '(')
6894         {
6895           ++s;
6896           if (is_space_char (*s))
6897             ++s;
6898           if (*s >= '0' && *s <= '7')
6899             {
6900               int fpr = *s - '0';
6901               ++s;
6902               if (is_space_char (*s))
6903                 ++s;
6904               if (*s == ')')
6905                 {
6906                   *end_op = s + 1;
6907                   r = hash_find (reg_hash, "st(0)");
6908                   know (r);
6909                   return r + fpr;
6910                 }
6911             }
6912           /* We have "%st(" then garbage.  */
6913           return (const reg_entry *) NULL;
6914         }
6915     }
6916
6917   /* Don't allow fake index register unless allow_index_reg isn't 0. */
6918   if (r != NULL
6919       && !allow_index_reg
6920       && (r->reg_num == RegEiz || r->reg_num == RegRiz))
6921     return (const reg_entry *) NULL;
6922
6923   if (r != NULL
6924       && ((r->reg_flags & (RegRex64 | RegRex))
6925           || r->reg_type.bitfield.reg64)
6926       && (!cpu_arch_flags.bitfield.cpulm
6927           || !UINTS_EQUAL (r->reg_type, control))
6928       && flag_code != CODE_64BIT)
6929     return (const reg_entry *) NULL;
6930
6931   return r;
6932 }
6933
6934 /* REG_STRING starts *before* REGISTER_PREFIX.  */
6935
6936 static const reg_entry *
6937 parse_register (char *reg_string, char **end_op)
6938 {
6939   const reg_entry *r;
6940
6941   if (*reg_string == REGISTER_PREFIX || allow_naked_reg)
6942     r = parse_real_register (reg_string, end_op);
6943   else
6944     r = NULL;
6945   if (!r)
6946     {
6947       char *save = input_line_pointer;
6948       char c;
6949       symbolS *symbolP;
6950
6951       input_line_pointer = reg_string;
6952       c = get_symbol_end ();
6953       symbolP = symbol_find (reg_string);
6954       if (symbolP && S_GET_SEGMENT (symbolP) == reg_section)
6955         {
6956           const expressionS *e = symbol_get_value_expression (symbolP);
6957
6958           know (e->X_op == O_register);
6959           know (e->X_add_number >= 0
6960                 && (valueT) e->X_add_number < i386_regtab_size);
6961           r = i386_regtab + e->X_add_number;
6962           *end_op = input_line_pointer;
6963         }
6964       *input_line_pointer = c;
6965       input_line_pointer = save;
6966     }
6967   return r;
6968 }
6969
6970 int
6971 i386_parse_name (char *name, expressionS *e, char *nextcharP)
6972 {
6973   const reg_entry *r;
6974   char *end = input_line_pointer;
6975
6976   *end = *nextcharP;
6977   r = parse_register (name, &input_line_pointer);
6978   if (r && end <= input_line_pointer)
6979     {
6980       *nextcharP = *input_line_pointer;
6981       *input_line_pointer = 0;
6982       e->X_op = O_register;
6983       e->X_add_number = r - i386_regtab;
6984       return 1;
6985     }
6986   input_line_pointer = end;
6987   *end = 0;
6988   return 0;
6989 }
6990
6991 void
6992 md_operand (expressionS *e)
6993 {
6994   if (*input_line_pointer == REGISTER_PREFIX)
6995     {
6996       char *end;
6997       const reg_entry *r = parse_real_register (input_line_pointer, &end);
6998
6999       if (r)
7000         {
7001           e->X_op = O_register;
7002           e->X_add_number = r - i386_regtab;
7003           input_line_pointer = end;
7004         }
7005     }
7006 }
7007
7008 \f
7009 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
7010 const char *md_shortopts = "kVQ:sqn";
7011 #else
7012 const char *md_shortopts = "qn";
7013 #endif
7014
7015 #define OPTION_32 (OPTION_MD_BASE + 0)
7016 #define OPTION_64 (OPTION_MD_BASE + 1)
7017 #define OPTION_DIVIDE (OPTION_MD_BASE + 2)
7018 #define OPTION_MARCH (OPTION_MD_BASE + 3)
7019 #define OPTION_MTUNE (OPTION_MD_BASE + 4)
7020
7021 struct option md_longopts[] =
7022 {
7023   {"32", no_argument, NULL, OPTION_32},
7024 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) || defined(TE_PEP)
7025   {"64", no_argument, NULL, OPTION_64},
7026 #endif
7027   {"divide", no_argument, NULL, OPTION_DIVIDE},
7028   {"march", required_argument, NULL, OPTION_MARCH},
7029   {"mtune", required_argument, NULL, OPTION_MTUNE},
7030   {NULL, no_argument, NULL, 0}
7031 };
7032 size_t md_longopts_size = sizeof (md_longopts);
7033
7034 int
7035 md_parse_option (int c, char *arg)
7036 {
7037   unsigned int i;
7038
7039   switch (c)
7040     {
7041     case 'n':
7042       optimize_align_code = 0;
7043       break;
7044
7045     case 'q':
7046       quiet_warnings = 1;
7047       break;
7048
7049 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
7050       /* -Qy, -Qn: SVR4 arguments controlling whether a .comment section
7051          should be emitted or not.  FIXME: Not implemented.  */
7052     case 'Q':
7053       break;
7054
7055       /* -V: SVR4 argument to print version ID.  */
7056     case 'V':
7057       print_version_id ();
7058       break;
7059
7060       /* -k: Ignore for FreeBSD compatibility.  */
7061     case 'k':
7062       break;
7063
7064     case 's':
7065       /* -s: On i386 Solaris, this tells the native assembler to use
7066          .stab instead of .stab.excl.  We always use .stab anyhow.  */
7067       break;
7068 #endif
7069 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) || defined(TE_PEP)
7070     case OPTION_64:
7071       {
7072         const char **list, **l;
7073
7074         list = bfd_target_list ();
7075         for (l = list; *l != NULL; l++)
7076           if (CONST_STRNEQ (*l, "elf64-x86-64")
7077               || strcmp (*l, "coff-x86-64") == 0
7078               || strcmp (*l, "pe-x86-64") == 0
7079               || strcmp (*l, "pei-x86-64") == 0)
7080             {
7081               default_arch = "x86_64";
7082               break;
7083             }
7084         if (*l == NULL)
7085           as_fatal (_("No compiled in support for x86_64"));
7086         free (list);
7087       }
7088       break;
7089 #endif
7090
7091     case OPTION_32:
7092       default_arch = "i386";
7093       break;
7094
7095     case OPTION_DIVIDE:
7096 #ifdef SVR4_COMMENT_CHARS
7097       {
7098         char *n, *t;
7099         const char *s;
7100
7101         n = (char *) xmalloc (strlen (i386_comment_chars) + 1);
7102         t = n;
7103         for (s = i386_comment_chars; *s != '\0'; s++)
7104           if (*s != '/')
7105             *t++ = *s;
7106         *t = '\0';
7107         i386_comment_chars = n;
7108       }
7109 #endif
7110       break;
7111
7112     case OPTION_MARCH:
7113       if (*arg == '.')
7114         as_fatal (_("Invalid -march= option: `%s'"), arg);
7115       for (i = 0; i < ARRAY_SIZE (cpu_arch); i++)
7116         {
7117           if (strcmp (arg, cpu_arch [i].name) == 0)
7118             {
7119               cpu_arch_isa = cpu_arch[i].type;
7120               cpu_arch_isa_flags = cpu_arch[i].flags;
7121               if (!cpu_arch_tune_set)
7122                 {
7123                   cpu_arch_tune = cpu_arch_isa;
7124                   cpu_arch_tune_flags = cpu_arch_isa_flags;
7125                 }
7126               break;
7127             }
7128         }
7129       if (i >= ARRAY_SIZE (cpu_arch))
7130         as_fatal (_("Invalid -march= option: `%s'"), arg);
7131       break;
7132
7133     case OPTION_MTUNE:
7134       if (*arg == '.')
7135         as_fatal (_("Invalid -mtune= option: `%s'"), arg);
7136       for (i = 0; i < ARRAY_SIZE (cpu_arch); i++)
7137         {
7138           if (strcmp (arg, cpu_arch [i].name) == 0)
7139             {
7140               cpu_arch_tune_set = 1;
7141               cpu_arch_tune = cpu_arch [i].type;
7142               cpu_arch_tune_flags = cpu_arch[i].flags;
7143               break;
7144             }
7145         }
7146       if (i >= ARRAY_SIZE (cpu_arch))
7147         as_fatal (_("Invalid -mtune= option: `%s'"), arg);
7148       break;
7149
7150     default:
7151       return 0;
7152     }
7153   return 1;
7154 }
7155
7156 void
7157 md_show_usage (stream)
7158      FILE *stream;
7159 {
7160 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
7161   fprintf (stream, _("\
7162   -Q                      ignored\n\
7163   -V                      print assembler version number\n\
7164   -k                      ignored\n"));
7165 #endif
7166   fprintf (stream, _("\
7167   -n                      Do not optimize code alignment\n\
7168   -q                      quieten some warnings\n"));
7169 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
7170   fprintf (stream, _("\
7171   -s                      ignored\n"));
7172 #endif
7173 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) || defined(TE_PEP)
7174   fprintf (stream, _("\
7175   --32/--64               generate 32bit/64bit code\n"));
7176 #endif
7177 #ifdef SVR4_COMMENT_CHARS
7178   fprintf (stream, _("\
7179   --divide                do not treat `/' as a comment character\n"));
7180 #else
7181   fprintf (stream, _("\
7182   --divide                ignored\n"));
7183 #endif
7184   fprintf (stream, _("\
7185   -march=CPU/-mtune=CPU   generate code/optimize for CPU, where CPU is one of:\n\
7186                            i386, i486, pentium, pentiumpro, pentium4, nocona,\n\
7187                            core, core2, k6, athlon, k8, generic32, generic64\n"));
7188
7189 }
7190
7191 #if ((defined (OBJ_MAYBE_COFF) && defined (OBJ_MAYBE_AOUT)) \
7192      || defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) || defined (TE_PEP))
7193
7194 /* Pick the target format to use.  */
7195
7196 const char *
7197 i386_target_format (void)
7198 {
7199   if (!strcmp (default_arch, "x86_64"))
7200     {
7201       set_code_flag (CODE_64BIT);
7202       if (UINTS_ALL_ZERO (cpu_arch_isa_flags))
7203         {
7204           cpu_arch_isa_flags.bitfield.cpui186 = 1;
7205           cpu_arch_isa_flags.bitfield.cpui286 = 1;
7206           cpu_arch_isa_flags.bitfield.cpui386 = 1;
7207           cpu_arch_isa_flags.bitfield.cpui486 = 1;
7208           cpu_arch_isa_flags.bitfield.cpui586 = 1;
7209           cpu_arch_isa_flags.bitfield.cpui686 = 1;
7210           cpu_arch_isa_flags.bitfield.cpup4 = 1;
7211           cpu_arch_isa_flags.bitfield.cpummx= 1;
7212           cpu_arch_isa_flags.bitfield.cpummx2 = 1;
7213           cpu_arch_isa_flags.bitfield.cpusse = 1;
7214           cpu_arch_isa_flags.bitfield.cpusse2 = 1;
7215         }
7216       if (UINTS_ALL_ZERO (cpu_arch_tune_flags))
7217         {
7218           cpu_arch_tune_flags.bitfield.cpui186 = 1;
7219           cpu_arch_tune_flags.bitfield.cpui286 = 1;
7220           cpu_arch_tune_flags.bitfield.cpui386 = 1;
7221           cpu_arch_tune_flags.bitfield.cpui486 = 1;
7222           cpu_arch_tune_flags.bitfield.cpui586 = 1;
7223           cpu_arch_tune_flags.bitfield.cpui686 = 1;
7224           cpu_arch_tune_flags.bitfield.cpup4 = 1;
7225           cpu_arch_tune_flags.bitfield.cpummx= 1;
7226           cpu_arch_tune_flags.bitfield.cpummx2 = 1;
7227           cpu_arch_tune_flags.bitfield.cpusse = 1;
7228           cpu_arch_tune_flags.bitfield.cpusse2 = 1;
7229         }
7230     }
7231   else if (!strcmp (default_arch, "i386"))
7232     {
7233       set_code_flag (CODE_32BIT);
7234       if (UINTS_ALL_ZERO (cpu_arch_isa_flags))
7235         {
7236           cpu_arch_isa_flags.bitfield.cpui186 = 1;
7237           cpu_arch_isa_flags.bitfield.cpui286 = 1;
7238           cpu_arch_isa_flags.bitfield.cpui386 = 1;
7239         }
7240       if (UINTS_ALL_ZERO (cpu_arch_tune_flags))
7241         {
7242           cpu_arch_tune_flags.bitfield.cpui186 = 1;
7243           cpu_arch_tune_flags.bitfield.cpui286 = 1;
7244           cpu_arch_tune_flags.bitfield.cpui386 = 1;
7245         }
7246     }
7247   else
7248     as_fatal (_("Unknown architecture"));
7249   switch (OUTPUT_FLAVOR)
7250     {
7251 #ifdef TE_PEP
7252     case bfd_target_coff_flavour:
7253       return flag_code == CODE_64BIT ? COFF_TARGET_FORMAT : "coff-i386";
7254       break;
7255 #endif
7256 #ifdef OBJ_MAYBE_AOUT
7257     case bfd_target_aout_flavour:
7258       return AOUT_TARGET_FORMAT;
7259 #endif
7260 #ifdef OBJ_MAYBE_COFF
7261     case bfd_target_coff_flavour:
7262       return "coff-i386";
7263 #endif
7264 #if defined (OBJ_MAYBE_ELF) || defined (OBJ_ELF)
7265     case bfd_target_elf_flavour:
7266       {
7267         if (flag_code == CODE_64BIT)
7268           {
7269             object_64bit = 1;
7270             use_rela_relocations = 1;
7271           }
7272         return flag_code == CODE_64BIT ? ELF_TARGET_FORMAT64 : ELF_TARGET_FORMAT;
7273       }
7274 #endif
7275     default:
7276       abort ();
7277       return NULL;
7278     }
7279 }
7280
7281 #endif /* OBJ_MAYBE_ more than one  */
7282
7283 #if (defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF))
7284 void
7285 i386_elf_emit_arch_note (void)
7286 {
7287   if (IS_ELF && cpu_arch_name != NULL)
7288     {
7289       char *p;
7290       asection *seg = now_seg;
7291       subsegT subseg = now_subseg;
7292       Elf_Internal_Note i_note;
7293       Elf_External_Note e_note;
7294       asection *note_secp;
7295       int len;
7296
7297       /* Create the .note section.  */
7298       note_secp = subseg_new (".note", 0);
7299       bfd_set_section_flags (stdoutput,
7300                              note_secp,
7301                              SEC_HAS_CONTENTS | SEC_READONLY);
7302
7303       /* Process the arch string.  */
7304       len = strlen (cpu_arch_name);
7305
7306       i_note.namesz = len + 1;
7307       i_note.descsz = 0;
7308       i_note.type = NT_ARCH;
7309       p = frag_more (sizeof (e_note.namesz));
7310       md_number_to_chars (p, (valueT) i_note.namesz, sizeof (e_note.namesz));
7311       p = frag_more (sizeof (e_note.descsz));
7312       md_number_to_chars (p, (valueT) i_note.descsz, sizeof (e_note.descsz));
7313       p = frag_more (sizeof (e_note.type));
7314       md_number_to_chars (p, (valueT) i_note.type, sizeof (e_note.type));
7315       p = frag_more (len + 1);
7316       strcpy (p, cpu_arch_name);
7317
7318       frag_align (2, 0, 0);
7319
7320       subseg_set (seg, subseg);
7321     }
7322 }
7323 #endif
7324 \f
7325 symbolS *
7326 md_undefined_symbol (name)
7327      char *name;
7328 {
7329   if (name[0] == GLOBAL_OFFSET_TABLE_NAME[0]
7330       && name[1] == GLOBAL_OFFSET_TABLE_NAME[1]
7331       && name[2] == GLOBAL_OFFSET_TABLE_NAME[2]
7332       && strcmp (name, GLOBAL_OFFSET_TABLE_NAME) == 0)
7333     {
7334       if (!GOT_symbol)
7335         {
7336           if (symbol_find (name))
7337             as_bad (_("GOT already in symbol table"));
7338           GOT_symbol = symbol_new (name, undefined_section,
7339                                    (valueT) 0, &zero_address_frag);
7340         };
7341       return GOT_symbol;
7342     }
7343   return 0;
7344 }
7345
7346 /* Round up a section size to the appropriate boundary.  */
7347
7348 valueT
7349 md_section_align (segment, size)
7350      segT segment ATTRIBUTE_UNUSED;
7351      valueT size;
7352 {
7353 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
7354   if (OUTPUT_FLAVOR == bfd_target_aout_flavour)
7355     {
7356       /* For a.out, force the section size to be aligned.  If we don't do
7357          this, BFD will align it for us, but it will not write out the
7358          final bytes of the section.  This may be a bug in BFD, but it is
7359          easier to fix it here since that is how the other a.out targets
7360          work.  */
7361       int align;
7362
7363       align = bfd_get_section_alignment (stdoutput, segment);
7364       size = ((size + (1 << align) - 1) & ((valueT) -1 << align));
7365     }
7366 #endif
7367
7368   return size;
7369 }
7370
7371 /* On the i386, PC-relative offsets are relative to the start of the
7372    next instruction.  That is, the address of the offset, plus its
7373    size, since the offset is always the last part of the insn.  */
7374
7375 long
7376 md_pcrel_from (fixS *fixP)
7377 {
7378   return fixP->fx_size + fixP->fx_where + fixP->fx_frag->fr_address;
7379 }
7380
7381 #ifndef I386COFF
7382
7383 static void
7384 s_bss (int ignore ATTRIBUTE_UNUSED)
7385 {
7386   int temp;
7387
7388 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
7389   if (IS_ELF)
7390     obj_elf_section_change_hook ();
7391 #endif
7392   temp = get_absolute_expression ();
7393   subseg_set (bss_section, (subsegT) temp);
7394   demand_empty_rest_of_line ();
7395 }
7396
7397 #endif
7398
7399 void
7400 i386_validate_fix (fixS *fixp)
7401 {
7402   if (fixp->fx_subsy && fixp->fx_subsy == GOT_symbol)
7403     {
7404       if (fixp->fx_r_type == BFD_RELOC_32_PCREL)
7405         {
7406           if (!object_64bit)
7407             abort ();
7408           fixp->fx_r_type = BFD_RELOC_X86_64_GOTPCREL;
7409         }
7410       else
7411         {
7412           if (!object_64bit)
7413             fixp->fx_r_type = BFD_RELOC_386_GOTOFF;
7414           else
7415             fixp->fx_r_type = BFD_RELOC_X86_64_GOTOFF64;
7416         }
7417       fixp->fx_subsy = 0;
7418     }
7419 }
7420
7421 arelent *
7422 tc_gen_reloc (section, fixp)
7423      asection *section ATTRIBUTE_UNUSED;
7424      fixS *fixp;
7425 {
7426   arelent *rel;
7427   bfd_reloc_code_real_type code;
7428
7429   switch (fixp->fx_r_type)
7430     {
7431     case BFD_RELOC_X86_64_PLT32:
7432     case BFD_RELOC_X86_64_GOT32:
7433     case BFD_RELOC_X86_64_GOTPCREL:
7434     case BFD_RELOC_386_PLT32:
7435     case BFD_RELOC_386_GOT32:
7436     case BFD_RELOC_386_GOTOFF:
7437     case BFD_RELOC_386_GOTPC:
7438     case BFD_RELOC_386_TLS_GD:
7439     case BFD_RELOC_386_TLS_LDM:
7440     case BFD_RELOC_386_TLS_LDO_32:
7441     case BFD_RELOC_386_TLS_IE_32:
7442     case BFD_RELOC_386_TLS_IE:
7443     case BFD_RELOC_386_TLS_GOTIE:
7444     case BFD_RELOC_386_TLS_LE_32:
7445     case BFD_RELOC_386_TLS_LE:
7446     case BFD_RELOC_386_TLS_GOTDESC:
7447     case BFD_RELOC_386_TLS_DESC_CALL:
7448     case BFD_RELOC_X86_64_TLSGD:
7449     case BFD_RELOC_X86_64_TLSLD:
7450     case BFD_RELOC_X86_64_DTPOFF32:
7451     case BFD_RELOC_X86_64_DTPOFF64:
7452     case BFD_RELOC_X86_64_GOTTPOFF:
7453     case BFD_RELOC_X86_64_TPOFF32:
7454     case BFD_RELOC_X86_64_TPOFF64:
7455     case BFD_RELOC_X86_64_GOTOFF64:
7456     case BFD_RELOC_X86_64_GOTPC32:
7457     case BFD_RELOC_X86_64_GOT64:
7458     case BFD_RELOC_X86_64_GOTPCREL64:
7459     case BFD_RELOC_X86_64_GOTPC64:
7460     case BFD_RELOC_X86_64_GOTPLT64:
7461     case BFD_RELOC_X86_64_PLTOFF64:
7462     case BFD_RELOC_X86_64_GOTPC32_TLSDESC:
7463     case BFD_RELOC_X86_64_TLSDESC_CALL:
7464     case BFD_RELOC_RVA:
7465     case BFD_RELOC_VTABLE_ENTRY:
7466     case BFD_RELOC_VTABLE_INHERIT:
7467 #ifdef TE_PE
7468     case BFD_RELOC_32_SECREL:
7469 #endif
7470       code = fixp->fx_r_type;
7471       break;
7472     case BFD_RELOC_X86_64_32S:
7473       if (!fixp->fx_pcrel)
7474         {
7475           /* Don't turn BFD_RELOC_X86_64_32S into BFD_RELOC_32.  */
7476           code = fixp->fx_r_type;
7477           break;
7478         }
7479     default:
7480       if (fixp->fx_pcrel)
7481         {
7482           switch (fixp->fx_size)
7483             {
7484             default:
7485               as_bad_where (fixp->fx_file, fixp->fx_line,
7486                             _("can not do %d byte pc-relative relocation"),
7487                             fixp->fx_size);
7488               code = BFD_RELOC_32_PCREL;
7489               break;
7490             case 1: code = BFD_RELOC_8_PCREL;  break;
7491             case 2: code = BFD_RELOC_16_PCREL; break;
7492             case 4: code = BFD_RELOC_32_PCREL; break;
7493 #ifdef BFD64
7494             case 8: code = BFD_RELOC_64_PCREL; break;
7495 #endif
7496             }
7497         }
7498       else
7499         {
7500           switch (fixp->fx_size)
7501             {
7502             default:
7503               as_bad_where (fixp->fx_file, fixp->fx_line,
7504                             _("can not do %d byte relocation"),
7505                             fixp->fx_size);
7506               code = BFD_RELOC_32;
7507               break;
7508             case 1: code = BFD_RELOC_8;  break;
7509             case 2: code = BFD_RELOC_16; break;
7510             case 4: code = BFD_RELOC_32; break;
7511 #ifdef BFD64
7512             case 8: code = BFD_RELOC_64; break;
7513 #endif
7514             }
7515         }
7516       break;
7517     }
7518
7519   if ((code == BFD_RELOC_32
7520        || code == BFD_RELOC_32_PCREL
7521        || code == BFD_RELOC_X86_64_32S)
7522       && GOT_symbol
7523       && fixp->fx_addsy == GOT_symbol)
7524     {
7525       if (!object_64bit)
7526         code = BFD_RELOC_386_GOTPC;
7527       else
7528         code = BFD_RELOC_X86_64_GOTPC32;
7529     }
7530   if ((code == BFD_RELOC_64 || code == BFD_RELOC_64_PCREL)
7531       && GOT_symbol
7532       && fixp->fx_addsy == GOT_symbol)
7533     {
7534       code = BFD_RELOC_X86_64_GOTPC64;
7535     }
7536
7537   rel = (arelent *) xmalloc (sizeof (arelent));
7538   rel->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
7539   *rel->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
7540
7541   rel->address = fixp->fx_frag->fr_address + fixp->fx_where;
7542
7543   if (!use_rela_relocations)
7544     {
7545       /* HACK: Since i386 ELF uses Rel instead of Rela, encode the
7546          vtable entry to be used in the relocation's section offset.  */
7547       if (fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
7548         rel->address = fixp->fx_offset;
7549
7550       rel->addend = 0;
7551     }
7552   /* Use the rela in 64bit mode.  */
7553   else
7554     {
7555       if (!fixp->fx_pcrel)
7556         rel->addend = fixp->fx_offset;
7557       else
7558         switch (code)
7559           {
7560           case BFD_RELOC_X86_64_PLT32:
7561           case BFD_RELOC_X86_64_GOT32:
7562           case BFD_RELOC_X86_64_GOTPCREL:
7563           case BFD_RELOC_X86_64_TLSGD:
7564           case BFD_RELOC_X86_64_TLSLD:
7565           case BFD_RELOC_X86_64_GOTTPOFF:
7566           case BFD_RELOC_X86_64_GOTPC32_TLSDESC:
7567           case BFD_RELOC_X86_64_TLSDESC_CALL:
7568             rel->addend = fixp->fx_offset - fixp->fx_size;
7569             break;
7570           default:
7571             rel->addend = (section->vma
7572                            - fixp->fx_size
7573                            + fixp->fx_addnumber
7574                            + md_pcrel_from (fixp));
7575             break;
7576           }
7577     }
7578
7579   rel->howto = bfd_reloc_type_lookup (stdoutput, code);
7580   if (rel->howto == NULL)
7581     {
7582       as_bad_where (fixp->fx_file, fixp->fx_line,
7583                     _("cannot represent relocation type %s"),
7584                     bfd_get_reloc_code_name (code));
7585       /* Set howto to a garbage value so that we can keep going.  */
7586       rel->howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_32);
7587       assert (rel->howto != NULL);
7588     }
7589
7590   return rel;
7591 }
7592
7593 \f
7594 /* Parse operands using Intel syntax. This implements a recursive descent
7595    parser based on the BNF grammar published in Appendix B of the MASM 6.1
7596    Programmer's Guide.
7597
7598    FIXME: We do not recognize the full operand grammar defined in the MASM
7599           documentation.  In particular, all the structure/union and
7600           high-level macro operands are missing.
7601
7602    Uppercase words are terminals, lower case words are non-terminals.
7603    Objects surrounded by double brackets '[[' ']]' are optional. Vertical
7604    bars '|' denote choices. Most grammar productions are implemented in
7605    functions called 'intel_<production>'.
7606
7607    Initial production is 'expr'.
7608
7609     addOp               + | -
7610
7611     alpha               [a-zA-Z]
7612
7613     binOp               & | AND | \| | OR | ^ | XOR
7614
7615     byteRegister        AL | AH | BL | BH | CL | CH | DL | DH
7616
7617     constant            digits [[ radixOverride ]]
7618
7619     dataType            BYTE | WORD | DWORD | FWORD | QWORD | TBYTE | OWORD | XMMWORD
7620
7621     digits              decdigit
7622                         | digits decdigit
7623                         | digits hexdigit
7624
7625     decdigit            [0-9]
7626
7627     e04                 e04 addOp e05
7628                         | e05
7629
7630     e05                 e05 binOp e06
7631                         | e06
7632
7633     e06                 e06 mulOp e09
7634                         | e09
7635
7636     e09                 OFFSET e10
7637                         | SHORT e10
7638                         | + e10
7639                         | - e10
7640                         | ~ e10
7641                         | NOT e10
7642                         | e09 PTR e10
7643                         | e09 : e10
7644                         | e10
7645
7646     e10                 e10 [ expr ]
7647                         | e11
7648
7649     e11                 ( expr )
7650                         | [ expr ]
7651                         | constant
7652                         | dataType
7653                         | id
7654                         | $
7655                         | register
7656
7657  => expr                expr cmpOp e04
7658                         | e04
7659
7660     gpRegister          AX | EAX | BX | EBX | CX | ECX | DX | EDX
7661                         | BP | EBP | SP | ESP | DI | EDI | SI | ESI
7662
7663     hexdigit            a | b | c | d | e | f
7664                         | A | B | C | D | E | F
7665
7666     id                  alpha
7667                         | id alpha
7668                         | id decdigit
7669
7670     mulOp               * | / | % | MOD | << | SHL | >> | SHR
7671
7672     quote               " | '
7673
7674     register            specialRegister
7675                         | gpRegister
7676                         | byteRegister
7677
7678     segmentRegister     CS | DS | ES | FS | GS | SS
7679
7680     specialRegister     CR0 | CR2 | CR3 | CR4
7681                         | DR0 | DR1 | DR2 | DR3 | DR6 | DR7
7682                         | TR3 | TR4 | TR5 | TR6 | TR7
7683
7684     We simplify the grammar in obvious places (e.g., register parsing is
7685     done by calling parse_register) and eliminate immediate left recursion
7686     to implement a recursive-descent parser.
7687
7688     expr        e04 expr'
7689
7690     expr'       cmpOp e04 expr'
7691                 | Empty
7692
7693     e04         e05 e04'
7694
7695     e04'        addOp e05 e04'
7696                 | Empty
7697
7698     e05         e06 e05'
7699
7700     e05'        binOp e06 e05'
7701                 | Empty
7702
7703     e06         e09 e06'
7704
7705     e06'        mulOp e09 e06'
7706                 | Empty
7707
7708     e09         OFFSET e10 e09'
7709                 | SHORT e10'
7710                 | + e10'
7711                 | - e10'
7712                 | ~ e10'
7713                 | NOT e10'
7714                 | e10 e09'
7715
7716     e09'        PTR e10 e09'
7717                 | : e10 e09'
7718                 | Empty
7719
7720     e10         e11 e10'
7721
7722     e10'        [ expr ] e10'
7723                 | Empty
7724
7725     e11         ( expr )
7726                 | [ expr ]
7727                 | BYTE
7728                 | WORD
7729                 | DWORD
7730                 | FWORD
7731                 | QWORD
7732                 | TBYTE
7733                 | OWORD
7734                 | XMMWORD
7735                 | .
7736                 | $
7737                 | register
7738                 | id
7739                 | constant  */
7740
7741 /* Parsing structure for the intel syntax parser. Used to implement the
7742    semantic actions for the operand grammar.  */
7743 struct intel_parser_s
7744   {
7745     char *op_string;            /* The string being parsed.  */
7746     int got_a_float;            /* Whether the operand is a float.  */
7747     int op_modifier;            /* Operand modifier.  */
7748     int is_mem;                 /* 1 if operand is memory reference.  */
7749     int in_offset;              /* >=1 if parsing operand of offset.  */
7750     int in_bracket;             /* >=1 if parsing operand in brackets.  */
7751     const reg_entry *reg;       /* Last register reference found.  */
7752     char *disp;                 /* Displacement string being built.  */
7753     char *next_operand;         /* Resume point when splitting operands.  */
7754   };
7755
7756 static struct intel_parser_s intel_parser;
7757
7758 /* Token structure for parsing intel syntax.  */
7759 struct intel_token
7760   {
7761     int code;                   /* Token code.  */
7762     const reg_entry *reg;       /* Register entry for register tokens.  */
7763     char *str;                  /* String representation.  */
7764   };
7765
7766 static struct intel_token cur_token, prev_token;
7767
7768 /* Token codes for the intel parser. Since T_SHORT is already used
7769    by COFF, undefine it first to prevent a warning.  */
7770 #define T_NIL           -1
7771 #define T_CONST         1
7772 #define T_REG           2
7773 #define T_BYTE          3
7774 #define T_WORD          4
7775 #define T_DWORD         5
7776 #define T_FWORD         6
7777 #define T_QWORD         7
7778 #define T_TBYTE         8
7779 #define T_XMMWORD       9
7780 #undef  T_SHORT
7781 #define T_SHORT         10
7782 #define T_OFFSET        11
7783 #define T_PTR           12
7784 #define T_ID            13
7785 #define T_SHL           14
7786 #define T_SHR           15
7787
7788 /* Prototypes for intel parser functions.  */
7789 static int intel_match_token (int);
7790 static void intel_putback_token (void);
7791 static void intel_get_token (void);
7792 static int intel_expr (void);
7793 static int intel_e04 (void);
7794 static int intel_e05 (void);
7795 static int intel_e06 (void);
7796 static int intel_e09 (void);
7797 static int intel_e10 (void);
7798 static int intel_e11 (void);
7799
7800 static int
7801 i386_intel_operand (char *operand_string, int got_a_float)
7802 {
7803   int ret;
7804   char *p;
7805
7806   p = intel_parser.op_string = xstrdup (operand_string);
7807   intel_parser.disp = (char *) xmalloc (strlen (operand_string) + 1);
7808
7809   for (;;)
7810     {
7811       /* Initialize token holders.  */
7812       cur_token.code = prev_token.code = T_NIL;
7813       cur_token.reg = prev_token.reg = NULL;
7814       cur_token.str = prev_token.str = NULL;
7815
7816       /* Initialize parser structure.  */
7817       intel_parser.got_a_float = got_a_float;
7818       intel_parser.op_modifier = 0;
7819       intel_parser.is_mem = 0;
7820       intel_parser.in_offset = 0;
7821       intel_parser.in_bracket = 0;
7822       intel_parser.reg = NULL;
7823       intel_parser.disp[0] = '\0';
7824       intel_parser.next_operand = NULL;
7825
7826       /* Read the first token and start the parser.  */
7827       intel_get_token ();
7828       ret = intel_expr ();
7829
7830       if (!ret)
7831         break;
7832
7833       if (cur_token.code != T_NIL)
7834         {
7835           as_bad (_("invalid operand for '%s' ('%s' unexpected)"),
7836                   current_templates->start->name, cur_token.str);
7837           ret = 0;
7838         }
7839       /* If we found a memory reference, hand it over to i386_displacement
7840          to fill in the rest of the operand fields.  */
7841       else if (intel_parser.is_mem)
7842         {
7843           if ((i.mem_operands == 1
7844                && !current_templates->start->opcode_modifier.isstring)
7845               || i.mem_operands == 2)
7846             {
7847               as_bad (_("too many memory references for '%s'"),
7848                       current_templates->start->name);
7849               ret = 0;
7850             }
7851           else
7852             {
7853               char *s = intel_parser.disp;
7854               i.mem_operands++;
7855
7856               if (!quiet_warnings && intel_parser.is_mem < 0)
7857                 /* See the comments in intel_bracket_expr.  */
7858                 as_warn (_("Treating `%s' as memory reference"), operand_string);
7859
7860               /* Add the displacement expression.  */
7861               if (*s != '\0')
7862                 ret = i386_displacement (s, s + strlen (s));
7863               if (ret)
7864                 {
7865                   /* Swap base and index in 16-bit memory operands like
7866                      [si+bx]. Since i386_index_check is also used in AT&T
7867                      mode we have to do that here.  */
7868                   if (i.base_reg
7869                       && i.index_reg
7870                       && i.base_reg->reg_type.bitfield.reg16
7871                       && i.index_reg->reg_type.bitfield.reg16
7872                       && i.base_reg->reg_num >= 6
7873                       && i.index_reg->reg_num < 6)
7874                     {
7875                       const reg_entry *base = i.index_reg;
7876
7877                       i.index_reg = i.base_reg;
7878                       i.base_reg = base;
7879                     }
7880                   ret = i386_index_check (operand_string);
7881                 }
7882             }
7883         }
7884
7885       /* Constant and OFFSET expressions are handled by i386_immediate.  */
7886       else if ((intel_parser.op_modifier & (1 << T_OFFSET))
7887                || intel_parser.reg == NULL)
7888         ret = i386_immediate (intel_parser.disp);
7889
7890       if (intel_parser.next_operand && this_operand >= MAX_OPERANDS - 1)
7891         ret = 0;
7892       if (!ret || !intel_parser.next_operand)
7893         break;
7894       intel_parser.op_string = intel_parser.next_operand;
7895       this_operand = i.operands++;
7896     }
7897
7898   free (p);
7899   free (intel_parser.disp);
7900
7901   return ret;
7902 }
7903
7904 #define NUM_ADDRESS_REGS (!!i.base_reg + !!i.index_reg)
7905
7906 /* expr e04 expr'
7907
7908    expr'  cmpOp e04 expr'
7909         | Empty  */
7910 static int
7911 intel_expr (void)
7912 {
7913   /* XXX Implement the comparison operators.  */
7914   return intel_e04 ();
7915 }
7916
7917 /* e04  e05 e04'
7918
7919    e04' addOp e05 e04'
7920         | Empty  */
7921 static int
7922 intel_e04 (void)
7923 {
7924   int nregs = -1;
7925
7926   for (;;)
7927     {
7928       if (!intel_e05())
7929         return 0;
7930
7931       if (nregs >= 0 && NUM_ADDRESS_REGS > nregs)
7932         i.base_reg = i386_regtab + REGNAM_AL; /* al is invalid as base */
7933
7934       if (cur_token.code == '+')
7935         nregs = -1;
7936       else if (cur_token.code == '-')
7937         nregs = NUM_ADDRESS_REGS;
7938       else
7939         return 1;
7940
7941       strcat (intel_parser.disp, cur_token.str);
7942       intel_match_token (cur_token.code);
7943     }
7944 }
7945
7946 /* e05  e06 e05'
7947
7948    e05' binOp e06 e05'
7949         | Empty  */
7950 static int
7951 intel_e05 (void)
7952 {
7953   int nregs = ~NUM_ADDRESS_REGS;
7954
7955   for (;;)
7956     {
7957       if (!intel_e06())
7958         return 0;
7959
7960       if (cur_token.code == '&'
7961           || cur_token.code == '|'
7962           || cur_token.code == '^')
7963         {
7964           char str[2];
7965
7966           str[0] = cur_token.code;
7967           str[1] = 0;
7968           strcat (intel_parser.disp, str);
7969         }
7970       else
7971         break;
7972
7973       intel_match_token (cur_token.code);
7974
7975       if (nregs < 0)
7976         nregs = ~nregs;
7977     }
7978   if (nregs >= 0 && NUM_ADDRESS_REGS > nregs)
7979     i.base_reg = i386_regtab + REGNAM_AL + 1; /* cl is invalid as base */
7980   return 1;
7981 }
7982
7983 /* e06  e09 e06'
7984
7985    e06' mulOp e09 e06'
7986         | Empty  */
7987 static int
7988 intel_e06 (void)
7989 {
7990   int nregs = ~NUM_ADDRESS_REGS;
7991
7992   for (;;)
7993     {
7994       if (!intel_e09())
7995         return 0;
7996
7997       if (cur_token.code == '*'
7998           || cur_token.code == '/'
7999           || cur_token.code == '%')
8000         {
8001           char str[2];
8002
8003           str[0] = cur_token.code;
8004           str[1] = 0;
8005           strcat (intel_parser.disp, str);
8006         }
8007       else if (cur_token.code == T_SHL)
8008         strcat (intel_parser.disp, "<<");
8009       else if (cur_token.code == T_SHR)
8010         strcat (intel_parser.disp, ">>");
8011       else
8012         break;
8013
8014       intel_match_token (cur_token.code);
8015
8016       if (nregs < 0)
8017         nregs = ~nregs;
8018     }
8019   if (nregs >= 0 && NUM_ADDRESS_REGS > nregs)
8020     i.base_reg = i386_regtab + REGNAM_AL + 2; /* dl is invalid as base */
8021   return 1;
8022 }
8023
8024 /* e09  OFFSET e09
8025         | SHORT e09
8026         | + e09
8027         | - e09
8028         | ~ e09
8029         | NOT e09
8030         | e10 e09'
8031
8032    e09' PTR e10 e09'
8033         | : e10 e09'
8034         | Empty */
8035 static int
8036 intel_e09 (void)
8037 {
8038   int nregs = ~NUM_ADDRESS_REGS;
8039   int in_offset = 0;
8040
8041   for (;;)
8042     {
8043       /* Don't consume constants here.  */
8044       if (cur_token.code == '+' || cur_token.code == '-')
8045         {
8046           /* Need to look one token ahead - if the next token
8047              is a constant, the current token is its sign.  */
8048           int next_code;
8049
8050           intel_match_token (cur_token.code);
8051           next_code = cur_token.code;
8052           intel_putback_token ();
8053           if (next_code == T_CONST)
8054             break;
8055         }
8056
8057       /* e09  OFFSET e09  */
8058       if (cur_token.code == T_OFFSET)
8059         {
8060           if (!in_offset++)
8061             ++intel_parser.in_offset;
8062         }
8063
8064       /* e09  SHORT e09  */
8065       else if (cur_token.code == T_SHORT)
8066         intel_parser.op_modifier |= 1 << T_SHORT;
8067
8068       /* e09  + e09  */
8069       else if (cur_token.code == '+')
8070         strcat (intel_parser.disp, "+");
8071
8072       /* e09  - e09
8073               | ~ e09
8074               | NOT e09  */
8075       else if (cur_token.code == '-' || cur_token.code == '~')
8076         {
8077           char str[2];
8078
8079           if (nregs < 0)
8080             nregs = ~nregs;
8081           str[0] = cur_token.code;
8082           str[1] = 0;
8083           strcat (intel_parser.disp, str);
8084         }
8085
8086       /* e09  e10 e09'  */
8087       else
8088         break;
8089
8090       intel_match_token (cur_token.code);
8091     }
8092
8093   for (;;)
8094     {
8095       if (!intel_e10 ())
8096         return 0;
8097
8098       /* e09'  PTR e10 e09' */
8099       if (cur_token.code == T_PTR)
8100         {
8101           char suffix;
8102
8103           if (prev_token.code == T_BYTE)
8104             suffix = BYTE_MNEM_SUFFIX;
8105
8106           else if (prev_token.code == T_WORD)
8107             {
8108               if (current_templates->start->name[0] == 'l'
8109                   && current_templates->start->name[2] == 's'
8110                   && current_templates->start->name[3] == 0)
8111                 suffix = BYTE_MNEM_SUFFIX; /* so it will cause an error */
8112               else if (intel_parser.got_a_float == 2)   /* "fi..." */
8113                 suffix = SHORT_MNEM_SUFFIX;
8114               else
8115                 suffix = WORD_MNEM_SUFFIX;
8116             }
8117
8118           else if (prev_token.code == T_DWORD)
8119             {
8120               if (current_templates->start->name[0] == 'l'
8121                   && current_templates->start->name[2] == 's'
8122                   && current_templates->start->name[3] == 0)
8123                 suffix = WORD_MNEM_SUFFIX;
8124               else if (flag_code == CODE_16BIT
8125                        && (current_templates->start->opcode_modifier.jump
8126                            || current_templates->start->opcode_modifier.jumpdword))
8127                 suffix = LONG_DOUBLE_MNEM_SUFFIX;
8128               else if (intel_parser.got_a_float == 1)   /* "f..." */
8129                 suffix = SHORT_MNEM_SUFFIX;
8130               else
8131                 suffix = LONG_MNEM_SUFFIX;
8132             }
8133
8134           else if (prev_token.code == T_FWORD)
8135             {
8136               if (current_templates->start->name[0] == 'l'
8137                   && current_templates->start->name[2] == 's'
8138                   && current_templates->start->name[3] == 0)
8139                 suffix = LONG_MNEM_SUFFIX;
8140               else if (!intel_parser.got_a_float)
8141                 {
8142                   if (flag_code == CODE_16BIT)
8143                     add_prefix (DATA_PREFIX_OPCODE);
8144                   suffix = LONG_DOUBLE_MNEM_SUFFIX;
8145                 }
8146               else
8147                 suffix = BYTE_MNEM_SUFFIX; /* so it will cause an error */
8148             }
8149
8150           else if (prev_token.code == T_QWORD)
8151             {
8152               if (intel_parser.got_a_float == 1)        /* "f..." */
8153                 suffix = LONG_MNEM_SUFFIX;
8154               else
8155                 suffix = QWORD_MNEM_SUFFIX;
8156             }
8157
8158           else if (prev_token.code == T_TBYTE)
8159             {
8160               if (intel_parser.got_a_float == 1)
8161                 suffix = LONG_DOUBLE_MNEM_SUFFIX;
8162               else
8163                 suffix = BYTE_MNEM_SUFFIX; /* so it will cause an error */
8164             }
8165
8166           else if (prev_token.code == T_XMMWORD)
8167             {
8168               /* XXX ignored for now, but accepted since gcc uses it */
8169               suffix = 0;
8170             }
8171
8172           else
8173             {
8174               as_bad (_("Unknown operand modifier `%s'"), prev_token.str);
8175               return 0;
8176             }
8177
8178           /* Operands for jump/call using 'ptr' notation denote absolute
8179              addresses.  */
8180           if (current_templates->start->opcode_modifier.jump
8181               || current_templates->start->opcode_modifier.jumpdword)
8182             i.types[this_operand].bitfield.jumpabsolute = 1;
8183
8184           if (current_templates->start->base_opcode == 0x8d /* lea */)
8185             ;
8186           else if (!i.suffix)
8187             i.suffix = suffix;
8188           else if (i.suffix != suffix)
8189             {
8190               as_bad (_("Conflicting operand modifiers"));
8191               return 0;
8192             }
8193
8194         }
8195
8196       /* e09'  : e10 e09'  */
8197       else if (cur_token.code == ':')
8198         {
8199           if (prev_token.code != T_REG)
8200             {
8201               /* While {call,jmp} SSSS:OOOO is MASM syntax only when SSSS is a
8202                  segment/group identifier (which we don't have), using comma
8203                  as the operand separator there is even less consistent, since
8204                  there all branches only have a single operand.  */
8205               if (this_operand != 0
8206                   || intel_parser.in_offset
8207                   || intel_parser.in_bracket
8208                   || (!current_templates->start->opcode_modifier.jump
8209                       && !current_templates->start->opcode_modifier.jumpdword
8210                       && !current_templates->start->opcode_modifier.jumpintersegment
8211                       && !current_templates->start->operand_types[0].bitfield.jumpabsolute))
8212                 return intel_match_token (T_NIL);
8213               /* Remember the start of the 2nd operand and terminate 1st
8214                  operand here.
8215                  XXX This isn't right, yet (when SSSS:OOOO is right operand of
8216                  another expression), but it gets at least the simplest case
8217                  (a plain number or symbol on the left side) right.  */
8218               intel_parser.next_operand = intel_parser.op_string;
8219               *--intel_parser.op_string = '\0';
8220               return intel_match_token (':');
8221             }
8222         }
8223
8224       /* e09'  Empty  */
8225       else
8226         break;
8227
8228       intel_match_token (cur_token.code);
8229
8230     }
8231
8232   if (in_offset)
8233     {
8234       --intel_parser.in_offset;
8235       if (nregs < 0)
8236         nregs = ~nregs;
8237       if (NUM_ADDRESS_REGS > nregs)
8238         {
8239           as_bad (_("Invalid operand to `OFFSET'"));
8240           return 0;
8241         }
8242       intel_parser.op_modifier |= 1 << T_OFFSET;
8243     }
8244
8245   if (nregs >= 0 && NUM_ADDRESS_REGS > nregs)
8246     i.base_reg = i386_regtab + REGNAM_AL + 3; /* bl is invalid as base */
8247   return 1;
8248 }
8249
8250 static int
8251 intel_bracket_expr (void)
8252 {
8253   int was_offset = intel_parser.op_modifier & (1 << T_OFFSET);
8254   const char *start = intel_parser.op_string;
8255   int len;
8256
8257   if (i.op[this_operand].regs)
8258     return intel_match_token (T_NIL);
8259
8260   intel_match_token ('[');
8261
8262   /* Mark as a memory operand only if it's not already known to be an
8263      offset expression.  If it's an offset expression, we need to keep
8264      the brace in.  */
8265   if (!intel_parser.in_offset)
8266     {
8267       ++intel_parser.in_bracket;
8268
8269       /* Operands for jump/call inside brackets denote absolute addresses.  */
8270       if (current_templates->start->opcode_modifier.jump
8271           || current_templates->start->opcode_modifier.jumpdword)
8272         i.types[this_operand].bitfield.jumpabsolute = 1;
8273
8274       /* Unfortunately gas always diverged from MASM in a respect that can't
8275          be easily fixed without risking to break code sequences likely to be
8276          encountered (the testsuite even check for this): MASM doesn't consider
8277          an expression inside brackets unconditionally as a memory reference.
8278          When that is e.g. a constant, an offset expression, or the sum of the
8279          two, this is still taken as a constant load. gas, however, always
8280          treated these as memory references. As a compromise, we'll try to make
8281          offset expressions inside brackets work the MASM way (since that's
8282          less likely to be found in real world code), but make constants alone
8283          continue to work the traditional gas way. In either case, issue a
8284          warning.  */
8285       intel_parser.op_modifier &= ~was_offset;
8286     }
8287   else
8288     strcat (intel_parser.disp, "[");
8289
8290   /* Add a '+' to the displacement string if necessary.  */
8291   if (*intel_parser.disp != '\0'
8292       && *(intel_parser.disp + strlen (intel_parser.disp) - 1) != '+')
8293     strcat (intel_parser.disp, "+");
8294
8295   if (intel_expr ()
8296       && (len = intel_parser.op_string - start - 1,
8297           intel_match_token (']')))
8298     {
8299       /* Preserve brackets when the operand is an offset expression.  */
8300       if (intel_parser.in_offset)
8301         strcat (intel_parser.disp, "]");
8302       else
8303         {
8304           --intel_parser.in_bracket;
8305           if (i.base_reg || i.index_reg)
8306             intel_parser.is_mem = 1;
8307           if (!intel_parser.is_mem)
8308             {
8309               if (!(intel_parser.op_modifier & (1 << T_OFFSET)))
8310                 /* Defer the warning until all of the operand was parsed.  */
8311                 intel_parser.is_mem = -1;
8312               else if (!quiet_warnings)
8313                 as_warn (_("`[%.*s]' taken to mean just `%.*s'"),
8314                          len, start, len, start);
8315             }
8316         }
8317       intel_parser.op_modifier |= was_offset;
8318
8319       return 1;
8320     }
8321   return 0;
8322 }
8323
8324 /* e10  e11 e10'
8325
8326    e10' [ expr ] e10'
8327         | Empty  */
8328 static int
8329 intel_e10 (void)
8330 {
8331   if (!intel_e11 ())
8332     return 0;
8333
8334   while (cur_token.code == '[')
8335     {
8336       if (!intel_bracket_expr ())
8337         return 0;
8338     }
8339
8340   return 1;
8341 }
8342
8343 /* e11  ( expr )
8344         | [ expr ]
8345         | BYTE
8346         | WORD
8347         | DWORD
8348         | FWORD
8349         | QWORD
8350         | TBYTE
8351         | OWORD
8352         | XMMWORD
8353         | $
8354         | .
8355         | register
8356         | id
8357         | constant  */
8358 static int
8359 intel_e11 (void)
8360 {
8361   switch (cur_token.code)
8362     {
8363     /* e11  ( expr ) */
8364     case '(':
8365       intel_match_token ('(');
8366       strcat (intel_parser.disp, "(");
8367
8368       if (intel_expr () && intel_match_token (')'))
8369         {
8370           strcat (intel_parser.disp, ")");
8371           return 1;
8372         }
8373       return 0;
8374
8375     /* e11  [ expr ] */
8376     case '[':
8377       return intel_bracket_expr ();
8378
8379     /* e11  $
8380             | .  */
8381     case '.':
8382       strcat (intel_parser.disp, cur_token.str);
8383       intel_match_token (cur_token.code);
8384
8385       /* Mark as a memory operand only if it's not already known to be an
8386          offset expression.  */
8387       if (!intel_parser.in_offset)
8388         intel_parser.is_mem = 1;
8389
8390       return 1;
8391
8392     /* e11  register  */
8393     case T_REG:
8394       {
8395         const reg_entry *reg = intel_parser.reg = cur_token.reg;
8396
8397         intel_match_token (T_REG);
8398
8399         /* Check for segment change.  */
8400         if (cur_token.code == ':')
8401           {
8402             if (!reg->reg_type.bitfield.sreg2
8403                 && !reg->reg_type.bitfield.sreg3)
8404               {
8405                 as_bad (_("`%s' is not a valid segment register"),
8406                         reg->reg_name);
8407                 return 0;
8408               }
8409             else if (i.seg[i.mem_operands])
8410               as_warn (_("Extra segment override ignored"));
8411             else
8412               {
8413                 if (!intel_parser.in_offset)
8414                   intel_parser.is_mem = 1;
8415                 switch (reg->reg_num)
8416                   {
8417                   case 0:
8418                     i.seg[i.mem_operands] = &es;
8419                     break;
8420                   case 1:
8421                     i.seg[i.mem_operands] = &cs;
8422                     break;
8423                   case 2:
8424                     i.seg[i.mem_operands] = &ss;
8425                     break;
8426                   case 3:
8427                     i.seg[i.mem_operands] = &ds;
8428                     break;
8429                   case 4:
8430                     i.seg[i.mem_operands] = &fs;
8431                     break;
8432                   case 5:
8433                     i.seg[i.mem_operands] = &gs;
8434                     break;
8435                   }
8436               }
8437           }
8438
8439         /* Not a segment register. Check for register scaling.  */
8440         else if (cur_token.code == '*')
8441           {
8442             if (!intel_parser.in_bracket)
8443               {
8444                 as_bad (_("Register scaling only allowed in memory operands"));
8445                 return 0;
8446               }
8447
8448             if (reg->reg_type.bitfield.reg16) /* Disallow things like [si*1]. */
8449               reg = i386_regtab + REGNAM_AX + 4; /* sp is invalid as index */
8450             else if (i.index_reg)
8451               reg = i386_regtab + REGNAM_EAX + 4; /* esp is invalid as index */
8452
8453             /* What follows must be a valid scale.  */
8454             intel_match_token ('*');
8455             i.index_reg = reg;
8456             i.types[this_operand].bitfield.baseindex = 1;
8457
8458             /* Set the scale after setting the register (otherwise,
8459                i386_scale will complain)  */
8460             if (cur_token.code == '+' || cur_token.code == '-')
8461               {
8462                 char *str, sign = cur_token.code;
8463                 intel_match_token (cur_token.code);
8464                 if (cur_token.code != T_CONST)
8465                   {
8466                     as_bad (_("Syntax error: Expecting a constant, got `%s'"),
8467                             cur_token.str);
8468                     return 0;
8469                   }
8470                 str = (char *) xmalloc (strlen (cur_token.str) + 2);
8471                 strcpy (str + 1, cur_token.str);
8472                 *str = sign;
8473                 if (!i386_scale (str))
8474                   return 0;
8475                 free (str);
8476               }
8477             else if (!i386_scale (cur_token.str))
8478               return 0;
8479             intel_match_token (cur_token.code);
8480           }
8481
8482         /* No scaling. If this is a memory operand, the register is either a
8483            base register (first occurrence) or an index register (second
8484            occurrence).  */
8485         else if (intel_parser.in_bracket)
8486           {
8487
8488             if (!i.base_reg)
8489               i.base_reg = reg;
8490             else if (!i.index_reg)
8491               i.index_reg = reg;
8492             else
8493               {
8494                 as_bad (_("Too many register references in memory operand"));
8495                 return 0;
8496               }
8497
8498             i.types[this_operand].bitfield.baseindex = 1;
8499           }
8500
8501         /* It's neither base nor index.  */
8502         else if (!intel_parser.in_offset && !intel_parser.is_mem)
8503           {
8504             i386_operand_type temp = reg->reg_type;
8505             temp.bitfield.baseindex = 0;
8506             i.types[this_operand] = operand_type_or (i.types[this_operand],
8507                                                      temp);
8508             i.op[this_operand].regs = reg;
8509             i.reg_operands++;
8510           }
8511         else
8512           {
8513             as_bad (_("Invalid use of register"));
8514             return 0;
8515           }
8516
8517         /* Since registers are not part of the displacement string (except
8518            when we're parsing offset operands), we may need to remove any
8519            preceding '+' from the displacement string.  */
8520         if (*intel_parser.disp != '\0'
8521             && !intel_parser.in_offset)
8522           {
8523             char *s = intel_parser.disp;
8524             s += strlen (s) - 1;
8525             if (*s == '+')
8526               *s = '\0';
8527           }
8528
8529         return 1;
8530       }
8531
8532     /* e11  BYTE
8533             | WORD
8534             | DWORD
8535             | FWORD
8536             | QWORD
8537             | TBYTE
8538             | OWORD
8539             | XMMWORD  */
8540     case T_BYTE:
8541     case T_WORD:
8542     case T_DWORD:
8543     case T_FWORD:
8544     case T_QWORD:
8545     case T_TBYTE:
8546     case T_XMMWORD:
8547       intel_match_token (cur_token.code);
8548
8549       if (cur_token.code == T_PTR)
8550         return 1;
8551
8552       /* It must have been an identifier.  */
8553       intel_putback_token ();
8554       cur_token.code = T_ID;
8555       /* FALLTHRU */
8556
8557     /* e11  id
8558             | constant  */
8559     case T_ID:
8560       if (!intel_parser.in_offset && intel_parser.is_mem <= 0)
8561         {
8562           symbolS *symbolP;
8563
8564           /* The identifier represents a memory reference only if it's not
8565              preceded by an offset modifier and if it's not an equate.  */
8566           symbolP = symbol_find(cur_token.str);
8567           if (!symbolP || S_GET_SEGMENT(symbolP) != absolute_section)
8568             intel_parser.is_mem = 1;
8569         }
8570         /* FALLTHRU */
8571
8572     case T_CONST:
8573     case '-':
8574     case '+':
8575       {
8576         char *save_str, sign = 0;
8577
8578         /* Allow constants that start with `+' or `-'.  */
8579         if (cur_token.code == '-' || cur_token.code == '+')
8580           {
8581             sign = cur_token.code;
8582             intel_match_token (cur_token.code);
8583             if (cur_token.code != T_CONST)
8584               {
8585                 as_bad (_("Syntax error: Expecting a constant, got `%s'"),
8586                         cur_token.str);
8587                 return 0;
8588               }
8589           }
8590
8591         save_str = (char *) xmalloc (strlen (cur_token.str) + 2);
8592         strcpy (save_str + !!sign, cur_token.str);
8593         if (sign)
8594           *save_str = sign;
8595
8596         /* Get the next token to check for register scaling.  */
8597         intel_match_token (cur_token.code);
8598
8599         /* Check if this constant is a scaling factor for an
8600            index register.  */
8601         if (cur_token.code == '*')
8602           {
8603             if (intel_match_token ('*') && cur_token.code == T_REG)
8604               {
8605                 const reg_entry *reg = cur_token.reg;
8606
8607                 if (!intel_parser.in_bracket)
8608                   {
8609                     as_bad (_("Register scaling only allowed "
8610                               "in memory operands"));
8611                     return 0;
8612                   }
8613
8614                  /* Disallow things like [1*si].
8615                     sp and esp are invalid as index.  */
8616                 if (reg->reg_type.bitfield.reg16)
8617                   reg = i386_regtab + REGNAM_AX + 4;
8618                 else if (i.index_reg)
8619                   reg = i386_regtab + REGNAM_EAX + 4;
8620
8621                 /* The constant is followed by `* reg', so it must be
8622                    a valid scale.  */
8623                 i.index_reg = reg;
8624                 i.types[this_operand].bitfield.baseindex = 1;
8625
8626                 /* Set the scale after setting the register (otherwise,
8627                    i386_scale will complain)  */
8628                 if (!i386_scale (save_str))
8629                   return 0;
8630                 intel_match_token (T_REG);
8631
8632                 /* Since registers are not part of the displacement
8633                    string, we may need to remove any preceding '+' from
8634                    the displacement string.  */
8635                 if (*intel_parser.disp != '\0')
8636                   {
8637                     char *s = intel_parser.disp;
8638                     s += strlen (s) - 1;
8639                     if (*s == '+')
8640                       *s = '\0';
8641                   }
8642
8643                 free (save_str);
8644
8645                 return 1;
8646               }
8647
8648             /* The constant was not used for register scaling. Since we have
8649                already consumed the token following `*' we now need to put it
8650                back in the stream.  */
8651             intel_putback_token ();
8652           }
8653
8654         /* Add the constant to the displacement string.  */
8655         strcat (intel_parser.disp, save_str);
8656         free (save_str);
8657
8658         return 1;
8659       }
8660     }
8661
8662   as_bad (_("Unrecognized token '%s'"), cur_token.str);
8663   return 0;
8664 }
8665
8666 /* Match the given token against cur_token. If they match, read the next
8667    token from the operand string.  */
8668 static int
8669 intel_match_token (int code)
8670 {
8671   if (cur_token.code == code)
8672     {
8673       intel_get_token ();
8674       return 1;
8675     }
8676   else
8677     {
8678       as_bad (_("Unexpected token `%s'"), cur_token.str);
8679       return 0;
8680     }
8681 }
8682
8683 /* Read a new token from intel_parser.op_string and store it in cur_token.  */
8684 static void
8685 intel_get_token (void)
8686 {
8687   char *end_op;
8688   const reg_entry *reg;
8689   struct intel_token new_token;
8690
8691   new_token.code = T_NIL;
8692   new_token.reg = NULL;
8693   new_token.str = NULL;
8694
8695   /* Free the memory allocated to the previous token and move
8696      cur_token to prev_token.  */
8697   if (prev_token.str)
8698     free (prev_token.str);
8699
8700   prev_token = cur_token;
8701
8702   /* Skip whitespace.  */
8703   while (is_space_char (*intel_parser.op_string))
8704     intel_parser.op_string++;
8705
8706   /* Return an empty token if we find nothing else on the line.  */
8707   if (*intel_parser.op_string == '\0')
8708     {
8709       cur_token = new_token;
8710       return;
8711     }
8712
8713   /* The new token cannot be larger than the remainder of the operand
8714      string.  */
8715   new_token.str = (char *) xmalloc (strlen (intel_parser.op_string) + 1);
8716   new_token.str[0] = '\0';
8717
8718   if (strchr ("0123456789", *intel_parser.op_string))
8719     {
8720       char *p = new_token.str;
8721       char *q = intel_parser.op_string;
8722       new_token.code = T_CONST;
8723
8724       /* Allow any kind of identifier char to encompass floating point and
8725          hexadecimal numbers.  */
8726       while (is_identifier_char (*q))
8727         *p++ = *q++;
8728       *p = '\0';
8729
8730       /* Recognize special symbol names [0-9][bf].  */
8731       if (strlen (intel_parser.op_string) == 2
8732           && (intel_parser.op_string[1] == 'b'
8733               || intel_parser.op_string[1] == 'f'))
8734         new_token.code = T_ID;
8735     }
8736
8737   else if ((reg = parse_register (intel_parser.op_string, &end_op)) != NULL)
8738     {
8739       size_t len = end_op - intel_parser.op_string;
8740
8741       new_token.code = T_REG;
8742       new_token.reg = reg;
8743
8744       memcpy (new_token.str, intel_parser.op_string, len);
8745       new_token.str[len] = '\0';
8746     }
8747
8748   else if (is_identifier_char (*intel_parser.op_string))
8749     {
8750       char *p = new_token.str;
8751       char *q = intel_parser.op_string;
8752
8753       /* A '.' or '$' followed by an identifier char is an identifier.
8754          Otherwise, it's operator '.' followed by an expression.  */
8755       if ((*q == '.' || *q == '$') && !is_identifier_char (*(q + 1)))
8756         {
8757           new_token.code = '.';
8758           new_token.str[0] = '.';
8759           new_token.str[1] = '\0';
8760         }
8761       else
8762         {
8763           while (is_identifier_char (*q) || *q == '@')
8764             *p++ = *q++;
8765           *p = '\0';
8766
8767           if (strcasecmp (new_token.str, "NOT") == 0)
8768             new_token.code = '~';
8769
8770           else if (strcasecmp (new_token.str, "MOD") == 0)
8771             new_token.code = '%';
8772
8773           else if (strcasecmp (new_token.str, "AND") == 0)
8774             new_token.code = '&';
8775
8776           else if (strcasecmp (new_token.str, "OR") == 0)
8777             new_token.code = '|';
8778
8779           else if (strcasecmp (new_token.str, "XOR") == 0)
8780             new_token.code = '^';
8781
8782           else if (strcasecmp (new_token.str, "SHL") == 0)
8783             new_token.code = T_SHL;
8784
8785           else if (strcasecmp (new_token.str, "SHR") == 0)
8786             new_token.code = T_SHR;
8787
8788           else if (strcasecmp (new_token.str, "BYTE") == 0)
8789             new_token.code = T_BYTE;
8790
8791           else if (strcasecmp (new_token.str, "WORD") == 0)
8792             new_token.code = T_WORD;
8793
8794           else if (strcasecmp (new_token.str, "DWORD") == 0)
8795             new_token.code = T_DWORD;
8796
8797           else if (strcasecmp (new_token.str, "FWORD") == 0)
8798             new_token.code = T_FWORD;
8799
8800           else if (strcasecmp (new_token.str, "QWORD") == 0)
8801             new_token.code = T_QWORD;
8802
8803           else if (strcasecmp (new_token.str, "TBYTE") == 0
8804                    /* XXX remove (gcc still uses it) */
8805                    || strcasecmp (new_token.str, "XWORD") == 0)
8806             new_token.code = T_TBYTE;
8807
8808           else if (strcasecmp (new_token.str, "XMMWORD") == 0
8809                    || strcasecmp (new_token.str, "OWORD") == 0)
8810             new_token.code = T_XMMWORD;
8811
8812           else if (strcasecmp (new_token.str, "PTR") == 0)
8813             new_token.code = T_PTR;
8814
8815           else if (strcasecmp (new_token.str, "SHORT") == 0)
8816             new_token.code = T_SHORT;
8817
8818           else if (strcasecmp (new_token.str, "OFFSET") == 0)
8819             {
8820               new_token.code = T_OFFSET;
8821
8822               /* ??? This is not mentioned in the MASM grammar but gcc
8823                      makes use of it with -mintel-syntax.  OFFSET may be
8824                      followed by FLAT:  */
8825               if (strncasecmp (q, " FLAT:", 6) == 0)
8826                 strcat (new_token.str, " FLAT:");
8827             }
8828
8829           /* ??? This is not mentioned in the MASM grammar.  */
8830           else if (strcasecmp (new_token.str, "FLAT") == 0)
8831             {
8832               new_token.code = T_OFFSET;
8833               if (*q == ':')
8834                 strcat (new_token.str, ":");
8835               else
8836                 as_bad (_("`:' expected"));
8837             }
8838
8839           else
8840             new_token.code = T_ID;
8841         }
8842     }
8843
8844   else if (strchr ("+-/*%|&^:[]()~", *intel_parser.op_string))
8845     {
8846       new_token.code = *intel_parser.op_string;
8847       new_token.str[0] = *intel_parser.op_string;
8848       new_token.str[1] = '\0';
8849     }
8850
8851   else if (strchr ("<>", *intel_parser.op_string)
8852            && *intel_parser.op_string == *(intel_parser.op_string + 1))
8853     {
8854       new_token.code = *intel_parser.op_string == '<' ? T_SHL : T_SHR;
8855       new_token.str[0] = *intel_parser.op_string;
8856       new_token.str[1] = *intel_parser.op_string;
8857       new_token.str[2] = '\0';
8858     }
8859
8860   else
8861     as_bad (_("Unrecognized token `%s'"), intel_parser.op_string);
8862
8863   intel_parser.op_string += strlen (new_token.str);
8864   cur_token = new_token;
8865 }
8866
8867 /* Put cur_token back into the token stream and make cur_token point to
8868    prev_token.  */
8869 static void
8870 intel_putback_token (void)
8871 {
8872   if (cur_token.code != T_NIL)
8873     {
8874       intel_parser.op_string -= strlen (cur_token.str);
8875       free (cur_token.str);
8876     }
8877   cur_token = prev_token;
8878
8879   /* Forget prev_token.  */
8880   prev_token.code = T_NIL;
8881   prev_token.reg = NULL;
8882   prev_token.str = NULL;
8883 }
8884
8885 int
8886 tc_x86_regname_to_dw2regnum (char *regname)
8887 {
8888   unsigned int regnum;
8889   unsigned int regnames_count;
8890   static const char *const regnames_32[] =
8891     {
8892       "eax", "ecx", "edx", "ebx",
8893       "esp", "ebp", "esi", "edi",
8894       "eip", "eflags", NULL,
8895       "st0", "st1", "st2", "st3",
8896       "st4", "st5", "st6", "st7",
8897       NULL, NULL,
8898       "xmm0", "xmm1", "xmm2", "xmm3",
8899       "xmm4", "xmm5", "xmm6", "xmm7",
8900       "mm0", "mm1", "mm2", "mm3",
8901       "mm4", "mm5", "mm6", "mm7",
8902       "fcw", "fsw", "mxcsr",
8903       "es", "cs", "ss", "ds", "fs", "gs", NULL, NULL,
8904       "tr", "ldtr"
8905     };
8906   static const char *const regnames_64[] =
8907     {
8908       "rax", "rdx", "rcx", "rbx",
8909       "rsi", "rdi", "rbp", "rsp",
8910       "r8",  "r9",  "r10", "r11",
8911       "r12", "r13", "r14", "r15",
8912       "rip",
8913       "xmm0",  "xmm1",  "xmm2",  "xmm3",
8914       "xmm4",  "xmm5",  "xmm6",  "xmm7",
8915       "xmm8",  "xmm9",  "xmm10", "xmm11",
8916       "xmm12", "xmm13", "xmm14", "xmm15",
8917       "st0", "st1", "st2", "st3",
8918       "st4", "st5", "st6", "st7",
8919       "mm0", "mm1", "mm2", "mm3",
8920       "mm4", "mm5", "mm6", "mm7",
8921       "rflags",
8922       "es", "cs", "ss", "ds", "fs", "gs", NULL, NULL,
8923       "fs.base", "gs.base", NULL, NULL,
8924       "tr", "ldtr",
8925       "mxcsr", "fcw", "fsw"
8926     };
8927   const char *const *regnames;
8928
8929   if (flag_code == CODE_64BIT)
8930     {
8931       regnames = regnames_64;
8932       regnames_count = ARRAY_SIZE (regnames_64);
8933     }
8934   else
8935     {
8936       regnames = regnames_32;
8937       regnames_count = ARRAY_SIZE (regnames_32);
8938     }
8939
8940   for (regnum = 0; regnum < regnames_count; regnum++)
8941     if (regnames[regnum] != NULL
8942         && strcmp (regname, regnames[regnum]) == 0)
8943       return regnum;
8944
8945   return -1;
8946 }
8947
8948 void
8949 tc_x86_frame_initial_instructions (void)
8950 {
8951   static unsigned int sp_regno;
8952
8953   if (!sp_regno)
8954     sp_regno = tc_x86_regname_to_dw2regnum (flag_code == CODE_64BIT
8955                                             ? "rsp" : "esp");
8956
8957   cfi_add_CFA_def_cfa (sp_regno, -x86_cie_data_alignment);
8958   cfi_add_CFA_offset (x86_dwarf2_return_column, x86_cie_data_alignment);
8959 }
8960
8961 int
8962 i386_elf_section_type (const char *str, size_t len)
8963 {
8964   if (flag_code == CODE_64BIT
8965       && len == sizeof ("unwind") - 1
8966       && strncmp (str, "unwind", 6) == 0)
8967     return SHT_X86_64_UNWIND;
8968
8969   return -1;
8970 }
8971
8972 #ifdef TE_PE
8973 void
8974 tc_pe_dwarf2_emit_offset (symbolS *symbol, unsigned int size)
8975 {
8976   expressionS expr;
8977
8978   expr.X_op = O_secrel;
8979   expr.X_add_symbol = symbol;
8980   expr.X_add_number = 0;
8981   emit_expr (&expr, size);
8982 }
8983 #endif
8984
8985 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
8986 /* For ELF on x86-64, add support for SHF_X86_64_LARGE.  */
8987
8988 int
8989 x86_64_section_letter (int letter, char **ptr_msg)
8990 {
8991   if (flag_code == CODE_64BIT)
8992     {
8993       if (letter == 'l')
8994         return SHF_X86_64_LARGE;
8995
8996       *ptr_msg = _("Bad .section directive: want a,l,w,x,M,S,G,T in string");
8997     }
8998   else
8999     *ptr_msg = _("Bad .section directive: want a,w,x,M,S,G,T in string");
9000   return -1;
9001 }
9002
9003 int
9004 x86_64_section_word (char *str, size_t len)
9005 {
9006   if (len == 5 && flag_code == CODE_64BIT && CONST_STRNEQ (str, "large"))
9007     return SHF_X86_64_LARGE;
9008
9009   return -1;
9010 }
9011
9012 static void
9013 handle_large_common (int small ATTRIBUTE_UNUSED)
9014 {
9015   if (flag_code != CODE_64BIT)
9016     {
9017       s_comm_internal (0, elf_common_parse);
9018       as_warn (_(".largecomm supported only in 64bit mode, producing .comm"));
9019     }
9020   else
9021     {
9022       static segT lbss_section;
9023       asection *saved_com_section_ptr = elf_com_section_ptr;
9024       asection *saved_bss_section = bss_section;
9025
9026       if (lbss_section == NULL)
9027         {
9028           flagword applicable;
9029           segT seg = now_seg;
9030           subsegT subseg = now_subseg;
9031
9032           /* The .lbss section is for local .largecomm symbols.  */
9033           lbss_section = subseg_new (".lbss", 0);
9034           applicable = bfd_applicable_section_flags (stdoutput);
9035           bfd_set_section_flags (stdoutput, lbss_section,
9036                                  applicable & SEC_ALLOC);
9037           seg_info (lbss_section)->bss = 1;
9038
9039           subseg_set (seg, subseg);
9040         }
9041
9042       elf_com_section_ptr = &_bfd_elf_large_com_section;
9043       bss_section = lbss_section;
9044
9045       s_comm_internal (0, elf_common_parse);
9046
9047       elf_com_section_ptr = saved_com_section_ptr;
9048       bss_section = saved_bss_section;
9049     }
9050 }
9051 #endif /* OBJ_ELF || OBJ_MAYBE_ELF */