LLVM 23.0.0git
Disassembler.cpp
Go to the documentation of this file.
1//===-- lib/MC/Disassembler.cpp - Disassembler Public C Interface ---------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Disassembler.h"
10#include "llvm-c/Disassembler.h"
11#include "llvm/ADT/ArrayRef.h"
13#include "llvm/MC/MCAsmInfo.h"
14#include "llvm/MC/MCContext.h"
18#include "llvm/MC/MCInst.h"
20#include "llvm/MC/MCInstrInfo.h"
22#include "llvm/MC/MCSchedule.h"
30#include <cassert>
31#include <cstring>
32
33using namespace llvm;
34
35// LLVMCreateDisasm() creates a disassembler for the TripleName. Symbolic
36// disassembly is supported by passing a block of information in the DisInfo
37// parameter and specifying the TagType and callback functions as described in
38// the header llvm-c/Disassembler.h . The pointer to the block and the
39// functions can all be passed as NULL. If successful, this returns a
40// disassembler context. If not, it returns NULL.
41//
43LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU,
44 const char *Features, void *DisInfo, int TagType,
45 LLVMOpInfoCallback GetOpInfo,
46 LLVMSymbolLookupCallback SymbolLookUp) {
47 Triple TheTriple(TT);
48
49 // Get the target.
50 std::string Error;
51 const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple, Error);
52 if (!TheTarget)
53 return nullptr;
54
55 std::unique_ptr<const MCRegisterInfo> MRI(
56 TheTarget->createMCRegInfo(TheTriple));
57 if (!MRI)
58 return nullptr;
59
60 MCTargetOptions MCOptions;
61 // Get the assembler info needed to setup the MCContext.
62 std::unique_ptr<const MCAsmInfo> MAI(
63 TheTarget->createMCAsmInfo(*MRI, TheTriple, MCOptions));
64 if (!MAI)
65 return nullptr;
66
67 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
68 if (!MII)
69 return nullptr;
70
71 std::unique_ptr<const MCSubtargetInfo> STI(
72 TheTarget->createMCSubtargetInfo(TheTriple, CPU, Features));
73 if (!STI)
74 return nullptr;
75
76 // Set up the MCContext for creating symbols and MCExpr's.
77 std::unique_ptr<MCContext> Ctx(new MCContext(TheTriple, *MAI, *MRI, *STI));
78 if (!Ctx)
79 return nullptr;
80
81 // Set up disassembler.
82 std::unique_ptr<MCDisassembler> DisAsm(
83 TheTarget->createMCDisassembler(*STI, *Ctx));
84 if (!DisAsm)
85 return nullptr;
86
87 std::unique_ptr<MCRelocationInfo> RelInfo(
88 TheTarget->createMCRelocationInfo(TheTriple, *Ctx));
89 if (!RelInfo)
90 return nullptr;
91
92 std::unique_ptr<MCSymbolizer> Symbolizer(
93 TheTarget->createMCSymbolizer(TheTriple, GetOpInfo, SymbolLookUp, DisInfo,
94 Ctx.get(), std::move(RelInfo)));
95 DisAsm->setSymbolizer(std::move(Symbolizer));
96
97 // Set up the instruction printer.
98 int AsmPrinterVariant = MAI->getAssemblerDialect();
99 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
100 Triple(TT), AsmPrinterVariant, *MAI, *MII, *MRI));
101 if (!IP)
102 return nullptr;
103
105 TT, DisInfo, TagType, GetOpInfo, SymbolLookUp, TheTarget, std::move(MAI),
106 std::move(MRI), std::move(STI), std::move(MII), std::move(Ctx),
107 std::move(DisAsm), std::move(IP));
108 if (!DC)
109 return nullptr;
110
111 DC->setCPU(CPU);
112 return DC;
113}
114
116LLVMCreateDisasmCPU(const char *TT, const char *CPU, void *DisInfo, int TagType,
117 LLVMOpInfoCallback GetOpInfo,
118 LLVMSymbolLookupCallback SymbolLookUp) {
119 return LLVMCreateDisasmCPUFeatures(TT, CPU, "", DisInfo, TagType, GetOpInfo,
120 SymbolLookUp);
121}
122
123LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo,
124 int TagType, LLVMOpInfoCallback GetOpInfo,
125 LLVMSymbolLookupCallback SymbolLookUp) {
126 return LLVMCreateDisasmCPUFeatures(TT, "", "", DisInfo, TagType, GetOpInfo,
127 SymbolLookUp);
128}
129
130//
131// LLVMDisasmDispose() disposes of the disassembler specified by the context.
132//
134 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
135 delete DC;
136}
137
138/// Emits the comments that are stored in \p DC comment stream.
139/// Each comment in the comment stream must end with a newline.
141 formatted_raw_ostream &FormattedOS) {
142 // Flush the stream before taking its content.
143 StringRef Comments = DC->CommentsToEmit.str();
144 // Get the default information for printing a comment.
145 const MCAsmInfo *MAI = DC->getAsmInfo();
146 StringRef CommentBegin = MAI->getCommentString();
147 unsigned CommentColumn = MAI->getCommentColumn();
148 bool IsFirst = true;
149 while (!Comments.empty()) {
150 if (!IsFirst)
151 FormattedOS << '\n';
152 // Emit a line of comments.
153 FormattedOS.PadToColumn(CommentColumn);
154 size_t Position = Comments.find('\n');
155 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
156 // Move after the newline character.
157 Comments = Comments.substr(Position+1);
158 IsFirst = false;
159 }
160 FormattedOS.flush();
161
162 // Tell the comment stream that the vector changed underneath it.
163 DC->CommentsToEmit.clear();
164}
165
166/// Emits latency information in DC->CommentStream for \p Inst, based
167/// on the information available in \p DC.
168static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
169 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
170 const MCInstrInfo *MCII = DC->getInstrInfo();
171 const MCSchedModel &SCModel = STI->getSchedModel();
172 int Latency = SCModel.computeInstrLatency(*STI, *MCII, Inst);
173
174 // Report only interesting latencies.
175 if (Latency < 2)
176 return;
177
178 DC->CommentStream << "Latency: " << Latency << '\n';
179}
180
181//
182// LLVMDisasmInstruction() disassembles a single instruction using the
183// disassembler context specified in the parameter DC. The bytes of the
184// instruction are specified in the parameter Bytes, and contains at least
185// BytesSize number of bytes. The instruction is at the address specified by
186// the PC parameter. If a valid instruction can be disassembled its string is
187// returned indirectly in OutString which whos size is specified in the
188// parameter OutStringSize. This function returns the number of bytes in the
189// instruction or zero if there was no valid instruction. If this function
190// returns zero the caller will have to pick how many bytes they want to step
191// over by printing a .byte, .long etc. to continue.
192//
194 uint64_t BytesSize, uint64_t PC, char *OutString,
195 size_t OutStringSize){
196 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
197 // Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
198 ArrayRef<uint8_t> Data(Bytes, BytesSize);
199
201 MCInst Inst;
202 const MCDisassembler *DisAsm = DC->getDisAsm();
203 MCInstPrinter *IP = DC->getIP();
205 SmallVector<char, 64> InsnStr;
207 S = DisAsm->getInstruction(Inst, Size, Data, PC, Annotations);
208 switch (S) {
211 // FIXME: Do something different for soft failure modes?
212 return 0;
213
215 StringRef AnnotationsStr = Annotations.str();
216
217 SmallVector<char, 64> InsnStr;
218 raw_svector_ostream OS(InsnStr);
219 formatted_raw_ostream FormattedOS(OS);
220
222 FormattedOS.enable_colors(true);
223 IP->setUseColor(true);
224 }
225
226 IP->printInst(&Inst, PC, AnnotationsStr, *DC->getSubtargetInfo(),
227 FormattedOS);
228
230 emitLatency(DC, Inst);
231
232 emitComments(DC, FormattedOS);
233
234 assert(OutStringSize != 0 && "Output buffer cannot be zero size");
235 size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
236 std::memcpy(OutString, InsnStr.data(), OutputSize);
237 OutString[OutputSize] = '\0'; // Terminate string.
238
239 return Size;
240 }
241 }
242 llvm_unreachable("Invalid DecodeStatus!");
243}
244
245//
246// LLVMSetDisasmOptions() sets the disassembler's options. It returns 1 if it
247// can set all the Options and 0 otherwise.
248//
251 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
252 MCInstPrinter *IP = DC->getIP();
253 IP->setUseMarkup(true);
256 }
258 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
259 MCInstPrinter *IP = DC->getIP();
260 IP->setPrintImmHex(true);
263 }
265 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
266 // Try to set up the new instruction printer.
267 const MCAsmInfo *MAI = DC->getAsmInfo();
268 const MCInstrInfo *MII = DC->getInstrInfo();
269 const MCRegisterInfo *MRI = DC->getRegisterInfo();
270 int AsmPrinterVariant = MAI->getAssemblerDialect();
271 AsmPrinterVariant = AsmPrinterVariant == 0 ? 1 : 0;
273 Triple(DC->getTripleName()), AsmPrinterVariant, *MAI, *MII, *MRI);
274 if (IP) {
275 DC->setIP(IP);
278 }
279 }
281 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
282 MCInstPrinter *IP = DC->getIP();
286 }
288 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
291 }
293 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
296 }
297 return (Options == 0);
298}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static void emitComments(LLVMDisasmContext *DC, formatted_raw_ostream &FormattedOS)
Emits the comments that are stored in DC comment stream.
static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst)
Emits latency information in DC->CommentStream for Inst, based on the information available in DC.
static LVOptions Options
Definition LVOptions.cpp:25
This file defines the SmallVector class.
Annotations lets you mark points and ranges inside source code, for tests:
Definition Annotations.h:53
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
const MCDisassembler * getDisAsm() const
void setCPU(const char *CPU)
void addOptions(uint64_t Options)
raw_svector_ostream CommentStream
void setIP(MCInstPrinter *NewIP)
const MCSubtargetInfo * getSubtargetInfo() const
const MCAsmInfo * getAsmInfo() const
uint64_t getOptions() const
const MCRegisterInfo * getRegisterInfo() const
SmallString< 128 > CommentsToEmit
MCInstPrinter * getIP()
StringRef getTripleName() const
const MCInstrInfo * getInstrInfo() const
const Target * getTarget() const
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:66
unsigned getAssemblerDialect() const
Definition MCAsmInfo.h:580
StringRef getCommentString() const
Definition MCAsmInfo.h:558
unsigned getCommentColumn() const
Definition MCAsmInfo.h:555
Context object for machine code objects.
Definition MCContext.h:83
Superclass for all disassemblers.
DecodeStatus
Ternary decode status.
virtual DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size, ArrayRef< uint8_t > Bytes, uint64_t Address, raw_ostream &CStream) const =0
Returns the disassembly of a single instruction.
This is an instance of a target assembly language printer that converts an MCInst to valid target ass...
void setCommentStream(raw_ostream &OS)
Specify a stream to emit comments to.
void setUseColor(bool Value)
void setPrintImmHex(bool Value)
void setUseMarkup(bool Value)
virtual void printInst(const MCInst *MI, uint64_t Address, StringRef Annot, const MCSubtargetInfo &STI, raw_ostream &OS)=0
Print the specified MCInst to the specified raw_ostream.
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
Interface to description of machine instruction set.
Definition MCInstrInfo.h:27
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Generic base class for all target subtargets.
const MCSchedModel & getSchedModel() const
Get the machine model for this subtarget's CPU.
StringRef str() const
Explicit conversion to StringRef.
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:591
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
Target - Wrapper for Target specific information.
MCRegisterInfo * createMCRegInfo(const Triple &TT) const
Create a MCRegisterInfo implementation.
MCAsmInfo * createMCAsmInfo(const MCRegisterInfo &MRI, const Triple &TheTriple, const MCTargetOptions &Options) const
Create a MCAsmInfo implementation for the specified target triple.
MCSymbolizer * createMCSymbolizer(const Triple &TT, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp, void *DisInfo, MCContext *Ctx, std::unique_ptr< MCRelocationInfo > &&RelInfo) const
createMCSymbolizer - Create a target specific MCSymbolizer.
MCDisassembler * createMCDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx) const
MCInstPrinter * createMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) const
MCRelocationInfo * createMCRelocationInfo(const Triple &TT, MCContext &Ctx) const
createMCRelocationInfo - Create a target specific MCRelocationInfo.
MCSubtargetInfo * createMCSubtargetInfo(const Triple &TheTriple, StringRef CPU, StringRef Features) const
createMCSubtargetInfo - Create a MCSubtargetInfo implementation.
MCInstrInfo * createMCInstrInfo() const
createMCInstrInfo - Create a MCInstrInfo implementation.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
formatted_raw_ostream - A raw_ostream that wraps another one and keeps track of line and column posit...
formatted_raw_ostream & PadToColumn(unsigned NewCol)
PadToColumn - Align the output to some column number.
virtual void enable_colors(bool enable)
A raw_ostream that writes to an SmallVector or SmallString.
const char *(* LLVMSymbolLookupCallback)(void *DisInfo, uint64_t ReferenceValue, uint64_t *ReferenceType, uint64_t ReferencePC, const char **ReferenceName)
The type for the symbol lookup function.
#define LLVMDisassembler_Option_PrintImmHex
#define LLVMDisassembler_Option_UseMarkup
void LLVMDisasmDispose(LLVMDisasmContextRef DCR)
Dispose of a disassembler context.
int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options)
Set the disassembler's options.
#define LLVMDisassembler_Option_PrintLatency
LLVMDisasmContextRef LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU, const char *Features, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp)
Create a disassembler for the TripleName, a specific CPU and specific feature string.
#define LLVMDisassembler_Option_SetInstrComments
LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp)
Create a disassembler for the TripleName.
#define LLVMDisassembler_Option_Color
int(* LLVMOpInfoCallback)(void *DisInfo, uint64_t PC, uint64_t Offset, uint64_t OpSize, uint64_t InstSize, int TagType, void *TagBuf)
The type for the operand information call back function.
size_t LLVMDisasmInstruction(LLVMDisasmContextRef DCR, uint8_t *Bytes, uint64_t BytesSize, uint64_t PC, char *OutString, size_t OutStringSize)
Disassemble a single instruction using the disassembler context specified in the parameter DC.
LLVMDisasmContextRef LLVMCreateDisasmCPU(const char *TT, const char *CPU, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp)
Create a disassembler for the TripleName and a specific CPU.
#define LLVMDisassembler_Option_AsmPrinterVariant
void * LLVMDisasmContextRef
An opaque reference to a disassembler context.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:258
static LLVM_ABI int computeInstrLatency(const MCSubtargetInfo &STI, const MCSchedClassDesc &SCDesc)
Returns the latency value for the scheduling class.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.