c3d24d2d70ec1fd8a1b055cb781a92775da4676d
[oota-llvm.git] / lib / Target / ARM / Disassembler / ARMDisassembler.cpp
1 //===- ARMDisassembler.cpp - Disassembler for ARM/Thumb ISA -----*- 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 ARM Disassembler.
11 // It contains code to implement the public interfaces of ARMDisassembler and
12 // ThumbDisassembler, both of which are instances of MCDisassembler.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "arm-disassembler"
17
18 #include "ARMDisassembler.h"
19 #include "ARMDisassemblerCore.h"
20
21 #include "llvm/MC/EDInstInfo.h"
22 #include "llvm/MC/MCInst.h"
23 #include "llvm/Target/TargetRegistry.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/MemoryObject.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28
29 //#define DEBUG(X) do { X; } while (0)
30
31 /// ARMGenDecoderTables.inc - ARMDecoderTables.inc is tblgen'ed from
32 /// ARMDecoderEmitter.cpp TableGen backend.  It contains:
33 ///
34 /// o Mappings from opcode to ARM/Thumb instruction format
35 ///
36 /// o static uint16_t decodeInstruction(uint32_t insn) - the decoding function
37 /// for an ARM instruction.
38 ///
39 /// o static uint16_t decodeThumbInstruction(field_t insn) - the decoding
40 /// function for a Thumb instruction.
41 ///
42 #include "ARMGenDecoderTables.inc"
43
44 #include "ARMGenEDInfo.inc"
45
46 using namespace llvm;
47
48 /// showBitVector - Use the raw_ostream to log a diagnostic message describing
49 /// the inidividual bits of the instruction.
50 ///
51 static inline void showBitVector(raw_ostream &os, const uint32_t &insn) {
52   // Split the bit position markers into more than one lines to fit 80 columns.
53   os << " 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11"
54      << " 10  9  8  7  6  5  4  3  2  1  0 \n";
55   os << "---------------------------------------------------------------"
56      << "----------------------------------\n";
57   os << '|';
58   for (unsigned i = 32; i != 0; --i) {
59     if (insn >> (i - 1) & 0x01)
60       os << " 1";
61     else
62       os << " 0";
63     os << (i%4 == 1 ? '|' : ':');
64   }
65   os << '\n';
66   // Split the bit position markers into more than one lines to fit 80 columns.
67   os << "---------------------------------------------------------------"
68      << "----------------------------------\n";
69   os << '\n';
70 }
71
72 /// decodeARMInstruction is a decorator function which tries special cases of
73 /// instruction matching before calling the auto-generated decoder function.
74 static unsigned decodeARMInstruction(uint32_t &insn) {
75   if (slice(insn, 31, 28) == 15)
76     goto AutoGenedDecoder;
77
78   // Special case processing, if any, goes here....
79
80   // LLVM combines the offset mode of A8.6.197 & A8.6.198 into STRB.
81   // The insufficient encoding information of the combined instruction confuses
82   // the decoder wrt BFC/BFI.  Therefore, we try to recover here.
83   // For BFC, Inst{27-21} = 0b0111110 & Inst{6-0} = 0b0011111.
84   // For BFI, Inst{27-21} = 0b0111110 & Inst{6-4} = 0b001 & Inst{3-0} =! 0b1111.
85   if (slice(insn, 27, 21) == 0x3e && slice(insn, 6, 4) == 1) {
86     if (slice(insn, 3, 0) == 15)
87       return ARM::BFC;
88     else
89       return ARM::BFI;
90   }
91
92   // Ditto for STRBT, which is a super-instruction for A8.6.199 Encodings
93   // A1 & A2.
94   // As a result, the decoder fails to deocode USAT properly.
95   if (slice(insn, 27, 21) == 0x37 && slice(insn, 5, 4) == 1)
96     return ARM::USAT;
97
98   // Ditto for ADDSrs, which is a super-instruction for A8.6.7 & A8.6.8.
99   // As a result, the decoder fails to decode UMULL properly.
100   if (slice(insn, 27, 21) == 0x04 && slice(insn, 7, 4) == 9) {
101     return ARM::UMULL;
102   }
103
104   // Ditto for STR_PRE, which is a super-instruction for A8.6.194 & A8.6.195.
105   // As a result, the decoder fails to decode SBFX properly.
106   if (slice(insn, 27, 21) == 0x3d && slice(insn, 6, 4) == 5)
107     return ARM::SBFX;
108
109   // And STRB_PRE, which is a super-instruction for A8.6.197 & A8.6.198.
110   // As a result, the decoder fails to decode UBFX properly.
111   if (slice(insn, 27, 21) == 0x3f && slice(insn, 6, 4) == 5)
112     return ARM::UBFX;
113
114   // Ditto for STRT, which is a super-instruction for A8.6.210 Encoding A1 & A2.
115   // As a result, the decoder fails to deocode SSAT properly.
116   if (slice(insn, 27, 21) == 0x35 && slice(insn, 5, 4) == 1)
117     return ARM::SSAT;
118
119   // Ditto for RSCrs, which is a super-instruction for A8.6.146 & A8.6.147.
120   // As a result, the decoder fails to decode STRHT/LDRHT/LDRSHT/LDRSBT.
121   if (slice(insn, 27, 24) == 0) {
122     switch (slice(insn, 21, 20)) {
123     case 2:
124       switch (slice(insn, 7, 4)) {
125       case 11:
126         return ARM::STRHT;
127       default:
128         break; // fallthrough
129       }
130       break;
131     case 3:
132       switch (slice(insn, 7, 4)) {
133       case 11:
134         return ARM::LDRHT;
135       case 13:
136         return ARM::LDRSBT;
137       case 15:
138         return ARM::LDRSHT;
139       default:
140         break; // fallthrough
141       }
142       break;
143     default:
144       break;   // fallthrough
145     }
146   }
147
148   // Ditto for SBCrs, which is a super-instruction for A8.6.152 & A8.6.153.
149   // As a result, the decoder fails to decode STRH_Post/LDRD_POST/STRD_POST
150   // properly.
151   if (slice(insn, 27, 25) == 0 && slice(insn, 20, 20) == 0) {
152     unsigned PW = slice(insn, 24, 24) << 1 | slice(insn, 21, 21);
153     switch (slice(insn, 7, 4)) {
154     case 11:
155       switch (PW) {
156       case 2: // Offset
157         return ARM::STRH;
158       case 3: // Pre-indexed
159         return ARM::STRH_PRE;
160       case 0: // Post-indexed
161         return ARM::STRH_POST;
162       default:
163         break; // fallthrough
164       }
165       break;
166     case 13:
167       switch (PW) {
168       case 2: // Offset
169         return ARM::LDRD;
170       case 3: // Pre-indexed
171         return ARM::LDRD_PRE;
172       case 0: // Post-indexed
173         return ARM::LDRD_POST;
174       default:
175         break; // fallthrough
176       }
177       break;
178     case 15:
179       switch (PW) {
180       case 2: // Offset
181         return ARM::STRD;
182       case 3: // Pre-indexed
183         return ARM::STRD_PRE;
184       case 0: // Post-indexed
185         return ARM::STRD_POST;
186       default:
187         break; // fallthrough
188       }
189       break;
190     default:
191       break; // fallthrough
192     }
193   }
194
195   // Ditto for SBCSSrs, which is a super-instruction for A8.6.152 & A8.6.153.
196   // As a result, the decoder fails to decode LDRH_POST/LDRSB_POST/LDRSH_POST
197   // properly.
198   if (slice(insn, 27, 25) == 0 && slice(insn, 20, 20) == 1) {
199     unsigned PW = slice(insn, 24, 24) << 1 | slice(insn, 21, 21);
200     switch (slice(insn, 7, 4)) {
201     case 11:
202       switch (PW) {
203       case 2: // Offset
204         return ARM::LDRH;
205       case 3: // Pre-indexed
206         return ARM::LDRH_PRE;
207       case 0: // Post-indexed
208         return ARM::LDRH_POST;
209       default:
210         break; // fallthrough
211       }
212       break;
213     case 13:
214       switch (PW) {
215       case 2: // Offset
216         return ARM::LDRSB;
217       case 3: // Pre-indexed
218         return ARM::LDRSB_PRE;
219       case 0: // Post-indexed
220         return ARM::LDRSB_POST;
221       default:
222         break; // fallthrough
223       }
224       break;
225     case 15:
226       switch (PW) {
227       case 2: // Offset
228         return ARM::LDRSH;
229       case 3: // Pre-indexed
230         return ARM::LDRSH_PRE;
231       case 0: // Post-indexed
232         return ARM::LDRSH_POST;
233       default:
234         break; // fallthrough
235       }
236       break;
237     default:
238       break; // fallthrough
239     }
240   }
241
242 AutoGenedDecoder:
243   // Calling the auto-generated decoder function.
244   return decodeInstruction(insn);
245 }
246
247 // Helper function for special case handling of LDR (literal) and friends.
248 // See, for example, A6.3.7 Load word: Table A6-18 Load word.
249 // See A8.6.57 T3, T4 & A8.6.60 T2 and friends for why we morphed the opcode
250 // before returning it.
251 static unsigned T2Morph2LoadLiteral(unsigned Opcode) {
252   switch (Opcode) {
253   default:
254     return Opcode; // Return unmorphed opcode.
255
256   case ARM::t2LDR_POST:   case ARM::t2LDR_PRE:
257   case ARM::t2LDRi12:     case ARM::t2LDRi8:
258   case ARM::t2LDRs:       case ARM::t2LDRT:
259     return ARM::t2LDRpci;
260
261   case ARM::t2LDRB_POST:  case ARM::t2LDRB_PRE:
262   case ARM::t2LDRBi12:    case ARM::t2LDRBi8:
263   case ARM::t2LDRBs:      case ARM::t2LDRBT:
264     return ARM::t2LDRBpci;
265
266   case ARM::t2LDRH_POST:  case ARM::t2LDRH_PRE:
267   case ARM::t2LDRHi12:    case ARM::t2LDRHi8:
268   case ARM::t2LDRHs:      case ARM::t2LDRHT:
269     return ARM::t2LDRHpci;
270
271   case ARM::t2LDRSB_POST:  case ARM::t2LDRSB_PRE:
272   case ARM::t2LDRSBi12:    case ARM::t2LDRSBi8:
273   case ARM::t2LDRSBs:      case ARM::t2LDRSBT:
274     return ARM::t2LDRSBpci;
275
276   case ARM::t2LDRSH_POST:  case ARM::t2LDRSH_PRE:
277   case ARM::t2LDRSHi12:    case ARM::t2LDRSHi8:
278   case ARM::t2LDRSHs:      case ARM::t2LDRSHT:
279     return ARM::t2LDRSHpci;
280   }
281 }
282
283 /// decodeThumbSideEffect is a decorator function which can potentially twiddle
284 /// the instruction or morph the returned opcode under Thumb2.
285 ///
286 /// First it checks whether the insn is a NEON or VFP instr; if true, bit
287 /// twiddling could be performed on insn to turn it into an ARM NEON/VFP
288 /// equivalent instruction and decodeInstruction is called with the transformed
289 /// insn.
290 ///
291 /// Next, there is special handling for Load byte/halfword/word instruction by
292 /// checking whether Rn=0b1111 and call T2Morph2LoadLiteral() on the decoded
293 /// Thumb2 instruction.  See comments below for further details.
294 ///
295 /// Finally, one last check is made to see whether the insn is a NEON/VFP and
296 /// decodeInstruction(insn) is invoked on the original insn.
297 ///
298 /// Otherwise, decodeThumbInstruction is called with the original insn.
299 static unsigned decodeThumbSideEffect(bool IsThumb2, unsigned &insn) {
300   if (IsThumb2) {
301     uint16_t op1 = slice(insn, 28, 27);
302     uint16_t op2 = slice(insn, 26, 20);
303
304     // A6.3 32-bit Thumb instruction encoding
305     // Table A6-9 32-bit Thumb instruction encoding
306
307     // The coprocessor instructions of interest are transformed to their ARM
308     // equivalents.
309
310     // --------- Transform Begin Marker ---------
311     if ((op1 == 1 || op1 == 3) && slice(op2, 6, 4) == 7) {
312       // A7.4 Advanced SIMD data-processing instructions
313       // U bit of Thumb corresponds to Inst{24} of ARM.
314       uint16_t U = slice(op1, 1, 1);
315
316       // Inst{28-24} of ARM = {1,0,0,1,U};
317       uint16_t bits28_24 = 9 << 1 | U;
318       DEBUG(showBitVector(errs(), insn));
319       setSlice(insn, 28, 24, bits28_24);
320       return decodeInstruction(insn);
321     }
322
323     if (op1 == 3 && slice(op2, 6, 4) == 1 && slice(op2, 0, 0) == 0) {
324       // A7.7 Advanced SIMD element or structure load/store instructions
325       // Inst{27-24} of Thumb = 0b1001
326       // Inst{27-24} of ARM   = 0b0100
327       DEBUG(showBitVector(errs(), insn));
328       setSlice(insn, 27, 24, 4);
329       return decodeInstruction(insn);
330     }
331     // --------- Transform End Marker ---------
332
333     // See, for example, A6.3.7 Load word: Table A6-18 Load word.
334     // See A8.6.57 T3, T4 & A8.6.60 T2 and friends for why we morphed the opcode
335     // before returning it to our caller.
336     if (op1 == 3 && slice(op2, 6, 5) == 0 && slice(op2, 0, 0) == 1
337         && slice(insn, 19, 16) == 15)
338       return T2Morph2LoadLiteral(decodeThumbInstruction(insn));
339
340     // One last check for NEON/VFP instructions.
341     if ((op1 == 1 || op1 == 3) && slice(op2, 6, 6) == 1)
342       return decodeInstruction(insn);
343
344     // Fall through.
345   }
346
347   return decodeThumbInstruction(insn);
348 }
349
350 //
351 // Public interface for the disassembler
352 //
353
354 bool ARMDisassembler::getInstruction(MCInst &MI,
355                                      uint64_t &Size,
356                                      const MemoryObject &Region,
357                                      uint64_t Address,
358                                      raw_ostream &os) const {
359   // The machine instruction.
360   uint32_t insn;
361   uint8_t bytes[4];
362
363   // We want to read exactly 4 bytes of data.
364   if (Region.readBytes(Address, 4, (uint8_t*)bytes, NULL) == -1)
365     return false;
366
367   // Encoded as a small-endian 32-bit word in the stream.
368   insn = (bytes[3] << 24) |
369          (bytes[2] << 16) |
370          (bytes[1] <<  8) |
371          (bytes[0] <<  0);
372
373   unsigned Opcode = decodeARMInstruction(insn);
374   ARMFormat Format = ARMFormats[Opcode];
375   Size = 4;
376
377   DEBUG({
378       errs() << "Opcode=" << Opcode << " Name=" << ARMUtils::OpcodeName(Opcode)
379              << " Format=" << stringForARMFormat(Format) << '(' << (int)Format
380              << ")\n";
381       showBitVector(errs(), insn);
382     });
383
384   ARMBasicMCBuilder *Builder = CreateMCBuilder(Opcode, Format);
385   if (!Builder)
386     return false;
387
388   if (!Builder->Build(MI, insn))
389     return false;
390
391   delete Builder;
392
393   return true;
394 }
395
396 bool ThumbDisassembler::getInstruction(MCInst &MI,
397                                        uint64_t &Size,
398                                        const MemoryObject &Region,
399                                        uint64_t Address,
400                                        raw_ostream &os) const {
401   // The Thumb instruction stream is a sequence of halhwords.
402
403   // This represents the first halfword as well as the machine instruction
404   // passed to decodeThumbInstruction().  For 16-bit Thumb instruction, the top
405   // halfword of insn is 0x00 0x00; otherwise, the first halfword is moved to
406   // the top half followed by the second halfword.
407   unsigned insn = 0;
408   // Possible second halfword.
409   uint16_t insn1 = 0;
410
411   // A6.1 Thumb instruction set encoding
412   //
413   // If bits [15:11] of the halfword being decoded take any of the following
414   // values, the halfword is the first halfword of a 32-bit instruction:
415   // o 0b11101
416   // o 0b11110
417   // o 0b11111.
418   //
419   // Otherwise, the halfword is a 16-bit instruction.
420
421   // Read 2 bytes of data first.
422   uint8_t bytes[2];
423   if (Region.readBytes(Address, 2, (uint8_t*)bytes, NULL) == -1)
424     return false;
425
426   // Encoded as a small-endian 16-bit halfword in the stream.
427   insn = (bytes[1] << 8) | bytes[0];
428   unsigned bits15_11 = slice(insn, 15, 11);
429   bool IsThumb2 = false;
430
431   // 32-bit instructions if the bits [15:11] of the halfword matches
432   // { 0b11101 /* 0x1D */, 0b11110 /* 0x1E */, ob11111 /* 0x1F */ }.
433   if (bits15_11 == 0x1D || bits15_11 == 0x1E || bits15_11 == 0x1F) {
434     IsThumb2 = true;
435     if (Region.readBytes(Address + 2, 2, (uint8_t*)bytes, NULL) == -1)
436       return false;
437     // Encoded as a small-endian 16-bit halfword in the stream.
438     insn1 = (bytes[1] << 8) | bytes[0];
439     insn = (insn << 16 | insn1);
440   }
441
442   // The insn could potentially be bit-twiddled in order to be decoded as an ARM
443   // NEON/VFP opcode.  In such case, the modified insn is later disassembled as
444   // an ARM NEON/VFP instruction.
445   //
446   // This is a short term solution for lack of encoding bits specified for the
447   // Thumb2 NEON/VFP instructions.  The long term solution could be adding some
448   // infrastructure to have each instruction support more than one encodings.
449   // Which encoding is used would be based on which subtarget the compiler/
450   // disassembler is working with at the time.  This would allow the sharing of
451   // the NEON patterns between ARM and Thumb2, as well as potential greater
452   // sharing between the regular ARM instructions and the 32-bit wide Thumb2
453   // instructions as well.
454   unsigned Opcode = decodeThumbSideEffect(IsThumb2, insn);
455
456   ARMFormat Format = ARMFormats[Opcode];
457   Size = IsThumb2 ? 4 : 2;
458
459   DEBUG({
460       errs() << "Opcode=" << Opcode << " Name=" << ARMUtils::OpcodeName(Opcode)
461              << " Format=" << stringForARMFormat(Format) << '(' << (int)Format
462              << ")\n";
463       showBitVector(errs(), insn);
464     });
465
466   ARMBasicMCBuilder *Builder = CreateMCBuilder(Opcode, Format);
467   if (!Builder)
468     return false;
469
470   Builder->SetSession(const_cast<Session *>(&SO));
471
472   if (!Builder->Build(MI, insn))
473     return false;
474
475   delete Builder;
476
477   return true;
478 }
479
480 // A8.6.50
481 // Valid return values are {1, 2, 3, 4}, with 0 signifying an error condition.
482 static unsigned short CountITSize(unsigned ITMask) {
483   // First count the trailing zeros of the IT mask.
484   unsigned TZ = CountTrailingZeros_32(ITMask);
485   if (TZ > 3) {
486     DEBUG(errs() << "Encoding error: IT Mask '0000'");
487     return 0;
488   }
489   return (4 - TZ);
490 }
491
492 /// Init ITState.  Note that at least one bit is always 1 in mask.
493 bool Session::InitIT(unsigned short bits7_0) {
494   ITCounter = CountITSize(slice(bits7_0, 3, 0));
495   if (ITCounter == 0)
496     return false;
497
498   // A8.6.50 IT
499   unsigned short FirstCond = slice(bits7_0, 7, 4);
500   if (FirstCond == 0xF) {
501     DEBUG(errs() << "Encoding error: IT FirstCond '1111'");
502     return false;
503   }
504   if (FirstCond == 0xE && ITCounter != 1) {
505     DEBUG(errs() << "Encoding error: IT FirstCond '1110' && Mask != '1000'");
506     return false;
507   }
508
509   ITState = bits7_0;
510
511   return true;
512 }
513
514 /// Update ITState if necessary.
515 void Session::UpdateIT() {
516   assert(ITCounter);
517   --ITCounter;
518   if (ITCounter == 0)
519     ITState = 0;
520   else {
521     unsigned short NewITState4_0 = slice(ITState, 4, 0) << 1;
522     setSlice(ITState, 4, 0, NewITState4_0);
523   }
524 }
525
526 static MCDisassembler *createARMDisassembler(const Target &T) {
527   return new ARMDisassembler;
528 }
529
530 static MCDisassembler *createThumbDisassembler(const Target &T) {
531   return new ThumbDisassembler;
532 }
533
534 extern "C" void LLVMInitializeARMDisassembler() { 
535   // Register the disassembler.
536   TargetRegistry::RegisterMCDisassembler(TheARMTarget, 
537                                          createARMDisassembler);
538   TargetRegistry::RegisterMCDisassembler(TheThumbTarget,
539                                          createThumbDisassembler);
540 }
541
542 EDInstInfo *ARMDisassembler::getEDInfo() const {
543   return instInfoARM;
544 }
545
546 EDInstInfo *ThumbDisassembler::getEDInfo() const {
547   return instInfoARM;
548 }