LLVM 22.0.0git
MCInstPrinter.cpp
Go to the documentation of this file.
1//===- MCInstPrinter.cpp - Convert an MCInst to target assembly syntax ----===//
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
10#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/StringRef.h"
12#include "llvm/MC/MCAsmInfo.h"
13#include "llvm/MC/MCInst.h"
14#include "llvm/MC/MCInstrInfo.h"
18#include "llvm/Support/Format.h"
20#include <cinttypes>
21#include <cstdint>
22
23using namespace llvm;
24
26 static const char hex_rep[] = "0123456789abcdef";
27 bool First = true;
28 for (char i: bytes) {
29 if (First)
30 First = false;
31 else
32 OS << ' ';
33 OS << hex_rep[(i & 0xF0) >> 4];
34 OS << hex_rep[i & 0xF];
35 }
36}
37
39
40/// getOpcodeName - Return the name of the specified opcode enum (e.g.
41/// "MOV32ri") or empty if we can't resolve it.
43 return MII.getName(Opcode);
44}
45
47 llvm_unreachable("Target should implement this");
48}
49
51 if (!Annot.empty()) {
52 if (CommentStream) {
53 (*CommentStream) << Annot;
54 // By definition (see MCInstPrinter.h), CommentStream must end with
55 // a newline after each comment.
56 if (Annot.back() != '\n')
57 (*CommentStream) << '\n';
58 } else
59 OS << " " << MAI.getCommentString() << " " << Annot;
60 }
61}
62
63static bool matchAliasCondition(const MCInst &MI, const MCSubtargetInfo *STI,
64 const MCInstrInfo &MII,
65 const MCRegisterInfo &MRI, unsigned &OpIdx,
66 const AliasMatchingData &M,
67 const AliasPatternCond &C,
68 bool &OrPredicateResult) {
69 // Feature tests are special, they don't consume operands.
71 return STI->getFeatureBits().test(C.Value);
73 return !STI->getFeatureBits().test(C.Value);
74 // For feature tests where just one feature is required in a list, set the
75 // predicate result bit to whether the expression will return true, and only
76 // return the real result at the end of list marker.
77 if (C.Kind == AliasPatternCond::K_OrFeature) {
78 OrPredicateResult |= STI->getFeatureBits().test(C.Value);
79 return true;
80 }
82 OrPredicateResult |= !(STI->getFeatureBits().test(C.Value));
83 return true;
84 }
86 bool Res = OrPredicateResult;
87 OrPredicateResult = false;
88 return Res;
89 }
90
91 // Get and consume an operand.
92 const MCOperand &Opnd = MI.getOperand(OpIdx);
93 ++OpIdx;
94
95 // Check the specific condition for the operand.
96 switch (C.Kind) {
98 // Operand must be a specific immediate.
99 return Opnd.isImm() && Opnd.getImm() == int32_t(C.Value);
101 // Operand must be a specific register.
102 return Opnd.isReg() && Opnd.getReg() == C.Value;
104 // Operand must match the register of another operand.
105 return Opnd.isReg() && Opnd.getReg() == MI.getOperand(C.Value).getReg();
107 // Operand must be RegisterByHwMode. Value is RegClassByHwMode index.
108 unsigned HwModeId = STI->getHwMode(MCSubtargetInfo::HwMode_RegInfo);
109 int16_t RCID = MII.getRegClassByHwModeTable(HwModeId)[C.Value];
110 return Opnd.isReg() && MRI.getRegClass(RCID).contains(Opnd.getReg());
111 }
113 // Operand must be a register in this class. Value is a register class id.
114 return Opnd.isReg() && MRI.getRegClass(C.Value).contains(Opnd.getReg());
116 // Operand must match some custom criteria.
117 return M.ValidateMCOperand(Opnd, *STI, C.Value);
119 // Operand can be anything.
120 return true;
126 llvm_unreachable("handled earlier");
127 }
128 llvm_unreachable("invalid kind");
129}
130
132 const MCSubtargetInfo *STI,
133 const AliasMatchingData &M) {
134 // Binary search by opcode. Return false if there are no aliases for this
135 // opcode.
136 auto It = lower_bound(M.OpToPatterns, MI->getOpcode(),
137 [](const PatternsForOpcode &L, unsigned Opcode) {
138 return L.Opcode < Opcode;
139 });
140 if (It == M.OpToPatterns.end() || It->Opcode != MI->getOpcode())
141 return nullptr;
142
143 // Try all patterns for this opcode.
144 uint32_t AsmStrOffset = ~0U;
145 ArrayRef<AliasPattern> Patterns =
146 M.Patterns.slice(It->PatternStart, It->NumPatterns);
147 for (const AliasPattern &P : Patterns) {
148 // Check operand count first.
149 if (MI->getNumOperands() != P.NumOperands)
150 return nullptr;
151
152 // Test all conditions for this pattern.
154 M.PatternConds.slice(P.AliasCondStart, P.NumConds);
155 unsigned OpIdx = 0;
156 bool OrPredicateResult = false;
157 if (llvm::all_of(Conds, [&](const AliasPatternCond &C) {
158 return matchAliasCondition(*MI, STI, MII, MRI, OpIdx, M, C,
159 OrPredicateResult);
160 })) {
161 // If all conditions matched, use this asm string.
162 AsmStrOffset = P.AsmStrOffset;
163 break;
164 }
165 }
166
167 // If no alias matched, don't print an alias.
168 if (AsmStrOffset == ~0U)
169 return nullptr;
170
171 // Go to offset AsmStrOffset and use the null terminated string there. The
172 // offset should point to the beginning of an alias string, so it should
173 // either be zero or be preceded by a null byte.
174 assert(AsmStrOffset < M.AsmStrings.size() &&
175 (AsmStrOffset == 0 || M.AsmStrings[AsmStrOffset - 1] == '\0') &&
176 "bad asm string offset");
177 return M.AsmStrings.data() + AsmStrOffset;
178}
179
180// For asm-style hex (e.g. 0ffh) the first digit always has to be a number.
182{
183 while (Value)
184 {
185 uint64_t digit = (Value >> 60) & 0xf;
186 if (digit != 0)
187 return (digit >= 0xa);
188 Value <<= 4;
189 }
190 return false;
191}
192
194 return format("%" PRId64, Value);
195}
196
198 switch (PrintHexStyle) {
199 case HexStyle::C:
200 if (Value < 0) {
201 if (Value == std::numeric_limits<int64_t>::min())
202 return format<int64_t>("-0x8000000000000000", Value);
203 return format("-0x%" PRIx64, -Value);
204 }
205 return format("0x%" PRIx64, Value);
206 case HexStyle::Asm:
207 if (Value < 0) {
208 if (Value == std::numeric_limits<int64_t>::min())
209 return format<int64_t>("-8000000000000000h", Value);
211 return format("-0%" PRIx64 "h", -Value);
212 return format("-%" PRIx64 "h", -Value);
213 }
215 return format("0%" PRIx64 "h", Value);
216 return format("%" PRIx64 "h", Value);
217 }
218 llvm_unreachable("unsupported print style");
219}
220
222 switch(PrintHexStyle) {
223 case HexStyle::C:
224 return format("0x%" PRIx64, Value);
225 case HexStyle::Asm:
227 return format("0%" PRIx64 "h", Value);
228 else
229 return format("%" PRIx64 "h", Value);
230 }
231 llvm_unreachable("unsupported print style");
232}
233
237
239 Markup M, bool EnableMarkup,
240 bool EnableColor)
241 : IP(IP), OS(OS), EnableMarkup(EnableMarkup), EnableColor(EnableColor) {
242 if (EnableColor) {
244 switch (M) {
246 Color = raw_ostream::RED;
247 break;
248 case Markup::Register:
249 Color = raw_ostream::CYAN;
250 break;
251 case Markup::Target:
252 Color = raw_ostream::YELLOW;
253 break;
254 case Markup::Memory:
255 Color = raw_ostream::GREEN;
256 break;
257 }
258 IP.ColorStack.push_back(Color);
259 OS.changeColor(Color);
260 }
261
262 if (EnableMarkup) {
263 switch (M) {
265 OS << "<imm:";
266 break;
267 case Markup::Register:
268 OS << "<reg:";
269 break;
270 case Markup::Target:
271 OS << "<target:";
272 break;
273 case Markup::Memory:
274 OS << "<mem:";
275 break;
276 }
277 }
278}
279
281 if (EnableMarkup)
282 OS << '>';
283 if (!EnableColor)
284 return;
285 IP.ColorStack.pop_back();
286 OS << IP.ColorStack.back();
287}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
IRTranslator LLVM IR MI
static bool needsLeadingZero(uint64_t Value)
static bool matchAliasCondition(const MCInst &MI, const MCSubtargetInfo *STI, const MCInstrInfo &MII, const MCRegisterInfo &MRI, unsigned &OpIdx, const AliasMatchingData &M, const AliasPatternCond &C, bool &OrPredicateResult)
modulo schedule test
MachineInstr unsigned OpIdx
#define P(N)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:186
constexpr bool test(unsigned I) const
LLVM_CTOR_NODISCARD LLVM_ABI WithMarkup(MCInstPrinter &IP, raw_ostream &OS, Markup M, bool EnableMarkup, bool EnableColor)
WithMarkup markup(raw_ostream &OS, Markup M)
format_object< int64_t > formatHex(int64_t Value) const
bool getUseColor() const
const MCInstrInfo & MII
raw_ostream * CommentStream
A stream that comments can be emitted to if desired.
virtual ~MCInstPrinter()
StringRef getOpcodeName(unsigned Opcode) const
Return the name of the specified opcode enum (e.g.
format_object< int64_t > formatDec(int64_t Value) const
Utility functions to print decimal/hexadecimal values.
const MCRegisterInfo & MRI
void printAnnotation(raw_ostream &OS, StringRef Annot)
Utility function for printing annotations.
const MCAsmInfo & MAI
bool getUseMarkup() const
virtual void printRegName(raw_ostream &OS, MCRegister Reg)
Print the assembler register name.
const char * matchAliasPatterns(const MCInst *MI, const MCSubtargetInfo *STI, const AliasMatchingData &M)
Helper for matching MCInsts to alias patterns when printing instructions.
MCInstPrinter(const MCAsmInfo &mai, const MCInstrInfo &mii, const MCRegisterInfo &mri)
HexStyle::Style PrintHexStyle
Which style to use for printing hexadecimal values.
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
const int16_t * getRegClassByHwModeTable(unsigned ModeId) const
Definition MCInstrInfo.h:71
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:40
int64_t getImm() const
Definition MCInst.h:84
bool isImm() const
Definition MCInst.h:66
bool isReg() const
Definition MCInst.h:65
MCRegister getReg() const
Returns the register number.
Definition MCInst.h:73
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
Generic base class for all target subtargets.
const FeatureBitset & getFeatureBits() const
virtual unsigned getHwMode(enum HwModeType type=HwMode_Default) const
HwMode ID corresponding to the 'type' parameter is retrieved from the HwMode bit set of the current s...
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
LLVM Value Representation.
Definition Value.h:75
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
static constexpr Colors GREEN
static constexpr Colors RED
static constexpr Colors YELLOW
static constexpr Colors CYAN
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1737
LLVM_ABI void dumpBytes(ArrayRef< uint8_t > Bytes, raw_ostream &OS)
Convert ‘Bytes’ to a hex string and output to ‘OS’.
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:129
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2006
Tablegenerated data structures needed to match alias patterns.
Data for each alias pattern.
Map from opcode to pattern list by binary search.