f8260af53c90f94d78ae44d96935dc972f0b4925
[oota-llvm.git] / lib / MC / MCDisassembler / Disassembler.cpp
1 //===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
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 #include "Disassembler.h"
11 #include "llvm-c/Disassembler.h"
12 #include "llvm/MC/MCAsmInfo.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCDisassembler.h"
15 #include "llvm/MC/MCInst.h"
16 #include "llvm/MC/MCInstPrinter.h"
17 #include "llvm/MC/MCInstrInfo.h"
18 #include "llvm/MC/MCRegisterInfo.h"
19 #include "llvm/MC/MCRelocationInfo.h"
20 #include "llvm/MC/MCSubtargetInfo.h"
21 #include "llvm/MC/MCSymbolizer.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/FormattedStream.h"
24 #include "llvm/Support/TargetRegistry.h"
25
26 using namespace llvm;
27
28 // LLVMCreateDisasm() creates a disassembler for the TripleName.  Symbolic
29 // disassembly is supported by passing a block of information in the DisInfo
30 // parameter and specifying the TagType and callback functions as described in
31 // the header llvm-c/Disassembler.h .  The pointer to the block and the 
32 // functions can all be passed as NULL.  If successful, this returns a
33 // disassembler context.  If not, it returns NULL.
34 //
35 LLVMDisasmContextRef
36 LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU,
37                             const char *Features, void *DisInfo, int TagType,
38                             LLVMOpInfoCallback GetOpInfo,
39                             LLVMSymbolLookupCallback SymbolLookUp) {
40   // Get the target.
41   std::string Error;
42   const Target *TheTarget = TargetRegistry::lookupTarget(TT, Error);
43   if (!TheTarget)
44     return nullptr;
45
46   const MCRegisterInfo *MRI = TheTarget->createMCRegInfo(TT);
47   if (!MRI)
48     return nullptr;
49
50   // Get the assembler info needed to setup the MCContext.
51   const MCAsmInfo *MAI = TheTarget->createMCAsmInfo(*MRI, TT);
52   if (!MAI)
53     return nullptr;
54
55   const MCInstrInfo *MII = TheTarget->createMCInstrInfo();
56   if (!MII)
57     return nullptr;
58
59   const MCSubtargetInfo *STI =
60       TheTarget->createMCSubtargetInfo(TT, CPU, Features);
61   if (!STI)
62     return nullptr;
63
64   // Set up the MCContext for creating symbols and MCExpr's.
65   MCContext *Ctx = new MCContext(MAI, MRI, nullptr);
66   if (!Ctx)
67     return nullptr;
68
69   // Set up disassembler.
70   MCDisassembler *DisAsm = TheTarget->createMCDisassembler(*STI, *Ctx);
71   if (!DisAsm)
72     return nullptr;
73
74   std::unique_ptr<MCRelocationInfo> RelInfo(
75       TheTarget->createMCRelocationInfo(TT, *Ctx));
76   if (!RelInfo)
77     return nullptr;
78
79   std::unique_ptr<MCSymbolizer> Symbolizer(TheTarget->createMCSymbolizer(
80       TT, GetOpInfo, SymbolLookUp, DisInfo, Ctx, std::move(RelInfo)));
81   DisAsm->setSymbolizer(std::move(Symbolizer));
82
83   // Set up the instruction printer.
84   int AsmPrinterVariant = MAI->getAssemblerDialect();
85   MCInstPrinter *IP = TheTarget->createMCInstPrinter(
86       Triple(TT), AsmPrinterVariant, *MAI, *MII, *MRI);
87   if (!IP)
88     return nullptr;
89
90   LLVMDisasmContext *DC =
91       new LLVMDisasmContext(TT, DisInfo, TagType, GetOpInfo, SymbolLookUp,
92                             TheTarget, MAI, MRI, STI, MII, Ctx, DisAsm, IP);
93   if (!DC)
94     return nullptr;
95
96   DC->setCPU(CPU);
97   return DC;
98 }
99
100 LLVMDisasmContextRef
101 LLVMCreateDisasmCPU(const char *TT, const char *CPU, void *DisInfo, int TagType,
102                     LLVMOpInfoCallback GetOpInfo,
103                     LLVMSymbolLookupCallback SymbolLookUp) {
104   return LLVMCreateDisasmCPUFeatures(TT, CPU, "", DisInfo, TagType, GetOpInfo,
105                                      SymbolLookUp);
106 }
107
108 LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo,
109                                       int TagType, LLVMOpInfoCallback GetOpInfo,
110                                       LLVMSymbolLookupCallback SymbolLookUp) {
111   return LLVMCreateDisasmCPUFeatures(TT, "", "", DisInfo, TagType, GetOpInfo,
112                                      SymbolLookUp);
113 }
114
115 //
116 // LLVMDisasmDispose() disposes of the disassembler specified by the context.
117 //
118 void LLVMDisasmDispose(LLVMDisasmContextRef DCR){
119   LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
120   delete DC;
121 }
122
123 /// \brief Emits the comments that are stored in \p DC comment stream.
124 /// Each comment in the comment stream must end with a newline.
125 static void emitComments(LLVMDisasmContext *DC,
126                          formatted_raw_ostream &FormattedOS) {
127   // Flush the stream before taking its content.
128   DC->CommentStream.flush();
129   StringRef Comments = DC->CommentsToEmit.str();
130   // Get the default information for printing a comment.
131   const MCAsmInfo *MAI = DC->getAsmInfo();
132   const char *CommentBegin = MAI->getCommentString();
133   unsigned CommentColumn = MAI->getCommentColumn();
134   bool IsFirst = true;
135   while (!Comments.empty()) {
136     if (!IsFirst)
137       FormattedOS << '\n';
138     // Emit a line of comments.
139     FormattedOS.PadToColumn(CommentColumn);
140     size_t Position = Comments.find('\n');
141     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
142     // Move after the newline character.
143     Comments = Comments.substr(Position+1);
144     IsFirst = false;
145   }
146   FormattedOS.flush();
147
148   // Tell the comment stream that the vector changed underneath it.
149   DC->CommentsToEmit.clear();
150 }
151
152 /// \brief Gets latency information for \p Inst from the itinerary
153 /// scheduling model, based on \p DC information.
154 /// \return The maximum expected latency over all the operands or -1
155 /// if no information is available.
156 static int getItineraryLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
157   const int NoInformationAvailable = -1;
158
159   // Check if we have a CPU to get the itinerary information.
160   if (DC->getCPU().empty())
161     return NoInformationAvailable;
162
163   // Get itinerary information.
164   const MCSubtargetInfo *STI = DC->getSubtargetInfo();
165   InstrItineraryData IID = STI->getInstrItineraryForCPU(DC->getCPU());
166   // Get the scheduling class of the requested instruction.
167   const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
168   unsigned SCClass = Desc.getSchedClass();
169
170   int Latency = 0;
171   for (unsigned OpIdx = 0, OpIdxEnd = Inst.getNumOperands(); OpIdx != OpIdxEnd;
172        ++OpIdx)
173     Latency = std::max(Latency, IID.getOperandCycle(SCClass, OpIdx));
174
175   return Latency;
176 }
177
178 /// \brief Gets latency information for \p Inst, based on \p DC information.
179 /// \return The maximum expected latency over all the definitions or -1
180 /// if no information is available.
181 static int getLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
182   // Try to compute scheduling information.
183   const MCSubtargetInfo *STI = DC->getSubtargetInfo();
184   const MCSchedModel SCModel = STI->getSchedModel();
185   const int NoInformationAvailable = -1;
186
187   // Check if we have a scheduling model for instructions.
188   if (!SCModel.hasInstrSchedModel())
189     // Try to fall back to the itinerary model if the scheduling model doesn't
190     // have a scheduling table.  Note the default does not have a table.
191     return getItineraryLatency(DC, Inst);
192
193   // Get the scheduling class of the requested instruction.
194   const MCInstrDesc& Desc = DC->getInstrInfo()->get(Inst.getOpcode());
195   unsigned SCClass = Desc.getSchedClass();
196   const MCSchedClassDesc *SCDesc = SCModel.getSchedClassDesc(SCClass);
197   // Resolving the variant SchedClass requires an MI to pass to
198   // SubTargetInfo::resolveSchedClass.
199   if (!SCDesc || !SCDesc->isValid() || SCDesc->isVariant())
200     return NoInformationAvailable;
201
202   // Compute output latency.
203   int Latency = 0;
204   for (unsigned DefIdx = 0, DefEnd = SCDesc->NumWriteLatencyEntries;
205        DefIdx != DefEnd; ++DefIdx) {
206     // Lookup the definition's write latency in SubtargetInfo.
207     const MCWriteLatencyEntry *WLEntry = STI->getWriteLatencyEntry(SCDesc,
208                                                                    DefIdx);
209     Latency = std::max(Latency, WLEntry->Cycles);
210   }
211
212   return Latency;
213 }
214
215
216 /// \brief Emits latency information in DC->CommentStream for \p Inst, based
217 /// on the information available in \p DC.
218 static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
219   int Latency = getLatency(DC, Inst);
220
221   // Report only interesting latencies.
222   if (Latency < 2)
223     return;
224
225   DC->CommentStream << "Latency: " << Latency << '\n';
226 }
227
228 //
229 // LLVMDisasmInstruction() disassembles a single instruction using the
230 // disassembler context specified in the parameter DC.  The bytes of the
231 // instruction are specified in the parameter Bytes, and contains at least
232 // BytesSize number of bytes.  The instruction is at the address specified by
233 // the PC parameter.  If a valid instruction can be disassembled its string is
234 // returned indirectly in OutString which whos size is specified in the
235 // parameter OutStringSize.  This function returns the number of bytes in the
236 // instruction or zero if there was no valid instruction.  If this function
237 // returns zero the caller will have to pick how many bytes they want to step
238 // over by printing a .byte, .long etc. to continue.
239 //
240 size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes,
241                              uint64_t BytesSize, uint64_t PC, char *OutString,
242                              size_t OutStringSize){
243   LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
244   // Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
245   ArrayRef<uint8_t> Data(Bytes, BytesSize);
246
247   uint64_t Size;
248   MCInst Inst;
249   const MCDisassembler *DisAsm = DC->getDisAsm();
250   MCInstPrinter *IP = DC->getIP();
251   MCDisassembler::DecodeStatus S;
252   SmallVector<char, 64> InsnStr;
253   raw_svector_ostream Annotations(InsnStr);
254   S = DisAsm->getInstruction(Inst, Size, Data, PC,
255                              /*REMOVE*/ nulls(), Annotations);
256   switch (S) {
257   case MCDisassembler::Fail:
258   case MCDisassembler::SoftFail:
259     // FIXME: Do something different for soft failure modes?
260     return 0;
261
262   case MCDisassembler::Success: {
263     Annotations.flush();
264     StringRef AnnotationsStr = Annotations.str();
265
266     SmallVector<char, 64> InsnStr;
267     raw_svector_ostream OS(InsnStr);
268     formatted_raw_ostream FormattedOS(OS);
269     IP->printInst(&Inst, FormattedOS, AnnotationsStr, *DC->getSubtargetInfo());
270
271     if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
272       emitLatency(DC, Inst);
273
274     emitComments(DC, FormattedOS);
275     OS.flush();
276
277     assert(OutStringSize != 0 && "Output buffer cannot be zero size");
278     size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
279     std::memcpy(OutString, InsnStr.data(), OutputSize);
280     OutString[OutputSize] = '\0'; // Terminate string.
281
282     return Size;
283   }
284   }
285   llvm_unreachable("Invalid DecodeStatus!");
286 }
287
288 //
289 // LLVMSetDisasmOptions() sets the disassembler's options.  It returns 1 if it
290 // can set all the Options and 0 otherwise.
291 //
292 int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options){
293   if (Options & LLVMDisassembler_Option_UseMarkup){
294       LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
295       MCInstPrinter *IP = DC->getIP();
296       IP->setUseMarkup(1);
297       DC->addOptions(LLVMDisassembler_Option_UseMarkup);
298       Options &= ~LLVMDisassembler_Option_UseMarkup;
299   }
300   if (Options & LLVMDisassembler_Option_PrintImmHex){
301       LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
302       MCInstPrinter *IP = DC->getIP();
303       IP->setPrintImmHex(1);
304       DC->addOptions(LLVMDisassembler_Option_PrintImmHex);
305       Options &= ~LLVMDisassembler_Option_PrintImmHex;
306   }
307   if (Options & LLVMDisassembler_Option_AsmPrinterVariant){
308       LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
309       // Try to set up the new instruction printer.
310       const MCAsmInfo *MAI = DC->getAsmInfo();
311       const MCInstrInfo *MII = DC->getInstrInfo();
312       const MCRegisterInfo *MRI = DC->getRegisterInfo();
313       int AsmPrinterVariant = MAI->getAssemblerDialect();
314       AsmPrinterVariant = AsmPrinterVariant == 0 ? 1 : 0;
315       MCInstPrinter *IP = DC->getTarget()->createMCInstPrinter(
316           Triple(DC->getTripleName()), AsmPrinterVariant, *MAI, *MII, *MRI);
317       if (IP) {
318         DC->setIP(IP);
319         DC->addOptions(LLVMDisassembler_Option_AsmPrinterVariant);
320         Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
321       }
322   }
323   if (Options & LLVMDisassembler_Option_SetInstrComments) {
324     LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
325     MCInstPrinter *IP = DC->getIP();
326     IP->setCommentStream(DC->CommentStream);
327     DC->addOptions(LLVMDisassembler_Option_SetInstrComments);
328     Options &= ~LLVMDisassembler_Option_SetInstrComments;
329   }
330   if (Options & LLVMDisassembler_Option_PrintLatency) {
331     LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
332     DC->addOptions(LLVMDisassembler_Option_PrintLatency);
333     Options &= ~LLVMDisassembler_Option_PrintLatency;
334   }
335   return (Options == 0);
336 }