Silence -Wunused-variable in release builds.
[llvm/stm8.git] / lib / MC / MCDisassembler / EDDisassembler.cpp
blob77c959f6713d557734308f61b3c3d8cd90c3a2c9
1 //===-EDDisassembler.cpp - LLVM Enhanced Disassembler ---------------------===//
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 implements the Enhanced Disassembly library's disassembler class.
11 // The disassembler is responsible for vending individual instructions according
12 // to a given architecture and disassembly syntax.
14 //===----------------------------------------------------------------------===//
16 #include "EDDisassembler.h"
17 #include "EDInst.h"
18 #include "llvm/MC/EDInstInfo.h"
19 #include "llvm/MC/MCAsmInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCDisassembler.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstPrinter.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCParser/AsmLexer.h"
28 #include "llvm/MC/MCParser/MCAsmParser.h"
29 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/MemoryObject.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Target/TargetAsmLexer.h"
34 #include "llvm/Target/TargetAsmParser.h"
35 #include "llvm/Target/TargetRegistry.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSelect.h"
39 using namespace llvm;
41 bool EDDisassembler::sInitialized = false;
42 EDDisassembler::DisassemblerMap_t EDDisassembler::sDisassemblers;
44 struct TripleMap {
45 Triple::ArchType Arch;
46 const char *String;
49 static struct TripleMap triplemap[] = {
50 { Triple::x86, "i386-unknown-unknown" },
51 { Triple::x86_64, "x86_64-unknown-unknown" },
52 { Triple::arm, "arm-unknown-unknown" },
53 { Triple::thumb, "thumb-unknown-unknown" },
54 { Triple::InvalidArch, NULL, }
57 /// infoFromArch - Returns the TripleMap corresponding to a given architecture,
58 /// or NULL if there is an error
59 ///
60 /// @arg arch - The Triple::ArchType for the desired architecture
61 static const char *tripleFromArch(Triple::ArchType arch) {
62 unsigned int infoIndex;
64 for (infoIndex = 0; triplemap[infoIndex].String != NULL; ++infoIndex) {
65 if (arch == triplemap[infoIndex].Arch)
66 return triplemap[infoIndex].String;
69 return NULL;
72 /// getLLVMSyntaxVariant - gets the constant to use to get an assembly printer
73 /// for the desired assembly syntax, suitable for passing to
74 /// Target::createMCInstPrinter()
75 ///
76 /// @arg arch - The target architecture
77 /// @arg syntax - The assembly syntax in sd form
78 static int getLLVMSyntaxVariant(Triple::ArchType arch,
79 EDDisassembler::AssemblySyntax syntax) {
80 switch (syntax) {
81 default:
82 return -1;
83 // Mappings below from X86AsmPrinter.cpp
84 case EDDisassembler::kEDAssemblySyntaxX86ATT:
85 if (arch == Triple::x86 || arch == Triple::x86_64)
86 return 0;
87 else
88 return -1;
89 case EDDisassembler::kEDAssemblySyntaxX86Intel:
90 if (arch == Triple::x86 || arch == Triple::x86_64)
91 return 1;
92 else
93 return -1;
94 case EDDisassembler::kEDAssemblySyntaxARMUAL:
95 if (arch == Triple::arm || arch == Triple::thumb)
96 return 0;
97 else
98 return -1;
102 void EDDisassembler::initialize() {
103 if (sInitialized)
104 return;
106 sInitialized = true;
108 InitializeAllTargetInfos();
109 InitializeAllTargets();
110 InitializeAllAsmPrinters();
111 InitializeAllAsmParsers();
112 InitializeAllDisassemblers();
115 #undef BRINGUP_TARGET
117 EDDisassembler *EDDisassembler::getDisassembler(Triple::ArchType arch,
118 AssemblySyntax syntax) {
119 CPUKey key;
120 key.Arch = arch;
121 key.Syntax = syntax;
123 EDDisassembler::DisassemblerMap_t::iterator i = sDisassemblers.find(key);
125 if (i != sDisassemblers.end()) {
126 return i->second;
127 } else {
128 EDDisassembler* sdd = new EDDisassembler(key);
129 if (!sdd->valid()) {
130 delete sdd;
131 return NULL;
134 sDisassemblers[key] = sdd;
136 return sdd;
139 return NULL;
142 EDDisassembler *EDDisassembler::getDisassembler(StringRef str,
143 AssemblySyntax syntax) {
144 return getDisassembler(Triple(str).getArch(), syntax);
147 EDDisassembler::EDDisassembler(CPUKey &key) :
148 Valid(false),
149 HasSemantics(false),
150 ErrorStream(nulls()),
151 Key(key) {
152 const char *triple = tripleFromArch(key.Arch);
154 if (!triple)
155 return;
157 LLVMSyntaxVariant = getLLVMSyntaxVariant(key.Arch, key.Syntax);
159 if (LLVMSyntaxVariant < 0)
160 return;
162 std::string tripleString(triple);
163 std::string errorString;
165 Tgt = TargetRegistry::lookupTarget(tripleString,
166 errorString);
168 if (!Tgt)
169 return;
171 std::string CPU;
172 std::string featureString;
173 TargetMachine.reset(Tgt->createTargetMachine(tripleString, CPU,
174 featureString));
176 const TargetRegisterInfo *registerInfo = TargetMachine->getRegisterInfo();
178 if (!registerInfo)
179 return;
181 initMaps(*registerInfo);
183 AsmInfo.reset(Tgt->createAsmInfo(tripleString));
185 if (!AsmInfo)
186 return;
188 Disassembler.reset(Tgt->createMCDisassembler());
190 if (!Disassembler)
191 return;
193 InstInfos = Disassembler->getEDInfo();
195 InstString.reset(new std::string);
196 InstStream.reset(new raw_string_ostream(*InstString));
197 InstPrinter.reset(Tgt->createMCInstPrinter(LLVMSyntaxVariant, *AsmInfo));
199 if (!InstPrinter)
200 return;
202 GenericAsmLexer.reset(new AsmLexer(*AsmInfo));
203 SpecificAsmLexer.reset(Tgt->createAsmLexer(*AsmInfo));
204 SpecificAsmLexer->InstallLexer(*GenericAsmLexer);
206 initMaps(*TargetMachine->getRegisterInfo());
208 Valid = true;
211 EDDisassembler::~EDDisassembler() {
212 if (!valid())
213 return;
216 namespace {
217 /// EDMemoryObject - a subclass of MemoryObject that allows use of a callback
218 /// as provided by the sd interface. See MemoryObject.
219 class EDMemoryObject : public llvm::MemoryObject {
220 private:
221 EDByteReaderCallback Callback;
222 void *Arg;
223 public:
224 EDMemoryObject(EDByteReaderCallback callback,
225 void *arg) : Callback(callback), Arg(arg) { }
226 ~EDMemoryObject() { }
227 uint64_t getBase() const { return 0x0; }
228 uint64_t getExtent() const { return (uint64_t)-1; }
229 int readByte(uint64_t address, uint8_t *ptr) const {
230 if (!Callback)
231 return -1;
233 if (Callback(ptr, address, Arg))
234 return -1;
236 return 0;
241 EDInst *EDDisassembler::createInst(EDByteReaderCallback byteReader,
242 uint64_t address,
243 void *arg) {
244 EDMemoryObject memoryObject(byteReader, arg);
246 MCInst* inst = new MCInst;
247 uint64_t byteSize;
249 if (!Disassembler->getInstruction(*inst,
250 byteSize,
251 memoryObject,
252 address,
253 ErrorStream)) {
254 delete inst;
255 return NULL;
256 } else {
257 const llvm::EDInstInfo *thisInstInfo = NULL;
259 if (InstInfos) {
260 thisInstInfo = &InstInfos[inst->getOpcode()];
263 EDInst* sdInst = new EDInst(inst, byteSize, *this, thisInstInfo);
264 return sdInst;
268 void EDDisassembler::initMaps(const TargetRegisterInfo &registerInfo) {
269 unsigned numRegisters = registerInfo.getNumRegs();
270 unsigned registerIndex;
272 for (registerIndex = 0; registerIndex < numRegisters; ++registerIndex) {
273 const char* registerName = registerInfo.get(registerIndex).Name;
275 RegVec.push_back(registerName);
276 RegRMap[registerName] = registerIndex;
279 switch (Key.Arch) {
280 default:
281 break;
282 case Triple::x86:
283 case Triple::x86_64:
284 stackPointers.insert(registerIDWithName("SP"));
285 stackPointers.insert(registerIDWithName("ESP"));
286 stackPointers.insert(registerIDWithName("RSP"));
288 programCounters.insert(registerIDWithName("IP"));
289 programCounters.insert(registerIDWithName("EIP"));
290 programCounters.insert(registerIDWithName("RIP"));
291 break;
292 case Triple::arm:
293 case Triple::thumb:
294 stackPointers.insert(registerIDWithName("SP"));
296 programCounters.insert(registerIDWithName("PC"));
297 break;
301 const char *EDDisassembler::nameWithRegisterID(unsigned registerID) const {
302 if (registerID >= RegVec.size())
303 return NULL;
304 else
305 return RegVec[registerID].c_str();
308 unsigned EDDisassembler::registerIDWithName(const char *name) const {
309 regrmap_t::const_iterator iter = RegRMap.find(std::string(name));
310 if (iter == RegRMap.end())
311 return 0;
312 else
313 return (*iter).second;
316 bool EDDisassembler::registerIsStackPointer(unsigned registerID) {
317 return (stackPointers.find(registerID) != stackPointers.end());
320 bool EDDisassembler::registerIsProgramCounter(unsigned registerID) {
321 return (programCounters.find(registerID) != programCounters.end());
324 int EDDisassembler::printInst(std::string &str, MCInst &inst) {
325 PrinterMutex.acquire();
327 InstPrinter->printInst(&inst, *InstStream);
328 InstStream->flush();
329 str = *InstString;
330 InstString->clear();
332 PrinterMutex.release();
334 return 0;
337 static void diag_handler(const SMDiagnostic &diag,
338 void *context)
340 if (context) {
341 EDDisassembler *disassembler = static_cast<EDDisassembler*>(context);
342 diag.Print("", disassembler->ErrorStream);
346 int EDDisassembler::parseInst(SmallVectorImpl<MCParsedAsmOperand*> &operands,
347 SmallVectorImpl<AsmToken> &tokens,
348 const std::string &str) {
349 int ret = 0;
351 switch (Key.Arch) {
352 default:
353 return -1;
354 case Triple::x86:
355 case Triple::x86_64:
356 case Triple::arm:
357 case Triple::thumb:
358 break;
361 const char *cStr = str.c_str();
362 MemoryBuffer *buf = MemoryBuffer::getMemBuffer(cStr, cStr + strlen(cStr));
364 StringRef instName;
365 SMLoc instLoc;
367 SourceMgr sourceMgr;
368 sourceMgr.setDiagHandler(diag_handler, static_cast<void*>(this));
369 sourceMgr.AddNewSourceBuffer(buf, SMLoc()); // ownership of buf handed over
370 MCContext context(*AsmInfo, NULL);
371 OwningPtr<MCStreamer> streamer(createNullStreamer(context));
372 OwningPtr<MCAsmParser> genericParser(createMCAsmParser(*Tgt, sourceMgr,
373 context, *streamer,
374 *AsmInfo));
376 StringRef triple = tripleFromArch(Key.Arch);
377 OwningPtr<MCSubtargetInfo> STI(Tgt->createMCSubtargetInfo(triple, "", ""));
378 OwningPtr<TargetAsmParser> TargetParser(Tgt->createAsmParser(*STI,
379 *genericParser));
381 AsmToken OpcodeToken = genericParser->Lex();
382 AsmToken NextToken = genericParser->Lex(); // consume next token, because specificParser expects us to
384 if (OpcodeToken.is(AsmToken::Identifier)) {
385 instName = OpcodeToken.getString();
386 instLoc = OpcodeToken.getLoc();
388 if (NextToken.isNot(AsmToken::Eof) &&
389 TargetParser->ParseInstruction(instName, instLoc, operands))
390 ret = -1;
391 } else {
392 ret = -1;
395 ParserMutex.acquire();
397 if (!ret) {
398 GenericAsmLexer->setBuffer(buf);
400 while (SpecificAsmLexer->Lex(),
401 SpecificAsmLexer->isNot(AsmToken::Eof) &&
402 SpecificAsmLexer->isNot(AsmToken::EndOfStatement)) {
403 if (SpecificAsmLexer->is(AsmToken::Error)) {
404 ret = -1;
405 break;
407 tokens.push_back(SpecificAsmLexer->getTok());
411 ParserMutex.release();
413 return ret;
416 int EDDisassembler::llvmSyntaxVariant() const {
417 return LLVMSyntaxVariant;