Fix disassembler handling of CRC32 which is an odd instruction that uses 0xf2 as...
[oota-llvm.git] / utils / TableGen / X86DisassemblerTables.cpp
1 //===- X86DisassemblerTables.cpp - Disassembler tables ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is part of the X86 Disassembler Emitter.
11 // It contains the implementation of the disassembler tables.
12 // Documentation for the disassembler emitter in general can be found in
13 //  X86DisasemblerEmitter.h.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "X86DisassemblerShared.h"
18 #include "X86DisassemblerTables.h"
19
20 #include "llvm/TableGen/TableGenBackend.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/Format.h"
24
25 using namespace llvm;
26 using namespace X86Disassembler;
27   
28 /// inheritsFrom - Indicates whether all instructions in one class also belong
29 ///   to another class.
30 ///
31 /// @param child  - The class that may be the subset
32 /// @param parent - The class that may be the superset
33 /// @return       - True if child is a subset of parent, false otherwise.
34 static inline bool inheritsFrom(InstructionContext child,
35                                 InstructionContext parent) {
36   if (child == parent)
37     return true;
38   
39   switch (parent) {
40   case IC:
41     return(inheritsFrom(child, IC_64BIT) ||
42            inheritsFrom(child, IC_OPSIZE) ||
43            inheritsFrom(child, IC_XD) ||
44            inheritsFrom(child, IC_XS));
45   case IC_64BIT:
46     return(inheritsFrom(child, IC_64BIT_REXW)   ||
47            inheritsFrom(child, IC_64BIT_OPSIZE) ||
48            inheritsFrom(child, IC_64BIT_XD)     ||
49            inheritsFrom(child, IC_64BIT_XS));
50   case IC_OPSIZE:
51     return inheritsFrom(child, IC_64BIT_OPSIZE);
52   case IC_XD:
53     return inheritsFrom(child, IC_64BIT_XD);
54            inheritsFrom(child, IC_XD_OPSIZE);
55   case IC_XS:
56     return inheritsFrom(child, IC_64BIT_XS);
57   case IC_XD_OPSIZE:
58     return inheritsFrom(child, IC_64BIT_XD_OPSIZE);
59   case IC_64BIT_REXW:
60     return(inheritsFrom(child, IC_64BIT_REXW_XS) ||
61            inheritsFrom(child, IC_64BIT_REXW_XD) ||
62            inheritsFrom(child, IC_64BIT_REXW_OPSIZE));
63   case IC_64BIT_OPSIZE:
64     return(inheritsFrom(child, IC_64BIT_REXW_OPSIZE));
65   case IC_64BIT_XD:
66     return(inheritsFrom(child, IC_64BIT_REXW_XD));
67   case IC_64BIT_XS:
68     return(inheritsFrom(child, IC_64BIT_REXW_XS));
69   case IC_64BIT_XD_OPSIZE:
70     return false;
71   case IC_64BIT_REXW_XD:
72     return false;
73   case IC_64BIT_REXW_XS:
74     return false;
75   case IC_64BIT_REXW_OPSIZE:
76     return false;
77   case IC_VEX:
78     return inheritsFrom(child, IC_VEX_W);
79   case IC_VEX_XS:
80     return inheritsFrom(child, IC_VEX_W_XS);
81   case IC_VEX_XD:
82     return inheritsFrom(child, IC_VEX_W_XD);
83   case IC_VEX_OPSIZE:
84     return inheritsFrom(child, IC_VEX_W_OPSIZE);
85   case IC_VEX_W:
86     return false;
87   case IC_VEX_W_XS:
88     return false;
89   case IC_VEX_W_XD:
90     return false;
91   case IC_VEX_W_OPSIZE:
92     return false;
93   case IC_VEX_L:
94     return false;
95   case IC_VEX_L_XS:
96     return false;
97   case IC_VEX_L_XD:
98     return false;
99   case IC_VEX_L_OPSIZE:
100     return false;
101   default:
102     llvm_unreachable("Unknown instruction class");
103     return false;
104   }
105 }
106
107 /// outranks - Indicates whether, if an instruction has two different applicable
108 ///   classes, which class should be preferred when performing decode.  This
109 ///   imposes a total ordering (ties are resolved toward "lower")
110 ///
111 /// @param upper  - The class that may be preferable
112 /// @param lower  - The class that may be less preferable
113 /// @return       - True if upper is to be preferred, false otherwise.
114 static inline bool outranks(InstructionContext upper, 
115                             InstructionContext lower) {
116   assert(upper < IC_max);
117   assert(lower < IC_max);
118   
119 #define ENUM_ENTRY(n, r, d) r,
120   static int ranks[IC_max] = {
121     INSTRUCTION_CONTEXTS
122   };
123 #undef ENUM_ENTRY
124   
125   return (ranks[upper] > ranks[lower]);
126 }
127
128 /// stringForContext - Returns a string containing the name of a particular
129 ///   InstructionContext, usually for diagnostic purposes.
130 ///
131 /// @param insnContext  - The instruction class to transform to a string.
132 /// @return           - A statically-allocated string constant that contains the
133 ///                     name of the instruction class.
134 static inline const char* stringForContext(InstructionContext insnContext) {
135   switch (insnContext) {
136   default:
137     llvm_unreachable("Unhandled instruction class");
138 #define ENUM_ENTRY(n, r, d)   case n: return #n; break;
139   INSTRUCTION_CONTEXTS
140 #undef ENUM_ENTRY
141   }
142
143   return 0;
144 }
145
146 /// stringForOperandType - Like stringForContext, but for OperandTypes.
147 static inline const char* stringForOperandType(OperandType type) {
148   switch (type) {
149   default:
150     llvm_unreachable("Unhandled type");
151 #define ENUM_ENTRY(i, d) case i: return #i;
152   TYPES
153 #undef ENUM_ENTRY
154   }
155 }
156
157 /// stringForOperandEncoding - like stringForContext, but for
158 ///   OperandEncodings.
159 static inline const char* stringForOperandEncoding(OperandEncoding encoding) {
160   switch (encoding) {
161   default:
162     llvm_unreachable("Unhandled encoding");
163 #define ENUM_ENTRY(i, d) case i: return #i;
164   ENCODINGS
165 #undef ENUM_ENTRY
166   }
167 }
168
169 void DisassemblerTables::emitOneID(raw_ostream &o,
170                                    uint32_t &i,
171                                    InstrUID id,
172                                    bool addComma) const {
173   if (id)
174     o.indent(i * 2) << format("0x%hx", id);
175   else
176     o.indent(i * 2) << 0;
177   
178   if (addComma)
179     o << ", ";
180   else
181     o << "  ";
182   
183   o << "/* ";
184   o << InstructionSpecifiers[id].name;
185   o << "*/";
186   
187   o << "\n";
188 }
189
190 /// emitEmptyTable - Emits the modRMEmptyTable, which is used as a ID table by
191 ///   all ModR/M decisions for instructions that are invalid for all possible
192 ///   ModR/M byte values.
193 ///
194 /// @param o        - The output stream on which to emit the table.
195 /// @param i        - The indentation level for that output stream.
196 static void emitEmptyTable(raw_ostream &o, uint32_t &i)
197 {
198   o.indent(i * 2) << "static const InstrUID modRMEmptyTable[1] = { 0 };\n";
199   o << "\n";
200 }
201
202 /// getDecisionType - Determines whether a ModRM decision with 255 entries can
203 ///   be compacted by eliminating redundant information.
204 ///
205 /// @param decision - The decision to be compacted.
206 /// @return         - The compactest available representation for the decision.
207 static ModRMDecisionType getDecisionType(ModRMDecision &decision)
208 {
209   bool satisfiesOneEntry = true;
210   bool satisfiesSplitRM = true;
211   
212   uint16_t index;
213   
214   for (index = 0; index < 256; ++index) {
215     if (decision.instructionIDs[index] != decision.instructionIDs[0])
216       satisfiesOneEntry = false;
217     
218     if (((index & 0xc0) == 0xc0) &&
219        (decision.instructionIDs[index] != decision.instructionIDs[0xc0]))
220       satisfiesSplitRM = false;
221     
222     if (((index & 0xc0) != 0xc0) &&
223        (decision.instructionIDs[index] != decision.instructionIDs[0x00]))
224       satisfiesSplitRM = false;
225   }
226   
227   if (satisfiesOneEntry)
228     return MODRM_ONEENTRY;
229   
230   if (satisfiesSplitRM)
231     return MODRM_SPLITRM;
232   
233   return MODRM_FULL;
234 }
235
236 /// stringForDecisionType - Returns a statically-allocated string corresponding
237 ///   to a particular decision type.
238 ///
239 /// @param dt - The decision type.
240 /// @return   - A pointer to the statically-allocated string (e.g., 
241 ///             "MODRM_ONEENTRY" for MODRM_ONEENTRY).
242 static const char* stringForDecisionType(ModRMDecisionType dt)
243 {
244 #define ENUM_ENTRY(n) case n: return #n;
245   switch (dt) {
246     default:
247       llvm_unreachable("Unknown decision type");  
248     MODRMTYPES
249   };  
250 #undef ENUM_ENTRY
251 }
252   
253 /// stringForModifierType - Returns a statically-allocated string corresponding
254 ///   to an opcode modifier type.
255 ///
256 /// @param mt - The modifier type.
257 /// @return   - A pointer to the statically-allocated string (e.g.,
258 ///             "MODIFIER_NONE" for MODIFIER_NONE).
259 static const char* stringForModifierType(ModifierType mt)
260 {
261 #define ENUM_ENTRY(n) case n: return #n;
262   switch(mt) {
263     default:
264       llvm_unreachable("Unknown modifier type");
265     MODIFIER_TYPES
266   };
267 #undef ENUM_ENTRY
268 }
269   
270 DisassemblerTables::DisassemblerTables() {
271   unsigned i;
272   
273   for (i = 0; i < array_lengthof(Tables); i++) {
274     Tables[i] = new ContextDecision;
275     memset(Tables[i], 0, sizeof(ContextDecision));
276   }
277   
278   HasConflicts = false;
279 }
280   
281 DisassemblerTables::~DisassemblerTables() {
282   unsigned i;
283   
284   for (i = 0; i < array_lengthof(Tables); i++)
285     delete Tables[i];
286 }
287   
288 void DisassemblerTables::emitModRMDecision(raw_ostream &o1,
289                                            raw_ostream &o2,
290                                            uint32_t &i1,
291                                            uint32_t &i2,
292                                            ModRMDecision &decision)
293   const {
294   static uint64_t sTableNumber = 0;
295   uint64_t thisTableNumber = sTableNumber;
296   ModRMDecisionType dt = getDecisionType(decision);
297   uint16_t index;
298   
299   if (dt == MODRM_ONEENTRY && decision.instructionIDs[0] == 0)
300   {
301     o2.indent(i2) << "{ /* ModRMDecision */" << "\n";
302     i2++;
303     
304     o2.indent(i2) << stringForDecisionType(dt) << "," << "\n";
305     o2.indent(i2) << "modRMEmptyTable";
306     
307     i2--;
308     o2.indent(i2) << "}";
309     return;
310   }
311     
312   o1.indent(i1) << "static const InstrUID modRMTable" << thisTableNumber;
313     
314   switch (dt) {
315     default:
316       llvm_unreachable("Unknown decision type");
317     case MODRM_ONEENTRY:
318       o1 << "[1]";
319       break;
320     case MODRM_SPLITRM:
321       o1 << "[2]";
322       break;
323     case MODRM_FULL:
324       o1 << "[256]";
325       break;      
326   }
327
328   o1 << " = {" << "\n";
329   i1++;
330     
331   switch (dt) {
332     default:
333       llvm_unreachable("Unknown decision type");
334     case MODRM_ONEENTRY:
335       emitOneID(o1, i1, decision.instructionIDs[0], false);
336       break;
337     case MODRM_SPLITRM:
338       emitOneID(o1, i1, decision.instructionIDs[0x00], true); // mod = 0b00
339       emitOneID(o1, i1, decision.instructionIDs[0xc0], false); // mod = 0b11
340       break;
341     case MODRM_FULL:
342       for (index = 0; index < 256; ++index)
343         emitOneID(o1, i1, decision.instructionIDs[index], index < 255);
344       break;
345   }
346     
347   i1--;
348   o1.indent(i1) << "};" << "\n";
349   o1 << "\n";
350     
351   o2.indent(i2) << "{ /* struct ModRMDecision */" << "\n";
352   i2++;
353     
354   o2.indent(i2) << stringForDecisionType(dt) << "," << "\n";
355   o2.indent(i2) << "modRMTable" << sTableNumber << "\n";
356     
357   i2--;
358   o2.indent(i2) << "}";
359     
360   ++sTableNumber;
361 }
362
363 void DisassemblerTables::emitOpcodeDecision(
364   raw_ostream &o1,
365   raw_ostream &o2,
366   uint32_t &i1,
367   uint32_t &i2,
368   OpcodeDecision &decision) const {
369   uint16_t index;
370
371   o2.indent(i2) << "{ /* struct OpcodeDecision */" << "\n";
372   i2++;
373   o2.indent(i2) << "{" << "\n";
374   i2++;
375
376   for (index = 0; index < 256; ++index) {
377     o2.indent(i2);
378
379     o2 << "/* 0x" << format("%02hhx", index) << " */" << "\n";
380
381     emitModRMDecision(o1, o2, i1, i2, decision.modRMDecisions[index]);
382
383     if (index <  255)
384       o2 << ",";
385
386     o2 << "\n";
387   }
388
389   i2--;
390   o2.indent(i2) << "}" << "\n";
391   i2--;
392   o2.indent(i2) << "}" << "\n";
393 }
394
395 void DisassemblerTables::emitContextDecision(
396   raw_ostream &o1,
397   raw_ostream &o2,
398   uint32_t &i1,
399   uint32_t &i2,
400   ContextDecision &decision,
401   const char* name) const {
402   o2.indent(i2) << "static const struct ContextDecision " << name << " = {\n";
403   i2++;
404   o2.indent(i2) << "{ /* opcodeDecisions */" << "\n";
405   i2++;
406
407   unsigned index;
408
409   for (index = 0; index < IC_max; ++index) {
410     o2.indent(i2) << "/* ";
411     o2 << stringForContext((InstructionContext)index);
412     o2 << " */";
413     o2 << "\n";
414
415     emitOpcodeDecision(o1, o2, i1, i2, decision.opcodeDecisions[index]);
416
417     if (index + 1 < IC_max)
418       o2 << ", ";
419   }
420
421   i2--;
422   o2.indent(i2) << "}" << "\n";
423   i2--;
424   o2.indent(i2) << "};" << "\n";
425 }
426
427 void DisassemblerTables::emitInstructionInfo(raw_ostream &o, uint32_t &i) 
428   const {
429   o.indent(i * 2) << "static const struct InstructionSpecifier ";
430   o << INSTRUCTIONS_STR "[" << InstructionSpecifiers.size() << "] = {\n";
431   
432   i++;
433
434   uint16_t numInstructions = InstructionSpecifiers.size();
435   uint16_t index, operandIndex;
436
437   for (index = 0; index < numInstructions; ++index) {
438     o.indent(i * 2) << "{ /* " << index << " */" << "\n";
439     i++;
440     
441     o.indent(i * 2) << 
442       stringForModifierType(InstructionSpecifiers[index].modifierType);
443     o << "," << "\n";
444     
445     o.indent(i * 2) << "0x";
446     o << format("%02hhx", (uint16_t)InstructionSpecifiers[index].modifierBase);
447     o << "," << "\n";
448
449     o.indent(i * 2) << "{" << "\n";
450     i++;
451
452     for (operandIndex = 0; operandIndex < X86_MAX_OPERANDS; ++operandIndex) {
453       o.indent(i * 2) << "{ ";
454       o << stringForOperandEncoding(InstructionSpecifiers[index]
455                                     .operands[operandIndex]
456                                     .encoding);
457       o << ", ";
458       o << stringForOperandType(InstructionSpecifiers[index]
459                                 .operands[operandIndex]
460                                 .type);
461       o << " }";
462
463       if (operandIndex < X86_MAX_OPERANDS - 1)
464         o << ",";
465
466       o << "\n";
467     }
468
469     i--;
470     o.indent(i * 2) << "}," << "\n";
471     
472     o.indent(i * 2) << "\"" << InstructionSpecifiers[index].name << "\"";
473     o << "\n";
474
475     i--;
476     o.indent(i * 2) << "}";
477
478     if (index + 1 < numInstructions)
479       o << ",";
480
481     o << "\n";
482   }
483
484   i--;
485   o.indent(i * 2) << "};" << "\n";
486 }
487
488 void DisassemblerTables::emitContextTable(raw_ostream &o, uint32_t &i) const {
489   uint16_t index;
490
491   o.indent(i * 2) << "static const InstructionContext " CONTEXTS_STR
492                      "[256] = {\n";
493   i++;
494
495   for (index = 0; index < 256; ++index) {
496     o.indent(i * 2);
497
498     if ((index & ATTR_VEXL) && (index & ATTR_OPSIZE))
499       o << "IC_VEX_L_OPSIZE";
500     else if ((index & ATTR_VEXL) && (index & ATTR_XD))
501       o << "IC_VEX_L_XD";
502     else if ((index & ATTR_VEXL) && (index & ATTR_XS))
503       o << "IC_VEX_L_XS";
504     else if ((index & ATTR_VEX) && (index & ATTR_REXW) && (index & ATTR_OPSIZE))
505       o << "IC_VEX_W_OPSIZE";
506     else if ((index & ATTR_VEX) && (index & ATTR_REXW) && (index & ATTR_XD))
507       o << "IC_VEX_W_XD";
508     else if ((index & ATTR_VEX) && (index & ATTR_REXW) && (index & ATTR_XS))
509       o << "IC_VEX_W_XS";
510     else if (index & ATTR_VEXL)
511       o << "IC_VEX_L";
512     else if ((index & ATTR_VEX) && (index & ATTR_REXW))
513       o << "IC_VEX_W";
514     else if ((index & ATTR_VEX) && (index & ATTR_OPSIZE))
515       o << "IC_VEX_OPSIZE";
516     else if ((index & ATTR_VEX) && (index & ATTR_XD))
517       o << "IC_VEX_XD";
518     else if ((index & ATTR_VEX) && (index & ATTR_XS))
519       o << "IC_VEX_XS";
520     else if (index & ATTR_VEX)
521       o << "IC_VEX";
522     else if ((index & ATTR_64BIT) && (index & ATTR_REXW) && (index & ATTR_XS))
523       o << "IC_64BIT_REXW_XS";
524     else if ((index & ATTR_64BIT) && (index & ATTR_REXW) && (index & ATTR_XD))
525       o << "IC_64BIT_REXW_XD";
526     else if ((index & ATTR_64BIT) && (index & ATTR_REXW) && 
527              (index & ATTR_OPSIZE))
528       o << "IC_64BIT_REXW_OPSIZE";
529     else if ((index & ATTR_64BIT) && (index & ATTR_XD) && (index & ATTR_OPSIZE))
530       o << "IC_64BIT_XD_OPSIZE";
531     else if ((index & ATTR_64BIT) && (index & ATTR_XS))
532       o << "IC_64BIT_XS";
533     else if ((index & ATTR_64BIT) && (index & ATTR_XD))
534       o << "IC_64BIT_XD";
535     else if ((index & ATTR_64BIT) && (index & ATTR_OPSIZE))
536       o << "IC_64BIT_OPSIZE";
537     else if ((index & ATTR_64BIT) && (index & ATTR_REXW))
538       o << "IC_64BIT_REXW";
539     else if ((index & ATTR_64BIT))
540       o << "IC_64BIT";
541     else if ((index & ATTR_XD) && (index & ATTR_OPSIZE))
542       o << "IC_XD_OPSIZE";
543     else if (index & ATTR_XS)
544       o << "IC_XS";
545     else if (index & ATTR_XD)
546       o << "IC_XD";
547     else if (index & ATTR_OPSIZE)
548       o << "IC_OPSIZE";
549     else
550       o << "IC";
551
552     if (index < 255)
553       o << ",";
554     else
555       o << " ";
556
557     o << " /* " << index << " */";
558
559     o << "\n";
560   }
561
562   i--;
563   o.indent(i * 2) << "};" << "\n";
564 }
565
566 void DisassemblerTables::emitContextDecisions(raw_ostream &o1,
567                                             raw_ostream &o2,
568                                             uint32_t &i1,
569                                             uint32_t &i2)
570   const {
571   emitContextDecision(o1, o2, i1, i2, *Tables[0], ONEBYTE_STR);
572   emitContextDecision(o1, o2, i1, i2, *Tables[1], TWOBYTE_STR);
573   emitContextDecision(o1, o2, i1, i2, *Tables[2], THREEBYTE38_STR);
574   emitContextDecision(o1, o2, i1, i2, *Tables[3], THREEBYTE3A_STR);
575   emitContextDecision(o1, o2, i1, i2, *Tables[4], THREEBYTEA6_STR);
576   emitContextDecision(o1, o2, i1, i2, *Tables[5], THREEBYTEA7_STR);
577 }
578
579 void DisassemblerTables::emit(raw_ostream &o) const {
580   uint32_t i1 = 0;
581   uint32_t i2 = 0;
582   
583   std::string s1;
584   std::string s2;
585   
586   raw_string_ostream o1(s1);
587   raw_string_ostream o2(s2);
588   
589   emitInstructionInfo(o, i2);
590   o << "\n";
591
592   emitContextTable(o, i2);
593   o << "\n";
594   
595   emitEmptyTable(o1, i1);
596   emitContextDecisions(o1, o2, i1, i2);
597   
598   o << o1.str();
599   o << "\n";
600   o << o2.str();
601   o << "\n";
602   o << "\n";
603 }
604
605 void DisassemblerTables::setTableFields(ModRMDecision     &decision,
606                                         const ModRMFilter &filter,
607                                         InstrUID          uid,
608                                         uint8_t           opcode) {
609   unsigned index;
610
611   for (index = 0; index < 256; ++index) {
612     if (filter.accepts(index)) {
613       if (decision.instructionIDs[index] == uid)
614         continue;
615
616       if (decision.instructionIDs[index] != 0) {
617         InstructionSpecifier &newInfo =
618           InstructionSpecifiers[uid];
619         InstructionSpecifier &previousInfo =
620           InstructionSpecifiers[decision.instructionIDs[index]];
621         
622         if(newInfo.filtered)
623           continue; // filtered instructions get lowest priority
624         
625         if(previousInfo.name == "NOOP" && (newInfo.name == "XCHG16ar" ||
626                                            newInfo.name == "XCHG32ar" ||
627                                            newInfo.name == "XCHG64ar"))
628           continue; // special case for XCHG*ar and NOOP
629
630         if (outranks(previousInfo.insnContext, newInfo.insnContext))
631           continue;
632         
633         if (previousInfo.insnContext == newInfo.insnContext &&
634             !previousInfo.filtered) {
635           errs() << "Error: Primary decode conflict: ";
636           errs() << newInfo.name << " would overwrite " << previousInfo.name;
637           errs() << "\n";
638           errs() << "ModRM   " << index << "\n";
639           errs() << "Opcode  " << (uint16_t)opcode << "\n";
640           errs() << "Context " << stringForContext(newInfo.insnContext) << "\n";
641           HasConflicts = true;
642         }
643       }
644
645       decision.instructionIDs[index] = uid;
646     }
647   }
648 }
649
650 void DisassemblerTables::setTableFields(OpcodeType          type,
651                                         InstructionContext  insnContext,
652                                         uint8_t             opcode,
653                                         const ModRMFilter   &filter,
654                                         InstrUID            uid,
655                                         bool                is32bit) {
656   unsigned index;
657   
658   ContextDecision &decision = *Tables[type];
659
660   for (index = 0; index < IC_max; ++index) {
661     if (is32bit && inheritsFrom((InstructionContext)index, IC_64BIT))
662       continue;
663
664     if (inheritsFrom((InstructionContext)index, 
665                      InstructionSpecifiers[uid].insnContext))
666       setTableFields(decision.opcodeDecisions[index].modRMDecisions[opcode], 
667                      filter,
668                      uid,
669                      opcode);
670   }
671 }