[AMDGPU] Check for immediate SrcC in mfma in AsmParser
[llvm-core.git] / lib / Target / X86 / Disassembler / X86DisassemblerDecoder.cpp
bloba241362a271d38dac600a5a44fee584c23ad0bd9
1 //===-- X86DisassemblerDecoder.cpp - Disassembler decoder -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is part of the X86 Disassembler.
10 // It contains the implementation of the instruction decoder.
11 // Documentation for the disassembler can be found in X86Disassembler.h.
13 //===----------------------------------------------------------------------===//
15 #include <cstdarg> /* for va_*() */
16 #include <cstdio> /* for vsnprintf() */
17 #include <cstdlib> /* for exit() */
18 #include <cstring> /* for memset() */
20 #include "X86DisassemblerDecoder.h"
22 using namespace llvm::X86Disassembler;
24 /// Specifies whether a ModR/M byte is needed and (if so) which
25 /// instruction each possible value of the ModR/M byte corresponds to. Once
26 /// this information is known, we have narrowed down to a single instruction.
27 struct ModRMDecision {
28 uint8_t modrm_type;
29 uint16_t instructionIDs;
32 /// Specifies which set of ModR/M->instruction tables to look at
33 /// given a particular opcode.
34 struct OpcodeDecision {
35 ModRMDecision modRMDecisions[256];
38 /// Specifies which opcode->instruction tables to look at given
39 /// a particular context (set of attributes). Since there are many possible
40 /// contexts, the decoder first uses CONTEXTS_SYM to determine which context
41 /// applies given a specific set of attributes. Hence there are only IC_max
42 /// entries in this table, rather than 2^(ATTR_max).
43 struct ContextDecision {
44 OpcodeDecision opcodeDecisions[IC_max];
47 #include "X86GenDisassemblerTables.inc"
49 #ifndef NDEBUG
50 #define debug(s) do { Debug(__FILE__, __LINE__, s); } while (0)
51 #else
52 #define debug(s) do { } while (0)
53 #endif
56 * contextForAttrs - Client for the instruction context table. Takes a set of
57 * attributes and returns the appropriate decode context.
59 * @param attrMask - Attributes, from the enumeration attributeBits.
60 * @return - The InstructionContext to use when looking up an
61 * an instruction with these attributes.
63 static InstructionContext contextForAttrs(uint16_t attrMask) {
64 return static_cast<InstructionContext>(CONTEXTS_SYM[attrMask]);
68 * modRMRequired - Reads the appropriate instruction table to determine whether
69 * the ModR/M byte is required to decode a particular instruction.
71 * @param type - The opcode type (i.e., how many bytes it has).
72 * @param insnContext - The context for the instruction, as returned by
73 * contextForAttrs.
74 * @param opcode - The last byte of the instruction's opcode, not counting
75 * ModR/M extensions and escapes.
76 * @return - true if the ModR/M byte is required, false otherwise.
78 static int modRMRequired(OpcodeType type,
79 InstructionContext insnContext,
80 uint16_t opcode) {
81 const struct ContextDecision* decision = nullptr;
83 switch (type) {
84 case ONEBYTE:
85 decision = &ONEBYTE_SYM;
86 break;
87 case TWOBYTE:
88 decision = &TWOBYTE_SYM;
89 break;
90 case THREEBYTE_38:
91 decision = &THREEBYTE38_SYM;
92 break;
93 case THREEBYTE_3A:
94 decision = &THREEBYTE3A_SYM;
95 break;
96 case XOP8_MAP:
97 decision = &XOP8_MAP_SYM;
98 break;
99 case XOP9_MAP:
100 decision = &XOP9_MAP_SYM;
101 break;
102 case XOPA_MAP:
103 decision = &XOPA_MAP_SYM;
104 break;
105 case THREEDNOW_MAP:
106 decision = &THREEDNOW_MAP_SYM;
107 break;
110 return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].
111 modrm_type != MODRM_ONEENTRY;
115 * decode - Reads the appropriate instruction table to obtain the unique ID of
116 * an instruction.
118 * @param type - See modRMRequired().
119 * @param insnContext - See modRMRequired().
120 * @param opcode - See modRMRequired().
121 * @param modRM - The ModR/M byte if required, or any value if not.
122 * @return - The UID of the instruction, or 0 on failure.
124 static InstrUID decode(OpcodeType type,
125 InstructionContext insnContext,
126 uint8_t opcode,
127 uint8_t modRM) {
128 const struct ModRMDecision* dec = nullptr;
130 switch (type) {
131 case ONEBYTE:
132 dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
133 break;
134 case TWOBYTE:
135 dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
136 break;
137 case THREEBYTE_38:
138 dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
139 break;
140 case THREEBYTE_3A:
141 dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
142 break;
143 case XOP8_MAP:
144 dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
145 break;
146 case XOP9_MAP:
147 dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
148 break;
149 case XOPA_MAP:
150 dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
151 break;
152 case THREEDNOW_MAP:
153 dec = &THREEDNOW_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
154 break;
157 switch (dec->modrm_type) {
158 default:
159 debug("Corrupt table! Unknown modrm_type");
160 return 0;
161 case MODRM_ONEENTRY:
162 return modRMTable[dec->instructionIDs];
163 case MODRM_SPLITRM:
164 if (modFromModRM(modRM) == 0x3)
165 return modRMTable[dec->instructionIDs+1];
166 return modRMTable[dec->instructionIDs];
167 case MODRM_SPLITREG:
168 if (modFromModRM(modRM) == 0x3)
169 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)+8];
170 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
171 case MODRM_SPLITMISC:
172 if (modFromModRM(modRM) == 0x3)
173 return modRMTable[dec->instructionIDs+(modRM & 0x3f)+8];
174 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
175 case MODRM_FULL:
176 return modRMTable[dec->instructionIDs+modRM];
181 * specifierForUID - Given a UID, returns the name and operand specification for
182 * that instruction.
184 * @param uid - The unique ID for the instruction. This should be returned by
185 * decode(); specifierForUID will not check bounds.
186 * @return - A pointer to the specification for that instruction.
188 static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
189 return &INSTRUCTIONS_SYM[uid];
193 * consumeByte - Uses the reader function provided by the user to consume one
194 * byte from the instruction's memory and advance the cursor.
196 * @param insn - The instruction with the reader function to use. The cursor
197 * for this instruction is advanced.
198 * @param byte - A pointer to a pre-allocated memory buffer to be populated
199 * with the data read.
200 * @return - 0 if the read was successful; nonzero otherwise.
202 static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
203 int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
205 if (!ret)
206 ++(insn->readerCursor);
208 return ret;
212 * lookAtByte - Like consumeByte, but does not advance the cursor.
214 * @param insn - See consumeByte().
215 * @param byte - See consumeByte().
216 * @return - See consumeByte().
218 static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
219 return insn->reader(insn->readerArg, byte, insn->readerCursor);
222 static void unconsumeByte(struct InternalInstruction* insn) {
223 insn->readerCursor--;
226 #define CONSUME_FUNC(name, type) \
227 static int name(struct InternalInstruction* insn, type* ptr) { \
228 type combined = 0; \
229 unsigned offset; \
230 for (offset = 0; offset < sizeof(type); ++offset) { \
231 uint8_t byte; \
232 int ret = insn->reader(insn->readerArg, \
233 &byte, \
234 insn->readerCursor + offset); \
235 if (ret) \
236 return ret; \
237 combined = combined | ((uint64_t)byte << (offset * 8)); \
239 *ptr = combined; \
240 insn->readerCursor += sizeof(type); \
241 return 0; \
245 * consume* - Use the reader function provided by the user to consume data
246 * values of various sizes from the instruction's memory and advance the
247 * cursor appropriately. These readers perform endian conversion.
249 * @param insn - See consumeByte().
250 * @param ptr - A pointer to a pre-allocated memory of appropriate size to
251 * be populated with the data read.
252 * @return - See consumeByte().
254 CONSUME_FUNC(consumeInt8, int8_t)
255 CONSUME_FUNC(consumeInt16, int16_t)
256 CONSUME_FUNC(consumeInt32, int32_t)
257 CONSUME_FUNC(consumeUInt16, uint16_t)
258 CONSUME_FUNC(consumeUInt32, uint32_t)
259 CONSUME_FUNC(consumeUInt64, uint64_t)
262 * dbgprintf - Uses the logging function provided by the user to log a single
263 * message, typically without a carriage-return.
265 * @param insn - The instruction containing the logging function.
266 * @param format - See printf().
267 * @param ... - See printf().
269 static void dbgprintf(struct InternalInstruction* insn,
270 const char* format,
271 ...) {
272 char buffer[256];
273 va_list ap;
275 if (!insn->dlog)
276 return;
278 va_start(ap, format);
279 (void)vsnprintf(buffer, sizeof(buffer), format, ap);
280 va_end(ap);
282 insn->dlog(insn->dlogArg, buffer);
285 static bool isREX(struct InternalInstruction *insn, uint8_t prefix) {
286 if (insn->mode == MODE_64BIT)
287 return prefix >= 0x40 && prefix <= 0x4f;
288 return false;
292 * setPrefixPresent - Marks that a particular prefix is present as mandatory
294 * @param insn - The instruction to be marked as having the prefix.
295 * @param prefix - The prefix that is present.
297 static void setPrefixPresent(struct InternalInstruction *insn, uint8_t prefix) {
298 uint8_t nextByte;
299 switch (prefix) {
300 case 0xf0:
301 insn->hasLockPrefix = true;
302 break;
303 case 0xf2:
304 case 0xf3:
305 if (lookAtByte(insn, &nextByte))
306 break;
307 // TODO:
308 // 1. There could be several 0x66
309 // 2. if (nextByte == 0x66) and nextNextByte != 0x0f then
310 // it's not mandatory prefix
311 // 3. if (nextByte >= 0x40 && nextByte <= 0x4f) it's REX and we need
312 // 0x0f exactly after it to be mandatory prefix
313 if (isREX(insn, nextByte) || nextByte == 0x0f || nextByte == 0x66)
314 // The last of 0xf2 /0xf3 is mandatory prefix
315 insn->mandatoryPrefix = prefix;
316 insn->repeatPrefix = prefix;
317 break;
318 case 0x66:
319 if (lookAtByte(insn, &nextByte))
320 break;
321 // 0x66 can't overwrite existing mandatory prefix and should be ignored
322 if (!insn->mandatoryPrefix && (nextByte == 0x0f || isREX(insn, nextByte)))
323 insn->mandatoryPrefix = prefix;
324 break;
329 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
330 * instruction as having them. Also sets the instruction's default operand,
331 * address, and other relevant data sizes to report operands correctly.
333 * @param insn - The instruction whose prefixes are to be read.
334 * @return - 0 if the instruction could be read until the end of the prefix
335 * bytes, and no prefixes conflicted; nonzero otherwise.
337 static int readPrefixes(struct InternalInstruction* insn) {
338 bool isPrefix = true;
339 uint8_t byte = 0;
340 uint8_t nextByte;
342 dbgprintf(insn, "readPrefixes()");
344 while (isPrefix) {
345 /* If we fail reading prefixes, just stop here and let the opcode reader deal with it */
346 if (consumeByte(insn, &byte))
347 break;
350 * If the byte is a LOCK/REP/REPNE prefix and not a part of the opcode, then
351 * break and let it be disassembled as a normal "instruction".
353 if (insn->readerCursor - 1 == insn->startLocation && byte == 0xf0) // LOCK
354 break;
356 if ((byte == 0xf2 || byte == 0xf3) && !lookAtByte(insn, &nextByte)) {
358 * If the byte is 0xf2 or 0xf3, and any of the following conditions are
359 * met:
360 * - it is followed by a LOCK (0xf0) prefix
361 * - it is followed by an xchg instruction
362 * then it should be disassembled as a xacquire/xrelease not repne/rep.
364 if (((nextByte == 0xf0) ||
365 ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90))) {
366 insn->xAcquireRelease = true;
367 if (!(byte == 0xf3 && nextByte == 0x90)) // PAUSE instruction support
368 break;
371 * Also if the byte is 0xf3, and the following condition is met:
372 * - it is followed by a "mov mem, reg" (opcode 0x88/0x89) or
373 * "mov mem, imm" (opcode 0xc6/0xc7) instructions.
374 * then it should be disassembled as an xrelease not rep.
376 if (byte == 0xf3 && (nextByte == 0x88 || nextByte == 0x89 ||
377 nextByte == 0xc6 || nextByte == 0xc7)) {
378 insn->xAcquireRelease = true;
379 break;
381 if (isREX(insn, nextByte)) {
382 uint8_t nnextByte;
383 // Go to REX prefix after the current one
384 if (consumeByte(insn, &nnextByte))
385 return -1;
386 // We should be able to read next byte after REX prefix
387 if (lookAtByte(insn, &nnextByte))
388 return -1;
389 unconsumeByte(insn);
393 switch (byte) {
394 case 0xf0: /* LOCK */
395 case 0xf2: /* REPNE/REPNZ */
396 case 0xf3: /* REP or REPE/REPZ */
397 setPrefixPresent(insn, byte);
398 break;
399 case 0x2e: /* CS segment override -OR- Branch not taken */
400 case 0x36: /* SS segment override -OR- Branch taken */
401 case 0x3e: /* DS segment override */
402 case 0x26: /* ES segment override */
403 case 0x64: /* FS segment override */
404 case 0x65: /* GS segment override */
405 switch (byte) {
406 case 0x2e:
407 insn->segmentOverride = SEG_OVERRIDE_CS;
408 break;
409 case 0x36:
410 insn->segmentOverride = SEG_OVERRIDE_SS;
411 break;
412 case 0x3e:
413 insn->segmentOverride = SEG_OVERRIDE_DS;
414 break;
415 case 0x26:
416 insn->segmentOverride = SEG_OVERRIDE_ES;
417 break;
418 case 0x64:
419 insn->segmentOverride = SEG_OVERRIDE_FS;
420 break;
421 case 0x65:
422 insn->segmentOverride = SEG_OVERRIDE_GS;
423 break;
424 default:
425 debug("Unhandled override");
426 return -1;
428 setPrefixPresent(insn, byte);
429 break;
430 case 0x66: /* Operand-size override */
431 insn->hasOpSize = true;
432 setPrefixPresent(insn, byte);
433 break;
434 case 0x67: /* Address-size override */
435 insn->hasAdSize = true;
436 setPrefixPresent(insn, byte);
437 break;
438 default: /* Not a prefix byte */
439 isPrefix = false;
440 break;
443 if (isPrefix)
444 dbgprintf(insn, "Found prefix 0x%hhx", byte);
447 insn->vectorExtensionType = TYPE_NO_VEX_XOP;
449 if (byte == 0x62) {
450 uint8_t byte1, byte2;
452 if (consumeByte(insn, &byte1)) {
453 dbgprintf(insn, "Couldn't read second byte of EVEX prefix");
454 return -1;
457 if (lookAtByte(insn, &byte2)) {
458 dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
459 return -1;
462 if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) &&
463 ((~byte1 & 0xc) == 0xc) && ((byte2 & 0x4) == 0x4)) {
464 insn->vectorExtensionType = TYPE_EVEX;
465 } else {
466 unconsumeByte(insn); /* unconsume byte1 */
467 unconsumeByte(insn); /* unconsume byte */
470 if (insn->vectorExtensionType == TYPE_EVEX) {
471 insn->vectorExtensionPrefix[0] = byte;
472 insn->vectorExtensionPrefix[1] = byte1;
473 if (consumeByte(insn, &insn->vectorExtensionPrefix[2])) {
474 dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
475 return -1;
477 if (consumeByte(insn, &insn->vectorExtensionPrefix[3])) {
478 dbgprintf(insn, "Couldn't read fourth byte of EVEX prefix");
479 return -1;
482 /* We simulate the REX prefix for simplicity's sake */
483 if (insn->mode == MODE_64BIT) {
484 insn->rexPrefix = 0x40
485 | (wFromEVEX3of4(insn->vectorExtensionPrefix[2]) << 3)
486 | (rFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 2)
487 | (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 1)
488 | (bFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 0);
491 dbgprintf(insn, "Found EVEX prefix 0x%hhx 0x%hhx 0x%hhx 0x%hhx",
492 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
493 insn->vectorExtensionPrefix[2], insn->vectorExtensionPrefix[3]);
495 } else if (byte == 0xc4) {
496 uint8_t byte1;
498 if (lookAtByte(insn, &byte1)) {
499 dbgprintf(insn, "Couldn't read second byte of VEX");
500 return -1;
503 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
504 insn->vectorExtensionType = TYPE_VEX_3B;
505 else
506 unconsumeByte(insn);
508 if (insn->vectorExtensionType == TYPE_VEX_3B) {
509 insn->vectorExtensionPrefix[0] = byte;
510 consumeByte(insn, &insn->vectorExtensionPrefix[1]);
511 consumeByte(insn, &insn->vectorExtensionPrefix[2]);
513 /* We simulate the REX prefix for simplicity's sake */
515 if (insn->mode == MODE_64BIT)
516 insn->rexPrefix = 0x40
517 | (wFromVEX3of3(insn->vectorExtensionPrefix[2]) << 3)
518 | (rFromVEX2of3(insn->vectorExtensionPrefix[1]) << 2)
519 | (xFromVEX2of3(insn->vectorExtensionPrefix[1]) << 1)
520 | (bFromVEX2of3(insn->vectorExtensionPrefix[1]) << 0);
522 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx",
523 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
524 insn->vectorExtensionPrefix[2]);
526 } else if (byte == 0xc5) {
527 uint8_t byte1;
529 if (lookAtByte(insn, &byte1)) {
530 dbgprintf(insn, "Couldn't read second byte of VEX");
531 return -1;
534 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0)
535 insn->vectorExtensionType = TYPE_VEX_2B;
536 else
537 unconsumeByte(insn);
539 if (insn->vectorExtensionType == TYPE_VEX_2B) {
540 insn->vectorExtensionPrefix[0] = byte;
541 consumeByte(insn, &insn->vectorExtensionPrefix[1]);
543 if (insn->mode == MODE_64BIT)
544 insn->rexPrefix = 0x40
545 | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
547 switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
548 default:
549 break;
550 case VEX_PREFIX_66:
551 insn->hasOpSize = true;
552 break;
555 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx",
556 insn->vectorExtensionPrefix[0],
557 insn->vectorExtensionPrefix[1]);
559 } else if (byte == 0x8f) {
560 uint8_t byte1;
562 if (lookAtByte(insn, &byte1)) {
563 dbgprintf(insn, "Couldn't read second byte of XOP");
564 return -1;
567 if ((byte1 & 0x38) != 0x0) /* 0 in these 3 bits is a POP instruction. */
568 insn->vectorExtensionType = TYPE_XOP;
569 else
570 unconsumeByte(insn);
572 if (insn->vectorExtensionType == TYPE_XOP) {
573 insn->vectorExtensionPrefix[0] = byte;
574 consumeByte(insn, &insn->vectorExtensionPrefix[1]);
575 consumeByte(insn, &insn->vectorExtensionPrefix[2]);
577 /* We simulate the REX prefix for simplicity's sake */
579 if (insn->mode == MODE_64BIT)
580 insn->rexPrefix = 0x40
581 | (wFromXOP3of3(insn->vectorExtensionPrefix[2]) << 3)
582 | (rFromXOP2of3(insn->vectorExtensionPrefix[1]) << 2)
583 | (xFromXOP2of3(insn->vectorExtensionPrefix[1]) << 1)
584 | (bFromXOP2of3(insn->vectorExtensionPrefix[1]) << 0);
586 switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
587 default:
588 break;
589 case VEX_PREFIX_66:
590 insn->hasOpSize = true;
591 break;
594 dbgprintf(insn, "Found XOP prefix 0x%hhx 0x%hhx 0x%hhx",
595 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
596 insn->vectorExtensionPrefix[2]);
598 } else if (isREX(insn, byte)) {
599 if (lookAtByte(insn, &nextByte))
600 return -1;
601 insn->rexPrefix = byte;
602 dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
603 } else
604 unconsumeByte(insn);
606 if (insn->mode == MODE_16BIT) {
607 insn->registerSize = (insn->hasOpSize ? 4 : 2);
608 insn->addressSize = (insn->hasAdSize ? 4 : 2);
609 insn->displacementSize = (insn->hasAdSize ? 4 : 2);
610 insn->immediateSize = (insn->hasOpSize ? 4 : 2);
611 } else if (insn->mode == MODE_32BIT) {
612 insn->registerSize = (insn->hasOpSize ? 2 : 4);
613 insn->addressSize = (insn->hasAdSize ? 2 : 4);
614 insn->displacementSize = (insn->hasAdSize ? 2 : 4);
615 insn->immediateSize = (insn->hasOpSize ? 2 : 4);
616 } else if (insn->mode == MODE_64BIT) {
617 if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
618 insn->registerSize = 8;
619 insn->addressSize = (insn->hasAdSize ? 4 : 8);
620 insn->displacementSize = 4;
621 insn->immediateSize = 4;
622 } else {
623 insn->registerSize = (insn->hasOpSize ? 2 : 4);
624 insn->addressSize = (insn->hasAdSize ? 4 : 8);
625 insn->displacementSize = (insn->hasOpSize ? 2 : 4);
626 insn->immediateSize = (insn->hasOpSize ? 2 : 4);
630 return 0;
633 static int readModRM(struct InternalInstruction* insn);
636 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
637 * extended or escape opcodes).
639 * @param insn - The instruction whose opcode is to be read.
640 * @return - 0 if the opcode could be read successfully; nonzero otherwise.
642 static int readOpcode(struct InternalInstruction* insn) {
643 /* Determine the length of the primary opcode */
645 uint8_t current;
647 dbgprintf(insn, "readOpcode()");
649 insn->opcodeType = ONEBYTE;
651 if (insn->vectorExtensionType == TYPE_EVEX) {
652 switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
653 default:
654 dbgprintf(insn, "Unhandled mm field for instruction (0x%hhx)",
655 mmFromEVEX2of4(insn->vectorExtensionPrefix[1]));
656 return -1;
657 case VEX_LOB_0F:
658 insn->opcodeType = TWOBYTE;
659 return consumeByte(insn, &insn->opcode);
660 case VEX_LOB_0F38:
661 insn->opcodeType = THREEBYTE_38;
662 return consumeByte(insn, &insn->opcode);
663 case VEX_LOB_0F3A:
664 insn->opcodeType = THREEBYTE_3A;
665 return consumeByte(insn, &insn->opcode);
667 } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
668 switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
669 default:
670 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
671 mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
672 return -1;
673 case VEX_LOB_0F:
674 insn->opcodeType = TWOBYTE;
675 return consumeByte(insn, &insn->opcode);
676 case VEX_LOB_0F38:
677 insn->opcodeType = THREEBYTE_38;
678 return consumeByte(insn, &insn->opcode);
679 case VEX_LOB_0F3A:
680 insn->opcodeType = THREEBYTE_3A;
681 return consumeByte(insn, &insn->opcode);
683 } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
684 insn->opcodeType = TWOBYTE;
685 return consumeByte(insn, &insn->opcode);
686 } else if (insn->vectorExtensionType == TYPE_XOP) {
687 switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
688 default:
689 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
690 mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
691 return -1;
692 case XOP_MAP_SELECT_8:
693 insn->opcodeType = XOP8_MAP;
694 return consumeByte(insn, &insn->opcode);
695 case XOP_MAP_SELECT_9:
696 insn->opcodeType = XOP9_MAP;
697 return consumeByte(insn, &insn->opcode);
698 case XOP_MAP_SELECT_A:
699 insn->opcodeType = XOPA_MAP;
700 return consumeByte(insn, &insn->opcode);
704 if (consumeByte(insn, &current))
705 return -1;
707 if (current == 0x0f) {
708 dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
710 if (consumeByte(insn, &current))
711 return -1;
713 if (current == 0x38) {
714 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
716 if (consumeByte(insn, &current))
717 return -1;
719 insn->opcodeType = THREEBYTE_38;
720 } else if (current == 0x3a) {
721 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
723 if (consumeByte(insn, &current))
724 return -1;
726 insn->opcodeType = THREEBYTE_3A;
727 } else if (current == 0x0f) {
728 dbgprintf(insn, "Found a 3dnow escape prefix (0x%hhx)", current);
730 // Consume operands before the opcode to comply with the 3DNow encoding
731 if (readModRM(insn))
732 return -1;
734 if (consumeByte(insn, &current))
735 return -1;
737 insn->opcodeType = THREEDNOW_MAP;
738 } else {
739 dbgprintf(insn, "Didn't find a three-byte escape prefix");
741 insn->opcodeType = TWOBYTE;
743 } else if (insn->mandatoryPrefix)
744 // The opcode with mandatory prefix must start with opcode escape.
745 // If not it's legacy repeat prefix
746 insn->mandatoryPrefix = 0;
749 * At this point we have consumed the full opcode.
750 * Anything we consume from here on must be unconsumed.
753 insn->opcode = current;
755 return 0;
759 * getIDWithAttrMask - Determines the ID of an instruction, consuming
760 * the ModR/M byte as appropriate for extended and escape opcodes,
761 * and using a supplied attribute mask.
763 * @param instructionID - A pointer whose target is filled in with the ID of the
764 * instruction.
765 * @param insn - The instruction whose ID is to be determined.
766 * @param attrMask - The attribute mask to search.
767 * @return - 0 if the ModR/M could be read when needed or was not
768 * needed; nonzero otherwise.
770 static int getIDWithAttrMask(uint16_t* instructionID,
771 struct InternalInstruction* insn,
772 uint16_t attrMask) {
773 bool hasModRMExtension;
775 InstructionContext instructionClass = contextForAttrs(attrMask);
777 hasModRMExtension = modRMRequired(insn->opcodeType,
778 instructionClass,
779 insn->opcode);
781 if (hasModRMExtension) {
782 if (readModRM(insn))
783 return -1;
785 *instructionID = decode(insn->opcodeType,
786 instructionClass,
787 insn->opcode,
788 insn->modRM);
789 } else {
790 *instructionID = decode(insn->opcodeType,
791 instructionClass,
792 insn->opcode,
796 return 0;
800 * is16BitEquivalent - Determines whether two instruction names refer to
801 * equivalent instructions but one is 16-bit whereas the other is not.
803 * @param orig - The instruction that is not 16-bit
804 * @param equiv - The instruction that is 16-bit
806 static bool is16BitEquivalent(const char *orig, const char *equiv) {
807 off_t i;
809 for (i = 0;; i++) {
810 if (orig[i] == '\0' && equiv[i] == '\0')
811 return true;
812 if (orig[i] == '\0' || equiv[i] == '\0')
813 return false;
814 if (orig[i] != equiv[i]) {
815 if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
816 continue;
817 if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
818 continue;
819 if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
820 continue;
821 return false;
827 * is64Bit - Determines whether this instruction is a 64-bit instruction.
829 * @param name - The instruction that is not 16-bit
831 static bool is64Bit(const char *name) {
832 off_t i;
834 for (i = 0;; ++i) {
835 if (name[i] == '\0')
836 return false;
837 if (name[i] == '6' && name[i+1] == '4')
838 return true;
843 * getID - Determines the ID of an instruction, consuming the ModR/M byte as
844 * appropriate for extended and escape opcodes. Determines the attributes and
845 * context for the instruction before doing so.
847 * @param insn - The instruction whose ID is to be determined.
848 * @return - 0 if the ModR/M could be read when needed or was not needed;
849 * nonzero otherwise.
851 static int getID(struct InternalInstruction* insn, const void *miiArg) {
852 uint16_t attrMask;
853 uint16_t instructionID;
855 dbgprintf(insn, "getID()");
857 attrMask = ATTR_NONE;
859 if (insn->mode == MODE_64BIT)
860 attrMask |= ATTR_64BIT;
862 if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
863 attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
865 if (insn->vectorExtensionType == TYPE_EVEX) {
866 switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
867 case VEX_PREFIX_66:
868 attrMask |= ATTR_OPSIZE;
869 break;
870 case VEX_PREFIX_F3:
871 attrMask |= ATTR_XS;
872 break;
873 case VEX_PREFIX_F2:
874 attrMask |= ATTR_XD;
875 break;
878 if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
879 attrMask |= ATTR_EVEXKZ;
880 if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
881 attrMask |= ATTR_EVEXB;
882 if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
883 attrMask |= ATTR_EVEXK;
884 if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
885 attrMask |= ATTR_VEXL;
886 if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
887 attrMask |= ATTR_EVEXL2;
888 } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
889 switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
890 case VEX_PREFIX_66:
891 attrMask |= ATTR_OPSIZE;
892 break;
893 case VEX_PREFIX_F3:
894 attrMask |= ATTR_XS;
895 break;
896 case VEX_PREFIX_F2:
897 attrMask |= ATTR_XD;
898 break;
901 if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
902 attrMask |= ATTR_VEXL;
903 } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
904 switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
905 case VEX_PREFIX_66:
906 attrMask |= ATTR_OPSIZE;
907 break;
908 case VEX_PREFIX_F3:
909 attrMask |= ATTR_XS;
910 break;
911 case VEX_PREFIX_F2:
912 attrMask |= ATTR_XD;
913 break;
916 if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
917 attrMask |= ATTR_VEXL;
918 } else if (insn->vectorExtensionType == TYPE_XOP) {
919 switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
920 case VEX_PREFIX_66:
921 attrMask |= ATTR_OPSIZE;
922 break;
923 case VEX_PREFIX_F3:
924 attrMask |= ATTR_XS;
925 break;
926 case VEX_PREFIX_F2:
927 attrMask |= ATTR_XD;
928 break;
931 if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
932 attrMask |= ATTR_VEXL;
933 } else {
934 return -1;
936 } else if (!insn->mandatoryPrefix) {
937 // If we don't have mandatory prefix we should use legacy prefixes here
938 if (insn->hasOpSize && (insn->mode != MODE_16BIT))
939 attrMask |= ATTR_OPSIZE;
940 if (insn->hasAdSize)
941 attrMask |= ATTR_ADSIZE;
942 if (insn->opcodeType == ONEBYTE) {
943 if (insn->repeatPrefix == 0xf3 && (insn->opcode == 0x90))
944 // Special support for PAUSE
945 attrMask |= ATTR_XS;
946 } else {
947 if (insn->repeatPrefix == 0xf2)
948 attrMask |= ATTR_XD;
949 else if (insn->repeatPrefix == 0xf3)
950 attrMask |= ATTR_XS;
952 } else {
953 switch (insn->mandatoryPrefix) {
954 case 0xf2:
955 attrMask |= ATTR_XD;
956 break;
957 case 0xf3:
958 attrMask |= ATTR_XS;
959 break;
960 case 0x66:
961 if (insn->mode != MODE_16BIT)
962 attrMask |= ATTR_OPSIZE;
963 break;
964 case 0x67:
965 attrMask |= ATTR_ADSIZE;
966 break;
971 if (insn->rexPrefix & 0x08) {
972 attrMask |= ATTR_REXW;
973 attrMask &= ~ATTR_ADSIZE;
977 * JCXZ/JECXZ need special handling for 16-bit mode because the meaning
978 * of the AdSize prefix is inverted w.r.t. 32-bit mode.
980 if (insn->mode == MODE_16BIT && insn->opcodeType == ONEBYTE &&
981 insn->opcode == 0xE3)
982 attrMask ^= ATTR_ADSIZE;
984 // If we're in 16-bit mode and this is one of the relative jumps and opsize
985 // prefix isn't present, we need to force the opsize attribute since the
986 // prefix is inverted relative to 32-bit mode.
987 if (insn->mode == MODE_16BIT && !insn->hasOpSize &&
988 insn->opcodeType == ONEBYTE &&
989 (insn->opcode == 0xE8 || insn->opcode == 0xE9))
990 attrMask |= ATTR_OPSIZE;
992 if (insn->mode == MODE_16BIT && !insn->hasOpSize &&
993 insn->opcodeType == TWOBYTE &&
994 insn->opcode >= 0x80 && insn->opcode <= 0x8F)
995 attrMask |= ATTR_OPSIZE;
997 if (getIDWithAttrMask(&instructionID, insn, attrMask))
998 return -1;
1000 /* The following clauses compensate for limitations of the tables. */
1002 if (insn->mode != MODE_64BIT &&
1003 insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1005 * The tables can't distinquish between cases where the W-bit is used to
1006 * select register size and cases where its a required part of the opcode.
1008 if ((insn->vectorExtensionType == TYPE_EVEX &&
1009 wFromEVEX3of4(insn->vectorExtensionPrefix[2])) ||
1010 (insn->vectorExtensionType == TYPE_VEX_3B &&
1011 wFromVEX3of3(insn->vectorExtensionPrefix[2])) ||
1012 (insn->vectorExtensionType == TYPE_XOP &&
1013 wFromXOP3of3(insn->vectorExtensionPrefix[2]))) {
1015 uint16_t instructionIDWithREXW;
1016 if (getIDWithAttrMask(&instructionIDWithREXW,
1017 insn, attrMask | ATTR_REXW)) {
1018 insn->instructionID = instructionID;
1019 insn->spec = specifierForUID(instructionID);
1020 return 0;
1023 auto SpecName = GetInstrName(instructionIDWithREXW, miiArg);
1024 // If not a 64-bit instruction. Switch the opcode.
1025 if (!is64Bit(SpecName.data())) {
1026 insn->instructionID = instructionIDWithREXW;
1027 insn->spec = specifierForUID(instructionIDWithREXW);
1028 return 0;
1034 * Absolute moves, umonitor, and movdir64b need special handling.
1035 * -For 16-bit mode because the meaning of the AdSize and OpSize prefixes are
1036 * inverted w.r.t.
1037 * -For 32-bit mode we need to ensure the ADSIZE prefix is observed in
1038 * any position.
1040 if ((insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0)) ||
1041 (insn->opcodeType == TWOBYTE && (insn->opcode == 0xAE)) ||
1042 (insn->opcodeType == THREEBYTE_38 && insn->opcode == 0xF8)) {
1043 /* Make sure we observed the prefixes in any position. */
1044 if (insn->hasAdSize)
1045 attrMask |= ATTR_ADSIZE;
1046 if (insn->hasOpSize)
1047 attrMask |= ATTR_OPSIZE;
1049 /* In 16-bit, invert the attributes. */
1050 if (insn->mode == MODE_16BIT) {
1051 attrMask ^= ATTR_ADSIZE;
1053 /* The OpSize attribute is only valid with the absolute moves. */
1054 if (insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0))
1055 attrMask ^= ATTR_OPSIZE;
1058 if (getIDWithAttrMask(&instructionID, insn, attrMask))
1059 return -1;
1061 insn->instructionID = instructionID;
1062 insn->spec = specifierForUID(instructionID);
1063 return 0;
1066 if ((insn->mode == MODE_16BIT || insn->hasOpSize) &&
1067 !(attrMask & ATTR_OPSIZE)) {
1069 * The instruction tables make no distinction between instructions that
1070 * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
1071 * particular spot (i.e., many MMX operations). In general we're
1072 * conservative, but in the specific case where OpSize is present but not
1073 * in the right place we check if there's a 16-bit operation.
1076 const struct InstructionSpecifier *spec;
1077 uint16_t instructionIDWithOpsize;
1078 llvm::StringRef specName, specWithOpSizeName;
1080 spec = specifierForUID(instructionID);
1082 if (getIDWithAttrMask(&instructionIDWithOpsize,
1083 insn,
1084 attrMask | ATTR_OPSIZE)) {
1086 * ModRM required with OpSize but not present; give up and return version
1087 * without OpSize set
1090 insn->instructionID = instructionID;
1091 insn->spec = spec;
1092 return 0;
1095 specName = GetInstrName(instructionID, miiArg);
1096 specWithOpSizeName = GetInstrName(instructionIDWithOpsize, miiArg);
1098 if (is16BitEquivalent(specName.data(), specWithOpSizeName.data()) &&
1099 (insn->mode == MODE_16BIT) ^ insn->hasOpSize) {
1100 insn->instructionID = instructionIDWithOpsize;
1101 insn->spec = specifierForUID(instructionIDWithOpsize);
1102 } else {
1103 insn->instructionID = instructionID;
1104 insn->spec = spec;
1106 return 0;
1109 if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1110 insn->rexPrefix & 0x01) {
1112 * NOOP shouldn't decode as NOOP if REX.b is set. Instead
1113 * it should decode as XCHG %r8, %eax.
1116 const struct InstructionSpecifier *spec;
1117 uint16_t instructionIDWithNewOpcode;
1118 const struct InstructionSpecifier *specWithNewOpcode;
1120 spec = specifierForUID(instructionID);
1122 /* Borrow opcode from one of the other XCHGar opcodes */
1123 insn->opcode = 0x91;
1125 if (getIDWithAttrMask(&instructionIDWithNewOpcode,
1126 insn,
1127 attrMask)) {
1128 insn->opcode = 0x90;
1130 insn->instructionID = instructionID;
1131 insn->spec = spec;
1132 return 0;
1135 specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
1137 /* Change back */
1138 insn->opcode = 0x90;
1140 insn->instructionID = instructionIDWithNewOpcode;
1141 insn->spec = specWithNewOpcode;
1143 return 0;
1146 insn->instructionID = instructionID;
1147 insn->spec = specifierForUID(insn->instructionID);
1149 return 0;
1153 * readSIB - Consumes the SIB byte to determine addressing information for an
1154 * instruction.
1156 * @param insn - The instruction whose SIB byte is to be read.
1157 * @return - 0 if the SIB byte was successfully read; nonzero otherwise.
1159 static int readSIB(struct InternalInstruction* insn) {
1160 SIBBase sibBaseBase = SIB_BASE_NONE;
1161 uint8_t index, base;
1163 dbgprintf(insn, "readSIB()");
1165 if (insn->consumedSIB)
1166 return 0;
1168 insn->consumedSIB = true;
1170 switch (insn->addressSize) {
1171 case 2:
1172 dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
1173 return -1;
1174 case 4:
1175 insn->sibIndexBase = SIB_INDEX_EAX;
1176 sibBaseBase = SIB_BASE_EAX;
1177 break;
1178 case 8:
1179 insn->sibIndexBase = SIB_INDEX_RAX;
1180 sibBaseBase = SIB_BASE_RAX;
1181 break;
1184 if (consumeByte(insn, &insn->sib))
1185 return -1;
1187 index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1189 if (index == 0x4) {
1190 insn->sibIndex = SIB_INDEX_NONE;
1191 } else {
1192 insn->sibIndex = (SIBIndex)(insn->sibIndexBase + index);
1195 insn->sibScale = 1 << scaleFromSIB(insn->sib);
1197 base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1199 switch (base) {
1200 case 0x5:
1201 case 0xd:
1202 switch (modFromModRM(insn->modRM)) {
1203 case 0x0:
1204 insn->eaDisplacement = EA_DISP_32;
1205 insn->sibBase = SIB_BASE_NONE;
1206 break;
1207 case 0x1:
1208 insn->eaDisplacement = EA_DISP_8;
1209 insn->sibBase = (SIBBase)(sibBaseBase + base);
1210 break;
1211 case 0x2:
1212 insn->eaDisplacement = EA_DISP_32;
1213 insn->sibBase = (SIBBase)(sibBaseBase + base);
1214 break;
1215 case 0x3:
1216 debug("Cannot have Mod = 0b11 and a SIB byte");
1217 return -1;
1219 break;
1220 default:
1221 insn->sibBase = (SIBBase)(sibBaseBase + base);
1222 break;
1225 return 0;
1229 * readDisplacement - Consumes the displacement of an instruction.
1231 * @param insn - The instruction whose displacement is to be read.
1232 * @return - 0 if the displacement byte was successfully read; nonzero
1233 * otherwise.
1235 static int readDisplacement(struct InternalInstruction* insn) {
1236 int8_t d8;
1237 int16_t d16;
1238 int32_t d32;
1240 dbgprintf(insn, "readDisplacement()");
1242 if (insn->consumedDisplacement)
1243 return 0;
1245 insn->consumedDisplacement = true;
1246 insn->displacementOffset = insn->readerCursor - insn->startLocation;
1248 switch (insn->eaDisplacement) {
1249 case EA_DISP_NONE:
1250 insn->consumedDisplacement = false;
1251 break;
1252 case EA_DISP_8:
1253 if (consumeInt8(insn, &d8))
1254 return -1;
1255 insn->displacement = d8;
1256 break;
1257 case EA_DISP_16:
1258 if (consumeInt16(insn, &d16))
1259 return -1;
1260 insn->displacement = d16;
1261 break;
1262 case EA_DISP_32:
1263 if (consumeInt32(insn, &d32))
1264 return -1;
1265 insn->displacement = d32;
1266 break;
1269 insn->consumedDisplacement = true;
1270 return 0;
1274 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1275 * displacement) for an instruction and interprets it.
1277 * @param insn - The instruction whose addressing information is to be read.
1278 * @return - 0 if the information was successfully read; nonzero otherwise.
1280 static int readModRM(struct InternalInstruction* insn) {
1281 uint8_t mod, rm, reg, evexrm;
1283 dbgprintf(insn, "readModRM()");
1285 if (insn->consumedModRM)
1286 return 0;
1288 if (consumeByte(insn, &insn->modRM))
1289 return -1;
1290 insn->consumedModRM = true;
1292 mod = modFromModRM(insn->modRM);
1293 rm = rmFromModRM(insn->modRM);
1294 reg = regFromModRM(insn->modRM);
1297 * This goes by insn->registerSize to pick the correct register, which messes
1298 * up if we're using (say) XMM or 8-bit register operands. That gets fixed in
1299 * fixupReg().
1301 switch (insn->registerSize) {
1302 case 2:
1303 insn->regBase = MODRM_REG_AX;
1304 insn->eaRegBase = EA_REG_AX;
1305 break;
1306 case 4:
1307 insn->regBase = MODRM_REG_EAX;
1308 insn->eaRegBase = EA_REG_EAX;
1309 break;
1310 case 8:
1311 insn->regBase = MODRM_REG_RAX;
1312 insn->eaRegBase = EA_REG_RAX;
1313 break;
1316 reg |= rFromREX(insn->rexPrefix) << 3;
1317 rm |= bFromREX(insn->rexPrefix) << 3;
1319 evexrm = 0;
1320 if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT) {
1321 reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1322 evexrm = xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1325 insn->reg = (Reg)(insn->regBase + reg);
1327 switch (insn->addressSize) {
1328 case 2: {
1329 EABase eaBaseBase = EA_BASE_BX_SI;
1331 switch (mod) {
1332 case 0x0:
1333 if (rm == 0x6) {
1334 insn->eaBase = EA_BASE_NONE;
1335 insn->eaDisplacement = EA_DISP_16;
1336 if (readDisplacement(insn))
1337 return -1;
1338 } else {
1339 insn->eaBase = (EABase)(eaBaseBase + rm);
1340 insn->eaDisplacement = EA_DISP_NONE;
1342 break;
1343 case 0x1:
1344 insn->eaBase = (EABase)(eaBaseBase + rm);
1345 insn->eaDisplacement = EA_DISP_8;
1346 insn->displacementSize = 1;
1347 if (readDisplacement(insn))
1348 return -1;
1349 break;
1350 case 0x2:
1351 insn->eaBase = (EABase)(eaBaseBase + rm);
1352 insn->eaDisplacement = EA_DISP_16;
1353 if (readDisplacement(insn))
1354 return -1;
1355 break;
1356 case 0x3:
1357 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1358 if (readDisplacement(insn))
1359 return -1;
1360 break;
1362 break;
1364 case 4:
1365 case 8: {
1366 EABase eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1368 switch (mod) {
1369 case 0x0:
1370 insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1371 // In determining whether RIP-relative mode is used (rm=5),
1372 // or whether a SIB byte is present (rm=4),
1373 // the extension bits (REX.b and EVEX.x) are ignored.
1374 switch (rm & 7) {
1375 case 0x4: // SIB byte is present
1376 insn->eaBase = (insn->addressSize == 4 ?
1377 EA_BASE_sib : EA_BASE_sib64);
1378 if (readSIB(insn) || readDisplacement(insn))
1379 return -1;
1380 break;
1381 case 0x5: // RIP-relative
1382 insn->eaBase = EA_BASE_NONE;
1383 insn->eaDisplacement = EA_DISP_32;
1384 if (readDisplacement(insn))
1385 return -1;
1386 break;
1387 default:
1388 insn->eaBase = (EABase)(eaBaseBase + rm);
1389 break;
1391 break;
1392 case 0x1:
1393 insn->displacementSize = 1;
1394 LLVM_FALLTHROUGH;
1395 case 0x2:
1396 insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1397 switch (rm & 7) {
1398 case 0x4: // SIB byte is present
1399 insn->eaBase = EA_BASE_sib;
1400 if (readSIB(insn) || readDisplacement(insn))
1401 return -1;
1402 break;
1403 default:
1404 insn->eaBase = (EABase)(eaBaseBase + rm);
1405 if (readDisplacement(insn))
1406 return -1;
1407 break;
1409 break;
1410 case 0x3:
1411 insn->eaDisplacement = EA_DISP_NONE;
1412 insn->eaBase = (EABase)(insn->eaRegBase + rm + evexrm);
1413 break;
1415 break;
1417 } /* switch (insn->addressSize) */
1419 return 0;
1422 #define GENERIC_FIXUP_FUNC(name, base, prefix, mask) \
1423 static uint16_t name(struct InternalInstruction *insn, \
1424 OperandType type, \
1425 uint8_t index, \
1426 uint8_t *valid) { \
1427 *valid = 1; \
1428 switch (type) { \
1429 default: \
1430 debug("Unhandled register type"); \
1431 *valid = 0; \
1432 return 0; \
1433 case TYPE_Rv: \
1434 return base + index; \
1435 case TYPE_R8: \
1436 index &= mask; \
1437 if (index > 0xf) \
1438 *valid = 0; \
1439 if (insn->rexPrefix && \
1440 index >= 4 && index <= 7) { \
1441 return prefix##_SPL + (index - 4); \
1442 } else { \
1443 return prefix##_AL + index; \
1445 case TYPE_R16: \
1446 index &= mask; \
1447 if (index > 0xf) \
1448 *valid = 0; \
1449 return prefix##_AX + index; \
1450 case TYPE_R32: \
1451 index &= mask; \
1452 if (index > 0xf) \
1453 *valid = 0; \
1454 return prefix##_EAX + index; \
1455 case TYPE_R64: \
1456 index &= mask; \
1457 if (index > 0xf) \
1458 *valid = 0; \
1459 return prefix##_RAX + index; \
1460 case TYPE_ZMM: \
1461 return prefix##_ZMM0 + index; \
1462 case TYPE_YMM: \
1463 return prefix##_YMM0 + index; \
1464 case TYPE_XMM: \
1465 return prefix##_XMM0 + index; \
1466 case TYPE_VK: \
1467 index &= 0xf; \
1468 if (index > 7) \
1469 *valid = 0; \
1470 return prefix##_K0 + index; \
1471 case TYPE_VK_PAIR: \
1472 if (index > 7) \
1473 *valid = 0; \
1474 return prefix##_K0_K1 + (index / 2); \
1475 case TYPE_MM64: \
1476 return prefix##_MM0 + (index & 0x7); \
1477 case TYPE_SEGMENTREG: \
1478 if ((index & 7) > 5) \
1479 *valid = 0; \
1480 return prefix##_ES + (index & 7); \
1481 case TYPE_DEBUGREG: \
1482 return prefix##_DR0 + index; \
1483 case TYPE_CONTROLREG: \
1484 return prefix##_CR0 + index; \
1485 case TYPE_BNDR: \
1486 if (index > 3) \
1487 *valid = 0; \
1488 return prefix##_BND0 + index; \
1489 case TYPE_MVSIBX: \
1490 return prefix##_XMM0 + index; \
1491 case TYPE_MVSIBY: \
1492 return prefix##_YMM0 + index; \
1493 case TYPE_MVSIBZ: \
1494 return prefix##_ZMM0 + index; \
1499 * fixup*Value - Consults an operand type to determine the meaning of the
1500 * reg or R/M field. If the operand is an XMM operand, for example, an
1501 * operand would be XMM0 instead of AX, which readModRM() would otherwise
1502 * misinterpret it as.
1504 * @param insn - The instruction containing the operand.
1505 * @param type - The operand type.
1506 * @param index - The existing value of the field as reported by readModRM().
1507 * @param valid - The address of a uint8_t. The target is set to 1 if the
1508 * field is valid for the register class; 0 if not.
1509 * @return - The proper value.
1511 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG, 0x1f)
1512 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG, 0xf)
1515 * fixupReg - Consults an operand specifier to determine which of the
1516 * fixup*Value functions to use in correcting readModRM()'ss interpretation.
1518 * @param insn - See fixup*Value().
1519 * @param op - The operand specifier.
1520 * @return - 0 if fixup was successful; -1 if the register returned was
1521 * invalid for its class.
1523 static int fixupReg(struct InternalInstruction *insn,
1524 const struct OperandSpecifier *op) {
1525 uint8_t valid;
1527 dbgprintf(insn, "fixupReg()");
1529 switch ((OperandEncoding)op->encoding) {
1530 default:
1531 debug("Expected a REG or R/M encoding in fixupReg");
1532 return -1;
1533 case ENCODING_VVVV:
1534 insn->vvvv = (Reg)fixupRegValue(insn,
1535 (OperandType)op->type,
1536 insn->vvvv,
1537 &valid);
1538 if (!valid)
1539 return -1;
1540 break;
1541 case ENCODING_REG:
1542 insn->reg = (Reg)fixupRegValue(insn,
1543 (OperandType)op->type,
1544 insn->reg - insn->regBase,
1545 &valid);
1546 if (!valid)
1547 return -1;
1548 break;
1549 CASE_ENCODING_RM:
1550 if (insn->eaBase >= insn->eaRegBase) {
1551 insn->eaBase = (EABase)fixupRMValue(insn,
1552 (OperandType)op->type,
1553 insn->eaBase - insn->eaRegBase,
1554 &valid);
1555 if (!valid)
1556 return -1;
1558 break;
1561 return 0;
1565 * readOpcodeRegister - Reads an operand from the opcode field of an
1566 * instruction and interprets it appropriately given the operand width.
1567 * Handles AddRegFrm instructions.
1569 * @param insn - the instruction whose opcode field is to be read.
1570 * @param size - The width (in bytes) of the register being specified.
1571 * 1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1572 * RAX.
1573 * @return - 0 on success; nonzero otherwise.
1575 static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1576 dbgprintf(insn, "readOpcodeRegister()");
1578 if (size == 0)
1579 size = insn->registerSize;
1581 switch (size) {
1582 case 1:
1583 insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1584 | (insn->opcode & 7)));
1585 if (insn->rexPrefix &&
1586 insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1587 insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1588 insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1589 + (insn->opcodeRegister - MODRM_REG_AL - 4));
1592 break;
1593 case 2:
1594 insn->opcodeRegister = (Reg)(MODRM_REG_AX
1595 + ((bFromREX(insn->rexPrefix) << 3)
1596 | (insn->opcode & 7)));
1597 break;
1598 case 4:
1599 insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1600 + ((bFromREX(insn->rexPrefix) << 3)
1601 | (insn->opcode & 7)));
1602 break;
1603 case 8:
1604 insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1605 + ((bFromREX(insn->rexPrefix) << 3)
1606 | (insn->opcode & 7)));
1607 break;
1610 return 0;
1614 * readImmediate - Consumes an immediate operand from an instruction, given the
1615 * desired operand size.
1617 * @param insn - The instruction whose operand is to be read.
1618 * @param size - The width (in bytes) of the operand.
1619 * @return - 0 if the immediate was successfully consumed; nonzero
1620 * otherwise.
1622 static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1623 uint8_t imm8;
1624 uint16_t imm16;
1625 uint32_t imm32;
1626 uint64_t imm64;
1628 dbgprintf(insn, "readImmediate()");
1630 if (insn->numImmediatesConsumed == 2) {
1631 debug("Already consumed two immediates");
1632 return -1;
1635 if (size == 0)
1636 size = insn->immediateSize;
1637 else
1638 insn->immediateSize = size;
1639 insn->immediateOffset = insn->readerCursor - insn->startLocation;
1641 switch (size) {
1642 case 1:
1643 if (consumeByte(insn, &imm8))
1644 return -1;
1645 insn->immediates[insn->numImmediatesConsumed] = imm8;
1646 break;
1647 case 2:
1648 if (consumeUInt16(insn, &imm16))
1649 return -1;
1650 insn->immediates[insn->numImmediatesConsumed] = imm16;
1651 break;
1652 case 4:
1653 if (consumeUInt32(insn, &imm32))
1654 return -1;
1655 insn->immediates[insn->numImmediatesConsumed] = imm32;
1656 break;
1657 case 8:
1658 if (consumeUInt64(insn, &imm64))
1659 return -1;
1660 insn->immediates[insn->numImmediatesConsumed] = imm64;
1661 break;
1664 insn->numImmediatesConsumed++;
1666 return 0;
1670 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1672 * @param insn - The instruction whose operand is to be read.
1673 * @return - 0 if the vvvv was successfully consumed; nonzero
1674 * otherwise.
1676 static int readVVVV(struct InternalInstruction* insn) {
1677 dbgprintf(insn, "readVVVV()");
1679 int vvvv;
1680 if (insn->vectorExtensionType == TYPE_EVEX)
1681 vvvv = (v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4 |
1682 vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]));
1683 else if (insn->vectorExtensionType == TYPE_VEX_3B)
1684 vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1685 else if (insn->vectorExtensionType == TYPE_VEX_2B)
1686 vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1687 else if (insn->vectorExtensionType == TYPE_XOP)
1688 vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1689 else
1690 return -1;
1692 if (insn->mode != MODE_64BIT)
1693 vvvv &= 0xf; // Can only clear bit 4. Bit 3 must be cleared later.
1695 insn->vvvv = static_cast<Reg>(vvvv);
1696 return 0;
1700 * readMaskRegister - Reads an mask register from the opcode field of an
1701 * instruction.
1703 * @param insn - The instruction whose opcode field is to be read.
1704 * @return - 0 on success; nonzero otherwise.
1706 static int readMaskRegister(struct InternalInstruction* insn) {
1707 dbgprintf(insn, "readMaskRegister()");
1709 if (insn->vectorExtensionType != TYPE_EVEX)
1710 return -1;
1712 insn->writemask =
1713 static_cast<Reg>(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1714 return 0;
1718 * readOperands - Consults the specifier for an instruction and consumes all
1719 * operands for that instruction, interpreting them as it goes.
1721 * @param insn - The instruction whose operands are to be read and interpreted.
1722 * @return - 0 if all operands could be read; nonzero otherwise.
1724 static int readOperands(struct InternalInstruction* insn) {
1725 int hasVVVV, needVVVV;
1726 int sawRegImm = 0;
1728 dbgprintf(insn, "readOperands()");
1730 /* If non-zero vvvv specified, need to make sure one of the operands
1731 uses it. */
1732 hasVVVV = !readVVVV(insn);
1733 needVVVV = hasVVVV && (insn->vvvv != 0);
1735 for (const auto &Op : x86OperandSets[insn->spec->operands]) {
1736 switch (Op.encoding) {
1737 case ENCODING_NONE:
1738 case ENCODING_SI:
1739 case ENCODING_DI:
1740 break;
1741 CASE_ENCODING_VSIB:
1742 // VSIB can use the V2 bit so check only the other bits.
1743 if (needVVVV)
1744 needVVVV = hasVVVV & ((insn->vvvv & 0xf) != 0);
1745 if (readModRM(insn))
1746 return -1;
1748 // Reject if SIB wasn't used.
1749 if (insn->eaBase != EA_BASE_sib && insn->eaBase != EA_BASE_sib64)
1750 return -1;
1752 // If sibIndex was set to SIB_INDEX_NONE, index offset is 4.
1753 if (insn->sibIndex == SIB_INDEX_NONE)
1754 insn->sibIndex = (SIBIndex)(insn->sibIndexBase + 4);
1756 // If EVEX.v2 is set this is one of the 16-31 registers.
1757 if (insn->vectorExtensionType == TYPE_EVEX && insn->mode == MODE_64BIT &&
1758 v2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
1759 insn->sibIndex = (SIBIndex)(insn->sibIndex + 16);
1761 // Adjust the index register to the correct size.
1762 switch ((OperandType)Op.type) {
1763 default:
1764 debug("Unhandled VSIB index type");
1765 return -1;
1766 case TYPE_MVSIBX:
1767 insn->sibIndex = (SIBIndex)(SIB_INDEX_XMM0 +
1768 (insn->sibIndex - insn->sibIndexBase));
1769 break;
1770 case TYPE_MVSIBY:
1771 insn->sibIndex = (SIBIndex)(SIB_INDEX_YMM0 +
1772 (insn->sibIndex - insn->sibIndexBase));
1773 break;
1774 case TYPE_MVSIBZ:
1775 insn->sibIndex = (SIBIndex)(SIB_INDEX_ZMM0 +
1776 (insn->sibIndex - insn->sibIndexBase));
1777 break;
1780 // Apply the AVX512 compressed displacement scaling factor.
1781 if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1782 insn->displacement *= 1 << (Op.encoding - ENCODING_VSIB);
1783 break;
1784 case ENCODING_REG:
1785 CASE_ENCODING_RM:
1786 if (readModRM(insn))
1787 return -1;
1788 if (fixupReg(insn, &Op))
1789 return -1;
1790 // Apply the AVX512 compressed displacement scaling factor.
1791 if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1792 insn->displacement *= 1 << (Op.encoding - ENCODING_RM);
1793 break;
1794 case ENCODING_IB:
1795 if (sawRegImm) {
1796 /* Saw a register immediate so don't read again and instead split the
1797 previous immediate. FIXME: This is a hack. */
1798 insn->immediates[insn->numImmediatesConsumed] =
1799 insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1800 ++insn->numImmediatesConsumed;
1801 break;
1803 if (readImmediate(insn, 1))
1804 return -1;
1805 if (Op.type == TYPE_XMM || Op.type == TYPE_YMM)
1806 sawRegImm = 1;
1807 break;
1808 case ENCODING_IW:
1809 if (readImmediate(insn, 2))
1810 return -1;
1811 break;
1812 case ENCODING_ID:
1813 if (readImmediate(insn, 4))
1814 return -1;
1815 break;
1816 case ENCODING_IO:
1817 if (readImmediate(insn, 8))
1818 return -1;
1819 break;
1820 case ENCODING_Iv:
1821 if (readImmediate(insn, insn->immediateSize))
1822 return -1;
1823 break;
1824 case ENCODING_Ia:
1825 if (readImmediate(insn, insn->addressSize))
1826 return -1;
1827 break;
1828 case ENCODING_IRC:
1829 insn->RC = (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 1) |
1830 lFromEVEX4of4(insn->vectorExtensionPrefix[3]);
1831 break;
1832 case ENCODING_RB:
1833 if (readOpcodeRegister(insn, 1))
1834 return -1;
1835 break;
1836 case ENCODING_RW:
1837 if (readOpcodeRegister(insn, 2))
1838 return -1;
1839 break;
1840 case ENCODING_RD:
1841 if (readOpcodeRegister(insn, 4))
1842 return -1;
1843 break;
1844 case ENCODING_RO:
1845 if (readOpcodeRegister(insn, 8))
1846 return -1;
1847 break;
1848 case ENCODING_Rv:
1849 if (readOpcodeRegister(insn, 0))
1850 return -1;
1851 break;
1852 case ENCODING_CC:
1853 insn->immediates[1] = insn->opcode & 0xf;
1854 break;
1855 case ENCODING_FP:
1856 break;
1857 case ENCODING_VVVV:
1858 needVVVV = 0; /* Mark that we have found a VVVV operand. */
1859 if (!hasVVVV)
1860 return -1;
1861 if (insn->mode != MODE_64BIT)
1862 insn->vvvv = static_cast<Reg>(insn->vvvv & 0x7);
1863 if (fixupReg(insn, &Op))
1864 return -1;
1865 break;
1866 case ENCODING_WRITEMASK:
1867 if (readMaskRegister(insn))
1868 return -1;
1869 break;
1870 case ENCODING_DUP:
1871 break;
1872 default:
1873 dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1874 return -1;
1878 /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1879 if (needVVVV) return -1;
1881 return 0;
1885 * decodeInstruction - Reads and interprets a full instruction provided by the
1886 * user.
1888 * @param insn - A pointer to the instruction to be populated. Must be
1889 * pre-allocated.
1890 * @param reader - The function to be used to read the instruction's bytes.
1891 * @param readerArg - A generic argument to be passed to the reader to store
1892 * any internal state.
1893 * @param logger - If non-NULL, the function to be used to write log messages
1894 * and warnings.
1895 * @param loggerArg - A generic argument to be passed to the logger to store
1896 * any internal state.
1897 * @param startLoc - The address (in the reader's address space) of the first
1898 * byte in the instruction.
1899 * @param mode - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1900 * decode the instruction in.
1901 * @return - 0 if the instruction's memory could be read; nonzero if
1902 * not.
1904 int llvm::X86Disassembler::decodeInstruction(
1905 struct InternalInstruction *insn, byteReader_t reader,
1906 const void *readerArg, dlog_t logger, void *loggerArg, const void *miiArg,
1907 uint64_t startLoc, DisassemblerMode mode) {
1908 memset(insn, 0, sizeof(struct InternalInstruction));
1910 insn->reader = reader;
1911 insn->readerArg = readerArg;
1912 insn->dlog = logger;
1913 insn->dlogArg = loggerArg;
1914 insn->startLocation = startLoc;
1915 insn->readerCursor = startLoc;
1916 insn->mode = mode;
1917 insn->numImmediatesConsumed = 0;
1919 if (readPrefixes(insn) ||
1920 readOpcode(insn) ||
1921 getID(insn, miiArg) ||
1922 insn->instructionID == 0 ||
1923 readOperands(insn))
1924 return -1;
1926 insn->operands = x86OperandSets[insn->spec->operands];
1928 insn->length = insn->readerCursor - insn->startLocation;
1930 dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1931 startLoc, insn->readerCursor, insn->length);
1933 if (insn->length > 15)
1934 dbgprintf(insn, "Instruction exceeds 15-byte limit");
1936 return 0;