1 //===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
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.
36 LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU,
37 const char *Features, void *DisInfo, int TagType,
38 LLVMOpInfoCallback GetOpInfo,
39 LLVMSymbolLookupCallback SymbolLookUp) {
42 const Target *TheTarget = TargetRegistry::lookupTarget(TT, Error);
46 const MCRegisterInfo *MRI = TheTarget->createMCRegInfo(TT);
50 // Get the assembler info needed to setup the MCContext.
51 const MCAsmInfo *MAI = TheTarget->createMCAsmInfo(*MRI, TT);
55 const MCInstrInfo *MII = TheTarget->createMCInstrInfo();
59 const MCSubtargetInfo *STI =
60 TheTarget->createMCSubtargetInfo(TT, CPU, Features);
64 // Set up the MCContext for creating symbols and MCExpr's.
65 MCContext *Ctx = new MCContext(MAI, MRI, nullptr);
69 // Set up disassembler.
70 MCDisassembler *DisAsm = TheTarget->createMCDisassembler(*STI, *Ctx);
74 std::unique_ptr<MCRelocationInfo> RelInfo(
75 TheTarget->createMCRelocationInfo(TT, *Ctx));
79 std::unique_ptr<MCSymbolizer> Symbolizer(TheTarget->createMCSymbolizer(
80 TT, GetOpInfo, SymbolLookUp, DisInfo, Ctx, std::move(RelInfo)));
81 DisAsm->setSymbolizer(std::move(Symbolizer));
83 // Set up the instruction printer.
84 int AsmPrinterVariant = MAI->getAssemblerDialect();
85 MCInstPrinter *IP = TheTarget->createMCInstPrinter(
86 Triple(TT), AsmPrinterVariant, *MAI, *MII, *MRI);
90 LLVMDisasmContext *DC =
91 new LLVMDisasmContext(TT, DisInfo, TagType, GetOpInfo, SymbolLookUp,
92 TheTarget, MAI, MRI, STI, MII, Ctx, DisAsm, IP);
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,
108 LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo,
109 int TagType, LLVMOpInfoCallback GetOpInfo,
110 LLVMSymbolLookupCallback SymbolLookUp) {
111 return LLVMCreateDisasmCPUFeatures(TT, "", "", DisInfo, TagType, GetOpInfo,
116 // LLVMDisasmDispose() disposes of the disassembler specified by the context.
118 void LLVMDisasmDispose(LLVMDisasmContextRef DCR){
119 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
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();
135 while (!Comments.empty()) {
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);
148 // Tell the comment stream that the vector changed underneath it.
149 DC->CommentsToEmit.clear();
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;
159 // Check if we have a CPU to get the itinerary information.
160 if (DC->getCPU().empty())
161 return NoInformationAvailable;
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();
171 for (unsigned OpIdx = 0, OpIdxEnd = Inst.getNumOperands(); OpIdx != OpIdxEnd;
173 Latency = std::max(Latency, IID.getOperandCycle(SCClass, OpIdx));
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;
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);
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;
202 // Compute output latency.
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,
209 Latency = std::max(Latency, WLEntry->Cycles);
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);
221 // Report only interesting latencies.
225 DC->CommentStream << "Latency: " << Latency << '\n';
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.
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);
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);
257 case MCDisassembler::Fail:
258 case MCDisassembler::SoftFail:
259 // FIXME: Do something different for soft failure modes?
262 case MCDisassembler::Success: {
264 StringRef AnnotationsStr = Annotations.str();
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());
271 if (DC->getOptions() & LLVMDisassembler_Option_PrintLatency)
272 emitLatency(DC, Inst);
274 emitComments(DC, FormattedOS);
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.
285 llvm_unreachable("Invalid DecodeStatus!");
289 // LLVMSetDisasmOptions() sets the disassembler's options. It returns 1 if it
290 // can set all the Options and 0 otherwise.
292 int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options){
293 if (Options & LLVMDisassembler_Option_UseMarkup){
294 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
295 MCInstPrinter *IP = DC->getIP();
297 DC->addOptions(LLVMDisassembler_Option_UseMarkup);
298 Options &= ~LLVMDisassembler_Option_UseMarkup;
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;
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);
319 DC->addOptions(LLVMDisassembler_Option_AsmPrinterVariant);
320 Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
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;
330 if (Options & LLVMDisassembler_Option_PrintLatency) {
331 LLVMDisasmContext *DC = (LLVMDisasmContext *)DCR;
332 DC->addOptions(LLVMDisassembler_Option_PrintLatency);
333 Options &= ~LLVMDisassembler_Option_PrintLatency;
335 return (Options == 0);