LLVM 20.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/MCInstrDesc.h"
21#include "llvm/MC/MCInstrInfo.h"
23#include "llvm/MC/MCSchedule.h"
31#include <cassert>
32#include <cstring>
33
34using namespace llvm;
35
36// LLVMCreateDisasm() creates a disassembler for the TripleName. Symbolic
37// disassembly is supported by passing a block of information in the DisInfo
38// parameter and specifying the TagType and callback functions as described in
39// the header llvm-c/Disassembler.h . The pointer to the block and the
40// functions can all be passed as NULL. If successful, this returns a
41// disassembler context. If not, it returns NULL.
42//
44LLVMCreateDisasmCPUFeatures(const char *TT, const char *CPU,
45 const char *Features, void *DisInfo, int TagType,
46 LLVMOpInfoCallback GetOpInfo,
47 LLVMSymbolLookupCallback SymbolLookUp) {
48 // Get the target.
49 std::string Error;
50 const Target *TheTarget = TargetRegistry::lookupTarget(TT, Error);
51 if (!TheTarget)
52 return nullptr;
53
54 std::unique_ptr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
55 if (!MRI)
56 return nullptr;
57
58 MCTargetOptions MCOptions;
59 // Get the assembler info needed to setup the MCContext.
60 std::unique_ptr<const MCAsmInfo> MAI(
61 TheTarget->createMCAsmInfo(*MRI, TT, MCOptions));
62 if (!MAI)
63 return nullptr;
64
65 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
66 if (!MII)
67 return nullptr;
68
69 std::unique_ptr<const MCSubtargetInfo> STI(
70 TheTarget->createMCSubtargetInfo(TT, CPU, Features));
71 if (!STI)
72 return nullptr;
73
74 // Set up the MCContext for creating symbols and MCExpr's.
75 std::unique_ptr<MCContext> Ctx(
76 new MCContext(Triple(TT), MAI.get(), MRI.get(), STI.get()));
77 if (!Ctx)
78 return nullptr;
79
80 // Set up disassembler.
81 std::unique_ptr<MCDisassembler> DisAsm(
82 TheTarget->createMCDisassembler(*STI, *Ctx));
83 if (!DisAsm)
84 return nullptr;
85
86 std::unique_ptr<MCRelocationInfo> RelInfo(
87 TheTarget->createMCRelocationInfo(TT, *Ctx));
88 if (!RelInfo)
89 return nullptr;
90
91 std::unique_ptr<MCSymbolizer> Symbolizer(TheTarget->createMCSymbolizer(
92 TT, GetOpInfo, SymbolLookUp, DisInfo, Ctx.get(), std::move(RelInfo)));
93 DisAsm->setSymbolizer(std::move(Symbolizer));
94
95 // Set up the instruction printer.
96 int AsmPrinterVariant = MAI->getAssemblerDialect();
97 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
98 Triple(TT), AsmPrinterVariant, *MAI, *MII, *MRI));
99 if (!IP)
100 return nullptr;
101
103 TT, DisInfo, TagType, GetOpInfo, SymbolLookUp, TheTarget, std::move(MAI),
104 std::move(MRI), std::move(STI), std::move(MII), std::move(Ctx),
105 std::move(DisAsm), std::move(IP));
106 if (!DC)
107 return nullptr;
108
109 DC->setCPU(CPU);
110 return DC;
111}
112
114LLVMCreateDisasmCPU(const char *TT, const char *CPU, void *DisInfo, int TagType,
115 LLVMOpInfoCallback GetOpInfo,
116 LLVMSymbolLookupCallback SymbolLookUp) {
117 return LLVMCreateDisasmCPUFeatures(TT, CPU, "", DisInfo, TagType, GetOpInfo,
118 SymbolLookUp);
119}
120
121LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo,
122 int TagType, LLVMOpInfoCallback GetOpInfo,
123 LLVMSymbolLookupCallback SymbolLookUp) {
124 return LLVMCreateDisasmCPUFeatures(TT, "", "", DisInfo, TagType, GetOpInfo,
125 SymbolLookUp);
126}
127
128//
129// LLVMDisasmDispose() disposes of the disassembler specified by the context.
130//
132 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
133 delete DC;
134}
135
136/// Emits the comments that are stored in \p DC comment stream.
137/// Each comment in the comment stream must end with a newline.
139 formatted_raw_ostream &FormattedOS) {
140 // Flush the stream before taking its content.
141 StringRef Comments = DC->CommentsToEmit.str();
142 // Get the default information for printing a comment.
143 const MCAsmInfo *MAI = DC->getAsmInfo();
144 StringRef CommentBegin = MAI->getCommentString();
145 unsigned CommentColumn = MAI->getCommentColumn();
146 bool IsFirst = true;
147 while (!Comments.empty()) {
148 if (!IsFirst)
149 FormattedOS << '\n';
150 // Emit a line of comments.
151 FormattedOS.PadToColumn(CommentColumn);
152 size_t Position = Comments.find('\n');
153 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
154 // Move after the newline character.
155 Comments = Comments.substr(Position+1);
156 IsFirst = false;
157 }
158 FormattedOS.flush();
159
160 // Tell the comment stream that the vector changed underneath it.
161 DC->CommentsToEmit.clear();
162}
163
164/// Emits latency information in DC->CommentStream for \p Inst, based
165/// on the information available in \p DC.
166static void emitLatency(LLVMDisasmContext *DC, const MCInst &Inst) {
167 const MCSubtargetInfo *STI = DC->getSubtargetInfo();
168 const MCInstrInfo *MCII = DC->getInstrInfo();
169 const MCSchedModel &SCModel = STI->getSchedModel();
170 int Latency = SCModel.computeInstrLatency(*STI, *MCII, Inst);
171
172 // Report only interesting latencies.
173 if (Latency < 2)
174 return;
175
176 DC->CommentStream << "Latency: " << Latency << '\n';
177}
178
179//
180// LLVMDisasmInstruction() disassembles a single instruction using the
181// disassembler context specified in the parameter DC. The bytes of the
182// instruction are specified in the parameter Bytes, and contains at least
183// BytesSize number of bytes. The instruction is at the address specified by
184// the PC parameter. If a valid instruction can be disassembled its string is
185// returned indirectly in OutString which whos size is specified in the
186// parameter OutStringSize. This function returns the number of bytes in the
187// instruction or zero if there was no valid instruction. If this function
188// returns zero the caller will have to pick how many bytes they want to step
189// over by printing a .byte, .long etc. to continue.
190//
192 uint64_t BytesSize, uint64_t PC, char *OutString,
193 size_t OutStringSize){
194 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
195 // Wrap the pointer to the Bytes, BytesSize and PC in a MemoryObject.
196 ArrayRef<uint8_t> Data(Bytes, BytesSize);
197
199 MCInst Inst;
200 const MCDisassembler *DisAsm = DC->getDisAsm();
201 MCInstPrinter *IP = DC->getIP();
203 SmallVector<char, 64> InsnStr;
205 S = DisAsm->getInstruction(Inst, Size, Data, PC, Annotations);
206 switch (S) {
209 // FIXME: Do something different for soft failure modes?
210 return 0;
211
213 StringRef AnnotationsStr = Annotations.str();
214
215 SmallVector<char, 64> InsnStr;
216 raw_svector_ostream OS(InsnStr);
217 formatted_raw_ostream FormattedOS(OS);
218
220 FormattedOS.enable_colors(true);
221 IP->setUseColor(true);
222 }
223
224 IP->printInst(&Inst, PC, AnnotationsStr, *DC->getSubtargetInfo(),
225 FormattedOS);
226
228 emitLatency(DC, Inst);
229
230 emitComments(DC, FormattedOS);
231
232 assert(OutStringSize != 0 && "Output buffer cannot be zero size");
233 size_t OutputSize = std::min(OutStringSize-1, InsnStr.size());
234 std::memcpy(OutString, InsnStr.data(), OutputSize);
235 OutString[OutputSize] = '\0'; // Terminate string.
236
237 return Size;
238 }
239 }
240 llvm_unreachable("Invalid DecodeStatus!");
241}
242
243//
244// LLVMSetDisasmOptions() sets the disassembler's options. It returns 1 if it
245// can set all the Options and 0 otherwise.
246//
249 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
250 MCInstPrinter *IP = DC->getIP();
251 IP->setUseMarkup(true);
253 Options &= ~LLVMDisassembler_Option_UseMarkup;
254 }
256 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
257 MCInstPrinter *IP = DC->getIP();
258 IP->setPrintImmHex(true);
260 Options &= ~LLVMDisassembler_Option_PrintImmHex;
261 }
263 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
264 // Try to set up the new instruction printer.
265 const MCAsmInfo *MAI = DC->getAsmInfo();
266 const MCInstrInfo *MII = DC->getInstrInfo();
267 const MCRegisterInfo *MRI = DC->getRegisterInfo();
268 int AsmPrinterVariant = MAI->getAssemblerDialect();
269 AsmPrinterVariant = AsmPrinterVariant == 0 ? 1 : 0;
271 Triple(DC->getTripleName()), AsmPrinterVariant, *MAI, *MII, *MRI);
272 if (IP) {
273 DC->setIP(IP);
275 Options &= ~LLVMDisassembler_Option_AsmPrinterVariant;
276 }
277 }
279 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
280 MCInstPrinter *IP = DC->getIP();
283 Options &= ~LLVMDisassembler_Option_SetInstrComments;
284 }
286 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
288 Options &= ~LLVMDisassembler_Option_PrintLatency;
289 }
291 LLVMDisasmContext *DC = static_cast<LLVMDisasmContext *>(DCR);
293 Options &= ~LLVMDisassembler_Option_Color;
294 }
295 return (Options == 0);
296}
unsigned const MachineRegisterInfo * MRI
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.
uint64_t Size
static LVOptions Options
Definition: LVOptions.cpp:25
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallVector class.
Annotations lets you mark points and ranges inside source code, for tests:
Definition: Annotations.h:53
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
const MCDisassembler * getDisAsm() const
Definition: Disassembler.h:109
void setCPU(const char *CPU)
Definition: Disassembler.h:119
void addOptions(uint64_t Options)
Definition: Disassembler.h:117
raw_svector_ostream CommentStream
Definition: Disassembler.h:83
void setIP(MCInstPrinter *NewIP)
Definition: Disassembler.h:115
const MCSubtargetInfo * getSubtargetInfo() const
Definition: Disassembler.h:113
const MCAsmInfo * getAsmInfo() const
Definition: Disassembler.h:110
uint64_t getOptions() const
Definition: Disassembler.h:116
const MCRegisterInfo * getRegisterInfo() const
Definition: Disassembler.h:112
SmallString< 128 > CommentsToEmit
Definition: Disassembler.h:82
MCInstPrinter * getIP()
Definition: Disassembler.h:114
const MCInstrInfo * getInstrInfo() const
Definition: Disassembler.h:111
const Target * getTarget() const
Definition: Disassembler.h:108
const std::string & getTripleName() const
Definition: Disassembler.h:101
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
unsigned getAssemblerDialect() const
Definition: MCAsmInfo.h:646
StringRef getCommentString() const
Definition: MCAsmInfo.h:615
unsigned getCommentColumn() const
Definition: MCAsmInfo.h:612
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...
Definition: MCInstPrinter.h:46
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:185
Interface to description of machine instruction set.
Definition: MCInstrInfo.h:26
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.
Definition: SmallString.h:254
size_t size() const
Definition: SmallVector.h:78
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:286
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:571
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:297
Target - Wrapper for Target specific information.
MCSubtargetInfo * createMCSubtargetInfo(StringRef TheTriple, StringRef CPU, StringRef Features) const
createMCSubtargetInfo - Create a MCSubtargetInfo implementation.
MCSymbolizer * createMCSymbolizer(StringRef TT, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp, void *DisInfo, MCContext *Ctx, std::unique_ptr< MCRelocationInfo > &&RelInfo) const
createMCSymbolizer - Create a target specific MCSymbolizer.
MCRelocationInfo * createMCRelocationInfo(StringRef TT, MCContext &Ctx) const
createMCRelocationInfo - Create a target specific MCRelocationInfo.
MCRegisterInfo * createMCRegInfo(StringRef TT) const
createMCRegInfo - Create a MCRegisterInfo implementation.
MCDisassembler * createMCDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx) const
MCAsmInfo * createMCAsmInfo(const MCRegisterInfo &MRI, StringRef TheTriple, const MCTargetOptions &Options) const
createMCAsmInfo - Create a MCAsmInfo implementation for the specified target triple.
MCInstPrinter * createMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) const
MCInstrInfo * createMCInstrInfo() const
createMCInstrInfo - Create a MCInstrInfo implementation.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
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)
Definition: raw_ostream.h:355
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
const char *(* LLVMSymbolLookupCallback)(void *DisInfo, uint64_t ReferenceValue, uint64_t *ReferenceType, uint64_t ReferencePC, const char **ReferenceName)
The type for the symbol lookup function.
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.
void LLVMDisasmDispose(LLVMDisasmContextRef DCR)
Dispose of a disassembler context.
#define LLVMDisassembler_Option_PrintImmHex
Definition: Disassembler.h:77
#define LLVMDisassembler_Option_UseMarkup
Definition: Disassembler.h:75
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.
#define LLVMDisassembler_Option_PrintLatency
Definition: Disassembler.h:83
#define LLVMDisassembler_Option_SetInstrComments
Definition: Disassembler.h:81
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_Color
Definition: Disassembler.h:85
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.
LLVMDisasmContextRef LLVMCreateDisasm(const char *TT, void *DisInfo, int TagType, LLVMOpInfoCallback GetOpInfo, LLVMSymbolLookupCallback SymbolLookUp)
Create a disassembler for the TripleName.
int LLVMSetDisasmOptions(LLVMDisasmContextRef DCR, uint64_t Options)
Set the disassembler's options.
#define LLVMDisassembler_Option_AsmPrinterVariant
Definition: Disassembler.h:79
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.
Definition: AddressRanges.h:18
Machine model for scheduling, bundling, and heuristics.
Definition: MCSchedule.h:256
static int computeInstrLatency(const MCSubtargetInfo &STI, const MCSchedClassDesc &SCDesc)
Returns the latency value for the scheduling class.
Definition: MCSchedule.cpp:42
static const Target * lookupTarget(StringRef Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.