MPX: Move BND prefix indication from bytecode to iflags
[platform/upstream/nasm.git] / assemble.c
1 /* ----------------------------------------------------------------------- *
2  *
3  *   Copyright 1996-2013 The NASM Authors - All Rights Reserved
4  *   See the file AUTHORS included with the NASM distribution for
5  *   the specific copyright holders.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following
9  *   conditions are met:
10  *
11  *   * Redistributions of source code must retain the above copyright
12  *     notice, this list of conditions and the following disclaimer.
13  *   * Redistributions in binary form must reproduce the above
14  *     copyright notice, this list of conditions and the following
15  *     disclaimer in the documentation and/or other materials provided
16  *     with the distribution.
17  *
18  *     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
19  *     CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
20  *     INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21  *     MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  *     DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23  *     CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  *     SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  *     NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  *     LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  *     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  *     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
29  *     OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30  *     EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * ----------------------------------------------------------------------- */
33
34 /*
35  * assemble.c   code generation for the Netwide Assembler
36  *
37  * the actual codes (C syntax, i.e. octal):
38  * \0            - terminates the code. (Unless it's a literal of course.)
39  * \1..\4        - that many literal bytes follow in the code stream
40  * \5            - add 4 to the primary operand number (b, low octdigit)
41  * \6            - add 4 to the secondary operand number (a, middle octdigit)
42  * \7            - add 4 to both the primary and the secondary operand number
43  * \10..\13      - a literal byte follows in the code stream, to be added
44  *                 to the register value of operand 0..3
45  * \14..\17      - the position of index register operand in MIB (BND insns)
46  * \20..\23      - a byte immediate operand, from operand 0..3
47  * \24..\27      - a zero-extended byte immediate operand, from operand 0..3
48  * \30..\33      - a word immediate operand, from operand 0..3
49  * \34..\37      - select between \3[0-3] and \4[0-3] depending on 16/32 bit
50  *                 assembly mode or the operand-size override on the operand
51  * \40..\43      - a long immediate operand, from operand 0..3
52  * \44..\47      - select between \3[0-3], \4[0-3] and \5[4-7]
53  *                 depending on the address size of the instruction.
54  * \50..\53      - a byte relative operand, from operand 0..3
55  * \54..\57      - a qword immediate operand, from operand 0..3
56  * \60..\63      - a word relative operand, from operand 0..3
57  * \64..\67      - select between \6[0-3] and \7[0-3] depending on 16/32 bit
58  *                 assembly mode or the operand-size override on the operand
59  * \70..\73      - a long relative operand, from operand 0..3
60  * \74..\77      - a word constant, from the _segment_ part of operand 0..3
61  * \1ab          - a ModRM, calculated on EA in operand a, with the spare
62  *                 field the register value of operand b.
63  * \172\ab       - the register number from operand a in bits 7..4, with
64  *                 the 4-bit immediate from operand b in bits 3..0.
65  * \173\xab      - the register number from operand a in bits 7..4, with
66  *                 the value b in bits 3..0.
67  * \174..\177    - the register number from operand 0..3 in bits 7..4, and
68  *                 an arbitrary value in bits 3..0 (assembled as zero.)
69  * \2ab          - a ModRM, calculated on EA in operand a, with the spare
70  *                 field equal to digit b.
71  *
72  * \240..\243    - this instruction uses EVEX rather than REX or VEX/XOP, with the
73  *                 V field taken from operand 0..3.
74  * \250          - this instruction uses EVEX rather than REX or VEX/XOP, with the
75  *                 V field set to 1111b.
76  * EVEX prefixes are followed by the sequence:
77  * \cm\wlp\tup    where cm is:
78  *                  cc 000 0mm
79  *                  c = 2 for EVEX and m is the legacy escape (0f, 0f38, 0f3a)
80  *                and wlp is:
81  *                  00 wwl lpp
82  *                  [l0]  ll = 0 (.128, .lz)
83  *                  [l1]  ll = 1 (.256)
84  *                  [l2]  ll = 2 (.512)
85  *                  [lig] ll = 3 for EVEX.L'L don't care (always assembled as 0)
86  *
87  *                  [w0]  ww = 0 for W = 0
88  *                  [w1]  ww = 1 for W = 1
89  *                  [wig] ww = 2 for W don't care (always assembled as 0)
90  *                  [ww]  ww = 3 for W used as REX.W
91  *
92  *                  [p0]  pp = 0 for no prefix
93  *                  [60]  pp = 1 for legacy prefix 60
94  *                  [f3]  pp = 2
95  *                  [f2]  pp = 3
96  *
97  *                tup is tuple type for Disp8*N from %tuple_codes in insns.pl
98  *                    (compressed displacement encoding)
99  *
100  * \254..\257    - a signed 32-bit operand to be extended to 64 bits.
101  * \260..\263    - this instruction uses VEX/XOP rather than REX, with the
102  *                 V field taken from operand 0..3.
103  * \270          - this instruction uses VEX/XOP rather than REX, with the
104  *                 V field set to 1111b.
105  *
106  * VEX/XOP prefixes are followed by the sequence:
107  * \tmm\wlp        where mm is the M field; and wlp is:
108  *                 00 wwl lpp
109  *                 [l0]  ll = 0 for L = 0 (.128, .lz)
110  *                 [l1]  ll = 1 for L = 1 (.256)
111  *                 [lig] ll = 2 for L don't care (always assembled as 0)
112  *
113  *                 [w0]  ww = 0 for W = 0
114  *                 [w1 ] ww = 1 for W = 1
115  *                 [wig] ww = 2 for W don't care (always assembled as 0)
116  *                 [ww]  ww = 3 for W used as REX.W
117  *
118  * t = 0 for VEX (C4/C5), t = 1 for XOP (8F).
119  *
120  * \271          - instruction takes XRELEASE (F3) with or without lock
121  * \272          - instruction takes XACQUIRE/XRELEASE with or without lock
122  * \273          - instruction takes XACQUIRE/XRELEASE with lock only
123  * \274..\277    - a byte immediate operand, from operand 0..3, sign-extended
124  *                 to the operand size (if o16/o32/o64 present) or the bit size
125  * \310          - indicates fixed 16-bit address size, i.e. optional 0x67.
126  * \311          - indicates fixed 32-bit address size, i.e. optional 0x67.
127  * \312          - (disassembler only) invalid with non-default address size.
128  * \313          - indicates fixed 64-bit address size, 0x67 invalid.
129  * \314          - (disassembler only) invalid with REX.B
130  * \315          - (disassembler only) invalid with REX.X
131  * \316          - (disassembler only) invalid with REX.R
132  * \317          - (disassembler only) invalid with REX.W
133  * \320          - indicates fixed 16-bit operand size, i.e. optional 0x66.
134  * \321          - indicates fixed 32-bit operand size, i.e. optional 0x66.
135  * \322          - indicates that this instruction is only valid when the
136  *                 operand size is the default (instruction to disassembler,
137  *                 generates no code in the assembler)
138  * \323          - indicates fixed 64-bit operand size, REX on extensions only.
139  * \324          - indicates 64-bit operand size requiring REX prefix.
140  * \325          - instruction which always uses spl/bpl/sil/dil
141  * \326          - instruction not valid with 0xF3 REP prefix.  Hint for
142                    disassembler only; for SSE instructions.
143  * \330          - a literal byte follows in the code stream, to be added
144  *                 to the condition code value of the instruction.
145  * \331          - instruction not valid with REP prefix.  Hint for
146  *                 disassembler only; for SSE instructions.
147  * \332          - REP prefix (0xF2 byte) used as opcode extension.
148  * \333          - REP prefix (0xF3 byte) used as opcode extension.
149  * \334          - LOCK prefix used as REX.R (used in non-64-bit mode)
150  * \335          - disassemble a rep (0xF3 byte) prefix as repe not rep.
151  * \336          - force a REP(E) prefix (0xF3) even if not specified.
152  * \337          - force a REPNE prefix (0xF2) even if not specified.
153  *                 \336-\337 are still listed as prefixes in the disassembler.
154  * \340          - reserve <operand 0> bytes of uninitialized storage.
155  *                 Operand 0 had better be a segmentless constant.
156  * \341          - this instruction needs a WAIT "prefix"
157  * \360          - no SSE prefix (== \364\331)
158  * \361          - 66 SSE prefix (== \366\331)
159  * \364          - operand-size prefix (0x66) not permitted
160  * \365          - address-size prefix (0x67) not permitted
161  * \366          - operand-size prefix (0x66) used as opcode extension
162  * \367          - address-size prefix (0x67) used as opcode extension
163  * \370,\371     - match only if operand 0 meets byte jump criteria.
164  *                 370 is used for Jcc, 371 is used for JMP.
165  * \373          - assemble 0x03 if bits==16, 0x05 if bits==32;
166  *                 used for conditional jump over longer jump
167  * \374          - this instruction takes an XMM VSIB memory EA
168  * \375          - this instruction takes an YMM VSIB memory EA
169  * \376          - this instruction takes an ZMM VSIB memory EA
170  */
171
172 #include "compiler.h"
173
174 #include <stdio.h>
175 #include <string.h>
176 #include <inttypes.h>
177
178 #include "nasm.h"
179 #include "nasmlib.h"
180 #include "assemble.h"
181 #include "insns.h"
182 #include "tables.h"
183
184 enum match_result {
185     /*
186      * Matching errors.  These should be sorted so that more specific
187      * errors come later in the sequence.
188      */
189     MERR_INVALOP,
190     MERR_OPSIZEMISSING,
191     MERR_OPSIZEMISMATCH,
192     MERR_BADCPU,
193     MERR_BADMODE,
194     MERR_BADHLE,
195     MERR_ENCMISMATCH,
196     MERR_BADBND,
197     /*
198      * Matching success; the conditional ones first
199      */
200     MOK_JUMP,   /* Matching OK but needs jmp_match() */
201     MOK_GOOD    /* Matching unconditionally OK */
202 };
203
204 typedef struct {
205     enum ea_type type;            /* what kind of EA is this? */
206     int sib_present;              /* is a SIB byte necessary? */
207     int bytes;                    /* # of bytes of offset needed */
208     int size;                     /* lazy - this is sib+bytes+1 */
209     uint8_t modrm, sib, rex, rip; /* the bytes themselves */
210     int8_t disp8;                  /* compressed displacement for EVEX */
211 } ea;
212
213 #define GEN_SIB(scale, index, base)                 \
214         (((scale) << 6) | ((index) << 3) | ((base)))
215
216 #define GEN_MODRM(mod, reg, rm)                     \
217         (((mod) << 6) | (((reg) & 7) << 3) | ((rm) & 7))
218
219 static iflags_t cpu;            /* cpu level received from nasm.c */
220 static efunc errfunc;
221 static struct ofmt *outfmt;
222 static ListGen *list;
223
224 static int64_t calcsize(int32_t, int64_t, int, insn *,
225                         const struct itemplate *);
226 static void gencode(int32_t segment, int64_t offset, int bits,
227                     insn * ins, const struct itemplate *temp,
228                     int64_t insn_end);
229 static enum match_result find_match(const struct itemplate **tempp,
230                                     insn *instruction,
231                                     int32_t segment, int64_t offset, int bits);
232 static enum match_result matches(const struct itemplate *, insn *, int bits);
233 static opflags_t regflag(const operand *);
234 static int32_t regval(const operand *);
235 static int rexflags(int, opflags_t, int);
236 static int op_rexflags(const operand *, int);
237 static int op_evexflags(const operand *, int, uint8_t);
238 static void add_asp(insn *, int);
239
240 static enum ea_type process_ea(operand *, ea *, int, int, opflags_t, insn *);
241
242 static int has_prefix(insn * ins, enum prefix_pos pos, int prefix)
243 {
244     return ins->prefixes[pos] == prefix;
245 }
246
247 static void assert_no_prefix(insn * ins, enum prefix_pos pos)
248 {
249     if (ins->prefixes[pos])
250         errfunc(ERR_NONFATAL, "invalid %s prefix",
251                 prefix_name(ins->prefixes[pos]));
252 }
253
254 static const char *size_name(int size)
255 {
256     switch (size) {
257     case 1:
258         return "byte";
259     case 2:
260         return "word";
261     case 4:
262         return "dword";
263     case 8:
264         return "qword";
265     case 10:
266         return "tword";
267     case 16:
268         return "oword";
269     case 32:
270         return "yword";
271     case 64:
272         return "zword";
273     default:
274         return "???";
275     }
276 }
277
278 static void warn_overflow(int pass, int size)
279 {
280     errfunc(ERR_WARNING | pass | ERR_WARN_NOV,
281             "%s data exceeds bounds", size_name(size));
282 }
283
284 static void warn_overflow_const(int64_t data, int size)
285 {
286     if (overflow_general(data, size))
287         warn_overflow(ERR_PASS1, size);
288 }
289
290 static void warn_overflow_opd(const struct operand *o, int size)
291 {
292     if (o->wrt == NO_SEG && o->segment == NO_SEG) {
293         if (overflow_general(o->offset, size))
294             warn_overflow(ERR_PASS2, size);
295     }
296 }
297
298 /*
299  * This routine wrappers the real output format's output routine,
300  * in order to pass a copy of the data off to the listing file
301  * generator at the same time.
302  */
303 static void out(int64_t offset, int32_t segto, const void *data,
304                 enum out_type type, uint64_t size,
305                 int32_t segment, int32_t wrt)
306 {
307     static int32_t lineno = 0;     /* static!!! */
308     static char *lnfname = NULL;
309     uint8_t p[8];
310
311     if (type == OUT_ADDRESS && segment == NO_SEG && wrt == NO_SEG) {
312         /*
313          * This is a non-relocated address, and we're going to
314          * convert it into RAWDATA format.
315          */
316         uint8_t *q = p;
317
318         if (size > 8) {
319             errfunc(ERR_PANIC, "OUT_ADDRESS with size > 8");
320             return;
321         }
322
323         WRITEADDR(q, *(int64_t *)data, size);
324         data = p;
325         type = OUT_RAWDATA;
326     }
327
328     list->output(offset, data, type, size);
329
330     /*
331      * this call to src_get determines when we call the
332      * debug-format-specific "linenum" function
333      * it updates lineno and lnfname to the current values
334      * returning 0 if "same as last time", -2 if lnfname
335      * changed, and the amount by which lineno changed,
336      * if it did. thus, these variables must be static
337      */
338
339     if (src_get(&lineno, &lnfname))
340         outfmt->current_dfmt->linenum(lnfname, lineno, segto);
341
342     outfmt->output(segto, data, type, size, segment, wrt);
343 }
344
345 static void out_imm8(int64_t offset, int32_t segment, struct operand *opx)
346 {
347     if (opx->segment != NO_SEG) {
348         uint64_t data = opx->offset;
349         out(offset, segment, &data, OUT_ADDRESS, 1, opx->segment, opx->wrt);
350     } else {
351         uint8_t byte = opx->offset;
352         out(offset, segment, &byte, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
353     }
354 }
355
356 static bool jmp_match(int32_t segment, int64_t offset, int bits,
357                       insn * ins, const struct itemplate *temp)
358 {
359     int64_t isize;
360     const uint8_t *code = temp->code;
361     uint8_t c = code[0];
362
363     if (((c & ~1) != 0370) || (ins->oprs[0].type & STRICT))
364         return false;
365     if (!optimizing)
366         return false;
367     if (optimizing < 0 && c == 0371)
368         return false;
369
370     isize = calcsize(segment, offset, bits, ins, temp);
371
372     if (ins->oprs[0].opflags & OPFLAG_UNKNOWN)
373         /* Be optimistic in pass 1 */
374         return true;
375
376     if (ins->oprs[0].segment != segment)
377         return false;
378
379     isize = ins->oprs[0].offset - offset - isize; /* isize is delta */
380     return (isize >= -128 && isize <= 127); /* is it byte size? */
381 }
382
383 int64_t assemble(int32_t segment, int64_t offset, int bits, iflags_t cp,
384                  insn * instruction, struct ofmt *output, efunc error,
385                  ListGen * listgen)
386 {
387     const struct itemplate *temp;
388     int j;
389     enum match_result m;
390     int64_t insn_end;
391     int32_t itimes;
392     int64_t start = offset;
393     int64_t wsize;              /* size for DB etc. */
394
395     errfunc = error;            /* to pass to other functions */
396     cpu = cp;
397     outfmt = output;            /* likewise */
398     list = listgen;             /* and again */
399
400     wsize = idata_bytes(instruction->opcode);
401     if (wsize == -1)
402         return 0;
403
404     if (wsize) {
405         extop *e;
406         int32_t t = instruction->times;
407         if (t < 0)
408             errfunc(ERR_PANIC,
409                     "instruction->times < 0 (%ld) in assemble()", t);
410
411         while (t--) {           /* repeat TIMES times */
412             list_for_each(e, instruction->eops) {
413                 if (e->type == EOT_DB_NUMBER) {
414                     if (wsize > 8) {
415                         errfunc(ERR_NONFATAL,
416                                 "integer supplied to a DT, DO or DY"
417                                 " instruction");
418                     } else {
419                         out(offset, segment, &e->offset,
420                             OUT_ADDRESS, wsize, e->segment, e->wrt);
421                         offset += wsize;
422                     }
423                 } else if (e->type == EOT_DB_STRING ||
424                            e->type == EOT_DB_STRING_FREE) {
425                     int align;
426
427                     out(offset, segment, e->stringval,
428                         OUT_RAWDATA, e->stringlen, NO_SEG, NO_SEG);
429                     align = e->stringlen % wsize;
430
431                     if (align) {
432                         align = wsize - align;
433                         out(offset, segment, zero_buffer,
434                             OUT_RAWDATA, align, NO_SEG, NO_SEG);
435                     }
436                     offset += e->stringlen + align;
437                 }
438             }
439             if (t > 0 && t == instruction->times - 1) {
440                 /*
441                  * Dummy call to list->output to give the offset to the
442                  * listing module.
443                  */
444                 list->output(offset, NULL, OUT_RAWDATA, 0);
445                 list->uplevel(LIST_TIMES);
446             }
447         }
448         if (instruction->times > 1)
449             list->downlevel(LIST_TIMES);
450         return offset - start;
451     }
452
453     if (instruction->opcode == I_INCBIN) {
454         const char *fname = instruction->eops->stringval;
455         FILE *fp;
456
457         fp = fopen(fname, "rb");
458         if (!fp) {
459             error(ERR_NONFATAL, "`incbin': unable to open file `%s'",
460                   fname);
461         } else if (fseek(fp, 0L, SEEK_END) < 0) {
462             error(ERR_NONFATAL, "`incbin': unable to seek on file `%s'",
463                   fname);
464             fclose(fp);
465         } else {
466             static char buf[4096];
467             size_t t = instruction->times;
468             size_t base = 0;
469             size_t len;
470
471             len = ftell(fp);
472             if (instruction->eops->next) {
473                 base = instruction->eops->next->offset;
474                 len -= base;
475                 if (instruction->eops->next->next &&
476                     len > (size_t)instruction->eops->next->next->offset)
477                     len = (size_t)instruction->eops->next->next->offset;
478             }
479             /*
480              * Dummy call to list->output to give the offset to the
481              * listing module.
482              */
483             list->output(offset, NULL, OUT_RAWDATA, 0);
484             list->uplevel(LIST_INCBIN);
485             while (t--) {
486                 size_t l;
487
488                 fseek(fp, base, SEEK_SET);
489                 l = len;
490                 while (l > 0) {
491                     int32_t m;
492                     m = fread(buf, 1, l > sizeof(buf) ? sizeof(buf) : l, fp);
493                     if (!m) {
494                         /*
495                          * This shouldn't happen unless the file
496                          * actually changes while we are reading
497                          * it.
498                          */
499                         error(ERR_NONFATAL,
500                               "`incbin': unexpected EOF while"
501                               " reading file `%s'", fname);
502                         t = 0;  /* Try to exit cleanly */
503                         break;
504                     }
505                     out(offset, segment, buf, OUT_RAWDATA, m,
506                         NO_SEG, NO_SEG);
507                     l -= m;
508                 }
509             }
510             list->downlevel(LIST_INCBIN);
511             if (instruction->times > 1) {
512                 /*
513                  * Dummy call to list->output to give the offset to the
514                  * listing module.
515                  */
516                 list->output(offset, NULL, OUT_RAWDATA, 0);
517                 list->uplevel(LIST_TIMES);
518                 list->downlevel(LIST_TIMES);
519             }
520             fclose(fp);
521             return instruction->times * len;
522         }
523         return 0;               /* if we're here, there's an error */
524     }
525
526     /* Check to see if we need an address-size prefix */
527     add_asp(instruction, bits);
528
529     m = find_match(&temp, instruction, segment, offset, bits);
530
531     if (m == MOK_GOOD) {
532         /* Matches! */
533         int64_t insn_size = calcsize(segment, offset, bits, instruction, temp);
534         itimes = instruction->times;
535         if (insn_size < 0)  /* shouldn't be, on pass two */
536             error(ERR_PANIC, "errors made it through from pass one");
537         else
538             while (itimes--) {
539                 for (j = 0; j < MAXPREFIX; j++) {
540                     uint8_t c = 0;
541                     switch (instruction->prefixes[j]) {
542                     case P_WAIT:
543                         c = 0x9B;
544                         break;
545                     case P_LOCK:
546                         c = 0xF0;
547                         break;
548                     case P_REPNE:
549                     case P_REPNZ:
550                     case P_XACQUIRE:
551                     case P_BND:
552                         c = 0xF2;
553                         break;
554                     case P_REPE:
555                     case P_REPZ:
556                     case P_REP:
557                     case P_XRELEASE:
558                         c = 0xF3;
559                         break;
560                     case R_CS:
561                         if (bits == 64) {
562                             error(ERR_WARNING | ERR_PASS2,
563                                   "cs segment base generated, but will be ignored in 64-bit mode");
564                         }
565                         c = 0x2E;
566                         break;
567                     case R_DS:
568                         if (bits == 64) {
569                             error(ERR_WARNING | ERR_PASS2,
570                                   "ds segment base generated, but will be ignored in 64-bit mode");
571                         }
572                         c = 0x3E;
573                         break;
574                     case R_ES:
575                         if (bits == 64) {
576                             error(ERR_WARNING | ERR_PASS2,
577                                   "es segment base generated, but will be ignored in 64-bit mode");
578                         }
579                         c = 0x26;
580                         break;
581                     case R_FS:
582                         c = 0x64;
583                         break;
584                     case R_GS:
585                         c = 0x65;
586                         break;
587                     case R_SS:
588                         if (bits == 64) {
589                             error(ERR_WARNING | ERR_PASS2,
590                                   "ss segment base generated, but will be ignored in 64-bit mode");
591                         }
592                         c = 0x36;
593                         break;
594                     case R_SEGR6:
595                     case R_SEGR7:
596                         error(ERR_NONFATAL,
597                               "segr6 and segr7 cannot be used as prefixes");
598                         break;
599                     case P_A16:
600                         if (bits == 64) {
601                             error(ERR_NONFATAL,
602                                   "16-bit addressing is not supported "
603                                   "in 64-bit mode");
604                         } else if (bits != 16)
605                             c = 0x67;
606                         break;
607                     case P_A32:
608                         if (bits != 32)
609                             c = 0x67;
610                         break;
611                     case P_A64:
612                         if (bits != 64) {
613                             error(ERR_NONFATAL,
614                                   "64-bit addressing is only supported "
615                                   "in 64-bit mode");
616                         }
617                         break;
618                     case P_ASP:
619                         c = 0x67;
620                         break;
621                     case P_O16:
622                         if (bits != 16)
623                             c = 0x66;
624                         break;
625                     case P_O32:
626                         if (bits == 16)
627                             c = 0x66;
628                         break;
629                     case P_O64:
630                         /* REX.W */
631                         break;
632                     case P_OSP:
633                         c = 0x66;
634                         break;
635                     case P_none:
636                         break;
637                     default:
638                         error(ERR_PANIC, "invalid instruction prefix");
639                     }
640                     if (c != 0) {
641                         out(offset, segment, &c, OUT_RAWDATA, 1,
642                             NO_SEG, NO_SEG);
643                         offset++;
644                     }
645                 }
646                 insn_end = offset + insn_size;
647                 gencode(segment, offset, bits, instruction,
648                         temp, insn_end);
649                 offset += insn_size;
650                 if (itimes > 0 && itimes == instruction->times - 1) {
651                     /*
652                      * Dummy call to list->output to give the offset to the
653                      * listing module.
654                      */
655                     list->output(offset, NULL, OUT_RAWDATA, 0);
656                     list->uplevel(LIST_TIMES);
657                 }
658             }
659         if (instruction->times > 1)
660             list->downlevel(LIST_TIMES);
661         return offset - start;
662     } else {
663         /* No match */
664         switch (m) {
665         case MERR_OPSIZEMISSING:
666             error(ERR_NONFATAL, "operation size not specified");
667             break;
668         case MERR_OPSIZEMISMATCH:
669             error(ERR_NONFATAL, "mismatch in operand sizes");
670             break;
671         case MERR_BADCPU:
672             error(ERR_NONFATAL, "no instruction for this cpu level");
673             break;
674         case MERR_BADMODE:
675             error(ERR_NONFATAL, "instruction not supported in %d-bit mode",
676                   bits);
677             break;
678         default:
679             error(ERR_NONFATAL,
680                   "invalid combination of opcode and operands");
681             break;
682         }
683     }
684     return 0;
685 }
686
687 int64_t insn_size(int32_t segment, int64_t offset, int bits, iflags_t cp,
688                   insn * instruction, efunc error)
689 {
690     const struct itemplate *temp;
691     enum match_result m;
692
693     errfunc = error;            /* to pass to other functions */
694     cpu = cp;
695
696     if (instruction->opcode == I_none)
697         return 0;
698
699     if (instruction->opcode == I_DB || instruction->opcode == I_DW ||
700         instruction->opcode == I_DD || instruction->opcode == I_DQ ||
701         instruction->opcode == I_DT || instruction->opcode == I_DO ||
702         instruction->opcode == I_DY) {
703         extop *e;
704         int32_t isize, osize, wsize;
705
706         isize = 0;
707         wsize = idata_bytes(instruction->opcode);
708
709         list_for_each(e, instruction->eops) {
710             int32_t align;
711
712             osize = 0;
713             if (e->type == EOT_DB_NUMBER) {
714                 osize = 1;
715                 warn_overflow_const(e->offset, wsize);
716             } else if (e->type == EOT_DB_STRING ||
717                        e->type == EOT_DB_STRING_FREE)
718                 osize = e->stringlen;
719
720             align = (-osize) % wsize;
721             if (align < 0)
722                 align += wsize;
723             isize += osize + align;
724         }
725         return isize * instruction->times;
726     }
727
728     if (instruction->opcode == I_INCBIN) {
729         const char *fname = instruction->eops->stringval;
730         FILE *fp;
731         int64_t val = 0;
732         size_t len;
733
734         fp = fopen(fname, "rb");
735         if (!fp)
736             error(ERR_NONFATAL, "`incbin': unable to open file `%s'",
737                   fname);
738         else if (fseek(fp, 0L, SEEK_END) < 0)
739             error(ERR_NONFATAL, "`incbin': unable to seek on file `%s'",
740                   fname);
741         else {
742             len = ftell(fp);
743             if (instruction->eops->next) {
744                 len -= instruction->eops->next->offset;
745                 if (instruction->eops->next->next &&
746                     len > (size_t)instruction->eops->next->next->offset) {
747                     len = (size_t)instruction->eops->next->next->offset;
748                 }
749             }
750             val = instruction->times * len;
751         }
752         if (fp)
753             fclose(fp);
754         return val;
755     }
756
757     /* Check to see if we need an address-size prefix */
758     add_asp(instruction, bits);
759
760     m = find_match(&temp, instruction, segment, offset, bits);
761     if (m == MOK_GOOD) {
762         /* we've matched an instruction. */
763         int64_t isize;
764         int j;
765
766         isize = calcsize(segment, offset, bits, instruction, temp);
767         if (isize < 0)
768             return -1;
769         for (j = 0; j < MAXPREFIX; j++) {
770             switch (instruction->prefixes[j]) {
771             case P_A16:
772                 if (bits != 16)
773                     isize++;
774                 break;
775             case P_A32:
776                 if (bits != 32)
777                     isize++;
778                 break;
779             case P_O16:
780                 if (bits != 16)
781                     isize++;
782                 break;
783             case P_O32:
784                 if (bits == 16)
785                     isize++;
786                 break;
787             case P_A64:
788             case P_O64:
789             case P_none:
790                 break;
791             default:
792                 isize++;
793                 break;
794             }
795         }
796         return isize * instruction->times;
797     } else {
798         return -1;                  /* didn't match any instruction */
799     }
800 }
801
802 static void bad_hle_warn(const insn * ins, uint8_t hleok)
803 {
804     enum prefixes rep_pfx = ins->prefixes[PPS_REP];
805     enum whatwarn { w_none, w_lock, w_inval } ww;
806     static const enum whatwarn warn[2][4] =
807     {
808         { w_inval, w_inval, w_none, w_lock }, /* XACQUIRE */
809         { w_inval, w_none,  w_none, w_lock }, /* XRELEASE */
810     };
811     unsigned int n;
812
813     n = (unsigned int)rep_pfx - P_XACQUIRE;
814     if (n > 1)
815         return;                 /* Not XACQUIRE/XRELEASE */
816
817     ww = warn[n][hleok];
818     if (!is_class(MEMORY, ins->oprs[0].type))
819         ww = w_inval;           /* HLE requires operand 0 to be memory */
820
821     switch (ww) {
822     case w_none:
823         break;
824
825     case w_lock:
826         if (ins->prefixes[PPS_LOCK] != P_LOCK) {
827             errfunc(ERR_WARNING | ERR_WARN_HLE | ERR_PASS2,
828                     "%s with this instruction requires lock",
829                     prefix_name(rep_pfx));
830         }
831         break;
832
833     case w_inval:
834         errfunc(ERR_WARNING | ERR_WARN_HLE | ERR_PASS2,
835                 "%s invalid with this instruction",
836                 prefix_name(rep_pfx));
837         break;
838     }
839 }
840
841 /* Common construct */
842 #define case3(x) case (x): case (x)+1: case (x)+2
843 #define case4(x) case3(x): case (x)+3
844
845 static int64_t calcsize(int32_t segment, int64_t offset, int bits,
846                         insn * ins, const struct itemplate *temp)
847 {
848     const uint8_t *codes = temp->code;
849     int64_t length = 0;
850     uint8_t c;
851     int rex_mask = ~0;
852     int op1, op2;
853     struct operand *opx;
854     uint8_t opex = 0;
855     enum ea_type eat;
856     uint8_t hleok = 0;
857     bool lockcheck = true;
858     enum reg_enum mib_index = R_none;   /* For a separate index MIB reg form */
859
860     ins->rex = 0;               /* Ensure REX is reset */
861     eat = EA_SCALAR;            /* Expect a scalar EA */
862     memset(ins->evex_p, 0, 3);  /* Ensure EVEX is reset */
863
864     if (ins->prefixes[PPS_OSIZE] == P_O64)
865         ins->rex |= REX_W;
866
867     (void)segment;              /* Don't warn that this parameter is unused */
868     (void)offset;               /* Don't warn that this parameter is unused */
869
870     while (*codes) {
871         c = *codes++;
872         op1 = (c & 3) + ((opex & 1) << 2);
873         op2 = ((c >> 3) & 3) + ((opex & 2) << 1);
874         opx = &ins->oprs[op1];
875         opex = 0;               /* For the next iteration */
876
877         switch (c) {
878         case4(01):
879             codes += c, length += c;
880             break;
881
882         case3(05):
883             opex = c;
884             break;
885
886         case4(010):
887             ins->rex |=
888                 op_rexflags(opx, REX_B|REX_H|REX_P|REX_W);
889             codes++, length++;
890             break;
891
892         case4(014):
893             /* this is an index reg of MIB operand */
894             mib_index = opx->basereg;
895             break;
896
897         case4(020):
898         case4(024):
899             length++;
900             break;
901
902         case4(030):
903             length += 2;
904             break;
905
906         case4(034):
907             if (opx->type & (BITS16 | BITS32 | BITS64))
908                 length += (opx->type & BITS16) ? 2 : 4;
909             else
910                 length += (bits == 16) ? 2 : 4;
911             break;
912
913         case4(040):
914             length += 4;
915             break;
916
917         case4(044):
918             length += ins->addr_size >> 3;
919             break;
920
921         case4(050):
922             length++;
923             break;
924
925         case4(054):
926             length += 8; /* MOV reg64/imm */
927             break;
928
929         case4(060):
930             length += 2;
931             break;
932
933         case4(064):
934             if (opx->type & (BITS16 | BITS32 | BITS64))
935                 length += (opx->type & BITS16) ? 2 : 4;
936             else
937                 length += (bits == 16) ? 2 : 4;
938             break;
939
940         case4(070):
941             length += 4;
942             break;
943
944         case4(074):
945             length += 2;
946             break;
947
948         case 0172:
949         case 0173:
950             codes++;
951             length++;
952             break;
953
954         case4(0174):
955             length++;
956             break;
957
958         case4(0240):
959             ins->rex |= REX_EV;
960             ins->vexreg = regval(opx);
961             ins->evex_p[2] |= op_evexflags(opx, EVEX_P2VP, 2); /* High-16 NDS */
962             ins->vex_cm = *codes++;
963             ins->vex_wlp = *codes++;
964             ins->evex_tuple = (*codes++ - 0300);
965             break;
966
967         case 0250:
968             ins->rex |= REX_EV;
969             ins->vexreg = 0;
970             ins->vex_cm = *codes++;
971             ins->vex_wlp = *codes++;
972             ins->evex_tuple = (*codes++ - 0300);
973             break;
974
975         case4(0254):
976             length += 4;
977             break;
978
979         case4(0260):
980             ins->rex |= REX_V;
981             ins->vexreg = regval(opx);
982             ins->vex_cm = *codes++;
983             ins->vex_wlp = *codes++;
984             break;
985
986         case 0270:
987             ins->rex |= REX_V;
988             ins->vexreg = 0;
989             ins->vex_cm = *codes++;
990             ins->vex_wlp = *codes++;
991             break;
992
993         case3(0271):
994             hleok = c & 3;
995             break;
996
997         case4(0274):
998             length++;
999             break;
1000
1001         case4(0300):
1002             break;
1003
1004         case 0310:
1005             if (bits == 64)
1006                 return -1;
1007             length += (bits != 16) && !has_prefix(ins, PPS_ASIZE, P_A16);
1008             break;
1009
1010         case 0311:
1011             length += (bits != 32) && !has_prefix(ins, PPS_ASIZE, P_A32);
1012             break;
1013
1014         case 0312:
1015             break;
1016
1017         case 0313:
1018             if (bits != 64 || has_prefix(ins, PPS_ASIZE, P_A16) ||
1019                 has_prefix(ins, PPS_ASIZE, P_A32))
1020                 return -1;
1021             break;
1022
1023         case4(0314):
1024             break;
1025
1026         case 0320:
1027         {
1028             enum prefixes pfx = ins->prefixes[PPS_OSIZE];
1029             if (pfx == P_O16)
1030                 break;
1031             if (pfx != P_none)
1032                 errfunc(ERR_WARNING | ERR_PASS2, "invalid operand size prefix");
1033             else
1034                 ins->prefixes[PPS_OSIZE] = P_O16;
1035             break;
1036         }
1037
1038         case 0321:
1039         {
1040             enum prefixes pfx = ins->prefixes[PPS_OSIZE];
1041             if (pfx == P_O32)
1042                 break;
1043             if (pfx != P_none)
1044                 errfunc(ERR_WARNING | ERR_PASS2, "invalid operand size prefix");
1045             else
1046                 ins->prefixes[PPS_OSIZE] = P_O32;
1047             break;
1048         }
1049
1050         case 0322:
1051             break;
1052
1053         case 0323:
1054             rex_mask &= ~REX_W;
1055             break;
1056
1057         case 0324:
1058             ins->rex |= REX_W;
1059             break;
1060
1061         case 0325:
1062             ins->rex |= REX_NH;
1063             break;
1064
1065         case 0326:
1066             break;
1067
1068         case 0330:
1069             codes++, length++;
1070             break;
1071
1072         case 0331:
1073             break;
1074
1075         case 0332:
1076         case 0333:
1077             length++;
1078             break;
1079
1080         case 0334:
1081             ins->rex |= REX_L;
1082             break;
1083
1084         case 0335:
1085             break;
1086
1087         case 0336:
1088             if (!ins->prefixes[PPS_REP])
1089                 ins->prefixes[PPS_REP] = P_REP;
1090             break;
1091
1092         case 0337:
1093             if (!ins->prefixes[PPS_REP])
1094                 ins->prefixes[PPS_REP] = P_REPNE;
1095             break;
1096
1097         case 0340:
1098             if (ins->oprs[0].segment != NO_SEG)
1099                 errfunc(ERR_NONFATAL, "attempt to reserve non-constant"
1100                         " quantity of BSS space");
1101             else
1102                 length += ins->oprs[0].offset;
1103             break;
1104
1105         case 0341:
1106             if (!ins->prefixes[PPS_WAIT])
1107                 ins->prefixes[PPS_WAIT] = P_WAIT;
1108             break;
1109
1110         case 0360:
1111             break;
1112
1113         case 0361:
1114             length++;
1115             break;
1116
1117         case 0364:
1118         case 0365:
1119             break;
1120
1121         case 0366:
1122         case 0367:
1123             length++;
1124             break;
1125
1126         case 0370:
1127         case 0371:
1128             break;
1129
1130         case 0373:
1131             length++;
1132             break;
1133
1134         case 0374:
1135             eat = EA_XMMVSIB;
1136             break;
1137
1138         case 0375:
1139             eat = EA_YMMVSIB;
1140             break;
1141
1142         case 0376:
1143             eat = EA_ZMMVSIB;
1144             break;
1145
1146         case4(0100):
1147         case4(0110):
1148         case4(0120):
1149         case4(0130):
1150         case4(0200):
1151         case4(0204):
1152         case4(0210):
1153         case4(0214):
1154         case4(0220):
1155         case4(0224):
1156         case4(0230):
1157         case4(0234):
1158             {
1159                 ea ea_data;
1160                 int rfield;
1161                 opflags_t rflags;
1162                 struct operand *opy = &ins->oprs[op2];
1163                 struct operand *op_er_sae;
1164
1165                 ea_data.rex = 0;           /* Ensure ea.REX is initially 0 */
1166
1167                 if (c <= 0177) {
1168                     /* pick rfield from operand b (opx) */
1169                     rflags = regflag(opx);
1170                     rfield = nasm_regvals[opx->basereg];
1171                 } else {
1172                     rflags = 0;
1173                     rfield = c & 7;
1174                 }
1175
1176                 /* EVEX.b1 : evex_brerop contains the operand position */
1177                 op_er_sae = (ins->evex_brerop >= 0 ?
1178                              &ins->oprs[ins->evex_brerop] : NULL);
1179
1180                 if (op_er_sae && (op_er_sae->decoflags & (ER | SAE))) {
1181                     /* set EVEX.b */
1182                     ins->evex_p[2] |= EVEX_P2B;
1183                     if (op_er_sae->decoflags & ER) {
1184                         /* set EVEX.RC (rounding control) */
1185                         ins->evex_p[2] |= ((ins->evex_rm - BRC_RN) << 5)
1186                                           & EVEX_P2RC;
1187                     }
1188                 } else {
1189                     /* set EVEX.L'L (vector length) */
1190                     ins->evex_p[2] |= ((ins->vex_wlp << (5 - 2)) & EVEX_P2LL);
1191                     if (opy->decoflags & BRDCAST_MASK) {
1192                         /* set EVEX.b */
1193                         ins->evex_p[2] |= EVEX_P2B;
1194                     }
1195                 }
1196
1197                 /*
1198                  * if a separate form of MIB (ICC style) is used,
1199                  * the index reg info is merged into mem operand
1200                  */
1201                 if (mib_index != R_none) {
1202                     opy->indexreg = mib_index;
1203                     opy->scale = 1;
1204                     opy->hintbase = mib_index;
1205                     opy->hinttype = EAH_NOTBASE;
1206                 }
1207
1208                 /*
1209                  * only for mib operands, make a single reg index [reg*1].
1210                  * gas uses this form to explicitly denote index register.
1211                  */
1212                 if ((temp->flags & IF_MIB) &&
1213                     (opy->indexreg == -1 && opy->hintbase == opy->basereg &&
1214                      opy->hinttype == EAH_NOTBASE)) {
1215                     opy->indexreg = opy->basereg;
1216                     opy->basereg  = -1;
1217                     opy->scale    = 1;
1218                 }
1219
1220                 if (process_ea(opy, &ea_data, bits,
1221                                rfield, rflags, ins) != eat) {
1222                     errfunc(ERR_NONFATAL, "invalid effective address");
1223                     return -1;
1224                 } else {
1225                     ins->rex |= ea_data.rex;
1226                     length += ea_data.size;
1227                 }
1228             }
1229             break;
1230
1231         default:
1232             errfunc(ERR_PANIC, "internal instruction table corrupt"
1233                     ": instruction code \\%o (0x%02X) given", c, c);
1234             break;
1235         }
1236     }
1237
1238     ins->rex &= rex_mask;
1239
1240     if (ins->rex & REX_NH) {
1241         if (ins->rex & REX_H) {
1242             errfunc(ERR_NONFATAL, "instruction cannot use high registers");
1243             return -1;
1244         }
1245         ins->rex &= ~REX_P;        /* Don't force REX prefix due to high reg */
1246     }
1247
1248     if (ins->rex & (REX_V | REX_EV)) {
1249         int bad32 = REX_R|REX_W|REX_X|REX_B;
1250
1251         if (ins->rex & REX_H) {
1252             errfunc(ERR_NONFATAL, "cannot use high register in AVX instruction");
1253             return -1;
1254         }
1255         switch (ins->vex_wlp & 060) {
1256         case 000:
1257         case 040:
1258             ins->rex &= ~REX_W;
1259             break;
1260         case 020:
1261             ins->rex |= REX_W;
1262             bad32 &= ~REX_W;
1263             break;
1264         case 060:
1265             /* Follow REX_W */
1266             break;
1267         }
1268
1269         if (bits != 64 && ((ins->rex & bad32) || ins->vexreg > 7)) {
1270             errfunc(ERR_NONFATAL, "invalid operands in non-64-bit mode");
1271             return -1;
1272         } else if (!(ins->rex & REX_EV) &&
1273                    ((ins->vexreg > 15) || (ins->evex_p[0] & 0xf0))) {
1274             errfunc(ERR_NONFATAL, "invalid high-16 register in non-AVX-512");
1275             return -1;
1276         }
1277         if (ins->rex & REX_EV)
1278             length += 4;
1279         else if (ins->vex_cm != 1 || (ins->rex & (REX_W|REX_X|REX_B)))
1280             length += 3;
1281         else
1282             length += 2;
1283     } else if (ins->rex & REX_REAL) {
1284         if (ins->rex & REX_H) {
1285             errfunc(ERR_NONFATAL, "cannot use high register in rex instruction");
1286             return -1;
1287         } else if (bits == 64) {
1288             length++;
1289         } else if ((ins->rex & REX_L) &&
1290                    !(ins->rex & (REX_P|REX_W|REX_X|REX_B)) &&
1291                    cpu >= IF_X86_64) {
1292             /* LOCK-as-REX.R */
1293             assert_no_prefix(ins, PPS_LOCK);
1294             lockcheck = false;  /* Already errored, no need for warning */
1295             length++;
1296         } else {
1297             errfunc(ERR_NONFATAL, "invalid operands in non-64-bit mode");
1298             return -1;
1299         }
1300     }
1301
1302     if (has_prefix(ins, PPS_LOCK, P_LOCK) && lockcheck &&
1303         (!(temp->flags & IF_LOCK) || !is_class(MEMORY, ins->oprs[0].type))) {
1304         errfunc(ERR_WARNING | ERR_WARN_LOCK | ERR_PASS2 ,
1305                 "instruction is not lockable");
1306     }
1307
1308     bad_hle_warn(ins, hleok);
1309
1310     return length;
1311 }
1312
1313 static inline unsigned int emit_rex(insn *ins, int32_t segment, int64_t offset, int bits)
1314 {
1315     if (bits == 64) {
1316         if ((ins->rex & REX_REAL) && !(ins->rex & (REX_V | REX_EV))) {
1317             ins->rex = (ins->rex & REX_REAL) | REX_P;
1318             out(offset, segment, &ins->rex, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1319             ins->rex = 0;
1320             return 1;
1321         }
1322     }
1323
1324     return 0;
1325 }
1326
1327 static void gencode(int32_t segment, int64_t offset, int bits,
1328                     insn * ins, const struct itemplate *temp,
1329                     int64_t insn_end)
1330 {
1331     uint8_t c;
1332     uint8_t bytes[4];
1333     int64_t size;
1334     int64_t data;
1335     int op1, op2;
1336     struct operand *opx;
1337     const uint8_t *codes = temp->code;
1338     uint8_t opex = 0;
1339     enum ea_type eat = EA_SCALAR;
1340
1341     while (*codes) {
1342         c = *codes++;
1343         op1 = (c & 3) + ((opex & 1) << 2);
1344         op2 = ((c >> 3) & 3) + ((opex & 2) << 1);
1345         opx = &ins->oprs[op1];
1346         opex = 0;                /* For the next iteration */
1347
1348         switch (c) {
1349         case 01:
1350         case 02:
1351         case 03:
1352         case 04:
1353             offset += emit_rex(ins, segment, offset, bits);
1354             out(offset, segment, codes, OUT_RAWDATA, c, NO_SEG, NO_SEG);
1355             codes += c;
1356             offset += c;
1357             break;
1358
1359         case 05:
1360         case 06:
1361         case 07:
1362             opex = c;
1363             break;
1364
1365         case4(010):
1366             offset += emit_rex(ins, segment, offset, bits);
1367             bytes[0] = *codes++ + (regval(opx) & 7);
1368             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1369             offset += 1;
1370             break;
1371
1372         case4(014):
1373             break;
1374
1375         case4(020):
1376             if (opx->offset < -256 || opx->offset > 255) {
1377                 errfunc(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1378                         "byte value exceeds bounds");
1379             }
1380             out_imm8(offset, segment, opx);
1381             offset += 1;
1382             break;
1383
1384         case4(024):
1385             if (opx->offset < 0 || opx->offset > 255)
1386                 errfunc(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1387                         "unsigned byte value exceeds bounds");
1388             out_imm8(offset, segment, opx);
1389             offset += 1;
1390             break;
1391
1392         case4(030):
1393             warn_overflow_opd(opx, 2);
1394             data = opx->offset;
1395             out(offset, segment, &data, OUT_ADDRESS, 2,
1396                 opx->segment, opx->wrt);
1397             offset += 2;
1398             break;
1399
1400         case4(034):
1401             if (opx->type & (BITS16 | BITS32))
1402                 size = (opx->type & BITS16) ? 2 : 4;
1403             else
1404                 size = (bits == 16) ? 2 : 4;
1405             warn_overflow_opd(opx, size);
1406             data = opx->offset;
1407             out(offset, segment, &data, OUT_ADDRESS, size,
1408                 opx->segment, opx->wrt);
1409             offset += size;
1410             break;
1411
1412         case4(040):
1413             warn_overflow_opd(opx, 4);
1414             data = opx->offset;
1415             out(offset, segment, &data, OUT_ADDRESS, 4,
1416                 opx->segment, opx->wrt);
1417             offset += 4;
1418             break;
1419
1420         case4(044):
1421             data = opx->offset;
1422             size = ins->addr_size >> 3;
1423             warn_overflow_opd(opx, size);
1424             out(offset, segment, &data, OUT_ADDRESS, size,
1425                 opx->segment, opx->wrt);
1426             offset += size;
1427             break;
1428
1429         case4(050):
1430             if (opx->segment != segment) {
1431                 data = opx->offset;
1432                 out(offset, segment, &data,
1433                     OUT_REL1ADR, insn_end - offset,
1434                     opx->segment, opx->wrt);
1435             } else {
1436                 data = opx->offset - insn_end;
1437                 if (data > 127 || data < -128)
1438                     errfunc(ERR_NONFATAL, "short jump is out of range");
1439                 out(offset, segment, &data,
1440                     OUT_ADDRESS, 1, NO_SEG, NO_SEG);
1441             }
1442             offset += 1;
1443             break;
1444
1445         case4(054):
1446             data = (int64_t)opx->offset;
1447             out(offset, segment, &data, OUT_ADDRESS, 8,
1448                 opx->segment, opx->wrt);
1449             offset += 8;
1450             break;
1451
1452         case4(060):
1453             if (opx->segment != segment) {
1454                 data = opx->offset;
1455                 out(offset, segment, &data,
1456                     OUT_REL2ADR, insn_end - offset,
1457                     opx->segment, opx->wrt);
1458             } else {
1459                 data = opx->offset - insn_end;
1460                 out(offset, segment, &data,
1461                     OUT_ADDRESS, 2, NO_SEG, NO_SEG);
1462             }
1463             offset += 2;
1464             break;
1465
1466         case4(064):
1467             if (opx->type & (BITS16 | BITS32 | BITS64))
1468                 size = (opx->type & BITS16) ? 2 : 4;
1469             else
1470                 size = (bits == 16) ? 2 : 4;
1471             if (opx->segment != segment) {
1472                 data = opx->offset;
1473                 out(offset, segment, &data,
1474                     size == 2 ? OUT_REL2ADR : OUT_REL4ADR,
1475                     insn_end - offset, opx->segment, opx->wrt);
1476             } else {
1477                 data = opx->offset - insn_end;
1478                 out(offset, segment, &data,
1479                     OUT_ADDRESS, size, NO_SEG, NO_SEG);
1480             }
1481             offset += size;
1482             break;
1483
1484         case4(070):
1485             if (opx->segment != segment) {
1486                 data = opx->offset;
1487                 out(offset, segment, &data,
1488                     OUT_REL4ADR, insn_end - offset,
1489                     opx->segment, opx->wrt);
1490             } else {
1491                 data = opx->offset - insn_end;
1492                 out(offset, segment, &data,
1493                     OUT_ADDRESS, 4, NO_SEG, NO_SEG);
1494             }
1495             offset += 4;
1496             break;
1497
1498         case4(074):
1499             if (opx->segment == NO_SEG)
1500                 errfunc(ERR_NONFATAL, "value referenced by FAR is not"
1501                         " relocatable");
1502             data = 0;
1503             out(offset, segment, &data, OUT_ADDRESS, 2,
1504                 outfmt->segbase(1 + opx->segment),
1505                 opx->wrt);
1506             offset += 2;
1507             break;
1508
1509         case 0172:
1510             c = *codes++;
1511             opx = &ins->oprs[c >> 3];
1512             bytes[0] = nasm_regvals[opx->basereg] << 4;
1513             opx = &ins->oprs[c & 7];
1514             if (opx->segment != NO_SEG || opx->wrt != NO_SEG) {
1515                 errfunc(ERR_NONFATAL,
1516                         "non-absolute expression not permitted as argument %d",
1517                         c & 7);
1518             } else {
1519                 if (opx->offset & ~15) {
1520                     errfunc(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1521                             "four-bit argument exceeds bounds");
1522                 }
1523                 bytes[0] |= opx->offset & 15;
1524             }
1525             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1526             offset++;
1527             break;
1528
1529         case 0173:
1530             c = *codes++;
1531             opx = &ins->oprs[c >> 4];
1532             bytes[0] = nasm_regvals[opx->basereg] << 4;
1533             bytes[0] |= c & 15;
1534             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1535             offset++;
1536             break;
1537
1538         case4(0174):
1539             bytes[0] = nasm_regvals[opx->basereg] << 4;
1540             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1541             offset++;
1542             break;
1543
1544         case4(0254):
1545             data = opx->offset;
1546             if (opx->wrt == NO_SEG && opx->segment == NO_SEG &&
1547                 (int32_t)data != (int64_t)data) {
1548                 errfunc(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1549                         "signed dword immediate exceeds bounds");
1550             }
1551             out(offset, segment, &data, OUT_ADDRESS, 4,
1552                 opx->segment, opx->wrt);
1553             offset += 4;
1554             break;
1555
1556         case4(0240):
1557         case 0250:
1558             codes += 3;
1559             ins->evex_p[2] |= op_evexflags(&ins->oprs[0],
1560                                            EVEX_P2Z | EVEX_P2AAA, 2);
1561             ins->evex_p[2] ^= EVEX_P2VP;        /* 1's complement */
1562             bytes[0] = 0x62;
1563             /* EVEX.X can be set by either REX or EVEX for different reasons */
1564             bytes[1] = ((((ins->rex & 7) << 5) |
1565                          (ins->evex_p[0] & (EVEX_P0X | EVEX_P0RP))) ^ 0xf0) |
1566                        (ins->vex_cm & 3);
1567             bytes[2] = ((ins->rex & REX_W) << (7 - 3)) |
1568                        ((~ins->vexreg & 15) << 3) |
1569                        (1 << 2) | (ins->vex_wlp & 3);
1570             bytes[3] = ins->evex_p[2];
1571             out(offset, segment, &bytes, OUT_RAWDATA, 4, NO_SEG, NO_SEG);
1572             offset += 4;
1573             break;
1574
1575         case4(0260):
1576         case 0270:
1577             codes += 2;
1578             if (ins->vex_cm != 1 || (ins->rex & (REX_W|REX_X|REX_B))) {
1579                 bytes[0] = (ins->vex_cm >> 6) ? 0x8f : 0xc4;
1580                 bytes[1] = (ins->vex_cm & 31) | ((~ins->rex & 7) << 5);
1581                 bytes[2] = ((ins->rex & REX_W) << (7-3)) |
1582                     ((~ins->vexreg & 15)<< 3) | (ins->vex_wlp & 07);
1583                 out(offset, segment, &bytes, OUT_RAWDATA, 3, NO_SEG, NO_SEG);
1584                 offset += 3;
1585             } else {
1586                 bytes[0] = 0xc5;
1587                 bytes[1] = ((~ins->rex & REX_R) << (7-2)) |
1588                     ((~ins->vexreg & 15) << 3) | (ins->vex_wlp & 07);
1589                 out(offset, segment, &bytes, OUT_RAWDATA, 2, NO_SEG, NO_SEG);
1590                 offset += 2;
1591             }
1592             break;
1593
1594         case 0271:
1595         case 0272:
1596         case 0273:
1597             break;
1598
1599         case4(0274):
1600         {
1601             uint64_t uv, um;
1602             int s;
1603
1604             if (ins->rex & REX_W)
1605                 s = 64;
1606             else if (ins->prefixes[PPS_OSIZE] == P_O16)
1607                 s = 16;
1608             else if (ins->prefixes[PPS_OSIZE] == P_O32)
1609                 s = 32;
1610             else
1611                 s = bits;
1612
1613             um = (uint64_t)2 << (s-1);
1614             uv = opx->offset;
1615
1616             if (uv > 127 && uv < (uint64_t)-128 &&
1617                 (uv < um-128 || uv > um-1)) {
1618                 /* If this wasn't explicitly byte-sized, warn as though we
1619                  * had fallen through to the imm16/32/64 case.
1620                  */
1621                 errfunc(ERR_WARNING | ERR_PASS2 | ERR_WARN_NOV,
1622                         "%s value exceeds bounds",
1623                         (opx->type & BITS8) ? "signed byte" :
1624                         s == 16 ? "word" :
1625                         s == 32 ? "dword" :
1626                         "signed dword");
1627             }
1628             if (opx->segment != NO_SEG) {
1629                 data = uv;
1630                 out(offset, segment, &data, OUT_ADDRESS, 1,
1631                     opx->segment, opx->wrt);
1632             } else {
1633                 bytes[0] = uv;
1634                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG,
1635                     NO_SEG);
1636             }
1637             offset += 1;
1638             break;
1639         }
1640
1641         case4(0300):
1642             break;
1643
1644         case 0310:
1645             if (bits == 32 && !has_prefix(ins, PPS_ASIZE, P_A16)) {
1646                 *bytes = 0x67;
1647                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1648                 offset += 1;
1649             } else
1650                 offset += 0;
1651             break;
1652
1653         case 0311:
1654             if (bits != 32 && !has_prefix(ins, PPS_ASIZE, P_A32)) {
1655                 *bytes = 0x67;
1656                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1657                 offset += 1;
1658             } else
1659                 offset += 0;
1660             break;
1661
1662         case 0312:
1663             break;
1664
1665         case 0313:
1666             ins->rex = 0;
1667             break;
1668
1669         case4(0314):
1670             break;
1671
1672         case 0320:
1673         case 0321:
1674             break;
1675
1676         case 0322:
1677         case 0323:
1678             break;
1679
1680         case 0324:
1681             ins->rex |= REX_W;
1682             break;
1683
1684         case 0325:
1685             break;
1686
1687         case 0326:
1688             break;
1689
1690         case 0330:
1691             *bytes = *codes++ ^ get_cond_opcode(ins->condition);
1692             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1693             offset += 1;
1694             break;
1695
1696         case 0331:
1697             break;
1698
1699         case 0332:
1700         case 0333:
1701             *bytes = c - 0332 + 0xF2;
1702             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1703             offset += 1;
1704             break;
1705
1706         case 0334:
1707             if (ins->rex & REX_R) {
1708                 *bytes = 0xF0;
1709                 out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1710                 offset += 1;
1711             }
1712             ins->rex &= ~(REX_L|REX_R);
1713             break;
1714
1715         case 0335:
1716             break;
1717
1718         case 0336:
1719         case 0337:
1720             break;
1721
1722         case 0340:
1723             if (ins->oprs[0].segment != NO_SEG)
1724                 errfunc(ERR_PANIC, "non-constant BSS size in pass two");
1725             else {
1726                 int64_t size = ins->oprs[0].offset;
1727                 if (size > 0)
1728                     out(offset, segment, NULL,
1729                         OUT_RESERVE, size, NO_SEG, NO_SEG);
1730                 offset += size;
1731             }
1732             break;
1733
1734         case 0341:
1735             break;
1736
1737         case 0360:
1738             break;
1739
1740         case 0361:
1741             bytes[0] = 0x66;
1742             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1743             offset += 1;
1744             break;
1745
1746         case 0364:
1747         case 0365:
1748             break;
1749
1750         case 0366:
1751         case 0367:
1752             *bytes = c - 0366 + 0x66;
1753             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1754             offset += 1;
1755             break;
1756
1757         case3(0370):
1758             break;
1759
1760         case 0373:
1761             *bytes = bits == 16 ? 3 : 5;
1762             out(offset, segment, bytes, OUT_RAWDATA, 1, NO_SEG, NO_SEG);
1763             offset += 1;
1764             break;
1765
1766         case 0374:
1767             eat = EA_XMMVSIB;
1768             break;
1769
1770         case 0375:
1771             eat = EA_YMMVSIB;
1772             break;
1773
1774         case 0376:
1775             eat = EA_ZMMVSIB;
1776             break;
1777
1778         case4(0100):
1779         case4(0110):
1780         case4(0120):
1781         case4(0130):
1782         case4(0200):
1783         case4(0204):
1784         case4(0210):
1785         case4(0214):
1786         case4(0220):
1787         case4(0224):
1788         case4(0230):
1789         case4(0234):
1790             {
1791                 ea ea_data;
1792                 int rfield;
1793                 opflags_t rflags;
1794                 uint8_t *p;
1795                 int32_t s;
1796                 struct operand *opy = &ins->oprs[op2];
1797
1798                 if (c <= 0177) {
1799                     /* pick rfield from operand b (opx) */
1800                     rflags = regflag(opx);
1801                     rfield = nasm_regvals[opx->basereg];
1802                 } else {
1803                     /* rfield is constant */
1804                     rflags = 0;
1805                     rfield = c & 7;
1806                 }
1807
1808                 if (process_ea(opy, &ea_data, bits,
1809                                rfield, rflags, ins) != eat)
1810                     errfunc(ERR_NONFATAL, "invalid effective address");
1811
1812                 p = bytes;
1813                 *p++ = ea_data.modrm;
1814                 if (ea_data.sib_present)
1815                     *p++ = ea_data.sib;
1816
1817                 s = p - bytes;
1818                 out(offset, segment, bytes, OUT_RAWDATA, s, NO_SEG, NO_SEG);
1819
1820                 /*
1821                  * Make sure the address gets the right offset in case
1822                  * the line breaks in the .lst file (BR 1197827)
1823                  */
1824                 offset += s;
1825                 s = 0;
1826
1827                 switch (ea_data.bytes) {
1828                 case 0:
1829                     break;
1830                 case 1:
1831                 case 2:
1832                 case 4:
1833                 case 8:
1834                     /* use compressed displacement, if available */
1835                     data = ea_data.disp8 ? ea_data.disp8 : opy->offset;
1836                     s += ea_data.bytes;
1837                     if (ea_data.rip) {
1838                         if (opy->segment == segment) {
1839                             data -= insn_end;
1840                             if (overflow_signed(data, ea_data.bytes))
1841                                 warn_overflow(ERR_PASS2, ea_data.bytes);
1842                             out(offset, segment, &data, OUT_ADDRESS,
1843                                 ea_data.bytes, NO_SEG, NO_SEG);
1844                         } else {
1845                             /* overflow check in output/linker? */
1846                             out(offset, segment, &data,        OUT_REL4ADR,
1847                                 insn_end - offset, opy->segment, opy->wrt);
1848                         }
1849                     } else {
1850                         if (overflow_general(data, ins->addr_size >> 3) ||
1851                             signed_bits(data, ins->addr_size) !=
1852                             signed_bits(data, ea_data.bytes * 8))
1853                             warn_overflow(ERR_PASS2, ea_data.bytes);
1854
1855                         out(offset, segment, &data, OUT_ADDRESS,
1856                             ea_data.bytes, opy->segment, opy->wrt);
1857                     }
1858                     break;
1859                 default:
1860                     /* Impossible! */
1861                     errfunc(ERR_PANIC,
1862                             "Invalid amount of bytes (%d) for offset?!",
1863                             ea_data.bytes);
1864                     break;
1865                 }
1866                 offset += s;
1867             }
1868             break;
1869
1870         default:
1871             errfunc(ERR_PANIC, "internal instruction table corrupt"
1872                     ": instruction code \\%o (0x%02X) given", c, c);
1873             break;
1874         }
1875     }
1876 }
1877
1878 static opflags_t regflag(const operand * o)
1879 {
1880     if (!is_register(o->basereg))
1881         errfunc(ERR_PANIC, "invalid operand passed to regflag()");
1882     return nasm_reg_flags[o->basereg];
1883 }
1884
1885 static int32_t regval(const operand * o)
1886 {
1887     if (!is_register(o->basereg))
1888         errfunc(ERR_PANIC, "invalid operand passed to regval()");
1889     return nasm_regvals[o->basereg];
1890 }
1891
1892 static int op_rexflags(const operand * o, int mask)
1893 {
1894     opflags_t flags;
1895     int val;
1896
1897     if (!is_register(o->basereg))
1898         errfunc(ERR_PANIC, "invalid operand passed to op_rexflags()");
1899
1900     flags = nasm_reg_flags[o->basereg];
1901     val = nasm_regvals[o->basereg];
1902
1903     return rexflags(val, flags, mask);
1904 }
1905
1906 static int rexflags(int val, opflags_t flags, int mask)
1907 {
1908     int rex = 0;
1909
1910     if (val >= 0 && (val & 8))
1911         rex |= REX_B|REX_X|REX_R;
1912     if (flags & BITS64)
1913         rex |= REX_W;
1914     if (!(REG_HIGH & ~flags))                   /* AH, CH, DH, BH */
1915         rex |= REX_H;
1916     else if (!(REG8 & ~flags) && val >= 4)      /* SPL, BPL, SIL, DIL */
1917         rex |= REX_P;
1918
1919     return rex & mask;
1920 }
1921
1922 static int evexflags(int val, decoflags_t deco,
1923                      int mask, uint8_t byte)
1924 {
1925     int evex = 0;
1926
1927     switch (byte) {
1928     case 0:
1929         if (val >= 0 && (val & 16))
1930             evex |= (EVEX_P0RP | EVEX_P0X);
1931         break;
1932     case 2:
1933         if (val >= 0 && (val & 16))
1934             evex |= EVEX_P2VP;
1935         if (deco & Z)
1936             evex |= EVEX_P2Z;
1937         if (deco & OPMASK_MASK)
1938             evex |= deco & EVEX_P2AAA;
1939         break;
1940     }
1941     return evex & mask;
1942 }
1943
1944 static int op_evexflags(const operand * o, int mask, uint8_t byte)
1945 {
1946     int val;
1947
1948     if (!is_register(o->basereg))
1949         errfunc(ERR_PANIC, "invalid operand passed to op_evexflags()");
1950
1951     val = nasm_regvals[o->basereg];
1952
1953     return evexflags(val, o->decoflags, mask, byte);
1954 }
1955
1956 static enum match_result find_match(const struct itemplate **tempp,
1957                                     insn *instruction,
1958                                     int32_t segment, int64_t offset, int bits)
1959 {
1960     const struct itemplate *temp;
1961     enum match_result m, merr;
1962     opflags_t xsizeflags[MAX_OPERANDS];
1963     bool opsizemissing = false;
1964     int8_t broadcast = instruction->evex_brerop;
1965     int i;
1966
1967     /* broadcasting uses a different data element size */
1968     for (i = 0; i < instruction->operands; i++)
1969         if (i == broadcast)
1970             xsizeflags[i] = instruction->oprs[i].decoflags & BRSIZE_MASK;
1971         else
1972             xsizeflags[i] = instruction->oprs[i].type & SIZE_MASK;
1973
1974     merr = MERR_INVALOP;
1975
1976     for (temp = nasm_instructions[instruction->opcode];
1977          temp->opcode != I_none; temp++) {
1978         m = matches(temp, instruction, bits);
1979         if (m == MOK_JUMP) {
1980             if (jmp_match(segment, offset, bits, instruction, temp))
1981                 m = MOK_GOOD;
1982             else
1983                 m = MERR_INVALOP;
1984         } else if (m == MERR_OPSIZEMISSING &&
1985                    (temp->flags & IF_SMASK) != IF_SX) {
1986             /*
1987              * Missing operand size and a candidate for fuzzy matching...
1988              */
1989             for (i = 0; i < temp->operands; i++)
1990                 if (i == broadcast)
1991                     xsizeflags[i] |= temp->deco[i] & BRSIZE_MASK;
1992                 else
1993                     xsizeflags[i] |= temp->opd[i] & SIZE_MASK;
1994             opsizemissing = true;
1995         }
1996         if (m > merr)
1997             merr = m;
1998         if (merr == MOK_GOOD)
1999             goto done;
2000     }
2001
2002     /* No match, but see if we can get a fuzzy operand size match... */
2003     if (!opsizemissing)
2004         goto done;
2005
2006     for (i = 0; i < instruction->operands; i++) {
2007         /*
2008          * We ignore extrinsic operand sizes on registers, so we should
2009          * never try to fuzzy-match on them.  This also resolves the case
2010          * when we have e.g. "xmmrm128" in two different positions.
2011          */
2012         if (is_class(REGISTER, instruction->oprs[i].type))
2013             continue;
2014
2015         /* This tests if xsizeflags[i] has more than one bit set */
2016         if ((xsizeflags[i] & (xsizeflags[i]-1)))
2017             goto done;                /* No luck */
2018
2019         if (i == broadcast)
2020             instruction->oprs[i].decoflags |= xsizeflags[i];
2021         else
2022             instruction->oprs[i].type |= xsizeflags[i]; /* Set the size */
2023     }
2024
2025     /* Try matching again... */
2026     for (temp = nasm_instructions[instruction->opcode];
2027          temp->opcode != I_none; temp++) {
2028         m = matches(temp, instruction, bits);
2029         if (m == MOK_JUMP) {
2030             if (jmp_match(segment, offset, bits, instruction, temp))
2031                 m = MOK_GOOD;
2032             else
2033                 m = MERR_INVALOP;
2034         }
2035         if (m > merr)
2036             merr = m;
2037         if (merr == MOK_GOOD)
2038             goto done;
2039     }
2040
2041 done:
2042     *tempp = temp;
2043     return merr;
2044 }
2045
2046 static enum match_result matches(const struct itemplate *itemp,
2047                                  insn *instruction, int bits)
2048 {
2049     opflags_t size[MAX_OPERANDS], asize;
2050     bool opsizemissing = false;
2051     int i, oprs;
2052
2053     /*
2054      * Check the opcode
2055      */
2056     if (itemp->opcode != instruction->opcode)
2057         return MERR_INVALOP;
2058
2059     /*
2060      * Count the operands
2061      */
2062     if (itemp->operands != instruction->operands)
2063         return MERR_INVALOP;
2064
2065     /*
2066      * Is it legal?
2067      */
2068     if (!(optimizing > 0) && (itemp->flags & IF_OPT))
2069         return MERR_INVALOP;
2070
2071     /*
2072      * Check that no spurious colons or TOs are present
2073      */
2074     for (i = 0; i < itemp->operands; i++)
2075         if (instruction->oprs[i].type & ~itemp->opd[i] & (COLON | TO))
2076             return MERR_INVALOP;
2077
2078     /*
2079      * Process size flags
2080      */
2081     switch (itemp->flags & IF_SMASK) {
2082     case IF_SB:
2083         asize = BITS8;
2084         break;
2085     case IF_SW:
2086         asize = BITS16;
2087         break;
2088     case IF_SD:
2089         asize = BITS32;
2090         break;
2091     case IF_SQ:
2092         asize = BITS64;
2093         break;
2094     case IF_SO:
2095         asize = BITS128;
2096         break;
2097     case IF_SY:
2098         asize = BITS256;
2099         break;
2100     case IF_SZ:
2101         asize = BITS512;
2102         break;
2103     case IF_SIZE:
2104         switch (bits) {
2105         case 16:
2106             asize = BITS16;
2107             break;
2108         case 32:
2109             asize = BITS32;
2110             break;
2111         case 64:
2112             asize = BITS64;
2113             break;
2114         default:
2115             asize = 0;
2116             break;
2117         }
2118         break;
2119     default:
2120         asize = 0;
2121         break;
2122     }
2123
2124     if (itemp->flags & IF_ARMASK) {
2125         /* S- flags only apply to a specific operand */
2126         i = ((itemp->flags & IF_ARMASK) >> IF_ARSHFT) - 1;
2127         memset(size, 0, sizeof size);
2128         size[i] = asize;
2129     } else {
2130         /* S- flags apply to all operands */
2131         for (i = 0; i < MAX_OPERANDS; i++)
2132             size[i] = asize;
2133     }
2134
2135     /*
2136      * Check that the operand flags all match up,
2137      * it's a bit tricky so lets be verbose:
2138      *
2139      * 1) Find out the size of operand. If instruction
2140      *    doesn't have one specified -- we're trying to
2141      *    guess it either from template (IF_S* flag) or
2142      *    from code bits.
2143      *
2144      * 2) If template operand do not match the instruction OR
2145      *    template has an operand size specified AND this size differ
2146      *    from which instruction has (perhaps we got it from code bits)
2147      *    we are:
2148      *      a)  Check that only size of instruction and operand is differ
2149      *          other characteristics do match
2150      *      b)  Perhaps it's a register specified in instruction so
2151      *          for such a case we just mark that operand as "size
2152      *          missing" and this will turn on fuzzy operand size
2153      *          logic facility (handled by a caller)
2154      */
2155     for (i = 0; i < itemp->operands; i++) {
2156         opflags_t type = instruction->oprs[i].type;
2157         decoflags_t deco = instruction->oprs[i].decoflags;
2158         if (!(type & SIZE_MASK))
2159             type |= size[i];
2160
2161         if ((itemp->opd[i] & ~type & ~SIZE_MASK) ||
2162             (itemp->deco[i] & deco) != deco) {
2163             return MERR_INVALOP;
2164         } else if ((itemp->opd[i] & SIZE_MASK) &&
2165                    (itemp->opd[i] & SIZE_MASK) != (type & SIZE_MASK)) {
2166             if (type & SIZE_MASK) {
2167                 /*
2168                  * when broadcasting, the element size depends on
2169                  * the instruction type. decorator flag should match.
2170                  */
2171 #define MATCH_BRSZ(bits) (((type & SIZE_MASK) == BITS##bits) &&             \
2172                           ((itemp->deco[i] & BRSIZE_MASK) == BR_BITS##bits))
2173                 if (!((deco & BRDCAST_MASK) &&
2174                       (MATCH_BRSZ(32) || MATCH_BRSZ(64)))) {
2175                     return MERR_INVALOP;
2176                 }
2177             } else if (!is_class(REGISTER, type)) {
2178                 /*
2179                  * Note: we don't honor extrinsic operand sizes for registers,
2180                  * so "missing operand size" for a register should be
2181                  * considered a wildcard match rather than an error.
2182                  */
2183                 opsizemissing = true;
2184             }
2185         } else if (is_register(instruction->oprs[i].basereg) &&
2186                    nasm_regvals[instruction->oprs[i].basereg] >= 16 &&
2187                    !(itemp->flags & IF_AVX512)) {
2188             return MERR_ENCMISMATCH;
2189         }
2190     }
2191
2192     if (opsizemissing)
2193         return MERR_OPSIZEMISSING;
2194
2195     /*
2196      * Check operand sizes
2197      */
2198     if (itemp->flags & (IF_SM | IF_SM2)) {
2199         oprs = (itemp->flags & IF_SM2 ? 2 : itemp->operands);
2200         for (i = 0; i < oprs; i++) {
2201             asize = itemp->opd[i] & SIZE_MASK;
2202             if (asize) {
2203                 for (i = 0; i < oprs; i++)
2204                     size[i] = asize;
2205                 break;
2206             }
2207         }
2208     } else {
2209         oprs = itemp->operands;
2210     }
2211
2212     for (i = 0; i < itemp->operands; i++) {
2213         if (!(itemp->opd[i] & SIZE_MASK) &&
2214             (instruction->oprs[i].type & SIZE_MASK & ~size[i]))
2215             return MERR_OPSIZEMISMATCH;
2216     }
2217
2218     /*
2219      * Check template is okay at the set cpu level
2220      */
2221     if (((itemp->flags & IF_PLEVEL) > cpu))
2222         return MERR_BADCPU;
2223
2224     /*
2225      * Verify the appropriate long mode flag.
2226      */
2227     if ((itemp->flags & (bits == 64 ? IF_NOLONG : IF_LONG)))
2228         return MERR_BADMODE;
2229
2230     /*
2231      * If we have a HLE prefix, look for the NOHLE flag
2232      */
2233     if ((itemp->flags & IF_NOHLE) &&
2234         (has_prefix(instruction, PPS_REP, P_XACQUIRE) ||
2235          has_prefix(instruction, PPS_REP, P_XRELEASE)))
2236         return MERR_BADHLE;
2237
2238     /*
2239      * Check if special handling needed for Jumps
2240      */
2241     if ((itemp->code[0] & ~1) == 0370)
2242         return MOK_JUMP;
2243
2244     /*
2245      * Check if BND prefix is allowed
2246      */
2247     if ((IF_BND & ~itemp->flags) &&
2248         has_prefix(instruction, PPS_REP, P_BND))
2249         return MERR_BADBND;
2250
2251     return MOK_GOOD;
2252 }
2253
2254 /*
2255  * Check if offset is a multiple of N with corresponding tuple type
2256  * if Disp8*N is available, compressed displacement is stored in compdisp
2257  */
2258 static bool is_disp8n(operand *input, insn *ins, int8_t *compdisp)
2259 {
2260     const uint8_t fv_n[2][2][VLMAX] = {{{16, 32, 64}, {4, 4, 4}},
2261                                        {{16, 32, 64}, {8, 8, 8}}};
2262     const uint8_t hv_n[2][VLMAX]    =  {{8, 16, 32}, {4, 4, 4}};
2263     const uint8_t dup_n[VLMAX]      =   {8, 32, 64};
2264
2265     bool evex_b           = input->decoflags & BRDCAST_MASK;
2266     enum ttypes   tuple   = ins->evex_tuple;
2267     /* vex_wlp composed as [wwllpp] */
2268     enum vectlens vectlen = (ins->vex_wlp & 0x0c) >> 2;
2269     /* wig(=2) is treated as w0(=0) */
2270     bool evex_w           = (ins->vex_wlp & 0x10) >> 4;
2271     int32_t off           = input->offset;
2272     uint8_t n = 0;
2273     int32_t disp8;
2274
2275     switch(tuple) {
2276     case FV:
2277         n = fv_n[evex_w][evex_b][vectlen];
2278         break;
2279     case HV:
2280         n = hv_n[evex_b][vectlen];
2281         break;
2282
2283     case FVM:
2284         /* 16, 32, 64 for VL 128, 256, 512 respectively*/
2285         n = 1 << (vectlen + 4);
2286         break;
2287     case T1S8:  /* N = 1 */
2288     case T1S16: /* N = 2 */
2289         n = tuple - T1S8 + 1;
2290         break;
2291     case T1S:
2292         /* N = 4 for 32bit, 8 for 64bit */
2293         n = evex_w ? 8 : 4;
2294         break;
2295     case T1F32:
2296     case T1F64:
2297         /* N = 4 for 32bit, 8 for 64bit */
2298         n = (tuple == T1F32 ? 4 : 8);
2299         break;
2300     case T2:
2301     case T4:
2302     case T8:
2303         if (vectlen + 7 <= (evex_w + 5) + (tuple - T2 + 1))
2304             n = 0;
2305         else
2306             n = 1 << (tuple - T2 + evex_w + 3);
2307         break;
2308     case HVM:
2309     case QVM:
2310     case OVM:
2311         n = 1 << (OVM - tuple + vectlen + 1);
2312         break;
2313     case M128:
2314         n = 16;
2315         break;
2316     case DUP:
2317         n = dup_n[vectlen];
2318         break;
2319
2320     default:
2321         break;
2322     }
2323
2324     if (n && !(off & (n - 1))) {
2325         disp8 = off / n;
2326         /* if it fits in Disp8 */
2327         if (disp8 >= -128 && disp8 <= 127) {
2328             *compdisp = disp8;
2329             return true;
2330         }
2331     }
2332
2333     *compdisp = 0;
2334     return false;
2335 }
2336
2337 /*
2338  * Check if ModR/M.mod should/can be 01.
2339  * - EAF_BYTEOFFS is set
2340  * - offset can fit in a byte when EVEX is not used
2341  * - offset can be compressed when EVEX is used
2342  */
2343 #define IS_MOD_01()     (input->eaflags & EAF_BYTEOFFS ||       \
2344                          (o >= -128 && o <= 127 &&              \
2345                           seg == NO_SEG && !forw_ref &&         \
2346                           !(input->eaflags & EAF_WORDOFFS) &&   \
2347                           !(ins->rex & REX_EV)) ||              \
2348                          (ins->rex & REX_EV &&                  \
2349                           is_disp8n(input, ins, &output->disp8)))
2350
2351 static enum ea_type process_ea(operand *input, ea *output, int bits,
2352                                int rfield, opflags_t rflags, insn *ins)
2353 {
2354     bool forw_ref = !!(input->opflags & OPFLAG_UNKNOWN);
2355     int addrbits = ins->addr_size;
2356
2357     output->type    = EA_SCALAR;
2358     output->rip     = false;
2359     output->disp8   = 0;
2360
2361     /* REX flags for the rfield operand */
2362     output->rex     |= rexflags(rfield, rflags, REX_R | REX_P | REX_W | REX_H);
2363     /* EVEX.R' flag for the REG operand */
2364     ins->evex_p[0]  |= evexflags(rfield, 0, EVEX_P0RP, 0);
2365
2366     if (is_class(REGISTER, input->type)) {
2367         /*
2368          * It's a direct register.
2369          */
2370         if (!is_register(input->basereg))
2371             goto err;
2372
2373         if (!is_reg_class(REG_EA, input->basereg))
2374             goto err;
2375
2376         /* broadcasting is not available with a direct register operand. */
2377         if (input->decoflags & BRDCAST_MASK) {
2378             nasm_error(ERR_NONFATAL, "Broadcasting not allowed from a register");
2379             goto err;
2380         }
2381
2382         output->rex         |= op_rexflags(input, REX_B | REX_P | REX_W | REX_H);
2383         ins->evex_p[0]      |= op_evexflags(input, EVEX_P0X, 0);
2384         output->sib_present = false;    /* no SIB necessary */
2385         output->bytes       = 0;        /* no offset necessary either */
2386         output->modrm       = GEN_MODRM(3, rfield, nasm_regvals[input->basereg]);
2387     } else {
2388         /*
2389          * It's a memory reference.
2390          */
2391
2392         /* Embedded rounding or SAE is not available with a mem ref operand. */
2393         if (input->decoflags & (ER | SAE)) {
2394             nasm_error(ERR_NONFATAL,
2395                        "Embedded rounding is available only with reg-reg op.");
2396             return -1;
2397         }
2398
2399         if (input->basereg == -1 &&
2400             (input->indexreg == -1 || input->scale == 0)) {
2401             /*
2402              * It's a pure offset.
2403              */
2404             if (bits == 64 && ((input->type & IP_REL) == IP_REL) &&
2405                 input->segment == NO_SEG) {
2406                 nasm_error(ERR_WARNING | ERR_PASS1, "absolute address can not be RIP-relative");
2407                 input->type &= ~IP_REL;
2408                 input->type |= MEMORY;
2409             }
2410
2411             if (input->eaflags & EAF_BYTEOFFS ||
2412                 (input->eaflags & EAF_WORDOFFS &&
2413                  input->disp_size != (addrbits != 16 ? 32 : 16))) {
2414                 nasm_error(ERR_WARNING | ERR_PASS1, "displacement size ignored on absolute address");
2415             }
2416
2417             if (bits == 64 && (~input->type & IP_REL)) {
2418                 output->sib_present = true;
2419                 output->sib         = GEN_SIB(0, 4, 5);
2420                 output->bytes       = 4;
2421                 output->modrm       = GEN_MODRM(0, rfield, 4);
2422                 output->rip         = false;
2423             } else {
2424                 output->sib_present = false;
2425                 output->bytes       = (addrbits != 16 ? 4 : 2);
2426                 output->modrm       = GEN_MODRM(0, rfield, (addrbits != 16 ? 5 : 6));
2427                 output->rip         = bits == 64;
2428             }
2429         } else {
2430             /*
2431              * It's an indirection.
2432              */
2433             int i = input->indexreg, b = input->basereg, s = input->scale;
2434             int32_t seg = input->segment;
2435             int hb = input->hintbase, ht = input->hinttype;
2436             int t, it, bt;              /* register numbers */
2437             opflags_t x, ix, bx;        /* register flags */
2438
2439             if (s == 0)
2440                 i = -1;         /* make this easy, at least */
2441
2442             if (is_register(i)) {
2443                 it = nasm_regvals[i];
2444                 ix = nasm_reg_flags[i];
2445             } else {
2446                 it = -1;
2447                 ix = 0;
2448             }
2449
2450             if (is_register(b)) {
2451                 bt = nasm_regvals[b];
2452                 bx = nasm_reg_flags[b];
2453             } else {
2454                 bt = -1;
2455                 bx = 0;
2456             }
2457
2458             /* if either one are a vector register... */
2459             if ((ix|bx) & (XMMREG|YMMREG|ZMMREG) & ~REG_EA) {
2460                 opflags_t sok = BITS32 | BITS64;
2461                 int32_t o = input->offset;
2462                 int mod, scale, index, base;
2463
2464                 /*
2465                  * For a vector SIB, one has to be a vector and the other,
2466                  * if present, a GPR.  The vector must be the index operand.
2467                  */
2468                 if (it == -1 || (bx & (XMMREG|YMMREG|ZMMREG) & ~REG_EA)) {
2469                     if (s == 0)
2470                         s = 1;
2471                     else if (s != 1)
2472                         goto err;
2473
2474                     t = bt, bt = it, it = t;
2475                     x = bx, bx = ix, ix = x;
2476                 }
2477
2478                 if (bt != -1) {
2479                     if (REG_GPR & ~bx)
2480                         goto err;
2481                     if (!(REG64 & ~bx) || !(REG32 & ~bx))
2482                         sok &= bx;
2483                     else
2484                         goto err;
2485                 }
2486
2487                 /*
2488                  * While we're here, ensure the user didn't specify
2489                  * WORD or QWORD
2490                  */
2491                 if (input->disp_size == 16 || input->disp_size == 64)
2492                     goto err;
2493
2494                 if (addrbits == 16 ||
2495                     (addrbits == 32 && !(sok & BITS32)) ||
2496                     (addrbits == 64 && !(sok & BITS64)))
2497                     goto err;
2498
2499                 output->type = ((ix & ZMMREG & ~REG_EA) ? EA_ZMMVSIB
2500                                 : ((ix & YMMREG & ~REG_EA)
2501                                 ? EA_YMMVSIB : EA_XMMVSIB));
2502
2503                 output->rex    |= rexflags(it, ix, REX_X);
2504                 output->rex    |= rexflags(bt, bx, REX_B);
2505                 ins->evex_p[2] |= evexflags(it, 0, EVEX_P2VP, 2);
2506
2507                 index = it & 7; /* it is known to be != -1 */
2508
2509                 switch (s) {
2510                 case 1:
2511                     scale = 0;
2512                     break;
2513                 case 2:
2514                     scale = 1;
2515                     break;
2516                 case 4:
2517                     scale = 2;
2518                     break;
2519                 case 8:
2520                     scale = 3;
2521                     break;
2522                 default:   /* then what the smeg is it? */
2523                     goto err;    /* panic */
2524                 }
2525                 
2526                 if (bt == -1) {
2527                     base = 5;
2528                     mod = 0;
2529                 } else {
2530                     base = (bt & 7);
2531                     if (base != REG_NUM_EBP && o == 0 &&
2532                         seg == NO_SEG && !forw_ref &&
2533                         !(input->eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2534                         mod = 0;
2535                     else if (IS_MOD_01())
2536                         mod = 1;
2537                     else
2538                         mod = 2;
2539                 }
2540
2541                 output->sib_present = true;
2542                 output->bytes       = (bt == -1 || mod == 2 ? 4 : mod);
2543                 output->modrm       = GEN_MODRM(mod, rfield, 4);
2544                 output->sib         = GEN_SIB(scale, index, base);
2545             } else if ((ix|bx) & (BITS32|BITS64)) {
2546                 /*
2547                  * it must be a 32/64-bit memory reference. Firstly we have
2548                  * to check that all registers involved are type E/Rxx.
2549                  */
2550                 opflags_t sok = BITS32 | BITS64;
2551                 int32_t o = input->offset;
2552
2553                 if (it != -1) {
2554                     if (!(REG64 & ~ix) || !(REG32 & ~ix))
2555                         sok &= ix;
2556                     else
2557                         goto err;
2558                 }
2559
2560                 if (bt != -1) {
2561                     if (REG_GPR & ~bx)
2562                         goto err; /* Invalid register */
2563                     if (~sok & bx & SIZE_MASK)
2564                         goto err; /* Invalid size */
2565                     sok &= bx;
2566                 }
2567
2568                 /*
2569                  * While we're here, ensure the user didn't specify
2570                  * WORD or QWORD
2571                  */
2572                 if (input->disp_size == 16 || input->disp_size == 64)
2573                     goto err;
2574
2575                 if (addrbits == 16 ||
2576                     (addrbits == 32 && !(sok & BITS32)) ||
2577                     (addrbits == 64 && !(sok & BITS64)))
2578                     goto err;
2579
2580                 /* now reorganize base/index */
2581                 if (s == 1 && bt != it && bt != -1 && it != -1 &&
2582                     ((hb == b && ht == EAH_NOTBASE) ||
2583                      (hb == i && ht == EAH_MAKEBASE))) {
2584                     /* swap if hints say so */
2585                     t = bt, bt = it, it = t;
2586                     x = bx, bx = ix, ix = x;
2587                 }
2588                 if (bt == it)     /* convert EAX+2*EAX to 3*EAX */
2589                     bt = -1, bx = 0, s++;
2590                 if (bt == -1 && s == 1 && !(hb == i && ht == EAH_NOTBASE)) {
2591                     /* make single reg base, unless hint */
2592                     bt = it, bx = ix, it = -1, ix = 0;
2593                 }
2594                 if (((s == 2 && it != REG_NUM_ESP && !(input->eaflags & EAF_TIMESTWO)) ||
2595                       s == 3 || s == 5 || s == 9) && bt == -1)
2596                     bt = it, bx = ix, s--; /* convert 3*EAX to EAX+2*EAX */
2597                 if (it == -1 && (bt & 7) != REG_NUM_ESP &&
2598                     (input->eaflags & EAF_TIMESTWO))
2599                     it = bt, ix = bx, bt = -1, bx = 0, s = 1;
2600                 /* convert [NOSPLIT EAX] to sib format with 0x0 displacement */
2601                 if (s == 1 && it == REG_NUM_ESP) {
2602                     /* swap ESP into base if scale is 1 */
2603                     t = it, it = bt, bt = t;
2604                     x = ix, ix = bx, bx = x;
2605                 }
2606                 if (it == REG_NUM_ESP ||
2607                     (s != 1 && s != 2 && s != 4 && s != 8 && it != -1))
2608                     goto err;        /* wrong, for various reasons */
2609
2610                 output->rex |= rexflags(it, ix, REX_X);
2611                 output->rex |= rexflags(bt, bx, REX_B);
2612
2613                 if (it == -1 && (bt & 7) != REG_NUM_ESP) {
2614                     /* no SIB needed */
2615                     int mod, rm;
2616
2617                     if (bt == -1) {
2618                         rm = 5;
2619                         mod = 0;
2620                     } else {
2621                         rm = (bt & 7);
2622                         if (rm != REG_NUM_EBP && o == 0 &&
2623                             seg == NO_SEG && !forw_ref &&
2624                             !(input->eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2625                             mod = 0;
2626                         else if (IS_MOD_01())
2627                             mod = 1;
2628                         else
2629                             mod = 2;
2630                     }
2631
2632                     output->sib_present = false;
2633                     output->bytes       = (bt == -1 || mod == 2 ? 4 : mod);
2634                     output->modrm       = GEN_MODRM(mod, rfield, rm);
2635                 } else {
2636                     /* we need a SIB */
2637                     int mod, scale, index, base;
2638
2639                     if (it == -1)
2640                         index = 4, s = 1;
2641                     else
2642                         index = (it & 7);
2643
2644                     switch (s) {
2645                     case 1:
2646                         scale = 0;
2647                         break;
2648                     case 2:
2649                         scale = 1;
2650                         break;
2651                     case 4:
2652                         scale = 2;
2653                         break;
2654                     case 8:
2655                         scale = 3;
2656                         break;
2657                     default:   /* then what the smeg is it? */
2658                         goto err;    /* panic */
2659                     }
2660
2661                     if (bt == -1) {
2662                         base = 5;
2663                         mod = 0;
2664                     } else {
2665                         base = (bt & 7);
2666                         if (base != REG_NUM_EBP && o == 0 &&
2667                             seg == NO_SEG && !forw_ref &&
2668                             !(input->eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2669                             mod = 0;
2670                         else if (IS_MOD_01())
2671                             mod = 1;
2672                         else
2673                             mod = 2;
2674                     }
2675
2676                     output->sib_present = true;
2677                     output->bytes       = (bt == -1 || mod == 2 ? 4 : mod);
2678                     output->modrm       = GEN_MODRM(mod, rfield, 4);
2679                     output->sib         = GEN_SIB(scale, index, base);
2680                 }
2681             } else {            /* it's 16-bit */
2682                 int mod, rm;
2683                 int16_t o = input->offset;
2684
2685                 /* check for 64-bit long mode */
2686                 if (addrbits == 64)
2687                     goto err;
2688
2689                 /* check all registers are BX, BP, SI or DI */
2690                 if ((b != -1 && b != R_BP && b != R_BX && b != R_SI && b != R_DI) ||
2691                     (i != -1 && i != R_BP && i != R_BX && i != R_SI && i != R_DI))
2692                     goto err;
2693
2694                 /* ensure the user didn't specify DWORD/QWORD */
2695                 if (input->disp_size == 32 || input->disp_size == 64)
2696                     goto err;
2697
2698                 if (s != 1 && i != -1)
2699                     goto err;        /* no can do, in 16-bit EA */
2700                 if (b == -1 && i != -1) {
2701                     int tmp = b;
2702                     b = i;
2703                     i = tmp;
2704                 }               /* swap */
2705                 if ((b == R_SI || b == R_DI) && i != -1) {
2706                     int tmp = b;
2707                     b = i;
2708                     i = tmp;
2709                 }
2710                 /* have BX/BP as base, SI/DI index */
2711                 if (b == i)
2712                     goto err;        /* shouldn't ever happen, in theory */
2713                 if (i != -1 && b != -1 &&
2714                     (i == R_BP || i == R_BX || b == R_SI || b == R_DI))
2715                     goto err;        /* invalid combinations */
2716                 if (b == -1)            /* pure offset: handled above */
2717                     goto err;        /* so if it gets to here, panic! */
2718
2719                 rm = -1;
2720                 if (i != -1)
2721                     switch (i * 256 + b) {
2722                     case R_SI * 256 + R_BX:
2723                         rm = 0;
2724                         break;
2725                     case R_DI * 256 + R_BX:
2726                         rm = 1;
2727                         break;
2728                     case R_SI * 256 + R_BP:
2729                         rm = 2;
2730                         break;
2731                     case R_DI * 256 + R_BP:
2732                         rm = 3;
2733                         break;
2734                 } else
2735                     switch (b) {
2736                     case R_SI:
2737                         rm = 4;
2738                         break;
2739                     case R_DI:
2740                         rm = 5;
2741                         break;
2742                     case R_BP:
2743                         rm = 6;
2744                         break;
2745                     case R_BX:
2746                         rm = 7;
2747                         break;
2748                     }
2749                 if (rm == -1)           /* can't happen, in theory */
2750                     goto err;        /* so panic if it does */
2751
2752                 if (o == 0 && seg == NO_SEG && !forw_ref && rm != 6 &&
2753                     !(input->eaflags & (EAF_BYTEOFFS | EAF_WORDOFFS)))
2754                     mod = 0;
2755                 else if (IS_MOD_01())
2756                     mod = 1;
2757                 else
2758                     mod = 2;
2759
2760                 output->sib_present = false;    /* no SIB - it's 16-bit */
2761                 output->bytes       = mod;      /* bytes of offset needed */
2762                 output->modrm       = GEN_MODRM(mod, rfield, rm);
2763             }
2764         }
2765     }
2766
2767     output->size = 1 + output->sib_present + output->bytes;
2768     return output->type;
2769
2770 err:
2771     return output->type = EA_INVALID;
2772 }
2773
2774 static void add_asp(insn *ins, int addrbits)
2775 {
2776     int j, valid;
2777     int defdisp;
2778
2779     valid = (addrbits == 64) ? 64|32 : 32|16;
2780
2781     switch (ins->prefixes[PPS_ASIZE]) {
2782     case P_A16:
2783         valid &= 16;
2784         break;
2785     case P_A32:
2786         valid &= 32;
2787         break;
2788     case P_A64:
2789         valid &= 64;
2790         break;
2791     case P_ASP:
2792         valid &= (addrbits == 32) ? 16 : 32;
2793         break;
2794     default:
2795         break;
2796     }
2797
2798     for (j = 0; j < ins->operands; j++) {
2799         if (is_class(MEMORY, ins->oprs[j].type)) {
2800             opflags_t i, b;
2801
2802             /* Verify as Register */
2803             if (!is_register(ins->oprs[j].indexreg))
2804                 i = 0;
2805             else
2806                 i = nasm_reg_flags[ins->oprs[j].indexreg];
2807
2808             /* Verify as Register */
2809             if (!is_register(ins->oprs[j].basereg))
2810                 b = 0;
2811             else
2812                 b = nasm_reg_flags[ins->oprs[j].basereg];
2813
2814             if (ins->oprs[j].scale == 0)
2815                 i = 0;
2816
2817             if (!i && !b) {
2818                 int ds = ins->oprs[j].disp_size;
2819                 if ((addrbits != 64 && ds > 8) ||
2820                     (addrbits == 64 && ds == 16))
2821                     valid &= ds;
2822             } else {
2823                 if (!(REG16 & ~b))
2824                     valid &= 16;
2825                 if (!(REG32 & ~b))
2826                     valid &= 32;
2827                 if (!(REG64 & ~b))
2828                     valid &= 64;
2829
2830                 if (!(REG16 & ~i))
2831                     valid &= 16;
2832                 if (!(REG32 & ~i))
2833                     valid &= 32;
2834                 if (!(REG64 & ~i))
2835                     valid &= 64;
2836             }
2837         }
2838     }
2839
2840     if (valid & addrbits) {
2841         ins->addr_size = addrbits;
2842     } else if (valid & ((addrbits == 32) ? 16 : 32)) {
2843         /* Add an address size prefix */
2844         ins->prefixes[PPS_ASIZE] = (addrbits == 32) ? P_A16 : P_A32;;
2845         ins->addr_size = (addrbits == 32) ? 16 : 32;
2846     } else {
2847         /* Impossible... */
2848         errfunc(ERR_NONFATAL, "impossible combination of address sizes");
2849         ins->addr_size = addrbits; /* Error recovery */
2850     }
2851
2852     defdisp = ins->addr_size == 16 ? 16 : 32;
2853
2854     for (j = 0; j < ins->operands; j++) {
2855         if (!(MEM_OFFS & ~ins->oprs[j].type) &&
2856             (ins->oprs[j].disp_size ? ins->oprs[j].disp_size : defdisp) != ins->addr_size) {
2857             /*
2858              * mem_offs sizes must match the address size; if not,
2859              * strip the MEM_OFFS bit and match only EA instructions
2860              */
2861             ins->oprs[j].type &= ~(MEM_OFFS & ~MEMORY);
2862         }
2863     }
2864 }