x86: Optimize with EVEX128 encoding for AVX512VL
[external/binutils.git] / gas / config / tc-i386.c
1 /* tc-i386.c -- Assemble code for the Intel 80386
2    Copyright (C) 1989-2018 Free Software Foundation, Inc.
3
4    This file is part of GAS, the GNU Assembler.
5
6    GAS is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3, or (at your option)
9    any later version.
10
11    GAS is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with GAS; see the file COPYING.  If not, write to the Free
18    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
19    02110-1301, USA.  */
20
21 /* Intel 80386 machine specific gas.
22    Written by Eliot Dresselhaus (eliot@mgm.mit.edu).
23    x86_64 support by Jan Hubicka (jh@suse.cz)
24    VIA PadLock support by Michal Ludvig (mludvig@suse.cz)
25    Bugs & suggestions are completely welcome.  This is free software.
26    Please help us make it better.  */
27
28 #include "as.h"
29 #include "safe-ctype.h"
30 #include "subsegs.h"
31 #include "dwarf2dbg.h"
32 #include "dw2gencfi.h"
33 #include "elf/x86-64.h"
34 #include "opcodes/i386-init.h"
35
36 #ifndef REGISTER_WARNINGS
37 #define REGISTER_WARNINGS 1
38 #endif
39
40 #ifndef INFER_ADDR_PREFIX
41 #define INFER_ADDR_PREFIX 1
42 #endif
43
44 #ifndef DEFAULT_ARCH
45 #define DEFAULT_ARCH "i386"
46 #endif
47
48 #ifndef INLINE
49 #if __GNUC__ >= 2
50 #define INLINE __inline__
51 #else
52 #define INLINE
53 #endif
54 #endif
55
56 /* Prefixes will be emitted in the order defined below.
57    WAIT_PREFIX must be the first prefix since FWAIT is really is an
58    instruction, and so must come before any prefixes.
59    The preferred prefix order is SEG_PREFIX, ADDR_PREFIX, DATA_PREFIX,
60    REP_PREFIX/HLE_PREFIX, LOCK_PREFIX.  */
61 #define WAIT_PREFIX     0
62 #define SEG_PREFIX      1
63 #define ADDR_PREFIX     2
64 #define DATA_PREFIX     3
65 #define REP_PREFIX      4
66 #define HLE_PREFIX      REP_PREFIX
67 #define BND_PREFIX      REP_PREFIX
68 #define LOCK_PREFIX     5
69 #define REX_PREFIX      6       /* must come last.  */
70 #define MAX_PREFIXES    7       /* max prefixes per opcode */
71
72 /* we define the syntax here (modulo base,index,scale syntax) */
73 #define REGISTER_PREFIX '%'
74 #define IMMEDIATE_PREFIX '$'
75 #define ABSOLUTE_PREFIX '*'
76
77 /* these are the instruction mnemonic suffixes in AT&T syntax or
78    memory operand size in Intel syntax.  */
79 #define WORD_MNEM_SUFFIX  'w'
80 #define BYTE_MNEM_SUFFIX  'b'
81 #define SHORT_MNEM_SUFFIX 's'
82 #define LONG_MNEM_SUFFIX  'l'
83 #define QWORD_MNEM_SUFFIX  'q'
84 /* Intel Syntax.  Use a non-ascii letter since since it never appears
85    in instructions.  */
86 #define LONG_DOUBLE_MNEM_SUFFIX '\1'
87
88 #define END_OF_INSN '\0'
89
90 /*
91   'templates' is for grouping together 'template' structures for opcodes
92   of the same name.  This is only used for storing the insns in the grand
93   ole hash table of insns.
94   The templates themselves start at START and range up to (but not including)
95   END.
96   */
97 typedef struct
98 {
99   const insn_template *start;
100   const insn_template *end;
101 }
102 templates;
103
104 /* 386 operand encoding bytes:  see 386 book for details of this.  */
105 typedef struct
106 {
107   unsigned int regmem;  /* codes register or memory operand */
108   unsigned int reg;     /* codes register operand (or extended opcode) */
109   unsigned int mode;    /* how to interpret regmem & reg */
110 }
111 modrm_byte;
112
113 /* x86-64 extension prefix.  */
114 typedef int rex_byte;
115
116 /* 386 opcode byte to code indirect addressing.  */
117 typedef struct
118 {
119   unsigned base;
120   unsigned index;
121   unsigned scale;
122 }
123 sib_byte;
124
125 /* x86 arch names, types and features */
126 typedef struct
127 {
128   const char *name;             /* arch name */
129   unsigned int len;             /* arch string length */
130   enum processor_type type;     /* arch type */
131   i386_cpu_flags flags;         /* cpu feature flags */
132   unsigned int skip;            /* show_arch should skip this. */
133 }
134 arch_entry;
135
136 /* Used to turn off indicated flags.  */
137 typedef struct
138 {
139   const char *name;             /* arch name */
140   unsigned int len;             /* arch string length */
141   i386_cpu_flags flags;         /* cpu feature flags */
142 }
143 noarch_entry;
144
145 static void update_code_flag (int, int);
146 static void set_code_flag (int);
147 static void set_16bit_gcc_code_flag (int);
148 static void set_intel_syntax (int);
149 static void set_intel_mnemonic (int);
150 static void set_allow_index_reg (int);
151 static void set_check (int);
152 static void set_cpu_arch (int);
153 #ifdef TE_PE
154 static void pe_directive_secrel (int);
155 #endif
156 static void signed_cons (int);
157 static char *output_invalid (int c);
158 static int i386_finalize_immediate (segT, expressionS *, i386_operand_type,
159                                     const char *);
160 static int i386_finalize_displacement (segT, expressionS *, i386_operand_type,
161                                        const char *);
162 static int i386_att_operand (char *);
163 static int i386_intel_operand (char *, int);
164 static int i386_intel_simplify (expressionS *);
165 static int i386_intel_parse_name (const char *, expressionS *);
166 static const reg_entry *parse_register (char *, char **);
167 static char *parse_insn (char *, char *);
168 static char *parse_operands (char *, const char *);
169 static void swap_operands (void);
170 static void swap_2_operands (int, int);
171 static void optimize_imm (void);
172 static void optimize_disp (void);
173 static const insn_template *match_template (char);
174 static int check_string (void);
175 static int process_suffix (void);
176 static int check_byte_reg (void);
177 static int check_long_reg (void);
178 static int check_qword_reg (void);
179 static int check_word_reg (void);
180 static int finalize_imm (void);
181 static int process_operands (void);
182 static const seg_entry *build_modrm_byte (void);
183 static void output_insn (void);
184 static void output_imm (fragS *, offsetT);
185 static void output_disp (fragS *, offsetT);
186 #ifndef I386COFF
187 static void s_bss (int);
188 #endif
189 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
190 static void handle_large_common (int small ATTRIBUTE_UNUSED);
191 #endif
192
193 static const char *default_arch = DEFAULT_ARCH;
194
195 /* This struct describes rounding control and SAE in the instruction.  */
196 struct RC_Operation
197 {
198   enum rc_type
199     {
200       rne = 0,
201       rd,
202       ru,
203       rz,
204       saeonly
205     } type;
206   int operand;
207 };
208
209 static struct RC_Operation rc_op;
210
211 /* The struct describes masking, applied to OPERAND in the instruction.
212    MASK is a pointer to the corresponding mask register.  ZEROING tells
213    whether merging or zeroing mask is used.  */
214 struct Mask_Operation
215 {
216   const reg_entry *mask;
217   unsigned int zeroing;
218   /* The operand where this operation is associated.  */
219   int operand;
220 };
221
222 static struct Mask_Operation mask_op;
223
224 /* The struct describes broadcasting, applied to OPERAND.  FACTOR is
225    broadcast factor.  */
226 struct Broadcast_Operation
227 {
228   /* Type of broadcast: no broadcast, {1to8}, or {1to16}.  */
229   int type;
230
231   /* Index of broadcasted operand.  */
232   int operand;
233 };
234
235 static struct Broadcast_Operation broadcast_op;
236
237 /* VEX prefix.  */
238 typedef struct
239 {
240   /* VEX prefix is either 2 byte or 3 byte.  EVEX is 4 byte.  */
241   unsigned char bytes[4];
242   unsigned int length;
243   /* Destination or source register specifier.  */
244   const reg_entry *register_specifier;
245 } vex_prefix;
246
247 /* 'md_assemble ()' gathers together information and puts it into a
248    i386_insn.  */
249
250 union i386_op
251   {
252     expressionS *disps;
253     expressionS *imms;
254     const reg_entry *regs;
255   };
256
257 enum i386_error
258   {
259     operand_size_mismatch,
260     operand_type_mismatch,
261     register_type_mismatch,
262     number_of_operands_mismatch,
263     invalid_instruction_suffix,
264     bad_imm4,
265     unsupported_with_intel_mnemonic,
266     unsupported_syntax,
267     unsupported,
268     invalid_vsib_address,
269     invalid_vector_register_set,
270     unsupported_vector_index_register,
271     unsupported_broadcast,
272     broadcast_not_on_src_operand,
273     broadcast_needed,
274     unsupported_masking,
275     mask_not_on_destination,
276     no_default_mask,
277     unsupported_rc_sae,
278     rc_sae_operand_not_last_imm,
279     invalid_register_operand,
280   };
281
282 struct _i386_insn
283   {
284     /* TM holds the template for the insn were currently assembling.  */
285     insn_template tm;
286
287     /* SUFFIX holds the instruction size suffix for byte, word, dword
288        or qword, if given.  */
289     char suffix;
290
291     /* OPERANDS gives the number of given operands.  */
292     unsigned int operands;
293
294     /* REG_OPERANDS, DISP_OPERANDS, MEM_OPERANDS, IMM_OPERANDS give the number
295        of given register, displacement, memory operands and immediate
296        operands.  */
297     unsigned int reg_operands, disp_operands, mem_operands, imm_operands;
298
299     /* TYPES [i] is the type (see above #defines) which tells us how to
300        use OP[i] for the corresponding operand.  */
301     i386_operand_type types[MAX_OPERANDS];
302
303     /* Displacement expression, immediate expression, or register for each
304        operand.  */
305     union i386_op op[MAX_OPERANDS];
306
307     /* Flags for operands.  */
308     unsigned int flags[MAX_OPERANDS];
309 #define Operand_PCrel 1
310
311     /* Relocation type for operand */
312     enum bfd_reloc_code_real reloc[MAX_OPERANDS];
313
314     /* BASE_REG, INDEX_REG, and LOG2_SCALE_FACTOR are used to encode
315        the base index byte below.  */
316     const reg_entry *base_reg;
317     const reg_entry *index_reg;
318     unsigned int log2_scale_factor;
319
320     /* SEG gives the seg_entries of this insn.  They are zero unless
321        explicit segment overrides are given.  */
322     const seg_entry *seg[2];
323
324     /* Copied first memory operand string, for re-checking.  */
325     char *memop1_string;
326
327     /* PREFIX holds all the given prefix opcodes (usually null).
328        PREFIXES is the number of prefix opcodes.  */
329     unsigned int prefixes;
330     unsigned char prefix[MAX_PREFIXES];
331
332     /* RM and SIB are the modrm byte and the sib byte where the
333        addressing modes of this insn are encoded.  */
334     modrm_byte rm;
335     rex_byte rex;
336     rex_byte vrex;
337     sib_byte sib;
338     vex_prefix vex;
339
340     /* Masking attributes.  */
341     struct Mask_Operation *mask;
342
343     /* Rounding control and SAE attributes.  */
344     struct RC_Operation *rounding;
345
346     /* Broadcasting attributes.  */
347     struct Broadcast_Operation *broadcast;
348
349     /* Compressed disp8*N attribute.  */
350     unsigned int memshift;
351
352     /* Prefer load or store in encoding.  */
353     enum
354       {
355         dir_encoding_default = 0,
356         dir_encoding_load,
357         dir_encoding_store
358       } dir_encoding;
359
360     /* Prefer 8bit or 32bit displacement in encoding.  */
361     enum
362       {
363         disp_encoding_default = 0,
364         disp_encoding_8bit,
365         disp_encoding_32bit
366       } disp_encoding;
367
368     /* Prefer the REX byte in encoding.  */
369     bfd_boolean rex_encoding;
370
371     /* Disable instruction size optimization.  */
372     bfd_boolean no_optimize;
373
374     /* How to encode vector instructions.  */
375     enum
376       {
377         vex_encoding_default = 0,
378         vex_encoding_vex2,
379         vex_encoding_vex3,
380         vex_encoding_evex
381       } vec_encoding;
382
383     /* REP prefix.  */
384     const char *rep_prefix;
385
386     /* HLE prefix.  */
387     const char *hle_prefix;
388
389     /* Have BND prefix.  */
390     const char *bnd_prefix;
391
392     /* Have NOTRACK prefix.  */
393     const char *notrack_prefix;
394
395     /* Error message.  */
396     enum i386_error error;
397   };
398
399 typedef struct _i386_insn i386_insn;
400
401 /* Link RC type with corresponding string, that'll be looked for in
402    asm.  */
403 struct RC_name
404 {
405   enum rc_type type;
406   const char *name;
407   unsigned int len;
408 };
409
410 static const struct RC_name RC_NamesTable[] =
411 {
412   {  rne, STRING_COMMA_LEN ("rn-sae") },
413   {  rd,  STRING_COMMA_LEN ("rd-sae") },
414   {  ru,  STRING_COMMA_LEN ("ru-sae") },
415   {  rz,  STRING_COMMA_LEN ("rz-sae") },
416   {  saeonly,  STRING_COMMA_LEN ("sae") },
417 };
418
419 /* List of chars besides those in app.c:symbol_chars that can start an
420    operand.  Used to prevent the scrubber eating vital white-space.  */
421 const char extra_symbol_chars[] = "*%-([{}"
422 #ifdef LEX_AT
423         "@"
424 #endif
425 #ifdef LEX_QM
426         "?"
427 #endif
428         ;
429
430 #if (defined (TE_I386AIX)                               \
431      || ((defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)) \
432          && !defined (TE_GNU)                           \
433          && !defined (TE_LINUX)                         \
434          && !defined (TE_NACL)                          \
435          && !defined (TE_NETWARE)                       \
436          && !defined (TE_FreeBSD)                       \
437          && !defined (TE_DragonFly)                     \
438          && !defined (TE_NetBSD)))
439 /* This array holds the chars that always start a comment.  If the
440    pre-processor is disabled, these aren't very useful.  The option
441    --divide will remove '/' from this list.  */
442 const char *i386_comment_chars = "#/";
443 #define SVR4_COMMENT_CHARS 1
444 #define PREFIX_SEPARATOR '\\'
445
446 #else
447 const char *i386_comment_chars = "#";
448 #define PREFIX_SEPARATOR '/'
449 #endif
450
451 /* This array holds the chars that only start a comment at the beginning of
452    a line.  If the line seems to have the form '# 123 filename'
453    .line and .file directives will appear in the pre-processed output.
454    Note that input_file.c hand checks for '#' at the beginning of the
455    first line of the input file.  This is because the compiler outputs
456    #NO_APP at the beginning of its output.
457    Also note that comments started like this one will always work if
458    '/' isn't otherwise defined.  */
459 const char line_comment_chars[] = "#/";
460
461 const char line_separator_chars[] = ";";
462
463 /* Chars that can be used to separate mant from exp in floating point
464    nums.  */
465 const char EXP_CHARS[] = "eE";
466
467 /* Chars that mean this number is a floating point constant
468    As in 0f12.456
469    or    0d1.2345e12.  */
470 const char FLT_CHARS[] = "fFdDxX";
471
472 /* Tables for lexical analysis.  */
473 static char mnemonic_chars[256];
474 static char register_chars[256];
475 static char operand_chars[256];
476 static char identifier_chars[256];
477 static char digit_chars[256];
478
479 /* Lexical macros.  */
480 #define is_mnemonic_char(x) (mnemonic_chars[(unsigned char) x])
481 #define is_operand_char(x) (operand_chars[(unsigned char) x])
482 #define is_register_char(x) (register_chars[(unsigned char) x])
483 #define is_space_char(x) ((x) == ' ')
484 #define is_identifier_char(x) (identifier_chars[(unsigned char) x])
485 #define is_digit_char(x) (digit_chars[(unsigned char) x])
486
487 /* All non-digit non-letter characters that may occur in an operand.  */
488 static char operand_special_chars[] = "%$-+(,)*._~/<>|&^!:[@]";
489
490 /* md_assemble() always leaves the strings it's passed unaltered.  To
491    effect this we maintain a stack of saved characters that we've smashed
492    with '\0's (indicating end of strings for various sub-fields of the
493    assembler instruction).  */
494 static char save_stack[32];
495 static char *save_stack_p;
496 #define END_STRING_AND_SAVE(s) \
497         do { *save_stack_p++ = *(s); *(s) = '\0'; } while (0)
498 #define RESTORE_END_STRING(s) \
499         do { *(s) = *--save_stack_p; } while (0)
500
501 /* The instruction we're assembling.  */
502 static i386_insn i;
503
504 /* Possible templates for current insn.  */
505 static const templates *current_templates;
506
507 /* Per instruction expressionS buffers: max displacements & immediates.  */
508 static expressionS disp_expressions[MAX_MEMORY_OPERANDS];
509 static expressionS im_expressions[MAX_IMMEDIATE_OPERANDS];
510
511 /* Current operand we are working on.  */
512 static int this_operand = -1;
513
514 /* We support four different modes.  FLAG_CODE variable is used to distinguish
515    these.  */
516
517 enum flag_code {
518         CODE_32BIT,
519         CODE_16BIT,
520         CODE_64BIT };
521
522 static enum flag_code flag_code;
523 static unsigned int object_64bit;
524 static unsigned int disallow_64bit_reloc;
525 static int use_rela_relocations = 0;
526
527 #if ((defined (OBJ_MAYBE_COFF) && defined (OBJ_MAYBE_AOUT)) \
528      || defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) \
529      || defined (TE_PE) || defined (TE_PEP) || defined (OBJ_MACH_O))
530
531 /* The ELF ABI to use.  */
532 enum x86_elf_abi
533 {
534   I386_ABI,
535   X86_64_ABI,
536   X86_64_X32_ABI
537 };
538
539 static enum x86_elf_abi x86_elf_abi = I386_ABI;
540 #endif
541
542 #if defined (TE_PE) || defined (TE_PEP)
543 /* Use big object file format.  */
544 static int use_big_obj = 0;
545 #endif
546
547 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
548 /* 1 if generating code for a shared library.  */
549 static int shared = 0;
550 #endif
551
552 /* 1 for intel syntax,
553    0 if att syntax.  */
554 static int intel_syntax = 0;
555
556 /* 1 for Intel64 ISA,
557    0 if AMD64 ISA.  */
558 static int intel64;
559
560 /* 1 for intel mnemonic,
561    0 if att mnemonic.  */
562 static int intel_mnemonic = !SYSV386_COMPAT;
563
564 /* 1 if pseudo registers are permitted.  */
565 static int allow_pseudo_reg = 0;
566
567 /* 1 if register prefix % not required.  */
568 static int allow_naked_reg = 0;
569
570 /* 1 if the assembler should add BND prefix for all control-transferring
571    instructions supporting it, even if this prefix wasn't specified
572    explicitly.  */
573 static int add_bnd_prefix = 0;
574
575 /* 1 if pseudo index register, eiz/riz, is allowed .  */
576 static int allow_index_reg = 0;
577
578 /* 1 if the assembler should ignore LOCK prefix, even if it was
579    specified explicitly.  */
580 static int omit_lock_prefix = 0;
581
582 /* 1 if the assembler should encode lfence, mfence, and sfence as
583    "lock addl $0, (%{re}sp)".  */
584 static int avoid_fence = 0;
585
586 /* 1 if the assembler should generate relax relocations.  */
587
588 static int generate_relax_relocations
589   = DEFAULT_GENERATE_X86_RELAX_RELOCATIONS;
590
591 static enum check_kind
592   {
593     check_none = 0,
594     check_warning,
595     check_error
596   }
597 sse_check, operand_check = check_warning;
598
599 /* Optimization:
600    1. Clear the REX_W bit with register operand if possible.
601    2. Above plus use 128bit vector instruction to clear the full vector
602       register.
603  */
604 static int optimize = 0;
605
606 /* Optimization:
607    1. Clear the REX_W bit with register operand if possible.
608    2. Above plus use 128bit vector instruction to clear the full vector
609       register.
610    3. Above plus optimize "test{q,l,w} $imm8,%r{64,32,16}" to
611       "testb $imm7,%r8".
612  */
613 static int optimize_for_space = 0;
614
615 /* Register prefix used for error message.  */
616 static const char *register_prefix = "%";
617
618 /* Used in 16 bit gcc mode to add an l suffix to call, ret, enter,
619    leave, push, and pop instructions so that gcc has the same stack
620    frame as in 32 bit mode.  */
621 static char stackop_size = '\0';
622
623 /* Non-zero to optimize code alignment.  */
624 int optimize_align_code = 1;
625
626 /* Non-zero to quieten some warnings.  */
627 static int quiet_warnings = 0;
628
629 /* CPU name.  */
630 static const char *cpu_arch_name = NULL;
631 static char *cpu_sub_arch_name = NULL;
632
633 /* CPU feature flags.  */
634 static i386_cpu_flags cpu_arch_flags = CPU_UNKNOWN_FLAGS;
635
636 /* If we have selected a cpu we are generating instructions for.  */
637 static int cpu_arch_tune_set = 0;
638
639 /* Cpu we are generating instructions for.  */
640 enum processor_type cpu_arch_tune = PROCESSOR_UNKNOWN;
641
642 /* CPU feature flags of cpu we are generating instructions for.  */
643 static i386_cpu_flags cpu_arch_tune_flags;
644
645 /* CPU instruction set architecture used.  */
646 enum processor_type cpu_arch_isa = PROCESSOR_UNKNOWN;
647
648 /* CPU feature flags of instruction set architecture used.  */
649 i386_cpu_flags cpu_arch_isa_flags;
650
651 /* If set, conditional jumps are not automatically promoted to handle
652    larger than a byte offset.  */
653 static unsigned int no_cond_jump_promotion = 0;
654
655 /* Encode SSE instructions with VEX prefix.  */
656 static unsigned int sse2avx;
657
658 /* Encode scalar AVX instructions with specific vector length.  */
659 static enum
660   {
661     vex128 = 0,
662     vex256
663   } avxscalar;
664
665 /* Encode scalar EVEX LIG instructions with specific vector length.  */
666 static enum
667   {
668     evexl128 = 0,
669     evexl256,
670     evexl512
671   } evexlig;
672
673 /* Encode EVEX WIG instructions with specific evex.w.  */
674 static enum
675   {
676     evexw0 = 0,
677     evexw1
678   } evexwig;
679
680 /* Value to encode in EVEX RC bits, for SAE-only instructions.  */
681 static enum rc_type evexrcig = rne;
682
683 /* Pre-defined "_GLOBAL_OFFSET_TABLE_".  */
684 static symbolS *GOT_symbol;
685
686 /* The dwarf2 return column, adjusted for 32 or 64 bit.  */
687 unsigned int x86_dwarf2_return_column;
688
689 /* The dwarf2 data alignment, adjusted for 32 or 64 bit.  */
690 int x86_cie_data_alignment;
691
692 /* Interface to relax_segment.
693    There are 3 major relax states for 386 jump insns because the
694    different types of jumps add different sizes to frags when we're
695    figuring out what sort of jump to choose to reach a given label.  */
696
697 /* Types.  */
698 #define UNCOND_JUMP 0
699 #define COND_JUMP 1
700 #define COND_JUMP86 2
701
702 /* Sizes.  */
703 #define CODE16  1
704 #define SMALL   0
705 #define SMALL16 (SMALL | CODE16)
706 #define BIG     2
707 #define BIG16   (BIG | CODE16)
708
709 #ifndef INLINE
710 #ifdef __GNUC__
711 #define INLINE __inline__
712 #else
713 #define INLINE
714 #endif
715 #endif
716
717 #define ENCODE_RELAX_STATE(type, size) \
718   ((relax_substateT) (((type) << 2) | (size)))
719 #define TYPE_FROM_RELAX_STATE(s) \
720   ((s) >> 2)
721 #define DISP_SIZE_FROM_RELAX_STATE(s) \
722     ((((s) & 3) == BIG ? 4 : (((s) & 3) == BIG16 ? 2 : 1)))
723
724 /* This table is used by relax_frag to promote short jumps to long
725    ones where necessary.  SMALL (short) jumps may be promoted to BIG
726    (32 bit long) ones, and SMALL16 jumps to BIG16 (16 bit long).  We
727    don't allow a short jump in a 32 bit code segment to be promoted to
728    a 16 bit offset jump because it's slower (requires data size
729    prefix), and doesn't work, unless the destination is in the bottom
730    64k of the code segment (The top 16 bits of eip are zeroed).  */
731
732 const relax_typeS md_relax_table[] =
733 {
734   /* The fields are:
735      1) most positive reach of this state,
736      2) most negative reach of this state,
737      3) how many bytes this mode will have in the variable part of the frag
738      4) which index into the table to try if we can't fit into this one.  */
739
740   /* UNCOND_JUMP states.  */
741   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (UNCOND_JUMP, BIG)},
742   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (UNCOND_JUMP, BIG16)},
743   /* dword jmp adds 4 bytes to frag:
744      0 extra opcode bytes, 4 displacement bytes.  */
745   {0, 0, 4, 0},
746   /* word jmp adds 2 byte2 to frag:
747      0 extra opcode bytes, 2 displacement bytes.  */
748   {0, 0, 2, 0},
749
750   /* COND_JUMP states.  */
751   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP, BIG)},
752   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP, BIG16)},
753   /* dword conditionals adds 5 bytes to frag:
754      1 extra opcode byte, 4 displacement bytes.  */
755   {0, 0, 5, 0},
756   /* word conditionals add 3 bytes to frag:
757      1 extra opcode byte, 2 displacement bytes.  */
758   {0, 0, 3, 0},
759
760   /* COND_JUMP86 states.  */
761   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP86, BIG)},
762   {127 + 1, -128 + 1, 1, ENCODE_RELAX_STATE (COND_JUMP86, BIG16)},
763   /* dword conditionals adds 5 bytes to frag:
764      1 extra opcode byte, 4 displacement bytes.  */
765   {0, 0, 5, 0},
766   /* word conditionals add 4 bytes to frag:
767      1 displacement byte and a 3 byte long branch insn.  */
768   {0, 0, 4, 0}
769 };
770
771 static const arch_entry cpu_arch[] =
772 {
773   /* Do not replace the first two entries - i386_target_format()
774      relies on them being there in this order.  */
775   { STRING_COMMA_LEN ("generic32"), PROCESSOR_GENERIC32,
776     CPU_GENERIC32_FLAGS, 0 },
777   { STRING_COMMA_LEN ("generic64"), PROCESSOR_GENERIC64,
778     CPU_GENERIC64_FLAGS, 0 },
779   { STRING_COMMA_LEN ("i8086"), PROCESSOR_UNKNOWN,
780     CPU_NONE_FLAGS, 0 },
781   { STRING_COMMA_LEN ("i186"), PROCESSOR_UNKNOWN,
782     CPU_I186_FLAGS, 0 },
783   { STRING_COMMA_LEN ("i286"), PROCESSOR_UNKNOWN,
784     CPU_I286_FLAGS, 0 },
785   { STRING_COMMA_LEN ("i386"), PROCESSOR_I386,
786     CPU_I386_FLAGS, 0 },
787   { STRING_COMMA_LEN ("i486"), PROCESSOR_I486,
788     CPU_I486_FLAGS, 0 },
789   { STRING_COMMA_LEN ("i586"), PROCESSOR_PENTIUM,
790     CPU_I586_FLAGS, 0 },
791   { STRING_COMMA_LEN ("i686"), PROCESSOR_PENTIUMPRO,
792     CPU_I686_FLAGS, 0 },
793   { STRING_COMMA_LEN ("pentium"), PROCESSOR_PENTIUM,
794     CPU_I586_FLAGS, 0 },
795   { STRING_COMMA_LEN ("pentiumpro"), PROCESSOR_PENTIUMPRO,
796     CPU_PENTIUMPRO_FLAGS, 0 },
797   { STRING_COMMA_LEN ("pentiumii"), PROCESSOR_PENTIUMPRO,
798     CPU_P2_FLAGS, 0 },
799   { STRING_COMMA_LEN ("pentiumiii"),PROCESSOR_PENTIUMPRO,
800     CPU_P3_FLAGS, 0 },
801   { STRING_COMMA_LEN ("pentium4"), PROCESSOR_PENTIUM4,
802     CPU_P4_FLAGS, 0 },
803   { STRING_COMMA_LEN ("prescott"), PROCESSOR_NOCONA,
804     CPU_CORE_FLAGS, 0 },
805   { STRING_COMMA_LEN ("nocona"), PROCESSOR_NOCONA,
806     CPU_NOCONA_FLAGS, 0 },
807   { STRING_COMMA_LEN ("yonah"), PROCESSOR_CORE,
808     CPU_CORE_FLAGS, 1 },
809   { STRING_COMMA_LEN ("core"), PROCESSOR_CORE,
810     CPU_CORE_FLAGS, 0 },
811   { STRING_COMMA_LEN ("merom"), PROCESSOR_CORE2,
812     CPU_CORE2_FLAGS, 1 },
813   { STRING_COMMA_LEN ("core2"), PROCESSOR_CORE2,
814     CPU_CORE2_FLAGS, 0 },
815   { STRING_COMMA_LEN ("corei7"), PROCESSOR_COREI7,
816     CPU_COREI7_FLAGS, 0 },
817   { STRING_COMMA_LEN ("l1om"), PROCESSOR_L1OM,
818     CPU_L1OM_FLAGS, 0 },
819   { STRING_COMMA_LEN ("k1om"), PROCESSOR_K1OM,
820     CPU_K1OM_FLAGS, 0 },
821   { STRING_COMMA_LEN ("iamcu"), PROCESSOR_IAMCU,
822     CPU_IAMCU_FLAGS, 0 },
823   { STRING_COMMA_LEN ("k6"), PROCESSOR_K6,
824     CPU_K6_FLAGS, 0 },
825   { STRING_COMMA_LEN ("k6_2"), PROCESSOR_K6,
826     CPU_K6_2_FLAGS, 0 },
827   { STRING_COMMA_LEN ("athlon"), PROCESSOR_ATHLON,
828     CPU_ATHLON_FLAGS, 0 },
829   { STRING_COMMA_LEN ("sledgehammer"), PROCESSOR_K8,
830     CPU_K8_FLAGS, 1 },
831   { STRING_COMMA_LEN ("opteron"), PROCESSOR_K8,
832     CPU_K8_FLAGS, 0 },
833   { STRING_COMMA_LEN ("k8"), PROCESSOR_K8,
834     CPU_K8_FLAGS, 0 },
835   { STRING_COMMA_LEN ("amdfam10"), PROCESSOR_AMDFAM10,
836     CPU_AMDFAM10_FLAGS, 0 },
837   { STRING_COMMA_LEN ("bdver1"), PROCESSOR_BD,
838     CPU_BDVER1_FLAGS, 0 },
839   { STRING_COMMA_LEN ("bdver2"), PROCESSOR_BD,
840     CPU_BDVER2_FLAGS, 0 },
841   { STRING_COMMA_LEN ("bdver3"), PROCESSOR_BD,
842     CPU_BDVER3_FLAGS, 0 },
843   { STRING_COMMA_LEN ("bdver4"), PROCESSOR_BD,
844     CPU_BDVER4_FLAGS, 0 },
845   { STRING_COMMA_LEN ("znver1"), PROCESSOR_ZNVER,
846     CPU_ZNVER1_FLAGS, 0 },
847   { STRING_COMMA_LEN ("btver1"), PROCESSOR_BT,
848     CPU_BTVER1_FLAGS, 0 },
849   { STRING_COMMA_LEN ("btver2"), PROCESSOR_BT,
850     CPU_BTVER2_FLAGS, 0 },
851   { STRING_COMMA_LEN (".8087"), PROCESSOR_UNKNOWN,
852     CPU_8087_FLAGS, 0 },
853   { STRING_COMMA_LEN (".287"), PROCESSOR_UNKNOWN,
854     CPU_287_FLAGS, 0 },
855   { STRING_COMMA_LEN (".387"), PROCESSOR_UNKNOWN,
856     CPU_387_FLAGS, 0 },
857   { STRING_COMMA_LEN (".687"), PROCESSOR_UNKNOWN,
858     CPU_687_FLAGS, 0 },
859   { STRING_COMMA_LEN (".mmx"), PROCESSOR_UNKNOWN,
860     CPU_MMX_FLAGS, 0 },
861   { STRING_COMMA_LEN (".sse"), PROCESSOR_UNKNOWN,
862     CPU_SSE_FLAGS, 0 },
863   { STRING_COMMA_LEN (".sse2"), PROCESSOR_UNKNOWN,
864     CPU_SSE2_FLAGS, 0 },
865   { STRING_COMMA_LEN (".sse3"), PROCESSOR_UNKNOWN,
866     CPU_SSE3_FLAGS, 0 },
867   { STRING_COMMA_LEN (".ssse3"), PROCESSOR_UNKNOWN,
868     CPU_SSSE3_FLAGS, 0 },
869   { STRING_COMMA_LEN (".sse4.1"), PROCESSOR_UNKNOWN,
870     CPU_SSE4_1_FLAGS, 0 },
871   { STRING_COMMA_LEN (".sse4.2"), PROCESSOR_UNKNOWN,
872     CPU_SSE4_2_FLAGS, 0 },
873   { STRING_COMMA_LEN (".sse4"), PROCESSOR_UNKNOWN,
874     CPU_SSE4_2_FLAGS, 0 },
875   { STRING_COMMA_LEN (".avx"), PROCESSOR_UNKNOWN,
876     CPU_AVX_FLAGS, 0 },
877   { STRING_COMMA_LEN (".avx2"), PROCESSOR_UNKNOWN,
878     CPU_AVX2_FLAGS, 0 },
879   { STRING_COMMA_LEN (".avx512f"), PROCESSOR_UNKNOWN,
880     CPU_AVX512F_FLAGS, 0 },
881   { STRING_COMMA_LEN (".avx512cd"), PROCESSOR_UNKNOWN,
882     CPU_AVX512CD_FLAGS, 0 },
883   { STRING_COMMA_LEN (".avx512er"), PROCESSOR_UNKNOWN,
884     CPU_AVX512ER_FLAGS, 0 },
885   { STRING_COMMA_LEN (".avx512pf"), PROCESSOR_UNKNOWN,
886     CPU_AVX512PF_FLAGS, 0 },
887   { STRING_COMMA_LEN (".avx512dq"), PROCESSOR_UNKNOWN,
888     CPU_AVX512DQ_FLAGS, 0 },
889   { STRING_COMMA_LEN (".avx512bw"), PROCESSOR_UNKNOWN,
890     CPU_AVX512BW_FLAGS, 0 },
891   { STRING_COMMA_LEN (".avx512vl"), PROCESSOR_UNKNOWN,
892     CPU_AVX512VL_FLAGS, 0 },
893   { STRING_COMMA_LEN (".vmx"), PROCESSOR_UNKNOWN,
894     CPU_VMX_FLAGS, 0 },
895   { STRING_COMMA_LEN (".vmfunc"), PROCESSOR_UNKNOWN,
896     CPU_VMFUNC_FLAGS, 0 },
897   { STRING_COMMA_LEN (".smx"), PROCESSOR_UNKNOWN,
898     CPU_SMX_FLAGS, 0 },
899   { STRING_COMMA_LEN (".xsave"), PROCESSOR_UNKNOWN,
900     CPU_XSAVE_FLAGS, 0 },
901   { STRING_COMMA_LEN (".xsaveopt"), PROCESSOR_UNKNOWN,
902     CPU_XSAVEOPT_FLAGS, 0 },
903   { STRING_COMMA_LEN (".xsavec"), PROCESSOR_UNKNOWN,
904     CPU_XSAVEC_FLAGS, 0 },
905   { STRING_COMMA_LEN (".xsaves"), PROCESSOR_UNKNOWN,
906     CPU_XSAVES_FLAGS, 0 },
907   { STRING_COMMA_LEN (".aes"), PROCESSOR_UNKNOWN,
908     CPU_AES_FLAGS, 0 },
909   { STRING_COMMA_LEN (".pclmul"), PROCESSOR_UNKNOWN,
910     CPU_PCLMUL_FLAGS, 0 },
911   { STRING_COMMA_LEN (".clmul"), PROCESSOR_UNKNOWN,
912     CPU_PCLMUL_FLAGS, 1 },
913   { STRING_COMMA_LEN (".fsgsbase"), PROCESSOR_UNKNOWN,
914     CPU_FSGSBASE_FLAGS, 0 },
915   { STRING_COMMA_LEN (".rdrnd"), PROCESSOR_UNKNOWN,
916     CPU_RDRND_FLAGS, 0 },
917   { STRING_COMMA_LEN (".f16c"), PROCESSOR_UNKNOWN,
918     CPU_F16C_FLAGS, 0 },
919   { STRING_COMMA_LEN (".bmi2"), PROCESSOR_UNKNOWN,
920     CPU_BMI2_FLAGS, 0 },
921   { STRING_COMMA_LEN (".fma"), PROCESSOR_UNKNOWN,
922     CPU_FMA_FLAGS, 0 },
923   { STRING_COMMA_LEN (".fma4"), PROCESSOR_UNKNOWN,
924     CPU_FMA4_FLAGS, 0 },
925   { STRING_COMMA_LEN (".xop"), PROCESSOR_UNKNOWN,
926     CPU_XOP_FLAGS, 0 },
927   { STRING_COMMA_LEN (".lwp"), PROCESSOR_UNKNOWN,
928     CPU_LWP_FLAGS, 0 },
929   { STRING_COMMA_LEN (".movbe"), PROCESSOR_UNKNOWN,
930     CPU_MOVBE_FLAGS, 0 },
931   { STRING_COMMA_LEN (".cx16"), PROCESSOR_UNKNOWN,
932     CPU_CX16_FLAGS, 0 },
933   { STRING_COMMA_LEN (".ept"), PROCESSOR_UNKNOWN,
934     CPU_EPT_FLAGS, 0 },
935   { STRING_COMMA_LEN (".lzcnt"), PROCESSOR_UNKNOWN,
936     CPU_LZCNT_FLAGS, 0 },
937   { STRING_COMMA_LEN (".hle"), PROCESSOR_UNKNOWN,
938     CPU_HLE_FLAGS, 0 },
939   { STRING_COMMA_LEN (".rtm"), PROCESSOR_UNKNOWN,
940     CPU_RTM_FLAGS, 0 },
941   { STRING_COMMA_LEN (".invpcid"), PROCESSOR_UNKNOWN,
942     CPU_INVPCID_FLAGS, 0 },
943   { STRING_COMMA_LEN (".clflush"), PROCESSOR_UNKNOWN,
944     CPU_CLFLUSH_FLAGS, 0 },
945   { STRING_COMMA_LEN (".nop"), PROCESSOR_UNKNOWN,
946     CPU_NOP_FLAGS, 0 },
947   { STRING_COMMA_LEN (".syscall"), PROCESSOR_UNKNOWN,
948     CPU_SYSCALL_FLAGS, 0 },
949   { STRING_COMMA_LEN (".rdtscp"), PROCESSOR_UNKNOWN,
950     CPU_RDTSCP_FLAGS, 0 },
951   { STRING_COMMA_LEN (".3dnow"), PROCESSOR_UNKNOWN,
952     CPU_3DNOW_FLAGS, 0 },
953   { STRING_COMMA_LEN (".3dnowa"), PROCESSOR_UNKNOWN,
954     CPU_3DNOWA_FLAGS, 0 },
955   { STRING_COMMA_LEN (".padlock"), PROCESSOR_UNKNOWN,
956     CPU_PADLOCK_FLAGS, 0 },
957   { STRING_COMMA_LEN (".pacifica"), PROCESSOR_UNKNOWN,
958     CPU_SVME_FLAGS, 1 },
959   { STRING_COMMA_LEN (".svme"), PROCESSOR_UNKNOWN,
960     CPU_SVME_FLAGS, 0 },
961   { STRING_COMMA_LEN (".sse4a"), PROCESSOR_UNKNOWN,
962     CPU_SSE4A_FLAGS, 0 },
963   { STRING_COMMA_LEN (".abm"), PROCESSOR_UNKNOWN,
964     CPU_ABM_FLAGS, 0 },
965   { STRING_COMMA_LEN (".bmi"), PROCESSOR_UNKNOWN,
966     CPU_BMI_FLAGS, 0 },
967   { STRING_COMMA_LEN (".tbm"), PROCESSOR_UNKNOWN,
968     CPU_TBM_FLAGS, 0 },
969   { STRING_COMMA_LEN (".adx"), PROCESSOR_UNKNOWN,
970     CPU_ADX_FLAGS, 0 },
971   { STRING_COMMA_LEN (".rdseed"), PROCESSOR_UNKNOWN,
972     CPU_RDSEED_FLAGS, 0 },
973   { STRING_COMMA_LEN (".prfchw"), PROCESSOR_UNKNOWN,
974     CPU_PRFCHW_FLAGS, 0 },
975   { STRING_COMMA_LEN (".smap"), PROCESSOR_UNKNOWN,
976     CPU_SMAP_FLAGS, 0 },
977   { STRING_COMMA_LEN (".mpx"), PROCESSOR_UNKNOWN,
978     CPU_MPX_FLAGS, 0 },
979   { STRING_COMMA_LEN (".sha"), PROCESSOR_UNKNOWN,
980     CPU_SHA_FLAGS, 0 },
981   { STRING_COMMA_LEN (".clflushopt"), PROCESSOR_UNKNOWN,
982     CPU_CLFLUSHOPT_FLAGS, 0 },
983   { STRING_COMMA_LEN (".prefetchwt1"), PROCESSOR_UNKNOWN,
984     CPU_PREFETCHWT1_FLAGS, 0 },
985   { STRING_COMMA_LEN (".se1"), PROCESSOR_UNKNOWN,
986     CPU_SE1_FLAGS, 0 },
987   { STRING_COMMA_LEN (".clwb"), PROCESSOR_UNKNOWN,
988     CPU_CLWB_FLAGS, 0 },
989   { STRING_COMMA_LEN (".avx512ifma"), PROCESSOR_UNKNOWN,
990     CPU_AVX512IFMA_FLAGS, 0 },
991   { STRING_COMMA_LEN (".avx512vbmi"), PROCESSOR_UNKNOWN,
992     CPU_AVX512VBMI_FLAGS, 0 },
993   { STRING_COMMA_LEN (".avx512_4fmaps"), PROCESSOR_UNKNOWN,
994     CPU_AVX512_4FMAPS_FLAGS, 0 },
995   { STRING_COMMA_LEN (".avx512_4vnniw"), PROCESSOR_UNKNOWN,
996     CPU_AVX512_4VNNIW_FLAGS, 0 },
997   { STRING_COMMA_LEN (".avx512_vpopcntdq"), PROCESSOR_UNKNOWN,
998     CPU_AVX512_VPOPCNTDQ_FLAGS, 0 },
999   { STRING_COMMA_LEN (".avx512_vbmi2"), PROCESSOR_UNKNOWN,
1000     CPU_AVX512_VBMI2_FLAGS, 0 },
1001   { STRING_COMMA_LEN (".avx512_vnni"), PROCESSOR_UNKNOWN,
1002     CPU_AVX512_VNNI_FLAGS, 0 },
1003   { STRING_COMMA_LEN (".avx512_bitalg"), PROCESSOR_UNKNOWN,
1004     CPU_AVX512_BITALG_FLAGS, 0 },
1005   { STRING_COMMA_LEN (".clzero"), PROCESSOR_UNKNOWN,
1006     CPU_CLZERO_FLAGS, 0 },
1007   { STRING_COMMA_LEN (".mwaitx"), PROCESSOR_UNKNOWN,
1008     CPU_MWAITX_FLAGS, 0 },
1009   { STRING_COMMA_LEN (".ospke"), PROCESSOR_UNKNOWN,
1010     CPU_OSPKE_FLAGS, 0 },
1011   { STRING_COMMA_LEN (".rdpid"), PROCESSOR_UNKNOWN,
1012     CPU_RDPID_FLAGS, 0 },
1013   { STRING_COMMA_LEN (".ptwrite"), PROCESSOR_UNKNOWN,
1014     CPU_PTWRITE_FLAGS, 0 },
1015   { STRING_COMMA_LEN (".ibt"), PROCESSOR_UNKNOWN,
1016     CPU_IBT_FLAGS, 0 },
1017   { STRING_COMMA_LEN (".shstk"), PROCESSOR_UNKNOWN,
1018     CPU_SHSTK_FLAGS, 0 },
1019   { STRING_COMMA_LEN (".gfni"), PROCESSOR_UNKNOWN,
1020     CPU_GFNI_FLAGS, 0 },
1021   { STRING_COMMA_LEN (".vaes"), PROCESSOR_UNKNOWN,
1022     CPU_VAES_FLAGS, 0 },
1023   { STRING_COMMA_LEN (".vpclmulqdq"), PROCESSOR_UNKNOWN,
1024     CPU_VPCLMULQDQ_FLAGS, 0 },
1025   { STRING_COMMA_LEN (".wbnoinvd"), PROCESSOR_UNKNOWN,
1026     CPU_WBNOINVD_FLAGS, 0 },
1027   { STRING_COMMA_LEN (".pconfig"), PROCESSOR_UNKNOWN,
1028     CPU_PCONFIG_FLAGS, 0 },
1029 };
1030
1031 static const noarch_entry cpu_noarch[] =
1032 {
1033   { STRING_COMMA_LEN ("no87"),  CPU_ANY_X87_FLAGS },
1034   { STRING_COMMA_LEN ("no287"),  CPU_ANY_287_FLAGS },
1035   { STRING_COMMA_LEN ("no387"),  CPU_ANY_387_FLAGS },
1036   { STRING_COMMA_LEN ("no687"),  CPU_ANY_687_FLAGS },
1037   { STRING_COMMA_LEN ("nommx"),  CPU_ANY_MMX_FLAGS },
1038   { STRING_COMMA_LEN ("nosse"),  CPU_ANY_SSE_FLAGS },
1039   { STRING_COMMA_LEN ("nosse2"),  CPU_ANY_SSE2_FLAGS },
1040   { STRING_COMMA_LEN ("nosse3"),  CPU_ANY_SSE3_FLAGS },
1041   { STRING_COMMA_LEN ("nossse3"),  CPU_ANY_SSSE3_FLAGS },
1042   { STRING_COMMA_LEN ("nosse4.1"),  CPU_ANY_SSE4_1_FLAGS },
1043   { STRING_COMMA_LEN ("nosse4.2"),  CPU_ANY_SSE4_2_FLAGS },
1044   { STRING_COMMA_LEN ("nosse4"),  CPU_ANY_SSE4_1_FLAGS },
1045   { STRING_COMMA_LEN ("noavx"),  CPU_ANY_AVX_FLAGS },
1046   { STRING_COMMA_LEN ("noavx2"),  CPU_ANY_AVX2_FLAGS },
1047   { STRING_COMMA_LEN ("noavx512f"), CPU_ANY_AVX512F_FLAGS },
1048   { STRING_COMMA_LEN ("noavx512cd"), CPU_ANY_AVX512CD_FLAGS },
1049   { STRING_COMMA_LEN ("noavx512er"), CPU_ANY_AVX512ER_FLAGS },
1050   { STRING_COMMA_LEN ("noavx512pf"), CPU_ANY_AVX512PF_FLAGS },
1051   { STRING_COMMA_LEN ("noavx512dq"), CPU_ANY_AVX512DQ_FLAGS },
1052   { STRING_COMMA_LEN ("noavx512bw"), CPU_ANY_AVX512BW_FLAGS },
1053   { STRING_COMMA_LEN ("noavx512vl"), CPU_ANY_AVX512VL_FLAGS },
1054   { STRING_COMMA_LEN ("noavx512ifma"), CPU_ANY_AVX512IFMA_FLAGS },
1055   { STRING_COMMA_LEN ("noavx512vbmi"), CPU_ANY_AVX512VBMI_FLAGS },
1056   { STRING_COMMA_LEN ("noavx512_4fmaps"), CPU_ANY_AVX512_4FMAPS_FLAGS },
1057   { STRING_COMMA_LEN ("noavx512_4vnniw"), CPU_ANY_AVX512_4VNNIW_FLAGS },
1058   { STRING_COMMA_LEN ("noavx512_vpopcntdq"), CPU_ANY_AVX512_VPOPCNTDQ_FLAGS },
1059   { STRING_COMMA_LEN ("noavx512_vbmi2"), CPU_ANY_AVX512_VBMI2_FLAGS },
1060   { STRING_COMMA_LEN ("noavx512_vnni"), CPU_ANY_AVX512_VNNI_FLAGS },
1061   { STRING_COMMA_LEN ("noavx512_bitalg"), CPU_ANY_AVX512_BITALG_FLAGS },
1062   { STRING_COMMA_LEN ("noibt"), CPU_ANY_IBT_FLAGS },
1063   { STRING_COMMA_LEN ("noshstk"), CPU_ANY_SHSTK_FLAGS },
1064 };
1065
1066 #ifdef I386COFF
1067 /* Like s_lcomm_internal in gas/read.c but the alignment string
1068    is allowed to be optional.  */
1069
1070 static symbolS *
1071 pe_lcomm_internal (int needs_align, symbolS *symbolP, addressT size)
1072 {
1073   addressT align = 0;
1074
1075   SKIP_WHITESPACE ();
1076
1077   if (needs_align
1078       && *input_line_pointer == ',')
1079     {
1080       align = parse_align (needs_align - 1);
1081
1082       if (align == (addressT) -1)
1083         return NULL;
1084     }
1085   else
1086     {
1087       if (size >= 8)
1088         align = 3;
1089       else if (size >= 4)
1090         align = 2;
1091       else if (size >= 2)
1092         align = 1;
1093       else
1094         align = 0;
1095     }
1096
1097   bss_alloc (symbolP, size, align);
1098   return symbolP;
1099 }
1100
1101 static void
1102 pe_lcomm (int needs_align)
1103 {
1104   s_comm_internal (needs_align * 2, pe_lcomm_internal);
1105 }
1106 #endif
1107
1108 const pseudo_typeS md_pseudo_table[] =
1109 {
1110 #if !defined(OBJ_AOUT) && !defined(USE_ALIGN_PTWO)
1111   {"align", s_align_bytes, 0},
1112 #else
1113   {"align", s_align_ptwo, 0},
1114 #endif
1115   {"arch", set_cpu_arch, 0},
1116 #ifndef I386COFF
1117   {"bss", s_bss, 0},
1118 #else
1119   {"lcomm", pe_lcomm, 1},
1120 #endif
1121   {"ffloat", float_cons, 'f'},
1122   {"dfloat", float_cons, 'd'},
1123   {"tfloat", float_cons, 'x'},
1124   {"value", cons, 2},
1125   {"slong", signed_cons, 4},
1126   {"noopt", s_ignore, 0},
1127   {"optim", s_ignore, 0},
1128   {"code16gcc", set_16bit_gcc_code_flag, CODE_16BIT},
1129   {"code16", set_code_flag, CODE_16BIT},
1130   {"code32", set_code_flag, CODE_32BIT},
1131 #ifdef BFD64
1132   {"code64", set_code_flag, CODE_64BIT},
1133 #endif
1134   {"intel_syntax", set_intel_syntax, 1},
1135   {"att_syntax", set_intel_syntax, 0},
1136   {"intel_mnemonic", set_intel_mnemonic, 1},
1137   {"att_mnemonic", set_intel_mnemonic, 0},
1138   {"allow_index_reg", set_allow_index_reg, 1},
1139   {"disallow_index_reg", set_allow_index_reg, 0},
1140   {"sse_check", set_check, 0},
1141   {"operand_check", set_check, 1},
1142 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
1143   {"largecomm", handle_large_common, 0},
1144 #else
1145   {"file", dwarf2_directive_file, 0},
1146   {"loc", dwarf2_directive_loc, 0},
1147   {"loc_mark_labels", dwarf2_directive_loc_mark_labels, 0},
1148 #endif
1149 #ifdef TE_PE
1150   {"secrel32", pe_directive_secrel, 0},
1151 #endif
1152   {0, 0, 0}
1153 };
1154
1155 /* For interface with expression ().  */
1156 extern char *input_line_pointer;
1157
1158 /* Hash table for instruction mnemonic lookup.  */
1159 static struct hash_control *op_hash;
1160
1161 /* Hash table for register lookup.  */
1162 static struct hash_control *reg_hash;
1163 \f
1164   /* Various efficient no-op patterns for aligning code labels.
1165      Note: Don't try to assemble the instructions in the comments.
1166      0L and 0w are not legal.  */
1167 static const unsigned char f32_1[] =
1168   {0x90};                               /* nop                  */
1169 static const unsigned char f32_2[] =
1170   {0x66,0x90};                          /* xchg %ax,%ax         */
1171 static const unsigned char f32_3[] =
1172   {0x8d,0x76,0x00};                     /* leal 0(%esi),%esi    */
1173 static const unsigned char f32_4[] =
1174   {0x8d,0x74,0x26,0x00};                /* leal 0(%esi,1),%esi  */
1175 static const unsigned char f32_6[] =
1176   {0x8d,0xb6,0x00,0x00,0x00,0x00};      /* leal 0L(%esi),%esi   */
1177 static const unsigned char f32_7[] =
1178   {0x8d,0xb4,0x26,0x00,0x00,0x00,0x00}; /* leal 0L(%esi,1),%esi */
1179 static const unsigned char f16_3[] =
1180   {0x8d,0x74,0x00};                     /* lea 0(%si),%si       */
1181 static const unsigned char f16_4[] =
1182   {0x8d,0xb4,0x00,0x00};                /* lea 0W(%si),%si      */
1183 static const unsigned char jump_disp8[] =
1184   {0xeb};                               /* jmp disp8           */
1185 static const unsigned char jump32_disp32[] =
1186   {0xe9};                               /* jmp disp32          */
1187 static const unsigned char jump16_disp32[] =
1188   {0x66,0xe9};                          /* jmp disp32          */
1189 /* 32-bit NOPs patterns.  */
1190 static const unsigned char *const f32_patt[] = {
1191   f32_1, f32_2, f32_3, f32_4, NULL, f32_6, f32_7
1192 };
1193 /* 16-bit NOPs patterns.  */
1194 static const unsigned char *const f16_patt[] = {
1195   f32_1, f32_2, f16_3, f16_4
1196 };
1197 /* nopl (%[re]ax) */
1198 static const unsigned char alt_3[] =
1199   {0x0f,0x1f,0x00};
1200 /* nopl 0(%[re]ax) */
1201 static const unsigned char alt_4[] =
1202   {0x0f,0x1f,0x40,0x00};
1203 /* nopl 0(%[re]ax,%[re]ax,1) */
1204 static const unsigned char alt_5[] =
1205   {0x0f,0x1f,0x44,0x00,0x00};
1206 /* nopw 0(%[re]ax,%[re]ax,1) */
1207 static const unsigned char alt_6[] =
1208   {0x66,0x0f,0x1f,0x44,0x00,0x00};
1209 /* nopl 0L(%[re]ax) */
1210 static const unsigned char alt_7[] =
1211   {0x0f,0x1f,0x80,0x00,0x00,0x00,0x00};
1212 /* nopl 0L(%[re]ax,%[re]ax,1) */
1213 static const unsigned char alt_8[] =
1214   {0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
1215 /* nopw 0L(%[re]ax,%[re]ax,1) */
1216 static const unsigned char alt_9[] =
1217   {0x66,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
1218 /* nopw %cs:0L(%[re]ax,%[re]ax,1) */
1219 static const unsigned char alt_10[] =
1220   {0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
1221 /* data16 nopw %cs:0L(%eax,%eax,1) */
1222 static const unsigned char alt_11[] =
1223   {0x66,0x66,0x2e,0x0f,0x1f,0x84,0x00,0x00,0x00,0x00,0x00};
1224 /* 32-bit and 64-bit NOPs patterns.  */
1225 static const unsigned char *const alt_patt[] = {
1226   f32_1, f32_2, alt_3, alt_4, alt_5, alt_6, alt_7, alt_8,
1227   alt_9, alt_10, alt_11
1228 };
1229
1230 /* Genenerate COUNT bytes of NOPs to WHERE from PATT with the maximum
1231    size of a single NOP instruction MAX_SINGLE_NOP_SIZE.  */
1232
1233 static void
1234 i386_output_nops (char *where, const unsigned char *const *patt,
1235                   int count, int max_single_nop_size)
1236
1237 {
1238   /* Place the longer NOP first.  */
1239   int last;
1240   int offset;
1241   const unsigned char *nops =  patt[max_single_nop_size - 1];
1242
1243   /* Use the smaller one if the requsted one isn't available.  */
1244   if (nops == NULL)
1245     {
1246       max_single_nop_size--;
1247       nops = patt[max_single_nop_size - 1];
1248     }
1249
1250   last = count % max_single_nop_size;
1251
1252   count -= last;
1253   for (offset = 0; offset < count; offset += max_single_nop_size)
1254     memcpy (where + offset, nops, max_single_nop_size);
1255
1256   if (last)
1257     {
1258       nops = patt[last - 1];
1259       if (nops == NULL)
1260         {
1261           /* Use the smaller one plus one-byte NOP if the needed one
1262              isn't available.  */
1263           last--;
1264           nops = patt[last - 1];
1265           memcpy (where + offset, nops, last);
1266           where[offset + last] = *patt[0];
1267         }
1268       else
1269         memcpy (where + offset, nops, last);
1270     }
1271 }
1272
1273 static INLINE int
1274 fits_in_imm7 (offsetT num)
1275 {
1276   return (num & 0x7f) == num;
1277 }
1278
1279 static INLINE int
1280 fits_in_imm31 (offsetT num)
1281 {
1282   return (num & 0x7fffffff) == num;
1283 }
1284
1285 /* Genenerate COUNT bytes of NOPs to WHERE with the maximum size of a
1286    single NOP instruction LIMIT.  */
1287
1288 void
1289 i386_generate_nops (fragS *fragP, char *where, offsetT count, int limit)
1290 {
1291   const unsigned char *const *patt = NULL;
1292   int max_single_nop_size;
1293   /* Maximum number of NOPs before switching to jump over NOPs.  */
1294   int max_number_of_nops;
1295
1296   switch (fragP->fr_type)
1297     {
1298     case rs_fill_nop:
1299     case rs_align_code:
1300       break;
1301     default:
1302       return;
1303     }
1304
1305   /* We need to decide which NOP sequence to use for 32bit and
1306      64bit. When -mtune= is used:
1307
1308      1. For PROCESSOR_I386, PROCESSOR_I486, PROCESSOR_PENTIUM and
1309      PROCESSOR_GENERIC32, f32_patt will be used.
1310      2. For the rest, alt_patt will be used.
1311
1312      When -mtune= isn't used, alt_patt will be used if
1313      cpu_arch_isa_flags has CpuNop.  Otherwise, f32_patt will
1314      be used.
1315
1316      When -march= or .arch is used, we can't use anything beyond
1317      cpu_arch_isa_flags.   */
1318
1319   if (flag_code == CODE_16BIT)
1320     {
1321       patt = f16_patt;
1322       max_single_nop_size = sizeof (f16_patt) / sizeof (f16_patt[0]);
1323       /* Limit number of NOPs to 2 in 16-bit mode.  */
1324       max_number_of_nops = 2;
1325     }
1326   else
1327     {
1328       if (fragP->tc_frag_data.isa == PROCESSOR_UNKNOWN)
1329         {
1330           /* PROCESSOR_UNKNOWN means that all ISAs may be used.  */
1331           switch (cpu_arch_tune)
1332             {
1333             case PROCESSOR_UNKNOWN:
1334               /* We use cpu_arch_isa_flags to check if we SHOULD
1335                  optimize with nops.  */
1336               if (fragP->tc_frag_data.isa_flags.bitfield.cpunop)
1337                 patt = alt_patt;
1338               else
1339                 patt = f32_patt;
1340               break;
1341             case PROCESSOR_PENTIUM4:
1342             case PROCESSOR_NOCONA:
1343             case PROCESSOR_CORE:
1344             case PROCESSOR_CORE2:
1345             case PROCESSOR_COREI7:
1346             case PROCESSOR_L1OM:
1347             case PROCESSOR_K1OM:
1348             case PROCESSOR_GENERIC64:
1349             case PROCESSOR_K6:
1350             case PROCESSOR_ATHLON:
1351             case PROCESSOR_K8:
1352             case PROCESSOR_AMDFAM10:
1353             case PROCESSOR_BD:
1354             case PROCESSOR_ZNVER:
1355             case PROCESSOR_BT:
1356               patt = alt_patt;
1357               break;
1358             case PROCESSOR_I386:
1359             case PROCESSOR_I486:
1360             case PROCESSOR_PENTIUM:
1361             case PROCESSOR_PENTIUMPRO:
1362             case PROCESSOR_IAMCU:
1363             case PROCESSOR_GENERIC32:
1364               patt = f32_patt;
1365               break;
1366             }
1367         }
1368       else
1369         {
1370           switch (fragP->tc_frag_data.tune)
1371             {
1372             case PROCESSOR_UNKNOWN:
1373               /* When cpu_arch_isa is set, cpu_arch_tune shouldn't be
1374                  PROCESSOR_UNKNOWN.  */
1375               abort ();
1376               break;
1377
1378             case PROCESSOR_I386:
1379             case PROCESSOR_I486:
1380             case PROCESSOR_PENTIUM:
1381             case PROCESSOR_IAMCU:
1382             case PROCESSOR_K6:
1383             case PROCESSOR_ATHLON:
1384             case PROCESSOR_K8:
1385             case PROCESSOR_AMDFAM10:
1386             case PROCESSOR_BD:
1387             case PROCESSOR_ZNVER:
1388             case PROCESSOR_BT:
1389             case PROCESSOR_GENERIC32:
1390               /* We use cpu_arch_isa_flags to check if we CAN optimize
1391                  with nops.  */
1392               if (fragP->tc_frag_data.isa_flags.bitfield.cpunop)
1393                 patt = alt_patt;
1394               else
1395                 patt = f32_patt;
1396               break;
1397             case PROCESSOR_PENTIUMPRO:
1398             case PROCESSOR_PENTIUM4:
1399             case PROCESSOR_NOCONA:
1400             case PROCESSOR_CORE:
1401             case PROCESSOR_CORE2:
1402             case PROCESSOR_COREI7:
1403             case PROCESSOR_L1OM:
1404             case PROCESSOR_K1OM:
1405               if (fragP->tc_frag_data.isa_flags.bitfield.cpunop)
1406                 patt = alt_patt;
1407               else
1408                 patt = f32_patt;
1409               break;
1410             case PROCESSOR_GENERIC64:
1411               patt = alt_patt;
1412               break;
1413             }
1414         }
1415
1416       if (patt == f32_patt)
1417         {
1418           max_single_nop_size = sizeof (f32_patt) / sizeof (f32_patt[0]);
1419           /* Limit number of NOPs to 2 for older processors.  */
1420           max_number_of_nops = 2;
1421         }
1422       else
1423         {
1424           max_single_nop_size = sizeof (alt_patt) / sizeof (alt_patt[0]);
1425           /* Limit number of NOPs to 7 for newer processors.  */
1426           max_number_of_nops = 7;
1427         }
1428     }
1429
1430   if (limit == 0)
1431     limit = max_single_nop_size;
1432
1433   if (fragP->fr_type == rs_fill_nop)
1434     {
1435       /* Output NOPs for .nop directive.  */
1436       if (limit > max_single_nop_size)
1437         {
1438           as_bad_where (fragP->fr_file, fragP->fr_line,
1439                         _("invalid single nop size: %d "
1440                           "(expect within [0, %d])"),
1441                         limit, max_single_nop_size);
1442           return;
1443         }
1444     }
1445   else
1446     fragP->fr_var = count;
1447
1448   if ((count / max_single_nop_size) > max_number_of_nops)
1449     {
1450       /* Generate jump over NOPs.  */
1451       offsetT disp = count - 2;
1452       if (fits_in_imm7 (disp))
1453         {
1454           /* Use "jmp disp8" if possible.  */
1455           count = disp;
1456           where[0] = jump_disp8[0];
1457           where[1] = count;
1458           where += 2;
1459         }
1460       else
1461         {
1462           unsigned int size_of_jump;
1463
1464           if (flag_code == CODE_16BIT)
1465             {
1466               where[0] = jump16_disp32[0];
1467               where[1] = jump16_disp32[1];
1468               size_of_jump = 2;
1469             }
1470           else
1471             {
1472               where[0] = jump32_disp32[0];
1473               size_of_jump = 1;
1474             }
1475
1476           count -= size_of_jump + 4;
1477           if (!fits_in_imm31 (count))
1478             {
1479               as_bad_where (fragP->fr_file, fragP->fr_line,
1480                             _("jump over nop padding out of range"));
1481               return;
1482             }
1483
1484           md_number_to_chars (where + size_of_jump, count, 4);
1485           where += size_of_jump + 4;
1486         }
1487     }
1488
1489   /* Generate multiple NOPs.  */
1490   i386_output_nops (where, patt, count, limit);
1491 }
1492
1493 static INLINE int
1494 operand_type_all_zero (const union i386_operand_type *x)
1495 {
1496   switch (ARRAY_SIZE(x->array))
1497     {
1498     case 3:
1499       if (x->array[2])
1500         return 0;
1501       /* Fall through.  */
1502     case 2:
1503       if (x->array[1])
1504         return 0;
1505       /* Fall through.  */
1506     case 1:
1507       return !x->array[0];
1508     default:
1509       abort ();
1510     }
1511 }
1512
1513 static INLINE void
1514 operand_type_set (union i386_operand_type *x, unsigned int v)
1515 {
1516   switch (ARRAY_SIZE(x->array))
1517     {
1518     case 3:
1519       x->array[2] = v;
1520       /* Fall through.  */
1521     case 2:
1522       x->array[1] = v;
1523       /* Fall through.  */
1524     case 1:
1525       x->array[0] = v;
1526       /* Fall through.  */
1527       break;
1528     default:
1529       abort ();
1530     }
1531 }
1532
1533 static INLINE int
1534 operand_type_equal (const union i386_operand_type *x,
1535                     const union i386_operand_type *y)
1536 {
1537   switch (ARRAY_SIZE(x->array))
1538     {
1539     case 3:
1540       if (x->array[2] != y->array[2])
1541         return 0;
1542       /* Fall through.  */
1543     case 2:
1544       if (x->array[1] != y->array[1])
1545         return 0;
1546       /* Fall through.  */
1547     case 1:
1548       return x->array[0] == y->array[0];
1549       break;
1550     default:
1551       abort ();
1552     }
1553 }
1554
1555 static INLINE int
1556 cpu_flags_all_zero (const union i386_cpu_flags *x)
1557 {
1558   switch (ARRAY_SIZE(x->array))
1559     {
1560     case 4:
1561       if (x->array[3])
1562         return 0;
1563       /* Fall through.  */
1564     case 3:
1565       if (x->array[2])
1566         return 0;
1567       /* Fall through.  */
1568     case 2:
1569       if (x->array[1])
1570         return 0;
1571       /* Fall through.  */
1572     case 1:
1573       return !x->array[0];
1574     default:
1575       abort ();
1576     }
1577 }
1578
1579 static INLINE int
1580 cpu_flags_equal (const union i386_cpu_flags *x,
1581                  const union i386_cpu_flags *y)
1582 {
1583   switch (ARRAY_SIZE(x->array))
1584     {
1585     case 4:
1586       if (x->array[3] != y->array[3])
1587         return 0;
1588       /* Fall through.  */
1589     case 3:
1590       if (x->array[2] != y->array[2])
1591         return 0;
1592       /* Fall through.  */
1593     case 2:
1594       if (x->array[1] != y->array[1])
1595         return 0;
1596       /* Fall through.  */
1597     case 1:
1598       return x->array[0] == y->array[0];
1599       break;
1600     default:
1601       abort ();
1602     }
1603 }
1604
1605 static INLINE int
1606 cpu_flags_check_cpu64 (i386_cpu_flags f)
1607 {
1608   return !((flag_code == CODE_64BIT && f.bitfield.cpuno64)
1609            || (flag_code != CODE_64BIT && f.bitfield.cpu64));
1610 }
1611
1612 static INLINE i386_cpu_flags
1613 cpu_flags_and (i386_cpu_flags x, i386_cpu_flags y)
1614 {
1615   switch (ARRAY_SIZE (x.array))
1616     {
1617     case 4:
1618       x.array [3] &= y.array [3];
1619       /* Fall through.  */
1620     case 3:
1621       x.array [2] &= y.array [2];
1622       /* Fall through.  */
1623     case 2:
1624       x.array [1] &= y.array [1];
1625       /* Fall through.  */
1626     case 1:
1627       x.array [0] &= y.array [0];
1628       break;
1629     default:
1630       abort ();
1631     }
1632   return x;
1633 }
1634
1635 static INLINE i386_cpu_flags
1636 cpu_flags_or (i386_cpu_flags x, i386_cpu_flags y)
1637 {
1638   switch (ARRAY_SIZE (x.array))
1639     {
1640     case 4:
1641       x.array [3] |= y.array [3];
1642       /* Fall through.  */
1643     case 3:
1644       x.array [2] |= y.array [2];
1645       /* Fall through.  */
1646     case 2:
1647       x.array [1] |= y.array [1];
1648       /* Fall through.  */
1649     case 1:
1650       x.array [0] |= y.array [0];
1651       break;
1652     default:
1653       abort ();
1654     }
1655   return x;
1656 }
1657
1658 static INLINE i386_cpu_flags
1659 cpu_flags_and_not (i386_cpu_flags x, i386_cpu_flags y)
1660 {
1661   switch (ARRAY_SIZE (x.array))
1662     {
1663     case 4:
1664       x.array [3] &= ~y.array [3];
1665       /* Fall through.  */
1666     case 3:
1667       x.array [2] &= ~y.array [2];
1668       /* Fall through.  */
1669     case 2:
1670       x.array [1] &= ~y.array [1];
1671       /* Fall through.  */
1672     case 1:
1673       x.array [0] &= ~y.array [0];
1674       break;
1675     default:
1676       abort ();
1677     }
1678   return x;
1679 }
1680
1681 #define CPU_FLAGS_ARCH_MATCH            0x1
1682 #define CPU_FLAGS_64BIT_MATCH           0x2
1683
1684 #define CPU_FLAGS_PERFECT_MATCH \
1685   (CPU_FLAGS_ARCH_MATCH | CPU_FLAGS_64BIT_MATCH)
1686
1687 /* Return CPU flags match bits. */
1688
1689 static int
1690 cpu_flags_match (const insn_template *t)
1691 {
1692   i386_cpu_flags x = t->cpu_flags;
1693   int match = cpu_flags_check_cpu64 (x) ? CPU_FLAGS_64BIT_MATCH : 0;
1694
1695   x.bitfield.cpu64 = 0;
1696   x.bitfield.cpuno64 = 0;
1697
1698   if (cpu_flags_all_zero (&x))
1699     {
1700       /* This instruction is available on all archs.  */
1701       match |= CPU_FLAGS_ARCH_MATCH;
1702     }
1703   else
1704     {
1705       /* This instruction is available only on some archs.  */
1706       i386_cpu_flags cpu = cpu_arch_flags;
1707
1708       /* AVX512VL is no standalone feature - match it and then strip it.  */
1709       if (x.bitfield.cpuavx512vl && !cpu.bitfield.cpuavx512vl)
1710         return match;
1711       x.bitfield.cpuavx512vl = 0;
1712
1713       cpu = cpu_flags_and (x, cpu);
1714       if (!cpu_flags_all_zero (&cpu))
1715         {
1716           if (x.bitfield.cpuavx)
1717             {
1718               /* We need to check a few extra flags with AVX.  */
1719               if (cpu.bitfield.cpuavx
1720                   && (!t->opcode_modifier.sse2avx || sse2avx)
1721                   && (!x.bitfield.cpuaes || cpu.bitfield.cpuaes)
1722                   && (!x.bitfield.cpugfni || cpu.bitfield.cpugfni)
1723                   && (!x.bitfield.cpupclmul || cpu.bitfield.cpupclmul))
1724                 match |= CPU_FLAGS_ARCH_MATCH;
1725             }
1726           else if (x.bitfield.cpuavx512f)
1727             {
1728               /* We need to check a few extra flags with AVX512F.  */
1729               if (cpu.bitfield.cpuavx512f
1730                   && (!x.bitfield.cpugfni || cpu.bitfield.cpugfni)
1731                   && (!x.bitfield.cpuvaes || cpu.bitfield.cpuvaes)
1732                   && (!x.bitfield.cpuvpclmulqdq || cpu.bitfield.cpuvpclmulqdq))
1733                 match |= CPU_FLAGS_ARCH_MATCH;
1734             }
1735           else
1736             match |= CPU_FLAGS_ARCH_MATCH;
1737         }
1738     }
1739   return match;
1740 }
1741
1742 static INLINE i386_operand_type
1743 operand_type_and (i386_operand_type x, i386_operand_type y)
1744 {
1745   switch (ARRAY_SIZE (x.array))
1746     {
1747     case 3:
1748       x.array [2] &= y.array [2];
1749       /* Fall through.  */
1750     case 2:
1751       x.array [1] &= y.array [1];
1752       /* Fall through.  */
1753     case 1:
1754       x.array [0] &= y.array [0];
1755       break;
1756     default:
1757       abort ();
1758     }
1759   return x;
1760 }
1761
1762 static INLINE i386_operand_type
1763 operand_type_and_not (i386_operand_type x, i386_operand_type y)
1764 {
1765   switch (ARRAY_SIZE (x.array))
1766     {
1767     case 3:
1768       x.array [2] &= ~y.array [2];
1769       /* Fall through.  */
1770     case 2:
1771       x.array [1] &= ~y.array [1];
1772       /* Fall through.  */
1773     case 1:
1774       x.array [0] &= ~y.array [0];
1775       break;
1776     default:
1777       abort ();
1778     }
1779   return x;
1780 }
1781
1782 static INLINE i386_operand_type
1783 operand_type_or (i386_operand_type x, i386_operand_type y)
1784 {
1785   switch (ARRAY_SIZE (x.array))
1786     {
1787     case 3:
1788       x.array [2] |= y.array [2];
1789       /* Fall through.  */
1790     case 2:
1791       x.array [1] |= y.array [1];
1792       /* Fall through.  */
1793     case 1:
1794       x.array [0] |= y.array [0];
1795       break;
1796     default:
1797       abort ();
1798     }
1799   return x;
1800 }
1801
1802 static INLINE i386_operand_type
1803 operand_type_xor (i386_operand_type x, i386_operand_type y)
1804 {
1805   switch (ARRAY_SIZE (x.array))
1806     {
1807     case 3:
1808       x.array [2] ^= y.array [2];
1809       /* Fall through.  */
1810     case 2:
1811       x.array [1] ^= y.array [1];
1812       /* Fall through.  */
1813     case 1:
1814       x.array [0] ^= y.array [0];
1815       break;
1816     default:
1817       abort ();
1818     }
1819   return x;
1820 }
1821
1822 static const i386_operand_type acc32 = OPERAND_TYPE_ACC32;
1823 static const i386_operand_type acc64 = OPERAND_TYPE_ACC64;
1824 static const i386_operand_type control = OPERAND_TYPE_CONTROL;
1825 static const i386_operand_type inoutportreg
1826   = OPERAND_TYPE_INOUTPORTREG;
1827 static const i386_operand_type reg16_inoutportreg
1828   = OPERAND_TYPE_REG16_INOUTPORTREG;
1829 static const i386_operand_type disp16 = OPERAND_TYPE_DISP16;
1830 static const i386_operand_type disp32 = OPERAND_TYPE_DISP32;
1831 static const i386_operand_type disp32s = OPERAND_TYPE_DISP32S;
1832 static const i386_operand_type disp16_32 = OPERAND_TYPE_DISP16_32;
1833 static const i386_operand_type anydisp
1834   = OPERAND_TYPE_ANYDISP;
1835 static const i386_operand_type regxmm = OPERAND_TYPE_REGXMM;
1836 static const i386_operand_type regmask = OPERAND_TYPE_REGMASK;
1837 static const i386_operand_type imm8 = OPERAND_TYPE_IMM8;
1838 static const i386_operand_type imm8s = OPERAND_TYPE_IMM8S;
1839 static const i386_operand_type imm16 = OPERAND_TYPE_IMM16;
1840 static const i386_operand_type imm32 = OPERAND_TYPE_IMM32;
1841 static const i386_operand_type imm32s = OPERAND_TYPE_IMM32S;
1842 static const i386_operand_type imm64 = OPERAND_TYPE_IMM64;
1843 static const i386_operand_type imm16_32 = OPERAND_TYPE_IMM16_32;
1844 static const i386_operand_type imm16_32s = OPERAND_TYPE_IMM16_32S;
1845 static const i386_operand_type imm16_32_32s = OPERAND_TYPE_IMM16_32_32S;
1846 static const i386_operand_type vec_imm4 = OPERAND_TYPE_VEC_IMM4;
1847
1848 enum operand_type
1849 {
1850   reg,
1851   imm,
1852   disp,
1853   anymem
1854 };
1855
1856 static INLINE int
1857 operand_type_check (i386_operand_type t, enum operand_type c)
1858 {
1859   switch (c)
1860     {
1861     case reg:
1862       return t.bitfield.reg;
1863
1864     case imm:
1865       return (t.bitfield.imm8
1866               || t.bitfield.imm8s
1867               || t.bitfield.imm16
1868               || t.bitfield.imm32
1869               || t.bitfield.imm32s
1870               || t.bitfield.imm64);
1871
1872     case disp:
1873       return (t.bitfield.disp8
1874               || t.bitfield.disp16
1875               || t.bitfield.disp32
1876               || t.bitfield.disp32s
1877               || t.bitfield.disp64);
1878
1879     case anymem:
1880       return (t.bitfield.disp8
1881               || t.bitfield.disp16
1882               || t.bitfield.disp32
1883               || t.bitfield.disp32s
1884               || t.bitfield.disp64
1885               || t.bitfield.baseindex);
1886
1887     default:
1888       abort ();
1889     }
1890
1891   return 0;
1892 }
1893
1894 /* Return 1 if there is no conflict in 8bit/16bit/32bit/64bit/80bit on
1895    operand J for instruction template T.  */
1896
1897 static INLINE int
1898 match_reg_size (const insn_template *t, unsigned int j)
1899 {
1900   return !((i.types[j].bitfield.byte
1901             && !t->operand_types[j].bitfield.byte)
1902            || (i.types[j].bitfield.word
1903                && !t->operand_types[j].bitfield.word)
1904            || (i.types[j].bitfield.dword
1905                && !t->operand_types[j].bitfield.dword)
1906            || (i.types[j].bitfield.qword
1907                && !t->operand_types[j].bitfield.qword)
1908            || (i.types[j].bitfield.tbyte
1909                && !t->operand_types[j].bitfield.tbyte));
1910 }
1911
1912 /* Return 1 if there is no conflict in SIMD register on
1913    operand J for instruction template T.  */
1914
1915 static INLINE int
1916 match_simd_size (const insn_template *t, unsigned int j)
1917 {
1918   return !((i.types[j].bitfield.xmmword
1919             && !t->operand_types[j].bitfield.xmmword)
1920            || (i.types[j].bitfield.ymmword
1921                && !t->operand_types[j].bitfield.ymmword)
1922            || (i.types[j].bitfield.zmmword
1923                && !t->operand_types[j].bitfield.zmmword));
1924 }
1925
1926 /* Return 1 if there is no conflict in any size on operand J for
1927    instruction template T.  */
1928
1929 static INLINE int
1930 match_mem_size (const insn_template *t, unsigned int j)
1931 {
1932   return (match_reg_size (t, j)
1933           && !((i.types[j].bitfield.unspecified
1934                 && !i.broadcast
1935                 && !t->operand_types[j].bitfield.unspecified)
1936                || (i.types[j].bitfield.fword
1937                    && !t->operand_types[j].bitfield.fword)
1938                /* For scalar opcode templates to allow register and memory
1939                   operands at the same time, some special casing is needed
1940                   here.  */
1941                || ((t->operand_types[j].bitfield.regsimd
1942                     && !t->opcode_modifier.broadcast
1943                     && (t->operand_types[j].bitfield.dword
1944                         || t->operand_types[j].bitfield.qword))
1945                    ? (i.types[j].bitfield.xmmword
1946                       || i.types[j].bitfield.ymmword
1947                       || i.types[j].bitfield.zmmword)
1948                    : !match_simd_size(t, j))));
1949 }
1950
1951 /* Return 1 if there is no size conflict on any operands for
1952    instruction template T.  */
1953
1954 static INLINE int
1955 operand_size_match (const insn_template *t)
1956 {
1957   unsigned int j;
1958   int match = 1;
1959
1960   /* Don't check jump instructions.  */
1961   if (t->opcode_modifier.jump
1962       || t->opcode_modifier.jumpbyte
1963       || t->opcode_modifier.jumpdword
1964       || t->opcode_modifier.jumpintersegment)
1965     return match;
1966
1967   /* Check memory and accumulator operand size.  */
1968   for (j = 0; j < i.operands; j++)
1969     {
1970       if (!i.types[j].bitfield.reg && !i.types[j].bitfield.regsimd
1971           && t->operand_types[j].bitfield.anysize)
1972         continue;
1973
1974       if (t->operand_types[j].bitfield.reg
1975           && !match_reg_size (t, j))
1976         {
1977           match = 0;
1978           break;
1979         }
1980
1981       if (t->operand_types[j].bitfield.regsimd
1982           && !match_simd_size (t, j))
1983         {
1984           match = 0;
1985           break;
1986         }
1987
1988       if (t->operand_types[j].bitfield.acc
1989           && (!match_reg_size (t, j) || !match_simd_size (t, j)))
1990         {
1991           match = 0;
1992           break;
1993         }
1994
1995       if (i.types[j].bitfield.mem && !match_mem_size (t, j))
1996         {
1997           match = 0;
1998           break;
1999         }
2000     }
2001
2002   if (match)
2003     return match;
2004   else if (!t->opcode_modifier.d)
2005     {
2006 mismatch:
2007       i.error = operand_size_mismatch;
2008       return 0;
2009     }
2010
2011   /* Check reverse.  */
2012   gas_assert (i.operands == 2);
2013
2014   match = 1;
2015   for (j = 0; j < 2; j++)
2016     {
2017       if ((t->operand_types[j].bitfield.reg
2018            || t->operand_types[j].bitfield.acc)
2019           && !match_reg_size (t, j ? 0 : 1))
2020         goto mismatch;
2021
2022       if (i.types[j].bitfield.mem
2023           && !match_mem_size (t, j ? 0 : 1))
2024         goto mismatch;
2025     }
2026
2027   return match;
2028 }
2029
2030 static INLINE int
2031 operand_type_match (i386_operand_type overlap,
2032                     i386_operand_type given)
2033 {
2034   i386_operand_type temp = overlap;
2035
2036   temp.bitfield.jumpabsolute = 0;
2037   temp.bitfield.unspecified = 0;
2038   temp.bitfield.byte = 0;
2039   temp.bitfield.word = 0;
2040   temp.bitfield.dword = 0;
2041   temp.bitfield.fword = 0;
2042   temp.bitfield.qword = 0;
2043   temp.bitfield.tbyte = 0;
2044   temp.bitfield.xmmword = 0;
2045   temp.bitfield.ymmword = 0;
2046   temp.bitfield.zmmword = 0;
2047   if (operand_type_all_zero (&temp))
2048     goto mismatch;
2049
2050   if (given.bitfield.baseindex == overlap.bitfield.baseindex
2051       && given.bitfield.jumpabsolute == overlap.bitfield.jumpabsolute)
2052     return 1;
2053
2054 mismatch:
2055   i.error = operand_type_mismatch;
2056   return 0;
2057 }
2058
2059 /* If given types g0 and g1 are registers they must be of the same type
2060    unless the expected operand type register overlap is null.
2061    Memory operand size of certain SIMD instructions is also being checked
2062    here.  */
2063
2064 static INLINE int
2065 operand_type_register_match (i386_operand_type g0,
2066                              i386_operand_type t0,
2067                              i386_operand_type g1,
2068                              i386_operand_type t1)
2069 {
2070   if (!g0.bitfield.reg
2071       && !g0.bitfield.regsimd
2072       && (!operand_type_check (g0, anymem)
2073           || g0.bitfield.unspecified
2074           || !t0.bitfield.regsimd))
2075     return 1;
2076
2077   if (!g1.bitfield.reg
2078       && !g1.bitfield.regsimd
2079       && (!operand_type_check (g1, anymem)
2080           || g1.bitfield.unspecified
2081           || !t1.bitfield.regsimd))
2082     return 1;
2083
2084   if (g0.bitfield.byte == g1.bitfield.byte
2085       && g0.bitfield.word == g1.bitfield.word
2086       && g0.bitfield.dword == g1.bitfield.dword
2087       && g0.bitfield.qword == g1.bitfield.qword
2088       && g0.bitfield.xmmword == g1.bitfield.xmmword
2089       && g0.bitfield.ymmword == g1.bitfield.ymmword
2090       && g0.bitfield.zmmword == g1.bitfield.zmmword)
2091     return 1;
2092
2093   if (!(t0.bitfield.byte & t1.bitfield.byte)
2094       && !(t0.bitfield.word & t1.bitfield.word)
2095       && !(t0.bitfield.dword & t1.bitfield.dword)
2096       && !(t0.bitfield.qword & t1.bitfield.qword)
2097       && !(t0.bitfield.xmmword & t1.bitfield.xmmword)
2098       && !(t0.bitfield.ymmword & t1.bitfield.ymmword)
2099       && !(t0.bitfield.zmmword & t1.bitfield.zmmword))
2100     return 1;
2101
2102   i.error = register_type_mismatch;
2103
2104   return 0;
2105 }
2106
2107 static INLINE unsigned int
2108 register_number (const reg_entry *r)
2109 {
2110   unsigned int nr = r->reg_num;
2111
2112   if (r->reg_flags & RegRex)
2113     nr += 8;
2114
2115   if (r->reg_flags & RegVRex)
2116     nr += 16;
2117
2118   return nr;
2119 }
2120
2121 static INLINE unsigned int
2122 mode_from_disp_size (i386_operand_type t)
2123 {
2124   if (t.bitfield.disp8)
2125     return 1;
2126   else if (t.bitfield.disp16
2127            || t.bitfield.disp32
2128            || t.bitfield.disp32s)
2129     return 2;
2130   else
2131     return 0;
2132 }
2133
2134 static INLINE int
2135 fits_in_signed_byte (addressT num)
2136 {
2137   return num + 0x80 <= 0xff;
2138 }
2139
2140 static INLINE int
2141 fits_in_unsigned_byte (addressT num)
2142 {
2143   return num <= 0xff;
2144 }
2145
2146 static INLINE int
2147 fits_in_unsigned_word (addressT num)
2148 {
2149   return num <= 0xffff;
2150 }
2151
2152 static INLINE int
2153 fits_in_signed_word (addressT num)
2154 {
2155   return num + 0x8000 <= 0xffff;
2156 }
2157
2158 static INLINE int
2159 fits_in_signed_long (addressT num ATTRIBUTE_UNUSED)
2160 {
2161 #ifndef BFD64
2162   return 1;
2163 #else
2164   return num + 0x80000000 <= 0xffffffff;
2165 #endif
2166 }                               /* fits_in_signed_long() */
2167
2168 static INLINE int
2169 fits_in_unsigned_long (addressT num ATTRIBUTE_UNUSED)
2170 {
2171 #ifndef BFD64
2172   return 1;
2173 #else
2174   return num <= 0xffffffff;
2175 #endif
2176 }                               /* fits_in_unsigned_long() */
2177
2178 static INLINE int
2179 fits_in_disp8 (offsetT num)
2180 {
2181   int shift = i.memshift;
2182   unsigned int mask;
2183
2184   if (shift == -1)
2185     abort ();
2186
2187   mask = (1 << shift) - 1;
2188
2189   /* Return 0 if NUM isn't properly aligned.  */
2190   if ((num & mask))
2191     return 0;
2192
2193   /* Check if NUM will fit in 8bit after shift.  */
2194   return fits_in_signed_byte (num >> shift);
2195 }
2196
2197 static INLINE int
2198 fits_in_imm4 (offsetT num)
2199 {
2200   return (num & 0xf) == num;
2201 }
2202
2203 static i386_operand_type
2204 smallest_imm_type (offsetT num)
2205 {
2206   i386_operand_type t;
2207
2208   operand_type_set (&t, 0);
2209   t.bitfield.imm64 = 1;
2210
2211   if (cpu_arch_tune != PROCESSOR_I486 && num == 1)
2212     {
2213       /* This code is disabled on the 486 because all the Imm1 forms
2214          in the opcode table are slower on the i486.  They're the
2215          versions with the implicitly specified single-position
2216          displacement, which has another syntax if you really want to
2217          use that form.  */
2218       t.bitfield.imm1 = 1;
2219       t.bitfield.imm8 = 1;
2220       t.bitfield.imm8s = 1;
2221       t.bitfield.imm16 = 1;
2222       t.bitfield.imm32 = 1;
2223       t.bitfield.imm32s = 1;
2224     }
2225   else if (fits_in_signed_byte (num))
2226     {
2227       t.bitfield.imm8 = 1;
2228       t.bitfield.imm8s = 1;
2229       t.bitfield.imm16 = 1;
2230       t.bitfield.imm32 = 1;
2231       t.bitfield.imm32s = 1;
2232     }
2233   else if (fits_in_unsigned_byte (num))
2234     {
2235       t.bitfield.imm8 = 1;
2236       t.bitfield.imm16 = 1;
2237       t.bitfield.imm32 = 1;
2238       t.bitfield.imm32s = 1;
2239     }
2240   else if (fits_in_signed_word (num) || fits_in_unsigned_word (num))
2241     {
2242       t.bitfield.imm16 = 1;
2243       t.bitfield.imm32 = 1;
2244       t.bitfield.imm32s = 1;
2245     }
2246   else if (fits_in_signed_long (num))
2247     {
2248       t.bitfield.imm32 = 1;
2249       t.bitfield.imm32s = 1;
2250     }
2251   else if (fits_in_unsigned_long (num))
2252     t.bitfield.imm32 = 1;
2253
2254   return t;
2255 }
2256
2257 static offsetT
2258 offset_in_range (offsetT val, int size)
2259 {
2260   addressT mask;
2261
2262   switch (size)
2263     {
2264     case 1: mask = ((addressT) 1 <<  8) - 1; break;
2265     case 2: mask = ((addressT) 1 << 16) - 1; break;
2266     case 4: mask = ((addressT) 2 << 31) - 1; break;
2267 #ifdef BFD64
2268     case 8: mask = ((addressT) 2 << 63) - 1; break;
2269 #endif
2270     default: abort ();
2271     }
2272
2273 #ifdef BFD64
2274   /* If BFD64, sign extend val for 32bit address mode.  */
2275   if (flag_code != CODE_64BIT
2276       || i.prefix[ADDR_PREFIX])
2277     if ((val & ~(((addressT) 2 << 31) - 1)) == 0)
2278       val = (val ^ ((addressT) 1 << 31)) - ((addressT) 1 << 31);
2279 #endif
2280
2281   if ((val & ~mask) != 0 && (val & ~mask) != ~mask)
2282     {
2283       char buf1[40], buf2[40];
2284
2285       sprint_value (buf1, val);
2286       sprint_value (buf2, val & mask);
2287       as_warn (_("%s shortened to %s"), buf1, buf2);
2288     }
2289   return val & mask;
2290 }
2291
2292 enum PREFIX_GROUP
2293 {
2294   PREFIX_EXIST = 0,
2295   PREFIX_LOCK,
2296   PREFIX_REP,
2297   PREFIX_DS,
2298   PREFIX_OTHER
2299 };
2300
2301 /* Returns
2302    a. PREFIX_EXIST if attempting to add a prefix where one from the
2303    same class already exists.
2304    b. PREFIX_LOCK if lock prefix is added.
2305    c. PREFIX_REP if rep/repne prefix is added.
2306    d. PREFIX_DS if ds prefix is added.
2307    e. PREFIX_OTHER if other prefix is added.
2308  */
2309
2310 static enum PREFIX_GROUP
2311 add_prefix (unsigned int prefix)
2312 {
2313   enum PREFIX_GROUP ret = PREFIX_OTHER;
2314   unsigned int q;
2315
2316   if (prefix >= REX_OPCODE && prefix < REX_OPCODE + 16
2317       && flag_code == CODE_64BIT)
2318     {
2319       if ((i.prefix[REX_PREFIX] & prefix & REX_W)
2320           || ((i.prefix[REX_PREFIX] & (REX_R | REX_X | REX_B))
2321               && (prefix & (REX_R | REX_X | REX_B))))
2322         ret = PREFIX_EXIST;
2323       q = REX_PREFIX;
2324     }
2325   else
2326     {
2327       switch (prefix)
2328         {
2329         default:
2330           abort ();
2331
2332         case DS_PREFIX_OPCODE:
2333           ret = PREFIX_DS;
2334           /* Fall through.  */
2335         case CS_PREFIX_OPCODE:
2336         case ES_PREFIX_OPCODE:
2337         case FS_PREFIX_OPCODE:
2338         case GS_PREFIX_OPCODE:
2339         case SS_PREFIX_OPCODE:
2340           q = SEG_PREFIX;
2341           break;
2342
2343         case REPNE_PREFIX_OPCODE:
2344         case REPE_PREFIX_OPCODE:
2345           q = REP_PREFIX;
2346           ret = PREFIX_REP;
2347           break;
2348
2349         case LOCK_PREFIX_OPCODE:
2350           q = LOCK_PREFIX;
2351           ret = PREFIX_LOCK;
2352           break;
2353
2354         case FWAIT_OPCODE:
2355           q = WAIT_PREFIX;
2356           break;
2357
2358         case ADDR_PREFIX_OPCODE:
2359           q = ADDR_PREFIX;
2360           break;
2361
2362         case DATA_PREFIX_OPCODE:
2363           q = DATA_PREFIX;
2364           break;
2365         }
2366       if (i.prefix[q] != 0)
2367         ret = PREFIX_EXIST;
2368     }
2369
2370   if (ret)
2371     {
2372       if (!i.prefix[q])
2373         ++i.prefixes;
2374       i.prefix[q] |= prefix;
2375     }
2376   else
2377     as_bad (_("same type of prefix used twice"));
2378
2379   return ret;
2380 }
2381
2382 static void
2383 update_code_flag (int value, int check)
2384 {
2385   PRINTF_LIKE ((*as_error));
2386
2387   flag_code = (enum flag_code) value;
2388   if (flag_code == CODE_64BIT)
2389     {
2390       cpu_arch_flags.bitfield.cpu64 = 1;
2391       cpu_arch_flags.bitfield.cpuno64 = 0;
2392     }
2393   else
2394     {
2395       cpu_arch_flags.bitfield.cpu64 = 0;
2396       cpu_arch_flags.bitfield.cpuno64 = 1;
2397     }
2398   if (value == CODE_64BIT && !cpu_arch_flags.bitfield.cpulm )
2399     {
2400       if (check)
2401         as_error = as_fatal;
2402       else
2403         as_error = as_bad;
2404       (*as_error) (_("64bit mode not supported on `%s'."),
2405                    cpu_arch_name ? cpu_arch_name : default_arch);
2406     }
2407   if (value == CODE_32BIT && !cpu_arch_flags.bitfield.cpui386)
2408     {
2409       if (check)
2410         as_error = as_fatal;
2411       else
2412         as_error = as_bad;
2413       (*as_error) (_("32bit mode not supported on `%s'."),
2414                    cpu_arch_name ? cpu_arch_name : default_arch);
2415     }
2416   stackop_size = '\0';
2417 }
2418
2419 static void
2420 set_code_flag (int value)
2421 {
2422   update_code_flag (value, 0);
2423 }
2424
2425 static void
2426 set_16bit_gcc_code_flag (int new_code_flag)
2427 {
2428   flag_code = (enum flag_code) new_code_flag;
2429   if (flag_code != CODE_16BIT)
2430     abort ();
2431   cpu_arch_flags.bitfield.cpu64 = 0;
2432   cpu_arch_flags.bitfield.cpuno64 = 1;
2433   stackop_size = LONG_MNEM_SUFFIX;
2434 }
2435
2436 static void
2437 set_intel_syntax (int syntax_flag)
2438 {
2439   /* Find out if register prefixing is specified.  */
2440   int ask_naked_reg = 0;
2441
2442   SKIP_WHITESPACE ();
2443   if (!is_end_of_line[(unsigned char) *input_line_pointer])
2444     {
2445       char *string;
2446       int e = get_symbol_name (&string);
2447
2448       if (strcmp (string, "prefix") == 0)
2449         ask_naked_reg = 1;
2450       else if (strcmp (string, "noprefix") == 0)
2451         ask_naked_reg = -1;
2452       else
2453         as_bad (_("bad argument to syntax directive."));
2454       (void) restore_line_pointer (e);
2455     }
2456   demand_empty_rest_of_line ();
2457
2458   intel_syntax = syntax_flag;
2459
2460   if (ask_naked_reg == 0)
2461     allow_naked_reg = (intel_syntax
2462                        && (bfd_get_symbol_leading_char (stdoutput) != '\0'));
2463   else
2464     allow_naked_reg = (ask_naked_reg < 0);
2465
2466   expr_set_rank (O_full_ptr, syntax_flag ? 10 : 0);
2467
2468   identifier_chars['%'] = intel_syntax && allow_naked_reg ? '%' : 0;
2469   identifier_chars['$'] = intel_syntax ? '$' : 0;
2470   register_prefix = allow_naked_reg ? "" : "%";
2471 }
2472
2473 static void
2474 set_intel_mnemonic (int mnemonic_flag)
2475 {
2476   intel_mnemonic = mnemonic_flag;
2477 }
2478
2479 static void
2480 set_allow_index_reg (int flag)
2481 {
2482   allow_index_reg = flag;
2483 }
2484
2485 static void
2486 set_check (int what)
2487 {
2488   enum check_kind *kind;
2489   const char *str;
2490
2491   if (what)
2492     {
2493       kind = &operand_check;
2494       str = "operand";
2495     }
2496   else
2497     {
2498       kind = &sse_check;
2499       str = "sse";
2500     }
2501
2502   SKIP_WHITESPACE ();
2503
2504   if (!is_end_of_line[(unsigned char) *input_line_pointer])
2505     {
2506       char *string;
2507       int e = get_symbol_name (&string);
2508
2509       if (strcmp (string, "none") == 0)
2510         *kind = check_none;
2511       else if (strcmp (string, "warning") == 0)
2512         *kind = check_warning;
2513       else if (strcmp (string, "error") == 0)
2514         *kind = check_error;
2515       else
2516         as_bad (_("bad argument to %s_check directive."), str);
2517       (void) restore_line_pointer (e);
2518     }
2519   else
2520     as_bad (_("missing argument for %s_check directive"), str);
2521
2522   demand_empty_rest_of_line ();
2523 }
2524
2525 static void
2526 check_cpu_arch_compatible (const char *name ATTRIBUTE_UNUSED,
2527                            i386_cpu_flags new_flag ATTRIBUTE_UNUSED)
2528 {
2529 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
2530   static const char *arch;
2531
2532   /* Intel LIOM is only supported on ELF.  */
2533   if (!IS_ELF)
2534     return;
2535
2536   if (!arch)
2537     {
2538       /* Use cpu_arch_name if it is set in md_parse_option.  Otherwise
2539          use default_arch.  */
2540       arch = cpu_arch_name;
2541       if (!arch)
2542         arch = default_arch;
2543     }
2544
2545   /* If we are targeting Intel MCU, we must enable it.  */
2546   if (get_elf_backend_data (stdoutput)->elf_machine_code != EM_IAMCU
2547       || new_flag.bitfield.cpuiamcu)
2548     return;
2549
2550   /* If we are targeting Intel L1OM, we must enable it.  */
2551   if (get_elf_backend_data (stdoutput)->elf_machine_code != EM_L1OM
2552       || new_flag.bitfield.cpul1om)
2553     return;
2554
2555   /* If we are targeting Intel K1OM, we must enable it.  */
2556   if (get_elf_backend_data (stdoutput)->elf_machine_code != EM_K1OM
2557       || new_flag.bitfield.cpuk1om)
2558     return;
2559
2560   as_bad (_("`%s' is not supported on `%s'"), name, arch);
2561 #endif
2562 }
2563
2564 static void
2565 set_cpu_arch (int dummy ATTRIBUTE_UNUSED)
2566 {
2567   SKIP_WHITESPACE ();
2568
2569   if (!is_end_of_line[(unsigned char) *input_line_pointer])
2570     {
2571       char *string;
2572       int e = get_symbol_name (&string);
2573       unsigned int j;
2574       i386_cpu_flags flags;
2575
2576       for (j = 0; j < ARRAY_SIZE (cpu_arch); j++)
2577         {
2578           if (strcmp (string, cpu_arch[j].name) == 0)
2579             {
2580               check_cpu_arch_compatible (string, cpu_arch[j].flags);
2581
2582               if (*string != '.')
2583                 {
2584                   cpu_arch_name = cpu_arch[j].name;
2585                   cpu_sub_arch_name = NULL;
2586                   cpu_arch_flags = cpu_arch[j].flags;
2587                   if (flag_code == CODE_64BIT)
2588                     {
2589                       cpu_arch_flags.bitfield.cpu64 = 1;
2590                       cpu_arch_flags.bitfield.cpuno64 = 0;
2591                     }
2592                   else
2593                     {
2594                       cpu_arch_flags.bitfield.cpu64 = 0;
2595                       cpu_arch_flags.bitfield.cpuno64 = 1;
2596                     }
2597                   cpu_arch_isa = cpu_arch[j].type;
2598                   cpu_arch_isa_flags = cpu_arch[j].flags;
2599                   if (!cpu_arch_tune_set)
2600                     {
2601                       cpu_arch_tune = cpu_arch_isa;
2602                       cpu_arch_tune_flags = cpu_arch_isa_flags;
2603                     }
2604                   break;
2605                 }
2606
2607               flags = cpu_flags_or (cpu_arch_flags,
2608                                     cpu_arch[j].flags);
2609
2610               if (!cpu_flags_equal (&flags, &cpu_arch_flags))
2611                 {
2612                   if (cpu_sub_arch_name)
2613                     {
2614                       char *name = cpu_sub_arch_name;
2615                       cpu_sub_arch_name = concat (name,
2616                                                   cpu_arch[j].name,
2617                                                   (const char *) NULL);
2618                       free (name);
2619                     }
2620                   else
2621                     cpu_sub_arch_name = xstrdup (cpu_arch[j].name);
2622                   cpu_arch_flags = flags;
2623                   cpu_arch_isa_flags = flags;
2624                 }
2625               else
2626                 cpu_arch_isa_flags
2627                   = cpu_flags_or (cpu_arch_isa_flags,
2628                                   cpu_arch[j].flags);
2629               (void) restore_line_pointer (e);
2630               demand_empty_rest_of_line ();
2631               return;
2632             }
2633         }
2634
2635       if (*string == '.' && j >= ARRAY_SIZE (cpu_arch))
2636         {
2637           /* Disable an ISA extension.  */
2638           for (j = 0; j < ARRAY_SIZE (cpu_noarch); j++)
2639             if (strcmp (string + 1, cpu_noarch [j].name) == 0)
2640               {
2641                 flags = cpu_flags_and_not (cpu_arch_flags,
2642                                            cpu_noarch[j].flags);
2643                 if (!cpu_flags_equal (&flags, &cpu_arch_flags))
2644                   {
2645                     if (cpu_sub_arch_name)
2646                       {
2647                         char *name = cpu_sub_arch_name;
2648                         cpu_sub_arch_name = concat (name, string,
2649                                                     (const char *) NULL);
2650                         free (name);
2651                       }
2652                     else
2653                       cpu_sub_arch_name = xstrdup (string);
2654                     cpu_arch_flags = flags;
2655                     cpu_arch_isa_flags = flags;
2656                   }
2657                 (void) restore_line_pointer (e);
2658                 demand_empty_rest_of_line ();
2659                 return;
2660               }
2661
2662           j = ARRAY_SIZE (cpu_arch);
2663         }
2664
2665       if (j >= ARRAY_SIZE (cpu_arch))
2666         as_bad (_("no such architecture: `%s'"), string);
2667
2668       *input_line_pointer = e;
2669     }
2670   else
2671     as_bad (_("missing cpu architecture"));
2672
2673   no_cond_jump_promotion = 0;
2674   if (*input_line_pointer == ','
2675       && !is_end_of_line[(unsigned char) input_line_pointer[1]])
2676     {
2677       char *string;
2678       char e;
2679
2680       ++input_line_pointer;
2681       e = get_symbol_name (&string);
2682
2683       if (strcmp (string, "nojumps") == 0)
2684         no_cond_jump_promotion = 1;
2685       else if (strcmp (string, "jumps") == 0)
2686         ;
2687       else
2688         as_bad (_("no such architecture modifier: `%s'"), string);
2689
2690       (void) restore_line_pointer (e);
2691     }
2692
2693   demand_empty_rest_of_line ();
2694 }
2695
2696 enum bfd_architecture
2697 i386_arch (void)
2698 {
2699   if (cpu_arch_isa == PROCESSOR_L1OM)
2700     {
2701       if (OUTPUT_FLAVOR != bfd_target_elf_flavour
2702           || flag_code != CODE_64BIT)
2703         as_fatal (_("Intel L1OM is 64bit ELF only"));
2704       return bfd_arch_l1om;
2705     }
2706   else if (cpu_arch_isa == PROCESSOR_K1OM)
2707     {
2708       if (OUTPUT_FLAVOR != bfd_target_elf_flavour
2709           || flag_code != CODE_64BIT)
2710         as_fatal (_("Intel K1OM is 64bit ELF only"));
2711       return bfd_arch_k1om;
2712     }
2713   else if (cpu_arch_isa == PROCESSOR_IAMCU)
2714     {
2715       if (OUTPUT_FLAVOR != bfd_target_elf_flavour
2716           || flag_code == CODE_64BIT)
2717         as_fatal (_("Intel MCU is 32bit ELF only"));
2718       return bfd_arch_iamcu;
2719     }
2720   else
2721     return bfd_arch_i386;
2722 }
2723
2724 unsigned long
2725 i386_mach (void)
2726 {
2727   if (!strncmp (default_arch, "x86_64", 6))
2728     {
2729       if (cpu_arch_isa == PROCESSOR_L1OM)
2730         {
2731           if (OUTPUT_FLAVOR != bfd_target_elf_flavour
2732               || default_arch[6] != '\0')
2733             as_fatal (_("Intel L1OM is 64bit ELF only"));
2734           return bfd_mach_l1om;
2735         }
2736       else if (cpu_arch_isa == PROCESSOR_K1OM)
2737         {
2738           if (OUTPUT_FLAVOR != bfd_target_elf_flavour
2739               || default_arch[6] != '\0')
2740             as_fatal (_("Intel K1OM is 64bit ELF only"));
2741           return bfd_mach_k1om;
2742         }
2743       else if (default_arch[6] == '\0')
2744         return bfd_mach_x86_64;
2745       else
2746         return bfd_mach_x64_32;
2747     }
2748   else if (!strcmp (default_arch, "i386")
2749            || !strcmp (default_arch, "iamcu"))
2750     {
2751       if (cpu_arch_isa == PROCESSOR_IAMCU)
2752         {
2753           if (OUTPUT_FLAVOR != bfd_target_elf_flavour)
2754             as_fatal (_("Intel MCU is 32bit ELF only"));
2755           return bfd_mach_i386_iamcu;
2756         }
2757       else
2758         return bfd_mach_i386_i386;
2759     }
2760   else
2761     as_fatal (_("unknown architecture"));
2762 }
2763 \f
2764 void
2765 md_begin (void)
2766 {
2767   const char *hash_err;
2768
2769   /* Support pseudo prefixes like {disp32}.  */
2770   lex_type ['{'] = LEX_BEGIN_NAME;
2771
2772   /* Initialize op_hash hash table.  */
2773   op_hash = hash_new ();
2774
2775   {
2776     const insn_template *optab;
2777     templates *core_optab;
2778
2779     /* Setup for loop.  */
2780     optab = i386_optab;
2781     core_optab = XNEW (templates);
2782     core_optab->start = optab;
2783
2784     while (1)
2785       {
2786         ++optab;
2787         if (optab->name == NULL
2788             || strcmp (optab->name, (optab - 1)->name) != 0)
2789           {
2790             /* different name --> ship out current template list;
2791                add to hash table; & begin anew.  */
2792             core_optab->end = optab;
2793             hash_err = hash_insert (op_hash,
2794                                     (optab - 1)->name,
2795                                     (void *) core_optab);
2796             if (hash_err)
2797               {
2798                 as_fatal (_("can't hash %s: %s"),
2799                           (optab - 1)->name,
2800                           hash_err);
2801               }
2802             if (optab->name == NULL)
2803               break;
2804             core_optab = XNEW (templates);
2805             core_optab->start = optab;
2806           }
2807       }
2808   }
2809
2810   /* Initialize reg_hash hash table.  */
2811   reg_hash = hash_new ();
2812   {
2813     const reg_entry *regtab;
2814     unsigned int regtab_size = i386_regtab_size;
2815
2816     for (regtab = i386_regtab; regtab_size--; regtab++)
2817       {
2818         hash_err = hash_insert (reg_hash, regtab->reg_name, (void *) regtab);
2819         if (hash_err)
2820           as_fatal (_("can't hash %s: %s"),
2821                     regtab->reg_name,
2822                     hash_err);
2823       }
2824   }
2825
2826   /* Fill in lexical tables:  mnemonic_chars, operand_chars.  */
2827   {
2828     int c;
2829     char *p;
2830
2831     for (c = 0; c < 256; c++)
2832       {
2833         if (ISDIGIT (c))
2834           {
2835             digit_chars[c] = c;
2836             mnemonic_chars[c] = c;
2837             register_chars[c] = c;
2838             operand_chars[c] = c;
2839           }
2840         else if (ISLOWER (c))
2841           {
2842             mnemonic_chars[c] = c;
2843             register_chars[c] = c;
2844             operand_chars[c] = c;
2845           }
2846         else if (ISUPPER (c))
2847           {
2848             mnemonic_chars[c] = TOLOWER (c);
2849             register_chars[c] = mnemonic_chars[c];
2850             operand_chars[c] = c;
2851           }
2852         else if (c == '{' || c == '}')
2853           {
2854             mnemonic_chars[c] = c;
2855             operand_chars[c] = c;
2856           }
2857
2858         if (ISALPHA (c) || ISDIGIT (c))
2859           identifier_chars[c] = c;
2860         else if (c >= 128)
2861           {
2862             identifier_chars[c] = c;
2863             operand_chars[c] = c;
2864           }
2865       }
2866
2867 #ifdef LEX_AT
2868     identifier_chars['@'] = '@';
2869 #endif
2870 #ifdef LEX_QM
2871     identifier_chars['?'] = '?';
2872     operand_chars['?'] = '?';
2873 #endif
2874     digit_chars['-'] = '-';
2875     mnemonic_chars['_'] = '_';
2876     mnemonic_chars['-'] = '-';
2877     mnemonic_chars['.'] = '.';
2878     identifier_chars['_'] = '_';
2879     identifier_chars['.'] = '.';
2880
2881     for (p = operand_special_chars; *p != '\0'; p++)
2882       operand_chars[(unsigned char) *p] = *p;
2883   }
2884
2885   if (flag_code == CODE_64BIT)
2886     {
2887 #if defined (OBJ_COFF) && defined (TE_PE)
2888       x86_dwarf2_return_column = (OUTPUT_FLAVOR == bfd_target_coff_flavour
2889                                   ? 32 : 16);
2890 #else
2891       x86_dwarf2_return_column = 16;
2892 #endif
2893       x86_cie_data_alignment = -8;
2894     }
2895   else
2896     {
2897       x86_dwarf2_return_column = 8;
2898       x86_cie_data_alignment = -4;
2899     }
2900 }
2901
2902 void
2903 i386_print_statistics (FILE *file)
2904 {
2905   hash_print_statistics (file, "i386 opcode", op_hash);
2906   hash_print_statistics (file, "i386 register", reg_hash);
2907 }
2908 \f
2909 #ifdef DEBUG386
2910
2911 /* Debugging routines for md_assemble.  */
2912 static void pte (insn_template *);
2913 static void pt (i386_operand_type);
2914 static void pe (expressionS *);
2915 static void ps (symbolS *);
2916
2917 static void
2918 pi (char *line, i386_insn *x)
2919 {
2920   unsigned int j;
2921
2922   fprintf (stdout, "%s: template ", line);
2923   pte (&x->tm);
2924   fprintf (stdout, "  address: base %s  index %s  scale %x\n",
2925            x->base_reg ? x->base_reg->reg_name : "none",
2926            x->index_reg ? x->index_reg->reg_name : "none",
2927            x->log2_scale_factor);
2928   fprintf (stdout, "  modrm:  mode %x  reg %x  reg/mem %x\n",
2929            x->rm.mode, x->rm.reg, x->rm.regmem);
2930   fprintf (stdout, "  sib:  base %x  index %x  scale %x\n",
2931            x->sib.base, x->sib.index, x->sib.scale);
2932   fprintf (stdout, "  rex: 64bit %x  extX %x  extY %x  extZ %x\n",
2933            (x->rex & REX_W) != 0,
2934            (x->rex & REX_R) != 0,
2935            (x->rex & REX_X) != 0,
2936            (x->rex & REX_B) != 0);
2937   for (j = 0; j < x->operands; j++)
2938     {
2939       fprintf (stdout, "    #%d:  ", j + 1);
2940       pt (x->types[j]);
2941       fprintf (stdout, "\n");
2942       if (x->types[j].bitfield.reg
2943           || x->types[j].bitfield.regmmx
2944           || x->types[j].bitfield.regsimd
2945           || x->types[j].bitfield.sreg2
2946           || x->types[j].bitfield.sreg3
2947           || x->types[j].bitfield.control
2948           || x->types[j].bitfield.debug
2949           || x->types[j].bitfield.test)
2950         fprintf (stdout, "%s\n", x->op[j].regs->reg_name);
2951       if (operand_type_check (x->types[j], imm))
2952         pe (x->op[j].imms);
2953       if (operand_type_check (x->types[j], disp))
2954         pe (x->op[j].disps);
2955     }
2956 }
2957
2958 static void
2959 pte (insn_template *t)
2960 {
2961   unsigned int j;
2962   fprintf (stdout, " %d operands ", t->operands);
2963   fprintf (stdout, "opcode %x ", t->base_opcode);
2964   if (t->extension_opcode != None)
2965     fprintf (stdout, "ext %x ", t->extension_opcode);
2966   if (t->opcode_modifier.d)
2967     fprintf (stdout, "D");
2968   if (t->opcode_modifier.w)
2969     fprintf (stdout, "W");
2970   fprintf (stdout, "\n");
2971   for (j = 0; j < t->operands; j++)
2972     {
2973       fprintf (stdout, "    #%d type ", j + 1);
2974       pt (t->operand_types[j]);
2975       fprintf (stdout, "\n");
2976     }
2977 }
2978
2979 static void
2980 pe (expressionS *e)
2981 {
2982   fprintf (stdout, "    operation     %d\n", e->X_op);
2983   fprintf (stdout, "    add_number    %ld (%lx)\n",
2984            (long) e->X_add_number, (long) e->X_add_number);
2985   if (e->X_add_symbol)
2986     {
2987       fprintf (stdout, "    add_symbol    ");
2988       ps (e->X_add_symbol);
2989       fprintf (stdout, "\n");
2990     }
2991   if (e->X_op_symbol)
2992     {
2993       fprintf (stdout, "    op_symbol    ");
2994       ps (e->X_op_symbol);
2995       fprintf (stdout, "\n");
2996     }
2997 }
2998
2999 static void
3000 ps (symbolS *s)
3001 {
3002   fprintf (stdout, "%s type %s%s",
3003            S_GET_NAME (s),
3004            S_IS_EXTERNAL (s) ? "EXTERNAL " : "",
3005            segment_name (S_GET_SEGMENT (s)));
3006 }
3007
3008 static struct type_name
3009   {
3010     i386_operand_type mask;
3011     const char *name;
3012   }
3013 const type_names[] =
3014 {
3015   { OPERAND_TYPE_REG8, "r8" },
3016   { OPERAND_TYPE_REG16, "r16" },
3017   { OPERAND_TYPE_REG32, "r32" },
3018   { OPERAND_TYPE_REG64, "r64" },
3019   { OPERAND_TYPE_IMM8, "i8" },
3020   { OPERAND_TYPE_IMM8, "i8s" },
3021   { OPERAND_TYPE_IMM16, "i16" },
3022   { OPERAND_TYPE_IMM32, "i32" },
3023   { OPERAND_TYPE_IMM32S, "i32s" },
3024   { OPERAND_TYPE_IMM64, "i64" },
3025   { OPERAND_TYPE_IMM1, "i1" },
3026   { OPERAND_TYPE_BASEINDEX, "BaseIndex" },
3027   { OPERAND_TYPE_DISP8, "d8" },
3028   { OPERAND_TYPE_DISP16, "d16" },
3029   { OPERAND_TYPE_DISP32, "d32" },
3030   { OPERAND_TYPE_DISP32S, "d32s" },
3031   { OPERAND_TYPE_DISP64, "d64" },
3032   { OPERAND_TYPE_INOUTPORTREG, "InOutPortReg" },
3033   { OPERAND_TYPE_SHIFTCOUNT, "ShiftCount" },
3034   { OPERAND_TYPE_CONTROL, "control reg" },
3035   { OPERAND_TYPE_TEST, "test reg" },
3036   { OPERAND_TYPE_DEBUG, "debug reg" },
3037   { OPERAND_TYPE_FLOATREG, "FReg" },
3038   { OPERAND_TYPE_FLOATACC, "FAcc" },
3039   { OPERAND_TYPE_SREG2, "SReg2" },
3040   { OPERAND_TYPE_SREG3, "SReg3" },
3041   { OPERAND_TYPE_ACC, "Acc" },
3042   { OPERAND_TYPE_JUMPABSOLUTE, "Jump Absolute" },
3043   { OPERAND_TYPE_REGMMX, "rMMX" },
3044   { OPERAND_TYPE_REGXMM, "rXMM" },
3045   { OPERAND_TYPE_REGYMM, "rYMM" },
3046   { OPERAND_TYPE_REGZMM, "rZMM" },
3047   { OPERAND_TYPE_REGMASK, "Mask reg" },
3048   { OPERAND_TYPE_ESSEG, "es" },
3049 };
3050
3051 static void
3052 pt (i386_operand_type t)
3053 {
3054   unsigned int j;
3055   i386_operand_type a;
3056
3057   for (j = 0; j < ARRAY_SIZE (type_names); j++)
3058     {
3059       a = operand_type_and (t, type_names[j].mask);
3060       if (!operand_type_all_zero (&a))
3061         fprintf (stdout, "%s, ",  type_names[j].name);
3062     }
3063   fflush (stdout);
3064 }
3065
3066 #endif /* DEBUG386 */
3067 \f
3068 static bfd_reloc_code_real_type
3069 reloc (unsigned int size,
3070        int pcrel,
3071        int sign,
3072        bfd_reloc_code_real_type other)
3073 {
3074   if (other != NO_RELOC)
3075     {
3076       reloc_howto_type *rel;
3077
3078       if (size == 8)
3079         switch (other)
3080           {
3081           case BFD_RELOC_X86_64_GOT32:
3082             return BFD_RELOC_X86_64_GOT64;
3083             break;
3084           case BFD_RELOC_X86_64_GOTPLT64:
3085             return BFD_RELOC_X86_64_GOTPLT64;
3086             break;
3087           case BFD_RELOC_X86_64_PLTOFF64:
3088             return BFD_RELOC_X86_64_PLTOFF64;
3089             break;
3090           case BFD_RELOC_X86_64_GOTPC32:
3091             other = BFD_RELOC_X86_64_GOTPC64;
3092             break;
3093           case BFD_RELOC_X86_64_GOTPCREL:
3094             other = BFD_RELOC_X86_64_GOTPCREL64;
3095             break;
3096           case BFD_RELOC_X86_64_TPOFF32:
3097             other = BFD_RELOC_X86_64_TPOFF64;
3098             break;
3099           case BFD_RELOC_X86_64_DTPOFF32:
3100             other = BFD_RELOC_X86_64_DTPOFF64;
3101             break;
3102           default:
3103             break;
3104           }
3105
3106 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
3107       if (other == BFD_RELOC_SIZE32)
3108         {
3109           if (size == 8)
3110             other = BFD_RELOC_SIZE64;
3111           if (pcrel)
3112             {
3113               as_bad (_("there are no pc-relative size relocations"));
3114               return NO_RELOC;
3115             }
3116         }
3117 #endif
3118
3119       /* Sign-checking 4-byte relocations in 16-/32-bit code is pointless.  */
3120       if (size == 4 && (flag_code != CODE_64BIT || disallow_64bit_reloc))
3121         sign = -1;
3122
3123       rel = bfd_reloc_type_lookup (stdoutput, other);
3124       if (!rel)
3125         as_bad (_("unknown relocation (%u)"), other);
3126       else if (size != bfd_get_reloc_size (rel))
3127         as_bad (_("%u-byte relocation cannot be applied to %u-byte field"),
3128                 bfd_get_reloc_size (rel),
3129                 size);
3130       else if (pcrel && !rel->pc_relative)
3131         as_bad (_("non-pc-relative relocation for pc-relative field"));
3132       else if ((rel->complain_on_overflow == complain_overflow_signed
3133                 && !sign)
3134                || (rel->complain_on_overflow == complain_overflow_unsigned
3135                    && sign > 0))
3136         as_bad (_("relocated field and relocation type differ in signedness"));
3137       else
3138         return other;
3139       return NO_RELOC;
3140     }
3141
3142   if (pcrel)
3143     {
3144       if (!sign)
3145         as_bad (_("there are no unsigned pc-relative relocations"));
3146       switch (size)
3147         {
3148         case 1: return BFD_RELOC_8_PCREL;
3149         case 2: return BFD_RELOC_16_PCREL;
3150         case 4: return BFD_RELOC_32_PCREL;
3151         case 8: return BFD_RELOC_64_PCREL;
3152         }
3153       as_bad (_("cannot do %u byte pc-relative relocation"), size);
3154     }
3155   else
3156     {
3157       if (sign > 0)
3158         switch (size)
3159           {
3160           case 4: return BFD_RELOC_X86_64_32S;
3161           }
3162       else
3163         switch (size)
3164           {
3165           case 1: return BFD_RELOC_8;
3166           case 2: return BFD_RELOC_16;
3167           case 4: return BFD_RELOC_32;
3168           case 8: return BFD_RELOC_64;
3169           }
3170       as_bad (_("cannot do %s %u byte relocation"),
3171               sign > 0 ? "signed" : "unsigned", size);
3172     }
3173
3174   return NO_RELOC;
3175 }
3176
3177 /* Here we decide which fixups can be adjusted to make them relative to
3178    the beginning of the section instead of the symbol.  Basically we need
3179    to make sure that the dynamic relocations are done correctly, so in
3180    some cases we force the original symbol to be used.  */
3181
3182 int
3183 tc_i386_fix_adjustable (fixS *fixP ATTRIBUTE_UNUSED)
3184 {
3185 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
3186   if (!IS_ELF)
3187     return 1;
3188
3189   /* Don't adjust pc-relative references to merge sections in 64-bit
3190      mode.  */
3191   if (use_rela_relocations
3192       && (S_GET_SEGMENT (fixP->fx_addsy)->flags & SEC_MERGE) != 0
3193       && fixP->fx_pcrel)
3194     return 0;
3195
3196   /* The x86_64 GOTPCREL are represented as 32bit PCrel relocations
3197      and changed later by validate_fix.  */
3198   if (GOT_symbol && fixP->fx_subsy == GOT_symbol
3199       && fixP->fx_r_type == BFD_RELOC_32_PCREL)
3200     return 0;
3201
3202   /* Adjust_reloc_syms doesn't know about the GOT.  Need to keep symbol
3203      for size relocations.  */
3204   if (fixP->fx_r_type == BFD_RELOC_SIZE32
3205       || fixP->fx_r_type == BFD_RELOC_SIZE64
3206       || fixP->fx_r_type == BFD_RELOC_386_GOTOFF
3207       || fixP->fx_r_type == BFD_RELOC_386_PLT32
3208       || fixP->fx_r_type == BFD_RELOC_386_GOT32
3209       || fixP->fx_r_type == BFD_RELOC_386_GOT32X
3210       || fixP->fx_r_type == BFD_RELOC_386_TLS_GD
3211       || fixP->fx_r_type == BFD_RELOC_386_TLS_LDM
3212       || fixP->fx_r_type == BFD_RELOC_386_TLS_LDO_32
3213       || fixP->fx_r_type == BFD_RELOC_386_TLS_IE_32
3214       || fixP->fx_r_type == BFD_RELOC_386_TLS_IE
3215       || fixP->fx_r_type == BFD_RELOC_386_TLS_GOTIE
3216       || fixP->fx_r_type == BFD_RELOC_386_TLS_LE_32
3217       || fixP->fx_r_type == BFD_RELOC_386_TLS_LE
3218       || fixP->fx_r_type == BFD_RELOC_386_TLS_GOTDESC
3219       || fixP->fx_r_type == BFD_RELOC_386_TLS_DESC_CALL
3220       || fixP->fx_r_type == BFD_RELOC_X86_64_PLT32
3221       || fixP->fx_r_type == BFD_RELOC_X86_64_GOT32
3222       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTPCREL
3223       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTPCRELX
3224       || fixP->fx_r_type == BFD_RELOC_X86_64_REX_GOTPCRELX
3225       || fixP->fx_r_type == BFD_RELOC_X86_64_TLSGD
3226       || fixP->fx_r_type == BFD_RELOC_X86_64_TLSLD
3227       || fixP->fx_r_type == BFD_RELOC_X86_64_DTPOFF32
3228       || fixP->fx_r_type == BFD_RELOC_X86_64_DTPOFF64
3229       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTTPOFF
3230       || fixP->fx_r_type == BFD_RELOC_X86_64_TPOFF32
3231       || fixP->fx_r_type == BFD_RELOC_X86_64_TPOFF64
3232       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTOFF64
3233       || fixP->fx_r_type == BFD_RELOC_X86_64_GOTPC32_TLSDESC
3234       || fixP->fx_r_type == BFD_RELOC_X86_64_TLSDESC_CALL
3235       || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
3236       || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
3237     return 0;
3238 #endif
3239   return 1;
3240 }
3241
3242 static int
3243 intel_float_operand (const char *mnemonic)
3244 {
3245   /* Note that the value returned is meaningful only for opcodes with (memory)
3246      operands, hence the code here is free to improperly handle opcodes that
3247      have no operands (for better performance and smaller code). */
3248
3249   if (mnemonic[0] != 'f')
3250     return 0; /* non-math */
3251
3252   switch (mnemonic[1])
3253     {
3254     /* fclex, fdecstp, fdisi, femms, feni, fincstp, finit, fsetpm, and
3255        the fs segment override prefix not currently handled because no
3256        call path can make opcodes without operands get here */
3257     case 'i':
3258       return 2 /* integer op */;
3259     case 'l':
3260       if (mnemonic[2] == 'd' && (mnemonic[3] == 'c' || mnemonic[3] == 'e'))
3261         return 3; /* fldcw/fldenv */
3262       break;
3263     case 'n':
3264       if (mnemonic[2] != 'o' /* fnop */)
3265         return 3; /* non-waiting control op */
3266       break;
3267     case 'r':
3268       if (mnemonic[2] == 's')
3269         return 3; /* frstor/frstpm */
3270       break;
3271     case 's':
3272       if (mnemonic[2] == 'a')
3273         return 3; /* fsave */
3274       if (mnemonic[2] == 't')
3275         {
3276           switch (mnemonic[3])
3277             {
3278             case 'c': /* fstcw */
3279             case 'd': /* fstdw */
3280             case 'e': /* fstenv */
3281             case 's': /* fsts[gw] */
3282               return 3;
3283             }
3284         }
3285       break;
3286     case 'x':
3287       if (mnemonic[2] == 'r' || mnemonic[2] == 's')
3288         return 0; /* fxsave/fxrstor are not really math ops */
3289       break;
3290     }
3291
3292   return 1;
3293 }
3294
3295 /* Build the VEX prefix.  */
3296
3297 static void
3298 build_vex_prefix (const insn_template *t)
3299 {
3300   unsigned int register_specifier;
3301   unsigned int implied_prefix;
3302   unsigned int vector_length;
3303
3304   /* Check register specifier.  */
3305   if (i.vex.register_specifier)
3306     {
3307       register_specifier =
3308         ~register_number (i.vex.register_specifier) & 0xf;
3309       gas_assert ((i.vex.register_specifier->reg_flags & RegVRex) == 0);
3310     }
3311   else
3312     register_specifier = 0xf;
3313
3314   /* Use 2-byte VEX prefix by swapping destination and source
3315      operand.  */
3316   if (i.vec_encoding != vex_encoding_vex3
3317       && i.dir_encoding == dir_encoding_default
3318       && i.operands == i.reg_operands
3319       && i.tm.opcode_modifier.vexopcode == VEX0F
3320       && i.tm.opcode_modifier.load
3321       && i.rex == REX_B)
3322     {
3323       unsigned int xchg = i.operands - 1;
3324       union i386_op temp_op;
3325       i386_operand_type temp_type;
3326
3327       temp_type = i.types[xchg];
3328       i.types[xchg] = i.types[0];
3329       i.types[0] = temp_type;
3330       temp_op = i.op[xchg];
3331       i.op[xchg] = i.op[0];
3332       i.op[0] = temp_op;
3333
3334       gas_assert (i.rm.mode == 3);
3335
3336       i.rex = REX_R;
3337       xchg = i.rm.regmem;
3338       i.rm.regmem = i.rm.reg;
3339       i.rm.reg = xchg;
3340
3341       /* Use the next insn.  */
3342       i.tm = t[1];
3343     }
3344
3345   if (i.tm.opcode_modifier.vex == VEXScalar)
3346     vector_length = avxscalar;
3347   else if (i.tm.opcode_modifier.vex == VEX256)
3348     vector_length = 1;
3349   else
3350     {
3351       unsigned int op;
3352
3353       vector_length = 0;
3354       for (op = 0; op < t->operands; ++op)
3355         if (t->operand_types[op].bitfield.xmmword
3356             && t->operand_types[op].bitfield.ymmword
3357             && i.types[op].bitfield.ymmword)
3358           {
3359             vector_length = 1;
3360             break;
3361           }
3362     }
3363
3364   switch ((i.tm.base_opcode >> 8) & 0xff)
3365     {
3366     case 0:
3367       implied_prefix = 0;
3368       break;
3369     case DATA_PREFIX_OPCODE:
3370       implied_prefix = 1;
3371       break;
3372     case REPE_PREFIX_OPCODE:
3373       implied_prefix = 2;
3374       break;
3375     case REPNE_PREFIX_OPCODE:
3376       implied_prefix = 3;
3377       break;
3378     default:
3379       abort ();
3380     }
3381
3382   /* Use 2-byte VEX prefix if possible.  */
3383   if (i.vec_encoding != vex_encoding_vex3
3384       && i.tm.opcode_modifier.vexopcode == VEX0F
3385       && i.tm.opcode_modifier.vexw != VEXW1
3386       && (i.rex & (REX_W | REX_X | REX_B)) == 0)
3387     {
3388       /* 2-byte VEX prefix.  */
3389       unsigned int r;
3390
3391       i.vex.length = 2;
3392       i.vex.bytes[0] = 0xc5;
3393
3394       /* Check the REX.R bit.  */
3395       r = (i.rex & REX_R) ? 0 : 1;
3396       i.vex.bytes[1] = (r << 7
3397                         | register_specifier << 3
3398                         | vector_length << 2
3399                         | implied_prefix);
3400     }
3401   else
3402     {
3403       /* 3-byte VEX prefix.  */
3404       unsigned int m, w;
3405
3406       i.vex.length = 3;
3407
3408       switch (i.tm.opcode_modifier.vexopcode)
3409         {
3410         case VEX0F:
3411           m = 0x1;
3412           i.vex.bytes[0] = 0xc4;
3413           break;
3414         case VEX0F38:
3415           m = 0x2;
3416           i.vex.bytes[0] = 0xc4;
3417           break;
3418         case VEX0F3A:
3419           m = 0x3;
3420           i.vex.bytes[0] = 0xc4;
3421           break;
3422         case XOP08:
3423           m = 0x8;
3424           i.vex.bytes[0] = 0x8f;
3425           break;
3426         case XOP09:
3427           m = 0x9;
3428           i.vex.bytes[0] = 0x8f;
3429           break;
3430         case XOP0A:
3431           m = 0xa;
3432           i.vex.bytes[0] = 0x8f;
3433           break;
3434         default:
3435           abort ();
3436         }
3437
3438       /* The high 3 bits of the second VEX byte are 1's compliment
3439          of RXB bits from REX.  */
3440       i.vex.bytes[1] = (~i.rex & 0x7) << 5 | m;
3441
3442       /* Check the REX.W bit.  */
3443       w = (i.rex & REX_W) ? 1 : 0;
3444       if (i.tm.opcode_modifier.vexw == VEXW1)
3445         w = 1;
3446
3447       i.vex.bytes[2] = (w << 7
3448                         | register_specifier << 3
3449                         | vector_length << 2
3450                         | implied_prefix);
3451     }
3452 }
3453
3454 static INLINE bfd_boolean
3455 is_evex_encoding (const insn_template *t)
3456 {
3457   return t->opcode_modifier.evex
3458          || t->opcode_modifier.broadcast || t->opcode_modifier.masking
3459          || t->opcode_modifier.staticrounding || t->opcode_modifier.sae;
3460 }
3461
3462 /* Build the EVEX prefix.  */
3463
3464 static void
3465 build_evex_prefix (void)
3466 {
3467   unsigned int register_specifier;
3468   unsigned int implied_prefix;
3469   unsigned int m, w;
3470   rex_byte vrex_used = 0;
3471
3472   /* Check register specifier.  */
3473   if (i.vex.register_specifier)
3474     {
3475       gas_assert ((i.vrex & REX_X) == 0);
3476
3477       register_specifier = i.vex.register_specifier->reg_num;
3478       if ((i.vex.register_specifier->reg_flags & RegRex))
3479         register_specifier += 8;
3480       /* The upper 16 registers are encoded in the fourth byte of the
3481          EVEX prefix.  */
3482       if (!(i.vex.register_specifier->reg_flags & RegVRex))
3483         i.vex.bytes[3] = 0x8;
3484       register_specifier = ~register_specifier & 0xf;
3485     }
3486   else
3487     {
3488       register_specifier = 0xf;
3489
3490       /* Encode upper 16 vector index register in the fourth byte of
3491          the EVEX prefix.  */
3492       if (!(i.vrex & REX_X))
3493         i.vex.bytes[3] = 0x8;
3494       else
3495         vrex_used |= REX_X;
3496     }
3497
3498   switch ((i.tm.base_opcode >> 8) & 0xff)
3499     {
3500     case 0:
3501       implied_prefix = 0;
3502       break;
3503     case DATA_PREFIX_OPCODE:
3504       implied_prefix = 1;
3505       break;
3506     case REPE_PREFIX_OPCODE:
3507       implied_prefix = 2;
3508       break;
3509     case REPNE_PREFIX_OPCODE:
3510       implied_prefix = 3;
3511       break;
3512     default:
3513       abort ();
3514     }
3515
3516   /* 4 byte EVEX prefix.  */
3517   i.vex.length = 4;
3518   i.vex.bytes[0] = 0x62;
3519
3520   /* mmmm bits.  */
3521   switch (i.tm.opcode_modifier.vexopcode)
3522     {
3523     case VEX0F:
3524       m = 1;
3525       break;
3526     case VEX0F38:
3527       m = 2;
3528       break;
3529     case VEX0F3A:
3530       m = 3;
3531       break;
3532     default:
3533       abort ();
3534       break;
3535     }
3536
3537   /* The high 3 bits of the second EVEX byte are 1's compliment of RXB
3538      bits from REX.  */
3539   i.vex.bytes[1] = (~i.rex & 0x7) << 5 | m;
3540
3541   /* The fifth bit of the second EVEX byte is 1's compliment of the
3542      REX_R bit in VREX.  */
3543   if (!(i.vrex & REX_R))
3544     i.vex.bytes[1] |= 0x10;
3545   else
3546     vrex_used |= REX_R;
3547
3548   if ((i.reg_operands + i.imm_operands) == i.operands)
3549     {
3550       /* When all operands are registers, the REX_X bit in REX is not
3551          used.  We reuse it to encode the upper 16 registers, which is
3552          indicated by the REX_B bit in VREX.  The REX_X bit is encoded
3553          as 1's compliment.  */
3554       if ((i.vrex & REX_B))
3555         {
3556           vrex_used |= REX_B;
3557           i.vex.bytes[1] &= ~0x40;
3558         }
3559     }
3560
3561   /* EVEX instructions shouldn't need the REX prefix.  */
3562   i.vrex &= ~vrex_used;
3563   gas_assert (i.vrex == 0);
3564
3565   /* Check the REX.W bit.  */
3566   w = (i.rex & REX_W) ? 1 : 0;
3567   if (i.tm.opcode_modifier.vexw)
3568     {
3569       if (i.tm.opcode_modifier.vexw == VEXW1)
3570         w = 1;
3571     }
3572   /* If w is not set it means we are dealing with WIG instruction.  */
3573   else if (!w)
3574     {
3575       if (evexwig == evexw1)
3576         w = 1;
3577     }
3578
3579   /* Encode the U bit.  */
3580   implied_prefix |= 0x4;
3581
3582   /* The third byte of the EVEX prefix.  */
3583   i.vex.bytes[2] = (w << 7 | register_specifier << 3 | implied_prefix);
3584
3585   /* The fourth byte of the EVEX prefix.  */
3586   /* The zeroing-masking bit.  */
3587   if (i.mask && i.mask->zeroing)
3588     i.vex.bytes[3] |= 0x80;
3589
3590   /* Don't always set the broadcast bit if there is no RC.  */
3591   if (!i.rounding)
3592     {
3593       /* Encode the vector length.  */
3594       unsigned int vec_length;
3595
3596       if (!i.tm.opcode_modifier.evex
3597           || i.tm.opcode_modifier.evex == EVEXDYN)
3598         {
3599           unsigned int op;
3600
3601           vec_length = 0;
3602           for (op = 0; op < i.tm.operands; ++op)
3603             if (i.tm.operand_types[op].bitfield.xmmword
3604                 + i.tm.operand_types[op].bitfield.ymmword
3605                 + i.tm.operand_types[op].bitfield.zmmword > 1)
3606               {
3607                 if (i.types[op].bitfield.zmmword)
3608                   i.tm.opcode_modifier.evex = EVEX512;
3609                 else if (i.types[op].bitfield.ymmword)
3610                   i.tm.opcode_modifier.evex = EVEX256;
3611                 else if (i.types[op].bitfield.xmmword)
3612                   i.tm.opcode_modifier.evex = EVEX128;
3613                 else
3614                   continue;
3615                 break;
3616               }
3617         }
3618
3619       switch (i.tm.opcode_modifier.evex)
3620         {
3621         case EVEXLIG: /* LL' is ignored */
3622           vec_length = evexlig << 5;
3623           break;
3624         case EVEX128:
3625           vec_length = 0 << 5;
3626           break;
3627         case EVEX256:
3628           vec_length = 1 << 5;
3629           break;
3630         case EVEX512:
3631           vec_length = 2 << 5;
3632           break;
3633         default:
3634           abort ();
3635           break;
3636         }
3637       i.vex.bytes[3] |= vec_length;
3638       /* Encode the broadcast bit.  */
3639       if (i.broadcast)
3640         i.vex.bytes[3] |= 0x10;
3641     }
3642   else
3643     {
3644       if (i.rounding->type != saeonly)
3645         i.vex.bytes[3] |= 0x10 | (i.rounding->type << 5);
3646       else
3647         i.vex.bytes[3] |= 0x10 | (evexrcig << 5);
3648     }
3649
3650   if (i.mask && i.mask->mask)
3651     i.vex.bytes[3] |= i.mask->mask->reg_num;
3652 }
3653
3654 static void
3655 process_immext (void)
3656 {
3657   expressionS *exp;
3658
3659   if ((i.tm.cpu_flags.bitfield.cpusse3 || i.tm.cpu_flags.bitfield.cpusvme)
3660       && i.operands > 0)
3661     {
3662       /* MONITOR/MWAIT as well as SVME instructions have fixed operands
3663          with an opcode suffix which is coded in the same place as an
3664          8-bit immediate field would be.
3665          Here we check those operands and remove them afterwards.  */
3666       unsigned int x;
3667
3668       for (x = 0; x < i.operands; x++)
3669         if (register_number (i.op[x].regs) != x)
3670           as_bad (_("can't use register '%s%s' as operand %d in '%s'."),
3671                   register_prefix, i.op[x].regs->reg_name, x + 1,
3672                   i.tm.name);
3673
3674       i.operands = 0;
3675     }
3676
3677   if (i.tm.cpu_flags.bitfield.cpumwaitx && i.operands > 0)
3678     {
3679       /* MONITORX/MWAITX instructions have fixed operands with an opcode
3680          suffix which is coded in the same place as an 8-bit immediate
3681          field would be.
3682          Here we check those operands and remove them afterwards.  */
3683       unsigned int x;
3684
3685       if (i.operands != 3)
3686         abort();
3687
3688       for (x = 0; x < 2; x++)
3689         if (register_number (i.op[x].regs) != x)
3690           goto bad_register_operand;
3691
3692       /* Check for third operand for mwaitx/monitorx insn.  */
3693       if (register_number (i.op[x].regs)
3694           != (x + (i.tm.extension_opcode == 0xfb)))
3695         {
3696 bad_register_operand:
3697           as_bad (_("can't use register '%s%s' as operand %d in '%s'."),
3698                   register_prefix, i.op[x].regs->reg_name, x+1,
3699                   i.tm.name);
3700         }
3701
3702       i.operands = 0;
3703     }
3704
3705   /* These AMD 3DNow! and SSE2 instructions have an opcode suffix
3706      which is coded in the same place as an 8-bit immediate field
3707      would be.  Here we fake an 8-bit immediate operand from the
3708      opcode suffix stored in tm.extension_opcode.
3709
3710      AVX instructions also use this encoding, for some of
3711      3 argument instructions.  */
3712
3713   gas_assert (i.imm_operands <= 1
3714               && (i.operands <= 2
3715                   || ((i.tm.opcode_modifier.vex
3716                        || i.tm.opcode_modifier.vexopcode
3717                        || is_evex_encoding (&i.tm))
3718                       && i.operands <= 4)));
3719
3720   exp = &im_expressions[i.imm_operands++];
3721   i.op[i.operands].imms = exp;
3722   i.types[i.operands] = imm8;
3723   i.operands++;
3724   exp->X_op = O_constant;
3725   exp->X_add_number = i.tm.extension_opcode;
3726   i.tm.extension_opcode = None;
3727 }
3728
3729
3730 static int
3731 check_hle (void)
3732 {
3733   switch (i.tm.opcode_modifier.hleprefixok)
3734     {
3735     default:
3736       abort ();
3737     case HLEPrefixNone:
3738       as_bad (_("invalid instruction `%s' after `%s'"),
3739               i.tm.name, i.hle_prefix);
3740       return 0;
3741     case HLEPrefixLock:
3742       if (i.prefix[LOCK_PREFIX])
3743         return 1;
3744       as_bad (_("missing `lock' with `%s'"), i.hle_prefix);
3745       return 0;
3746     case HLEPrefixAny:
3747       return 1;
3748     case HLEPrefixRelease:
3749       if (i.prefix[HLE_PREFIX] != XRELEASE_PREFIX_OPCODE)
3750         {
3751           as_bad (_("instruction `%s' after `xacquire' not allowed"),
3752                   i.tm.name);
3753           return 0;
3754         }
3755       if (i.mem_operands == 0
3756           || !operand_type_check (i.types[i.operands - 1], anymem))
3757         {
3758           as_bad (_("memory destination needed for instruction `%s'"
3759                     " after `xrelease'"), i.tm.name);
3760           return 0;
3761         }
3762       return 1;
3763     }
3764 }
3765
3766 /* Try the shortest encoding by shortening operand size.  */
3767
3768 static void
3769 optimize_encoding (void)
3770 {
3771   int j;
3772
3773   if (optimize_for_space
3774       && i.reg_operands == 1
3775       && i.imm_operands == 1
3776       && !i.types[1].bitfield.byte
3777       && i.op[0].imms->X_op == O_constant
3778       && fits_in_imm7 (i.op[0].imms->X_add_number)
3779       && ((i.tm.base_opcode == 0xa8
3780            && i.tm.extension_opcode == None)
3781           || (i.tm.base_opcode == 0xf6
3782               && i.tm.extension_opcode == 0x0)))
3783     {
3784       /* Optimize: -Os:
3785            test $imm7, %r64/%r32/%r16  -> test $imm7, %r8
3786        */
3787       unsigned int base_regnum = i.op[1].regs->reg_num;
3788       if (flag_code == CODE_64BIT || base_regnum < 4)
3789         {
3790           i.types[1].bitfield.byte = 1;
3791           /* Ignore the suffix.  */
3792           i.suffix = 0;
3793           if (base_regnum >= 4
3794               && !(i.op[1].regs->reg_flags & RegRex))
3795             {
3796               /* Handle SP, BP, SI and DI registers.  */
3797               if (i.types[1].bitfield.word)
3798                 j = 16;
3799               else if (i.types[1].bitfield.dword)
3800                 j = 32;
3801               else
3802                 j = 48;
3803               i.op[1].regs -= j;
3804             }
3805         }
3806     }
3807   else if (flag_code == CODE_64BIT
3808            && ((i.types[1].bitfield.qword
3809                 && i.reg_operands == 1
3810                 && i.imm_operands == 1
3811                 && i.op[0].imms->X_op == O_constant
3812                 && ((i.tm.base_opcode == 0xb0
3813                      && i.tm.extension_opcode == None
3814                      && fits_in_unsigned_long (i.op[0].imms->X_add_number))
3815                     || (fits_in_imm31 (i.op[0].imms->X_add_number)
3816                         && (((i.tm.base_opcode == 0x24
3817                               || i.tm.base_opcode == 0xa8)
3818                              && i.tm.extension_opcode == None)
3819                             || (i.tm.base_opcode == 0x80
3820                                 && i.tm.extension_opcode == 0x4)
3821                             || ((i.tm.base_opcode == 0xf6
3822                                  || i.tm.base_opcode == 0xc6)
3823                                 && i.tm.extension_opcode == 0x0)))))
3824                || (i.types[0].bitfield.qword
3825                    && ((i.reg_operands == 2
3826                         && i.op[0].regs == i.op[1].regs
3827                         && ((i.tm.base_opcode == 0x30
3828                              || i.tm.base_opcode == 0x28)
3829                             && i.tm.extension_opcode == None))
3830                        || (i.reg_operands == 1
3831                            && i.operands == 1
3832                            && i.tm.base_opcode == 0x30
3833                            && i.tm.extension_opcode == None)))))
3834     {
3835       /* Optimize: -O:
3836            andq $imm31, %r64   -> andl $imm31, %r32
3837            testq $imm31, %r64  -> testl $imm31, %r32
3838            xorq %r64, %r64     -> xorl %r32, %r32
3839            subq %r64, %r64     -> subl %r32, %r32
3840            movq $imm31, %r64   -> movl $imm31, %r32
3841            movq $imm32, %r64   -> movl $imm32, %r32
3842         */
3843       i.tm.opcode_modifier.norex64 = 1;
3844       if (i.tm.base_opcode == 0xb0 || i.tm.base_opcode == 0xc6)
3845         {
3846           /* Handle
3847                movq $imm31, %r64   -> movl $imm31, %r32
3848                movq $imm32, %r64   -> movl $imm32, %r32
3849            */
3850           i.tm.operand_types[0].bitfield.imm32 = 1;
3851           i.tm.operand_types[0].bitfield.imm32s = 0;
3852           i.tm.operand_types[0].bitfield.imm64 = 0;
3853           i.types[0].bitfield.imm32 = 1;
3854           i.types[0].bitfield.imm32s = 0;
3855           i.types[0].bitfield.imm64 = 0;
3856           i.types[1].bitfield.dword = 1;
3857           i.types[1].bitfield.qword = 0;
3858           if (i.tm.base_opcode == 0xc6)
3859             {
3860               /* Handle
3861                    movq $imm31, %r64   -> movl $imm31, %r32
3862                */
3863               i.tm.base_opcode = 0xb0;
3864               i.tm.extension_opcode = None;
3865               i.tm.opcode_modifier.shortform = 1;
3866               i.tm.opcode_modifier.modrm = 0;
3867             }
3868         }
3869     }
3870   else if (optimize > 1
3871            && i.reg_operands == 3
3872            && i.op[0].regs == i.op[1].regs
3873            && !i.types[2].bitfield.xmmword
3874            && (i.tm.opcode_modifier.vex
3875                || (!i.mask
3876                    && !i.rounding
3877                    && is_evex_encoding (&i.tm)
3878                    && (i.tm.cpu_flags.bitfield.cpuavx512vl
3879                        || cpu_arch_isa_flags.bitfield.cpuavx512vl)))
3880            && ((i.tm.base_opcode == 0x55
3881                 || i.tm.base_opcode == 0x6655
3882                 || i.tm.base_opcode == 0x66df
3883                 || i.tm.base_opcode == 0x57
3884                 || i.tm.base_opcode == 0x6657
3885                 || i.tm.base_opcode == 0x66ef
3886                 || i.tm.base_opcode == 0x66f8
3887                 || i.tm.base_opcode == 0x66f9
3888                 || i.tm.base_opcode == 0x66fa
3889                 || i.tm.base_opcode == 0x66fb)
3890                && i.tm.extension_opcode == None))
3891     {
3892       /* Optimize: -O2:
3893            VOP, one of vandnps, vandnpd, vxorps, vxorpd, vpsubb, vpsubd,
3894            vpsubq and vpsubw:
3895              EVEX VOP %zmmM, %zmmM, %zmmN
3896                -> VEX VOP %xmmM, %xmmM, %xmmN (M and N < 16)
3897                -> EVEX VOP %xmmM, %xmmM, %xmmN (M || N >= 16)
3898              EVEX VOP %ymmM, %ymmM, %ymmN
3899                -> VEX VOP %xmmM, %xmmM, %xmmN (M and N < 16)
3900                -> EVEX VOP %xmmM, %xmmM, %xmmN (M || N >= 16)
3901              VEX VOP %ymmM, %ymmM, %ymmN
3902                -> VEX VOP %xmmM, %xmmM, %xmmN
3903            VOP, one of vpandn and vpxor:
3904              VEX VOP %ymmM, %ymmM, %ymmN
3905                -> VEX VOP %xmmM, %xmmM, %xmmN
3906            VOP, one of vpandnd and vpandnq:
3907              EVEX VOP %zmmM, %zmmM, %zmmN
3908                -> VEX vpandn %xmmM, %xmmM, %xmmN (M and N < 16)
3909                -> EVEX VOP %xmmM, %xmmM, %xmmN (M || N >= 16)
3910              EVEX VOP %ymmM, %ymmM, %ymmN
3911                -> VEX vpandn %xmmM, %xmmM, %xmmN (M and N < 16)
3912                -> EVEX VOP %xmmM, %xmmM, %xmmN (M || N >= 16)
3913            VOP, one of vpxord and vpxorq:
3914              EVEX VOP %zmmM, %zmmM, %zmmN
3915                -> VEX vpxor %xmmM, %xmmM, %xmmN (M and N < 16)
3916                -> EVEX VOP %xmmM, %xmmM, %xmmN (M || N >= 16)
3917              EVEX VOP %ymmM, %ymmM, %ymmN
3918                -> VEX vpxor %xmmM, %xmmM, %xmmN (M and N < 16)
3919                -> EVEX VOP %xmmM, %xmmM, %xmmN (M || N >= 16)
3920        */
3921       if (is_evex_encoding (&i.tm))
3922         {
3923           if (i.vec_encoding == vex_encoding_evex)
3924             i.tm.opcode_modifier.evex = EVEX128;
3925           else
3926             {
3927               i.tm.opcode_modifier.vex = VEX128;
3928               i.tm.opcode_modifier.vexw = VEXW0;
3929               i.tm.opcode_modifier.evex = 0;
3930             }
3931         }
3932       else
3933         i.tm.opcode_modifier.vex = VEX128;
3934
3935       if (i.tm.opcode_modifier.vex)
3936         for (j = 0; j < 3; j++)
3937           {
3938             i.types[j].bitfield.xmmword = 1;
3939             i.types[j].bitfield.ymmword = 0;
3940           }
3941     }
3942 }
3943
3944 /* This is the guts of the machine-dependent assembler.  LINE points to a
3945    machine dependent instruction.  This function is supposed to emit
3946    the frags/bytes it assembles to.  */
3947
3948 void
3949 md_assemble (char *line)
3950 {
3951   unsigned int j;
3952   char mnemonic[MAX_MNEM_SIZE], mnem_suffix;
3953   const insn_template *t;
3954
3955   /* Initialize globals.  */
3956   memset (&i, '\0', sizeof (i));
3957   for (j = 0; j < MAX_OPERANDS; j++)
3958     i.reloc[j] = NO_RELOC;
3959   memset (disp_expressions, '\0', sizeof (disp_expressions));
3960   memset (im_expressions, '\0', sizeof (im_expressions));
3961   save_stack_p = save_stack;
3962
3963   /* First parse an instruction mnemonic & call i386_operand for the operands.
3964      We assume that the scrubber has arranged it so that line[0] is the valid
3965      start of a (possibly prefixed) mnemonic.  */
3966
3967   line = parse_insn (line, mnemonic);
3968   if (line == NULL)
3969     return;
3970   mnem_suffix = i.suffix;
3971
3972   line = parse_operands (line, mnemonic);
3973   this_operand = -1;
3974   xfree (i.memop1_string);
3975   i.memop1_string = NULL;
3976   if (line == NULL)
3977     return;
3978
3979   /* Now we've parsed the mnemonic into a set of templates, and have the
3980      operands at hand.  */
3981
3982   /* All intel opcodes have reversed operands except for "bound" and
3983      "enter".  We also don't reverse intersegment "jmp" and "call"
3984      instructions with 2 immediate operands so that the immediate segment
3985      precedes the offset, as it does when in AT&T mode. */
3986   if (intel_syntax
3987       && i.operands > 1
3988       && (strcmp (mnemonic, "bound") != 0)
3989       && (strcmp (mnemonic, "invlpga") != 0)
3990       && !(operand_type_check (i.types[0], imm)
3991            && operand_type_check (i.types[1], imm)))
3992     swap_operands ();
3993
3994   /* The order of the immediates should be reversed
3995      for 2 immediates extrq and insertq instructions */
3996   if (i.imm_operands == 2
3997       && (strcmp (mnemonic, "extrq") == 0
3998           || strcmp (mnemonic, "insertq") == 0))
3999       swap_2_operands (0, 1);
4000
4001   if (i.imm_operands)
4002     optimize_imm ();
4003
4004   /* Don't optimize displacement for movabs since it only takes 64bit
4005      displacement.  */
4006   if (i.disp_operands
4007       && i.disp_encoding != disp_encoding_32bit
4008       && (flag_code != CODE_64BIT
4009           || strcmp (mnemonic, "movabs") != 0))
4010     optimize_disp ();
4011
4012   /* Next, we find a template that matches the given insn,
4013      making sure the overlap of the given operands types is consistent
4014      with the template operand types.  */
4015
4016   if (!(t = match_template (mnem_suffix)))
4017     return;
4018
4019   if (sse_check != check_none
4020       && !i.tm.opcode_modifier.noavx
4021       && !i.tm.cpu_flags.bitfield.cpuavx
4022       && (i.tm.cpu_flags.bitfield.cpusse
4023           || i.tm.cpu_flags.bitfield.cpusse2
4024           || i.tm.cpu_flags.bitfield.cpusse3
4025           || i.tm.cpu_flags.bitfield.cpussse3
4026           || i.tm.cpu_flags.bitfield.cpusse4_1
4027           || i.tm.cpu_flags.bitfield.cpusse4_2
4028           || i.tm.cpu_flags.bitfield.cpupclmul
4029           || i.tm.cpu_flags.bitfield.cpuaes
4030           || i.tm.cpu_flags.bitfield.cpugfni))
4031     {
4032       (sse_check == check_warning
4033        ? as_warn
4034        : as_bad) (_("SSE instruction `%s' is used"), i.tm.name);
4035     }
4036
4037   /* Zap movzx and movsx suffix.  The suffix has been set from
4038      "word ptr" or "byte ptr" on the source operand in Intel syntax
4039      or extracted from mnemonic in AT&T syntax.  But we'll use
4040      the destination register to choose the suffix for encoding.  */
4041   if ((i.tm.base_opcode & ~9) == 0x0fb6)
4042     {
4043       /* In Intel syntax, there must be a suffix.  In AT&T syntax, if
4044          there is no suffix, the default will be byte extension.  */
4045       if (i.reg_operands != 2
4046           && !i.suffix
4047           && intel_syntax)
4048         as_bad (_("ambiguous operand size for `%s'"), i.tm.name);
4049
4050       i.suffix = 0;
4051     }
4052
4053   if (i.tm.opcode_modifier.fwait)
4054     if (!add_prefix (FWAIT_OPCODE))
4055       return;
4056
4057   /* Check if REP prefix is OK.  */
4058   if (i.rep_prefix && !i.tm.opcode_modifier.repprefixok)
4059     {
4060       as_bad (_("invalid instruction `%s' after `%s'"),
4061                 i.tm.name, i.rep_prefix);
4062       return;
4063     }
4064
4065   /* Check for lock without a lockable instruction.  Destination operand
4066      must be memory unless it is xchg (0x86).  */
4067   if (i.prefix[LOCK_PREFIX]
4068       && (!i.tm.opcode_modifier.islockable
4069           || i.mem_operands == 0
4070           || (i.tm.base_opcode != 0x86
4071               && !operand_type_check (i.types[i.operands - 1], anymem))))
4072     {
4073       as_bad (_("expecting lockable instruction after `lock'"));
4074       return;
4075     }
4076
4077   /* Check if HLE prefix is OK.  */
4078   if (i.hle_prefix && !check_hle ())
4079     return;
4080
4081   /* Check BND prefix.  */
4082   if (i.bnd_prefix && !i.tm.opcode_modifier.bndprefixok)
4083     as_bad (_("expecting valid branch instruction after `bnd'"));
4084
4085   /* Check NOTRACK prefix.  */
4086   if (i.notrack_prefix && !i.tm.opcode_modifier.notrackprefixok)
4087     as_bad (_("expecting indirect branch instruction after `notrack'"));
4088
4089   if (i.tm.cpu_flags.bitfield.cpumpx)
4090     {
4091       if (flag_code == CODE_64BIT && i.prefix[ADDR_PREFIX])
4092         as_bad (_("32-bit address isn't allowed in 64-bit MPX instructions."));
4093       else if (flag_code != CODE_16BIT
4094                ? i.prefix[ADDR_PREFIX]
4095                : i.mem_operands && !i.prefix[ADDR_PREFIX])
4096         as_bad (_("16-bit address isn't allowed in MPX instructions"));
4097     }
4098
4099   /* Insert BND prefix.  */
4100   if (add_bnd_prefix
4101       && i.tm.opcode_modifier.bndprefixok
4102       && !i.prefix[BND_PREFIX])
4103     add_prefix (BND_PREFIX_OPCODE);
4104
4105   /* Check string instruction segment overrides.  */
4106   if (i.tm.opcode_modifier.isstring && i.mem_operands != 0)
4107     {
4108       if (!check_string ())
4109         return;
4110       i.disp_operands = 0;
4111     }
4112
4113   if (optimize && !i.no_optimize && i.tm.opcode_modifier.optimize)
4114     optimize_encoding ();
4115
4116   if (!process_suffix ())
4117     return;
4118
4119   /* Update operand types.  */
4120   for (j = 0; j < i.operands; j++)
4121     i.types[j] = operand_type_and (i.types[j], i.tm.operand_types[j]);
4122
4123   /* Make still unresolved immediate matches conform to size of immediate
4124      given in i.suffix.  */
4125   if (!finalize_imm ())
4126     return;
4127
4128   if (i.types[0].bitfield.imm1)
4129     i.imm_operands = 0; /* kludge for shift insns.  */
4130
4131   /* We only need to check those implicit registers for instructions
4132      with 3 operands or less.  */
4133   if (i.operands <= 3)
4134     for (j = 0; j < i.operands; j++)
4135       if (i.types[j].bitfield.inoutportreg
4136           || i.types[j].bitfield.shiftcount
4137           || (i.types[j].bitfield.acc && !i.types[j].bitfield.xmmword))
4138         i.reg_operands--;
4139
4140   /* ImmExt should be processed after SSE2AVX.  */
4141   if (!i.tm.opcode_modifier.sse2avx
4142       && i.tm.opcode_modifier.immext)
4143     process_immext ();
4144
4145   /* For insns with operands there are more diddles to do to the opcode.  */
4146   if (i.operands)
4147     {
4148       if (!process_operands ())
4149         return;
4150     }
4151   else if (!quiet_warnings && i.tm.opcode_modifier.ugh)
4152     {
4153       /* UnixWare fsub no args is alias for fsubp, fadd -> faddp, etc.  */
4154       as_warn (_("translating to `%sp'"), i.tm.name);
4155     }
4156
4157   if (i.tm.opcode_modifier.vex || i.tm.opcode_modifier.vexopcode
4158       || is_evex_encoding (&i.tm))
4159     {
4160       if (flag_code == CODE_16BIT)
4161         {
4162           as_bad (_("instruction `%s' isn't supported in 16-bit mode."),
4163                   i.tm.name);
4164           return;
4165         }
4166
4167       if (i.tm.opcode_modifier.vex)
4168         build_vex_prefix (t);
4169       else
4170         build_evex_prefix ();
4171     }
4172
4173   /* Handle conversion of 'int $3' --> special int3 insn.  XOP or FMA4
4174      instructions may define INT_OPCODE as well, so avoid this corner
4175      case for those instructions that use MODRM.  */
4176   if (i.tm.base_opcode == INT_OPCODE
4177       && !i.tm.opcode_modifier.modrm
4178       && i.op[0].imms->X_add_number == 3)
4179     {
4180       i.tm.base_opcode = INT3_OPCODE;
4181       i.imm_operands = 0;
4182     }
4183
4184   if ((i.tm.opcode_modifier.jump
4185        || i.tm.opcode_modifier.jumpbyte
4186        || i.tm.opcode_modifier.jumpdword)
4187       && i.op[0].disps->X_op == O_constant)
4188     {
4189       /* Convert "jmp constant" (and "call constant") to a jump (call) to
4190          the absolute address given by the constant.  Since ix86 jumps and
4191          calls are pc relative, we need to generate a reloc.  */
4192       i.op[0].disps->X_add_symbol = &abs_symbol;
4193       i.op[0].disps->X_op = O_symbol;
4194     }
4195
4196   if (i.tm.opcode_modifier.rex64)
4197     i.rex |= REX_W;
4198
4199   /* For 8 bit registers we need an empty rex prefix.  Also if the
4200      instruction already has a prefix, we need to convert old
4201      registers to new ones.  */
4202
4203   if ((i.types[0].bitfield.reg && i.types[0].bitfield.byte
4204        && (i.op[0].regs->reg_flags & RegRex64) != 0)
4205       || (i.types[1].bitfield.reg && i.types[1].bitfield.byte
4206           && (i.op[1].regs->reg_flags & RegRex64) != 0)
4207       || (((i.types[0].bitfield.reg && i.types[0].bitfield.byte)
4208            || (i.types[1].bitfield.reg && i.types[1].bitfield.byte))
4209           && i.rex != 0))
4210     {
4211       int x;
4212
4213       i.rex |= REX_OPCODE;
4214       for (x = 0; x < 2; x++)
4215         {
4216           /* Look for 8 bit operand that uses old registers.  */
4217           if (i.types[x].bitfield.reg && i.types[x].bitfield.byte
4218               && (i.op[x].regs->reg_flags & RegRex64) == 0)
4219             {
4220               /* In case it is "hi" register, give up.  */
4221               if (i.op[x].regs->reg_num > 3)
4222                 as_bad (_("can't encode register '%s%s' in an "
4223                           "instruction requiring REX prefix."),
4224                         register_prefix, i.op[x].regs->reg_name);
4225
4226               /* Otherwise it is equivalent to the extended register.
4227                  Since the encoding doesn't change this is merely
4228                  cosmetic cleanup for debug output.  */
4229
4230               i.op[x].regs = i.op[x].regs + 8;
4231             }
4232         }
4233     }
4234
4235   if (i.rex == 0 && i.rex_encoding)
4236     {
4237       /* Check if we can add a REX_OPCODE byte.  Look for 8 bit operand
4238          that uses legacy register.  If it is "hi" register, don't add
4239          the REX_OPCODE byte.  */
4240       int x;
4241       for (x = 0; x < 2; x++)
4242         if (i.types[x].bitfield.reg
4243             && i.types[x].bitfield.byte
4244             && (i.op[x].regs->reg_flags & RegRex64) == 0
4245             && i.op[x].regs->reg_num > 3)
4246           {
4247             i.rex_encoding = FALSE;
4248             break;
4249           }
4250
4251       if (i.rex_encoding)
4252         i.rex = REX_OPCODE;
4253     }
4254
4255   if (i.rex != 0)
4256     add_prefix (REX_OPCODE | i.rex);
4257
4258   /* We are ready to output the insn.  */
4259   output_insn ();
4260 }
4261
4262 static char *
4263 parse_insn (char *line, char *mnemonic)
4264 {
4265   char *l = line;
4266   char *token_start = l;
4267   char *mnem_p;
4268   int supported;
4269   const insn_template *t;
4270   char *dot_p = NULL;
4271
4272   while (1)
4273     {
4274       mnem_p = mnemonic;
4275       while ((*mnem_p = mnemonic_chars[(unsigned char) *l]) != 0)
4276         {
4277           if (*mnem_p == '.')
4278             dot_p = mnem_p;
4279           mnem_p++;
4280           if (mnem_p >= mnemonic + MAX_MNEM_SIZE)
4281             {
4282               as_bad (_("no such instruction: `%s'"), token_start);
4283               return NULL;
4284             }
4285           l++;
4286         }
4287       if (!is_space_char (*l)
4288           && *l != END_OF_INSN
4289           && (intel_syntax
4290               || (*l != PREFIX_SEPARATOR
4291                   && *l != ',')))
4292         {
4293           as_bad (_("invalid character %s in mnemonic"),
4294                   output_invalid (*l));
4295           return NULL;
4296         }
4297       if (token_start == l)
4298         {
4299           if (!intel_syntax && *l == PREFIX_SEPARATOR)
4300             as_bad (_("expecting prefix; got nothing"));
4301           else
4302             as_bad (_("expecting mnemonic; got nothing"));
4303           return NULL;
4304         }
4305
4306       /* Look up instruction (or prefix) via hash table.  */
4307       current_templates = (const templates *) hash_find (op_hash, mnemonic);
4308
4309       if (*l != END_OF_INSN
4310           && (!is_space_char (*l) || l[1] != END_OF_INSN)
4311           && current_templates
4312           && current_templates->start->opcode_modifier.isprefix)
4313         {
4314           if (!cpu_flags_check_cpu64 (current_templates->start->cpu_flags))
4315             {
4316               as_bad ((flag_code != CODE_64BIT
4317                        ? _("`%s' is only supported in 64-bit mode")
4318                        : _("`%s' is not supported in 64-bit mode")),
4319                       current_templates->start->name);
4320               return NULL;
4321             }
4322           /* If we are in 16-bit mode, do not allow addr16 or data16.
4323              Similarly, in 32-bit mode, do not allow addr32 or data32.  */
4324           if ((current_templates->start->opcode_modifier.size16
4325                || current_templates->start->opcode_modifier.size32)
4326               && flag_code != CODE_64BIT
4327               && (current_templates->start->opcode_modifier.size32
4328                   ^ (flag_code == CODE_16BIT)))
4329             {
4330               as_bad (_("redundant %s prefix"),
4331                       current_templates->start->name);
4332               return NULL;
4333             }
4334           if (current_templates->start->opcode_length == 0)
4335             {
4336               /* Handle pseudo prefixes.  */
4337               switch (current_templates->start->base_opcode)
4338                 {
4339                 case 0x0:
4340                   /* {disp8} */
4341                   i.disp_encoding = disp_encoding_8bit;
4342                   break;
4343                 case 0x1:
4344                   /* {disp32} */
4345                   i.disp_encoding = disp_encoding_32bit;
4346                   break;
4347                 case 0x2:
4348                   /* {load} */
4349                   i.dir_encoding = dir_encoding_load;
4350                   break;
4351                 case 0x3:
4352                   /* {store} */
4353                   i.dir_encoding = dir_encoding_store;
4354                   break;
4355                 case 0x4:
4356                   /* {vex2} */
4357                   i.vec_encoding = vex_encoding_vex2;
4358                   break;
4359                 case 0x5:
4360                   /* {vex3} */
4361                   i.vec_encoding = vex_encoding_vex3;
4362                   break;
4363                 case 0x6:
4364                   /* {evex} */
4365                   i.vec_encoding = vex_encoding_evex;
4366                   break;
4367                 case 0x7:
4368                   /* {rex} */
4369                   i.rex_encoding = TRUE;
4370                   break;
4371                 case 0x8:
4372                   /* {nooptimize} */
4373                   i.no_optimize = TRUE;
4374                   break;
4375                 default:
4376                   abort ();
4377                 }
4378             }
4379           else
4380             {
4381               /* Add prefix, checking for repeated prefixes.  */
4382               switch (add_prefix (current_templates->start->base_opcode))
4383                 {
4384                 case PREFIX_EXIST:
4385                   return NULL;
4386                 case PREFIX_DS:
4387                   if (current_templates->start->cpu_flags.bitfield.cpuibt)
4388                     i.notrack_prefix = current_templates->start->name;
4389                   break;
4390                 case PREFIX_REP:
4391                   if (current_templates->start->cpu_flags.bitfield.cpuhle)
4392                     i.hle_prefix = current_templates->start->name;
4393                   else if (current_templates->start->cpu_flags.bitfield.cpumpx)
4394                     i.bnd_prefix = current_templates->start->name;
4395                   else
4396                     i.rep_prefix = current_templates->start->name;
4397                   break;
4398                 default:
4399                   break;
4400                 }
4401             }
4402           /* Skip past PREFIX_SEPARATOR and reset token_start.  */
4403           token_start = ++l;
4404         }
4405       else
4406         break;
4407     }
4408
4409   if (!current_templates)
4410     {
4411       /* Check if we should swap operand or force 32bit displacement in
4412          encoding.  */
4413       if (mnem_p - 2 == dot_p && dot_p[1] == 's')
4414         i.dir_encoding = dir_encoding_store;
4415       else if (mnem_p - 3 == dot_p
4416                && dot_p[1] == 'd'
4417                && dot_p[2] == '8')
4418         i.disp_encoding = disp_encoding_8bit;
4419       else if (mnem_p - 4 == dot_p
4420                && dot_p[1] == 'd'
4421                && dot_p[2] == '3'
4422                && dot_p[3] == '2')
4423         i.disp_encoding = disp_encoding_32bit;
4424       else
4425         goto check_suffix;
4426       mnem_p = dot_p;
4427       *dot_p = '\0';
4428       current_templates = (const templates *) hash_find (op_hash, mnemonic);
4429     }
4430
4431   if (!current_templates)
4432     {
4433 check_suffix:
4434       /* See if we can get a match by trimming off a suffix.  */
4435       switch (mnem_p[-1])
4436         {
4437         case WORD_MNEM_SUFFIX:
4438           if (intel_syntax && (intel_float_operand (mnemonic) & 2))
4439             i.suffix = SHORT_MNEM_SUFFIX;
4440           else
4441             /* Fall through.  */
4442         case BYTE_MNEM_SUFFIX:
4443         case QWORD_MNEM_SUFFIX:
4444           i.suffix = mnem_p[-1];
4445           mnem_p[-1] = '\0';
4446           current_templates = (const templates *) hash_find (op_hash,
4447                                                              mnemonic);
4448           break;
4449         case SHORT_MNEM_SUFFIX:
4450         case LONG_MNEM_SUFFIX:
4451           if (!intel_syntax)
4452             {
4453               i.suffix = mnem_p[-1];
4454               mnem_p[-1] = '\0';
4455               current_templates = (const templates *) hash_find (op_hash,
4456                                                                  mnemonic);
4457             }
4458           break;
4459
4460           /* Intel Syntax.  */
4461         case 'd':
4462           if (intel_syntax)
4463             {
4464               if (intel_float_operand (mnemonic) == 1)
4465                 i.suffix = SHORT_MNEM_SUFFIX;
4466               else
4467                 i.suffix = LONG_MNEM_SUFFIX;
4468               mnem_p[-1] = '\0';
4469               current_templates = (const templates *) hash_find (op_hash,
4470                                                                  mnemonic);
4471             }
4472           break;
4473         }
4474       if (!current_templates)
4475         {
4476           as_bad (_("no such instruction: `%s'"), token_start);
4477           return NULL;
4478         }
4479     }
4480
4481   if (current_templates->start->opcode_modifier.jump
4482       || current_templates->start->opcode_modifier.jumpbyte)
4483     {
4484       /* Check for a branch hint.  We allow ",pt" and ",pn" for
4485          predict taken and predict not taken respectively.
4486          I'm not sure that branch hints actually do anything on loop
4487          and jcxz insns (JumpByte) for current Pentium4 chips.  They
4488          may work in the future and it doesn't hurt to accept them
4489          now.  */
4490       if (l[0] == ',' && l[1] == 'p')
4491         {
4492           if (l[2] == 't')
4493             {
4494               if (!add_prefix (DS_PREFIX_OPCODE))
4495                 return NULL;
4496               l += 3;
4497             }
4498           else if (l[2] == 'n')
4499             {
4500               if (!add_prefix (CS_PREFIX_OPCODE))
4501                 return NULL;
4502               l += 3;
4503             }
4504         }
4505     }
4506   /* Any other comma loses.  */
4507   if (*l == ',')
4508     {
4509       as_bad (_("invalid character %s in mnemonic"),
4510               output_invalid (*l));
4511       return NULL;
4512     }
4513
4514   /* Check if instruction is supported on specified architecture.  */
4515   supported = 0;
4516   for (t = current_templates->start; t < current_templates->end; ++t)
4517     {
4518       supported |= cpu_flags_match (t);
4519       if (supported == CPU_FLAGS_PERFECT_MATCH)
4520         {
4521           if (!cpu_arch_flags.bitfield.cpui386 && (flag_code != CODE_16BIT))
4522             as_warn (_("use .code16 to ensure correct addressing mode"));
4523
4524           return l;
4525         }
4526     }
4527
4528   if (!(supported & CPU_FLAGS_64BIT_MATCH))
4529     as_bad (flag_code == CODE_64BIT
4530             ? _("`%s' is not supported in 64-bit mode")
4531             : _("`%s' is only supported in 64-bit mode"),
4532             current_templates->start->name);
4533   else
4534     as_bad (_("`%s' is not supported on `%s%s'"),
4535             current_templates->start->name,
4536             cpu_arch_name ? cpu_arch_name : default_arch,
4537             cpu_sub_arch_name ? cpu_sub_arch_name : "");
4538
4539   return NULL;
4540 }
4541
4542 static char *
4543 parse_operands (char *l, const char *mnemonic)
4544 {
4545   char *token_start;
4546
4547   /* 1 if operand is pending after ','.  */
4548   unsigned int expecting_operand = 0;
4549
4550   /* Non-zero if operand parens not balanced.  */
4551   unsigned int paren_not_balanced;
4552
4553   while (*l != END_OF_INSN)
4554     {
4555       /* Skip optional white space before operand.  */
4556       if (is_space_char (*l))
4557         ++l;
4558       if (!is_operand_char (*l) && *l != END_OF_INSN && *l != '"')
4559         {
4560           as_bad (_("invalid character %s before operand %d"),
4561                   output_invalid (*l),
4562                   i.operands + 1);
4563           return NULL;
4564         }
4565       token_start = l;  /* After white space.  */
4566       paren_not_balanced = 0;
4567       while (paren_not_balanced || *l != ',')
4568         {
4569           if (*l == END_OF_INSN)
4570             {
4571               if (paren_not_balanced)
4572                 {
4573                   if (!intel_syntax)
4574                     as_bad (_("unbalanced parenthesis in operand %d."),
4575                             i.operands + 1);
4576                   else
4577                     as_bad (_("unbalanced brackets in operand %d."),
4578                             i.operands + 1);
4579                   return NULL;
4580                 }
4581               else
4582                 break;  /* we are done */
4583             }
4584           else if (!is_operand_char (*l) && !is_space_char (*l) && *l != '"')
4585             {
4586               as_bad (_("invalid character %s in operand %d"),
4587                       output_invalid (*l),
4588                       i.operands + 1);
4589               return NULL;
4590             }
4591           if (!intel_syntax)
4592             {
4593               if (*l == '(')
4594                 ++paren_not_balanced;
4595               if (*l == ')')
4596                 --paren_not_balanced;
4597             }
4598           else
4599             {
4600               if (*l == '[')
4601                 ++paren_not_balanced;
4602               if (*l == ']')
4603                 --paren_not_balanced;
4604             }
4605           l++;
4606         }
4607       if (l != token_start)
4608         {                       /* Yes, we've read in another operand.  */
4609           unsigned int operand_ok;
4610           this_operand = i.operands++;
4611           if (i.operands > MAX_OPERANDS)
4612             {
4613               as_bad (_("spurious operands; (%d operands/instruction max)"),
4614                       MAX_OPERANDS);
4615               return NULL;
4616             }
4617           i.types[this_operand].bitfield.unspecified = 1;
4618           /* Now parse operand adding info to 'i' as we go along.  */
4619           END_STRING_AND_SAVE (l);
4620
4621           if (intel_syntax)
4622             operand_ok =
4623               i386_intel_operand (token_start,
4624                                   intel_float_operand (mnemonic));
4625           else
4626             operand_ok = i386_att_operand (token_start);
4627
4628           RESTORE_END_STRING (l);
4629           if (!operand_ok)
4630             return NULL;
4631         }
4632       else
4633         {
4634           if (expecting_operand)
4635             {
4636             expecting_operand_after_comma:
4637               as_bad (_("expecting operand after ','; got nothing"));
4638               return NULL;
4639             }
4640           if (*l == ',')
4641             {
4642               as_bad (_("expecting operand before ','; got nothing"));
4643               return NULL;
4644             }
4645         }
4646
4647       /* Now *l must be either ',' or END_OF_INSN.  */
4648       if (*l == ',')
4649         {
4650           if (*++l == END_OF_INSN)
4651             {
4652               /* Just skip it, if it's \n complain.  */
4653               goto expecting_operand_after_comma;
4654             }
4655           expecting_operand = 1;
4656         }
4657     }
4658   return l;
4659 }
4660
4661 static void
4662 swap_2_operands (int xchg1, int xchg2)
4663 {
4664   union i386_op temp_op;
4665   i386_operand_type temp_type;
4666   enum bfd_reloc_code_real temp_reloc;
4667
4668   temp_type = i.types[xchg2];
4669   i.types[xchg2] = i.types[xchg1];
4670   i.types[xchg1] = temp_type;
4671   temp_op = i.op[xchg2];
4672   i.op[xchg2] = i.op[xchg1];
4673   i.op[xchg1] = temp_op;
4674   temp_reloc = i.reloc[xchg2];
4675   i.reloc[xchg2] = i.reloc[xchg1];
4676   i.reloc[xchg1] = temp_reloc;
4677
4678   if (i.mask)
4679     {
4680       if (i.mask->operand == xchg1)
4681         i.mask->operand = xchg2;
4682       else if (i.mask->operand == xchg2)
4683         i.mask->operand = xchg1;
4684     }
4685   if (i.broadcast)
4686     {
4687       if (i.broadcast->operand == xchg1)
4688         i.broadcast->operand = xchg2;
4689       else if (i.broadcast->operand == xchg2)
4690         i.broadcast->operand = xchg1;
4691     }
4692   if (i.rounding)
4693     {
4694       if (i.rounding->operand == xchg1)
4695         i.rounding->operand = xchg2;
4696       else if (i.rounding->operand == xchg2)
4697         i.rounding->operand = xchg1;
4698     }
4699 }
4700
4701 static void
4702 swap_operands (void)
4703 {
4704   switch (i.operands)
4705     {
4706     case 5:
4707     case 4:
4708       swap_2_operands (1, i.operands - 2);
4709       /* Fall through.  */
4710     case 3:
4711     case 2:
4712       swap_2_operands (0, i.operands - 1);
4713       break;
4714     default:
4715       abort ();
4716     }
4717
4718   if (i.mem_operands == 2)
4719     {
4720       const seg_entry *temp_seg;
4721       temp_seg = i.seg[0];
4722       i.seg[0] = i.seg[1];
4723       i.seg[1] = temp_seg;
4724     }
4725 }
4726
4727 /* Try to ensure constant immediates are represented in the smallest
4728    opcode possible.  */
4729 static void
4730 optimize_imm (void)
4731 {
4732   char guess_suffix = 0;
4733   int op;
4734
4735   if (i.suffix)
4736     guess_suffix = i.suffix;
4737   else if (i.reg_operands)
4738     {
4739       /* Figure out a suffix from the last register operand specified.
4740          We can't do this properly yet, ie. excluding InOutPortReg,
4741          but the following works for instructions with immediates.
4742          In any case, we can't set i.suffix yet.  */
4743       for (op = i.operands; --op >= 0;)
4744         if (i.types[op].bitfield.reg && i.types[op].bitfield.byte)
4745           {
4746             guess_suffix = BYTE_MNEM_SUFFIX;
4747             break;
4748           }
4749         else if (i.types[op].bitfield.reg && i.types[op].bitfield.word)
4750           {
4751             guess_suffix = WORD_MNEM_SUFFIX;
4752             break;
4753           }
4754         else if (i.types[op].bitfield.reg && i.types[op].bitfield.dword)
4755           {
4756             guess_suffix = LONG_MNEM_SUFFIX;
4757             break;
4758           }
4759         else if (i.types[op].bitfield.reg && i.types[op].bitfield.qword)
4760           {
4761             guess_suffix = QWORD_MNEM_SUFFIX;
4762             break;
4763           }
4764     }
4765   else if ((flag_code == CODE_16BIT) ^ (i.prefix[DATA_PREFIX] != 0))
4766     guess_suffix = WORD_MNEM_SUFFIX;
4767
4768   for (op = i.operands; --op >= 0;)
4769     if (operand_type_check (i.types[op], imm))
4770       {
4771         switch (i.op[op].imms->X_op)
4772           {
4773           case O_constant:
4774             /* If a suffix is given, this operand may be shortened.  */
4775             switch (guess_suffix)
4776               {
4777               case LONG_MNEM_SUFFIX:
4778                 i.types[op].bitfield.imm32 = 1;
4779                 i.types[op].bitfield.imm64 = 1;
4780                 break;
4781               case WORD_MNEM_SUFFIX:
4782                 i.types[op].bitfield.imm16 = 1;
4783                 i.types[op].bitfield.imm32 = 1;
4784                 i.types[op].bitfield.imm32s = 1;
4785                 i.types[op].bitfield.imm64 = 1;
4786                 break;
4787               case BYTE_MNEM_SUFFIX:
4788                 i.types[op].bitfield.imm8 = 1;
4789                 i.types[op].bitfield.imm8s = 1;
4790                 i.types[op].bitfield.imm16 = 1;
4791                 i.types[op].bitfield.imm32 = 1;
4792                 i.types[op].bitfield.imm32s = 1;
4793                 i.types[op].bitfield.imm64 = 1;
4794                 break;
4795               }
4796
4797             /* If this operand is at most 16 bits, convert it
4798                to a signed 16 bit number before trying to see
4799                whether it will fit in an even smaller size.
4800                This allows a 16-bit operand such as $0xffe0 to
4801                be recognised as within Imm8S range.  */
4802             if ((i.types[op].bitfield.imm16)
4803                 && (i.op[op].imms->X_add_number & ~(offsetT) 0xffff) == 0)
4804               {
4805                 i.op[op].imms->X_add_number =
4806                   (((i.op[op].imms->X_add_number & 0xffff) ^ 0x8000) - 0x8000);
4807               }
4808 #ifdef BFD64
4809             /* Store 32-bit immediate in 64-bit for 64-bit BFD.  */
4810             if ((i.types[op].bitfield.imm32)
4811                 && ((i.op[op].imms->X_add_number & ~(((offsetT) 2 << 31) - 1))
4812                     == 0))
4813               {
4814                 i.op[op].imms->X_add_number = ((i.op[op].imms->X_add_number
4815                                                 ^ ((offsetT) 1 << 31))
4816                                                - ((offsetT) 1 << 31));
4817               }
4818 #endif
4819             i.types[op]
4820               = operand_type_or (i.types[op],
4821                                  smallest_imm_type (i.op[op].imms->X_add_number));
4822
4823             /* We must avoid matching of Imm32 templates when 64bit
4824                only immediate is available.  */
4825             if (guess_suffix == QWORD_MNEM_SUFFIX)
4826               i.types[op].bitfield.imm32 = 0;
4827             break;
4828
4829           case O_absent:
4830           case O_register:
4831             abort ();
4832
4833             /* Symbols and expressions.  */
4834           default:
4835             /* Convert symbolic operand to proper sizes for matching, but don't
4836                prevent matching a set of insns that only supports sizes other
4837                than those matching the insn suffix.  */
4838             {
4839               i386_operand_type mask, allowed;
4840               const insn_template *t;
4841
4842               operand_type_set (&mask, 0);
4843               operand_type_set (&allowed, 0);
4844
4845               for (t = current_templates->start;
4846                    t < current_templates->end;
4847                    ++t)
4848                 allowed = operand_type_or (allowed,
4849                                            t->operand_types[op]);
4850               switch (guess_suffix)
4851                 {
4852                 case QWORD_MNEM_SUFFIX:
4853                   mask.bitfield.imm64 = 1;
4854                   mask.bitfield.imm32s = 1;
4855                   break;
4856                 case LONG_MNEM_SUFFIX:
4857                   mask.bitfield.imm32 = 1;
4858                   break;
4859                 case WORD_MNEM_SUFFIX:
4860                   mask.bitfield.imm16 = 1;
4861                   break;
4862                 case BYTE_MNEM_SUFFIX:
4863                   mask.bitfield.imm8 = 1;
4864                   break;
4865                 default:
4866                   break;
4867                 }
4868               allowed = operand_type_and (mask, allowed);
4869               if (!operand_type_all_zero (&allowed))
4870                 i.types[op] = operand_type_and (i.types[op], mask);
4871             }
4872             break;
4873           }
4874       }
4875 }
4876
4877 /* Try to use the smallest displacement type too.  */
4878 static void
4879 optimize_disp (void)
4880 {
4881   int op;
4882
4883   for (op = i.operands; --op >= 0;)
4884     if (operand_type_check (i.types[op], disp))
4885       {
4886         if (i.op[op].disps->X_op == O_constant)
4887           {
4888             offsetT op_disp = i.op[op].disps->X_add_number;
4889
4890             if (i.types[op].bitfield.disp16
4891                 && (op_disp & ~(offsetT) 0xffff) == 0)
4892               {
4893                 /* If this operand is at most 16 bits, convert
4894                    to a signed 16 bit number and don't use 64bit
4895                    displacement.  */
4896                 op_disp = (((op_disp & 0xffff) ^ 0x8000) - 0x8000);
4897                 i.types[op].bitfield.disp64 = 0;
4898               }
4899 #ifdef BFD64
4900             /* Optimize 64-bit displacement to 32-bit for 64-bit BFD.  */
4901             if (i.types[op].bitfield.disp32
4902                 && (op_disp & ~(((offsetT) 2 << 31) - 1)) == 0)
4903               {
4904                 /* If this operand is at most 32 bits, convert
4905                    to a signed 32 bit number and don't use 64bit
4906                    displacement.  */
4907                 op_disp &= (((offsetT) 2 << 31) - 1);
4908                 op_disp = (op_disp ^ ((offsetT) 1 << 31)) - ((addressT) 1 << 31);
4909                 i.types[op].bitfield.disp64 = 0;
4910               }
4911 #endif
4912             if (!op_disp && i.types[op].bitfield.baseindex)
4913               {
4914                 i.types[op].bitfield.disp8 = 0;
4915                 i.types[op].bitfield.disp16 = 0;
4916                 i.types[op].bitfield.disp32 = 0;
4917                 i.types[op].bitfield.disp32s = 0;
4918                 i.types[op].bitfield.disp64 = 0;
4919                 i.op[op].disps = 0;
4920                 i.disp_operands--;
4921               }
4922             else if (flag_code == CODE_64BIT)
4923               {
4924                 if (fits_in_signed_long (op_disp))
4925                   {
4926                     i.types[op].bitfield.disp64 = 0;
4927                     i.types[op].bitfield.disp32s = 1;
4928                   }
4929                 if (i.prefix[ADDR_PREFIX]
4930                     && fits_in_unsigned_long (op_disp))
4931                   i.types[op].bitfield.disp32 = 1;
4932               }
4933             if ((i.types[op].bitfield.disp32
4934                  || i.types[op].bitfield.disp32s
4935                  || i.types[op].bitfield.disp16)
4936                 && fits_in_disp8 (op_disp))
4937               i.types[op].bitfield.disp8 = 1;
4938           }
4939         else if (i.reloc[op] == BFD_RELOC_386_TLS_DESC_CALL
4940                  || i.reloc[op] == BFD_RELOC_X86_64_TLSDESC_CALL)
4941           {
4942             fix_new_exp (frag_now, frag_more (0) - frag_now->fr_literal, 0,
4943                          i.op[op].disps, 0, i.reloc[op]);
4944             i.types[op].bitfield.disp8 = 0;
4945             i.types[op].bitfield.disp16 = 0;
4946             i.types[op].bitfield.disp32 = 0;
4947             i.types[op].bitfield.disp32s = 0;
4948             i.types[op].bitfield.disp64 = 0;
4949           }
4950         else
4951           /* We only support 64bit displacement on constants.  */
4952           i.types[op].bitfield.disp64 = 0;
4953       }
4954 }
4955
4956 /* Check if operands are valid for the instruction.  */
4957
4958 static int
4959 check_VecOperands (const insn_template *t)
4960 {
4961   unsigned int op;
4962
4963   /* Without VSIB byte, we can't have a vector register for index.  */
4964   if (!t->opcode_modifier.vecsib
4965       && i.index_reg
4966       && (i.index_reg->reg_type.bitfield.xmmword
4967           || i.index_reg->reg_type.bitfield.ymmword
4968           || i.index_reg->reg_type.bitfield.zmmword))
4969     {
4970       i.error = unsupported_vector_index_register;
4971       return 1;
4972     }
4973
4974   /* Check if default mask is allowed.  */
4975   if (t->opcode_modifier.nodefmask
4976       && (!i.mask || i.mask->mask->reg_num == 0))
4977     {
4978       i.error = no_default_mask;
4979       return 1;
4980     }
4981
4982   /* For VSIB byte, we need a vector register for index, and all vector
4983      registers must be distinct.  */
4984   if (t->opcode_modifier.vecsib)
4985     {
4986       if (!i.index_reg
4987           || !((t->opcode_modifier.vecsib == VecSIB128
4988                 && i.index_reg->reg_type.bitfield.xmmword)
4989                || (t->opcode_modifier.vecsib == VecSIB256
4990                    && i.index_reg->reg_type.bitfield.ymmword)
4991                || (t->opcode_modifier.vecsib == VecSIB512
4992                    && i.index_reg->reg_type.bitfield.zmmword)))
4993       {
4994         i.error = invalid_vsib_address;
4995         return 1;
4996       }
4997
4998       gas_assert (i.reg_operands == 2 || i.mask);
4999       if (i.reg_operands == 2 && !i.mask)
5000         {
5001           gas_assert (i.types[0].bitfield.regsimd);
5002           gas_assert (i.types[0].bitfield.xmmword
5003                       || i.types[0].bitfield.ymmword);
5004           gas_assert (i.types[2].bitfield.regsimd);
5005           gas_assert (i.types[2].bitfield.xmmword
5006                       || i.types[2].bitfield.ymmword);
5007           if (operand_check == check_none)
5008             return 0;
5009           if (register_number (i.op[0].regs)
5010               != register_number (i.index_reg)
5011               && register_number (i.op[2].regs)
5012                  != register_number (i.index_reg)
5013               && register_number (i.op[0].regs)
5014                  != register_number (i.op[2].regs))
5015             return 0;
5016           if (operand_check == check_error)
5017             {
5018               i.error = invalid_vector_register_set;
5019               return 1;
5020             }
5021           as_warn (_("mask, index, and destination registers should be distinct"));
5022         }
5023       else if (i.reg_operands == 1 && i.mask)
5024         {
5025           if (i.types[1].bitfield.regsimd
5026               && (i.types[1].bitfield.xmmword
5027                   || i.types[1].bitfield.ymmword
5028                   || i.types[1].bitfield.zmmword)
5029               && (register_number (i.op[1].regs)
5030                   == register_number (i.index_reg)))
5031             {
5032               if (operand_check == check_error)
5033                 {
5034                   i.error = invalid_vector_register_set;
5035                   return 1;
5036                 }
5037               if (operand_check != check_none)
5038                 as_warn (_("index and destination registers should be distinct"));
5039             }
5040         }
5041     }
5042
5043   /* Check if broadcast is supported by the instruction and is applied
5044      to the memory operand.  */
5045   if (i.broadcast)
5046     {
5047       int broadcasted_opnd_size;
5048
5049       /* Check if specified broadcast is supported in this instruction,
5050          and it's applied to memory operand of DWORD or QWORD type,
5051          depending on VecESize.  */
5052       if (i.broadcast->type != t->opcode_modifier.broadcast
5053           || !i.types[i.broadcast->operand].bitfield.mem
5054           || (t->opcode_modifier.vecesize == 0
5055               && !i.types[i.broadcast->operand].bitfield.dword
5056               && !i.types[i.broadcast->operand].bitfield.unspecified)
5057           || (t->opcode_modifier.vecesize == 1
5058               && !i.types[i.broadcast->operand].bitfield.qword
5059               && !i.types[i.broadcast->operand].bitfield.unspecified))
5060         goto bad_broadcast;
5061
5062       broadcasted_opnd_size = t->opcode_modifier.vecesize ? 64 : 32;
5063       if (i.broadcast->type == BROADCAST_1TO16)
5064         broadcasted_opnd_size <<= 4; /* Broadcast 1to16.  */
5065       else if (i.broadcast->type == BROADCAST_1TO8)
5066         broadcasted_opnd_size <<= 3; /* Broadcast 1to8.  */
5067       else if (i.broadcast->type == BROADCAST_1TO4)
5068         broadcasted_opnd_size <<= 2; /* Broadcast 1to4.  */
5069       else if (i.broadcast->type == BROADCAST_1TO2)
5070         broadcasted_opnd_size <<= 1; /* Broadcast 1to2.  */
5071       else
5072         goto bad_broadcast;
5073
5074       if ((broadcasted_opnd_size == 256
5075            && !t->operand_types[i.broadcast->operand].bitfield.ymmword)
5076           || (broadcasted_opnd_size == 512
5077               && !t->operand_types[i.broadcast->operand].bitfield.zmmword))
5078         {
5079         bad_broadcast:
5080           i.error = unsupported_broadcast;
5081           return 1;
5082         }
5083     }
5084   /* If broadcast is supported in this instruction, we need to check if
5085      operand of one-element size isn't specified without broadcast.  */
5086   else if (t->opcode_modifier.broadcast && i.mem_operands)
5087     {
5088       /* Find memory operand.  */
5089       for (op = 0; op < i.operands; op++)
5090         if (operand_type_check (i.types[op], anymem))
5091           break;
5092       gas_assert (op < i.operands);
5093       /* Check size of the memory operand.  */
5094       if ((t->opcode_modifier.vecesize == 0
5095            && i.types[op].bitfield.dword)
5096           || (t->opcode_modifier.vecesize == 1
5097               && i.types[op].bitfield.qword))
5098         {
5099           i.error = broadcast_needed;
5100           return 1;
5101         }
5102     }
5103
5104   /* Check if requested masking is supported.  */
5105   if (i.mask
5106       && (!t->opcode_modifier.masking
5107           || (i.mask->zeroing
5108               && t->opcode_modifier.masking == MERGING_MASKING)))
5109     {
5110       i.error = unsupported_masking;
5111       return 1;
5112     }
5113
5114   /* Check if masking is applied to dest operand.  */
5115   if (i.mask && (i.mask->operand != (int) (i.operands - 1)))
5116     {
5117       i.error = mask_not_on_destination;
5118       return 1;
5119     }
5120
5121   /* Check RC/SAE.  */
5122   if (i.rounding)
5123     {
5124       if ((i.rounding->type != saeonly
5125            && !t->opcode_modifier.staticrounding)
5126           || (i.rounding->type == saeonly
5127               && (t->opcode_modifier.staticrounding
5128                   || !t->opcode_modifier.sae)))
5129         {
5130           i.error = unsupported_rc_sae;
5131           return 1;
5132         }
5133       /* If the instruction has several immediate operands and one of
5134          them is rounding, the rounding operand should be the last
5135          immediate operand.  */
5136       if (i.imm_operands > 1
5137           && i.rounding->operand != (int) (i.imm_operands - 1))
5138         {
5139           i.error = rc_sae_operand_not_last_imm;
5140           return 1;
5141         }
5142     }
5143
5144   /* Check vector Disp8 operand.  */
5145   if (t->opcode_modifier.disp8memshift
5146       && i.disp_encoding != disp_encoding_32bit)
5147     {
5148       if (i.broadcast)
5149         i.memshift = t->opcode_modifier.vecesize ? 3 : 2;
5150       else
5151         i.memshift = t->opcode_modifier.disp8memshift;
5152
5153       for (op = 0; op < i.operands; op++)
5154         if (operand_type_check (i.types[op], disp)
5155             && i.op[op].disps->X_op == O_constant)
5156           {
5157             if (fits_in_disp8 (i.op[op].disps->X_add_number))
5158               {
5159                 i.types[op].bitfield.disp8 = 1;
5160                 return 0;
5161               }
5162             i.types[op].bitfield.disp8 = 0;
5163           }
5164     }
5165
5166   i.memshift = 0;
5167
5168   return 0;
5169 }
5170
5171 /* Check if operands are valid for the instruction.  Update VEX
5172    operand types.  */
5173
5174 static int
5175 VEX_check_operands (const insn_template *t)
5176 {
5177   if (i.vec_encoding == vex_encoding_evex)
5178     {
5179       /* This instruction must be encoded with EVEX prefix.  */
5180       if (!is_evex_encoding (t))
5181         {
5182           i.error = unsupported;
5183           return 1;
5184         }
5185       return 0;
5186     }
5187
5188   if (!t->opcode_modifier.vex)
5189     {
5190       /* This instruction template doesn't have VEX prefix.  */
5191       if (i.vec_encoding != vex_encoding_default)
5192         {
5193           i.error = unsupported;
5194           return 1;
5195         }
5196       return 0;
5197     }
5198
5199   /* Only check VEX_Imm4, which must be the first operand.  */
5200   if (t->operand_types[0].bitfield.vec_imm4)
5201     {
5202       if (i.op[0].imms->X_op != O_constant
5203           || !fits_in_imm4 (i.op[0].imms->X_add_number))
5204         {
5205           i.error = bad_imm4;
5206           return 1;
5207         }
5208
5209       /* Turn off Imm8 so that update_imm won't complain.  */
5210       i.types[0] = vec_imm4;
5211     }
5212
5213   return 0;
5214 }
5215
5216 static const insn_template *
5217 match_template (char mnem_suffix)
5218 {
5219   /* Points to template once we've found it.  */
5220   const insn_template *t;
5221   i386_operand_type overlap0, overlap1, overlap2, overlap3;
5222   i386_operand_type overlap4;
5223   unsigned int found_reverse_match;
5224   i386_opcode_modifier suffix_check, mnemsuf_check;
5225   i386_operand_type operand_types [MAX_OPERANDS];
5226   int addr_prefix_disp;
5227   unsigned int j;
5228   unsigned int found_cpu_match;
5229   unsigned int check_register;
5230   enum i386_error specific_error = 0;
5231
5232 #if MAX_OPERANDS != 5
5233 # error "MAX_OPERANDS must be 5."
5234 #endif
5235
5236   found_reverse_match = 0;
5237   addr_prefix_disp = -1;
5238
5239   memset (&suffix_check, 0, sizeof (suffix_check));
5240   if (i.suffix == BYTE_MNEM_SUFFIX)
5241     suffix_check.no_bsuf = 1;
5242   else if (i.suffix == WORD_MNEM_SUFFIX)
5243     suffix_check.no_wsuf = 1;
5244   else if (i.suffix == SHORT_MNEM_SUFFIX)
5245     suffix_check.no_ssuf = 1;
5246   else if (i.suffix == LONG_MNEM_SUFFIX)
5247     suffix_check.no_lsuf = 1;
5248   else if (i.suffix == QWORD_MNEM_SUFFIX)
5249     suffix_check.no_qsuf = 1;
5250   else if (i.suffix == LONG_DOUBLE_MNEM_SUFFIX)
5251     suffix_check.no_ldsuf = 1;
5252
5253   memset (&mnemsuf_check, 0, sizeof (mnemsuf_check));
5254   if (intel_syntax)
5255     {
5256       switch (mnem_suffix)
5257         {
5258         case BYTE_MNEM_SUFFIX:  mnemsuf_check.no_bsuf = 1; break;
5259         case WORD_MNEM_SUFFIX:  mnemsuf_check.no_wsuf = 1; break;
5260         case SHORT_MNEM_SUFFIX: mnemsuf_check.no_ssuf = 1; break;
5261         case LONG_MNEM_SUFFIX:  mnemsuf_check.no_lsuf = 1; break;
5262         case QWORD_MNEM_SUFFIX: mnemsuf_check.no_qsuf = 1; break;
5263         }
5264     }
5265
5266   /* Must have right number of operands.  */
5267   i.error = number_of_operands_mismatch;
5268
5269   for (t = current_templates->start; t < current_templates->end; t++)
5270     {
5271       addr_prefix_disp = -1;
5272
5273       if (i.operands != t->operands)
5274         continue;
5275
5276       /* Check processor support.  */
5277       i.error = unsupported;
5278       found_cpu_match = (cpu_flags_match (t)
5279                          == CPU_FLAGS_PERFECT_MATCH);
5280       if (!found_cpu_match)
5281         continue;
5282
5283       /* Check AT&T mnemonic.   */
5284       i.error = unsupported_with_intel_mnemonic;
5285       if (intel_mnemonic && t->opcode_modifier.attmnemonic)
5286         continue;
5287
5288       /* Check AT&T/Intel syntax and Intel64/AMD64 ISA.   */
5289       i.error = unsupported_syntax;
5290       if ((intel_syntax && t->opcode_modifier.attsyntax)
5291           || (!intel_syntax && t->opcode_modifier.intelsyntax)
5292           || (intel64 && t->opcode_modifier.amd64)
5293           || (!intel64 && t->opcode_modifier.intel64))
5294         continue;
5295
5296       /* Check the suffix, except for some instructions in intel mode.  */
5297       i.error = invalid_instruction_suffix;
5298       if ((!intel_syntax || !t->opcode_modifier.ignoresize)
5299           && ((t->opcode_modifier.no_bsuf && suffix_check.no_bsuf)
5300               || (t->opcode_modifier.no_wsuf && suffix_check.no_wsuf)
5301               || (t->opcode_modifier.no_lsuf && suffix_check.no_lsuf)
5302               || (t->opcode_modifier.no_ssuf && suffix_check.no_ssuf)
5303               || (t->opcode_modifier.no_qsuf && suffix_check.no_qsuf)
5304               || (t->opcode_modifier.no_ldsuf && suffix_check.no_ldsuf)))
5305         continue;
5306       /* In Intel mode all mnemonic suffixes must be explicitly allowed.  */
5307       if ((t->opcode_modifier.no_bsuf && mnemsuf_check.no_bsuf)
5308           || (t->opcode_modifier.no_wsuf && mnemsuf_check.no_wsuf)
5309           || (t->opcode_modifier.no_lsuf && mnemsuf_check.no_lsuf)
5310           || (t->opcode_modifier.no_ssuf && mnemsuf_check.no_ssuf)
5311           || (t->opcode_modifier.no_qsuf && mnemsuf_check.no_qsuf)
5312           || (t->opcode_modifier.no_ldsuf && mnemsuf_check.no_ldsuf))
5313         continue;
5314
5315       if (!operand_size_match (t))
5316         continue;
5317
5318       for (j = 0; j < MAX_OPERANDS; j++)
5319         operand_types[j] = t->operand_types[j];
5320
5321       /* In general, don't allow 64-bit operands in 32-bit mode.  */
5322       if (i.suffix == QWORD_MNEM_SUFFIX
5323           && flag_code != CODE_64BIT
5324           && (intel_syntax
5325               ? (!t->opcode_modifier.ignoresize
5326                  && !intel_float_operand (t->name))
5327               : intel_float_operand (t->name) != 2)
5328           && ((!operand_types[0].bitfield.regmmx
5329                && !operand_types[0].bitfield.regsimd)
5330               || (!operand_types[t->operands > 1].bitfield.regmmx
5331                   && !operand_types[t->operands > 1].bitfield.regsimd))
5332           && (t->base_opcode != 0x0fc7
5333               || t->extension_opcode != 1 /* cmpxchg8b */))
5334         continue;
5335
5336       /* In general, don't allow 32-bit operands on pre-386.  */
5337       else if (i.suffix == LONG_MNEM_SUFFIX
5338                && !cpu_arch_flags.bitfield.cpui386
5339                && (intel_syntax
5340                    ? (!t->opcode_modifier.ignoresize
5341                       && !intel_float_operand (t->name))
5342                    : intel_float_operand (t->name) != 2)
5343                && ((!operand_types[0].bitfield.regmmx
5344                     && !operand_types[0].bitfield.regsimd)
5345                    || (!operand_types[t->operands > 1].bitfield.regmmx
5346                        && !operand_types[t->operands > 1].bitfield.regsimd)))
5347         continue;
5348
5349       /* Do not verify operands when there are none.  */
5350       else
5351         {
5352           if (!t->operands)
5353             /* We've found a match; break out of loop.  */
5354             break;
5355         }
5356
5357       /* Address size prefix will turn Disp64/Disp32/Disp16 operand
5358          into Disp32/Disp16/Disp32 operand.  */
5359       if (i.prefix[ADDR_PREFIX] != 0)
5360           {
5361             /* There should be only one Disp operand.  */
5362             switch (flag_code)
5363             {
5364             case CODE_16BIT:
5365               for (j = 0; j < MAX_OPERANDS; j++)
5366                 {
5367                   if (operand_types[j].bitfield.disp16)
5368                     {
5369                       addr_prefix_disp = j;
5370                       operand_types[j].bitfield.disp32 = 1;
5371                       operand_types[j].bitfield.disp16 = 0;
5372                       break;
5373                     }
5374                 }
5375               break;
5376             case CODE_32BIT:
5377               for (j = 0; j < MAX_OPERANDS; j++)
5378                 {
5379                   if (operand_types[j].bitfield.disp32)
5380                     {
5381                       addr_prefix_disp = j;
5382                       operand_types[j].bitfield.disp32 = 0;
5383                       operand_types[j].bitfield.disp16 = 1;
5384                       break;
5385                     }
5386                 }
5387               break;
5388             case CODE_64BIT:
5389               for (j = 0; j < MAX_OPERANDS; j++)
5390                 {
5391                   if (operand_types[j].bitfield.disp64)
5392                     {
5393                       addr_prefix_disp = j;
5394                       operand_types[j].bitfield.disp64 = 0;
5395                       operand_types[j].bitfield.disp32 = 1;
5396                       break;
5397                     }
5398                 }
5399               break;
5400             }
5401           }
5402
5403       /* Force 0x8b encoding for "mov foo@GOT, %eax".  */
5404       if (i.reloc[0] == BFD_RELOC_386_GOT32 && t->base_opcode == 0xa0)
5405         continue;
5406
5407       /* We check register size if needed.  */
5408       check_register = t->opcode_modifier.checkregsize;
5409       overlap0 = operand_type_and (i.types[0], operand_types[0]);
5410       switch (t->operands)
5411         {
5412         case 1:
5413           if (!operand_type_match (overlap0, i.types[0]))
5414             continue;
5415           break;
5416         case 2:
5417           /* xchg %eax, %eax is a special case. It is an alias for nop
5418              only in 32bit mode and we can use opcode 0x90.  In 64bit
5419              mode, we can't use 0x90 for xchg %eax, %eax since it should
5420              zero-extend %eax to %rax.  */
5421           if (flag_code == CODE_64BIT
5422               && t->base_opcode == 0x90
5423               && operand_type_equal (&i.types [0], &acc32)
5424               && operand_type_equal (&i.types [1], &acc32))
5425             continue;
5426           /* If we want store form, we reverse direction of operands.  */
5427           if (i.dir_encoding == dir_encoding_store
5428               && t->opcode_modifier.d)
5429             goto check_reverse;
5430           /* Fall through.  */
5431
5432         case 3:
5433           /* If we want store form, we skip the current load.  */
5434           if (i.dir_encoding == dir_encoding_store
5435               && i.mem_operands == 0
5436               && t->opcode_modifier.load)
5437             continue;
5438           /* Fall through.  */
5439         case 4:
5440         case 5:
5441           overlap1 = operand_type_and (i.types[1], operand_types[1]);
5442           if (!operand_type_match (overlap0, i.types[0])
5443               || !operand_type_match (overlap1, i.types[1])
5444               || (check_register
5445                   && !operand_type_register_match (i.types[0],
5446                                                    operand_types[0],
5447                                                    i.types[1],
5448                                                    operand_types[1])))
5449             {
5450               /* Check if other direction is valid ...  */
5451               if (!t->opcode_modifier.d)
5452                 continue;
5453
5454 check_reverse:
5455               /* Try reversing direction of operands.  */
5456               overlap0 = operand_type_and (i.types[0], operand_types[1]);
5457               overlap1 = operand_type_and (i.types[1], operand_types[0]);
5458               if (!operand_type_match (overlap0, i.types[0])
5459                   || !operand_type_match (overlap1, i.types[1])
5460                   || (check_register
5461                       && !operand_type_register_match (i.types[0],
5462                                                        operand_types[1],
5463                                                        i.types[1],
5464                                                        operand_types[0])))
5465                 {
5466                   /* Does not match either direction.  */
5467                   continue;
5468                 }
5469               /* found_reverse_match holds which of D or FloatR
5470                  we've found.  */
5471               if (!t->opcode_modifier.d)
5472                 found_reverse_match = 0;
5473               else if (operand_types[0].bitfield.tbyte)
5474                 found_reverse_match = Opcode_FloatD;
5475               else
5476                 found_reverse_match = Opcode_D;
5477               if (t->opcode_modifier.floatr)
5478                 found_reverse_match |= Opcode_FloatR;
5479             }
5480           else
5481             {
5482               /* Found a forward 2 operand match here.  */
5483               switch (t->operands)
5484                 {
5485                 case 5:
5486                   overlap4 = operand_type_and (i.types[4],
5487                                                operand_types[4]);
5488                   /* Fall through.  */
5489                 case 4:
5490                   overlap3 = operand_type_and (i.types[3],
5491                                                operand_types[3]);
5492                   /* Fall through.  */
5493                 case 3:
5494                   overlap2 = operand_type_and (i.types[2],
5495                                                operand_types[2]);
5496                   break;
5497                 }
5498
5499               switch (t->operands)
5500                 {
5501                 case 5:
5502                   if (!operand_type_match (overlap4, i.types[4])
5503                       || !operand_type_register_match (i.types[3],
5504                                                        operand_types[3],
5505                                                        i.types[4],
5506                                                        operand_types[4]))
5507                     continue;
5508                   /* Fall through.  */
5509                 case 4:
5510                   if (!operand_type_match (overlap3, i.types[3])
5511                       || (check_register
5512                           && !operand_type_register_match (i.types[2],
5513                                                            operand_types[2],
5514                                                            i.types[3],
5515                                                            operand_types[3])))
5516                     continue;
5517                   /* Fall through.  */
5518                 case 3:
5519                   /* Here we make use of the fact that there are no
5520                      reverse match 3 operand instructions.  */
5521                   if (!operand_type_match (overlap2, i.types[2])
5522                       || (check_register
5523                           && (!operand_type_register_match (i.types[0],
5524                                                             operand_types[0],
5525                                                             i.types[2],
5526                                                             operand_types[2])
5527                               || !operand_type_register_match (i.types[1],
5528                                                                operand_types[1],
5529                                                                i.types[2],
5530                                                                operand_types[2]))))
5531                     continue;
5532                   break;
5533                 }
5534             }
5535           /* Found either forward/reverse 2, 3 or 4 operand match here:
5536              slip through to break.  */
5537         }
5538       if (!found_cpu_match)
5539         {
5540           found_reverse_match = 0;
5541           continue;
5542         }
5543
5544       /* Check if vector and VEX operands are valid.  */
5545       if (check_VecOperands (t) || VEX_check_operands (t))
5546         {
5547           specific_error = i.error;
5548           continue;
5549         }
5550
5551       /* We've found a match; break out of loop.  */
5552       break;
5553     }
5554
5555   if (t == current_templates->end)
5556     {
5557       /* We found no match.  */
5558       const char *err_msg;
5559       switch (specific_error ? specific_error : i.error)
5560         {
5561         default:
5562           abort ();
5563         case operand_size_mismatch:
5564           err_msg = _("operand size mismatch");
5565           break;
5566         case operand_type_mismatch:
5567           err_msg = _("operand type mismatch");
5568           break;
5569         case register_type_mismatch:
5570           err_msg = _("register type mismatch");
5571           break;
5572         case number_of_operands_mismatch:
5573           err_msg = _("number of operands mismatch");
5574           break;
5575         case invalid_instruction_suffix:
5576           err_msg = _("invalid instruction suffix");
5577           break;
5578         case bad_imm4:
5579           err_msg = _("constant doesn't fit in 4 bits");
5580           break;
5581         case unsupported_with_intel_mnemonic:
5582           err_msg = _("unsupported with Intel mnemonic");
5583           break;
5584         case unsupported_syntax:
5585           err_msg = _("unsupported syntax");
5586           break;
5587         case unsupported:
5588           as_bad (_("unsupported instruction `%s'"),
5589                   current_templates->start->name);
5590           return NULL;
5591         case invalid_vsib_address:
5592           err_msg = _("invalid VSIB address");
5593           break;
5594         case invalid_vector_register_set:
5595           err_msg = _("mask, index, and destination registers must be distinct");
5596           break;
5597         case unsupported_vector_index_register:
5598           err_msg = _("unsupported vector index register");
5599           break;
5600         case unsupported_broadcast:
5601           err_msg = _("unsupported broadcast");
5602           break;
5603         case broadcast_not_on_src_operand:
5604           err_msg = _("broadcast not on source memory operand");
5605           break;
5606         case broadcast_needed:
5607           err_msg = _("broadcast is needed for operand of such type");
5608           break;
5609         case unsupported_masking:
5610           err_msg = _("unsupported masking");
5611           break;
5612         case mask_not_on_destination:
5613           err_msg = _("mask not on destination operand");
5614           break;
5615         case no_default_mask:
5616           err_msg = _("default mask isn't allowed");
5617           break;
5618         case unsupported_rc_sae:
5619           err_msg = _("unsupported static rounding/sae");
5620           break;
5621         case rc_sae_operand_not_last_imm:
5622           if (intel_syntax)
5623             err_msg = _("RC/SAE operand must precede immediate operands");
5624           else
5625             err_msg = _("RC/SAE operand must follow immediate operands");
5626           break;
5627         case invalid_register_operand:
5628           err_msg = _("invalid register operand");
5629           break;
5630         }
5631       as_bad (_("%s for `%s'"), err_msg,
5632               current_templates->start->name);
5633       return NULL;
5634     }
5635
5636   if (!quiet_warnings)
5637     {
5638       if (!intel_syntax
5639           && (i.types[0].bitfield.jumpabsolute
5640               != operand_types[0].bitfield.jumpabsolute))
5641         {
5642           as_warn (_("indirect %s without `*'"), t->name);
5643         }
5644
5645       if (t->opcode_modifier.isprefix
5646           && t->opcode_modifier.ignoresize)
5647         {
5648           /* Warn them that a data or address size prefix doesn't
5649              affect assembly of the next line of code.  */
5650           as_warn (_("stand-alone `%s' prefix"), t->name);
5651         }
5652     }
5653
5654   /* Copy the template we found.  */
5655   i.tm = *t;
5656
5657   if (addr_prefix_disp != -1)
5658     i.tm.operand_types[addr_prefix_disp]
5659       = operand_types[addr_prefix_disp];
5660
5661   if (found_reverse_match)
5662     {
5663       /* If we found a reverse match we must alter the opcode
5664          direction bit.  found_reverse_match holds bits to change
5665          (different for int & float insns).  */
5666
5667       i.tm.base_opcode ^= found_reverse_match;
5668
5669       i.tm.operand_types[0] = operand_types[1];
5670       i.tm.operand_types[1] = operand_types[0];
5671     }
5672
5673   return t;
5674 }
5675
5676 static int
5677 check_string (void)
5678 {
5679   int mem_op = operand_type_check (i.types[0], anymem) ? 0 : 1;
5680   if (i.tm.operand_types[mem_op].bitfield.esseg)
5681     {
5682       if (i.seg[0] != NULL && i.seg[0] != &es)
5683         {
5684           as_bad (_("`%s' operand %d must use `%ses' segment"),
5685                   i.tm.name,
5686                   mem_op + 1,
5687                   register_prefix);
5688           return 0;
5689         }
5690       /* There's only ever one segment override allowed per instruction.
5691          This instruction possibly has a legal segment override on the
5692          second operand, so copy the segment to where non-string
5693          instructions store it, allowing common code.  */
5694       i.seg[0] = i.seg[1];
5695     }
5696   else if (i.tm.operand_types[mem_op + 1].bitfield.esseg)
5697     {
5698       if (i.seg[1] != NULL && i.seg[1] != &es)
5699         {
5700           as_bad (_("`%s' operand %d must use `%ses' segment"),
5701                   i.tm.name,
5702                   mem_op + 2,
5703                   register_prefix);
5704           return 0;
5705         }
5706     }
5707   return 1;
5708 }
5709
5710 static int
5711 process_suffix (void)
5712 {
5713   /* If matched instruction specifies an explicit instruction mnemonic
5714      suffix, use it.  */
5715   if (i.tm.opcode_modifier.size16)
5716     i.suffix = WORD_MNEM_SUFFIX;
5717   else if (i.tm.opcode_modifier.size32)
5718     i.suffix = LONG_MNEM_SUFFIX;
5719   else if (i.tm.opcode_modifier.size64)
5720     i.suffix = QWORD_MNEM_SUFFIX;
5721   else if (i.reg_operands)
5722     {
5723       /* If there's no instruction mnemonic suffix we try to invent one
5724          based on register operands.  */
5725       if (!i.suffix)
5726         {
5727           /* We take i.suffix from the last register operand specified,
5728              Destination register type is more significant than source
5729              register type.  crc32 in SSE4.2 prefers source register
5730              type. */
5731           if (i.tm.base_opcode == 0xf20f38f1)
5732             {
5733               if (i.types[0].bitfield.reg && i.types[0].bitfield.word)
5734                 i.suffix = WORD_MNEM_SUFFIX;
5735               else if (i.types[0].bitfield.reg && i.types[0].bitfield.dword)
5736                 i.suffix = LONG_MNEM_SUFFIX;
5737               else if (i.types[0].bitfield.reg && i.types[0].bitfield.qword)
5738                 i.suffix = QWORD_MNEM_SUFFIX;
5739             }
5740           else if (i.tm.base_opcode == 0xf20f38f0)
5741             {
5742               if (i.types[0].bitfield.reg && i.types[0].bitfield.byte)
5743                 i.suffix = BYTE_MNEM_SUFFIX;
5744             }
5745
5746           if (!i.suffix)
5747             {
5748               int op;
5749
5750               if (i.tm.base_opcode == 0xf20f38f1
5751                   || i.tm.base_opcode == 0xf20f38f0)
5752                 {
5753                   /* We have to know the operand size for crc32.  */
5754                   as_bad (_("ambiguous memory operand size for `%s`"),
5755                           i.tm.name);
5756                   return 0;
5757                 }
5758
5759               for (op = i.operands; --op >= 0;)
5760                 if (!i.tm.operand_types[op].bitfield.inoutportreg
5761                     && !i.tm.operand_types[op].bitfield.shiftcount)
5762                   {
5763                     if (!i.types[op].bitfield.reg)
5764                       continue;
5765                     if (i.types[op].bitfield.byte)
5766                       i.suffix = BYTE_MNEM_SUFFIX;
5767                     else if (i.types[op].bitfield.word)
5768                       i.suffix = WORD_MNEM_SUFFIX;
5769                     else if (i.types[op].bitfield.dword)
5770                       i.suffix = LONG_MNEM_SUFFIX;
5771                     else if (i.types[op].bitfield.qword)
5772                       i.suffix = QWORD_MNEM_SUFFIX;
5773                     else
5774                       continue;
5775                     break;
5776                   }
5777             }
5778         }
5779       else if (i.suffix == BYTE_MNEM_SUFFIX)
5780         {
5781           if (intel_syntax
5782               && i.tm.opcode_modifier.ignoresize
5783               && i.tm.opcode_modifier.no_bsuf)
5784             i.suffix = 0;
5785           else if (!check_byte_reg ())
5786             return 0;
5787         }
5788       else if (i.suffix == LONG_MNEM_SUFFIX)
5789         {
5790           if (intel_syntax
5791               && i.tm.opcode_modifier.ignoresize
5792               && i.tm.opcode_modifier.no_lsuf)
5793             i.suffix = 0;
5794           else if (!check_long_reg ())
5795             return 0;
5796         }
5797       else if (i.suffix == QWORD_MNEM_SUFFIX)
5798         {
5799           if (intel_syntax
5800               && i.tm.opcode_modifier.ignoresize
5801               && i.tm.opcode_modifier.no_qsuf)
5802             i.suffix = 0;
5803           else if (!check_qword_reg ())
5804             return 0;
5805         }
5806       else if (i.suffix == WORD_MNEM_SUFFIX)
5807         {
5808           if (intel_syntax
5809               && i.tm.opcode_modifier.ignoresize
5810               && i.tm.opcode_modifier.no_wsuf)
5811             i.suffix = 0;
5812           else if (!check_word_reg ())
5813             return 0;
5814         }
5815       else if (intel_syntax && i.tm.opcode_modifier.ignoresize)
5816         /* Do nothing if the instruction is going to ignore the prefix.  */
5817         ;
5818       else
5819         abort ();
5820     }
5821   else if (i.tm.opcode_modifier.defaultsize
5822            && !i.suffix
5823            /* exclude fldenv/frstor/fsave/fstenv */
5824            && i.tm.opcode_modifier.no_ssuf)
5825     {
5826       i.suffix = stackop_size;
5827     }
5828   else if (intel_syntax
5829            && !i.suffix
5830            && (i.tm.operand_types[0].bitfield.jumpabsolute
5831                || i.tm.opcode_modifier.jumpbyte
5832                || i.tm.opcode_modifier.jumpintersegment
5833                || (i.tm.base_opcode == 0x0f01 /* [ls][gi]dt */
5834                    && i.tm.extension_opcode <= 3)))
5835     {
5836       switch (flag_code)
5837         {
5838         case CODE_64BIT:
5839           if (!i.tm.opcode_modifier.no_qsuf)
5840             {
5841               i.suffix = QWORD_MNEM_SUFFIX;
5842               break;
5843             }
5844           /* Fall through.  */
5845         case CODE_32BIT:
5846           if (!i.tm.opcode_modifier.no_lsuf)
5847             i.suffix = LONG_MNEM_SUFFIX;
5848           break;
5849         case CODE_16BIT:
5850           if (!i.tm.opcode_modifier.no_wsuf)
5851             i.suffix = WORD_MNEM_SUFFIX;
5852           break;
5853         }
5854     }
5855
5856   if (!i.suffix)
5857     {
5858       if (!intel_syntax)
5859         {
5860           if (i.tm.opcode_modifier.w)
5861             {
5862               as_bad (_("no instruction mnemonic suffix given and "
5863                         "no register operands; can't size instruction"));
5864               return 0;
5865             }
5866         }
5867       else
5868         {
5869           unsigned int suffixes;
5870
5871           suffixes = !i.tm.opcode_modifier.no_bsuf;
5872           if (!i.tm.opcode_modifier.no_wsuf)
5873             suffixes |= 1 << 1;
5874           if (!i.tm.opcode_modifier.no_lsuf)
5875             suffixes |= 1 << 2;
5876           if (!i.tm.opcode_modifier.no_ldsuf)
5877             suffixes |= 1 << 3;
5878           if (!i.tm.opcode_modifier.no_ssuf)
5879             suffixes |= 1 << 4;
5880           if (flag_code == CODE_64BIT && !i.tm.opcode_modifier.no_qsuf)
5881             suffixes |= 1 << 5;
5882
5883           /* There are more than suffix matches.  */
5884           if (i.tm.opcode_modifier.w
5885               || ((suffixes & (suffixes - 1))
5886                   && !i.tm.opcode_modifier.defaultsize
5887                   && !i.tm.opcode_modifier.ignoresize))
5888             {
5889               as_bad (_("ambiguous operand size for `%s'"), i.tm.name);
5890               return 0;
5891             }
5892         }
5893     }
5894
5895   /* Change the opcode based on the operand size given by i.suffix.  */
5896   switch (i.suffix)
5897     {
5898     /* Size floating point instruction.  */
5899     case LONG_MNEM_SUFFIX:
5900       if (i.tm.opcode_modifier.floatmf)
5901         {
5902           i.tm.base_opcode ^= 4;
5903           break;
5904         }
5905     /* fall through */
5906     case WORD_MNEM_SUFFIX:
5907     case QWORD_MNEM_SUFFIX:
5908       /* It's not a byte, select word/dword operation.  */
5909       if (i.tm.opcode_modifier.w)
5910         {
5911           if (i.tm.opcode_modifier.shortform)
5912             i.tm.base_opcode |= 8;
5913           else
5914             i.tm.base_opcode |= 1;
5915         }
5916     /* fall through */
5917     case SHORT_MNEM_SUFFIX:
5918       /* Now select between word & dword operations via the operand
5919          size prefix, except for instructions that will ignore this
5920          prefix anyway.  */
5921       if (i.tm.opcode_modifier.addrprefixop0)
5922         {
5923           /* The address size override prefix changes the size of the
5924              first operand.  */
5925           if ((flag_code == CODE_32BIT
5926                && i.op->regs[0].reg_type.bitfield.word)
5927               || (flag_code != CODE_32BIT
5928                   && i.op->regs[0].reg_type.bitfield.dword))
5929             if (!add_prefix (ADDR_PREFIX_OPCODE))
5930               return 0;
5931         }
5932       else if (i.suffix != QWORD_MNEM_SUFFIX
5933                && !i.tm.opcode_modifier.ignoresize
5934                && !i.tm.opcode_modifier.floatmf
5935                && ((i.suffix == LONG_MNEM_SUFFIX) == (flag_code == CODE_16BIT)
5936                    || (flag_code == CODE_64BIT
5937                        && i.tm.opcode_modifier.jumpbyte)))
5938         {
5939           unsigned int prefix = DATA_PREFIX_OPCODE;
5940
5941           if (i.tm.opcode_modifier.jumpbyte) /* jcxz, loop */
5942             prefix = ADDR_PREFIX_OPCODE;
5943
5944           if (!add_prefix (prefix))
5945             return 0;
5946         }
5947
5948       /* Set mode64 for an operand.  */
5949       if (i.suffix == QWORD_MNEM_SUFFIX
5950           && flag_code == CODE_64BIT
5951           && !i.tm.opcode_modifier.norex64
5952           /* Special case for xchg %rax,%rax.  It is NOP and doesn't
5953              need rex64. */
5954           && ! (i.operands == 2
5955                 && i.tm.base_opcode == 0x90
5956                 && i.tm.extension_opcode == None
5957                 && operand_type_equal (&i.types [0], &acc64)
5958                 && operand_type_equal (&i.types [1], &acc64)))
5959         i.rex |= REX_W;
5960
5961       break;
5962     }
5963
5964   return 1;
5965 }
5966
5967 static int
5968 check_byte_reg (void)
5969 {
5970   int op;
5971
5972   for (op = i.operands; --op >= 0;)
5973     {
5974       /* Skip non-register operands. */
5975       if (!i.types[op].bitfield.reg)
5976         continue;
5977
5978       /* If this is an eight bit register, it's OK.  If it's the 16 or
5979          32 bit version of an eight bit register, we will just use the
5980          low portion, and that's OK too.  */
5981       if (i.types[op].bitfield.byte)
5982         continue;
5983
5984       /* I/O port address operands are OK too.  */
5985       if (i.tm.operand_types[op].bitfield.inoutportreg)
5986         continue;
5987
5988       /* crc32 doesn't generate this warning.  */
5989       if (i.tm.base_opcode == 0xf20f38f0)
5990         continue;
5991
5992       if ((i.types[op].bitfield.word
5993            || i.types[op].bitfield.dword
5994            || i.types[op].bitfield.qword)
5995           && i.op[op].regs->reg_num < 4
5996           /* Prohibit these changes in 64bit mode, since the lowering
5997              would be more complicated.  */
5998           && flag_code != CODE_64BIT)
5999         {
6000 #if REGISTER_WARNINGS
6001           if (!quiet_warnings)
6002             as_warn (_("using `%s%s' instead of `%s%s' due to `%c' suffix"),
6003                      register_prefix,
6004                      (i.op[op].regs + (i.types[op].bitfield.word
6005                                        ? REGNAM_AL - REGNAM_AX
6006                                        : REGNAM_AL - REGNAM_EAX))->reg_name,
6007                      register_prefix,
6008                      i.op[op].regs->reg_name,
6009                      i.suffix);
6010 #endif
6011           continue;
6012         }
6013       /* Any other register is bad.  */
6014       if (i.types[op].bitfield.reg
6015           || i.types[op].bitfield.regmmx
6016           || i.types[op].bitfield.regsimd
6017           || i.types[op].bitfield.sreg2
6018           || i.types[op].bitfield.sreg3
6019           || i.types[op].bitfield.control
6020           || i.types[op].bitfield.debug
6021           || i.types[op].bitfield.test)
6022         {
6023           as_bad (_("`%s%s' not allowed with `%s%c'"),
6024                   register_prefix,
6025                   i.op[op].regs->reg_name,
6026                   i.tm.name,
6027                   i.suffix);
6028           return 0;
6029         }
6030     }
6031   return 1;
6032 }
6033
6034 static int
6035 check_long_reg (void)
6036 {
6037   int op;
6038
6039   for (op = i.operands; --op >= 0;)
6040     /* Skip non-register operands. */
6041     if (!i.types[op].bitfield.reg)
6042       continue;
6043     /* Reject eight bit registers, except where the template requires
6044        them. (eg. movzb)  */
6045     else if (i.types[op].bitfield.byte
6046              && (i.tm.operand_types[op].bitfield.reg
6047                  || i.tm.operand_types[op].bitfield.acc)
6048              && (i.tm.operand_types[op].bitfield.word
6049                  || i.tm.operand_types[op].bitfield.dword))
6050       {
6051         as_bad (_("`%s%s' not allowed with `%s%c'"),
6052                 register_prefix,
6053                 i.op[op].regs->reg_name,
6054                 i.tm.name,
6055                 i.suffix);
6056         return 0;
6057       }
6058     /* Warn if the e prefix on a general reg is missing.  */
6059     else if ((!quiet_warnings || flag_code == CODE_64BIT)
6060              && i.types[op].bitfield.word
6061              && (i.tm.operand_types[op].bitfield.reg
6062                  || i.tm.operand_types[op].bitfield.acc)
6063              && i.tm.operand_types[op].bitfield.dword)
6064       {
6065         /* Prohibit these changes in the 64bit mode, since the
6066            lowering is more complicated.  */
6067         if (flag_code == CODE_64BIT)
6068           {
6069             as_bad (_("incorrect register `%s%s' used with `%c' suffix"),
6070                     register_prefix, i.op[op].regs->reg_name,
6071                     i.suffix);
6072             return 0;
6073           }
6074 #if REGISTER_WARNINGS
6075         as_warn (_("using `%s%s' instead of `%s%s' due to `%c' suffix"),
6076                  register_prefix,
6077                  (i.op[op].regs + REGNAM_EAX - REGNAM_AX)->reg_name,
6078                  register_prefix, i.op[op].regs->reg_name, i.suffix);
6079 #endif
6080       }
6081     /* Warn if the r prefix on a general reg is present.  */
6082     else if (i.types[op].bitfield.qword
6083              && (i.tm.operand_types[op].bitfield.reg
6084                  || i.tm.operand_types[op].bitfield.acc)
6085              && i.tm.operand_types[op].bitfield.dword)
6086       {
6087         if (intel_syntax
6088             && i.tm.opcode_modifier.toqword
6089             && !i.types[0].bitfield.regsimd)
6090           {
6091             /* Convert to QWORD.  We want REX byte. */
6092             i.suffix = QWORD_MNEM_SUFFIX;
6093           }
6094         else
6095           {
6096             as_bad (_("incorrect register `%s%s' used with `%c' suffix"),
6097                     register_prefix, i.op[op].regs->reg_name,
6098                     i.suffix);
6099             return 0;
6100           }
6101       }
6102   return 1;
6103 }
6104
6105 static int
6106 check_qword_reg (void)
6107 {
6108   int op;
6109
6110   for (op = i.operands; --op >= 0; )
6111     /* Skip non-register operands. */
6112     if (!i.types[op].bitfield.reg)
6113       continue;
6114     /* Reject eight bit registers, except where the template requires
6115        them. (eg. movzb)  */
6116     else if (i.types[op].bitfield.byte
6117              && (i.tm.operand_types[op].bitfield.reg
6118                  || i.tm.operand_types[op].bitfield.acc)
6119              && (i.tm.operand_types[op].bitfield.word
6120                  || i.tm.operand_types[op].bitfield.dword))
6121       {
6122         as_bad (_("`%s%s' not allowed with `%s%c'"),
6123                 register_prefix,
6124                 i.op[op].regs->reg_name,
6125                 i.tm.name,
6126                 i.suffix);
6127         return 0;
6128       }
6129     /* Warn if the r prefix on a general reg is missing.  */
6130     else if ((i.types[op].bitfield.word
6131               || i.types[op].bitfield.dword)
6132              && (i.tm.operand_types[op].bitfield.reg
6133                  || i.tm.operand_types[op].bitfield.acc)
6134              && i.tm.operand_types[op].bitfield.qword)
6135       {
6136         /* Prohibit these changes in the 64bit mode, since the
6137            lowering is more complicated.  */
6138         if (intel_syntax
6139             && i.tm.opcode_modifier.todword
6140             && !i.types[0].bitfield.regsimd)
6141           {
6142             /* Convert to DWORD.  We don't want REX byte. */
6143             i.suffix = LONG_MNEM_SUFFIX;
6144           }
6145         else
6146           {
6147             as_bad (_("incorrect register `%s%s' used with `%c' suffix"),
6148                     register_prefix, i.op[op].regs->reg_name,
6149                     i.suffix);
6150             return 0;
6151           }
6152       }
6153   return 1;
6154 }
6155
6156 static int
6157 check_word_reg (void)
6158 {
6159   int op;
6160   for (op = i.operands; --op >= 0;)
6161     /* Skip non-register operands. */
6162     if (!i.types[op].bitfield.reg)
6163       continue;
6164     /* Reject eight bit registers, except where the template requires
6165        them. (eg. movzb)  */
6166     else if (i.types[op].bitfield.byte
6167              && (i.tm.operand_types[op].bitfield.reg
6168                  || i.tm.operand_types[op].bitfield.acc)
6169              && (i.tm.operand_types[op].bitfield.word
6170                  || i.tm.operand_types[op].bitfield.dword))
6171       {
6172         as_bad (_("`%s%s' not allowed with `%s%c'"),
6173                 register_prefix,
6174                 i.op[op].regs->reg_name,
6175                 i.tm.name,
6176                 i.suffix);
6177         return 0;
6178       }
6179     /* Warn if the e or r prefix on a general reg is present.  */
6180     else if ((!quiet_warnings || flag_code == CODE_64BIT)
6181              && (i.types[op].bitfield.dword
6182                  || i.types[op].bitfield.qword)
6183              && (i.tm.operand_types[op].bitfield.reg
6184                  || i.tm.operand_types[op].bitfield.acc)
6185              && i.tm.operand_types[op].bitfield.word)
6186       {
6187         /* Prohibit these changes in the 64bit mode, since the
6188            lowering is more complicated.  */
6189         if (flag_code == CODE_64BIT)
6190           {
6191             as_bad (_("incorrect register `%s%s' used with `%c' suffix"),
6192                     register_prefix, i.op[op].regs->reg_name,
6193                     i.suffix);
6194             return 0;
6195           }
6196 #if REGISTER_WARNINGS
6197         as_warn (_("using `%s%s' instead of `%s%s' due to `%c' suffix"),
6198                  register_prefix,
6199                  (i.op[op].regs + REGNAM_AX - REGNAM_EAX)->reg_name,
6200                  register_prefix, i.op[op].regs->reg_name, i.suffix);
6201 #endif
6202       }
6203   return 1;
6204 }
6205
6206 static int
6207 update_imm (unsigned int j)
6208 {
6209   i386_operand_type overlap = i.types[j];
6210   if ((overlap.bitfield.imm8
6211        || overlap.bitfield.imm8s
6212        || overlap.bitfield.imm16
6213        || overlap.bitfield.imm32
6214        || overlap.bitfield.imm32s
6215        || overlap.bitfield.imm64)
6216       && !operand_type_equal (&overlap, &imm8)
6217       && !operand_type_equal (&overlap, &imm8s)
6218       && !operand_type_equal (&overlap, &imm16)
6219       && !operand_type_equal (&overlap, &imm32)
6220       && !operand_type_equal (&overlap, &imm32s)
6221       && !operand_type_equal (&overlap, &imm64))
6222     {
6223       if (i.suffix)
6224         {
6225           i386_operand_type temp;
6226
6227           operand_type_set (&temp, 0);
6228           if (i.suffix == BYTE_MNEM_SUFFIX)
6229             {
6230               temp.bitfield.imm8 = overlap.bitfield.imm8;
6231               temp.bitfield.imm8s = overlap.bitfield.imm8s;
6232             }
6233           else if (i.suffix == WORD_MNEM_SUFFIX)
6234             temp.bitfield.imm16 = overlap.bitfield.imm16;
6235           else if (i.suffix == QWORD_MNEM_SUFFIX)
6236             {
6237               temp.bitfield.imm64 = overlap.bitfield.imm64;
6238               temp.bitfield.imm32s = overlap.bitfield.imm32s;
6239             }
6240           else
6241             temp.bitfield.imm32 = overlap.bitfield.imm32;
6242           overlap = temp;
6243         }
6244       else if (operand_type_equal (&overlap, &imm16_32_32s)
6245                || operand_type_equal (&overlap, &imm16_32)
6246                || operand_type_equal (&overlap, &imm16_32s))
6247         {
6248           if ((flag_code == CODE_16BIT) ^ (i.prefix[DATA_PREFIX] != 0))
6249             overlap = imm16;
6250           else
6251             overlap = imm32s;
6252         }
6253       if (!operand_type_equal (&overlap, &imm8)
6254           && !operand_type_equal (&overlap, &imm8s)
6255           && !operand_type_equal (&overlap, &imm16)
6256           && !operand_type_equal (&overlap, &imm32)
6257           && !operand_type_equal (&overlap, &imm32s)
6258           && !operand_type_equal (&overlap, &imm64))
6259         {
6260           as_bad (_("no instruction mnemonic suffix given; "
6261                     "can't determine immediate size"));
6262           return 0;
6263         }
6264     }
6265   i.types[j] = overlap;
6266
6267   return 1;
6268 }
6269
6270 static int
6271 finalize_imm (void)
6272 {
6273   unsigned int j, n;
6274
6275   /* Update the first 2 immediate operands.  */
6276   n = i.operands > 2 ? 2 : i.operands;
6277   if (n)
6278     {
6279       for (j = 0; j < n; j++)
6280         if (update_imm (j) == 0)
6281           return 0;
6282
6283       /* The 3rd operand can't be immediate operand.  */
6284       gas_assert (operand_type_check (i.types[2], imm) == 0);
6285     }
6286
6287   return 1;
6288 }
6289
6290 static int
6291 process_operands (void)
6292 {
6293   /* Default segment register this instruction will use for memory
6294      accesses.  0 means unknown.  This is only for optimizing out
6295      unnecessary segment overrides.  */
6296   const seg_entry *default_seg = 0;
6297
6298   if (i.tm.opcode_modifier.sse2avx && i.tm.opcode_modifier.vexvvvv)
6299     {
6300       unsigned int dupl = i.operands;
6301       unsigned int dest = dupl - 1;
6302       unsigned int j;
6303
6304       /* The destination must be an xmm register.  */
6305       gas_assert (i.reg_operands
6306                   && MAX_OPERANDS > dupl
6307                   && operand_type_equal (&i.types[dest], &regxmm));
6308
6309       if (i.tm.operand_types[0].bitfield.acc
6310           && i.tm.operand_types[0].bitfield.xmmword)
6311         {
6312           if (i.tm.opcode_modifier.vexsources == VEX3SOURCES)
6313             {
6314               /* Keep xmm0 for instructions with VEX prefix and 3
6315                  sources.  */
6316               i.tm.operand_types[0].bitfield.acc = 0;
6317               i.tm.operand_types[0].bitfield.regsimd = 1;
6318               goto duplicate;
6319             }
6320           else
6321             {
6322               /* We remove the first xmm0 and keep the number of
6323                  operands unchanged, which in fact duplicates the
6324                  destination.  */
6325               for (j = 1; j < i.operands; j++)
6326                 {
6327                   i.op[j - 1] = i.op[j];
6328                   i.types[j - 1] = i.types[j];
6329                   i.tm.operand_types[j - 1] = i.tm.operand_types[j];
6330                 }
6331             }
6332         }
6333       else if (i.tm.opcode_modifier.implicit1stxmm0)
6334         {
6335           gas_assert ((MAX_OPERANDS - 1) > dupl
6336                       && (i.tm.opcode_modifier.vexsources
6337                           == VEX3SOURCES));
6338
6339           /* Add the implicit xmm0 for instructions with VEX prefix
6340              and 3 sources.  */
6341           for (j = i.operands; j > 0; j--)
6342             {
6343               i.op[j] = i.op[j - 1];
6344               i.types[j] = i.types[j - 1];
6345               i.tm.operand_types[j] = i.tm.operand_types[j - 1];
6346             }
6347           i.op[0].regs
6348             = (const reg_entry *) hash_find (reg_hash, "xmm0");
6349           i.types[0] = regxmm;
6350           i.tm.operand_types[0] = regxmm;
6351
6352           i.operands += 2;
6353           i.reg_operands += 2;
6354           i.tm.operands += 2;
6355
6356           dupl++;
6357           dest++;
6358           i.op[dupl] = i.op[dest];
6359           i.types[dupl] = i.types[dest];
6360           i.tm.operand_types[dupl] = i.tm.operand_types[dest];
6361         }
6362       else
6363         {
6364 duplicate:
6365           i.operands++;
6366           i.reg_operands++;
6367           i.tm.operands++;
6368
6369           i.op[dupl] = i.op[dest];
6370           i.types[dupl] = i.types[dest];
6371           i.tm.operand_types[dupl] = i.tm.operand_types[dest];
6372         }
6373
6374        if (i.tm.opcode_modifier.immext)
6375          process_immext ();
6376     }
6377   else if (i.tm.operand_types[0].bitfield.acc
6378            && i.tm.operand_types[0].bitfield.xmmword)
6379     {
6380       unsigned int j;
6381
6382       for (j = 1; j < i.operands; j++)
6383         {
6384           i.op[j - 1] = i.op[j];
6385           i.types[j - 1] = i.types[j];
6386
6387           /* We need to adjust fields in i.tm since they are used by
6388              build_modrm_byte.  */
6389           i.tm.operand_types [j - 1] = i.tm.operand_types [j];
6390         }
6391
6392       i.operands--;
6393       i.reg_operands--;
6394       i.tm.operands--;
6395     }
6396   else if (i.tm.opcode_modifier.implicitquadgroup)
6397     {
6398       unsigned int regnum, first_reg_in_group, last_reg_in_group;
6399
6400       /* The second operand must be {x,y,z}mmN, where N is a multiple of 4. */
6401       gas_assert (i.operands >= 2 && i.types[1].bitfield.regsimd);
6402       regnum = register_number (i.op[1].regs);
6403       first_reg_in_group = regnum & ~3;
6404       last_reg_in_group = first_reg_in_group + 3;
6405       if (regnum != first_reg_in_group)
6406         as_warn (_("source register `%s%s' implicitly denotes"
6407                    " `%s%.3s%u' to `%s%.3s%u' source group in `%s'"),
6408                  register_prefix, i.op[1].regs->reg_name,
6409                  register_prefix, i.op[1].regs->reg_name, first_reg_in_group,
6410                  register_prefix, i.op[1].regs->reg_name, last_reg_in_group,
6411                  i.tm.name);
6412     }
6413   else if (i.tm.opcode_modifier.regkludge)
6414     {
6415       /* The imul $imm, %reg instruction is converted into
6416          imul $imm, %reg, %reg, and the clr %reg instruction
6417          is converted into xor %reg, %reg.  */
6418
6419       unsigned int first_reg_op;
6420
6421       if (operand_type_check (i.types[0], reg))
6422         first_reg_op = 0;
6423       else
6424         first_reg_op = 1;
6425       /* Pretend we saw the extra register operand.  */
6426       gas_assert (i.reg_operands == 1
6427                   && i.op[first_reg_op + 1].regs == 0);
6428       i.op[first_reg_op + 1].regs = i.op[first_reg_op].regs;
6429       i.types[first_reg_op + 1] = i.types[first_reg_op];
6430       i.operands++;
6431       i.reg_operands++;
6432     }
6433
6434   if (i.tm.opcode_modifier.shortform)
6435     {
6436       if (i.types[0].bitfield.sreg2
6437           || i.types[0].bitfield.sreg3)
6438         {
6439           if (i.tm.base_opcode == POP_SEG_SHORT
6440               && i.op[0].regs->reg_num == 1)
6441             {
6442               as_bad (_("you can't `pop %scs'"), register_prefix);
6443               return 0;
6444             }
6445           i.tm.base_opcode |= (i.op[0].regs->reg_num << 3);
6446           if ((i.op[0].regs->reg_flags & RegRex) != 0)
6447             i.rex |= REX_B;
6448         }
6449       else
6450         {
6451           /* The register or float register operand is in operand
6452              0 or 1.  */
6453           unsigned int op;
6454
6455           if ((i.types[0].bitfield.reg && i.types[0].bitfield.tbyte)
6456               || operand_type_check (i.types[0], reg))
6457             op = 0;
6458           else
6459             op = 1;
6460           /* Register goes in low 3 bits of opcode.  */
6461           i.tm.base_opcode |= i.op[op].regs->reg_num;
6462           if ((i.op[op].regs->reg_flags & RegRex) != 0)
6463             i.rex |= REX_B;
6464           if (!quiet_warnings && i.tm.opcode_modifier.ugh)
6465             {
6466               /* Warn about some common errors, but press on regardless.
6467                  The first case can be generated by gcc (<= 2.8.1).  */
6468               if (i.operands == 2)
6469                 {
6470                   /* Reversed arguments on faddp, fsubp, etc.  */
6471                   as_warn (_("translating to `%s %s%s,%s%s'"), i.tm.name,
6472                            register_prefix, i.op[!intel_syntax].regs->reg_name,
6473                            register_prefix, i.op[intel_syntax].regs->reg_name);
6474                 }
6475               else
6476                 {
6477                   /* Extraneous `l' suffix on fp insn.  */
6478                   as_warn (_("translating to `%s %s%s'"), i.tm.name,
6479                            register_prefix, i.op[0].regs->reg_name);
6480                 }
6481             }
6482         }
6483     }
6484   else if (i.tm.opcode_modifier.modrm)
6485     {
6486       /* The opcode is completed (modulo i.tm.extension_opcode which
6487          must be put into the modrm byte).  Now, we make the modrm and
6488          index base bytes based on all the info we've collected.  */
6489
6490       default_seg = build_modrm_byte ();
6491     }
6492   else if ((i.tm.base_opcode & ~0x3) == MOV_AX_DISP32)
6493     {
6494       default_seg = &ds;
6495     }
6496   else if (i.tm.opcode_modifier.isstring)
6497     {
6498       /* For the string instructions that allow a segment override
6499          on one of their operands, the default segment is ds.  */
6500       default_seg = &ds;
6501     }
6502
6503   if (i.tm.base_opcode == 0x8d /* lea */
6504       && i.seg[0]
6505       && !quiet_warnings)
6506     as_warn (_("segment override on `%s' is ineffectual"), i.tm.name);
6507
6508   /* If a segment was explicitly specified, and the specified segment
6509      is not the default, use an opcode prefix to select it.  If we
6510      never figured out what the default segment is, then default_seg
6511      will be zero at this point, and the specified segment prefix will
6512      always be used.  */
6513   if ((i.seg[0]) && (i.seg[0] != default_seg))
6514     {
6515       if (!add_prefix (i.seg[0]->seg_prefix))
6516         return 0;
6517     }
6518   return 1;
6519 }
6520
6521 static const seg_entry *
6522 build_modrm_byte (void)
6523 {
6524   const seg_entry *default_seg = 0;
6525   unsigned int source, dest;
6526   int vex_3_sources;
6527
6528   /* The first operand of instructions with VEX prefix and 3 sources
6529      must be VEX_Imm4.  */
6530   vex_3_sources = i.tm.opcode_modifier.vexsources == VEX3SOURCES;
6531   if (vex_3_sources)
6532     {
6533       unsigned int nds, reg_slot;
6534       expressionS *exp;
6535
6536       if (i.tm.opcode_modifier.veximmext
6537           && i.tm.opcode_modifier.immext)
6538         {
6539           dest = i.operands - 2;
6540           gas_assert (dest == 3);
6541         }
6542       else
6543         dest = i.operands - 1;
6544       nds = dest - 1;
6545
6546       /* There are 2 kinds of instructions:
6547          1. 5 operands: 4 register operands or 3 register operands
6548          plus 1 memory operand plus one Vec_Imm4 operand, VexXDS, and
6549          VexW0 or VexW1.  The destination must be either XMM, YMM or
6550          ZMM register.
6551          2. 4 operands: 4 register operands or 3 register operands
6552          plus 1 memory operand, VexXDS, and VexImmExt  */
6553       gas_assert ((i.reg_operands == 4
6554                    || (i.reg_operands == 3 && i.mem_operands == 1))
6555                   && i.tm.opcode_modifier.vexvvvv == VEXXDS
6556                   && (i.tm.opcode_modifier.veximmext
6557                       || (i.imm_operands == 1
6558                           && i.types[0].bitfield.vec_imm4
6559                           && (i.tm.opcode_modifier.vexw == VEXW0
6560                               || i.tm.opcode_modifier.vexw == VEXW1)
6561                           && i.tm.operand_types[dest].bitfield.regsimd)));
6562
6563       if (i.imm_operands == 0)
6564         {
6565           /* When there is no immediate operand, generate an 8bit
6566              immediate operand to encode the first operand.  */
6567           exp = &im_expressions[i.imm_operands++];
6568           i.op[i.operands].imms = exp;
6569           i.types[i.operands] = imm8;
6570           i.operands++;
6571           /* If VexW1 is set, the first operand is the source and
6572              the second operand is encoded in the immediate operand.  */
6573           if (i.tm.opcode_modifier.vexw == VEXW1)
6574             {
6575               source = 0;
6576               reg_slot = 1;
6577             }
6578           else
6579             {
6580               source = 1;
6581               reg_slot = 0;
6582             }
6583
6584           /* FMA swaps REG and NDS.  */
6585           if (i.tm.cpu_flags.bitfield.cpufma)
6586             {
6587               unsigned int tmp;
6588               tmp = reg_slot;
6589               reg_slot = nds;
6590               nds = tmp;
6591             }
6592
6593           gas_assert (i.tm.operand_types[reg_slot].bitfield.regsimd);
6594           exp->X_op = O_constant;
6595           exp->X_add_number = register_number (i.op[reg_slot].regs) << 4;
6596           gas_assert ((i.op[reg_slot].regs->reg_flags & RegVRex) == 0);
6597         }
6598       else
6599         {
6600           unsigned int imm_slot;
6601
6602           if (i.tm.opcode_modifier.vexw == VEXW0)
6603             {
6604               /* If VexW0 is set, the third operand is the source and
6605                  the second operand is encoded in the immediate
6606                  operand.  */
6607               source = 2;
6608               reg_slot = 1;
6609             }
6610           else
6611             {
6612               /* VexW1 is set, the second operand is the source and
6613                  the third operand is encoded in the immediate
6614                  operand.  */
6615               source = 1;
6616               reg_slot = 2;
6617             }
6618
6619           if (i.tm.opcode_modifier.immext)
6620             {
6621               /* When ImmExt is set, the immediate byte is the last
6622                  operand.  */
6623               imm_slot = i.operands - 1;
6624               source--;
6625               reg_slot--;
6626             }
6627           else
6628             {
6629               imm_slot = 0;
6630
6631               /* Turn on Imm8 so that output_imm will generate it.  */
6632               i.types[imm_slot].bitfield.imm8 = 1;
6633             }
6634
6635           gas_assert (i.tm.operand_types[reg_slot].bitfield.regsimd);
6636           i.op[imm_slot].imms->X_add_number
6637               |= register_number (i.op[reg_slot].regs) << 4;
6638           gas_assert ((i.op[reg_slot].regs->reg_flags & RegVRex) == 0);
6639         }
6640
6641       gas_assert (i.tm.operand_types[nds].bitfield.regsimd);
6642       i.vex.register_specifier = i.op[nds].regs;
6643     }
6644   else
6645     source = dest = 0;
6646
6647   /* i.reg_operands MUST be the number of real register operands;
6648      implicit registers do not count.  If there are 3 register
6649      operands, it must be a instruction with VexNDS.  For a
6650      instruction with VexNDD, the destination register is encoded
6651      in VEX prefix.  If there are 4 register operands, it must be
6652      a instruction with VEX prefix and 3 sources.  */
6653   if (i.mem_operands == 0
6654       && ((i.reg_operands == 2
6655            && i.tm.opcode_modifier.vexvvvv <= VEXXDS)
6656           || (i.reg_operands == 3
6657               && i.tm.opcode_modifier.vexvvvv == VEXXDS)
6658           || (i.reg_operands == 4 && vex_3_sources)))
6659     {
6660       switch (i.operands)
6661         {
6662         case 2:
6663           source = 0;
6664           break;
6665         case 3:
6666           /* When there are 3 operands, one of them may be immediate,
6667              which may be the first or the last operand.  Otherwise,
6668              the first operand must be shift count register (cl) or it
6669              is an instruction with VexNDS. */
6670           gas_assert (i.imm_operands == 1
6671                       || (i.imm_operands == 0
6672                           && (i.tm.opcode_modifier.vexvvvv == VEXXDS
6673                               || i.types[0].bitfield.shiftcount)));
6674           if (operand_type_check (i.types[0], imm)
6675               || i.types[0].bitfield.shiftcount)
6676             source = 1;
6677           else
6678             source = 0;
6679           break;
6680         case 4:
6681           /* When there are 4 operands, the first two must be 8bit
6682              immediate operands. The source operand will be the 3rd
6683              one.
6684
6685              For instructions with VexNDS, if the first operand
6686              an imm8, the source operand is the 2nd one.  If the last
6687              operand is imm8, the source operand is the first one.  */
6688           gas_assert ((i.imm_operands == 2
6689                        && i.types[0].bitfield.imm8
6690                        && i.types[1].bitfield.imm8)
6691                       || (i.tm.opcode_modifier.vexvvvv == VEXXDS
6692                           && i.imm_operands == 1
6693                           && (i.types[0].bitfield.imm8
6694                               || i.types[i.operands - 1].bitfield.imm8
6695                               || i.rounding)));
6696           if (i.imm_operands == 2)
6697             source = 2;
6698           else
6699             {
6700               if (i.types[0].bitfield.imm8)
6701                 source = 1;
6702               else
6703                 source = 0;
6704             }
6705           break;
6706         case 5:
6707           if (is_evex_encoding (&i.tm))
6708             {
6709               /* For EVEX instructions, when there are 5 operands, the
6710                  first one must be immediate operand.  If the second one
6711                  is immediate operand, the source operand is the 3th
6712                  one.  If the last one is immediate operand, the source
6713                  operand is the 2nd one.  */
6714               gas_assert (i.imm_operands == 2
6715                           && i.tm.opcode_modifier.sae
6716                           && operand_type_check (i.types[0], imm));
6717               if (operand_type_check (i.types[1], imm))
6718                 source = 2;
6719               else if (operand_type_check (i.types[4], imm))
6720                 source = 1;
6721               else
6722                 abort ();
6723             }
6724           break;
6725         default:
6726           abort ();
6727         }
6728
6729       if (!vex_3_sources)
6730         {
6731           dest = source + 1;
6732
6733           /* RC/SAE operand could be between DEST and SRC.  That happens
6734              when one operand is GPR and the other one is XMM/YMM/ZMM
6735              register.  */
6736           if (i.rounding && i.rounding->operand == (int) dest)
6737             dest++;
6738
6739           if (i.tm.opcode_modifier.vexvvvv == VEXXDS)
6740             {
6741               /* For instructions with VexNDS, the register-only source
6742                  operand must be a 32/64bit integer, XMM, YMM, ZMM, or mask
6743                  register.  It is encoded in VEX prefix.  We need to
6744                  clear RegMem bit before calling operand_type_equal.  */
6745
6746               i386_operand_type op;
6747               unsigned int vvvv;
6748
6749               /* Check register-only source operand when two source
6750                  operands are swapped.  */
6751               if (!i.tm.operand_types[source].bitfield.baseindex
6752                   && i.tm.operand_types[dest].bitfield.baseindex)
6753                 {
6754                   vvvv = source;
6755                   source = dest;
6756                 }
6757               else
6758                 vvvv = dest;
6759
6760               op = i.tm.operand_types[vvvv];
6761               op.bitfield.regmem = 0;
6762               if ((dest + 1) >= i.operands
6763                   || ((!op.bitfield.reg
6764                        || (!op.bitfield.dword && !op.bitfield.qword))
6765                       && !op.bitfield.regsimd
6766                       && !operand_type_equal (&op, &regmask)))
6767                 abort ();
6768               i.vex.register_specifier = i.op[vvvv].regs;
6769               dest++;
6770             }
6771         }
6772
6773       i.rm.mode = 3;
6774       /* One of the register operands will be encoded in the i.tm.reg
6775          field, the other in the combined i.tm.mode and i.tm.regmem
6776          fields.  If no form of this instruction supports a memory
6777          destination operand, then we assume the source operand may
6778          sometimes be a memory operand and so we need to store the
6779          destination in the i.rm.reg field.  */
6780       if (!i.tm.operand_types[dest].bitfield.regmem
6781           && operand_type_check (i.tm.operand_types[dest], anymem) == 0)
6782         {
6783           i.rm.reg = i.op[dest].regs->reg_num;
6784           i.rm.regmem = i.op[source].regs->reg_num;
6785           if ((i.op[dest].regs->reg_flags & RegRex) != 0)
6786             i.rex |= REX_R;
6787           if ((i.op[dest].regs->reg_flags & RegVRex) != 0)
6788             i.vrex |= REX_R;
6789           if ((i.op[source].regs->reg_flags & RegRex) != 0)
6790             i.rex |= REX_B;
6791           if ((i.op[source].regs->reg_flags & RegVRex) != 0)
6792             i.vrex |= REX_B;
6793         }
6794       else
6795         {
6796           i.rm.reg = i.op[source].regs->reg_num;
6797           i.rm.regmem = i.op[dest].regs->reg_num;
6798           if ((i.op[dest].regs->reg_flags & RegRex) != 0)
6799             i.rex |= REX_B;
6800           if ((i.op[dest].regs->reg_flags & RegVRex) != 0)
6801             i.vrex |= REX_B;
6802           if ((i.op[source].regs->reg_flags & RegRex) != 0)
6803             i.rex |= REX_R;
6804           if ((i.op[source].regs->reg_flags & RegVRex) != 0)
6805             i.vrex |= REX_R;
6806         }
6807       if (flag_code != CODE_64BIT && (i.rex & (REX_R | REX_B)))
6808         {
6809           if (!i.types[0].bitfield.control
6810               && !i.types[1].bitfield.control)
6811             abort ();
6812           i.rex &= ~(REX_R | REX_B);
6813           add_prefix (LOCK_PREFIX_OPCODE);
6814         }
6815     }
6816   else
6817     {                   /* If it's not 2 reg operands...  */
6818       unsigned int mem;
6819
6820       if (i.mem_operands)
6821         {
6822           unsigned int fake_zero_displacement = 0;
6823           unsigned int op;
6824
6825           for (op = 0; op < i.operands; op++)
6826             if (operand_type_check (i.types[op], anymem))
6827               break;
6828           gas_assert (op < i.operands);
6829
6830           if (i.tm.opcode_modifier.vecsib)
6831             {
6832               if (i.index_reg->reg_num == RegEiz
6833                   || i.index_reg->reg_num == RegRiz)
6834                 abort ();
6835
6836               i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
6837               if (!i.base_reg)
6838                 {
6839                   i.sib.base = NO_BASE_REGISTER;
6840                   i.sib.scale = i.log2_scale_factor;
6841                   i.types[op].bitfield.disp8 = 0;
6842                   i.types[op].bitfield.disp16 = 0;
6843                   i.types[op].bitfield.disp64 = 0;
6844                   if (flag_code != CODE_64BIT || i.prefix[ADDR_PREFIX])
6845                     {
6846                       /* Must be 32 bit */
6847                       i.types[op].bitfield.disp32 = 1;
6848                       i.types[op].bitfield.disp32s = 0;
6849                     }
6850                   else
6851                     {
6852                       i.types[op].bitfield.disp32 = 0;
6853                       i.types[op].bitfield.disp32s = 1;
6854                     }
6855                 }
6856               i.sib.index = i.index_reg->reg_num;
6857               if ((i.index_reg->reg_flags & RegRex) != 0)
6858                 i.rex |= REX_X;
6859               if ((i.index_reg->reg_flags & RegVRex) != 0)
6860                 i.vrex |= REX_X;
6861             }
6862
6863           default_seg = &ds;
6864
6865           if (i.base_reg == 0)
6866             {
6867               i.rm.mode = 0;
6868               if (!i.disp_operands)
6869                 fake_zero_displacement = 1;
6870               if (i.index_reg == 0)
6871                 {
6872                   i386_operand_type newdisp;
6873
6874                   gas_assert (!i.tm.opcode_modifier.vecsib);
6875                   /* Operand is just <disp>  */
6876                   if (flag_code == CODE_64BIT)
6877                     {
6878                       /* 64bit mode overwrites the 32bit absolute
6879                          addressing by RIP relative addressing and
6880                          absolute addressing is encoded by one of the
6881                          redundant SIB forms.  */
6882                       i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
6883                       i.sib.base = NO_BASE_REGISTER;
6884                       i.sib.index = NO_INDEX_REGISTER;
6885                       newdisp = (!i.prefix[ADDR_PREFIX] ? disp32s : disp32);
6886                     }
6887                   else if ((flag_code == CODE_16BIT)
6888                            ^ (i.prefix[ADDR_PREFIX] != 0))
6889                     {
6890                       i.rm.regmem = NO_BASE_REGISTER_16;
6891                       newdisp = disp16;
6892                     }
6893                   else
6894                     {
6895                       i.rm.regmem = NO_BASE_REGISTER;
6896                       newdisp = disp32;
6897                     }
6898                   i.types[op] = operand_type_and_not (i.types[op], anydisp);
6899                   i.types[op] = operand_type_or (i.types[op], newdisp);
6900                 }
6901               else if (!i.tm.opcode_modifier.vecsib)
6902                 {
6903                   /* !i.base_reg && i.index_reg  */
6904                   if (i.index_reg->reg_num == RegEiz
6905                       || i.index_reg->reg_num == RegRiz)
6906                     i.sib.index = NO_INDEX_REGISTER;
6907                   else
6908                     i.sib.index = i.index_reg->reg_num;
6909                   i.sib.base = NO_BASE_REGISTER;
6910                   i.sib.scale = i.log2_scale_factor;
6911                   i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
6912                   i.types[op].bitfield.disp8 = 0;
6913                   i.types[op].bitfield.disp16 = 0;
6914                   i.types[op].bitfield.disp64 = 0;
6915                   if (flag_code != CODE_64BIT || i.prefix[ADDR_PREFIX])
6916                     {
6917                       /* Must be 32 bit */
6918                       i.types[op].bitfield.disp32 = 1;
6919                       i.types[op].bitfield.disp32s = 0;
6920                     }
6921                   else
6922                     {
6923                       i.types[op].bitfield.disp32 = 0;
6924                       i.types[op].bitfield.disp32s = 1;
6925                     }
6926                   if ((i.index_reg->reg_flags & RegRex) != 0)
6927                     i.rex |= REX_X;
6928                 }
6929             }
6930           /* RIP addressing for 64bit mode.  */
6931           else if (i.base_reg->reg_num == RegRip ||
6932                    i.base_reg->reg_num == RegEip)
6933             {
6934               gas_assert (!i.tm.opcode_modifier.vecsib);
6935               i.rm.regmem = NO_BASE_REGISTER;
6936               i.types[op].bitfield.disp8 = 0;
6937               i.types[op].bitfield.disp16 = 0;
6938               i.types[op].bitfield.disp32 = 0;
6939               i.types[op].bitfield.disp32s = 1;
6940               i.types[op].bitfield.disp64 = 0;
6941               i.flags[op] |= Operand_PCrel;
6942               if (! i.disp_operands)
6943                 fake_zero_displacement = 1;
6944             }
6945           else if (i.base_reg->reg_type.bitfield.word)
6946             {
6947               gas_assert (!i.tm.opcode_modifier.vecsib);
6948               switch (i.base_reg->reg_num)
6949                 {
6950                 case 3: /* (%bx)  */
6951                   if (i.index_reg == 0)
6952                     i.rm.regmem = 7;
6953                   else /* (%bx,%si) -> 0, or (%bx,%di) -> 1  */
6954                     i.rm.regmem = i.index_reg->reg_num - 6;
6955                   break;
6956                 case 5: /* (%bp)  */
6957                   default_seg = &ss;
6958                   if (i.index_reg == 0)
6959                     {
6960                       i.rm.regmem = 6;
6961                       if (operand_type_check (i.types[op], disp) == 0)
6962                         {
6963                           /* fake (%bp) into 0(%bp)  */
6964                           i.types[op].bitfield.disp8 = 1;
6965                           fake_zero_displacement = 1;
6966                         }
6967                     }
6968                   else /* (%bp,%si) -> 2, or (%bp,%di) -> 3  */
6969                     i.rm.regmem = i.index_reg->reg_num - 6 + 2;
6970                   break;
6971                 default: /* (%si) -> 4 or (%di) -> 5  */
6972                   i.rm.regmem = i.base_reg->reg_num - 6 + 4;
6973                 }
6974               i.rm.mode = mode_from_disp_size (i.types[op]);
6975             }
6976           else /* i.base_reg and 32/64 bit mode  */
6977             {
6978               if (flag_code == CODE_64BIT
6979                   && operand_type_check (i.types[op], disp))
6980                 {
6981                   i.types[op].bitfield.disp16 = 0;
6982                   i.types[op].bitfield.disp64 = 0;
6983                   if (i.prefix[ADDR_PREFIX] == 0)
6984                     {
6985                       i.types[op].bitfield.disp32 = 0;
6986                       i.types[op].bitfield.disp32s = 1;
6987                     }
6988                   else
6989                     {
6990                       i.types[op].bitfield.disp32 = 1;
6991                       i.types[op].bitfield.disp32s = 0;
6992                     }
6993                 }
6994
6995               if (!i.tm.opcode_modifier.vecsib)
6996                 i.rm.regmem = i.base_reg->reg_num;
6997               if ((i.base_reg->reg_flags & RegRex) != 0)
6998                 i.rex |= REX_B;
6999               i.sib.base = i.base_reg->reg_num;
7000               /* x86-64 ignores REX prefix bit here to avoid decoder
7001                  complications.  */
7002               if (!(i.base_reg->reg_flags & RegRex)
7003                   && (i.base_reg->reg_num == EBP_REG_NUM
7004                    || i.base_reg->reg_num == ESP_REG_NUM))
7005                   default_seg = &ss;
7006               if (i.base_reg->reg_num == 5 && i.disp_operands == 0)
7007                 {
7008                   fake_zero_displacement = 1;
7009                   i.types[op].bitfield.disp8 = 1;
7010                 }
7011               i.sib.scale = i.log2_scale_factor;
7012               if (i.index_reg == 0)
7013                 {
7014                   gas_assert (!i.tm.opcode_modifier.vecsib);
7015                   /* <disp>(%esp) becomes two byte modrm with no index
7016                      register.  We've already stored the code for esp
7017                      in i.rm.regmem ie. ESCAPE_TO_TWO_BYTE_ADDRESSING.
7018                      Any base register besides %esp will not use the
7019                      extra modrm byte.  */
7020                   i.sib.index = NO_INDEX_REGISTER;
7021                 }
7022               else if (!i.tm.opcode_modifier.vecsib)
7023                 {
7024                   if (i.index_reg->reg_num == RegEiz
7025                       || i.index_reg->reg_num == RegRiz)
7026                     i.sib.index = NO_INDEX_REGISTER;
7027                   else
7028                     i.sib.index = i.index_reg->reg_num;
7029                   i.rm.regmem = ESCAPE_TO_TWO_BYTE_ADDRESSING;
7030                   if ((i.index_reg->reg_flags & RegRex) != 0)
7031                     i.rex |= REX_X;
7032                 }
7033
7034               if (i.disp_operands
7035                   && (i.reloc[op] == BFD_RELOC_386_TLS_DESC_CALL
7036                       || i.reloc[op] == BFD_RELOC_X86_64_TLSDESC_CALL))
7037                 i.rm.mode = 0;
7038               else
7039                 {
7040                   if (!fake_zero_displacement
7041                       && !i.disp_operands
7042                       && i.disp_encoding)
7043                     {
7044                       fake_zero_displacement = 1;
7045                       if (i.disp_encoding == disp_encoding_8bit)
7046                         i.types[op].bitfield.disp8 = 1;
7047                       else
7048                         i.types[op].bitfield.disp32 = 1;
7049                     }
7050                   i.rm.mode = mode_from_disp_size (i.types[op]);
7051                 }
7052             }
7053
7054           if (fake_zero_displacement)
7055             {
7056               /* Fakes a zero displacement assuming that i.types[op]
7057                  holds the correct displacement size.  */
7058               expressionS *exp;
7059
7060               gas_assert (i.op[op].disps == 0);
7061               exp = &disp_expressions[i.disp_operands++];
7062               i.op[op].disps = exp;
7063               exp->X_op = O_constant;
7064               exp->X_add_number = 0;
7065               exp->X_add_symbol = (symbolS *) 0;
7066               exp->X_op_symbol = (symbolS *) 0;
7067             }
7068
7069           mem = op;
7070         }
7071       else
7072         mem = ~0;
7073
7074       if (i.tm.opcode_modifier.vexsources == XOP2SOURCES)
7075         {
7076           if (operand_type_check (i.types[0], imm))
7077             i.vex.register_specifier = NULL;
7078           else
7079             {
7080               /* VEX.vvvv encodes one of the sources when the first
7081                  operand is not an immediate.  */
7082               if (i.tm.opcode_modifier.vexw == VEXW0)
7083                 i.vex.register_specifier = i.op[0].regs;
7084               else
7085                 i.vex.register_specifier = i.op[1].regs;
7086             }
7087
7088           /* Destination is a XMM register encoded in the ModRM.reg
7089              and VEX.R bit.  */
7090           i.rm.reg = i.op[2].regs->reg_num;
7091           if ((i.op[2].regs->reg_flags & RegRex) != 0)
7092             i.rex |= REX_R;
7093
7094           /* ModRM.rm and VEX.B encodes the other source.  */
7095           if (!i.mem_operands)
7096             {
7097               i.rm.mode = 3;
7098
7099               if (i.tm.opcode_modifier.vexw == VEXW0)
7100                 i.rm.regmem = i.op[1].regs->reg_num;
7101               else
7102                 i.rm.regmem = i.op[0].regs->reg_num;
7103
7104               if ((i.op[1].regs->reg_flags & RegRex) != 0)
7105                 i.rex |= REX_B;
7106             }
7107         }
7108       else if (i.tm.opcode_modifier.vexvvvv == VEXLWP)
7109         {
7110           i.vex.register_specifier = i.op[2].regs;
7111           if (!i.mem_operands)
7112             {
7113               i.rm.mode = 3;
7114               i.rm.regmem = i.op[1].regs->reg_num;
7115               if ((i.op[1].regs->reg_flags & RegRex) != 0)
7116                 i.rex |= REX_B;
7117             }
7118         }
7119       /* Fill in i.rm.reg or i.rm.regmem field with register operand
7120          (if any) based on i.tm.extension_opcode.  Again, we must be
7121          careful to make sure that segment/control/debug/test/MMX
7122          registers are coded into the i.rm.reg field.  */
7123       else if (i.reg_operands)
7124         {
7125           unsigned int op;
7126           unsigned int vex_reg = ~0;
7127
7128           for (op = 0; op < i.operands; op++)
7129             if (i.types[op].bitfield.reg
7130                 || i.types[op].bitfield.regmmx
7131                 || i.types[op].bitfield.regsimd
7132                 || i.types[op].bitfield.regbnd
7133                 || i.types[op].bitfield.regmask
7134                 || i.types[op].bitfield.sreg2
7135                 || i.types[op].bitfield.sreg3
7136                 || i.types[op].bitfield.control
7137                 || i.types[op].bitfield.debug
7138                 || i.types[op].bitfield.test)
7139               break;
7140
7141           if (vex_3_sources)
7142             op = dest;
7143           else if (i.tm.opcode_modifier.vexvvvv == VEXXDS)
7144             {
7145               /* For instructions with VexNDS, the register-only
7146                  source operand is encoded in VEX prefix. */
7147               gas_assert (mem != (unsigned int) ~0);
7148
7149               if (op > mem)
7150                 {
7151                   vex_reg = op++;
7152                   gas_assert (op < i.operands);
7153                 }
7154               else
7155                 {
7156                   /* Check register-only source operand when two source
7157                      operands are swapped.  */
7158                   if (!i.tm.operand_types[op].bitfield.baseindex
7159                       && i.tm.operand_types[op + 1].bitfield.baseindex)
7160                     {
7161                       vex_reg = op;
7162                       op += 2;
7163                       gas_assert (mem == (vex_reg + 1)
7164                                   && op < i.operands);
7165                     }
7166                   else
7167                     {
7168                       vex_reg = op + 1;
7169                       gas_assert (vex_reg < i.operands);
7170                     }
7171                 }
7172             }
7173           else if (i.tm.opcode_modifier.vexvvvv == VEXNDD)
7174             {
7175               /* For instructions with VexNDD, the register destination
7176                  is encoded in VEX prefix.  */
7177               if (i.mem_operands == 0)
7178                 {
7179                   /* There is no memory operand.  */
7180                   gas_assert ((op + 2) == i.operands);
7181                   vex_reg = op + 1;
7182                 }
7183               else
7184                 {
7185                   /* There are only 2 non-immediate operands.  */
7186                   gas_assert (op < i.imm_operands + 2
7187                               && i.operands == i.imm_operands + 2);
7188                   vex_reg = i.imm_operands + 1;
7189                 }
7190             }
7191           else
7192             gas_assert (op < i.operands);
7193
7194           if (vex_reg != (unsigned int) ~0)
7195             {
7196               i386_operand_type *type = &i.tm.operand_types[vex_reg];
7197
7198               if ((!type->bitfield.reg
7199                    || (!type->bitfield.dword && !type->bitfield.qword))
7200                   && !type->bitfield.regsimd
7201                   && !operand_type_equal (type, &regmask))
7202                 abort ();
7203
7204               i.vex.register_specifier = i.op[vex_reg].regs;
7205             }
7206
7207           /* Don't set OP operand twice.  */
7208           if (vex_reg != op)
7209             {
7210               /* If there is an extension opcode to put here, the
7211                  register number must be put into the regmem field.  */
7212               if (i.tm.extension_opcode != None)
7213                 {
7214                   i.rm.regmem = i.op[op].regs->reg_num;
7215                   if ((i.op[op].regs->reg_flags & RegRex) != 0)
7216                     i.rex |= REX_B;
7217                   if ((i.op[op].regs->reg_flags & RegVRex) != 0)
7218                     i.vrex |= REX_B;
7219                 }
7220               else
7221                 {
7222                   i.rm.reg = i.op[op].regs->reg_num;
7223                   if ((i.op[op].regs->reg_flags & RegRex) != 0)
7224                     i.rex |= REX_R;
7225                   if ((i.op[op].regs->reg_flags & RegVRex) != 0)
7226                     i.vrex |= REX_R;
7227                 }
7228             }
7229
7230           /* Now, if no memory operand has set i.rm.mode = 0, 1, 2 we
7231              must set it to 3 to indicate this is a register operand
7232              in the regmem field.  */
7233           if (!i.mem_operands)
7234             i.rm.mode = 3;
7235         }
7236
7237       /* Fill in i.rm.reg field with extension opcode (if any).  */
7238       if (i.tm.extension_opcode != None)
7239         i.rm.reg = i.tm.extension_opcode;
7240     }
7241   return default_seg;
7242 }
7243
7244 static void
7245 output_branch (void)
7246 {
7247   char *p;
7248   int size;
7249   int code16;
7250   int prefix;
7251   relax_substateT subtype;
7252   symbolS *sym;
7253   offsetT off;
7254
7255   code16 = flag_code == CODE_16BIT ? CODE16 : 0;
7256   size = i.disp_encoding == disp_encoding_32bit ? BIG : SMALL;
7257
7258   prefix = 0;
7259   if (i.prefix[DATA_PREFIX] != 0)
7260     {
7261       prefix = 1;
7262       i.prefixes -= 1;
7263       code16 ^= CODE16;
7264     }
7265   /* Pentium4 branch hints.  */
7266   if (i.prefix[SEG_PREFIX] == CS_PREFIX_OPCODE /* not taken */
7267       || i.prefix[SEG_PREFIX] == DS_PREFIX_OPCODE /* taken */)
7268     {
7269       prefix++;
7270       i.prefixes--;
7271     }
7272   if (i.prefix[REX_PREFIX] != 0)
7273     {
7274       prefix++;
7275       i.prefixes--;
7276     }
7277
7278   /* BND prefixed jump.  */
7279   if (i.prefix[BND_PREFIX] != 0)
7280     {
7281       FRAG_APPEND_1_CHAR (i.prefix[BND_PREFIX]);
7282       i.prefixes -= 1;
7283     }
7284
7285   if (i.prefixes != 0 && !intel_syntax)
7286     as_warn (_("skipping prefixes on this instruction"));
7287
7288   /* It's always a symbol;  End frag & setup for relax.
7289      Make sure there is enough room in this frag for the largest
7290      instruction we may generate in md_convert_frag.  This is 2
7291      bytes for the opcode and room for the prefix and largest
7292      displacement.  */
7293   frag_grow (prefix + 2 + 4);
7294   /* Prefix and 1 opcode byte go in fr_fix.  */
7295   p = frag_more (prefix + 1);
7296   if (i.prefix[DATA_PREFIX] != 0)
7297     *p++ = DATA_PREFIX_OPCODE;
7298   if (i.prefix[SEG_PREFIX] == CS_PREFIX_OPCODE
7299       || i.prefix[SEG_PREFIX] == DS_PREFIX_OPCODE)
7300     *p++ = i.prefix[SEG_PREFIX];
7301   if (i.prefix[REX_PREFIX] != 0)
7302     *p++ = i.prefix[REX_PREFIX];
7303   *p = i.tm.base_opcode;
7304
7305   if ((unsigned char) *p == JUMP_PC_RELATIVE)
7306     subtype = ENCODE_RELAX_STATE (UNCOND_JUMP, size);
7307   else if (cpu_arch_flags.bitfield.cpui386)
7308     subtype = ENCODE_RELAX_STATE (COND_JUMP, size);
7309   else
7310     subtype = ENCODE_RELAX_STATE (COND_JUMP86, size);
7311   subtype |= code16;
7312
7313   sym = i.op[0].disps->X_add_symbol;
7314   off = i.op[0].disps->X_add_number;
7315
7316   if (i.op[0].disps->X_op != O_constant
7317       && i.op[0].disps->X_op != O_symbol)
7318     {
7319       /* Handle complex expressions.  */
7320       sym = make_expr_symbol (i.op[0].disps);
7321       off = 0;
7322     }
7323
7324   /* 1 possible extra opcode + 4 byte displacement go in var part.
7325      Pass reloc in fr_var.  */
7326   frag_var (rs_machine_dependent, 5, i.reloc[0], subtype, sym, off, p);
7327 }
7328
7329 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
7330 /* Return TRUE iff PLT32 relocation should be used for branching to
7331    symbol S.  */
7332
7333 static bfd_boolean
7334 need_plt32_p (symbolS *s)
7335 {
7336   /* PLT32 relocation is ELF only.  */
7337   if (!IS_ELF)
7338     return FALSE;
7339
7340   /* Since there is no need to prepare for PLT branch on x86-64, we
7341      can generate R_X86_64_PLT32, instead of R_X86_64_PC32, which can
7342      be used as a marker for 32-bit PC-relative branches.  */
7343   if (!object_64bit)
7344     return FALSE;
7345
7346   /* Weak or undefined symbol need PLT32 relocation.  */
7347   if (S_IS_WEAK (s) || !S_IS_DEFINED (s))
7348     return TRUE;
7349
7350   /* Non-global symbol doesn't need PLT32 relocation.  */
7351   if (! S_IS_EXTERNAL (s))
7352     return FALSE;
7353
7354   /* Other global symbols need PLT32 relocation.  NB: Symbol with
7355      non-default visibilities are treated as normal global symbol
7356      so that PLT32 relocation can be used as a marker for 32-bit
7357      PC-relative branches.  It is useful for linker relaxation.  */
7358   return TRUE;
7359 }
7360 #endif
7361
7362 static void
7363 output_jump (void)
7364 {
7365   char *p;
7366   int size;
7367   fixS *fixP;
7368   bfd_reloc_code_real_type jump_reloc = i.reloc[0];
7369
7370   if (i.tm.opcode_modifier.jumpbyte)
7371     {
7372       /* This is a loop or jecxz type instruction.  */
7373       size = 1;
7374       if (i.prefix[ADDR_PREFIX] != 0)
7375         {
7376           FRAG_APPEND_1_CHAR (ADDR_PREFIX_OPCODE);
7377           i.prefixes -= 1;
7378         }
7379       /* Pentium4 branch hints.  */
7380       if (i.prefix[SEG_PREFIX] == CS_PREFIX_OPCODE /* not taken */
7381           || i.prefix[SEG_PREFIX] == DS_PREFIX_OPCODE /* taken */)
7382         {
7383           FRAG_APPEND_1_CHAR (i.prefix[SEG_PREFIX]);
7384           i.prefixes--;
7385         }
7386     }
7387   else
7388     {
7389       int code16;
7390
7391       code16 = 0;
7392       if (flag_code == CODE_16BIT)
7393         code16 = CODE16;
7394
7395       if (i.prefix[DATA_PREFIX] != 0)
7396         {
7397           FRAG_APPEND_1_CHAR (DATA_PREFIX_OPCODE);
7398           i.prefixes -= 1;
7399           code16 ^= CODE16;
7400         }
7401
7402       size = 4;
7403       if (code16)
7404         size = 2;
7405     }
7406
7407   if (i.prefix[REX_PREFIX] != 0)
7408     {
7409       FRAG_APPEND_1_CHAR (i.prefix[REX_PREFIX]);
7410       i.prefixes -= 1;
7411     }
7412
7413   /* BND prefixed jump.  */
7414   if (i.prefix[BND_PREFIX] != 0)
7415     {
7416       FRAG_APPEND_1_CHAR (i.prefix[BND_PREFIX]);
7417       i.prefixes -= 1;
7418     }
7419
7420   if (i.prefixes != 0 && !intel_syntax)
7421     as_warn (_("skipping prefixes on this instruction"));
7422
7423   p = frag_more (i.tm.opcode_length + size);
7424   switch (i.tm.opcode_length)
7425     {
7426     case 2:
7427       *p++ = i.tm.base_opcode >> 8;
7428       /* Fall through.  */
7429     case 1:
7430       *p++ = i.tm.base_opcode;
7431       break;
7432     default:
7433       abort ();
7434     }
7435
7436 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
7437   if (size == 4
7438       && jump_reloc == NO_RELOC
7439       && need_plt32_p (i.op[0].disps->X_add_symbol))
7440     jump_reloc = BFD_RELOC_X86_64_PLT32;
7441 #endif
7442
7443   jump_reloc = reloc (size, 1, 1, jump_reloc);
7444
7445   fixP = fix_new_exp (frag_now, p - frag_now->fr_literal, size,
7446                       i.op[0].disps, 1, jump_reloc);
7447
7448   /* All jumps handled here are signed, but don't use a signed limit
7449      check for 32 and 16 bit jumps as we want to allow wrap around at
7450      4G and 64k respectively.  */
7451   if (size == 1)
7452     fixP->fx_signed = 1;
7453 }
7454
7455 static void
7456 output_interseg_jump (void)
7457 {
7458   char *p;
7459   int size;
7460   int prefix;
7461   int code16;
7462
7463   code16 = 0;
7464   if (flag_code == CODE_16BIT)
7465     code16 = CODE16;
7466
7467   prefix = 0;
7468   if (i.prefix[DATA_PREFIX] != 0)
7469     {
7470       prefix = 1;
7471       i.prefixes -= 1;
7472       code16 ^= CODE16;
7473     }
7474   if (i.prefix[REX_PREFIX] != 0)
7475     {
7476       prefix++;
7477       i.prefixes -= 1;
7478     }
7479
7480   size = 4;
7481   if (code16)
7482     size = 2;
7483
7484   if (i.prefixes != 0 && !intel_syntax)
7485     as_warn (_("skipping prefixes on this instruction"));
7486
7487   /* 1 opcode; 2 segment; offset  */
7488   p = frag_more (prefix + 1 + 2 + size);
7489
7490   if (i.prefix[DATA_PREFIX] != 0)
7491     *p++ = DATA_PREFIX_OPCODE;
7492
7493   if (i.prefix[REX_PREFIX] != 0)
7494     *p++ = i.prefix[REX_PREFIX];
7495
7496   *p++ = i.tm.base_opcode;
7497   if (i.op[1].imms->X_op == O_constant)
7498     {
7499       offsetT n = i.op[1].imms->X_add_number;
7500
7501       if (size == 2
7502           && !fits_in_unsigned_word (n)
7503           && !fits_in_signed_word (n))
7504         {
7505           as_bad (_("16-bit jump out of range"));
7506           return;
7507         }
7508       md_number_to_chars (p, n, size);
7509     }
7510   else
7511     fix_new_exp (frag_now, p - frag_now->fr_literal, size,
7512                  i.op[1].imms, 0, reloc (size, 0, 0, i.reloc[1]));
7513   if (i.op[0].imms->X_op != O_constant)
7514     as_bad (_("can't handle non absolute segment in `%s'"),
7515             i.tm.name);
7516   md_number_to_chars (p + size, (valueT) i.op[0].imms->X_add_number, 2);
7517 }
7518
7519 static void
7520 output_insn (void)
7521 {
7522   fragS *insn_start_frag;
7523   offsetT insn_start_off;
7524
7525   /* Tie dwarf2 debug info to the address at the start of the insn.
7526      We can't do this after the insn has been output as the current
7527      frag may have been closed off.  eg. by frag_var.  */
7528   dwarf2_emit_insn (0);
7529
7530   insn_start_frag = frag_now;
7531   insn_start_off = frag_now_fix ();
7532
7533   /* Output jumps.  */
7534   if (i.tm.opcode_modifier.jump)
7535     output_branch ();
7536   else if (i.tm.opcode_modifier.jumpbyte
7537            || i.tm.opcode_modifier.jumpdword)
7538     output_jump ();
7539   else if (i.tm.opcode_modifier.jumpintersegment)
7540     output_interseg_jump ();
7541   else
7542     {
7543       /* Output normal instructions here.  */
7544       char *p;
7545       unsigned char *q;
7546       unsigned int j;
7547       unsigned int prefix;
7548
7549       if (avoid_fence
7550          && i.tm.base_opcode == 0xfae
7551          && i.operands == 1
7552          && i.imm_operands == 1
7553          && (i.op[0].imms->X_add_number == 0xe8
7554              || i.op[0].imms->X_add_number == 0xf0
7555              || i.op[0].imms->X_add_number == 0xf8))
7556         {
7557           /* Encode lfence, mfence, and sfence as
7558              f0 83 04 24 00   lock addl $0x0, (%{re}sp).  */
7559           offsetT val = 0x240483f0ULL;
7560           p = frag_more (5);
7561           md_number_to_chars (p, val, 5);
7562           return;
7563         }
7564
7565       /* Some processors fail on LOCK prefix. This options makes
7566          assembler ignore LOCK prefix and serves as a workaround.  */
7567       if (omit_lock_prefix)
7568         {
7569           if (i.tm.base_opcode == LOCK_PREFIX_OPCODE)
7570             return;
7571           i.prefix[LOCK_PREFIX] = 0;
7572         }
7573
7574       /* Since the VEX/EVEX prefix contains the implicit prefix, we
7575          don't need the explicit prefix.  */
7576       if (!i.tm.opcode_modifier.vex && !i.tm.opcode_modifier.evex)
7577         {
7578           switch (i.tm.opcode_length)
7579             {
7580             case 3:
7581               if (i.tm.base_opcode & 0xff000000)
7582                 {
7583                   prefix = (i.tm.base_opcode >> 24) & 0xff;
7584                   goto check_prefix;
7585                 }
7586               break;
7587             case 2:
7588               if ((i.tm.base_opcode & 0xff0000) != 0)
7589                 {
7590                   prefix = (i.tm.base_opcode >> 16) & 0xff;
7591                   if (i.tm.cpu_flags.bitfield.cpupadlock)
7592                     {
7593 check_prefix:
7594                       if (prefix != REPE_PREFIX_OPCODE
7595                           || (i.prefix[REP_PREFIX]
7596                               != REPE_PREFIX_OPCODE))
7597                         add_prefix (prefix);
7598                     }
7599                   else
7600                     add_prefix (prefix);
7601                 }
7602               break;
7603             case 1:
7604               break;
7605             case 0:
7606               /* Check for pseudo prefixes.  */
7607               as_bad_where (insn_start_frag->fr_file,
7608                             insn_start_frag->fr_line,
7609                              _("pseudo prefix without instruction"));
7610               return;
7611             default:
7612               abort ();
7613             }
7614
7615 #if defined (OBJ_MAYBE_ELF) || defined (OBJ_ELF)
7616           /* For x32, add a dummy REX_OPCODE prefix for mov/add with
7617              R_X86_64_GOTTPOFF relocation so that linker can safely
7618              perform IE->LE optimization.  */
7619           if (x86_elf_abi == X86_64_X32_ABI
7620               && i.operands == 2
7621               && i.reloc[0] == BFD_RELOC_X86_64_GOTTPOFF
7622               && i.prefix[REX_PREFIX] == 0)
7623             add_prefix (REX_OPCODE);
7624 #endif
7625
7626           /* The prefix bytes.  */
7627           for (j = ARRAY_SIZE (i.prefix), q = i.prefix; j > 0; j--, q++)
7628             if (*q)
7629               FRAG_APPEND_1_CHAR (*q);
7630         }
7631       else
7632         {
7633           for (j = 0, q = i.prefix; j < ARRAY_SIZE (i.prefix); j++, q++)
7634             if (*q)
7635               switch (j)
7636                 {
7637                 case REX_PREFIX:
7638                   /* REX byte is encoded in VEX prefix.  */
7639                   break;
7640                 case SEG_PREFIX:
7641                 case ADDR_PREFIX:
7642                   FRAG_APPEND_1_CHAR (*q);
7643                   break;
7644                 default:
7645                   /* There should be no other prefixes for instructions
7646                      with VEX prefix.  */
7647                   abort ();
7648                 }
7649
7650           /* For EVEX instructions i.vrex should become 0 after
7651              build_evex_prefix.  For VEX instructions upper 16 registers
7652              aren't available, so VREX should be 0.  */
7653           if (i.vrex)
7654             abort ();
7655           /* Now the VEX prefix.  */
7656           p = frag_more (i.vex.length);
7657           for (j = 0; j < i.vex.length; j++)
7658             p[j] = i.vex.bytes[j];
7659         }
7660
7661       /* Now the opcode; be careful about word order here!  */
7662       if (i.tm.opcode_length == 1)
7663         {
7664           FRAG_APPEND_1_CHAR (i.tm.base_opcode);
7665         }
7666       else
7667         {
7668           switch (i.tm.opcode_length)
7669             {
7670             case 4:
7671               p = frag_more (4);
7672               *p++ = (i.tm.base_opcode >> 24) & 0xff;
7673               *p++ = (i.tm.base_opcode >> 16) & 0xff;
7674               break;
7675             case 3:
7676               p = frag_more (3);
7677               *p++ = (i.tm.base_opcode >> 16) & 0xff;
7678               break;
7679             case 2:
7680               p = frag_more (2);
7681               break;
7682             default:
7683               abort ();
7684               break;
7685             }
7686
7687           /* Put out high byte first: can't use md_number_to_chars!  */
7688           *p++ = (i.tm.base_opcode >> 8) & 0xff;
7689           *p = i.tm.base_opcode & 0xff;
7690         }
7691
7692       /* Now the modrm byte and sib byte (if present).  */
7693       if (i.tm.opcode_modifier.modrm)
7694         {
7695           FRAG_APPEND_1_CHAR ((i.rm.regmem << 0
7696                                | i.rm.reg << 3
7697                                | i.rm.mode << 6));
7698           /* If i.rm.regmem == ESP (4)
7699              && i.rm.mode != (Register mode)
7700              && not 16 bit
7701              ==> need second modrm byte.  */
7702           if (i.rm.regmem == ESCAPE_TO_TWO_BYTE_ADDRESSING
7703               && i.rm.mode != 3
7704               && !(i.base_reg && i.base_reg->reg_type.bitfield.word))
7705             FRAG_APPEND_1_CHAR ((i.sib.base << 0
7706                                  | i.sib.index << 3
7707                                  | i.sib.scale << 6));
7708         }
7709
7710       if (i.disp_operands)
7711         output_disp (insn_start_frag, insn_start_off);
7712
7713       if (i.imm_operands)
7714         output_imm (insn_start_frag, insn_start_off);
7715     }
7716
7717 #ifdef DEBUG386
7718   if (flag_debug)
7719     {
7720       pi ("" /*line*/, &i);
7721     }
7722 #endif /* DEBUG386  */
7723 }
7724
7725 /* Return the size of the displacement operand N.  */
7726
7727 static int
7728 disp_size (unsigned int n)
7729 {
7730   int size = 4;
7731
7732   if (i.types[n].bitfield.disp64)
7733     size = 8;
7734   else if (i.types[n].bitfield.disp8)
7735     size = 1;
7736   else if (i.types[n].bitfield.disp16)
7737     size = 2;
7738   return size;
7739 }
7740
7741 /* Return the size of the immediate operand N.  */
7742
7743 static int
7744 imm_size (unsigned int n)
7745 {
7746   int size = 4;
7747   if (i.types[n].bitfield.imm64)
7748     size = 8;
7749   else if (i.types[n].bitfield.imm8 || i.types[n].bitfield.imm8s)
7750     size = 1;
7751   else if (i.types[n].bitfield.imm16)
7752     size = 2;
7753   return size;
7754 }
7755
7756 static void
7757 output_disp (fragS *insn_start_frag, offsetT insn_start_off)
7758 {
7759   char *p;
7760   unsigned int n;
7761
7762   for (n = 0; n < i.operands; n++)
7763     {
7764       if (operand_type_check (i.types[n], disp))
7765         {
7766           if (i.op[n].disps->X_op == O_constant)
7767             {
7768               int size = disp_size (n);
7769               offsetT val = i.op[n].disps->X_add_number;
7770
7771               val = offset_in_range (val >> i.memshift, size);
7772               p = frag_more (size);
7773               md_number_to_chars (p, val, size);
7774             }
7775           else
7776             {
7777               enum bfd_reloc_code_real reloc_type;
7778               int size = disp_size (n);
7779               int sign = i.types[n].bitfield.disp32s;
7780               int pcrel = (i.flags[n] & Operand_PCrel) != 0;
7781               fixS *fixP;
7782
7783               /* We can't have 8 bit displacement here.  */
7784               gas_assert (!i.types[n].bitfield.disp8);
7785
7786               /* The PC relative address is computed relative
7787                  to the instruction boundary, so in case immediate
7788                  fields follows, we need to adjust the value.  */
7789               if (pcrel && i.imm_operands)
7790                 {
7791                   unsigned int n1;
7792                   int sz = 0;
7793
7794                   for (n1 = 0; n1 < i.operands; n1++)
7795                     if (operand_type_check (i.types[n1], imm))
7796                       {
7797                         /* Only one immediate is allowed for PC
7798                            relative address.  */
7799                         gas_assert (sz == 0);
7800                         sz = imm_size (n1);
7801                         i.op[n].disps->X_add_number -= sz;
7802                       }
7803                   /* We should find the immediate.  */
7804                   gas_assert (sz != 0);
7805                 }
7806
7807               p = frag_more (size);
7808               reloc_type = reloc (size, pcrel, sign, i.reloc[n]);
7809               if (GOT_symbol
7810                   && GOT_symbol == i.op[n].disps->X_add_symbol
7811                   && (((reloc_type == BFD_RELOC_32
7812                         || reloc_type == BFD_RELOC_X86_64_32S
7813                         || (reloc_type == BFD_RELOC_64
7814                             && object_64bit))
7815                        && (i.op[n].disps->X_op == O_symbol
7816                            || (i.op[n].disps->X_op == O_add
7817                                && ((symbol_get_value_expression
7818                                     (i.op[n].disps->X_op_symbol)->X_op)
7819                                    == O_subtract))))
7820                       || reloc_type == BFD_RELOC_32_PCREL))
7821                 {
7822                   offsetT add;
7823
7824                   if (insn_start_frag == frag_now)
7825                     add = (p - frag_now->fr_literal) - insn_start_off;
7826                   else
7827                     {
7828                       fragS *fr;
7829
7830                       add = insn_start_frag->fr_fix - insn_start_off;
7831                       for (fr = insn_start_frag->fr_next;
7832                            fr && fr != frag_now; fr = fr->fr_next)
7833                         add += fr->fr_fix;
7834                       add += p - frag_now->fr_literal;
7835                     }
7836
7837                   if (!object_64bit)
7838                     {
7839                       reloc_type = BFD_RELOC_386_GOTPC;
7840                       i.op[n].imms->X_add_number += add;
7841                     }
7842                   else if (reloc_type == BFD_RELOC_64)
7843                     reloc_type = BFD_RELOC_X86_64_GOTPC64;
7844                   else
7845                     /* Don't do the adjustment for x86-64, as there
7846                        the pcrel addressing is relative to the _next_
7847                        insn, and that is taken care of in other code.  */
7848                     reloc_type = BFD_RELOC_X86_64_GOTPC32;
7849                 }
7850               fixP = fix_new_exp (frag_now, p - frag_now->fr_literal,
7851                                   size, i.op[n].disps, pcrel,
7852                                   reloc_type);
7853               /* Check for "call/jmp *mem", "mov mem, %reg",
7854                  "test %reg, mem" and "binop mem, %reg" where binop
7855                  is one of adc, add, and, cmp, or, sbb, sub, xor
7856                  instructions.  Always generate R_386_GOT32X for
7857                  "sym*GOT" operand in 32-bit mode.  */
7858               if ((generate_relax_relocations
7859                    || (!object_64bit
7860                        && i.rm.mode == 0
7861                        && i.rm.regmem == 5))
7862                   && (i.rm.mode == 2
7863                       || (i.rm.mode == 0 && i.rm.regmem == 5))
7864                   && ((i.operands == 1
7865                        && i.tm.base_opcode == 0xff
7866                        && (i.rm.reg == 2 || i.rm.reg == 4))
7867                       || (i.operands == 2
7868                           && (i.tm.base_opcode == 0x8b
7869                               || i.tm.base_opcode == 0x85
7870                               || (i.tm.base_opcode & 0xc7) == 0x03))))
7871                 {
7872                   if (object_64bit)
7873                     {
7874                       fixP->fx_tcbit = i.rex != 0;
7875                       if (i.base_reg
7876                           && (i.base_reg->reg_num == RegRip
7877                               || i.base_reg->reg_num == RegEip))
7878                       fixP->fx_tcbit2 = 1;
7879                     }
7880                   else
7881                     fixP->fx_tcbit2 = 1;
7882                 }
7883             }
7884         }
7885     }
7886 }
7887
7888 static void
7889 output_imm (fragS *insn_start_frag, offsetT insn_start_off)
7890 {
7891   char *p;
7892   unsigned int n;
7893
7894   for (n = 0; n < i.operands; n++)
7895     {
7896       /* Skip SAE/RC Imm operand in EVEX.  They are already handled.  */
7897       if (i.rounding && (int) n == i.rounding->operand)
7898         continue;
7899
7900       if (operand_type_check (i.types[n], imm))
7901         {
7902           if (i.op[n].imms->X_op == O_constant)
7903             {
7904               int size = imm_size (n);
7905               offsetT val;
7906
7907               val = offset_in_range (i.op[n].imms->X_add_number,
7908                                      size);
7909               p = frag_more (size);
7910               md_number_to_chars (p, val, size);
7911             }
7912           else
7913             {
7914               /* Not absolute_section.
7915                  Need a 32-bit fixup (don't support 8bit
7916                  non-absolute imms).  Try to support other
7917                  sizes ...  */
7918               enum bfd_reloc_code_real reloc_type;
7919               int size = imm_size (n);
7920               int sign;
7921
7922               if (i.types[n].bitfield.imm32s
7923                   && (i.suffix == QWORD_MNEM_SUFFIX
7924                       || (!i.suffix && i.tm.opcode_modifier.no_lsuf)))
7925                 sign = 1;
7926               else
7927                 sign = 0;
7928
7929               p = frag_more (size);
7930               reloc_type = reloc (size, 0, sign, i.reloc[n]);
7931
7932               /*   This is tough to explain.  We end up with this one if we
7933                * have operands that look like
7934                * "_GLOBAL_OFFSET_TABLE_+[.-.L284]".  The goal here is to
7935                * obtain the absolute address of the GOT, and it is strongly
7936                * preferable from a performance point of view to avoid using
7937                * a runtime relocation for this.  The actual sequence of
7938                * instructions often look something like:
7939                *
7940                *        call    .L66
7941                * .L66:
7942                *        popl    %ebx
7943                *        addl    $_GLOBAL_OFFSET_TABLE_+[.-.L66],%ebx
7944                *
7945                *   The call and pop essentially return the absolute address
7946                * of the label .L66 and store it in %ebx.  The linker itself
7947                * will ultimately change the first operand of the addl so
7948                * that %ebx points to the GOT, but to keep things simple, the
7949                * .o file must have this operand set so that it generates not
7950                * the absolute address of .L66, but the absolute address of
7951                * itself.  This allows the linker itself simply treat a GOTPC
7952                * relocation as asking for a pcrel offset to the GOT to be
7953                * added in, and the addend of the relocation is stored in the
7954                * operand field for the instruction itself.
7955                *
7956                *   Our job here is to fix the operand so that it would add
7957                * the correct offset so that %ebx would point to itself.  The
7958                * thing that is tricky is that .-.L66 will point to the
7959                * beginning of the instruction, so we need to further modify
7960                * the operand so that it will point to itself.  There are
7961                * other cases where you have something like:
7962                *
7963                *        .long   $_GLOBAL_OFFSET_TABLE_+[.-.L66]
7964                *
7965                * and here no correction would be required.  Internally in
7966                * the assembler we treat operands of this form as not being
7967                * pcrel since the '.' is explicitly mentioned, and I wonder
7968                * whether it would simplify matters to do it this way.  Who
7969                * knows.  In earlier versions of the PIC patches, the
7970                * pcrel_adjust field was used to store the correction, but
7971                * since the expression is not pcrel, I felt it would be
7972                * confusing to do it this way.  */
7973
7974               if ((reloc_type == BFD_RELOC_32
7975                    || reloc_type == BFD_RELOC_X86_64_32S
7976                    || reloc_type == BFD_RELOC_64)
7977                   && GOT_symbol
7978                   && GOT_symbol == i.op[n].imms->X_add_symbol
7979                   && (i.op[n].imms->X_op == O_symbol
7980                       || (i.op[n].imms->X_op == O_add
7981                           && ((symbol_get_value_expression
7982                                (i.op[n].imms->X_op_symbol)->X_op)
7983                               == O_subtract))))
7984                 {
7985                   offsetT add;
7986
7987                   if (insn_start_frag == frag_now)
7988                     add = (p - frag_now->fr_literal) - insn_start_off;
7989                   else
7990                     {
7991                       fragS *fr;
7992
7993                       add = insn_start_frag->fr_fix - insn_start_off;
7994                       for (fr = insn_start_frag->fr_next;
7995                            fr && fr != frag_now; fr = fr->fr_next)
7996                         add += fr->fr_fix;
7997                       add += p - frag_now->fr_literal;
7998                     }
7999
8000                   if (!object_64bit)
8001                     reloc_type = BFD_RELOC_386_GOTPC;
8002                   else if (size == 4)
8003                     reloc_type = BFD_RELOC_X86_64_GOTPC32;
8004                   else if (size == 8)
8005                     reloc_type = BFD_RELOC_X86_64_GOTPC64;
8006                   i.op[n].imms->X_add_number += add;
8007                 }
8008               fix_new_exp (frag_now, p - frag_now->fr_literal, size,
8009                            i.op[n].imms, 0, reloc_type);
8010             }
8011         }
8012     }
8013 }
8014 \f
8015 /* x86_cons_fix_new is called via the expression parsing code when a
8016    reloc is needed.  We use this hook to get the correct .got reloc.  */
8017 static int cons_sign = -1;
8018
8019 void
8020 x86_cons_fix_new (fragS *frag, unsigned int off, unsigned int len,
8021                   expressionS *exp, bfd_reloc_code_real_type r)
8022 {
8023   r = reloc (len, 0, cons_sign, r);
8024
8025 #ifdef TE_PE
8026   if (exp->X_op == O_secrel)
8027     {
8028       exp->X_op = O_symbol;
8029       r = BFD_RELOC_32_SECREL;
8030     }
8031 #endif
8032
8033   fix_new_exp (frag, off, len, exp, 0, r);
8034 }
8035
8036 /* Export the ABI address size for use by TC_ADDRESS_BYTES for the
8037    purpose of the `.dc.a' internal pseudo-op.  */
8038
8039 int
8040 x86_address_bytes (void)
8041 {
8042   if ((stdoutput->arch_info->mach & bfd_mach_x64_32))
8043     return 4;
8044   return stdoutput->arch_info->bits_per_address / 8;
8045 }
8046
8047 #if !(defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) || defined (OBJ_MACH_O)) \
8048     || defined (LEX_AT)
8049 # define lex_got(reloc, adjust, types) NULL
8050 #else
8051 /* Parse operands of the form
8052    <symbol>@GOTOFF+<nnn>
8053    and similar .plt or .got references.
8054
8055    If we find one, set up the correct relocation in RELOC and copy the
8056    input string, minus the `@GOTOFF' into a malloc'd buffer for
8057    parsing by the calling routine.  Return this buffer, and if ADJUST
8058    is non-null set it to the length of the string we removed from the
8059    input line.  Otherwise return NULL.  */
8060 static char *
8061 lex_got (enum bfd_reloc_code_real *rel,
8062          int *adjust,
8063          i386_operand_type *types)
8064 {
8065   /* Some of the relocations depend on the size of what field is to
8066      be relocated.  But in our callers i386_immediate and i386_displacement
8067      we don't yet know the operand size (this will be set by insn
8068      matching).  Hence we record the word32 relocation here,
8069      and adjust the reloc according to the real size in reloc().  */
8070   static const struct {
8071     const char *str;
8072     int len;
8073     const enum bfd_reloc_code_real rel[2];
8074     const i386_operand_type types64;
8075   } gotrel[] = {
8076 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
8077     { STRING_COMMA_LEN ("SIZE"),      { BFD_RELOC_SIZE32,
8078                                         BFD_RELOC_SIZE32 },
8079       OPERAND_TYPE_IMM32_64 },
8080 #endif
8081     { STRING_COMMA_LEN ("PLTOFF"),   { _dummy_first_bfd_reloc_code_real,
8082                                        BFD_RELOC_X86_64_PLTOFF64 },
8083       OPERAND_TYPE_IMM64 },
8084     { STRING_COMMA_LEN ("PLT"),      { BFD_RELOC_386_PLT32,
8085                                        BFD_RELOC_X86_64_PLT32    },
8086       OPERAND_TYPE_IMM32_32S_DISP32 },
8087     { STRING_COMMA_LEN ("GOTPLT"),   { _dummy_first_bfd_reloc_code_real,
8088                                        BFD_RELOC_X86_64_GOTPLT64 },
8089       OPERAND_TYPE_IMM64_DISP64 },
8090     { STRING_COMMA_LEN ("GOTOFF"),   { BFD_RELOC_386_GOTOFF,
8091                                        BFD_RELOC_X86_64_GOTOFF64 },
8092       OPERAND_TYPE_IMM64_DISP64 },
8093     { STRING_COMMA_LEN ("GOTPCREL"), { _dummy_first_bfd_reloc_code_real,
8094                                        BFD_RELOC_X86_64_GOTPCREL },
8095       OPERAND_TYPE_IMM32_32S_DISP32 },
8096     { STRING_COMMA_LEN ("TLSGD"),    { BFD_RELOC_386_TLS_GD,
8097                                        BFD_RELOC_X86_64_TLSGD    },
8098       OPERAND_TYPE_IMM32_32S_DISP32 },
8099     { STRING_COMMA_LEN ("TLSLDM"),   { BFD_RELOC_386_TLS_LDM,
8100                                        _dummy_first_bfd_reloc_code_real },
8101       OPERAND_TYPE_NONE },
8102     { STRING_COMMA_LEN ("TLSLD"),    { _dummy_first_bfd_reloc_code_real,
8103                                        BFD_RELOC_X86_64_TLSLD    },
8104       OPERAND_TYPE_IMM32_32S_DISP32 },
8105     { STRING_COMMA_LEN ("GOTTPOFF"), { BFD_RELOC_386_TLS_IE_32,
8106                                        BFD_RELOC_X86_64_GOTTPOFF },
8107       OPERAND_TYPE_IMM32_32S_DISP32 },
8108     { STRING_COMMA_LEN ("TPOFF"),    { BFD_RELOC_386_TLS_LE_32,
8109                                        BFD_RELOC_X86_64_TPOFF32  },
8110       OPERAND_TYPE_IMM32_32S_64_DISP32_64 },
8111     { STRING_COMMA_LEN ("NTPOFF"),   { BFD_RELOC_386_TLS_LE,
8112                                        _dummy_first_bfd_reloc_code_real },
8113       OPERAND_TYPE_NONE },
8114     { STRING_COMMA_LEN ("DTPOFF"),   { BFD_RELOC_386_TLS_LDO_32,
8115                                        BFD_RELOC_X86_64_DTPOFF32 },
8116       OPERAND_TYPE_IMM32_32S_64_DISP32_64 },
8117     { STRING_COMMA_LEN ("GOTNTPOFF"),{ BFD_RELOC_386_TLS_GOTIE,
8118                                        _dummy_first_bfd_reloc_code_real },
8119       OPERAND_TYPE_NONE },
8120     { STRING_COMMA_LEN ("INDNTPOFF"),{ BFD_RELOC_386_TLS_IE,
8121                                        _dummy_first_bfd_reloc_code_real },
8122       OPERAND_TYPE_NONE },
8123     { STRING_COMMA_LEN ("GOT"),      { BFD_RELOC_386_GOT32,
8124                                        BFD_RELOC_X86_64_GOT32    },
8125       OPERAND_TYPE_IMM32_32S_64_DISP32 },
8126     { STRING_COMMA_LEN ("TLSDESC"),  { BFD_RELOC_386_TLS_GOTDESC,
8127                                        BFD_RELOC_X86_64_GOTPC32_TLSDESC },
8128       OPERAND_TYPE_IMM32_32S_DISP32 },
8129     { STRING_COMMA_LEN ("TLSCALL"),  { BFD_RELOC_386_TLS_DESC_CALL,
8130                                        BFD_RELOC_X86_64_TLSDESC_CALL },
8131       OPERAND_TYPE_IMM32_32S_DISP32 },
8132   };
8133   char *cp;
8134   unsigned int j;
8135
8136 #if defined (OBJ_MAYBE_ELF)
8137   if (!IS_ELF)
8138     return NULL;
8139 #endif
8140
8141   for (cp = input_line_pointer; *cp != '@'; cp++)
8142     if (is_end_of_line[(unsigned char) *cp] || *cp == ',')
8143       return NULL;
8144
8145   for (j = 0; j < ARRAY_SIZE (gotrel); j++)
8146     {
8147       int len = gotrel[j].len;
8148       if (strncasecmp (cp + 1, gotrel[j].str, len) == 0)
8149         {
8150           if (gotrel[j].rel[object_64bit] != 0)
8151             {
8152               int first, second;
8153               char *tmpbuf, *past_reloc;
8154
8155               *rel = gotrel[j].rel[object_64bit];
8156
8157               if (types)
8158                 {
8159                   if (flag_code != CODE_64BIT)
8160                     {
8161                       types->bitfield.imm32 = 1;
8162                       types->bitfield.disp32 = 1;
8163                     }
8164                   else
8165                     *types = gotrel[j].types64;
8166                 }
8167
8168               if (j != 0 && GOT_symbol == NULL)
8169                 GOT_symbol = symbol_find_or_make (GLOBAL_OFFSET_TABLE_NAME);
8170
8171               /* The length of the first part of our input line.  */
8172               first = cp - input_line_pointer;
8173
8174               /* The second part goes from after the reloc token until
8175                  (and including) an end_of_line char or comma.  */
8176               past_reloc = cp + 1 + len;
8177               cp = past_reloc;
8178               while (!is_end_of_line[(unsigned char) *cp] && *cp != ',')
8179                 ++cp;
8180               second = cp + 1 - past_reloc;
8181
8182               /* Allocate and copy string.  The trailing NUL shouldn't
8183                  be necessary, but be safe.  */
8184               tmpbuf = XNEWVEC (char, first + second + 2);
8185               memcpy (tmpbuf, input_line_pointer, first);
8186               if (second != 0 && *past_reloc != ' ')
8187                 /* Replace the relocation token with ' ', so that
8188                    errors like foo@GOTOFF1 will be detected.  */
8189                 tmpbuf[first++] = ' ';
8190               else
8191                 /* Increment length by 1 if the relocation token is
8192                    removed.  */
8193                 len++;
8194               if (adjust)
8195                 *adjust = len;
8196               memcpy (tmpbuf + first, past_reloc, second);
8197               tmpbuf[first + second] = '\0';
8198               return tmpbuf;
8199             }
8200
8201           as_bad (_("@%s reloc is not supported with %d-bit output format"),
8202                   gotrel[j].str, 1 << (5 + object_64bit));
8203           return NULL;
8204         }
8205     }
8206
8207   /* Might be a symbol version string.  Don't as_bad here.  */
8208   return NULL;
8209 }
8210 #endif
8211
8212 #ifdef TE_PE
8213 #ifdef lex_got
8214 #undef lex_got
8215 #endif
8216 /* Parse operands of the form
8217    <symbol>@SECREL32+<nnn>
8218
8219    If we find one, set up the correct relocation in RELOC and copy the
8220    input string, minus the `@SECREL32' into a malloc'd buffer for
8221    parsing by the calling routine.  Return this buffer, and if ADJUST
8222    is non-null set it to the length of the string we removed from the
8223    input line.  Otherwise return NULL.
8224
8225    This function is copied from the ELF version above adjusted for PE targets.  */
8226
8227 static char *
8228 lex_got (enum bfd_reloc_code_real *rel ATTRIBUTE_UNUSED,
8229          int *adjust ATTRIBUTE_UNUSED,
8230          i386_operand_type *types)
8231 {
8232   static const struct
8233   {
8234     const char *str;
8235     int len;
8236     const enum bfd_reloc_code_real rel[2];
8237     const i386_operand_type types64;
8238   }
8239   gotrel[] =
8240   {
8241     { STRING_COMMA_LEN ("SECREL32"),    { BFD_RELOC_32_SECREL,
8242                                           BFD_RELOC_32_SECREL },
8243       OPERAND_TYPE_IMM32_32S_64_DISP32_64 },
8244   };
8245
8246   char *cp;
8247   unsigned j;
8248
8249   for (cp = input_line_pointer; *cp != '@'; cp++)
8250     if (is_end_of_line[(unsigned char) *cp] || *cp == ',')
8251       return NULL;
8252
8253   for (j = 0; j < ARRAY_SIZE (gotrel); j++)
8254     {
8255       int len = gotrel[j].len;
8256
8257       if (strncasecmp (cp + 1, gotrel[j].str, len) == 0)
8258         {
8259           if (gotrel[j].rel[object_64bit] != 0)
8260             {
8261               int first, second;
8262               char *tmpbuf, *past_reloc;
8263
8264               *rel = gotrel[j].rel[object_64bit];
8265               if (adjust)
8266                 *adjust = len;
8267
8268               if (types)
8269                 {
8270                   if (flag_code != CODE_64BIT)
8271                     {
8272                       types->bitfield.imm32 = 1;
8273                       types->bitfield.disp32 = 1;
8274                     }
8275                   else
8276                     *types = gotrel[j].types64;
8277                 }
8278
8279               /* The length of the first part of our input line.  */
8280               first = cp - input_line_pointer;
8281
8282               /* The second part goes from after the reloc token until
8283                  (and including) an end_of_line char or comma.  */
8284               past_reloc = cp + 1 + len;
8285               cp = past_reloc;
8286               while (!is_end_of_line[(unsigned char) *cp] && *cp != ',')
8287                 ++cp;
8288               second = cp + 1 - past_reloc;
8289
8290               /* Allocate and copy string.  The trailing NUL shouldn't
8291                  be necessary, but be safe.  */
8292               tmpbuf = XNEWVEC (char, first + second + 2);
8293               memcpy (tmpbuf, input_line_pointer, first);
8294               if (second != 0 && *past_reloc != ' ')
8295                 /* Replace the relocation token with ' ', so that
8296                    errors like foo@SECLREL321 will be detected.  */
8297                 tmpbuf[first++] = ' ';
8298               memcpy (tmpbuf + first, past_reloc, second);
8299               tmpbuf[first + second] = '\0';
8300               return tmpbuf;
8301             }
8302
8303           as_bad (_("@%s reloc is not supported with %d-bit output format"),
8304                   gotrel[j].str, 1 << (5 + object_64bit));
8305           return NULL;
8306         }
8307     }
8308
8309   /* Might be a symbol version string.  Don't as_bad here.  */
8310   return NULL;
8311 }
8312
8313 #endif /* TE_PE */
8314
8315 bfd_reloc_code_real_type
8316 x86_cons (expressionS *exp, int size)
8317 {
8318   bfd_reloc_code_real_type got_reloc = NO_RELOC;
8319
8320   intel_syntax = -intel_syntax;
8321
8322   exp->X_md = 0;
8323   if (size == 4 || (object_64bit && size == 8))
8324     {
8325       /* Handle @GOTOFF and the like in an expression.  */
8326       char *save;
8327       char *gotfree_input_line;
8328       int adjust = 0;
8329
8330       save = input_line_pointer;
8331       gotfree_input_line = lex_got (&got_reloc, &adjust, NULL);
8332       if (gotfree_input_line)
8333         input_line_pointer = gotfree_input_line;
8334
8335       expression (exp);
8336
8337       if (gotfree_input_line)
8338         {
8339           /* expression () has merrily parsed up to the end of line,
8340              or a comma - in the wrong buffer.  Transfer how far
8341              input_line_pointer has moved to the right buffer.  */
8342           input_line_pointer = (save
8343                                 + (input_line_pointer - gotfree_input_line)
8344                                 + adjust);
8345           free (gotfree_input_line);
8346           if (exp->X_op == O_constant
8347               || exp->X_op == O_absent
8348               || exp->X_op == O_illegal
8349               || exp->X_op == O_register
8350               || exp->X_op == O_big)
8351             {
8352               char c = *input_line_pointer;
8353               *input_line_pointer = 0;
8354               as_bad (_("missing or invalid expression `%s'"), save);
8355               *input_line_pointer = c;
8356             }
8357         }
8358     }
8359   else
8360     expression (exp);
8361
8362   intel_syntax = -intel_syntax;
8363
8364   if (intel_syntax)
8365     i386_intel_simplify (exp);
8366
8367   return got_reloc;
8368 }
8369
8370 static void
8371 signed_cons (int size)
8372 {
8373   if (flag_code == CODE_64BIT)
8374     cons_sign = 1;
8375   cons (size);
8376   cons_sign = -1;
8377 }
8378
8379 #ifdef TE_PE
8380 static void
8381 pe_directive_secrel (int dummy ATTRIBUTE_UNUSED)
8382 {
8383   expressionS exp;
8384
8385   do
8386     {
8387       expression (&exp);
8388       if (exp.X_op == O_symbol)
8389         exp.X_op = O_secrel;
8390
8391       emit_expr (&exp, 4);
8392     }
8393   while (*input_line_pointer++ == ',');
8394
8395   input_line_pointer--;
8396   demand_empty_rest_of_line ();
8397 }
8398 #endif
8399
8400 /* Handle Vector operations.  */
8401
8402 static char *
8403 check_VecOperations (char *op_string, char *op_end)
8404 {
8405   const reg_entry *mask;
8406   const char *saved;
8407   char *end_op;
8408
8409   while (*op_string
8410          && (op_end == NULL || op_string < op_end))
8411     {
8412       saved = op_string;
8413       if (*op_string == '{')
8414         {
8415           op_string++;
8416
8417           /* Check broadcasts.  */
8418           if (strncmp (op_string, "1to", 3) == 0)
8419             {
8420               int bcst_type;
8421
8422               if (i.broadcast)
8423                 goto duplicated_vec_op;
8424
8425               op_string += 3;
8426               if (*op_string == '8')
8427                 bcst_type = BROADCAST_1TO8;
8428               else if (*op_string == '4')
8429                 bcst_type = BROADCAST_1TO4;
8430               else if (*op_string == '2')
8431                 bcst_type = BROADCAST_1TO2;
8432               else if (*op_string == '1'
8433                        && *(op_string+1) == '6')
8434                 {
8435                   bcst_type = BROADCAST_1TO16;
8436                   op_string++;
8437                 }
8438               else
8439                 {
8440                   as_bad (_("Unsupported broadcast: `%s'"), saved);
8441                   return NULL;
8442                 }
8443               op_string++;
8444
8445               broadcast_op.type = bcst_type;
8446               broadcast_op.operand = this_operand;
8447               i.broadcast = &broadcast_op;
8448             }
8449           /* Check masking operation.  */
8450           else if ((mask = parse_register (op_string, &end_op)) != NULL)
8451             {
8452               /* k0 can't be used for write mask.  */
8453               if (!mask->reg_type.bitfield.regmask || mask->reg_num == 0)
8454                 {
8455                   as_bad (_("`%s%s' can't be used for write mask"),
8456                           register_prefix, mask->reg_name);
8457                   return NULL;
8458                 }
8459
8460               if (!i.mask)
8461                 {
8462                   mask_op.mask = mask;
8463                   mask_op.zeroing = 0;
8464                   mask_op.operand = this_operand;
8465                   i.mask = &mask_op;
8466                 }
8467               else
8468                 {
8469                   if (i.mask->mask)
8470                     goto duplicated_vec_op;
8471
8472                   i.mask->mask = mask;
8473
8474                   /* Only "{z}" is allowed here.  No need to check
8475                      zeroing mask explicitly.  */
8476                   if (i.mask->operand != this_operand)
8477                     {
8478                       as_bad (_("invalid write mask `%s'"), saved);
8479                       return NULL;
8480                     }
8481                 }
8482
8483               op_string = end_op;
8484             }
8485           /* Check zeroing-flag for masking operation.  */
8486           else if (*op_string == 'z')
8487             {
8488               if (!i.mask)
8489                 {
8490                   mask_op.mask = NULL;
8491                   mask_op.zeroing = 1;
8492                   mask_op.operand = this_operand;
8493                   i.mask = &mask_op;
8494                 }
8495               else
8496                 {
8497                   if (i.mask->zeroing)
8498                     {
8499                     duplicated_vec_op:
8500                       as_bad (_("duplicated `%s'"), saved);
8501                       return NULL;
8502                     }
8503
8504                   i.mask->zeroing = 1;
8505
8506                   /* Only "{%k}" is allowed here.  No need to check mask
8507                      register explicitly.  */
8508                   if (i.mask->operand != this_operand)
8509                     {
8510                       as_bad (_("invalid zeroing-masking `%s'"),
8511                               saved);
8512                       return NULL;
8513                     }
8514                 }
8515
8516               op_string++;
8517             }
8518           else
8519             goto unknown_vec_op;
8520
8521           if (*op_string != '}')
8522             {
8523               as_bad (_("missing `}' in `%s'"), saved);
8524               return NULL;
8525             }
8526           op_string++;
8527           continue;
8528         }
8529     unknown_vec_op:
8530       /* We don't know this one.  */
8531       as_bad (_("unknown vector operation: `%s'"), saved);
8532       return NULL;
8533     }
8534
8535   if (i.mask && i.mask->zeroing && !i.mask->mask)
8536     {
8537       as_bad (_("zeroing-masking only allowed with write mask"));
8538       return NULL;
8539     }
8540
8541   return op_string;
8542 }
8543
8544 static int
8545 i386_immediate (char *imm_start)
8546 {
8547   char *save_input_line_pointer;
8548   char *gotfree_input_line;
8549   segT exp_seg = 0;
8550   expressionS *exp;
8551   i386_operand_type types;
8552
8553   operand_type_set (&types, ~0);
8554
8555   if (i.imm_operands == MAX_IMMEDIATE_OPERANDS)
8556     {
8557       as_bad (_("at most %d immediate operands are allowed"),
8558               MAX_IMMEDIATE_OPERANDS);
8559       return 0;
8560     }
8561
8562   exp = &im_expressions[i.imm_operands++];
8563   i.op[this_operand].imms = exp;
8564
8565   if (is_space_char (*imm_start))
8566     ++imm_start;
8567
8568   save_input_line_pointer = input_line_pointer;
8569   input_line_pointer = imm_start;
8570
8571   gotfree_input_line = lex_got (&i.reloc[this_operand], NULL, &types);
8572   if (gotfree_input_line)
8573     input_line_pointer = gotfree_input_line;
8574
8575   exp_seg = expression (exp);
8576
8577   SKIP_WHITESPACE ();
8578
8579   /* Handle vector operations.  */
8580   if (*input_line_pointer == '{')
8581     {
8582       input_line_pointer = check_VecOperations (input_line_pointer,
8583                                                 NULL);
8584       if (input_line_pointer == NULL)
8585         return 0;
8586     }
8587
8588   if (*input_line_pointer)
8589     as_bad (_("junk `%s' after expression"), input_line_pointer);
8590
8591   input_line_pointer = save_input_line_pointer;
8592   if (gotfree_input_line)
8593     {
8594       free (gotfree_input_line);
8595
8596       if (exp->X_op == O_constant || exp->X_op == O_register)
8597         exp->X_op = O_illegal;
8598     }
8599
8600   return i386_finalize_immediate (exp_seg, exp, types, imm_start);
8601 }
8602
8603 static int
8604 i386_finalize_immediate (segT exp_seg ATTRIBUTE_UNUSED, expressionS *exp,
8605                          i386_operand_type types, const char *imm_start)
8606 {
8607   if (exp->X_op == O_absent || exp->X_op == O_illegal || exp->X_op == O_big)
8608     {
8609       if (imm_start)
8610         as_bad (_("missing or invalid immediate expression `%s'"),
8611                 imm_start);
8612       return 0;
8613     }
8614   else if (exp->X_op == O_constant)
8615     {
8616       /* Size it properly later.  */
8617       i.types[this_operand].bitfield.imm64 = 1;
8618       /* If not 64bit, sign extend val.  */
8619       if (flag_code != CODE_64BIT
8620           && (exp->X_add_number & ~(((addressT) 2 << 31) - 1)) == 0)
8621         exp->X_add_number
8622           = (exp->X_add_number ^ ((addressT) 1 << 31)) - ((addressT) 1 << 31);
8623     }
8624 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
8625   else if (OUTPUT_FLAVOR == bfd_target_aout_flavour
8626            && exp_seg != absolute_section
8627            && exp_seg != text_section
8628            && exp_seg != data_section
8629            && exp_seg != bss_section
8630            && exp_seg != undefined_section
8631            && !bfd_is_com_section (exp_seg))
8632     {
8633       as_bad (_("unimplemented segment %s in operand"), exp_seg->name);
8634       return 0;
8635     }
8636 #endif
8637   else if (!intel_syntax && exp_seg == reg_section)
8638     {
8639       if (imm_start)
8640         as_bad (_("illegal immediate register operand %s"), imm_start);
8641       return 0;
8642     }
8643   else
8644     {
8645       /* This is an address.  The size of the address will be
8646          determined later, depending on destination register,
8647          suffix, or the default for the section.  */
8648       i.types[this_operand].bitfield.imm8 = 1;
8649       i.types[this_operand].bitfield.imm16 = 1;
8650       i.types[this_operand].bitfield.imm32 = 1;
8651       i.types[this_operand].bitfield.imm32s = 1;
8652       i.types[this_operand].bitfield.imm64 = 1;
8653       i.types[this_operand] = operand_type_and (i.types[this_operand],
8654                                                 types);
8655     }
8656
8657   return 1;
8658 }
8659
8660 static char *
8661 i386_scale (char *scale)
8662 {
8663   offsetT val;
8664   char *save = input_line_pointer;
8665
8666   input_line_pointer = scale;
8667   val = get_absolute_expression ();
8668
8669   switch (val)
8670     {
8671     case 1:
8672       i.log2_scale_factor = 0;
8673       break;
8674     case 2:
8675       i.log2_scale_factor = 1;
8676       break;
8677     case 4:
8678       i.log2_scale_factor = 2;
8679       break;
8680     case 8:
8681       i.log2_scale_factor = 3;
8682       break;
8683     default:
8684       {
8685         char sep = *input_line_pointer;
8686
8687         *input_line_pointer = '\0';
8688         as_bad (_("expecting scale factor of 1, 2, 4, or 8: got `%s'"),
8689                 scale);
8690         *input_line_pointer = sep;
8691         input_line_pointer = save;
8692         return NULL;
8693       }
8694     }
8695   if (i.log2_scale_factor != 0 && i.index_reg == 0)
8696     {
8697       as_warn (_("scale factor of %d without an index register"),
8698                1 << i.log2_scale_factor);
8699       i.log2_scale_factor = 0;
8700     }
8701   scale = input_line_pointer;
8702   input_line_pointer = save;
8703   return scale;
8704 }
8705
8706 static int
8707 i386_displacement (char *disp_start, char *disp_end)
8708 {
8709   expressionS *exp;
8710   segT exp_seg = 0;
8711   char *save_input_line_pointer;
8712   char *gotfree_input_line;
8713   int override;
8714   i386_operand_type bigdisp, types = anydisp;
8715   int ret;
8716
8717   if (i.disp_operands == MAX_MEMORY_OPERANDS)
8718     {
8719       as_bad (_("at most %d displacement operands are allowed"),
8720               MAX_MEMORY_OPERANDS);
8721       return 0;
8722     }
8723
8724   operand_type_set (&bigdisp, 0);
8725   if ((i.types[this_operand].bitfield.jumpabsolute)
8726       || (!current_templates->start->opcode_modifier.jump
8727           && !current_templates->start->opcode_modifier.jumpdword))
8728     {
8729       bigdisp.bitfield.disp32 = 1;
8730       override = (i.prefix[ADDR_PREFIX] != 0);
8731       if (flag_code == CODE_64BIT)
8732         {
8733           if (!override)
8734             {
8735               bigdisp.bitfield.disp32s = 1;
8736               bigdisp.bitfield.disp64 = 1;
8737             }
8738         }
8739       else if ((flag_code == CODE_16BIT) ^ override)
8740         {
8741           bigdisp.bitfield.disp32 = 0;
8742           bigdisp.bitfield.disp16 = 1;
8743         }
8744     }
8745   else
8746     {
8747       /* For PC-relative branches, the width of the displacement
8748          is dependent upon data size, not address size.  */
8749       override = (i.prefix[DATA_PREFIX] != 0);
8750       if (flag_code == CODE_64BIT)
8751         {
8752           if (override || i.suffix == WORD_MNEM_SUFFIX)
8753             bigdisp.bitfield.disp16 = 1;
8754           else
8755             {
8756               bigdisp.bitfield.disp32 = 1;
8757               bigdisp.bitfield.disp32s = 1;
8758             }
8759         }
8760       else
8761         {
8762           if (!override)
8763             override = (i.suffix == (flag_code != CODE_16BIT
8764                                      ? WORD_MNEM_SUFFIX
8765                                      : LONG_MNEM_SUFFIX));
8766           bigdisp.bitfield.disp32 = 1;
8767           if ((flag_code == CODE_16BIT) ^ override)
8768             {
8769               bigdisp.bitfield.disp32 = 0;
8770               bigdisp.bitfield.disp16 = 1;
8771             }
8772         }
8773     }
8774   i.types[this_operand] = operand_type_or (i.types[this_operand],
8775                                            bigdisp);
8776
8777   exp = &disp_expressions[i.disp_operands];
8778   i.op[this_operand].disps = exp;
8779   i.disp_operands++;
8780   save_input_line_pointer = input_line_pointer;
8781   input_line_pointer = disp_start;
8782   END_STRING_AND_SAVE (disp_end);
8783
8784 #ifndef GCC_ASM_O_HACK
8785 #define GCC_ASM_O_HACK 0
8786 #endif
8787 #if GCC_ASM_O_HACK
8788   END_STRING_AND_SAVE (disp_end + 1);
8789   if (i.types[this_operand].bitfield.baseIndex
8790       && displacement_string_end[-1] == '+')
8791     {
8792       /* This hack is to avoid a warning when using the "o"
8793          constraint within gcc asm statements.
8794          For instance:
8795
8796          #define _set_tssldt_desc(n,addr,limit,type) \
8797          __asm__ __volatile__ ( \
8798          "movw %w2,%0\n\t" \
8799          "movw %w1,2+%0\n\t" \
8800          "rorl $16,%1\n\t" \
8801          "movb %b1,4+%0\n\t" \
8802          "movb %4,5+%0\n\t" \
8803          "movb $0,6+%0\n\t" \
8804          "movb %h1,7+%0\n\t" \
8805          "rorl $16,%1" \
8806          : "=o"(*(n)) : "q" (addr), "ri"(limit), "i"(type))
8807
8808          This works great except that the output assembler ends
8809          up looking a bit weird if it turns out that there is
8810          no offset.  You end up producing code that looks like:
8811
8812          #APP
8813          movw $235,(%eax)
8814          movw %dx,2+(%eax)
8815          rorl $16,%edx
8816          movb %dl,4+(%eax)
8817          movb $137,5+(%eax)
8818          movb $0,6+(%eax)
8819          movb %dh,7+(%eax)
8820          rorl $16,%edx
8821          #NO_APP
8822
8823          So here we provide the missing zero.  */
8824
8825       *displacement_string_end = '0';
8826     }
8827 #endif
8828   gotfree_input_line = lex_got (&i.reloc[this_operand], NULL, &types);
8829   if (gotfree_input_line)
8830     input_line_pointer = gotfree_input_line;
8831
8832   exp_seg = expression (exp);
8833
8834   SKIP_WHITESPACE ();
8835   if (*input_line_pointer)
8836     as_bad (_("junk `%s' after expression"), input_line_pointer);
8837 #if GCC_ASM_O_HACK
8838   RESTORE_END_STRING (disp_end + 1);
8839 #endif
8840   input_line_pointer = save_input_line_pointer;
8841   if (gotfree_input_line)
8842     {
8843       free (gotfree_input_line);
8844
8845       if (exp->X_op == O_constant || exp->X_op == O_register)
8846         exp->X_op = O_illegal;
8847     }
8848
8849   ret = i386_finalize_displacement (exp_seg, exp, types, disp_start);
8850
8851   RESTORE_END_STRING (disp_end);
8852
8853   return ret;
8854 }
8855
8856 static int
8857 i386_finalize_displacement (segT exp_seg ATTRIBUTE_UNUSED, expressionS *exp,
8858                             i386_operand_type types, const char *disp_start)
8859 {
8860   i386_operand_type bigdisp;
8861   int ret = 1;
8862
8863   /* We do this to make sure that the section symbol is in
8864      the symbol table.  We will ultimately change the relocation
8865      to be relative to the beginning of the section.  */
8866   if (i.reloc[this_operand] == BFD_RELOC_386_GOTOFF
8867       || i.reloc[this_operand] == BFD_RELOC_X86_64_GOTPCREL
8868       || i.reloc[this_operand] == BFD_RELOC_X86_64_GOTOFF64)
8869     {
8870       if (exp->X_op != O_symbol)
8871         goto inv_disp;
8872
8873       if (S_IS_LOCAL (exp->X_add_symbol)
8874           && S_GET_SEGMENT (exp->X_add_symbol) != undefined_section
8875           && S_GET_SEGMENT (exp->X_add_symbol) != expr_section)
8876         section_symbol (S_GET_SEGMENT (exp->X_add_symbol));
8877       exp->X_op = O_subtract;
8878       exp->X_op_symbol = GOT_symbol;
8879       if (i.reloc[this_operand] == BFD_RELOC_X86_64_GOTPCREL)
8880         i.reloc[this_operand] = BFD_RELOC_32_PCREL;
8881       else if (i.reloc[this_operand] == BFD_RELOC_X86_64_GOTOFF64)
8882         i.reloc[this_operand] = BFD_RELOC_64;
8883       else
8884         i.reloc[this_operand] = BFD_RELOC_32;
8885     }
8886
8887   else if (exp->X_op == O_absent
8888            || exp->X_op == O_illegal
8889            || exp->X_op == O_big)
8890     {
8891     inv_disp:
8892       as_bad (_("missing or invalid displacement expression `%s'"),
8893               disp_start);
8894       ret = 0;
8895     }
8896
8897   else if (flag_code == CODE_64BIT
8898            && !i.prefix[ADDR_PREFIX]
8899            && exp->X_op == O_constant)
8900     {
8901       /* Since displacement is signed extended to 64bit, don't allow
8902          disp32 and turn off disp32s if they are out of range.  */
8903       i.types[this_operand].bitfield.disp32 = 0;
8904       if (!fits_in_signed_long (exp->X_add_number))
8905         {
8906           i.types[this_operand].bitfield.disp32s = 0;
8907           if (i.types[this_operand].bitfield.baseindex)
8908             {
8909               as_bad (_("0x%lx out range of signed 32bit displacement"),
8910                       (long) exp->X_add_number);
8911               ret = 0;
8912             }
8913         }
8914     }
8915
8916 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
8917   else if (exp->X_op != O_constant
8918            && OUTPUT_FLAVOR == bfd_target_aout_flavour
8919            && exp_seg != absolute_section
8920            && exp_seg != text_section
8921            && exp_seg != data_section
8922            && exp_seg != bss_section
8923            && exp_seg != undefined_section
8924            && !bfd_is_com_section (exp_seg))
8925     {
8926       as_bad (_("unimplemented segment %s in operand"), exp_seg->name);
8927       ret = 0;
8928     }
8929 #endif
8930
8931   /* Check if this is a displacement only operand.  */
8932   bigdisp = i.types[this_operand];
8933   bigdisp.bitfield.disp8 = 0;
8934   bigdisp.bitfield.disp16 = 0;
8935   bigdisp.bitfield.disp32 = 0;
8936   bigdisp.bitfield.disp32s = 0;
8937   bigdisp.bitfield.disp64 = 0;
8938   if (operand_type_all_zero (&bigdisp))
8939     i.types[this_operand] = operand_type_and (i.types[this_operand],
8940                                               types);
8941
8942   return ret;
8943 }
8944
8945 /* Return the active addressing mode, taking address override and
8946    registers forming the address into consideration.  Update the
8947    address override prefix if necessary.  */
8948
8949 static enum flag_code
8950 i386_addressing_mode (void)
8951 {
8952   enum flag_code addr_mode;
8953
8954   if (i.prefix[ADDR_PREFIX])
8955     addr_mode = flag_code == CODE_32BIT ? CODE_16BIT : CODE_32BIT;
8956   else
8957     {
8958       addr_mode = flag_code;
8959
8960 #if INFER_ADDR_PREFIX
8961       if (i.mem_operands == 0)
8962         {
8963           /* Infer address prefix from the first memory operand.  */
8964           const reg_entry *addr_reg = i.base_reg;
8965
8966           if (addr_reg == NULL)
8967             addr_reg = i.index_reg;
8968
8969           if (addr_reg)
8970             {
8971               if (addr_reg->reg_num == RegEip
8972                   || addr_reg->reg_num == RegEiz
8973                   || addr_reg->reg_type.bitfield.dword)
8974                 addr_mode = CODE_32BIT;
8975               else if (flag_code != CODE_64BIT
8976                        && addr_reg->reg_type.bitfield.word)
8977                 addr_mode = CODE_16BIT;
8978
8979               if (addr_mode != flag_code)
8980                 {
8981                   i.prefix[ADDR_PREFIX] = ADDR_PREFIX_OPCODE;
8982                   i.prefixes += 1;
8983                   /* Change the size of any displacement too.  At most one
8984                      of Disp16 or Disp32 is set.
8985                      FIXME.  There doesn't seem to be any real need for
8986                      separate Disp16 and Disp32 flags.  The same goes for
8987                      Imm16 and Imm32.  Removing them would probably clean
8988                      up the code quite a lot.  */
8989                   if (flag_code != CODE_64BIT
8990                       && (i.types[this_operand].bitfield.disp16
8991                           || i.types[this_operand].bitfield.disp32))
8992                     i.types[this_operand]
8993                       = operand_type_xor (i.types[this_operand], disp16_32);
8994                 }
8995             }
8996         }
8997 #endif
8998     }
8999
9000   return addr_mode;
9001 }
9002
9003 /* Make sure the memory operand we've been dealt is valid.
9004    Return 1 on success, 0 on a failure.  */
9005
9006 static int
9007 i386_index_check (const char *operand_string)
9008 {
9009   const char *kind = "base/index";
9010   enum flag_code addr_mode = i386_addressing_mode ();
9011
9012   if (current_templates->start->opcode_modifier.isstring
9013       && !current_templates->start->opcode_modifier.immext
9014       && (current_templates->end[-1].opcode_modifier.isstring
9015           || i.mem_operands))
9016     {
9017       /* Memory operands of string insns are special in that they only allow
9018          a single register (rDI, rSI, or rBX) as their memory address.  */
9019       const reg_entry *expected_reg;
9020       static const char *di_si[][2] =
9021         {
9022           { "esi", "edi" },
9023           { "si", "di" },
9024           { "rsi", "rdi" }
9025         };
9026       static const char *bx[] = { "ebx", "bx", "rbx" };
9027
9028       kind = "string address";
9029
9030       if (current_templates->start->opcode_modifier.repprefixok)
9031         {
9032           i386_operand_type type = current_templates->end[-1].operand_types[0];
9033
9034           if (!type.bitfield.baseindex
9035               || ((!i.mem_operands != !intel_syntax)
9036                   && current_templates->end[-1].operand_types[1]
9037                      .bitfield.baseindex))
9038             type = current_templates->end[-1].operand_types[1];
9039           expected_reg = hash_find (reg_hash,
9040                                     di_si[addr_mode][type.bitfield.esseg]);
9041
9042         }
9043       else
9044         expected_reg = hash_find (reg_hash, bx[addr_mode]);
9045
9046       if (i.base_reg != expected_reg
9047           || i.index_reg
9048           || operand_type_check (i.types[this_operand], disp))
9049         {
9050           /* The second memory operand must have the same size as
9051              the first one.  */
9052           if (i.mem_operands
9053               && i.base_reg
9054               && !((addr_mode == CODE_64BIT
9055                     && i.base_reg->reg_type.bitfield.qword)
9056                    || (addr_mode == CODE_32BIT
9057                        ? i.base_reg->reg_type.bitfield.dword
9058                        : i.base_reg->reg_type.bitfield.word)))
9059             goto bad_address;
9060
9061           as_warn (_("`%s' is not valid here (expected `%c%s%s%c')"),
9062                    operand_string,
9063                    intel_syntax ? '[' : '(',
9064                    register_prefix,
9065                    expected_reg->reg_name,
9066                    intel_syntax ? ']' : ')');
9067           return 1;
9068         }
9069       else
9070         return 1;
9071
9072 bad_address:
9073       as_bad (_("`%s' is not a valid %s expression"),
9074               operand_string, kind);
9075       return 0;
9076     }
9077   else
9078     {
9079       if (addr_mode != CODE_16BIT)
9080         {
9081           /* 32-bit/64-bit checks.  */
9082           if ((i.base_reg
9083                && (addr_mode == CODE_64BIT
9084                    ? !i.base_reg->reg_type.bitfield.qword
9085                    : !i.base_reg->reg_type.bitfield.dword)
9086                && (i.index_reg
9087                    || (i.base_reg->reg_num
9088                        != (addr_mode == CODE_64BIT ? RegRip : RegEip))))
9089               || (i.index_reg
9090                   && !i.index_reg->reg_type.bitfield.xmmword
9091                   && !i.index_reg->reg_type.bitfield.ymmword
9092                   && !i.index_reg->reg_type.bitfield.zmmword
9093                   && ((addr_mode == CODE_64BIT
9094                        ? !(i.index_reg->reg_type.bitfield.qword
9095                            || i.index_reg->reg_num == RegRiz)
9096                        : !(i.index_reg->reg_type.bitfield.dword
9097                            || i.index_reg->reg_num == RegEiz))
9098                       || !i.index_reg->reg_type.bitfield.baseindex)))
9099             goto bad_address;
9100
9101           /* bndmk, bndldx, and bndstx have special restrictions. */
9102           if (current_templates->start->base_opcode == 0xf30f1b
9103               || (current_templates->start->base_opcode & ~1) == 0x0f1a)
9104             {
9105               /* They cannot use RIP-relative addressing. */
9106               if (i.base_reg && i.base_reg->reg_num == RegRip)
9107                 {
9108                   as_bad (_("`%s' cannot be used here"), operand_string);
9109                   return 0;
9110                 }
9111
9112               /* bndldx and bndstx ignore their scale factor. */
9113               if (current_templates->start->base_opcode != 0xf30f1b
9114                   && i.log2_scale_factor)
9115                 as_warn (_("register scaling is being ignored here"));
9116             }
9117         }
9118       else
9119         {
9120           /* 16-bit checks.  */
9121           if ((i.base_reg
9122                && (!i.base_reg->reg_type.bitfield.word
9123                    || !i.base_reg->reg_type.bitfield.baseindex))
9124               || (i.index_reg
9125                   && (!i.index_reg->reg_type.bitfield.word
9126                       || !i.index_reg->reg_type.bitfield.baseindex
9127                       || !(i.base_reg
9128                            && i.base_reg->reg_num < 6
9129                            && i.index_reg->reg_num >= 6
9130                            && i.log2_scale_factor == 0))))
9131             goto bad_address;
9132         }
9133     }
9134   return 1;
9135 }
9136
9137 /* Handle vector immediates.  */
9138
9139 static int
9140 RC_SAE_immediate (const char *imm_start)
9141 {
9142   unsigned int match_found, j;
9143   const char *pstr = imm_start;
9144   expressionS *exp;
9145
9146   if (*pstr != '{')
9147     return 0;
9148
9149   pstr++;
9150   match_found = 0;
9151   for (j = 0; j < ARRAY_SIZE (RC_NamesTable); j++)
9152     {
9153       if (!strncmp (pstr, RC_NamesTable[j].name, RC_NamesTable[j].len))
9154         {
9155           if (!i.rounding)
9156             {
9157               rc_op.type = RC_NamesTable[j].type;
9158               rc_op.operand = this_operand;
9159               i.rounding = &rc_op;
9160             }
9161           else
9162             {
9163               as_bad (_("duplicated `%s'"), imm_start);
9164               return 0;
9165             }
9166           pstr += RC_NamesTable[j].len;
9167           match_found = 1;
9168           break;
9169         }
9170     }
9171   if (!match_found)
9172     return 0;
9173
9174   if (*pstr++ != '}')
9175     {
9176       as_bad (_("Missing '}': '%s'"), imm_start);
9177       return 0;
9178     }
9179   /* RC/SAE immediate string should contain nothing more.  */;
9180   if (*pstr != 0)
9181     {
9182       as_bad (_("Junk after '}': '%s'"), imm_start);
9183       return 0;
9184     }
9185
9186   exp = &im_expressions[i.imm_operands++];
9187   i.op[this_operand].imms = exp;
9188
9189   exp->X_op = O_constant;
9190   exp->X_add_number = 0;
9191   exp->X_add_symbol = (symbolS *) 0;
9192   exp->X_op_symbol = (symbolS *) 0;
9193
9194   i.types[this_operand].bitfield.imm8 = 1;
9195   return 1;
9196 }
9197
9198 /* Only string instructions can have a second memory operand, so
9199    reduce current_templates to just those if it contains any.  */
9200 static int
9201 maybe_adjust_templates (void)
9202 {
9203   const insn_template *t;
9204
9205   gas_assert (i.mem_operands == 1);
9206
9207   for (t = current_templates->start; t < current_templates->end; ++t)
9208     if (t->opcode_modifier.isstring)
9209       break;
9210
9211   if (t < current_templates->end)
9212     {
9213       static templates aux_templates;
9214       bfd_boolean recheck;
9215
9216       aux_templates.start = t;
9217       for (; t < current_templates->end; ++t)
9218         if (!t->opcode_modifier.isstring)
9219           break;
9220       aux_templates.end = t;
9221
9222       /* Determine whether to re-check the first memory operand.  */
9223       recheck = (aux_templates.start != current_templates->start
9224                  || t != current_templates->end);
9225
9226       current_templates = &aux_templates;
9227
9228       if (recheck)
9229         {
9230           i.mem_operands = 0;
9231           if (i.memop1_string != NULL
9232               && i386_index_check (i.memop1_string) == 0)
9233             return 0;
9234           i.mem_operands = 1;
9235         }
9236     }
9237
9238   return 1;
9239 }
9240
9241 /* Parse OPERAND_STRING into the i386_insn structure I.  Returns zero
9242    on error.  */
9243
9244 static int
9245 i386_att_operand (char *operand_string)
9246 {
9247   const reg_entry *r;
9248   char *end_op;
9249   char *op_string = operand_string;
9250
9251   if (is_space_char (*op_string))
9252     ++op_string;
9253
9254   /* We check for an absolute prefix (differentiating,
9255      for example, 'jmp pc_relative_label' from 'jmp *absolute_label'.  */
9256   if (*op_string == ABSOLUTE_PREFIX)
9257     {
9258       ++op_string;
9259       if (is_space_char (*op_string))
9260         ++op_string;
9261       i.types[this_operand].bitfield.jumpabsolute = 1;
9262     }
9263
9264   /* Check if operand is a register.  */
9265   if ((r = parse_register (op_string, &end_op)) != NULL)
9266     {
9267       i386_operand_type temp;
9268
9269       /* Check for a segment override by searching for ':' after a
9270          segment register.  */
9271       op_string = end_op;
9272       if (is_space_char (*op_string))
9273         ++op_string;
9274       if (*op_string == ':'
9275           && (r->reg_type.bitfield.sreg2
9276               || r->reg_type.bitfield.sreg3))
9277         {
9278           switch (r->reg_num)
9279             {
9280             case 0:
9281               i.seg[i.mem_operands] = &es;
9282               break;
9283             case 1:
9284               i.seg[i.mem_operands] = &cs;
9285               break;
9286             case 2:
9287               i.seg[i.mem_operands] = &ss;
9288               break;
9289             case 3:
9290               i.seg[i.mem_operands] = &ds;
9291               break;
9292             case 4:
9293               i.seg[i.mem_operands] = &fs;
9294               break;
9295             case 5:
9296               i.seg[i.mem_operands] = &gs;
9297               break;
9298             }
9299
9300           /* Skip the ':' and whitespace.  */
9301           ++op_string;
9302           if (is_space_char (*op_string))
9303             ++op_string;
9304
9305           if (!is_digit_char (*op_string)
9306               && !is_identifier_char (*op_string)
9307               && *op_string != '('
9308               && *op_string != ABSOLUTE_PREFIX)
9309             {
9310               as_bad (_("bad memory operand `%s'"), op_string);
9311               return 0;
9312             }
9313           /* Handle case of %es:*foo.  */
9314           if (*op_string == ABSOLUTE_PREFIX)
9315             {
9316               ++op_string;
9317               if (is_space_char (*op_string))
9318                 ++op_string;
9319               i.types[this_operand].bitfield.jumpabsolute = 1;
9320             }
9321           goto do_memory_reference;
9322         }
9323
9324       /* Handle vector operations.  */
9325       if (*op_string == '{')
9326         {
9327           op_string = check_VecOperations (op_string, NULL);
9328           if (op_string == NULL)
9329             return 0;
9330         }
9331
9332       if (*op_string)
9333         {
9334           as_bad (_("junk `%s' after register"), op_string);
9335           return 0;
9336         }
9337       temp = r->reg_type;
9338       temp.bitfield.baseindex = 0;
9339       i.types[this_operand] = operand_type_or (i.types[this_operand],
9340                                                temp);
9341       i.types[this_operand].bitfield.unspecified = 0;
9342       i.op[this_operand].regs = r;
9343       i.reg_operands++;
9344     }
9345   else if (*op_string == REGISTER_PREFIX)
9346     {
9347       as_bad (_("bad register name `%s'"), op_string);
9348       return 0;
9349     }
9350   else if (*op_string == IMMEDIATE_PREFIX)
9351     {
9352       ++op_string;
9353       if (i.types[this_operand].bitfield.jumpabsolute)
9354         {
9355           as_bad (_("immediate operand illegal with absolute jump"));
9356           return 0;
9357         }
9358       if (!i386_immediate (op_string))
9359         return 0;
9360     }
9361   else if (RC_SAE_immediate (operand_string))
9362     {
9363       /* If it is a RC or SAE immediate, do nothing.  */
9364       ;
9365     }
9366   else if (is_digit_char (*op_string)
9367            || is_identifier_char (*op_string)
9368            || *op_string == '"'
9369            || *op_string == '(')
9370     {
9371       /* This is a memory reference of some sort.  */
9372       char *base_string;
9373
9374       /* Start and end of displacement string expression (if found).  */
9375       char *displacement_string_start;
9376       char *displacement_string_end;
9377       char *vop_start;
9378
9379     do_memory_reference:
9380       if (i.mem_operands == 1 && !maybe_adjust_templates ())
9381         return 0;
9382       if ((i.mem_operands == 1
9383            && !current_templates->start->opcode_modifier.isstring)
9384           || i.mem_operands == 2)
9385         {
9386           as_bad (_("too many memory references for `%s'"),
9387                   current_templates->start->name);
9388           return 0;
9389         }
9390
9391       /* Check for base index form.  We detect the base index form by
9392          looking for an ')' at the end of the operand, searching
9393          for the '(' matching it, and finding a REGISTER_PREFIX or ','
9394          after the '('.  */
9395       base_string = op_string + strlen (op_string);
9396
9397       /* Handle vector operations.  */
9398       vop_start = strchr (op_string, '{');
9399       if (vop_start && vop_start < base_string)
9400         {
9401           if (check_VecOperations (vop_start, base_string) == NULL)
9402             return 0;
9403           base_string = vop_start;
9404         }
9405
9406       --base_string;
9407       if (is_space_char (*base_string))
9408         --base_string;
9409
9410       /* If we only have a displacement, set-up for it to be parsed later.  */
9411       displacement_string_start = op_string;
9412       displacement_string_end = base_string + 1;
9413
9414       if (*base_string == ')')
9415         {
9416           char *temp_string;
9417           unsigned int parens_balanced = 1;
9418           /* We've already checked that the number of left & right ()'s are
9419              equal, so this loop will not be infinite.  */
9420           do
9421             {
9422               base_string--;
9423               if (*base_string == ')')
9424                 parens_balanced++;
9425               if (*base_string == '(')
9426                 parens_balanced--;
9427             }
9428           while (parens_balanced);
9429
9430           temp_string = base_string;
9431
9432           /* Skip past '(' and whitespace.  */
9433           ++base_string;
9434           if (is_space_char (*base_string))
9435             ++base_string;
9436
9437           if (*base_string == ','
9438               || ((i.base_reg = parse_register (base_string, &end_op))
9439                   != NULL))
9440             {
9441               displacement_string_end = temp_string;
9442
9443               i.types[this_operand].bitfield.baseindex = 1;
9444
9445               if (i.base_reg)
9446                 {
9447                   base_string = end_op;
9448                   if (is_space_char (*base_string))
9449                     ++base_string;
9450                 }
9451
9452               /* There may be an index reg or scale factor here.  */
9453               if (*base_string == ',')
9454                 {
9455                   ++base_string;
9456                   if (is_space_char (*base_string))
9457                     ++base_string;
9458
9459                   if ((i.index_reg = parse_register (base_string, &end_op))
9460                       != NULL)
9461                     {
9462                       base_string = end_op;
9463                       if (is_space_char (*base_string))
9464                         ++base_string;
9465                       if (*base_string == ',')
9466                         {
9467                           ++base_string;
9468                           if (is_space_char (*base_string))
9469                             ++base_string;
9470                         }
9471                       else if (*base_string != ')')
9472                         {
9473                           as_bad (_("expecting `,' or `)' "
9474                                     "after index register in `%s'"),
9475                                   operand_string);
9476                           return 0;
9477                         }
9478                     }
9479                   else if (*base_string == REGISTER_PREFIX)
9480                     {
9481                       end_op = strchr (base_string, ',');
9482                       if (end_op)
9483                         *end_op = '\0';
9484                       as_bad (_("bad register name `%s'"), base_string);
9485                       return 0;
9486                     }
9487
9488                   /* Check for scale factor.  */
9489                   if (*base_string != ')')
9490                     {
9491                       char *end_scale = i386_scale (base_string);
9492
9493                       if (!end_scale)
9494                         return 0;
9495
9496                       base_string = end_scale;
9497                       if (is_space_char (*base_string))
9498                         ++base_string;
9499                       if (*base_string != ')')
9500                         {
9501                           as_bad (_("expecting `)' "
9502                                     "after scale factor in `%s'"),
9503                                   operand_string);
9504                           return 0;
9505                         }
9506                     }
9507                   else if (!i.index_reg)
9508                     {
9509                       as_bad (_("expecting index register or scale factor "
9510                                 "after `,'; got '%c'"),
9511                               *base_string);
9512                       return 0;
9513                     }
9514                 }
9515               else if (*base_string != ')')
9516                 {
9517                   as_bad (_("expecting `,' or `)' "
9518                             "after base register in `%s'"),
9519                           operand_string);
9520                   return 0;
9521                 }
9522             }
9523           else if (*base_string == REGISTER_PREFIX)
9524             {
9525               end_op = strchr (base_string, ',');
9526               if (end_op)
9527                 *end_op = '\0';
9528               as_bad (_("bad register name `%s'"), base_string);
9529               return 0;
9530             }
9531         }
9532
9533       /* If there's an expression beginning the operand, parse it,
9534          assuming displacement_string_start and
9535          displacement_string_end are meaningful.  */
9536       if (displacement_string_start != displacement_string_end)
9537         {
9538           if (!i386_displacement (displacement_string_start,
9539                                   displacement_string_end))
9540             return 0;
9541         }
9542
9543       /* Special case for (%dx) while doing input/output op.  */
9544       if (i.base_reg
9545           && operand_type_equal (&i.base_reg->reg_type,
9546                                  &reg16_inoutportreg)
9547           && i.index_reg == 0
9548           && i.log2_scale_factor == 0
9549           && i.seg[i.mem_operands] == 0
9550           && !operand_type_check (i.types[this_operand], disp))
9551         {
9552           i.types[this_operand] = inoutportreg;
9553           return 1;
9554         }
9555
9556       if (i386_index_check (operand_string) == 0)
9557         return 0;
9558       i.types[this_operand].bitfield.mem = 1;
9559       if (i.mem_operands == 0)
9560         i.memop1_string = xstrdup (operand_string);
9561       i.mem_operands++;
9562     }
9563   else
9564     {
9565       /* It's not a memory operand; argh!  */
9566       as_bad (_("invalid char %s beginning operand %d `%s'"),
9567               output_invalid (*op_string),
9568               this_operand + 1,
9569               op_string);
9570       return 0;
9571     }
9572   return 1;                     /* Normal return.  */
9573 }
9574 \f
9575 /* Calculate the maximum variable size (i.e., excluding fr_fix)
9576    that an rs_machine_dependent frag may reach.  */
9577
9578 unsigned int
9579 i386_frag_max_var (fragS *frag)
9580 {
9581   /* The only relaxable frags are for jumps.
9582      Unconditional jumps can grow by 4 bytes and others by 5 bytes.  */
9583   gas_assert (frag->fr_type == rs_machine_dependent);
9584   return TYPE_FROM_RELAX_STATE (frag->fr_subtype) == UNCOND_JUMP ? 4 : 5;
9585 }
9586
9587 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
9588 static int
9589 elf_symbol_resolved_in_segment_p (symbolS *fr_symbol, offsetT fr_var)
9590 {
9591   /* STT_GNU_IFUNC symbol must go through PLT.  */
9592   if ((symbol_get_bfdsym (fr_symbol)->flags
9593        & BSF_GNU_INDIRECT_FUNCTION) != 0)
9594     return 0;
9595
9596   if (!S_IS_EXTERNAL (fr_symbol))
9597     /* Symbol may be weak or local.  */
9598     return !S_IS_WEAK (fr_symbol);
9599
9600   /* Global symbols with non-default visibility can't be preempted. */
9601   if (ELF_ST_VISIBILITY (S_GET_OTHER (fr_symbol)) != STV_DEFAULT)
9602     return 1;
9603
9604   if (fr_var != NO_RELOC)
9605     switch ((enum bfd_reloc_code_real) fr_var)
9606       {
9607       case BFD_RELOC_386_PLT32:
9608       case BFD_RELOC_X86_64_PLT32:
9609         /* Symbol with PLT relocation may be preempted. */
9610         return 0;
9611       default:
9612         abort ();
9613       }
9614
9615   /* Global symbols with default visibility in a shared library may be
9616      preempted by another definition.  */
9617   return !shared;
9618 }
9619 #endif
9620
9621 /* md_estimate_size_before_relax()
9622
9623    Called just before relax() for rs_machine_dependent frags.  The x86
9624    assembler uses these frags to handle variable size jump
9625    instructions.
9626
9627    Any symbol that is now undefined will not become defined.
9628    Return the correct fr_subtype in the frag.
9629    Return the initial "guess for variable size of frag" to caller.
9630    The guess is actually the growth beyond the fixed part.  Whatever
9631    we do to grow the fixed or variable part contributes to our
9632    returned value.  */
9633
9634 int
9635 md_estimate_size_before_relax (fragS *fragP, segT segment)
9636 {
9637   /* We've already got fragP->fr_subtype right;  all we have to do is
9638      check for un-relaxable symbols.  On an ELF system, we can't relax
9639      an externally visible symbol, because it may be overridden by a
9640      shared library.  */
9641   if (S_GET_SEGMENT (fragP->fr_symbol) != segment
9642 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
9643       || (IS_ELF
9644           && !elf_symbol_resolved_in_segment_p (fragP->fr_symbol,
9645                                                 fragP->fr_var))
9646 #endif
9647 #if defined (OBJ_COFF) && defined (TE_PE)
9648       || (OUTPUT_FLAVOR == bfd_target_coff_flavour
9649           && S_IS_WEAK (fragP->fr_symbol))
9650 #endif
9651       )
9652     {
9653       /* Symbol is undefined in this segment, or we need to keep a
9654          reloc so that weak symbols can be overridden.  */
9655       int size = (fragP->fr_subtype & CODE16) ? 2 : 4;
9656       enum bfd_reloc_code_real reloc_type;
9657       unsigned char *opcode;
9658       int old_fr_fix;
9659
9660       if (fragP->fr_var != NO_RELOC)
9661         reloc_type = (enum bfd_reloc_code_real) fragP->fr_var;
9662       else if (size == 2)
9663         reloc_type = BFD_RELOC_16_PCREL;
9664 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
9665       else if (need_plt32_p (fragP->fr_symbol))
9666         reloc_type = BFD_RELOC_X86_64_PLT32;
9667 #endif
9668       else
9669         reloc_type = BFD_RELOC_32_PCREL;
9670
9671       old_fr_fix = fragP->fr_fix;
9672       opcode = (unsigned char *) fragP->fr_opcode;
9673
9674       switch (TYPE_FROM_RELAX_STATE (fragP->fr_subtype))
9675         {
9676         case UNCOND_JUMP:
9677           /* Make jmp (0xeb) a (d)word displacement jump.  */
9678           opcode[0] = 0xe9;
9679           fragP->fr_fix += size;
9680           fix_new (fragP, old_fr_fix, size,
9681                    fragP->fr_symbol,
9682                    fragP->fr_offset, 1,
9683                    reloc_type);
9684           break;
9685
9686         case COND_JUMP86:
9687           if (size == 2
9688               && (!no_cond_jump_promotion || fragP->fr_var != NO_RELOC))
9689             {
9690               /* Negate the condition, and branch past an
9691                  unconditional jump.  */
9692               opcode[0] ^= 1;
9693               opcode[1] = 3;
9694               /* Insert an unconditional jump.  */
9695               opcode[2] = 0xe9;
9696               /* We added two extra opcode bytes, and have a two byte
9697                  offset.  */
9698               fragP->fr_fix += 2 + 2;
9699               fix_new (fragP, old_fr_fix + 2, 2,
9700                        fragP->fr_symbol,
9701                        fragP->fr_offset, 1,
9702                        reloc_type);
9703               break;
9704             }
9705           /* Fall through.  */
9706
9707         case COND_JUMP:
9708           if (no_cond_jump_promotion && fragP->fr_var == NO_RELOC)
9709             {
9710               fixS *fixP;
9711
9712               fragP->fr_fix += 1;
9713               fixP = fix_new (fragP, old_fr_fix, 1,
9714                               fragP->fr_symbol,
9715                               fragP->fr_offset, 1,
9716                               BFD_RELOC_8_PCREL);
9717               fixP->fx_signed = 1;
9718               break;
9719             }
9720
9721           /* This changes the byte-displacement jump 0x7N
9722              to the (d)word-displacement jump 0x0f,0x8N.  */
9723           opcode[1] = opcode[0] + 0x10;
9724           opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
9725           /* We've added an opcode byte.  */
9726           fragP->fr_fix += 1 + size;
9727           fix_new (fragP, old_fr_fix + 1, size,
9728                    fragP->fr_symbol,
9729                    fragP->fr_offset, 1,
9730                    reloc_type);
9731           break;
9732
9733         default:
9734           BAD_CASE (fragP->fr_subtype);
9735           break;
9736         }
9737       frag_wane (fragP);
9738       return fragP->fr_fix - old_fr_fix;
9739     }
9740
9741   /* Guess size depending on current relax state.  Initially the relax
9742      state will correspond to a short jump and we return 1, because
9743      the variable part of the frag (the branch offset) is one byte
9744      long.  However, we can relax a section more than once and in that
9745      case we must either set fr_subtype back to the unrelaxed state,
9746      or return the value for the appropriate branch.  */
9747   return md_relax_table[fragP->fr_subtype].rlx_length;
9748 }
9749
9750 /* Called after relax() is finished.
9751
9752    In:  Address of frag.
9753         fr_type == rs_machine_dependent.
9754         fr_subtype is what the address relaxed to.
9755
9756    Out: Any fixSs and constants are set up.
9757         Caller will turn frag into a ".space 0".  */
9758
9759 void
9760 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, segT sec ATTRIBUTE_UNUSED,
9761                  fragS *fragP)
9762 {
9763   unsigned char *opcode;
9764   unsigned char *where_to_put_displacement = NULL;
9765   offsetT target_address;
9766   offsetT opcode_address;
9767   unsigned int extension = 0;
9768   offsetT displacement_from_opcode_start;
9769
9770   opcode = (unsigned char *) fragP->fr_opcode;
9771
9772   /* Address we want to reach in file space.  */
9773   target_address = S_GET_VALUE (fragP->fr_symbol) + fragP->fr_offset;
9774
9775   /* Address opcode resides at in file space.  */
9776   opcode_address = fragP->fr_address + fragP->fr_fix;
9777
9778   /* Displacement from opcode start to fill into instruction.  */
9779   displacement_from_opcode_start = target_address - opcode_address;
9780
9781   if ((fragP->fr_subtype & BIG) == 0)
9782     {
9783       /* Don't have to change opcode.  */
9784       extension = 1;            /* 1 opcode + 1 displacement  */
9785       where_to_put_displacement = &opcode[1];
9786     }
9787   else
9788     {
9789       if (no_cond_jump_promotion
9790           && TYPE_FROM_RELAX_STATE (fragP->fr_subtype) != UNCOND_JUMP)
9791         as_warn_where (fragP->fr_file, fragP->fr_line,
9792                        _("long jump required"));
9793
9794       switch (fragP->fr_subtype)
9795         {
9796         case ENCODE_RELAX_STATE (UNCOND_JUMP, BIG):
9797           extension = 4;                /* 1 opcode + 4 displacement  */
9798           opcode[0] = 0xe9;
9799           where_to_put_displacement = &opcode[1];
9800           break;
9801
9802         case ENCODE_RELAX_STATE (UNCOND_JUMP, BIG16):
9803           extension = 2;                /* 1 opcode + 2 displacement  */
9804           opcode[0] = 0xe9;
9805           where_to_put_displacement = &opcode[1];
9806           break;
9807
9808         case ENCODE_RELAX_STATE (COND_JUMP, BIG):
9809         case ENCODE_RELAX_STATE (COND_JUMP86, BIG):
9810           extension = 5;                /* 2 opcode + 4 displacement  */
9811           opcode[1] = opcode[0] + 0x10;
9812           opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
9813           where_to_put_displacement = &opcode[2];
9814           break;
9815
9816         case ENCODE_RELAX_STATE (COND_JUMP, BIG16):
9817           extension = 3;                /* 2 opcode + 2 displacement  */
9818           opcode[1] = opcode[0] + 0x10;
9819           opcode[0] = TWO_BYTE_OPCODE_ESCAPE;
9820           where_to_put_displacement = &opcode[2];
9821           break;
9822
9823         case ENCODE_RELAX_STATE (COND_JUMP86, BIG16):
9824           extension = 4;
9825           opcode[0] ^= 1;
9826           opcode[1] = 3;
9827           opcode[2] = 0xe9;
9828           where_to_put_displacement = &opcode[3];
9829           break;
9830
9831         default:
9832           BAD_CASE (fragP->fr_subtype);
9833           break;
9834         }
9835     }
9836
9837   /* If size if less then four we are sure that the operand fits,
9838      but if it's 4, then it could be that the displacement is larger
9839      then -/+ 2GB.  */
9840   if (DISP_SIZE_FROM_RELAX_STATE (fragP->fr_subtype) == 4
9841       && object_64bit
9842       && ((addressT) (displacement_from_opcode_start - extension
9843                       + ((addressT) 1 << 31))
9844           > (((addressT) 2 << 31) - 1)))
9845     {
9846       as_bad_where (fragP->fr_file, fragP->fr_line,
9847                     _("jump target out of range"));
9848       /* Make us emit 0.  */
9849       displacement_from_opcode_start = extension;
9850     }
9851   /* Now put displacement after opcode.  */
9852   md_number_to_chars ((char *) where_to_put_displacement,
9853                       (valueT) (displacement_from_opcode_start - extension),
9854                       DISP_SIZE_FROM_RELAX_STATE (fragP->fr_subtype));
9855   fragP->fr_fix += extension;
9856 }
9857 \f
9858 /* Apply a fixup (fixP) to segment data, once it has been determined
9859    by our caller that we have all the info we need to fix it up.
9860
9861    Parameter valP is the pointer to the value of the bits.
9862
9863    On the 386, immediates, displacements, and data pointers are all in
9864    the same (little-endian) format, so we don't need to care about which
9865    we are handling.  */
9866
9867 void
9868 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
9869 {
9870   char *p = fixP->fx_where + fixP->fx_frag->fr_literal;
9871   valueT value = *valP;
9872
9873 #if !defined (TE_Mach)
9874   if (fixP->fx_pcrel)
9875     {
9876       switch (fixP->fx_r_type)
9877         {
9878         default:
9879           break;
9880
9881         case BFD_RELOC_64:
9882           fixP->fx_r_type = BFD_RELOC_64_PCREL;
9883           break;
9884         case BFD_RELOC_32:
9885         case BFD_RELOC_X86_64_32S:
9886           fixP->fx_r_type = BFD_RELOC_32_PCREL;
9887           break;
9888         case BFD_RELOC_16:
9889           fixP->fx_r_type = BFD_RELOC_16_PCREL;
9890           break;
9891         case BFD_RELOC_8:
9892           fixP->fx_r_type = BFD_RELOC_8_PCREL;
9893           break;
9894         }
9895     }
9896
9897   if (fixP->fx_addsy != NULL
9898       && (fixP->fx_r_type == BFD_RELOC_32_PCREL
9899           || fixP->fx_r_type == BFD_RELOC_64_PCREL
9900           || fixP->fx_r_type == BFD_RELOC_16_PCREL
9901           || fixP->fx_r_type == BFD_RELOC_8_PCREL)
9902       && !use_rela_relocations)
9903     {
9904       /* This is a hack.  There should be a better way to handle this.
9905          This covers for the fact that bfd_install_relocation will
9906          subtract the current location (for partial_inplace, PC relative
9907          relocations); see more below.  */
9908 #ifndef OBJ_AOUT
9909       if (IS_ELF
9910 #ifdef TE_PE
9911           || OUTPUT_FLAVOR == bfd_target_coff_flavour
9912 #endif
9913           )
9914         value += fixP->fx_where + fixP->fx_frag->fr_address;
9915 #endif
9916 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
9917       if (IS_ELF)
9918         {
9919           segT sym_seg = S_GET_SEGMENT (fixP->fx_addsy);
9920
9921           if ((sym_seg == seg
9922                || (symbol_section_p (fixP->fx_addsy)
9923                    && sym_seg != absolute_section))
9924               && !generic_force_reloc (fixP))
9925             {
9926               /* Yes, we add the values in twice.  This is because
9927                  bfd_install_relocation subtracts them out again.  I think
9928                  bfd_install_relocation is broken, but I don't dare change
9929                  it.  FIXME.  */
9930               value += fixP->fx_where + fixP->fx_frag->fr_address;
9931             }
9932         }
9933 #endif
9934 #if defined (OBJ_COFF) && defined (TE_PE)
9935       /* For some reason, the PE format does not store a
9936          section address offset for a PC relative symbol.  */
9937       if (S_GET_SEGMENT (fixP->fx_addsy) != seg
9938           || S_IS_WEAK (fixP->fx_addsy))
9939         value += md_pcrel_from (fixP);
9940 #endif
9941     }
9942 #if defined (OBJ_COFF) && defined (TE_PE)
9943   if (fixP->fx_addsy != NULL
9944       && S_IS_WEAK (fixP->fx_addsy)
9945       /* PR 16858: Do not modify weak function references.  */
9946       && ! fixP->fx_pcrel)
9947     {
9948 #if !defined (TE_PEP)
9949       /* For x86 PE weak function symbols are neither PC-relative
9950          nor do they set S_IS_FUNCTION.  So the only reliable way
9951          to detect them is to check the flags of their containing
9952          section.  */
9953       if (S_GET_SEGMENT (fixP->fx_addsy) != NULL
9954           && S_GET_SEGMENT (fixP->fx_addsy)->flags & SEC_CODE)
9955         ;
9956       else
9957 #endif
9958       value -= S_GET_VALUE (fixP->fx_addsy);
9959     }
9960 #endif
9961
9962   /* Fix a few things - the dynamic linker expects certain values here,
9963      and we must not disappoint it.  */
9964 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
9965   if (IS_ELF && fixP->fx_addsy)
9966     switch (fixP->fx_r_type)
9967       {
9968       case BFD_RELOC_386_PLT32:
9969       case BFD_RELOC_X86_64_PLT32:
9970         /* Make the jump instruction point to the address of the operand.  At
9971            runtime we merely add the offset to the actual PLT entry.  */
9972         value = -4;
9973         break;
9974
9975       case BFD_RELOC_386_TLS_GD:
9976       case BFD_RELOC_386_TLS_LDM:
9977       case BFD_RELOC_386_TLS_IE_32:
9978       case BFD_RELOC_386_TLS_IE:
9979       case BFD_RELOC_386_TLS_GOTIE:
9980       case BFD_RELOC_386_TLS_GOTDESC:
9981       case BFD_RELOC_X86_64_TLSGD:
9982       case BFD_RELOC_X86_64_TLSLD:
9983       case BFD_RELOC_X86_64_GOTTPOFF:
9984       case BFD_RELOC_X86_64_GOTPC32_TLSDESC:
9985         value = 0; /* Fully resolved at runtime.  No addend.  */
9986         /* Fallthrough */
9987       case BFD_RELOC_386_TLS_LE:
9988       case BFD_RELOC_386_TLS_LDO_32:
9989       case BFD_RELOC_386_TLS_LE_32:
9990       case BFD_RELOC_X86_64_DTPOFF32:
9991       case BFD_RELOC_X86_64_DTPOFF64:
9992       case BFD_RELOC_X86_64_TPOFF32:
9993       case BFD_RELOC_X86_64_TPOFF64:
9994         S_SET_THREAD_LOCAL (fixP->fx_addsy);
9995         break;
9996
9997       case BFD_RELOC_386_TLS_DESC_CALL:
9998       case BFD_RELOC_X86_64_TLSDESC_CALL:
9999         value = 0; /* Fully resolved at runtime.  No addend.  */
10000         S_SET_THREAD_LOCAL (fixP->fx_addsy);
10001         fixP->fx_done = 0;
10002         return;
10003
10004       case BFD_RELOC_VTABLE_INHERIT:
10005       case BFD_RELOC_VTABLE_ENTRY:
10006         fixP->fx_done = 0;
10007         return;
10008
10009       default:
10010         break;
10011       }
10012 #endif /* defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)  */
10013   *valP = value;
10014 #endif /* !defined (TE_Mach)  */
10015
10016   /* Are we finished with this relocation now?  */
10017   if (fixP->fx_addsy == NULL)
10018     fixP->fx_done = 1;
10019 #if defined (OBJ_COFF) && defined (TE_PE)
10020   else if (fixP->fx_addsy != NULL && S_IS_WEAK (fixP->fx_addsy))
10021     {
10022       fixP->fx_done = 0;
10023       /* Remember value for tc_gen_reloc.  */
10024       fixP->fx_addnumber = value;
10025       /* Clear out the frag for now.  */
10026       value = 0;
10027     }
10028 #endif
10029   else if (use_rela_relocations)
10030     {
10031       fixP->fx_no_overflow = 1;
10032       /* Remember value for tc_gen_reloc.  */
10033       fixP->fx_addnumber = value;
10034       value = 0;
10035     }
10036
10037   md_number_to_chars (p, value, fixP->fx_size);
10038 }
10039 \f
10040 const char *
10041 md_atof (int type, char *litP, int *sizeP)
10042 {
10043   /* This outputs the LITTLENUMs in REVERSE order;
10044      in accord with the bigendian 386.  */
10045   return ieee_md_atof (type, litP, sizeP, FALSE);
10046 }
10047 \f
10048 static char output_invalid_buf[sizeof (unsigned char) * 2 + 6];
10049
10050 static char *
10051 output_invalid (int c)
10052 {
10053   if (ISPRINT (c))
10054     snprintf (output_invalid_buf, sizeof (output_invalid_buf),
10055               "'%c'", c);
10056   else
10057     snprintf (output_invalid_buf, sizeof (output_invalid_buf),
10058               "(0x%x)", (unsigned char) c);
10059   return output_invalid_buf;
10060 }
10061
10062 /* REG_STRING starts *before* REGISTER_PREFIX.  */
10063
10064 static const reg_entry *
10065 parse_real_register (char *reg_string, char **end_op)
10066 {
10067   char *s = reg_string;
10068   char *p;
10069   char reg_name_given[MAX_REG_NAME_SIZE + 1];
10070   const reg_entry *r;
10071
10072   /* Skip possible REGISTER_PREFIX and possible whitespace.  */
10073   if (*s == REGISTER_PREFIX)
10074     ++s;
10075
10076   if (is_space_char (*s))
10077     ++s;
10078
10079   p = reg_name_given;
10080   while ((*p++ = register_chars[(unsigned char) *s]) != '\0')
10081     {
10082       if (p >= reg_name_given + MAX_REG_NAME_SIZE)
10083         return (const reg_entry *) NULL;
10084       s++;
10085     }
10086
10087   /* For naked regs, make sure that we are not dealing with an identifier.
10088      This prevents confusing an identifier like `eax_var' with register
10089      `eax'.  */
10090   if (allow_naked_reg && identifier_chars[(unsigned char) *s])
10091     return (const reg_entry *) NULL;
10092
10093   *end_op = s;
10094
10095   r = (const reg_entry *) hash_find (reg_hash, reg_name_given);
10096
10097   /* Handle floating point regs, allowing spaces in the (i) part.  */
10098   if (r == i386_regtab /* %st is first entry of table  */)
10099     {
10100       if (is_space_char (*s))
10101         ++s;
10102       if (*s == '(')
10103         {
10104           ++s;
10105           if (is_space_char (*s))
10106             ++s;
10107           if (*s >= '0' && *s <= '7')
10108             {
10109               int fpr = *s - '0';
10110               ++s;
10111               if (is_space_char (*s))
10112                 ++s;
10113               if (*s == ')')
10114                 {
10115                   *end_op = s + 1;
10116                   r = (const reg_entry *) hash_find (reg_hash, "st(0)");
10117                   know (r);
10118                   return r + fpr;
10119                 }
10120             }
10121           /* We have "%st(" then garbage.  */
10122           return (const reg_entry *) NULL;
10123         }
10124     }
10125
10126   if (r == NULL || allow_pseudo_reg)
10127     return r;
10128
10129   if (operand_type_all_zero (&r->reg_type))
10130     return (const reg_entry *) NULL;
10131
10132   if ((r->reg_type.bitfield.dword
10133        || r->reg_type.bitfield.sreg3
10134        || r->reg_type.bitfield.control
10135        || r->reg_type.bitfield.debug
10136        || r->reg_type.bitfield.test)
10137       && !cpu_arch_flags.bitfield.cpui386)
10138     return (const reg_entry *) NULL;
10139
10140   if (r->reg_type.bitfield.tbyte
10141       && !cpu_arch_flags.bitfield.cpu8087
10142       && !cpu_arch_flags.bitfield.cpu287
10143       && !cpu_arch_flags.bitfield.cpu387)
10144     return (const reg_entry *) NULL;
10145
10146   if (r->reg_type.bitfield.regmmx && !cpu_arch_flags.bitfield.cpuregmmx)
10147     return (const reg_entry *) NULL;
10148
10149   if (r->reg_type.bitfield.xmmword && !cpu_arch_flags.bitfield.cpuregxmm)
10150     return (const reg_entry *) NULL;
10151
10152   if (r->reg_type.bitfield.ymmword && !cpu_arch_flags.bitfield.cpuregymm)
10153     return (const reg_entry *) NULL;
10154
10155   if (r->reg_type.bitfield.zmmword && !cpu_arch_flags.bitfield.cpuregzmm)
10156     return (const reg_entry *) NULL;
10157
10158   if (r->reg_type.bitfield.regmask
10159       && !cpu_arch_flags.bitfield.cpuregmask)
10160     return (const reg_entry *) NULL;
10161
10162   /* Don't allow fake index register unless allow_index_reg isn't 0. */
10163   if (!allow_index_reg
10164       && (r->reg_num == RegEiz || r->reg_num == RegRiz))
10165     return (const reg_entry *) NULL;
10166
10167   /* Upper 16 vector register is only available with VREX in 64bit
10168      mode.  */
10169   if ((r->reg_flags & RegVRex))
10170     {
10171       if (i.vec_encoding == vex_encoding_default)
10172         i.vec_encoding = vex_encoding_evex;
10173
10174       if (!cpu_arch_flags.bitfield.cpuvrex
10175           || i.vec_encoding != vex_encoding_evex
10176           || flag_code != CODE_64BIT)
10177         return (const reg_entry *) NULL;
10178     }
10179
10180   if (((r->reg_flags & (RegRex64 | RegRex))
10181        || r->reg_type.bitfield.qword)
10182       && (!cpu_arch_flags.bitfield.cpulm
10183           || !operand_type_equal (&r->reg_type, &control))
10184       && flag_code != CODE_64BIT)
10185     return (const reg_entry *) NULL;
10186
10187   if (r->reg_type.bitfield.sreg3 && r->reg_num == RegFlat && !intel_syntax)
10188     return (const reg_entry *) NULL;
10189
10190   return r;
10191 }
10192
10193 /* REG_STRING starts *before* REGISTER_PREFIX.  */
10194
10195 static const reg_entry *
10196 parse_register (char *reg_string, char **end_op)
10197 {
10198   const reg_entry *r;
10199
10200   if (*reg_string == REGISTER_PREFIX || allow_naked_reg)
10201     r = parse_real_register (reg_string, end_op);
10202   else
10203     r = NULL;
10204   if (!r)
10205     {
10206       char *save = input_line_pointer;
10207       char c;
10208       symbolS *symbolP;
10209
10210       input_line_pointer = reg_string;
10211       c = get_symbol_name (&reg_string);
10212       symbolP = symbol_find (reg_string);
10213       if (symbolP && S_GET_SEGMENT (symbolP) == reg_section)
10214         {
10215           const expressionS *e = symbol_get_value_expression (symbolP);
10216
10217           know (e->X_op == O_register);
10218           know (e->X_add_number >= 0
10219                 && (valueT) e->X_add_number < i386_regtab_size);
10220           r = i386_regtab + e->X_add_number;
10221           if ((r->reg_flags & RegVRex))
10222             i.vec_encoding = vex_encoding_evex;
10223           *end_op = input_line_pointer;
10224         }
10225       *input_line_pointer = c;
10226       input_line_pointer = save;
10227     }
10228   return r;
10229 }
10230
10231 int
10232 i386_parse_name (char *name, expressionS *e, char *nextcharP)
10233 {
10234   const reg_entry *r;
10235   char *end = input_line_pointer;
10236
10237   *end = *nextcharP;
10238   r = parse_register (name, &input_line_pointer);
10239   if (r && end <= input_line_pointer)
10240     {
10241       *nextcharP = *input_line_pointer;
10242       *input_line_pointer = 0;
10243       e->X_op = O_register;
10244       e->X_add_number = r - i386_regtab;
10245       return 1;
10246     }
10247   input_line_pointer = end;
10248   *end = 0;
10249   return intel_syntax ? i386_intel_parse_name (name, e) : 0;
10250 }
10251
10252 void
10253 md_operand (expressionS *e)
10254 {
10255   char *end;
10256   const reg_entry *r;
10257
10258   switch (*input_line_pointer)
10259     {
10260     case REGISTER_PREFIX:
10261       r = parse_real_register (input_line_pointer, &end);
10262       if (r)
10263         {
10264           e->X_op = O_register;
10265           e->X_add_number = r - i386_regtab;
10266           input_line_pointer = end;
10267         }
10268       break;
10269
10270     case '[':
10271       gas_assert (intel_syntax);
10272       end = input_line_pointer++;
10273       expression (e);
10274       if (*input_line_pointer == ']')
10275         {
10276           ++input_line_pointer;
10277           e->X_op_symbol = make_expr_symbol (e);
10278           e->X_add_symbol = NULL;
10279           e->X_add_number = 0;
10280           e->X_op = O_index;
10281         }
10282       else
10283         {
10284           e->X_op = O_absent;
10285           input_line_pointer = end;
10286         }
10287       break;
10288     }
10289 }
10290
10291 \f
10292 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
10293 const char *md_shortopts = "kVQ:sqnO::";
10294 #else
10295 const char *md_shortopts = "qnO::";
10296 #endif
10297
10298 #define OPTION_32 (OPTION_MD_BASE + 0)
10299 #define OPTION_64 (OPTION_MD_BASE + 1)
10300 #define OPTION_DIVIDE (OPTION_MD_BASE + 2)
10301 #define OPTION_MARCH (OPTION_MD_BASE + 3)
10302 #define OPTION_MTUNE (OPTION_MD_BASE + 4)
10303 #define OPTION_MMNEMONIC (OPTION_MD_BASE + 5)
10304 #define OPTION_MSYNTAX (OPTION_MD_BASE + 6)
10305 #define OPTION_MINDEX_REG (OPTION_MD_BASE + 7)
10306 #define OPTION_MNAKED_REG (OPTION_MD_BASE + 8)
10307 #define OPTION_MRELAX_RELOCATIONS (OPTION_MD_BASE + 9)
10308 #define OPTION_MSSE2AVX (OPTION_MD_BASE + 10)
10309 #define OPTION_MSSE_CHECK (OPTION_MD_BASE + 11)
10310 #define OPTION_MOPERAND_CHECK (OPTION_MD_BASE + 12)
10311 #define OPTION_MAVXSCALAR (OPTION_MD_BASE + 13)
10312 #define OPTION_X32 (OPTION_MD_BASE + 14)
10313 #define OPTION_MADD_BND_PREFIX (OPTION_MD_BASE + 15)
10314 #define OPTION_MEVEXLIG (OPTION_MD_BASE + 16)
10315 #define OPTION_MEVEXWIG (OPTION_MD_BASE + 17)
10316 #define OPTION_MBIG_OBJ (OPTION_MD_BASE + 18)
10317 #define OPTION_MOMIT_LOCK_PREFIX (OPTION_MD_BASE + 19)
10318 #define OPTION_MEVEXRCIG (OPTION_MD_BASE + 20)
10319 #define OPTION_MSHARED (OPTION_MD_BASE + 21)
10320 #define OPTION_MAMD64 (OPTION_MD_BASE + 22)
10321 #define OPTION_MINTEL64 (OPTION_MD_BASE + 23)
10322 #define OPTION_MFENCE_AS_LOCK_ADD (OPTION_MD_BASE + 24)
10323
10324 struct option md_longopts[] =
10325 {
10326   {"32", no_argument, NULL, OPTION_32},
10327 #if (defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) \
10328      || defined (TE_PE) || defined (TE_PEP) || defined (OBJ_MACH_O))
10329   {"64", no_argument, NULL, OPTION_64},
10330 #endif
10331 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
10332   {"x32", no_argument, NULL, OPTION_X32},
10333   {"mshared", no_argument, NULL, OPTION_MSHARED},
10334 #endif
10335   {"divide", no_argument, NULL, OPTION_DIVIDE},
10336   {"march", required_argument, NULL, OPTION_MARCH},
10337   {"mtune", required_argument, NULL, OPTION_MTUNE},
10338   {"mmnemonic", required_argument, NULL, OPTION_MMNEMONIC},
10339   {"msyntax", required_argument, NULL, OPTION_MSYNTAX},
10340   {"mindex-reg", no_argument, NULL, OPTION_MINDEX_REG},
10341   {"mnaked-reg", no_argument, NULL, OPTION_MNAKED_REG},
10342   {"msse2avx", no_argument, NULL, OPTION_MSSE2AVX},
10343   {"msse-check", required_argument, NULL, OPTION_MSSE_CHECK},
10344   {"moperand-check", required_argument, NULL, OPTION_MOPERAND_CHECK},
10345   {"mavxscalar", required_argument, NULL, OPTION_MAVXSCALAR},
10346   {"madd-bnd-prefix", no_argument, NULL, OPTION_MADD_BND_PREFIX},
10347   {"mevexlig", required_argument, NULL, OPTION_MEVEXLIG},
10348   {"mevexwig", required_argument, NULL, OPTION_MEVEXWIG},
10349 # if defined (TE_PE) || defined (TE_PEP)
10350   {"mbig-obj", no_argument, NULL, OPTION_MBIG_OBJ},
10351 #endif
10352   {"momit-lock-prefix", required_argument, NULL, OPTION_MOMIT_LOCK_PREFIX},
10353   {"mfence-as-lock-add", required_argument, NULL, OPTION_MFENCE_AS_LOCK_ADD},
10354   {"mrelax-relocations", required_argument, NULL, OPTION_MRELAX_RELOCATIONS},
10355   {"mevexrcig", required_argument, NULL, OPTION_MEVEXRCIG},
10356   {"mamd64", no_argument, NULL, OPTION_MAMD64},
10357   {"mintel64", no_argument, NULL, OPTION_MINTEL64},
10358   {NULL, no_argument, NULL, 0}
10359 };
10360 size_t md_longopts_size = sizeof (md_longopts);
10361
10362 int
10363 md_parse_option (int c, const char *arg)
10364 {
10365   unsigned int j;
10366   char *arch, *next, *saved;
10367
10368   switch (c)
10369     {
10370     case 'n':
10371       optimize_align_code = 0;
10372       break;
10373
10374     case 'q':
10375       quiet_warnings = 1;
10376       break;
10377
10378 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
10379       /* -Qy, -Qn: SVR4 arguments controlling whether a .comment section
10380          should be emitted or not.  FIXME: Not implemented.  */
10381     case 'Q':
10382       break;
10383
10384       /* -V: SVR4 argument to print version ID.  */
10385     case 'V':
10386       print_version_id ();
10387       break;
10388
10389       /* -k: Ignore for FreeBSD compatibility.  */
10390     case 'k':
10391       break;
10392
10393     case 's':
10394       /* -s: On i386 Solaris, this tells the native assembler to use
10395          .stab instead of .stab.excl.  We always use .stab anyhow.  */
10396       break;
10397
10398     case OPTION_MSHARED:
10399       shared = 1;
10400       break;
10401 #endif
10402 #if (defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) \
10403      || defined (TE_PE) || defined (TE_PEP) || defined (OBJ_MACH_O))
10404     case OPTION_64:
10405       {
10406         const char **list, **l;
10407
10408         list = bfd_target_list ();
10409         for (l = list; *l != NULL; l++)
10410           if (CONST_STRNEQ (*l, "elf64-x86-64")
10411               || strcmp (*l, "coff-x86-64") == 0
10412               || strcmp (*l, "pe-x86-64") == 0
10413               || strcmp (*l, "pei-x86-64") == 0
10414               || strcmp (*l, "mach-o-x86-64") == 0)
10415             {
10416               default_arch = "x86_64";
10417               break;
10418             }
10419         if (*l == NULL)
10420           as_fatal (_("no compiled in support for x86_64"));
10421         free (list);
10422       }
10423       break;
10424 #endif
10425
10426 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
10427     case OPTION_X32:
10428       if (IS_ELF)
10429         {
10430           const char **list, **l;
10431
10432           list = bfd_target_list ();
10433           for (l = list; *l != NULL; l++)
10434             if (CONST_STRNEQ (*l, "elf32-x86-64"))
10435               {
10436                 default_arch = "x86_64:32";
10437                 break;
10438               }
10439           if (*l == NULL)
10440             as_fatal (_("no compiled in support for 32bit x86_64"));
10441           free (list);
10442         }
10443       else
10444         as_fatal (_("32bit x86_64 is only supported for ELF"));
10445       break;
10446 #endif
10447
10448     case OPTION_32:
10449       default_arch = "i386";
10450       break;
10451
10452     case OPTION_DIVIDE:
10453 #ifdef SVR4_COMMENT_CHARS
10454       {
10455         char *n, *t;
10456         const char *s;
10457
10458         n = XNEWVEC (char, strlen (i386_comment_chars) + 1);
10459         t = n;
10460         for (s = i386_comment_chars; *s != '\0'; s++)
10461           if (*s != '/')
10462             *t++ = *s;
10463         *t = '\0';
10464         i386_comment_chars = n;
10465       }
10466 #endif
10467       break;
10468
10469     case OPTION_MARCH:
10470       saved = xstrdup (arg);
10471       arch = saved;
10472       /* Allow -march=+nosse.  */
10473       if (*arch == '+')
10474         arch++;
10475       do
10476         {
10477           if (*arch == '.')
10478             as_fatal (_("invalid -march= option: `%s'"), arg);
10479           next = strchr (arch, '+');
10480           if (next)
10481             *next++ = '\0';
10482           for (j = 0; j < ARRAY_SIZE (cpu_arch); j++)
10483             {
10484               if (strcmp (arch, cpu_arch [j].name) == 0)
10485                 {
10486                   /* Processor.  */
10487                   if (! cpu_arch[j].flags.bitfield.cpui386)
10488                     continue;
10489
10490                   cpu_arch_name = cpu_arch[j].name;
10491                   cpu_sub_arch_name = NULL;
10492                   cpu_arch_flags = cpu_arch[j].flags;
10493                   cpu_arch_isa = cpu_arch[j].type;
10494                   cpu_arch_isa_flags = cpu_arch[j].flags;
10495                   if (!cpu_arch_tune_set)
10496                     {
10497                       cpu_arch_tune = cpu_arch_isa;
10498                       cpu_arch_tune_flags = cpu_arch_isa_flags;
10499                     }
10500                   break;
10501                 }
10502               else if (*cpu_arch [j].name == '.'
10503                        && strcmp (arch, cpu_arch [j].name + 1) == 0)
10504                 {
10505                   /* ISA extension.  */
10506                   i386_cpu_flags flags;
10507
10508                   flags = cpu_flags_or (cpu_arch_flags,
10509                                         cpu_arch[j].flags);
10510
10511                   if (!cpu_flags_equal (&flags, &cpu_arch_flags))
10512                     {
10513                       if (cpu_sub_arch_name)
10514                         {
10515                           char *name = cpu_sub_arch_name;
10516                           cpu_sub_arch_name = concat (name,
10517                                                       cpu_arch[j].name,
10518                                                       (const char *) NULL);
10519                           free (name);
10520                         }
10521                       else
10522                         cpu_sub_arch_name = xstrdup (cpu_arch[j].name);
10523                       cpu_arch_flags = flags;
10524                       cpu_arch_isa_flags = flags;
10525                     }
10526                   else
10527                     cpu_arch_isa_flags
10528                       = cpu_flags_or (cpu_arch_isa_flags,
10529                                       cpu_arch[j].flags);
10530                   break;
10531                 }
10532             }
10533
10534           if (j >= ARRAY_SIZE (cpu_arch))
10535             {
10536               /* Disable an ISA extension.  */
10537               for (j = 0; j < ARRAY_SIZE (cpu_noarch); j++)
10538                 if (strcmp (arch, cpu_noarch [j].name) == 0)
10539                   {
10540                     i386_cpu_flags flags;
10541
10542                     flags = cpu_flags_and_not (cpu_arch_flags,
10543                                                cpu_noarch[j].flags);
10544                     if (!cpu_flags_equal (&flags, &cpu_arch_flags))
10545                       {
10546                         if (cpu_sub_arch_name)
10547                           {
10548                             char *name = cpu_sub_arch_name;
10549                             cpu_sub_arch_name = concat (arch,
10550                                                         (const char *) NULL);
10551                             free (name);
10552                           }
10553                         else
10554                           cpu_sub_arch_name = xstrdup (arch);
10555                         cpu_arch_flags = flags;
10556                         cpu_arch_isa_flags = flags;
10557                       }
10558                     break;
10559                   }
10560
10561               if (j >= ARRAY_SIZE (cpu_noarch))
10562                 j = ARRAY_SIZE (cpu_arch);
10563             }
10564
10565           if (j >= ARRAY_SIZE (cpu_arch))
10566             as_fatal (_("invalid -march= option: `%s'"), arg);
10567
10568           arch = next;
10569         }
10570       while (next != NULL);
10571       free (saved);
10572       break;
10573
10574     case OPTION_MTUNE:
10575       if (*arg == '.')
10576         as_fatal (_("invalid -mtune= option: `%s'"), arg);
10577       for (j = 0; j < ARRAY_SIZE (cpu_arch); j++)
10578         {
10579           if (strcmp (arg, cpu_arch [j].name) == 0)
10580             {
10581               cpu_arch_tune_set = 1;
10582               cpu_arch_tune = cpu_arch [j].type;
10583               cpu_arch_tune_flags = cpu_arch[j].flags;
10584               break;
10585             }
10586         }
10587       if (j >= ARRAY_SIZE (cpu_arch))
10588         as_fatal (_("invalid -mtune= option: `%s'"), arg);
10589       break;
10590
10591     case OPTION_MMNEMONIC:
10592       if (strcasecmp (arg, "att") == 0)
10593         intel_mnemonic = 0;
10594       else if (strcasecmp (arg, "intel") == 0)
10595         intel_mnemonic = 1;
10596       else
10597         as_fatal (_("invalid -mmnemonic= option: `%s'"), arg);
10598       break;
10599
10600     case OPTION_MSYNTAX:
10601       if (strcasecmp (arg, "att") == 0)
10602         intel_syntax = 0;
10603       else if (strcasecmp (arg, "intel") == 0)
10604         intel_syntax = 1;
10605       else
10606         as_fatal (_("invalid -msyntax= option: `%s'"), arg);
10607       break;
10608
10609     case OPTION_MINDEX_REG:
10610       allow_index_reg = 1;
10611       break;
10612
10613     case OPTION_MNAKED_REG:
10614       allow_naked_reg = 1;
10615       break;
10616
10617     case OPTION_MSSE2AVX:
10618       sse2avx = 1;
10619       break;
10620
10621     case OPTION_MSSE_CHECK:
10622       if (strcasecmp (arg, "error") == 0)
10623         sse_check = check_error;
10624       else if (strcasecmp (arg, "warning") == 0)
10625         sse_check = check_warning;
10626       else if (strcasecmp (arg, "none") == 0)
10627         sse_check = check_none;
10628       else
10629         as_fatal (_("invalid -msse-check= option: `%s'"), arg);
10630       break;
10631
10632     case OPTION_MOPERAND_CHECK:
10633       if (strcasecmp (arg, "error") == 0)
10634         operand_check = check_error;
10635       else if (strcasecmp (arg, "warning") == 0)
10636         operand_check = check_warning;
10637       else if (strcasecmp (arg, "none") == 0)
10638         operand_check = check_none;
10639       else
10640         as_fatal (_("invalid -moperand-check= option: `%s'"), arg);
10641       break;
10642
10643     case OPTION_MAVXSCALAR:
10644       if (strcasecmp (arg, "128") == 0)
10645         avxscalar = vex128;
10646       else if (strcasecmp (arg, "256") == 0)
10647         avxscalar = vex256;
10648       else
10649         as_fatal (_("invalid -mavxscalar= option: `%s'"), arg);
10650       break;
10651
10652     case OPTION_MADD_BND_PREFIX:
10653       add_bnd_prefix = 1;
10654       break;
10655
10656     case OPTION_MEVEXLIG:
10657       if (strcmp (arg, "128") == 0)
10658         evexlig = evexl128;
10659       else if (strcmp (arg, "256") == 0)
10660         evexlig = evexl256;
10661       else  if (strcmp (arg, "512") == 0)
10662         evexlig = evexl512;
10663       else
10664         as_fatal (_("invalid -mevexlig= option: `%s'"), arg);
10665       break;
10666
10667     case OPTION_MEVEXRCIG:
10668       if (strcmp (arg, "rne") == 0)
10669         evexrcig = rne;
10670       else if (strcmp (arg, "rd") == 0)
10671         evexrcig = rd;
10672       else if (strcmp (arg, "ru") == 0)
10673         evexrcig = ru;
10674       else if (strcmp (arg, "rz") == 0)
10675         evexrcig = rz;
10676       else
10677         as_fatal (_("invalid -mevexrcig= option: `%s'"), arg);
10678       break;
10679
10680     case OPTION_MEVEXWIG:
10681       if (strcmp (arg, "0") == 0)
10682         evexwig = evexw0;
10683       else if (strcmp (arg, "1") == 0)
10684         evexwig = evexw1;
10685       else
10686         as_fatal (_("invalid -mevexwig= option: `%s'"), arg);
10687       break;
10688
10689 # if defined (TE_PE) || defined (TE_PEP)
10690     case OPTION_MBIG_OBJ:
10691       use_big_obj = 1;
10692       break;
10693 #endif
10694
10695     case OPTION_MOMIT_LOCK_PREFIX:
10696       if (strcasecmp (arg, "yes") == 0)
10697         omit_lock_prefix = 1;
10698       else if (strcasecmp (arg, "no") == 0)
10699         omit_lock_prefix = 0;
10700       else
10701         as_fatal (_("invalid -momit-lock-prefix= option: `%s'"), arg);
10702       break;
10703
10704     case OPTION_MFENCE_AS_LOCK_ADD:
10705       if (strcasecmp (arg, "yes") == 0)
10706         avoid_fence = 1;
10707       else if (strcasecmp (arg, "no") == 0)
10708         avoid_fence = 0;
10709       else
10710         as_fatal (_("invalid -mfence-as-lock-add= option: `%s'"), arg);
10711       break;
10712
10713     case OPTION_MRELAX_RELOCATIONS:
10714       if (strcasecmp (arg, "yes") == 0)
10715         generate_relax_relocations = 1;
10716       else if (strcasecmp (arg, "no") == 0)
10717         generate_relax_relocations = 0;
10718       else
10719         as_fatal (_("invalid -mrelax-relocations= option: `%s'"), arg);
10720       break;
10721
10722     case OPTION_MAMD64:
10723       intel64 = 0;
10724       break;
10725
10726     case OPTION_MINTEL64:
10727       intel64 = 1;
10728       break;
10729
10730     case 'O':
10731       if (arg == NULL)
10732         {
10733           optimize = 1;
10734           /* Turn off -Os.  */
10735           optimize_for_space = 0;
10736         }
10737       else if (*arg == 's')
10738         {
10739           optimize_for_space = 1;
10740           /* Turn on all encoding optimizations.  */
10741           optimize = -1;
10742         }
10743       else
10744         {
10745           optimize = atoi (arg);
10746           /* Turn off -Os.  */
10747           optimize_for_space = 0;
10748         }
10749       break;
10750
10751     default:
10752       return 0;
10753     }
10754   return 1;
10755 }
10756
10757 #define MESSAGE_TEMPLATE \
10758 "                                                                                "
10759
10760 static char *
10761 output_message (FILE *stream, char *p, char *message, char *start,
10762                 int *left_p, const char *name, int len)
10763 {
10764   int size = sizeof (MESSAGE_TEMPLATE);
10765   int left = *left_p;
10766
10767   /* Reserve 2 spaces for ", " or ",\0" */
10768   left -= len + 2;
10769
10770   /* Check if there is any room.  */
10771   if (left >= 0)
10772     {
10773       if (p != start)
10774         {
10775           *p++ = ',';
10776           *p++ = ' ';
10777         }
10778       p = mempcpy (p, name, len);
10779     }
10780   else
10781     {
10782       /* Output the current message now and start a new one.  */
10783       *p++ = ',';
10784       *p = '\0';
10785       fprintf (stream, "%s\n", message);
10786       p = start;
10787       left = size - (start - message) - len - 2;
10788
10789       gas_assert (left >= 0);
10790
10791       p = mempcpy (p, name, len);
10792     }
10793
10794   *left_p = left;
10795   return p;
10796 }
10797
10798 static void
10799 show_arch (FILE *stream, int ext, int check)
10800 {
10801   static char message[] = MESSAGE_TEMPLATE;
10802   char *start = message + 27;
10803   char *p;
10804   int size = sizeof (MESSAGE_TEMPLATE);
10805   int left;
10806   const char *name;
10807   int len;
10808   unsigned int j;
10809
10810   p = start;
10811   left = size - (start - message);
10812   for (j = 0; j < ARRAY_SIZE (cpu_arch); j++)
10813     {
10814       /* Should it be skipped?  */
10815       if (cpu_arch [j].skip)
10816         continue;
10817
10818       name = cpu_arch [j].name;
10819       len = cpu_arch [j].len;
10820       if (*name == '.')
10821         {
10822           /* It is an extension.  Skip if we aren't asked to show it.  */
10823           if (ext)
10824             {
10825               name++;
10826               len--;
10827             }
10828           else
10829             continue;
10830         }
10831       else if (ext)
10832         {
10833           /* It is an processor.  Skip if we show only extension.  */
10834           continue;
10835         }
10836       else if (check && ! cpu_arch[j].flags.bitfield.cpui386)
10837         {
10838           /* It is an impossible processor - skip.  */
10839           continue;
10840         }
10841
10842       p = output_message (stream, p, message, start, &left, name, len);
10843     }
10844
10845   /* Display disabled extensions.  */
10846   if (ext)
10847     for (j = 0; j < ARRAY_SIZE (cpu_noarch); j++)
10848       {
10849         name = cpu_noarch [j].name;
10850         len = cpu_noarch [j].len;
10851         p = output_message (stream, p, message, start, &left, name,
10852                             len);
10853       }
10854
10855   *p = '\0';
10856   fprintf (stream, "%s\n", message);
10857 }
10858
10859 void
10860 md_show_usage (FILE *stream)
10861 {
10862 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
10863   fprintf (stream, _("\
10864   -Q                      ignored\n\
10865   -V                      print assembler version number\n\
10866   -k                      ignored\n"));
10867 #endif
10868   fprintf (stream, _("\
10869   -n                      Do not optimize code alignment\n\
10870   -q                      quieten some warnings\n"));
10871 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
10872   fprintf (stream, _("\
10873   -s                      ignored\n"));
10874 #endif
10875 #if (defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) \
10876      || defined (TE_PE) || defined (TE_PEP))
10877   fprintf (stream, _("\
10878   --32/--64/--x32         generate 32bit/64bit/x32 code\n"));
10879 #endif
10880 #ifdef SVR4_COMMENT_CHARS
10881   fprintf (stream, _("\
10882   --divide                do not treat `/' as a comment character\n"));
10883 #else
10884   fprintf (stream, _("\
10885   --divide                ignored\n"));
10886 #endif
10887   fprintf (stream, _("\
10888   -march=CPU[,+EXTENSION...]\n\
10889                           generate code for CPU and EXTENSION, CPU is one of:\n"));
10890   show_arch (stream, 0, 1);
10891   fprintf (stream, _("\
10892                           EXTENSION is combination of:\n"));
10893   show_arch (stream, 1, 0);
10894   fprintf (stream, _("\
10895   -mtune=CPU              optimize for CPU, CPU is one of:\n"));
10896   show_arch (stream, 0, 0);
10897   fprintf (stream, _("\
10898   -msse2avx               encode SSE instructions with VEX prefix\n"));
10899   fprintf (stream, _("\
10900   -msse-check=[none|error|warning]\n\
10901                           check SSE instructions\n"));
10902   fprintf (stream, _("\
10903   -moperand-check=[none|error|warning]\n\
10904                           check operand combinations for validity\n"));
10905   fprintf (stream, _("\
10906   -mavxscalar=[128|256]   encode scalar AVX instructions with specific vector\n\
10907                            length\n"));
10908   fprintf (stream, _("\
10909   -mevexlig=[128|256|512] encode scalar EVEX instructions with specific vector\n\
10910                            length\n"));
10911   fprintf (stream, _("\
10912   -mevexwig=[0|1]         encode EVEX instructions with specific EVEX.W value\n\
10913                            for EVEX.W bit ignored instructions\n"));
10914   fprintf (stream, _("\
10915   -mevexrcig=[rne|rd|ru|rz]\n\
10916                           encode EVEX instructions with specific EVEX.RC value\n\
10917                            for SAE-only ignored instructions\n"));
10918   fprintf (stream, _("\
10919   -mmnemonic=[att|intel]  use AT&T/Intel mnemonic\n"));
10920   fprintf (stream, _("\
10921   -msyntax=[att|intel]    use AT&T/Intel syntax\n"));
10922   fprintf (stream, _("\
10923   -mindex-reg             support pseudo index registers\n"));
10924   fprintf (stream, _("\
10925   -mnaked-reg             don't require `%%' prefix for registers\n"));
10926   fprintf (stream, _("\
10927   -madd-bnd-prefix        add BND prefix for all valid branches\n"));
10928   fprintf (stream, _("\
10929   -mshared                disable branch optimization for shared code\n"));
10930 # if defined (TE_PE) || defined (TE_PEP)
10931   fprintf (stream, _("\
10932   -mbig-obj               generate big object files\n"));
10933 #endif
10934   fprintf (stream, _("\
10935   -momit-lock-prefix=[no|yes]\n\
10936                           strip all lock prefixes\n"));
10937   fprintf (stream, _("\
10938   -mfence-as-lock-add=[no|yes]\n\
10939                           encode lfence, mfence and sfence as\n\
10940                            lock addl $0x0, (%%{re}sp)\n"));
10941   fprintf (stream, _("\
10942   -mrelax-relocations=[no|yes]\n\
10943                           generate relax relocations\n"));
10944   fprintf (stream, _("\
10945   -mamd64                 accept only AMD64 ISA\n"));
10946   fprintf (stream, _("\
10947   -mintel64               accept only Intel64 ISA\n"));
10948 }
10949
10950 #if ((defined (OBJ_MAYBE_COFF) && defined (OBJ_MAYBE_AOUT)) \
10951      || defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF) \
10952      || defined (TE_PE) || defined (TE_PEP) || defined (OBJ_MACH_O))
10953
10954 /* Pick the target format to use.  */
10955
10956 const char *
10957 i386_target_format (void)
10958 {
10959   if (!strncmp (default_arch, "x86_64", 6))
10960     {
10961       update_code_flag (CODE_64BIT, 1);
10962       if (default_arch[6] == '\0')
10963         x86_elf_abi = X86_64_ABI;
10964       else
10965         x86_elf_abi = X86_64_X32_ABI;
10966     }
10967   else if (!strcmp (default_arch, "i386"))
10968     update_code_flag (CODE_32BIT, 1);
10969   else if (!strcmp (default_arch, "iamcu"))
10970     {
10971       update_code_flag (CODE_32BIT, 1);
10972       if (cpu_arch_isa == PROCESSOR_UNKNOWN)
10973         {
10974           static const i386_cpu_flags iamcu_flags = CPU_IAMCU_FLAGS;
10975           cpu_arch_name = "iamcu";
10976           cpu_sub_arch_name = NULL;
10977           cpu_arch_flags = iamcu_flags;
10978           cpu_arch_isa = PROCESSOR_IAMCU;
10979           cpu_arch_isa_flags = iamcu_flags;
10980           if (!cpu_arch_tune_set)
10981             {
10982               cpu_arch_tune = cpu_arch_isa;
10983               cpu_arch_tune_flags = cpu_arch_isa_flags;
10984             }
10985         }
10986       else if (cpu_arch_isa != PROCESSOR_IAMCU)
10987         as_fatal (_("Intel MCU doesn't support `%s' architecture"),
10988                   cpu_arch_name);
10989     }
10990   else
10991     as_fatal (_("unknown architecture"));
10992
10993   if (cpu_flags_all_zero (&cpu_arch_isa_flags))
10994     cpu_arch_isa_flags = cpu_arch[flag_code == CODE_64BIT].flags;
10995   if (cpu_flags_all_zero (&cpu_arch_tune_flags))
10996     cpu_arch_tune_flags = cpu_arch[flag_code == CODE_64BIT].flags;
10997
10998   switch (OUTPUT_FLAVOR)
10999     {
11000 #if defined (OBJ_MAYBE_AOUT) || defined (OBJ_AOUT)
11001     case bfd_target_aout_flavour:
11002       return AOUT_TARGET_FORMAT;
11003 #endif
11004 #if defined (OBJ_MAYBE_COFF) || defined (OBJ_COFF)
11005 # if defined (TE_PE) || defined (TE_PEP)
11006     case bfd_target_coff_flavour:
11007       if (flag_code == CODE_64BIT)
11008         return use_big_obj ? "pe-bigobj-x86-64" : "pe-x86-64";
11009       else
11010         return "pe-i386";
11011 # elif defined (TE_GO32)
11012     case bfd_target_coff_flavour:
11013       return "coff-go32";
11014 # else
11015     case bfd_target_coff_flavour:
11016       return "coff-i386";
11017 # endif
11018 #endif
11019 #if defined (OBJ_MAYBE_ELF) || defined (OBJ_ELF)
11020     case bfd_target_elf_flavour:
11021       {
11022         const char *format;
11023
11024         switch (x86_elf_abi)
11025           {
11026           default:
11027             format = ELF_TARGET_FORMAT;
11028             break;
11029           case X86_64_ABI:
11030             use_rela_relocations = 1;
11031             object_64bit = 1;
11032             format = ELF_TARGET_FORMAT64;
11033             break;
11034           case X86_64_X32_ABI:
11035             use_rela_relocations = 1;
11036             object_64bit = 1;
11037             disallow_64bit_reloc = 1;
11038             format = ELF_TARGET_FORMAT32;
11039             break;
11040           }
11041         if (cpu_arch_isa == PROCESSOR_L1OM)
11042           {
11043             if (x86_elf_abi != X86_64_ABI)
11044               as_fatal (_("Intel L1OM is 64bit only"));
11045             return ELF_TARGET_L1OM_FORMAT;
11046           }
11047         else if (cpu_arch_isa == PROCESSOR_K1OM)
11048           {
11049             if (x86_elf_abi != X86_64_ABI)
11050               as_fatal (_("Intel K1OM is 64bit only"));
11051             return ELF_TARGET_K1OM_FORMAT;
11052           }
11053         else if (cpu_arch_isa == PROCESSOR_IAMCU)
11054           {
11055             if (x86_elf_abi != I386_ABI)
11056               as_fatal (_("Intel MCU is 32bit only"));
11057             return ELF_TARGET_IAMCU_FORMAT;
11058           }
11059         else
11060           return format;
11061       }
11062 #endif
11063 #if defined (OBJ_MACH_O)
11064     case bfd_target_mach_o_flavour:
11065       if (flag_code == CODE_64BIT)
11066         {
11067           use_rela_relocations = 1;
11068           object_64bit = 1;
11069           return "mach-o-x86-64";
11070         }
11071       else
11072         return "mach-o-i386";
11073 #endif
11074     default:
11075       abort ();
11076       return NULL;
11077     }
11078 }
11079
11080 #endif /* OBJ_MAYBE_ more than one  */
11081 \f
11082 symbolS *
11083 md_undefined_symbol (char *name)
11084 {
11085   if (name[0] == GLOBAL_OFFSET_TABLE_NAME[0]
11086       && name[1] == GLOBAL_OFFSET_TABLE_NAME[1]
11087       && name[2] == GLOBAL_OFFSET_TABLE_NAME[2]
11088       && strcmp (name, GLOBAL_OFFSET_TABLE_NAME) == 0)
11089     {
11090       if (!GOT_symbol)
11091         {
11092           if (symbol_find (name))
11093             as_bad (_("GOT already in symbol table"));
11094           GOT_symbol = symbol_new (name, undefined_section,
11095                                    (valueT) 0, &zero_address_frag);
11096         };
11097       return GOT_symbol;
11098     }
11099   return 0;
11100 }
11101
11102 /* Round up a section size to the appropriate boundary.  */
11103
11104 valueT
11105 md_section_align (segT segment ATTRIBUTE_UNUSED, valueT size)
11106 {
11107 #if (defined (OBJ_AOUT) || defined (OBJ_MAYBE_AOUT))
11108   if (OUTPUT_FLAVOR == bfd_target_aout_flavour)
11109     {
11110       /* For a.out, force the section size to be aligned.  If we don't do
11111          this, BFD will align it for us, but it will not write out the
11112          final bytes of the section.  This may be a bug in BFD, but it is
11113          easier to fix it here since that is how the other a.out targets
11114          work.  */
11115       int align;
11116
11117       align = bfd_get_section_alignment (stdoutput, segment);
11118       size = ((size + (1 << align) - 1) & (-((valueT) 1 << align)));
11119     }
11120 #endif
11121
11122   return size;
11123 }
11124
11125 /* On the i386, PC-relative offsets are relative to the start of the
11126    next instruction.  That is, the address of the offset, plus its
11127    size, since the offset is always the last part of the insn.  */
11128
11129 long
11130 md_pcrel_from (fixS *fixP)
11131 {
11132   return fixP->fx_size + fixP->fx_where + fixP->fx_frag->fr_address;
11133 }
11134
11135 #ifndef I386COFF
11136
11137 static void
11138 s_bss (int ignore ATTRIBUTE_UNUSED)
11139 {
11140   int temp;
11141
11142 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
11143   if (IS_ELF)
11144     obj_elf_section_change_hook ();
11145 #endif
11146   temp = get_absolute_expression ();
11147   subseg_set (bss_section, (subsegT) temp);
11148   demand_empty_rest_of_line ();
11149 }
11150
11151 #endif
11152
11153 void
11154 i386_validate_fix (fixS *fixp)
11155 {
11156   if (fixp->fx_subsy)
11157     {
11158       if (fixp->fx_subsy == GOT_symbol)
11159         {
11160           if (fixp->fx_r_type == BFD_RELOC_32_PCREL)
11161             {
11162               if (!object_64bit)
11163                 abort ();
11164 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
11165               if (fixp->fx_tcbit2)
11166                 fixp->fx_r_type = (fixp->fx_tcbit
11167                                    ? BFD_RELOC_X86_64_REX_GOTPCRELX
11168                                    : BFD_RELOC_X86_64_GOTPCRELX);
11169               else
11170 #endif
11171                 fixp->fx_r_type = BFD_RELOC_X86_64_GOTPCREL;
11172             }
11173           else
11174             {
11175               if (!object_64bit)
11176                 fixp->fx_r_type = BFD_RELOC_386_GOTOFF;
11177               else
11178                 fixp->fx_r_type = BFD_RELOC_X86_64_GOTOFF64;
11179             }
11180           fixp->fx_subsy = 0;
11181         }
11182     }
11183 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
11184   else if (!object_64bit)
11185     {
11186       if (fixp->fx_r_type == BFD_RELOC_386_GOT32
11187           && fixp->fx_tcbit2)
11188         fixp->fx_r_type = BFD_RELOC_386_GOT32X;
11189     }
11190 #endif
11191 }
11192
11193 arelent *
11194 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
11195 {
11196   arelent *rel;
11197   bfd_reloc_code_real_type code;
11198
11199   switch (fixp->fx_r_type)
11200     {
11201 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
11202     case BFD_RELOC_SIZE32:
11203     case BFD_RELOC_SIZE64:
11204       if (S_IS_DEFINED (fixp->fx_addsy)
11205           && !S_IS_EXTERNAL (fixp->fx_addsy))
11206         {
11207           /* Resolve size relocation against local symbol to size of
11208              the symbol plus addend.  */
11209           valueT value = S_GET_SIZE (fixp->fx_addsy) + fixp->fx_offset;
11210           if (fixp->fx_r_type == BFD_RELOC_SIZE32
11211               && !fits_in_unsigned_long (value))
11212             as_bad_where (fixp->fx_file, fixp->fx_line,
11213                           _("symbol size computation overflow"));
11214           fixp->fx_addsy = NULL;
11215           fixp->fx_subsy = NULL;
11216           md_apply_fix (fixp, (valueT *) &value, NULL);
11217           return NULL;
11218         }
11219 #endif
11220       /* Fall through.  */
11221
11222     case BFD_RELOC_X86_64_PLT32:
11223     case BFD_RELOC_X86_64_GOT32:
11224     case BFD_RELOC_X86_64_GOTPCREL:
11225     case BFD_RELOC_X86_64_GOTPCRELX:
11226     case BFD_RELOC_X86_64_REX_GOTPCRELX:
11227     case BFD_RELOC_386_PLT32:
11228     case BFD_RELOC_386_GOT32:
11229     case BFD_RELOC_386_GOT32X:
11230     case BFD_RELOC_386_GOTOFF:
11231     case BFD_RELOC_386_GOTPC:
11232     case BFD_RELOC_386_TLS_GD:
11233     case BFD_RELOC_386_TLS_LDM:
11234     case BFD_RELOC_386_TLS_LDO_32:
11235     case BFD_RELOC_386_TLS_IE_32:
11236     case BFD_RELOC_386_TLS_IE:
11237     case BFD_RELOC_386_TLS_GOTIE:
11238     case BFD_RELOC_386_TLS_LE_32:
11239     case BFD_RELOC_386_TLS_LE:
11240     case BFD_RELOC_386_TLS_GOTDESC:
11241     case BFD_RELOC_386_TLS_DESC_CALL:
11242     case BFD_RELOC_X86_64_TLSGD:
11243     case BFD_RELOC_X86_64_TLSLD:
11244     case BFD_RELOC_X86_64_DTPOFF32:
11245     case BFD_RELOC_X86_64_DTPOFF64:
11246     case BFD_RELOC_X86_64_GOTTPOFF:
11247     case BFD_RELOC_X86_64_TPOFF32:
11248     case BFD_RELOC_X86_64_TPOFF64:
11249     case BFD_RELOC_X86_64_GOTOFF64:
11250     case BFD_RELOC_X86_64_GOTPC32:
11251     case BFD_RELOC_X86_64_GOT64:
11252     case BFD_RELOC_X86_64_GOTPCREL64:
11253     case BFD_RELOC_X86_64_GOTPC64:
11254     case BFD_RELOC_X86_64_GOTPLT64:
11255     case BFD_RELOC_X86_64_PLTOFF64:
11256     case BFD_RELOC_X86_64_GOTPC32_TLSDESC:
11257     case BFD_RELOC_X86_64_TLSDESC_CALL:
11258     case BFD_RELOC_RVA:
11259     case BFD_RELOC_VTABLE_ENTRY:
11260     case BFD_RELOC_VTABLE_INHERIT:
11261 #ifdef TE_PE
11262     case BFD_RELOC_32_SECREL:
11263 #endif
11264       code = fixp->fx_r_type;
11265       break;
11266     case BFD_RELOC_X86_64_32S:
11267       if (!fixp->fx_pcrel)
11268         {
11269           /* Don't turn BFD_RELOC_X86_64_32S into BFD_RELOC_32.  */
11270           code = fixp->fx_r_type;
11271           break;
11272         }
11273       /* Fall through.  */
11274     default:
11275       if (fixp->fx_pcrel)
11276         {
11277           switch (fixp->fx_size)
11278             {
11279             default:
11280               as_bad_where (fixp->fx_file, fixp->fx_line,
11281                             _("can not do %d byte pc-relative relocation"),
11282                             fixp->fx_size);
11283               code = BFD_RELOC_32_PCREL;
11284               break;
11285             case 1: code = BFD_RELOC_8_PCREL;  break;
11286             case 2: code = BFD_RELOC_16_PCREL; break;
11287             case 4: code = BFD_RELOC_32_PCREL; break;
11288 #ifdef BFD64
11289             case 8: code = BFD_RELOC_64_PCREL; break;
11290 #endif
11291             }
11292         }
11293       else
11294         {
11295           switch (fixp->fx_size)
11296             {
11297             default:
11298               as_bad_where (fixp->fx_file, fixp->fx_line,
11299                             _("can not do %d byte relocation"),
11300                             fixp->fx_size);
11301               code = BFD_RELOC_32;
11302               break;
11303             case 1: code = BFD_RELOC_8;  break;
11304             case 2: code = BFD_RELOC_16; break;
11305             case 4: code = BFD_RELOC_32; break;
11306 #ifdef BFD64
11307             case 8: code = BFD_RELOC_64; break;
11308 #endif
11309             }
11310         }
11311       break;
11312     }
11313
11314   if ((code == BFD_RELOC_32
11315        || code == BFD_RELOC_32_PCREL
11316        || code == BFD_RELOC_X86_64_32S)
11317       && GOT_symbol
11318       && fixp->fx_addsy == GOT_symbol)
11319     {
11320       if (!object_64bit)
11321         code = BFD_RELOC_386_GOTPC;
11322       else
11323         code = BFD_RELOC_X86_64_GOTPC32;
11324     }
11325   if ((code == BFD_RELOC_64 || code == BFD_RELOC_64_PCREL)
11326       && GOT_symbol
11327       && fixp->fx_addsy == GOT_symbol)
11328     {
11329       code = BFD_RELOC_X86_64_GOTPC64;
11330     }
11331
11332   rel = XNEW (arelent);
11333   rel->sym_ptr_ptr = XNEW (asymbol *);
11334   *rel->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
11335
11336   rel->address = fixp->fx_frag->fr_address + fixp->fx_where;
11337
11338   if (!use_rela_relocations)
11339     {
11340       /* HACK: Since i386 ELF uses Rel instead of Rela, encode the
11341          vtable entry to be used in the relocation's section offset.  */
11342       if (fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
11343         rel->address = fixp->fx_offset;
11344 #if defined (OBJ_COFF) && defined (TE_PE)
11345       else if (fixp->fx_addsy && S_IS_WEAK (fixp->fx_addsy))
11346         rel->addend = fixp->fx_addnumber - (S_GET_VALUE (fixp->fx_addsy) * 2);
11347       else
11348 #endif
11349       rel->addend = 0;
11350     }
11351   /* Use the rela in 64bit mode.  */
11352   else
11353     {
11354       if (disallow_64bit_reloc)
11355         switch (code)
11356           {
11357           case BFD_RELOC_X86_64_DTPOFF64:
11358           case BFD_RELOC_X86_64_TPOFF64:
11359           case BFD_RELOC_64_PCREL:
11360           case BFD_RELOC_X86_64_GOTOFF64:
11361           case BFD_RELOC_X86_64_GOT64:
11362           case BFD_RELOC_X86_64_GOTPCREL64:
11363           case BFD_RELOC_X86_64_GOTPC64:
11364           case BFD_RELOC_X86_64_GOTPLT64:
11365           case BFD_RELOC_X86_64_PLTOFF64:
11366             as_bad_where (fixp->fx_file, fixp->fx_line,
11367                           _("cannot represent relocation type %s in x32 mode"),
11368                           bfd_get_reloc_code_name (code));
11369             break;
11370           default:
11371             break;
11372           }
11373
11374       if (!fixp->fx_pcrel)
11375         rel->addend = fixp->fx_offset;
11376       else
11377         switch (code)
11378           {
11379           case BFD_RELOC_X86_64_PLT32:
11380           case BFD_RELOC_X86_64_GOT32:
11381           case BFD_RELOC_X86_64_GOTPCREL:
11382           case BFD_RELOC_X86_64_GOTPCRELX:
11383           case BFD_RELOC_X86_64_REX_GOTPCRELX:
11384           case BFD_RELOC_X86_64_TLSGD:
11385           case BFD_RELOC_X86_64_TLSLD:
11386           case BFD_RELOC_X86_64_GOTTPOFF:
11387           case BFD_RELOC_X86_64_GOTPC32_TLSDESC:
11388           case BFD_RELOC_X86_64_TLSDESC_CALL:
11389             rel->addend = fixp->fx_offset - fixp->fx_size;
11390             break;
11391           default:
11392             rel->addend = (section->vma
11393                            - fixp->fx_size
11394                            + fixp->fx_addnumber
11395                            + md_pcrel_from (fixp));
11396             break;
11397           }
11398     }
11399
11400   rel->howto = bfd_reloc_type_lookup (stdoutput, code);
11401   if (rel->howto == NULL)
11402     {
11403       as_bad_where (fixp->fx_file, fixp->fx_line,
11404                     _("cannot represent relocation type %s"),
11405                     bfd_get_reloc_code_name (code));
11406       /* Set howto to a garbage value so that we can keep going.  */
11407       rel->howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_32);
11408       gas_assert (rel->howto != NULL);
11409     }
11410
11411   return rel;
11412 }
11413
11414 #include "tc-i386-intel.c"
11415
11416 void
11417 tc_x86_parse_to_dw2regnum (expressionS *exp)
11418 {
11419   int saved_naked_reg;
11420   char saved_register_dot;
11421
11422   saved_naked_reg = allow_naked_reg;
11423   allow_naked_reg = 1;
11424   saved_register_dot = register_chars['.'];
11425   register_chars['.'] = '.';
11426   allow_pseudo_reg = 1;
11427   expression_and_evaluate (exp);
11428   allow_pseudo_reg = 0;
11429   register_chars['.'] = saved_register_dot;
11430   allow_naked_reg = saved_naked_reg;
11431
11432   if (exp->X_op == O_register && exp->X_add_number >= 0)
11433     {
11434       if ((addressT) exp->X_add_number < i386_regtab_size)
11435         {
11436           exp->X_op = O_constant;
11437           exp->X_add_number = i386_regtab[exp->X_add_number]
11438                               .dw2_regnum[flag_code >> 1];
11439         }
11440       else
11441         exp->X_op = O_illegal;
11442     }
11443 }
11444
11445 void
11446 tc_x86_frame_initial_instructions (void)
11447 {
11448   static unsigned int sp_regno[2];
11449
11450   if (!sp_regno[flag_code >> 1])
11451     {
11452       char *saved_input = input_line_pointer;
11453       char sp[][4] = {"esp", "rsp"};
11454       expressionS exp;
11455
11456       input_line_pointer = sp[flag_code >> 1];
11457       tc_x86_parse_to_dw2regnum (&exp);
11458       gas_assert (exp.X_op == O_constant);
11459       sp_regno[flag_code >> 1] = exp.X_add_number;
11460       input_line_pointer = saved_input;
11461     }
11462
11463   cfi_add_CFA_def_cfa (sp_regno[flag_code >> 1], -x86_cie_data_alignment);
11464   cfi_add_CFA_offset (x86_dwarf2_return_column, x86_cie_data_alignment);
11465 }
11466
11467 int
11468 x86_dwarf2_addr_size (void)
11469 {
11470 #if defined (OBJ_MAYBE_ELF) || defined (OBJ_ELF)
11471   if (x86_elf_abi == X86_64_X32_ABI)
11472     return 4;
11473 #endif
11474   return bfd_arch_bits_per_address (stdoutput) / 8;
11475 }
11476
11477 int
11478 i386_elf_section_type (const char *str, size_t len)
11479 {
11480   if (flag_code == CODE_64BIT
11481       && len == sizeof ("unwind") - 1
11482       && strncmp (str, "unwind", 6) == 0)
11483     return SHT_X86_64_UNWIND;
11484
11485   return -1;
11486 }
11487
11488 #ifdef TE_SOLARIS
11489 void
11490 i386_solaris_fix_up_eh_frame (segT sec)
11491 {
11492   if (flag_code == CODE_64BIT)
11493     elf_section_type (sec) = SHT_X86_64_UNWIND;
11494 }
11495 #endif
11496
11497 #ifdef TE_PE
11498 void
11499 tc_pe_dwarf2_emit_offset (symbolS *symbol, unsigned int size)
11500 {
11501   expressionS exp;
11502
11503   exp.X_op = O_secrel;
11504   exp.X_add_symbol = symbol;
11505   exp.X_add_number = 0;
11506   emit_expr (&exp, size);
11507 }
11508 #endif
11509
11510 #if defined (OBJ_ELF) || defined (OBJ_MAYBE_ELF)
11511 /* For ELF on x86-64, add support for SHF_X86_64_LARGE.  */
11512
11513 bfd_vma
11514 x86_64_section_letter (int letter, const char **ptr_msg)
11515 {
11516   if (flag_code == CODE_64BIT)
11517     {
11518       if (letter == 'l')
11519         return SHF_X86_64_LARGE;
11520
11521       *ptr_msg = _("bad .section directive: want a,l,w,x,M,S,G,T in string");
11522     }
11523   else
11524     *ptr_msg = _("bad .section directive: want a,w,x,M,S,G,T in string");
11525   return -1;
11526 }
11527
11528 bfd_vma
11529 x86_64_section_word (char *str, size_t len)
11530 {
11531   if (len == 5 && flag_code == CODE_64BIT && CONST_STRNEQ (str, "large"))
11532     return SHF_X86_64_LARGE;
11533
11534   return -1;
11535 }
11536
11537 static void
11538 handle_large_common (int small ATTRIBUTE_UNUSED)
11539 {
11540   if (flag_code != CODE_64BIT)
11541     {
11542       s_comm_internal (0, elf_common_parse);
11543       as_warn (_(".largecomm supported only in 64bit mode, producing .comm"));
11544     }
11545   else
11546     {
11547       static segT lbss_section;
11548       asection *saved_com_section_ptr = elf_com_section_ptr;
11549       asection *saved_bss_section = bss_section;
11550
11551       if (lbss_section == NULL)
11552         {
11553           flagword applicable;
11554           segT seg = now_seg;
11555           subsegT subseg = now_subseg;
11556
11557           /* The .lbss section is for local .largecomm symbols.  */
11558           lbss_section = subseg_new (".lbss", 0);
11559           applicable = bfd_applicable_section_flags (stdoutput);
11560           bfd_set_section_flags (stdoutput, lbss_section,
11561                                  applicable & SEC_ALLOC);
11562           seg_info (lbss_section)->bss = 1;
11563
11564           subseg_set (seg, subseg);
11565         }
11566
11567       elf_com_section_ptr = &_bfd_elf_large_com_section;
11568       bss_section = lbss_section;
11569
11570       s_comm_internal (0, elf_common_parse);
11571
11572       elf_com_section_ptr = saved_com_section_ptr;
11573       bss_section = saved_bss_section;
11574     }
11575 }
11576 #endif /* OBJ_ELF || OBJ_MAYBE_ELF */