Applied another InstructionDecoder-x86.C patch
[dyninst.git] / instructionAPI / src / InstructionDecoder-x86.C
1 /*
2  * See the dyninst/COPYRIGHT file for copyright information.
3  * 
4  * We provide the Paradyn Tools (below described as "Paradyn")
5  * on an AS IS basis, and do not warrant its validity or performance.
6  * We reserve the right to update, modify, or discontinue this
7  * software at any time.  We shall have no obligation to supply such
8  * updates or modifications or any other form of support to you.
9  * 
10  * By your use of Paradyn, you understand and agree that we (or any
11  * other person or entity with proprietary rights in Paradyn) are
12  * under no obligation to provide either maintenance services,
13  * update services, notices of latent defects, or correction of
14  * defects for Paradyn.
15  * 
16  * This library is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU Lesser General Public
18  * License as published by the Free Software Foundation; either
19  * version 2.1 of the License, or (at your option) any later version.
20  * 
21  * This library is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24  * Lesser General Public License for more details.
25  * 
26  * You should have received a copy of the GNU Lesser General Public
27  * License along with this library; if not, write to the Free Software
28  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29  */
30
31 #define INSIDE_INSTRUCTION_API
32
33 #include "common/src/Types.h"
34 #include "InstructionDecoder-x86.h"
35 #include "Expression.h"
36 #include "common/src/arch-x86.h"
37 #include "Register.h"
38 #include "Dereference.h"
39 #include "Immediate.h" 
40 #include "BinaryFunction.h"
41 #include "common/src/singleton_object_pool.h"
42
43 #define VEX_DEBUG
44
45 using namespace std;
46 using namespace NS_x86;
47 namespace Dyninst
48 {
49     namespace InstructionAPI
50     {
51     
52         bool readsOperand(unsigned int opsema, unsigned int i)
53         {
54             switch(opsema) {
55                 case s1R2R:
56                     return (i == 0 || i == 1);
57                 case s1R:
58                 case s1RW:
59                     return i == 0;
60                 case s1W:
61                     return false;
62                 case s1W2RW:
63                 case s1W2R:   // second operand read, first operand written (e.g. mov)
64                     return i == 1;
65                 case s1RW2R:  // two operands read, first written (e.g. add)
66                 case s1RW2RW: // e.g. xchg
67                 case s1R2RW:
68                     return i == 0 || i == 1;
69                 case s1W2R3R: // e.g. imul
70                 case s1W2RW3R: // some mul
71                 case s1W2R3RW: // (stack) push & pop
72                     return i == 1 || i == 2;
73                 case s1W2W3R: // e.g. les
74                     return i == 2;
75                 case s1RW2R3RW:
76                 case s1RW2R3R: // shld/shrd
77                 case s1RW2RW3R: // [i]div, cmpxch8b
78                 case s1R2R3R:
79                     return i == 0 || i == 1 || i == 2;
80                 case s1W2R3R4R:
81                     return i == 1 || i == 2 || i == 3;
82                 case s1RW2R3R4R:
83                     return i == 0 || i == 1 || i == 2 || i == 3;
84                 case sNONE:
85                 default:
86                     return false;
87             }
88       
89         }
90       
91         bool writesOperand(unsigned int opsema, unsigned int i)
92         {
93             switch(opsema) {
94                 case s1R2R:
95                 case s1R:
96                     return false;
97                 case s1RW:
98                 case s1W:
99                 case s1W2R:   // second operand read, first operand written (e.g. mov)
100                 case s1RW2R:  // two operands read, first written (e.g. add)
101                 case s1W2R3R: // e.g. imul
102                 case s1RW2R3R: // shld/shrd
103                 case s1RW2R3R4R:
104                   return i == 0;
105                 case s1R2RW:
106                   return i == 1;
107                 case s1W2RW:
108                 case s1RW2RW: // e.g. xchg
109                 case s1W2RW3R: // some mul
110                 case s1W2W3R: // e.g. les
111                 case s1RW2RW3R: // [i]div, cmpxch8b
112                   return i == 0 || i == 1;
113                 case s1W2R3RW: // (stack) push & pop
114                   return i == 0 || i == 2;
115                 case s1RW2R3RW:
116                   return i == 0 || i == 2;
117                 case sNONE:
118                 default:
119                     return false;
120             }
121         }
122
123
124     
125     INSTRUCTION_EXPORT InstructionDecoder_x86::InstructionDecoder_x86(Architecture a) :
126       InstructionDecoderImpl(a),
127     locs(NULL),
128     decodedInstruction(NULL),
129     sizePrefixPresent(false),
130     addrSizePrefixPresent(false)
131     {
132       if(a == Arch_x86_64) setMode(true);
133       
134     }
135     INSTRUCTION_EXPORT InstructionDecoder_x86::~InstructionDecoder_x86()
136     {
137         if(decodedInstruction) decodedInstruction->~ia32_instruction();
138         free(decodedInstruction);
139         if(locs) locs->~ia32_locations();
140         free(locs);
141
142     }
143     static const unsigned char modrm_use_sib = 4;
144     
145     INSTRUCTION_EXPORT void InstructionDecoder_x86::setMode(bool is64)
146     {
147         ia32_set_mode_64(is64);
148     }
149     
150       Expression::Ptr InstructionDecoder_x86::makeSIBExpression(const InstructionDecoder::buffer& b)
151     {
152         unsigned scale;
153         Register index;
154         Register base;
155         Result_Type registerType = ia32_is_mode_64() ? u64 : u32;
156
157         decode_SIB(locs->sib_byte, scale, index, base);
158
159         Expression::Ptr scaleAST(make_shared(singleton_object_pool<Immediate>::construct(Result(u8, dword_t(scale)))));
160         Expression::Ptr indexAST(make_shared(singleton_object_pool<RegisterAST>::construct(makeRegisterID(index, registerType,
161                                     locs->rex_x))));
162         Expression::Ptr baseAST;
163         if(base == 0x05)
164         {
165             switch(locs->modrm_mod)
166             {
167                 case 0x00:
168                     baseAST = decodeImmediate(op_d, b.start + locs->sib_position + 1, true);
169                     break;
170                 case 0x01: 
171                 case 0x02: 
172                     baseAST = make_shared(singleton_object_pool<RegisterAST>::construct(makeRegisterID(base, 
173                                                                                                registerType,
174                                                                                                locs->rex_b)));
175                     break;
176                 case 0x03:
177                 default:
178                     assert(0);
179                     break;
180             };
181         }
182         else
183         {
184             baseAST = make_shared(singleton_object_pool<RegisterAST>::construct(makeRegisterID(base, 
185                                                                                                registerType,
186                                                                                                locs->rex_b)));
187         }
188
189         if(index == 0x04 && (!(ia32_is_mode_64()) || !(locs->rex_x)))
190         {
191             return baseAST;
192         }
193         return makeAddExpression(baseAST, makeMultiplyExpression(indexAST, scaleAST, registerType), registerType);
194     }
195
196       Expression::Ptr InstructionDecoder_x86::makeModRMExpression(const InstructionDecoder::buffer& b,
197                                                                   unsigned int opType)
198     {
199        unsigned int regType = op_d;
200        Result_Type aw;
201        if(ia32_is_mode_64())
202        {
203            if(addrSizePrefixPresent) {
204                aw = u32;
205            } else {
206                aw = u64;
207                regType = op_q;
208            }
209        }
210        else
211        {
212            if(!addrSizePrefixPresent) {
213                aw = u32;
214            } else {
215                aw = u16;
216                regType = op_w;
217            }
218        }
219         if (opType == op_lea) {
220             // For an LEA, aw (address width) is insufficient, use makeSizeType
221             aw = makeSizeType(opType);
222         }
223         Expression::Ptr e =
224             makeRegisterExpression(makeRegisterID(locs->modrm_rm, regType, locs->rex_b));
225         switch(locs->modrm_mod)
226         {
227             case 0:
228                 if(locs->modrm_rm == modrm_use_sib) {
229                     e = makeSIBExpression(b);
230                 }
231                 if(locs->modrm_rm == 0x5 && !addrSizePrefixPresent)
232                 {
233                     assert(locs->opcode_position > -1);
234                     if(ia32_is_mode_64())
235                     {
236                         e = makeAddExpression(makeRegisterExpression(x86_64::rip),
237                                             getModRMDisplacement(b), aw);
238                     }
239                     else
240                     {
241                         e = getModRMDisplacement(b);
242                     }
243         
244                 }
245                 if(locs->modrm_rm == 0x6 && addrSizePrefixPresent)
246                 {
247                     e = getModRMDisplacement(b);
248                 }
249                 if(opType == op_lea)
250                 {
251                     return e;
252                 }
253                 return makeDereferenceExpression(e, makeSizeType(opType));
254                 assert(0);
255                 break;
256             case 1:
257             case 2:
258             {
259                 if(locs->modrm_rm == modrm_use_sib) {
260                     e = makeSIBExpression(b);
261                 }
262                 Expression::Ptr disp_e = makeAddExpression(e, getModRMDisplacement(b), aw);
263                 if(opType == op_lea)
264                 {
265                     return disp_e;
266                 }
267                 return makeDereferenceExpression(disp_e, makeSizeType(opType));
268             }
269             assert(0);
270             break;
271             case 3:
272                 return makeRegisterExpression(makeRegisterID(locs->modrm_rm, opType, locs->rex_b));
273             default:
274                 return Expression::Ptr();
275         
276         };
277         // can't get here, but make the compiler happy...
278         assert(0);
279         return Expression::Ptr();
280     }
281
282     Expression::Ptr InstructionDecoder_x86::decodeImmediate(unsigned int opType, const unsigned char* immStart, 
283                                                             bool isSigned)
284     {
285         // rex_w indicates we need to sign-extend also.
286         isSigned = isSigned || locs->rex_w;
287         
288         switch(opType)
289         {
290             case op_b:
291                 return Immediate::makeImmediate(Result(isSigned ? s8 : u8 ,*(const byte_t*)(immStart)));
292                 break;
293             case op_d:
294                 return Immediate::makeImmediate(Result(isSigned ? s32 : u32,*(const dword_t*)(immStart)));
295             case op_w:
296                 return Immediate::makeImmediate(Result(isSigned ? s16 : u16,*(const word_t*)(immStart)));
297                 break;
298             case op_q:
299                 return Immediate::makeImmediate(Result(isSigned ? s64 : u64,*(const int64_t*)(immStart)));
300                 break;
301             case op_v:
302                 if (locs->rex_w || isDefault64Insn()) {
303                     return Immediate::makeImmediate(Result(isSigned ? s64 : u64,*(const int64_t*)(immStart)));
304                 }
305                 //if(!sizePrefixPresent)
306                 //{
307                     return Immediate::makeImmediate(Result(isSigned ? s32 : u32,*(const dword_t*)(immStart)));
308                     //}
309                     //else
310                     //{
311                     //return Immediate::makeImmediate(Result(isSigned ? s16 : u16,*(const word_t*)(immStart)));
312                     //}
313                 break;
314             case op_z:
315                 // 32 bit mode & no prefix, or 16 bit mode & prefix => 32 bit
316                 // 16 bit mode, no prefix or 32 bit mode, prefix => 16 bit
317                 //if(!addrSizePrefixPresent)
318                 //{
319                     return Immediate::makeImmediate(Result(isSigned ? s32 : u32,*(const dword_t*)(immStart)));
320                     //}
321                     //else
322                     //{
323                     //return Immediate::makeImmediate(Result(isSigned ? s16 : u16,*(const word_t*)(immStart)));
324                     //}
325                 break;
326             case op_p:
327                 // 32 bit mode & no prefix, or 16 bit mode & prefix => 48 bit
328                 // 16 bit mode, no prefix or 32 bit mode, prefix => 32 bit
329                 if(!sizePrefixPresent)
330                 {
331                     return Immediate::makeImmediate(Result(isSigned ? s48 : u48,*(const int64_t*)(immStart)));
332                 }
333                 else
334                 {
335                     return Immediate::makeImmediate(Result(isSigned ? s32 : u32,*(const dword_t*)(immStart)));
336                 }
337
338                 break;
339             case op_a:
340             case op_dq:
341             case op_pd:
342             case op_ps:
343             case op_s:
344             case op_si:
345             case op_lea:
346             case op_allgprs:
347             case op_512:
348             case op_c:
349                 assert(!"Can't happen: opType unexpected for valid ways to decode an immediate");
350                 return Expression::Ptr();
351             default:
352                 assert(!"Can't happen: opType out of range");
353                 return Expression::Ptr();
354         }
355     }
356     
357     Expression::Ptr InstructionDecoder_x86::getModRMDisplacement(const InstructionDecoder::buffer& b)
358     {
359         int disp_pos;
360
361         if(locs->sib_position != -1)
362         {
363             disp_pos = locs->sib_position + 1;
364         }
365         else
366         {
367             disp_pos = locs->modrm_position + 1;
368         }
369         switch(locs->modrm_mod)
370         {
371             case 1:
372                 return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, (*(const byte_t*)(b.start +
373                         disp_pos)))));
374                 break;
375             case 2:
376                 if(0 && sizePrefixPresent)
377                 {
378                     return make_shared(singleton_object_pool<Immediate>::construct(Result(s16, *((const word_t*)(b.start +
379                             disp_pos)))));
380                 }
381                 else
382                 {
383                     return make_shared(singleton_object_pool<Immediate>::construct(Result(s32, *((const dword_t*)(b.start +
384                             disp_pos)))));
385                 }
386                 break;
387             case 0:
388                 // In 16-bit mode, the word displacement is modrm r/m 6
389                 if(sizePrefixPresent && !ia32_is_mode_64())
390                 {
391                     if(locs->modrm_rm == 6)
392                     {
393                         return make_shared(singleton_object_pool<Immediate>::construct(Result(s16,
394                                            *((const dword_t*)(b.start + disp_pos)))));
395                     }
396                     // TODO FIXME; this was decoding wrong, but I'm not sure
397                     // why...
398                     else if (locs->modrm_rm == 5) {
399                         assert(b.start + disp_pos + 4 <= b.end);
400                         return make_shared(singleton_object_pool<Immediate>::construct(Result(s32,
401                                            *((const dword_t*)(b.start + disp_pos)))));
402                     } else {
403                         assert(b.start + disp_pos + 1 <= b.end);
404                         return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, 0)));
405                     }
406                     break;
407                 }
408                 // ...and in 32-bit mode, the dword displacement is modrm r/m 5
409                 else
410                 {
411                     if(locs->modrm_rm == 5)
412                     {
413                         if (b.start + disp_pos + 4 <= b.end) 
414                             return make_shared(singleton_object_pool<Immediate>::construct(Result(s32,
415                                                *((const dword_t*)(b.start + disp_pos)))));
416                         else
417                             return make_shared(singleton_object_pool<Immediate>::construct(Result()));
418                     }
419                     else
420                     {
421                         if (b.start + disp_pos + 1 <= b.end)
422                             return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, 0)));
423                         else
424                             return make_shared(singleton_object_pool<Immediate>::construct(Result()));
425                     }
426                     break;
427                 }
428             default:
429                 assert(b.start + disp_pos + 1 <= b.end);
430                 return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, 0)));
431                 break;
432         }
433     }
434
435     enum intelRegBanks
436     {
437         b_8bitNoREX = 0,
438         b_16bit,
439         b_32bit,
440         b_segment,
441         b_64bit,
442         b_xmm_set0, /* XMM0 -> XMM 7 */
443         b_xmm_set1, /* XMM8 -> XMM 15 */
444         b_xmm_set2, /* XMM16 -> XMM 23 */
445         b_xmm_set3, /* XMM24 -> XMM 31 */
446         b_ymm_set0, /* YMM0 -> YMM 7 */
447         b_ymm_set1, /* YMM8 -> YMM 15 */
448         b_ymm_set2, /* YMM16 -> YMM 23 */
449         b_ymm_set3, /* YMM24 -> YMM 31 */
450         b_zmm_set0, /* ZMM0 -> ZMM 7 */
451         b_zmm_set1, /* ZMM8 -> ZMM 15 */
452         b_zmm_set2, /* ZMM16 -> ZMM 23 */
453         b_zmm_set3, /* ZMM24 -> ZMM 31 */
454         b_mm,
455         b_cr,
456         b_dr,
457         b_tr,
458         b_amd64ext,
459         b_8bitWithREX,
460         b_fpstack,
461         amd64_ext_8,
462         amd64_ext_16,
463         amd64_ext_32,
464
465         b_invalid /* should remain the final entry */
466     };
467
468     static MachRegister IntelRegTable32[][8] = {
469         { x86::al, x86::cl, x86::dl, x86::bl, x86::ah, x86::ch, x86::dh, x86::bh }, /* b_8bitNoREX */
470         { x86::ax, x86::cx, x86::dx, x86::bx, x86::sp, x86::bp, x86::si, x86::di }, /* b_16bit */
471         { x86::eax, x86::ecx, x86::edx, x86::ebx, x86::esp, x86::ebp, x86::esi, x86::edi }, /* b_32bit */
472         { x86::es, x86::cs, x86::ss, x86::ds, x86::fs, x86::gs, InvalidReg, InvalidReg }, /* b_segment */
473         { x86_64::rax, x86_64::rcx, x86_64::rdx, x86_64::rbx, x86_64::rsp, x86_64::rbp, x86_64::rsi, x86_64::rdi }, /* b_64bit */
474         { x86::xmm0, x86::xmm1, x86::xmm2, x86::xmm3, x86::xmm4, x86::xmm5, x86::xmm6, x86::xmm7 }, /* b_xmm_set0 */
475         { x86_64::xmm8, x86_64::xmm9, x86_64::xmm10, x86_64::xmm11, x86_64::xmm12, x86_64::xmm13, x86_64::xmm14, x86_64::xmm15 }, /* b_xmm_set1 */
476         { x86_64::xmm16, x86_64::xmm17, x86_64::xmm18, x86_64::xmm19, x86_64::xmm20, x86_64::xmm21, x86_64::xmm22, x86_64::xmm23 }, /* b_xmm_set2 */
477         { x86_64::xmm24, x86_64::xmm25, x86_64::xmm26, x86_64::xmm27, x86_64::xmm28, x86_64::xmm29, x86_64::xmm30, x86_64::xmm31 }, /* b_xmm_set3 */
478         { x86_64::ymm0, x86_64::ymm1, x86_64::ymm2, x86_64::ymm3, x86_64::ymm4, x86_64::ymm5, x86_64::ymm6, x86_64::ymm7 }, /* b_ymm_set0 */
479         { x86_64::ymm8, x86_64::ymm9, x86_64::ymm10, x86_64::ymm11, x86_64::ymm12, x86_64::ymm13, x86_64::ymm14, x86_64::ymm15 }, /* b_ymm_set1 */
480         { x86_64::ymm16, x86_64::ymm17, x86_64::ymm18, x86_64::ymm19, x86_64::ymm20, x86_64::ymm21, x86_64::ymm22, x86_64::ymm23 }, /* b_ymm_set2 */
481         { x86_64::ymm24, x86_64::ymm25, x86_64::ymm26, x86_64::ymm27, x86_64::ymm28, x86_64::ymm29, x86_64::ymm30, x86_64::ymm31 }, /* b_ymm_set3 */
482         { x86_64::zmm0, x86_64::zmm1, x86_64::zmm2, x86_64::zmm3, x86_64::zmm4, x86_64::zmm5, x86_64::zmm6, x86_64::zmm7 }, /* b_zmm_set0 */
483         { x86_64::zmm8, x86_64::zmm9, x86_64::zmm10, x86_64::zmm11, x86_64::zmm12, x86_64::zmm13, x86_64::zmm14, x86_64::zmm15 }, /* b_zmm_set1 */
484         { x86_64::zmm16, x86_64::zmm17, x86_64::zmm18, x86_64::zmm19, x86_64::zmm20, x86_64::zmm21, x86_64::zmm22, x86_64::zmm23 }, /* b_zmm_set2 */
485         { x86_64::zmm24, x86_64::zmm25, x86_64::zmm26, x86_64::zmm27, x86_64::zmm28, x86_64::zmm29, x86_64::zmm30, x86_64::zmm31 }, /* b_zmm_set3 */
486         { x86::mm0, x86::mm1, x86::mm2, x86::mm3, x86::mm4, x86::mm5, x86::mm6, x86::mm7 },
487         { x86::cr0, x86::cr1, x86::cr2, x86::cr3, x86::cr4, x86::cr5, x86::cr6, x86::cr7 },
488         { x86::dr0, x86::dr1, x86::dr2, x86::dr3, x86::dr4, x86::dr5, x86::dr6, x86::dr7 },
489         { x86::tr0, x86::tr1, x86::tr2, x86::tr3, x86::tr4, x86::tr5, x86::tr6, x86::tr7 },
490         { x86_64::r8, x86_64::r9, x86_64::r10, x86_64::r11, x86_64::r12, x86_64::r13, x86_64::r14, x86_64::r15 },
491         { x86_64::al, x86_64::cl, x86_64::dl, x86_64::bl, x86_64::spl, x86_64::bpl, x86_64::sil, x86_64::dil },
492         { x86::st0, x86::st1, x86::st2, x86::st3, x86::st4, x86::st5, x86::st6, x86::st7 }
493     };
494
495     static MachRegister IntelRegTable64[][8] = {
496         { x86_64::al, x86_64::cl, x86_64::dl, x86_64::bl, x86_64::ah, x86_64::ch, x86_64::dh, x86_64::bh },
497         { x86_64::ax, x86_64::cx, x86_64::dx, x86_64::bx, x86_64::sp, x86_64::bp, x86_64::si, x86_64::di },
498         { x86_64::eax, x86_64::ecx, x86_64::edx, x86_64::ebx, x86_64::esp, x86_64::ebp, x86_64::esi, x86_64::edi },
499         { x86_64::es, x86_64::cs, x86_64::ss, x86_64::ds, x86_64::fs, x86_64::gs, InvalidReg, InvalidReg },
500         { x86_64::rax, x86_64::rcx, x86_64::rdx, x86_64::rbx, x86_64::rsp, x86_64::rbp, x86_64::rsi, x86_64::rdi },
501         { x86_64::xmm0, x86_64::xmm1, x86_64::xmm2, x86_64::xmm3, x86_64::xmm4, x86_64::xmm5, x86_64::xmm6, x86_64::xmm7 }, /* b_xmm_set0 */
502         { x86_64::xmm8, x86_64::xmm9, x86_64::xmm10, x86_64::xmm11, x86_64::xmm12, x86_64::xmm13, x86_64::xmm14, x86_64::xmm15 }, /* b_xmm_set1 */
503         { x86_64::xmm16, x86_64::xmm17, x86_64::xmm18, x86_64::xmm19, x86_64::xmm20, x86_64::xmm21, x86_64::xmm22, x86_64::xmm23 }, /* b_xmm_set2 */
504         { x86_64::xmm24, x86_64::xmm25, x86_64::xmm26, x86_64::xmm27, x86_64::xmm28, x86_64::xmm29, x86_64::xmm30, x86_64::xmm31 }, /* b_xmm_set3 */
505         { x86_64::ymm0, x86_64::ymm1, x86_64::ymm2, x86_64::ymm3, x86_64::ymm4, x86_64::ymm5, x86_64::ymm6, x86_64::ymm7 }, /* b_ymm_set0 */
506         { x86_64::ymm8, x86_64::ymm9, x86_64::ymm10, x86_64::ymm11, x86_64::ymm12, x86_64::ymm13, x86_64::ymm14, x86_64::ymm15 }, /* b_ymm_set1 */
507         { x86_64::ymm16, x86_64::ymm17, x86_64::ymm18, x86_64::ymm19, x86_64::ymm20, x86_64::ymm21, x86_64::ymm22, x86_64::ymm23 }, /* b_ymm_set2 */
508         { x86_64::ymm24, x86_64::ymm25, x86_64::ymm26, x86_64::ymm27, x86_64::ymm28, x86_64::ymm29, x86_64::ymm30, x86_64::ymm31 }, /* b_ymm_set3 */
509         { x86_64::zmm0, x86_64::zmm1, x86_64::zmm2, x86_64::zmm3, x86_64::zmm4, x86_64::zmm5, x86_64::zmm6, x86_64::zmm7 }, /* b_zmm_set0 */
510         { x86_64::zmm8, x86_64::zmm9, x86_64::zmm10, x86_64::zmm11, x86_64::zmm12, x86_64::zmm13, x86_64::zmm14, x86_64::zmm15 }, /* b_zmm_set1 */
511         { x86_64::zmm16, x86_64::zmm17, x86_64::zmm18, x86_64::zmm19, x86_64::zmm20, x86_64::zmm21, x86_64::zmm22, x86_64::zmm23 }, /* b_zmm_set2 */
512         { x86_64::zmm24, x86_64::zmm25, x86_64::zmm26, x86_64::zmm27, x86_64::zmm28, x86_64::zmm29, x86_64::zmm30, x86_64::zmm31 }, /* b_zmm_set3 */
513         { x86_64::mm0, x86_64::mm1, x86_64::mm2, x86_64::mm3, x86_64::mm4, x86_64::mm5, x86_64::mm6, x86_64::mm7 },
514         { x86_64::cr0, x86_64::cr1, x86_64::cr2, x86_64::cr3, x86_64::cr4, x86_64::cr5, x86_64::cr6, x86_64::cr7 },
515         { x86_64::dr0, x86_64::dr1, x86_64::dr2, x86_64::dr3, x86_64::dr4, x86_64::dr5, x86_64::dr6, x86_64::dr7 },
516         { x86_64::tr0, x86_64::tr1, x86_64::tr2, x86_64::tr3, x86_64::tr4, x86_64::tr5, x86_64::tr6, x86_64::tr7 },
517         { x86_64::r8, x86_64::r9, x86_64::r10, x86_64::r11, x86_64::r12, x86_64::r13, x86_64::r14, x86_64::r15 },
518         { x86_64::al, x86_64::cl, x86_64::dl, x86_64::bl, x86_64::spl, x86_64::bpl, x86_64::sil, x86_64::dil },
519         { x86_64::st0, x86_64::st1, x86_64::st2, x86_64::st3, x86_64::st4, x86_64::st5, x86_64::st6, x86_64::st7 },
520             { x86_64::r8b, x86_64::r9b, x86_64::r10b, x86_64::r11b, x86_64::r12b, x86_64::r13b, x86_64::r14b, x86_64::r15b },
521             { x86_64::r8w, x86_64::r9w, x86_64::r10w, x86_64::r11w, x86_64::r12w, x86_64::r13w, x86_64::r14w, x86_64::r15w },
522             { x86_64::r8d, x86_64::r9d, x86_64::r10d, x86_64::r11d, x86_64::r12d, x86_64::r13d, x86_64::r14d, x86_64::r15d },
523     };
524
525   /* Uses the appropriate lookup table based on the 
526      decoder architecture */
527   class IntelRegTable_access {
528     public:
529         inline MachRegister operator()(Architecture arch,
530                                        intelRegBanks bank,
531                                        int index)
532         {
533             assert(index >= 0 && index < 8);
534     
535             if(arch == Arch_x86_64)
536                 return IntelRegTable64[bank][index];
537             else if(arch == Arch_x86) 
538             {
539               if(bank > b_fpstack) return InvalidReg;
540               return IntelRegTable32[bank][index];
541             }
542             assert(0);
543             return InvalidReg;
544         }
545
546   };
547   static IntelRegTable_access IntelRegTable;
548
549       bool InstructionDecoder_x86::isDefault64Insn()
550       {
551         switch(m_Operation->getID())
552         {
553         case e_jmp:
554         case e_pop:
555         case e_push:
556         case e_call:
557           return true;
558         default:
559           return false;
560         }
561         
562       }
563       
564
565     MachRegister InstructionDecoder_x86::makeRegisterID(unsigned int intelReg, unsigned int opType,
566                                         bool isExtendedReg)
567     {
568         MachRegister retVal;
569         
570
571         if(isExtendedReg)
572         {
573             switch(opType)
574             {
575                 case op_q:  
576                     retVal = IntelRegTable(m_Arch,b_amd64ext,intelReg);
577                     break;
578                 case op_d:
579                     retVal = IntelRegTable(m_Arch,amd64_ext_32,intelReg);
580                     break;
581                 case op_w:
582                     retVal = IntelRegTable(m_Arch,amd64_ext_16,intelReg);
583                     break;
584                 case op_b:
585                     retVal = IntelRegTable(m_Arch,amd64_ext_8,intelReg);
586                     break;
587                 case op_v:
588                     if (locs->rex_w || isDefault64Insn())
589                         retVal = IntelRegTable(m_Arch, b_amd64ext, intelReg);
590                     else if (!sizePrefixPresent)
591                         retVal = IntelRegTable(m_Arch, amd64_ext_32, intelReg);
592                     //else
593                     //    retVal = IntelRegTable(m_Arch, amd64_ext_16, intelReg);
594                     break;      
595                 case op_p:
596                 case op_z:
597                     //              if (!sizePrefixPresent)
598                         retVal = IntelRegTable(m_Arch, amd64_ext_32, intelReg);
599                         //                  else
600                         //  retVal = IntelRegTable(m_Arch, amd64_ext_16, intelReg);
601                     break;
602             case op_f:
603             case op_dbl:
604                 // extended reg ignored on FP regs
605                 retVal = IntelRegTable(m_Arch, b_fpstack,intelReg);
606                 break;
607                 default:
608                     retVal = InvalidReg;
609             }
610         }
611         /* Promotion to 64-bit only applies to the operand types
612            that are varible (c,v,z). Ignoring c and z because they
613            do the right thing on 32- and 64-bit code.
614         else if(locs->rex_w)
615         {
616             // AMD64 with 64-bit operands
617             retVal = IntelRegTable[b_64bit][intelReg];
618         }
619         */
620         else
621         {
622             switch(opType)
623             {
624                 case op_v:
625                   if(locs->rex_w || isDefault64Insn())
626                         retVal = IntelRegTable(m_Arch,b_64bit,intelReg);
627                     else
628                         retVal = IntelRegTable(m_Arch,b_32bit,intelReg);
629                     break;
630                 case op_b:
631                     if (locs->rex_byte & 0x40) {
632                         retVal = IntelRegTable(m_Arch,b_8bitWithREX,intelReg);
633                     } else {
634                         retVal = IntelRegTable(m_Arch,b_8bitNoREX,intelReg);
635                     }
636                     break;
637                 case op_q:
638                     retVal = IntelRegTable(m_Arch,b_64bit,intelReg);
639                     break;
640                 case op_w:
641                     retVal = IntelRegTable(m_Arch,b_16bit,intelReg);
642                     break;
643                 case op_f:
644                 case op_dbl:
645                     retVal = IntelRegTable(m_Arch,b_fpstack,intelReg);
646                     break;
647                 case op_d:
648                 case op_si:
649                     retVal = IntelRegTable(m_Arch,b_32bit,intelReg);
650                     break;
651                 default:
652                     retVal = IntelRegTable(m_Arch,b_32bit,intelReg);
653                     break;
654             }
655         }
656
657         if (!ia32_is_mode_64()) {
658           if ((retVal.val() & 0x00ffffff) == 0x0001000c)
659             assert(0);
660         }
661
662         return MachRegister((retVal.val() & ~retVal.getArchitecture()) | m_Arch);
663     }
664     
665     Result_Type InstructionDecoder_x86::makeSizeType(unsigned int opType)
666     {
667         switch(opType)
668         {
669             case op_b:
670             case op_c:
671                 return u8;
672             case op_d:
673             case op_ss:
674             case op_allgprs:
675             case op_si:
676                 return u32;
677             case op_w:
678             case op_a:
679                 return u16;
680             case op_q:
681             case op_sd:
682                 return u64;
683             case op_v:
684             case op_lea:
685             case op_z:
686                 if (locs->rex_w) 
687                 {
688                     return u64;
689                 }
690                 //if(ia32_is_mode_64() || !sizePrefixPresent)
691                 //{
692                     return u32;
693                     //}
694                     //else
695                     //{
696                     //return u16;
697                     //}
698                 break;
699             case op_y:
700                 if(ia32_is_mode_64())
701                         return u64;
702                 else
703                         return u32;
704                 break;
705             case op_p:
706                 // book says operand size; arch-x86 says word + word * operand size
707                 if(!ia32_is_mode_64() ^ sizePrefixPresent)
708                 {
709                     return u48;
710                 }
711                 else
712                 {
713                     return u32;
714                 }
715             case op_dq:
716             case op_qq:
717                 return u64;
718             case op_512:
719                 return m512;
720             case op_pi:
721             case op_ps:
722             case op_pd:
723                 return dbl128;
724             case op_s:
725                 return u48;
726             case op_f:
727                 return sp_float;
728             case op_dbl:
729                 return dp_float;
730             case op_14:
731                 return m14;
732             default:
733                 assert(!"Can't happen!");
734                 return u8;
735         }
736     }
737
738     enum AVX_Regtype { AVX_XMM = 0, AVX_YMM, AVX_ZMM, AVX_NONE };
739     #define AVX_TYPE_OKAY(type) ((type) >= AVX_XMM && (type) <= AVX_ZMM)
740     /** 
741      * Decode an avx register based on the type of prefix. Returns true if the
742      * given configuration is invalid and should be rejected.
743      */
744     bool decodeAVX(intelRegBanks& bank, int* bank_index, int regnum, AVX_Regtype type)
745     {
746       if(type == AVX_NONE)
747       {
748         /* The register must be valid */
749         if(regnum < 0) return true;
750
751         if(regnum <= 7)
752         {
753           bank = b_xmm_set0;
754           *bank_index = regnum;
755         } else if(regnum <= 15)
756         {
757           bank = b_xmm_set1;
758           *bank_index = regnum - 8;
759         } else {
760           return true;
761         }
762   
763         /* Return success */
764         return false;
765       }
766
767       /* Operand comes from the VEX.vvvv bits */
768       int setnum = 0;
769       if(regnum < 8)
770       {
771         setnum = 0;
772         *bank_index = regnum;
773       } else if(regnum < 16)
774       {
775         setnum = 1;
776         *bank_index = regnum - 8;
777       } else if(regnum < 24)
778       {
779         setnum = 2;
780         *bank_index = regnum - 16;
781       } else if(regnum < 32){
782         setnum = 3;
783         *bank_index = regnum - 24;
784       } else {
785 #ifdef VEX_DEBUG
786         printf("AVX REGISTER NUMBER:   %d   is invalid!!\n", regnum);
787 #endif
788         return false;
789       }
790
791       switch(type)
792       {
793         case AVX_XMM:
794           if(setnum == 0)
795             bank = b_xmm_set0;
796           else if(setnum == 1)
797             bank = b_xmm_set1;
798           else if(setnum == 2)
799             bank = b_xmm_set2;
800           else if(setnum == 3)
801             bank = b_xmm_set3;
802           else assert(0);
803           break;
804         case AVX_YMM:
805           if(setnum == 0)
806             bank = b_ymm_set0;
807           else if(setnum == 1)
808             bank = b_ymm_set1;
809           else if(setnum == 2)
810             bank = b_ymm_set2;
811           else if(setnum == 3)
812             bank = b_ymm_set3;
813           else assert(0);
814           break;
815         case AVX_ZMM:
816           if(setnum == 0)
817             bank = b_zmm_set0;
818           else if(setnum == 1)
819             bank = b_zmm_set1;
820           else if(setnum == 2)
821             bank = b_zmm_set2;
822           else if(setnum == 3)
823             bank = b_zmm_set3;
824           else assert(0);
825           break;
826         default:
827           
828           return true;
829       }
830
831       return false;
832     }
833
834     bool InstructionDecoder_x86::decodeOneOperand(const InstructionDecoder::buffer& b,
835                                                   const ia32_operand& operand,
836                                                   int & imm_index, /* immediate operand index */
837                                                   const Instruction* insn_to_complete, 
838                                                   bool isRead, bool isWritten)
839     {
840       bool isCFT = false;
841       bool isCall = false;
842       bool isConditional = false;
843       InsnCategory cat = insn_to_complete->getCategory();
844       if(cat == c_BranchInsn || cat == c_CallInsn)
845             {
846               isCFT = true;
847               if(cat == c_CallInsn)
848               {
849                 isCall = true;
850               }
851             }
852
853       if (cat == c_BranchInsn && insn_to_complete->getOperation().getID() != e_jmp) 
854       {
855               isConditional = true;
856       }
857
858       unsigned int optype = operand.optype;
859         int vex_vvvv = 0; /* The register selected by the VEX prefix (1111 if unused) */
860         bool has_vex = false; /* Whether any sort of VEX prefix is present */
861         AVX_Regtype avx_type = AVX_NONE; /* The AVX register type (if VEX prefixed) */
862         intelRegBanks bank = b_invalid; /* Specifies an AVX bank to use for register decoding */
863         int bank_index = -1; /* Specifies a bank index for an AVX register */
864       if(decodedInstruction && decodedInstruction->getPrefix()->vex_prefix[0])
865       {
866         has_vex = true;
867             /* Get the AVX type from the prefix */
868             avx_type = (AVX_Regtype)decodedInstruction->getPrefix()->vex_ll;
869
870         /* The vvvv bits are bits 3, 4, 5, 6 and are in 1's complement */
871         if(decodedInstruction->getPrefix()->vex_prefix[2]) /* AVX512 (EVEX) */
872         {
873           vex_vvvv = (unsigned char)EVEXGET_VVVV(decodedInstruction->getPrefix()->vex_prefix[1]);
874
875                 /* The last 5 bits must be flipped to be used for EVEX */
876                 vex_vvvv = (unsigned char)((~vex_vvvv) & 0x0F);
877         } else if(decodedInstruction->getPrefix()->vex_prefix[1]){ /* AVX2 (VEX3) */
878           vex_vvvv = (unsigned char)VEXGET_VVVV(decodedInstruction->getPrefix()->vex_prefix[1]);
879
880                 /* The last 4 bits must be flipped to be used for VEX3 */
881                 vex_vvvv = (unsigned char)((~vex_vvvv) & 0x0F);
882         } else { /* AVX (VEX2) */
883           vex_vvvv = (unsigned char)VEXGET_VVVV(decodedInstruction->getPrefix()->vex_prefix[0]);
884
885                 /* The last 4 bits must be flipped to be used for VEX2*/
886                 vex_vvvv = (unsigned char)((~vex_vvvv) & 0x0F);
887             }
888       }
889
890       if (sizePrefixPresent 
891         && ((optype == op_v) || (optype == op_z)) 
892         && (operand.admet != am_J)) 
893       {
894                 optype = op_w;
895       }
896
897         if(optype == op_y) 
898         {
899           if(ia32_is_mode_64() && locs->rex_w)
900             {
901                   optype = op_q;
902             } else {
903                   optype = op_d;
904       }
905         }
906      
907                 switch(operand.admet)
908                 {
909                     case 0:
910                     // No operand
911                         assert(!"Mismatched number of operands--check tables");
912                         return false;
913                     case am_A:
914                     {
915                         // am_A only shows up as a far call/jump.  Position 1 should be universally safe.
916                         Expression::Ptr addr(decodeImmediate(optype, b.start + 1));
917                         insn_to_complete->addSuccessor(addr, isCall, false, false, false);
918                     }
919                     break;
920                     case am_C:
921                     {
922                         Expression::Ptr op(makeRegisterExpression(IntelRegTable(m_Arch,b_cr,locs->modrm_reg)));
923                         insn_to_complete->appendOperand(op, isRead, isWritten);
924                     }
925                     break;
926                     case am_D:
927                     {
928                         Expression::Ptr op(makeRegisterExpression(IntelRegTable(m_Arch,b_dr,locs->modrm_reg)));
929                         insn_to_complete->appendOperand(op, isRead, isWritten);
930                     }
931                     break;
932                     case am_E:
933                     // am_M is like am_E, except that mod of 0x03 should never occur (am_M specified memory,
934                     // mod of 0x03 specifies direct register access).
935                     case am_M:
936                     // am_R is the inverse of am_M; it should only have a mod of 3
937                     case am_R:
938                     // can be am_R or am_M      
939                     case am_RM: 
940                         if(isCFT)
941                         {
942                           insn_to_complete->addSuccessor(makeModRMExpression(b, optype), isCall, true, false, false);
943                 } else {
944                           insn_to_complete->appendOperand(makeModRMExpression(b, optype), isRead, isWritten);
945                         }
946                     break;
947                     case am_F:
948                     {
949                         Expression::Ptr op(makeRegisterExpression(x86::flags));
950                         insn_to_complete->appendOperand(op, isRead, isWritten);
951                     }
952                     break;
953                     case am_G:
954                     {
955                     Expression::Ptr op(makeRegisterExpression(makeRegisterID(locs->modrm_reg, optype, locs->rex_r)));
956                         insn_to_complete->appendOperand(op, isRead, isWritten);
957                     }
958                     break;
959             case am_H: /* Could be XMM, YMM or ZMM */
960                 /* Make sure this register class is valid for VEX */
961                 if(!AVX_TYPE_OKAY(avx_type) || !has_vex)
962                     return false;
963
964                 /* Grab the correct bank and bank index for this type of register */
965                 if(decodeAVX(bank, &bank_index, vex_vvvv, avx_type))
966                     return false;
967
968                 /* Append the operand */
969                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
970                 break;
971             case am_XH: /* Must be XMM */
972                 /* Make sure we are using a valid VEX register class */
973                 if(!AVX_TYPE_OKAY(avx_type) || !has_vex)
974                     return false;
975
976                 /* Constrain register type to only the XMM banks */
977                 avx_type = AVX_XMM;
978
979                 /* Grab the correct bank and bank index for this type of register */
980                 if(decodeAVX(bank, &bank_index, vex_vvvv, avx_type))
981                     return false;
982                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
983                 break;
984             case am_YH: /* Could be XMM or YMM */
985                 /* Make sure we are using a valid VEX register class */
986                 if(!AVX_TYPE_OKAY(avx_type) || !has_vex)
987                     return false;
988
989                 /* Constrain to only XMM or YMM registers */
990                 if(avx_type != AVX_XMM && avx_type != AVX_YMM)
991                     avx_type = AVX_YMM;
992
993                 /* Grab the correct bank and bank index for this type of register */
994                 if(decodeAVX(bank, &bank_index, vex_vvvv, avx_type))
995                     return false;
996
997                 /* Append the operand */
998                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
999                       break;
1000                     case am_I:
1001                 insn_to_complete->appendOperand(decodeImmediate(optype, b.start + locs->imm_position[imm_index++]), isRead, isWritten);
1002                         break;
1003                     case am_J:
1004                     {
1005                     Expression::Ptr Offset(decodeImmediate(optype, b.start + locs->imm_position[imm_index++], true));
1006                         Expression::Ptr EIP(makeRegisterExpression(MachRegister::getPC(m_Arch)));
1007                         Expression::Ptr InsnSize(make_shared(singleton_object_pool<Immediate>::construct(Result(u8,
1008                             decodedInstruction->getSize()))));
1009                         Expression::Ptr postEIP(makeAddExpression(EIP, InsnSize, u32));
1010
1011                         Expression::Ptr op(makeAddExpression(Offset, postEIP, u32));
1012                         insn_to_complete->addSuccessor(op, isCall, false, isConditional, false);
1013                         if (isConditional) 
1014                     {
1015                           insn_to_complete->addSuccessor(postEIP, false, false, true, true);
1016                     }
1017                 }
1018                     break;
1019                     case am_O:
1020                     {
1021                     // Address/offset width, which is *not* what's encoded by the optype...
1022                     // The deref's width is what's actually encoded here.
1023                         int pseudoOpType;
1024                         switch(locs->address_size)
1025                         {
1026                             case 1:
1027                                 pseudoOpType = op_b;
1028                                 break;
1029                             case 2:
1030                                 pseudoOpType = op_w;
1031                                 break;
1032                             case 4:
1033                                 pseudoOpType = op_d;
1034                                 break;
1035                             case 0:
1036                                 if(m_Arch == Arch_x86_64) {
1037                                     if(!addrSizePrefixPresent)
1038                                 {
1039                                         pseudoOpType = op_q;
1040                                 } else {
1041                                         pseudoOpType = op_d;
1042                                 }
1043                                 } else {
1044                                     pseudoOpType = op_v;
1045                                 }
1046                                 break;
1047                             default:
1048                                 assert(!"Bad address size, should be 0, 1, 2, or 4!");
1049                                 pseudoOpType = op_b;
1050                                 break;
1051                         }
1052
1053                         int offset_position = locs->opcode_position;
1054                     if(locs->modrm_position > offset_position && locs->modrm_operand < (int)(insn_to_complete->m_Operands.size()))
1055                         {
1056                             offset_position = locs->modrm_position;
1057                         }
1058                         if(locs->sib_position > offset_position)
1059                         {
1060                             offset_position = locs->sib_position;
1061                         }
1062                         offset_position++;
1063                         insn_to_complete->appendOperand(makeDereferenceExpression(
1064                     decodeImmediate(pseudoOpType, b.start + offset_position), makeSizeType(optype)), isRead, isWritten);
1065                     }
1066                     break;
1067                     case am_P:
1068                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch,b_mm,locs->modrm_reg)), isRead, isWritten);
1069                         break;
1070                     case am_Q:
1071                         switch(locs->modrm_mod)
1072                         {
1073                             // direct dereference
1074                             case 0x00:
1075                             case 0x01:
1076                             case 0x02:
1077                               insn_to_complete->appendOperand(makeModRMExpression(b, optype), isRead, isWritten);
1078                                 break;
1079                             case 0x03:
1080                                 // use of actual register
1081                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch,b_mm,locs->modrm_rm)), isRead, isWritten);
1082                                 break;
1083                             default:
1084                                 assert(!"2-bit value modrm_mod out of range");
1085                                 break;
1086                 }
1087                         break;
1088                     case am_S:
1089                     // Segment register in modrm reg field.
1090                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch,b_segment,locs->modrm_reg)), isRead, isWritten);
1091                         break;
1092                     case am_T:
1093                         // test register in modrm reg; should only be tr6/tr7, but we'll decode any of them
1094                         // NOTE: this only appears in deprecated opcodes
1095                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch,b_tr,locs->modrm_reg)), isRead, isWritten);
1096                         break;
1097                     case am_UM:
1098                         switch(locs->modrm_mod)
1099                         {
1100                         // direct dereference
1101                         case 0x00:
1102                         case 0x01:
1103                         case 0x02:
1104                         insn_to_complete->appendOperand(makeModRMExpression(b, makeSizeType(optype)), isRead, isWritten);
1105                                 break;
1106                         case 0x03:
1107                                 // use of actual register
1108                         decodeAVX(bank, &bank_index, locs->modrm_rm, AVX_XMM);
1109                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1110                                         break;
1111                         default:
1112                                 assert(!"2-bit value modrm_mod out of range");
1113                                 break;
1114                 }
1115           
1116                         break;
1117             case am_V: /* Could be XMM, YMM or ZMM (possibly non VEX)*/
1118                 /* Is this a vex prefixed instruction? */  
1119                 if(has_vex)
1120                 {
1121                     if(!AVX_TYPE_OKAY(avx_type))
1122                         return false;
1123                 }
1124
1125                 /* Get the register bank and the index */
1126                 if(decodeAVX(bank, &bank_index, locs->modrm_reg, avx_type))
1127                     return false;
1128     
1129                 /* Append the operand */
1130                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1131                 break;
1132             case am_XV: /* Must be XMM (must be VEX) */
1133                 
1134                 if(!AVX_TYPE_OKAY(avx_type) || !has_vex)
1135                     return false;
1136
1137                 /* Get the register bank and the index */
1138                 if(decodeAVX(bank, &bank_index, locs->modrm_reg, avx_type))
1139                     return false;
1140   
1141                 /* Append the operand */
1142                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1143                 break;
1144             case am_YV: /* Must be XMM or YMM (must be VEX) */
1145                 /* Make sure this register class is valid */
1146                 if(!AVX_TYPE_OKAY(avx_type) || !has_vex)
1147                     return false;
1148
1149                 /* Constrain to either XMM or YMM registers */
1150                 if(avx_type != AVX_XMM && avx_type != AVX_YMM)
1151                     avx_type = AVX_YMM;
1152
1153                 /* Get the register bank and index */
1154                 if(decodeAVX(bank, &bank_index, locs->modrm_reg, avx_type))
1155                     return false;
1156                        
1157                 /* Append the operand */
1158                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1159                         break;
1160             case am_U: /* Could be XMM, YMM, or ZMM (or possibly non VEX)*/
1161
1162                 /* Is this a vex prefixed instruction? */  
1163                 if(has_vex)
1164                 {
1165                     if(!AVX_TYPE_OKAY(avx_type))
1166                         return false;
1167                 }
1168
1169                 /* Grab the register bank and index */
1170                 if(decodeAVX(bank, &bank_index, locs->modrm_rm, AVX_XMM))
1171                     return false;
1172
1173                 /* Append the operand */
1174                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1175                 break;
1176             case am_XU: /* Must be XMM (must be VEX) */
1177                 /* Make sure this register class is valid */
1178                 if(!AVX_TYPE_OKAY(avx_type) || !has_vex)
1179                     return false;
1180   
1181                 /* Constrain register to XMM banks only */        
1182                 avx_type = AVX_XMM;
1183
1184                 /* Get the register bank and index for this register */
1185                 if(decodeAVX(bank, &bank_index, locs->modrm_rm, avx_type))
1186                     return false;
1187
1188                 /* Append the operand */
1189                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1190                 break;
1191             case am_YU: /* Must be XMM or YMM (must be VEX) */
1192                 /* Make sure this register class is valid */
1193                 if(!AVX_TYPE_OKAY(avx_type) || !has_vex)
1194                     return false;
1195
1196                 /* Constrain to either XMM or YMM registers */
1197                 if(avx_type != AVX_XMM && avx_type != AVX_YMM)
1198                     avx_type = AVX_YMM;
1199
1200                 /* Get the register bank and index */
1201                 if(decodeAVX(bank, &bank_index, locs->modrm_rm, avx_type))
1202                     return false;
1203
1204                 /* Append the operand */
1205                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1206                 break;
1207             case am_W: /* Could be XMM, YMM, or ZMM (or possibly not VEX) */
1208
1209                 if(has_vex)
1210                 {
1211                     if(!AVX_TYPE_OKAY(avx_type))
1212                         return false;
1213                 }
1214
1215                         switch(locs->modrm_mod)
1216                         {
1217                     /* Direct dereference */
1218                             case 0x00:
1219                             case 0x01:
1220                             case 0x02:
1221                                     insn_to_complete->appendOperand(makeModRMExpression(b, makeSizeType(optype)), isRead, isWritten);
1222                                 break;
1223                             case 0x03:
1224                         /* Just the register is used */
1225                         if(decodeAVX(bank, &bank_index, locs->modrm_rm, avx_type))
1226                             return false;
1227                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1228                         break;
1229                     default:
1230                         assert(!"2-bit value modrm_mod out of range");
1231                         break;
1232                 }
1233                 break;
1234             case am_XW: /* Must be XMM (must be VEX) */
1235
1236                 /* Make sure this vex is okay */
1237                 if(!AVX_TYPE_OKAY(avx_type) || !has_vex)
1238                     return false;
1239          
1240                 /* Constrain to the XMM banks */ 
1241                 avx_type = AVX_XMM;
1242
1243                 switch(locs->modrm_mod)
1244                             {
1245                     /* Direct dereference */
1246                     case 0x00:
1247                     case 0x01:
1248                     case 0x02:
1249                         insn_to_complete->appendOperand(makeModRMExpression(b, makeSizeType(optype)), isRead, isWritten);
1250                         break;
1251                     case 0x03:
1252                         /* Just the register is used */
1253                         if(decodeAVX(bank, &bank_index, locs->modrm_rm, avx_type))
1254                             return false;
1255                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1256                         break;
1257                     default:
1258                         assert(!"2-bit value modrm_mod out of range");
1259                                 break;
1260                             }
1261                 break;
1262             case am_YW: /* Must be either YMM or XMM (must be VEX) */
1263
1264                 /* Make sure the register class is okay and we have a vex prefix */
1265                 if(!AVX_TYPE_OKAY(avx_type) || !has_vex)
1266                     return false;
1267
1268                 /* Constrain to either XMM or YMM registers */
1269                 if(avx_type != AVX_XMM && avx_type != AVX_YMM)
1270                     avx_type = AVX_YMM;
1271
1272                 switch(locs->modrm_mod)
1273                 {
1274                     /* Direct dereference */
1275                     case 0x00:
1276                     case 0x01:
1277                     case 0x02:
1278                         insn_to_complete->appendOperand(makeModRMExpression(b, makeSizeType(optype)), isRead, isWritten);
1279                         break;
1280                     case 0x03:
1281                         /* Just the register is used */
1282                         if(decodeAVX(bank, &bank_index, locs->modrm_rm, avx_type))
1283                             return false;
1284
1285                         /* Append the operand */
1286                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch, bank, bank_index)), isRead, isWritten);
1287                         break;
1288                             default:
1289                                 assert(!"2-bit value modrm_mod out of range");
1290                                 break;
1291                 }
1292                         break;
1293                     case am_X:
1294                     {
1295                         MachRegister si_reg;
1296                         if(m_Arch == Arch_x86)
1297                         {
1298                                 if(addrSizePrefixPresent)
1299                                 {
1300                                         si_reg = x86::si;
1301                         } else {
1302                                         si_reg = x86::esi;
1303                                 }
1304                     } else {
1305                                 if(addrSizePrefixPresent)
1306                                 {
1307                                         si_reg = x86_64::esi;
1308                         } else {
1309                                         si_reg = x86_64::rsi;
1310                                 }
1311                         }
1312
1313                         Expression::Ptr ds(makeRegisterExpression(m_Arch == Arch_x86 ? x86::ds : x86_64::ds));
1314                         Expression::Ptr si(makeRegisterExpression(si_reg));
1315                     Expression::Ptr segmentOffset(make_shared(singleton_object_pool<Immediate>::construct(Result(u32, 0x10))));
1316                         Expression::Ptr ds_segment = makeMultiplyExpression(ds, segmentOffset, u32);
1317                         Expression::Ptr ds_si = makeAddExpression(ds_segment, si, u32);
1318                     insn_to_complete->appendOperand(makeDereferenceExpression(ds_si, makeSizeType(optype)), isRead, isWritten);
1319                     }
1320                     break;
1321                     case am_Y:
1322                     {
1323                         MachRegister di_reg;
1324                         if(m_Arch == Arch_x86)
1325                         {
1326                                 if(addrSizePrefixPresent)
1327                                 {
1328                                         di_reg = x86::di;
1329                         } else {
1330                                         di_reg = x86::edi;
1331                                 }
1332                     } else {
1333                                 if(addrSizePrefixPresent)
1334                                 {
1335                                         di_reg = x86_64::edi;
1336                         } else {
1337                                         di_reg = x86_64::rdi;
1338                                 }
1339                         }
1340                         Expression::Ptr es(makeRegisterExpression(m_Arch == Arch_x86 ? x86::es : x86_64::es));
1341                         Expression::Ptr di(makeRegisterExpression(di_reg));
1342                         Expression::Ptr es_segment = makeMultiplyExpression(es,
1343                             make_shared(singleton_object_pool<Immediate>::construct(Result(u32, 0x10))), u32);
1344                         Expression::Ptr es_di = makeAddExpression(es_segment, di, u32);
1345                     insn_to_complete->appendOperand(makeDereferenceExpression(es_di, makeSizeType(optype)), isRead, isWritten);
1346                     }
1347                     break;
1348                     case am_tworeghack:
1349                         if(optype == op_edxeax)
1350                         {
1351                             Expression::Ptr edx(makeRegisterExpression(m_Arch == Arch_x86 ? x86::edx : x86_64::edx));
1352                             Expression::Ptr eax(makeRegisterExpression(m_Arch == Arch_x86 ? x86::eax : x86_64::eax));
1353                     Expression::Ptr highAddr = makeMultiplyExpression(edx, Immediate::makeImmediate(Result(u64, 2^32)), u64);
1354                             Expression::Ptr addr = makeAddExpression(highAddr, eax, u64);
1355                             Expression::Ptr op = makeDereferenceExpression(addr, u64);
1356                             insn_to_complete->appendOperand(op, isRead, isWritten);
1357                 } else if (optype == op_ecxebx)
1358                         {
1359                             Expression::Ptr ecx(makeRegisterExpression(m_Arch == Arch_x86 ? x86::ecx : x86_64::ecx));
1360                             Expression::Ptr ebx(makeRegisterExpression(m_Arch == Arch_x86 ? x86::ebx : x86_64::ebx));
1361                             Expression::Ptr highAddr = makeMultiplyExpression(ecx,
1362                                     Immediate::makeImmediate(Result(u64, 2^32)), u64);
1363                             Expression::Ptr addr = makeAddExpression(highAddr, ebx, u64);
1364                             Expression::Ptr op = makeDereferenceExpression(addr, u64);
1365                             insn_to_complete->appendOperand(op, isRead, isWritten);
1366                         }
1367                     break;
1368                     
1369                     case am_reg:
1370                     {
1371                         MachRegister r(optype);
1372                         int size = r.size();
1373                     if((m_Arch == Arch_x86_64) && (r.regClass() == (unsigned int)x86::GPR) && (size == 4))
1374                         {
1375                             int reg_size = isDefault64Insn() ? op_q : op_v;
1376                             if(sizePrefixPresent)
1377                             {
1378                                 reg_size = op_w;
1379                             }
1380                             // implicit regs are not extended
1381                             r = makeRegisterID((r.val() & 0xFF), reg_size, false);
1382                             entryID entryid = decodedInstruction->getEntry()->getID(locs);
1383                             if(locs->rex_b && insn_to_complete->m_Operands.empty() &&
1384                                (entryid == e_push || entryid == e_pop || entryid == e_xchg || ((*(b.start + locs->opcode_position) & 0xf0) == 0xb0)))
1385                             {
1386                                 r = MachRegister((r.val()) | x86_64::r8.val());
1387                                 assert(r.name() != "<INVALID_REG>");
1388                             }
1389                     } else {
1390                             r = MachRegister((r.val() & ~r.getArchitecture()) | m_Arch);
1391                             
1392                             entryID entryid = decodedInstruction->getEntry()->getID(locs);
1393                             if(insn_to_complete->m_Operands.empty() && 
1394                                (entryid == e_push || entryid == e_pop || entryid == e_xchg || ((*(b.start + locs->opcode_position) & 0xf0) == 0xb0) ) )
1395                             {
1396                                 unsigned int opcode_byte = *(b.start+locs->opcode_position);
1397                                 unsigned int reg_id = (opcode_byte & 0x07);
1398                                 if(locs->rex_b) 
1399                                 {
1400                                     // FP stack registers are not affected by the rex_b bit in AM_REG.
1401                                     if(r.regClass() == (unsigned) x86::GPR)
1402                                     {
1403                                         int reg_op_type = op_d;
1404                                         switch(size)
1405                                         {
1406                                         case 1:
1407                                             reg_op_type = op_b;
1408                                             break;
1409                                         case 2:
1410                                             reg_op_type = op_w;
1411                                             break;
1412                                         case 8:
1413                                             reg_op_type = op_q;
1414                                             break;
1415                                         default:
1416                                             break;
1417                                         }
1418
1419                                         r = makeRegisterID(reg_id, reg_op_type, true);
1420                                         assert(r.name() != "<INVALID_REG>");
1421                                     }
1422                             } else if((r.size() == 1) && (locs->rex_byte & 0x40))
1423                                 {
1424                                     r = makeRegisterID(reg_id, op_b, false);
1425                                     assert(r.name() != "<INVALID_REG>");
1426                                 }
1427                             }
1428
1429                         if(sizePrefixPresent && (r.regClass() == (unsigned int)x86::GPR) && r.size() >= 4)
1430                             {
1431                                 r = MachRegister((r.val() & ~x86::FULL) | x86::W_REG);
1432                                 assert(r.name() != "<INVALID_REG>");
1433                             }
1434                         }
1435                         Expression::Ptr op(makeRegisterExpression(r));
1436                         insn_to_complete->appendOperand(op, isRead, isWritten);
1437                     }
1438                     break;
1439                 case am_stackH:
1440                 case am_stackP:
1441                 // handled elsewhere
1442                     break;
1443                 case am_allgprs:
1444                     if(m_Arch == Arch_x86)
1445                     {
1446                         insn_to_complete->appendOperand(makeRegisterExpression(x86::eax), isRead, isWritten);
1447                         insn_to_complete->appendOperand(makeRegisterExpression(x86::ecx), isRead, isWritten);
1448                         insn_to_complete->appendOperand(makeRegisterExpression(x86::edx), isRead, isWritten);
1449                         insn_to_complete->appendOperand(makeRegisterExpression(x86::ebx), isRead, isWritten);
1450                         insn_to_complete->appendOperand(makeRegisterExpression(x86::esp), isRead, isWritten);
1451                         insn_to_complete->appendOperand(makeRegisterExpression(x86::ebp), isRead, isWritten);
1452                         insn_to_complete->appendOperand(makeRegisterExpression(x86::esi), isRead, isWritten);
1453                         insn_to_complete->appendOperand(makeRegisterExpression(x86::edi), isRead, isWritten);
1454                 } else {
1455                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::eax), isRead, isWritten);
1456                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::ecx), isRead, isWritten);
1457                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::edx), isRead, isWritten);
1458                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::ebx), isRead, isWritten);
1459                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::esp), isRead, isWritten);
1460                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::ebp), isRead, isWritten);
1461                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::esi), isRead, isWritten);
1462                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::edi), isRead, isWritten);
1463                     }
1464                     break;
1465             case am_ImplImm:
1466                   insn_to_complete->appendOperand(Immediate::makeImmediate(Result(makeSizeType(optype), 1)), isRead, isWritten);
1467                   break;
1468                 default:
1469                     printf("decodeOneOperand() called with unknown addressing method %d\n", operand.admet);
1470                     // assert(0);
1471                 return false;
1472         }
1473       
1474                 return true;
1475             }
1476
1477     extern ia32_entry invalid;
1478     void InstructionDecoder_x86::doIA32Decode(InstructionDecoder::buffer& b)
1479     {
1480         if(decodedInstruction == NULL)
1481         {
1482             decodedInstruction = reinterpret_cast<ia32_instruction*>(malloc(sizeof(ia32_instruction)));
1483             assert(decodedInstruction);
1484         }
1485         if(locs == NULL)
1486         {
1487             locs = reinterpret_cast<ia32_locations*>(malloc(sizeof(ia32_locations)));
1488             assert(locs);
1489         }
1490         locs = new(locs) ia32_locations; //reinit();
1491         assert(locs->sib_position == -1);
1492         decodedInstruction = new (decodedInstruction) ia32_instruction(NULL, NULL, locs);
1493         ia32_decode(IA32_DECODE_PREFIXES, b.start, *decodedInstruction);
1494         sizePrefixPresent = (decodedInstruction->getPrefix()->getOperSzPrefix() == 0x66);
1495         if (decodedInstruction->getPrefix()->rexW()) {
1496            // as per 2.2.1.2 - rex.w overrides 66h
1497            sizePrefixPresent = false;
1498         }
1499         addrSizePrefixPresent = (decodedInstruction->getPrefix()->getAddrSzPrefix() == 0x67);
1500         static ia32_entry invalid = { e_No_Entry, 0, 0, false, { {0,0}, {0,0}, {0,0} }, 0, 0 };
1501         if(decodedInstruction->getEntry()) {
1502             // check prefix validity
1503             // lock prefix only allowed on certain insns.
1504             // TODO: refine further to check memory written operand
1505             if(decodedInstruction->getPrefix()->getPrefix(0) == PREFIX_LOCK)
1506             {
1507                 switch(decodedInstruction->getEntry()->id)
1508                 {
1509                 case e_add:
1510                 case e_adc:
1511                 case e_and:
1512                 case e_btc:
1513                 case e_btr:
1514                 case e_bts:
1515                 case e_cmpxch:
1516                 case e_cmpxch8b:
1517                 case e_dec:
1518                 case e_inc:
1519                 case e_neg:
1520                 case e_not:
1521                 case e_or:
1522                 case e_sbb:
1523                 case e_sub:
1524                 case e_xor:
1525                 case e_xadd:
1526                 case e_xchg:
1527                     break;
1528                 default:
1529                     m_Operation = make_shared(singleton_object_pool<Operation>::construct(&invalid,
1530                                     decodedInstruction->getPrefix(), locs, m_Arch));
1531                     return;
1532                 }
1533             }
1534             m_Operation = make_shared(singleton_object_pool<Operation>::construct(decodedInstruction->getEntry(),
1535                                     decodedInstruction->getPrefix(), locs, m_Arch));
1536             
1537       } else {
1538                 // Gap parsing can trigger this case; in particular, when it encounters prefixes in an invalid order.
1539                 // Notably, if a REX prefix (0x40-0x48) appears followed by another prefix (0x66, 0x67, etc)
1540                 // we'll reject the instruction as invalid and send it back with no entry.  Since this is a common
1541                 // byte sequence to see in, for example, ASCII strings, we want to simply accept this and move on, not
1542                 // yell at the user.
1543             m_Operation = make_shared(singleton_object_pool<Operation>::construct(&invalid,
1544                                     decodedInstruction->getPrefix(), locs, m_Arch));
1545         }
1546
1547     }
1548     
1549     void InstructionDecoder_x86::decodeOpcode(InstructionDecoder::buffer& b)
1550     {
1551         doIA32Decode(b);
1552         b.start += decodedInstruction->getSize();
1553     }
1554     
1555       bool InstructionDecoder_x86::decodeOperands(const Instruction* insn_to_complete)
1556     {
1557        int imm_index = 0; // handle multiple immediate operands
1558         if(!decodedInstruction) return false;
1559         unsigned int opsema = decodedInstruction->getEntry()->opsema & 0xFF;
1560         InstructionDecoder::buffer b(insn_to_complete->ptr(), insn_to_complete->size());
1561
1562         if (decodedInstruction->getEntry()->getID() == e_ret_near ||
1563             decodedInstruction->getEntry()->getID() == e_ret_far) {
1564            Expression::Ptr ret_addr = makeDereferenceExpression(makeRegisterExpression(ia32_is_mode_64() ? x86_64::rsp : x86::esp), 
1565                                                                 ia32_is_mode_64() ? u64 : u32);
1566            insn_to_complete->addSuccessor(ret_addr, false, true, false, false);
1567         }
1568
1569         for(int i = 0; i < 3; i++)
1570         {
1571             if(decodedInstruction->getEntry()->operands[i].admet == 0 && 
1572                decodedInstruction->getEntry()->operands[i].optype == 0)
1573                 return true;
1574             if(!decodeOneOperand(b,
1575                                  decodedInstruction->getEntry()->operands[i], 
1576                                  imm_index, 
1577                                  insn_to_complete, 
1578                                  readsOperand(opsema, i),
1579                                  writesOperand(opsema, i)))
1580             {
1581                 return false;
1582             }
1583         }
1584
1585         /* Does this instruction have a 4th operand? */
1586         if((decodedInstruction->getEntry()->opsema & 0xFFFF) >= s4OP)
1587         {
1588           if(!decodeOneOperand(b,
1589             {am_I, op_b}, /* This is always an IMM8 */
1590             imm_index,
1591             insn_to_complete,
1592             readsOperand(opsema, 3),
1593             writesOperand(opsema, 3)))
1594             {
1595                 return false;
1596             }
1597         }
1598     
1599         return true;
1600     }
1601
1602     
1603       INSTRUCTION_EXPORT Instruction::Ptr InstructionDecoder_x86::decode(InstructionDecoder::buffer& b)
1604     {
1605         return InstructionDecoderImpl::decode(b);
1606     }
1607     void InstructionDecoder_x86::doDelayedDecode(const Instruction* insn_to_complete)
1608     {
1609       InstructionDecoder::buffer b(insn_to_complete->ptr(), insn_to_complete->size());
1610       //insn_to_complete->m_Operands.reserve(4);
1611       doIA32Decode(b);        
1612       decodeOperands(insn_to_complete);
1613     }
1614     
1615 };
1616 };
1617