LLVM 24.0.0git
LoongArchAsmPrinter.cpp
Go to the documentation of this file.
1//===- LoongArchAsmPrinter.cpp - LoongArch LLVM Assembly Printer -*- C++ -*--=//
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// This file contains a printer that converts from our internal representation
10// of machine-dependent LLVM code to GAS-format LoongArch assembly language.
11//
12//===----------------------------------------------------------------------===//
13
14#include "LoongArchAsmPrinter.h"
15#include "LoongArch.h"
25#include "llvm/IR/Module.h"
26#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCContext.h"
32
33using namespace llvm;
34
35#define DEBUG_TYPE "loongarch-asm-printer"
36
38 "loongarch-annotate-tablejump", cl::Hidden,
40 "Annotate table jump instruction to correlate it with the jump table."),
41 cl::init(false));
42
43// Simple pseudo-instructions have their lowering (with expansion to real
44// instructions) auto-generated.
45#include "LoongArchGenMCPseudoLowering.inc"
46
47LoongArchTargetStreamer &LoongArchAsmPrinter::getTargetStreamer() const {
48 return static_cast<LoongArchTargetStreamer &>(
49 *OutStreamer->getTargetStreamer());
50}
51
53 StringRef ABIName = M.getTargetABIFromMD();
54 if (!ABIName.empty()) {
55 getTargetStreamer().setTargetABI(LoongArchABI::computeTargetABI(
56 M.getTargetTriple(), TM.getMCSubtargetInfo().getFeatureBits(),
57 ABIName));
58 }
59}
60
62 LoongArch_MC::verifyInstructionPredicates(
63 MI->getOpcode(), getSubtargetInfo().getFeatureBits());
64
65 // Do any auto-generated pseudo lowerings.
66 if (MCInst OutInst; lowerPseudoInstExpansion(MI, OutInst)) {
67 EmitToStreamer(*OutStreamer, OutInst);
68 return;
69 }
70
71 switch (MI->getOpcode()) {
72 case TargetOpcode::STATEPOINT:
74 return;
75 case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
77 return;
78 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
80 return;
81 case TargetOpcode::PATCHABLE_TAIL_CALL:
83 return;
84 }
85
86 MCInst TmpInst;
87 if (!lowerLoongArchMachineInstrToMCInst(MI, TmpInst, *this))
88 EmitToStreamer(*OutStreamer, TmpInst);
89}
90
92 const char *ExtraCode,
93 raw_ostream &OS) {
94 // First try the generic code, which knows about modifiers like 'c' and 'n'.
95 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
96 return false;
97
98 const MachineOperand &MO = MI->getOperand(OpNo);
99 if (ExtraCode && ExtraCode[0]) {
100 if (ExtraCode[1] != 0)
101 return true; // Unknown modifier.
102
103 switch (ExtraCode[0]) {
104 default:
105 return true; // Unknown modifier.
106 case 'z': // Print $zero register if zero, regular printing otherwise.
107 if (MO.isImm() && MO.getImm() == 0) {
108 OS << '$' << LoongArchInstPrinter::getRegisterName(LoongArch::R0);
109 return false;
110 }
111 break;
112 case 'u': // Print LASX registers.
113 case 'w': // Print LSX registers.
114 {
115 // If the operand is an LASX, LSX or floating point register, print the
116 // name of LASX or LSX register with the same index in that register
117 // class.
118 unsigned RegID = MO.getReg().id(), FirstReg;
119 if (RegID >= LoongArch::XR0 && RegID <= LoongArch::XR31)
120 FirstReg = LoongArch::XR0;
121 else if (RegID >= LoongArch::VR0 && RegID <= LoongArch::VR31)
122 FirstReg = LoongArch::VR0;
123 else if (RegID >= LoongArch::F0_64 && RegID <= LoongArch::F31_64)
124 FirstReg = LoongArch::F0_64;
125 else if (RegID >= LoongArch::F0 && RegID <= LoongArch::F31)
126 FirstReg = LoongArch::F0;
127 else
128 return true;
129 OS << '$'
131 RegID - FirstReg +
132 (ExtraCode[0] == 'u' ? LoongArch::XR0 : LoongArch::VR0));
133 return false;
134 }
135 // TODO: handle other extra codes if any.
136 }
137 }
138
139 switch (MO.getType()) {
141 OS << MO.getImm();
142 return false;
145 return false;
147 PrintSymbolOperand(MO, OS);
148 return false;
149 default:
150 llvm_unreachable("not implemented");
151 }
152
153 return true;
154}
155
157 unsigned OpNo,
158 const char *ExtraCode,
159 raw_ostream &OS) {
160 // TODO: handle extra code.
161 if (ExtraCode)
162 return true;
163
164 // We only support memory operands like "Base + Offset", where base must be a
165 // register, and offset can be a register or an immediate value.
166 const MachineOperand &BaseMO = MI->getOperand(OpNo);
167 // Base address must be a register.
168 if (!BaseMO.isReg())
169 return true;
170 // Print the base address register.
171 OS << "$" << LoongArchInstPrinter::getRegisterName(BaseMO.getReg());
172 // Print the offset operand.
173 const MachineOperand &OffsetMO = MI->getOperand(OpNo + 1);
174 MCOperand MCO;
175 if (!lowerOperand(OffsetMO, MCO))
176 return true;
177 if (OffsetMO.isReg())
178 OS << ", $" << LoongArchInstPrinter::getRegisterName(OffsetMO.getReg());
179 else if (OffsetMO.isImm())
180 OS << ", " << OffsetMO.getImm();
181 else if (OffsetMO.isGlobal() || OffsetMO.isBlockAddress() ||
182 OffsetMO.isMCSymbol() || OffsetMO.isCPI()) {
183 OS << ", ";
184 MAI.printExpr(OS, *MCO.getExpr());
185 } else
186 return true;
187
188 return false;
189}
190
192 StatepointOpers SOpers(&MI);
193 if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
194 assert(PatchBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
195 emitNops(PatchBytes / 4);
196 } else {
197 // Lower call target and choose correct opcode.
198 const MachineOperand &CallTarget = SOpers.getCallTarget();
199 MCOperand CallTargetMCOp;
200 switch (CallTarget.getType()) {
203 lowerOperand(CallTarget, CallTargetMCOp);
205 MCInstBuilder(LoongArch::BL).addOperand(CallTargetMCOp));
206 break;
208 CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
210 MCInstBuilder(LoongArch::BL).addOperand(CallTargetMCOp));
211 break;
213 CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
214 EmitToStreamer(*OutStreamer, MCInstBuilder(LoongArch::JIRL)
215 .addReg(LoongArch::R1)
216 .addOperand(CallTargetMCOp)
217 .addImm(0));
218 break;
219 default:
220 llvm_unreachable("Unsupported operand type in statepoint call target");
221 break;
222 }
223 }
224
225 auto &Ctx = OutStreamer->getContext();
226 MCSymbol *MILabel = Ctx.createTempSymbol();
227 OutStreamer->emitLabel(MILabel);
228 SM.recordStatepoint(*MILabel, MI);
229}
230
232 const MachineInstr &MI) {
233 const Function &F = MF->getFunction();
234 if (F.hasFnAttribute("patchable-function-entry")) {
235 unsigned Num = F.getFnAttributeAsParsedInteger("patchable-function-entry");
236 emitNops(Num);
237 return;
238 }
239
241}
242
246
250
252 // For loongarch64 we want to emit the following pattern:
253 //
254 // .Lxray_sled_beginN:
255 // B .Lxray_sled_endN
256 // 11 NOPs (44 bytes)
257 // .Lxray_sled_endN:
258 //
259 // We need the extra bytes because at runtime they may be used for the
260 // actual pattern defined at compiler-rt/lib/xray/xray_loongarch64.cpp.
261 // The count here should be adjusted accordingly if the implementation
262 // changes.
263 const int8_t NoopsInSledCount = 11;
264 OutStreamer->emitCodeAlignment(Align(4), getSubtargetInfo());
265 MCSymbol *BeginOfSled = OutContext.createTempSymbol("xray_sled_begin");
266 MCSymbol *EndOfSled = OutContext.createTempSymbol("xray_sled_end");
267 OutStreamer->emitLabel(BeginOfSled);
269 MCInstBuilder(LoongArch::B)
270 .addExpr(MCSymbolRefExpr::create(EndOfSled, OutContext)));
271 emitNops(NoopsInSledCount);
272 OutStreamer->emitLabel(EndOfSled);
273 recordSled(BeginOfSled, MI, Kind, 2);
274}
275
278
280 return;
281
282 assert(TM.getTargetTriple().isOSBinFormatELF());
283
284 auto *LAFI = MF->getInfo<LoongArchMachineFunctionInfo>();
285 unsigned EntrySize = LAFI->getJumpInfoSize();
286 auto JTI = MF->getJumpTableInfo();
287
288 if (!JTI || 0 == EntrySize)
289 return;
290
291 unsigned Size = getDataLayout().getPointerSize();
292 const auto &JT = JTI->getJumpTables();
293
294 // Emit an additional section to store the correlation info as pairs of
295 // addresses, each pair contains the address of a jump instruction (jr) and
296 // the address of the jump table.
297 OutStreamer->switchSection(MMI->getContext().getELFSection(
298 ".discard.tablejump_annotate", ELF::SHT_PROGBITS, 0));
299
300 for (unsigned Idx = 0; Idx < EntrySize; ++Idx) {
301 int JTIIdx = LAFI->getJumpInfoJTIIndex(Idx);
302 if (JT[JTIIdx].MBBs.empty())
303 continue;
304 OutStreamer->emitValue(
305 MCSymbolRefExpr::create(LAFI->getJumpInfoJrMI(Idx)->getPreInstrSymbol(),
306 OutContext),
307 Size);
308 OutStreamer->emitValue(
310 }
311}
312
313// Emit .dtprelword or .dtpreldword directive
314// and value for debug thread local expression.
316 unsigned Size) const {
317 if (auto *Expr = dyn_cast<MCSpecifierExpr>(Value)) {
318 if (Expr->getSpecifier() == LoongArchMCExpr::VK_DTPREL) {
319 switch (Size) {
320 case 4:
321 getTargetStreamer().emitDTPRel32Value(Expr->getSubExpr());
322 break;
323 case 8:
324 getTargetStreamer().emitDTPRel64Value(Expr->getSubExpr());
325 break;
326 default:
327 llvm_unreachable("Unexpected size of expression value.");
328 }
329 return;
330 }
331 }
333}
334
337 // Emit the XRay table for this function.
339 return true;
340}
341
343
344INITIALIZE_PASS(LoongArchAsmPrinter, "loongarch-asm-printer",
345 "LoongArch Assembly Printer", false, false)
346
347// Force static initialization.
349LLVMInitializeLoongArchAsmPrinter() {
352}
353
362
374
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
#define LLVM_ABI
Definition Compiler.h:211
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
cl::opt< bool > LArchAnnotateTableJump("loongarch-annotate-tablejump", cl::Hidden, cl::desc("Annotate table jump instruction to correlate it with the jump table."), cl::init(false))
#define F(x, y, z)
Definition MD5.cpp:54
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:93
void emitNops(unsigned N)
Emit N NOP instructions.
virtual void emitDebugValue(const MCExpr *Value, unsigned Size) const
Emit the directive and value for debug thread local expression.
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
TargetMachine & TM
Target machine description.
Definition AsmPrinter.h:96
void emitXRayTable()
Emit a table with all XRay instrumentation points.
virtual void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS)
Print the MachineOperand as a symbol.
MachineFunction * MF
The current machine function.
Definition AsmPrinter.h:111
virtual void emitJumpTableInfo()
Print assembly representations of the jump tables used by the current function to the current output ...
MCSymbol * GetJTISymbol(unsigned JTID, bool isLinkerPrivate=false) const
Return the symbol for the specified jump table entry.
void recordSled(MCSymbol *Sled, const MachineInstr &MI, SledKind Kind, uint8_t Version=0)
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
MachineModuleInfo * MMI
This is a pointer to the current MachineModuleInfo.
Definition AsmPrinter.h:114
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition AsmPrinter.h:103
bool doFinalization(Module &M) override
Shut down the asmprinter.
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
Definition AsmPrinter.h:478
std::unique_ptr< MCStreamer > OutStreamer
This is the MCStreamer object for the file we are generating.
Definition AsmPrinter.h:108
const MCAsmInfo & MAI
Target Asm Printer information.
Definition AsmPrinter.h:99
const DataLayout & getDataLayout() const
Return information about data layout.
const MCSubtargetInfo & getSubtargetInfo() const
Return information about subtarget.
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
LLVM_ABI unsigned getPointerSize(unsigned AS=0) const
The pointer representation size in bytes, rounded up to a whole number of bytes.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MFAM)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MFAM)
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
void emitSled(const MachineInstr &MI, SledKind Kind)
void LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr &MI)
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
void emitDebugValue(const MCExpr *Value, unsigned Size) const override
Emit the directive and value for debug thread local expression.
void emitStartOfAsmFile(Module &M) override
This virtual method can be overridden by targets that want to emit something at the start of their fi...
void LowerSTATEPOINT(const MachineInstr &MI)
void LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI)
void emitInstruction(const MachineInstr *MI) override
Targets should implement this to emit instructions.
bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant as...
bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp) const
bool lowerPseudoInstExpansion(const MachineInstr *MI, MCInst &Inst)
void emitJumpTableInfo() override
Print assembly representations of the jump tables used by the current function to the current output ...
bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, const char *ExtraCode, raw_ostream &OS) override
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant.
void LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI)
static const char * getRegisterName(MCRegister Reg)
LoongArchMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private Lo...
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:31
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
Instances of this class represent operands of the MCInst class.
Definition MCInst.h:39
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:137
static MCOperand createImm(int64_t Val)
Definition MCInst.h:144
const MCExpr * getExpr() const
Definition MCInst.h:117
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:210
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isCPI() const
isCPI - Tests if this is a MO_ConstantPoolIndex operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
bool isBlockAddress() const
isBlockAddress - Tests if this is a MO_BlockAddress operand.
Register getReg() const
getReg - Returns the register number.
@ MO_Immediate
Immediate operand.
@ MO_GlobalAddress
Address of a global value.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
constexpr unsigned id() const
Definition Register.h:100
MI-level Statepoint operands.
Definition StackMaps.h:159
uint32_t getNumPatchBytes() const
Return the number of patchable bytes the given statepoint should emit.
Definition StackMaps.h:208
const MachineOperand & getCallTarget() const
Return the target of the underlying call.
Definition StackMaps.h:213
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
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
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ SHT_PROGBITS
Definition ELF.h:996
ABI computeTargetABI(const Triple &TT, const FeatureBitset &FeatureBits, StringRef ABIName)
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
Target & getTheLoongArch64Target()
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool lowerLoongArchMachineInstrToMCInst(const MachineInstr *MI, MCInst &OutMI, AsmPrinter &AP)
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI void setupModuleAsmPrinter(Module &M, ModuleAnalysisManager &MAM, AsmPrinter &AsmPrinter)
Target & getTheLoongArch32Target()
LLVM_ABI void setupMachineFunctionAsmPrinter(MachineFunctionAnalysisManager &MFAM, MachineFunction &MF, AsmPrinter &AsmPrinter)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...