45#define DEBUG_TYPE "asm-printer"
48 "Number of RISC-V Compressed instructions emitted");
60 std::unique_ptr<MCStreamer> Streamer)
84 bool emitPseudoExpansionLowering(
MCStreamer &OutStreamer,
87 typedef std::tuple<unsigned, uint32_t> HwasanMemaccessTuple;
88 std::map<HwasanMemaccessTuple, MCSymbol *> HwasanMemaccessSymbols;
91 void EmitHwasanMemaccessSymbols(
Module &M);
100 bool emitDirectiveOptionArch();
103 void emitAttributes();
113 unsigned NOPBytes = STI->getFeatureBits()[RISCV::FeatureStdExtC] ? 2 : 4;
117 MCSymbol *MILabel = Ctx.createTempSymbol();
121 assert(NumNOPBytes % NOPBytes == 0 &&
122 "Invalid number of NOP bytes requested!");
128 while (NumNOPBytes > 0) {
129 if (MII ==
MBB.
end() || MII->isCall() ||
130 MII->getOpcode() == RISCV::DBG_VALUE ||
131 MII->getOpcode() == TargetOpcode::PATCHPOINT ||
132 MII->getOpcode() == TargetOpcode::STACKMAP)
139 emitNops(NumNOPBytes / NOPBytes);
146 unsigned NOPBytes = STI->getFeatureBits()[RISCV::FeatureStdExtC] ? 2 : 4;
149 MCSymbol *MILabel = Ctx.createTempSymbol();
155 unsigned EncodedBytes = 0;
158 unsigned NumBytes = Opers.getNumPatchBytes();
159 assert(NumBytes >= EncodedBytes &&
160 "Patchpoint can't request size less than the length of a call.");
161 assert((NumBytes - EncodedBytes) % NOPBytes == 0 &&
162 "Invalid number of NOP bytes requested!");
163 emitNops((NumBytes - EncodedBytes) / NOPBytes);
168 unsigned NOPBytes = STI->getFeatureBits()[RISCV::FeatureStdExtC] ? 2 : 4;
171 if (
unsigned PatchBytes = SOpers.getNumPatchBytes()) {
172 assert(PatchBytes % NOPBytes == 0 &&
173 "Invalid number of NOP bytes requested!");
174 emitNops(PatchBytes / NOPBytes);
178 MCSymbol *MILabel = Ctx.createTempSymbol();
187 ++RISCVNumInstrsCompressed;
193#include "RISCVGenMCPseudoLowering.inc"
198 if (!STI->hasStdExtZihintntl())
201 if (
MI->memoperands_empty())
208 unsigned NontemporalMode = 0;
210 NontemporalMode += 0b1;
212 NontemporalMode += 0b10;
215 if (STI->hasStdExtCOrZca() && STI->enableRVCHintInstrs())
224 EmitToStreamer(*OutStreamer, Hint);
228 RISCV_MC::verifyInstructionPredicates(
MI->getOpcode(),
229 getSubtargetInfo().getFeatureBits());
234 if (emitPseudoExpansionLowering(*OutStreamer,
MI))
238 switch (
MI->getOpcode()) {
239 case RISCV::HWASAN_CHECK_MEMACCESS_SHORTGRANULES:
240 LowerHWASAN_CHECK_MEMACCESS(*
MI);
242 case RISCV::KCFI_CHECK:
243 LowerKCFI_CHECK(*
MI);
245 case RISCV::PseudoRVVInitUndefM1:
246 case RISCV::PseudoRVVInitUndefM2:
247 case RISCV::PseudoRVVInitUndefM4:
248 case RISCV::PseudoRVVInitUndefM8:
250 case TargetOpcode::STACKMAP:
251 return LowerSTACKMAP(*OutStreamer, SM, *
MI);
252 case TargetOpcode::PATCHPOINT:
253 return LowerPATCHPOINT(*OutStreamer, SM, *
MI);
254 case TargetOpcode::STATEPOINT:
255 return LowerSTATEPOINT(*OutStreamer, SM, *
MI);
259 if (!lowerToMCInst(
MI, OutInst))
260 EmitToStreamer(*OutStreamer, OutInst);
263bool RISCVAsmPrinter::PrintAsmOperand(
const MachineInstr *
MI,
unsigned OpNo,
270 if (ExtraCode && ExtraCode[0]) {
271 if (ExtraCode[1] != 0)
274 switch (ExtraCode[0]) {
298 PrintSymbolOperand(MO,
OS);
312bool RISCVAsmPrinter::PrintAsmMemoryOperand(
const MachineInstr *
MI,
314 const char *ExtraCode,
320 assert(
MI->getNumOperands() > OpNo + 1 &&
"Expected additional operand");
324 if (!AddrReg.
isReg())
330 if (!lowerOperand(
Offset, MCO))
341bool RISCVAsmPrinter::emitDirectiveOptionArch() {
347 if (STI->hasFeature(Feature.Value) == MCSTI.
hasFeature(Feature.Value))
353 auto Delta = STI->hasFeature(Feature.Value) ? RISCVOptionArchArgType::Plus
354 : RISCVOptionArchArgType::Minus;
357 if (!NeedEmitStdOptionArgs.
empty()) {
371 bool EmittedOptionArch = emitDirectiveOptionArch();
373 SetupMachineFunction(MF);
376 if (EmittedOptionArch)
377 RTS.emitDirectiveOptionPop();
381void RISCVAsmPrinter::emitStartOfAsmFile(
Module &M) {
384 if (
const MDString *ModuleTargetABI =
385 dyn_cast_or_null<MDString>(
M.getModuleFlag(
"target-abi")))
387 if (
TM.getTargetTriple().isOSBinFormatELF())
391void RISCVAsmPrinter::emitEndOfAsmFile(
Module &M) {
395 if (
TM.getTargetTriple().isOSBinFormatELF())
397 EmitHwasanMemaccessSymbols(M);
400void RISCVAsmPrinter::emitAttributes() {
409void RISCVAsmPrinter::emitFunctionEntryLabel() {
411 if (RMFI->isVectorCall()) {
425void RISCVAsmPrinter::LowerHWASAN_CHECK_MEMACCESS(
const MachineInstr &
MI) {
427 uint32_t AccessInfo =
MI.getOperand(1).getImm();
429 HwasanMemaccessSymbols[HwasanMemaccessTuple(Reg, AccessInfo)];
432 if (!
TM.getTargetTriple().isOSBinFormatELF())
435 std::string SymName =
"__hwasan_check_x" + utostr(Reg - RISCV::X0) +
"_" +
436 utostr(AccessInfo) +
"_short";
437 Sym = OutContext.getOrCreateSymbol(SymName);
442 EmitToStreamer(*OutStreamer,
MCInstBuilder(RISCV::PseudoCALL).addExpr(Expr));
447 assert(std::next(
MI.getIterator())->isCall() &&
448 "KCFI_CHECK not followed by a call instruction");
449 assert(std::next(
MI.getIterator())->getOperand(0).getReg() == AddrReg &&
450 "KCFI_CHECK call target doesn't match call operand");
457 unsigned ScratchRegs[] = {RISCV::X6, RISCV::X7};
458 unsigned NextReg = RISCV::X28;
459 auto isRegAvailable = [&](
unsigned Reg) {
460 return Reg != AddrReg && !STI->isRegisterReservedByUser(Reg);
462 for (
auto &Reg : ScratchRegs) {
463 if (isRegAvailable(Reg))
465 while (!isRegAvailable(NextReg))
468 if (Reg > RISCV::X31)
472 if (AddrReg == RISCV::X0) {
476 .addReg(ScratchRegs[0])
482 int NopSize = STI->hasStdExtCOrZca() ? 2 : 4;
483 int64_t PrefixNops = 0;
486 .getFnAttribute(
"patchable-function-prefix")
488 .getAsInteger(10, PrefixNops);
492 .addReg(ScratchRegs[0])
494 .addImm(-(PrefixNops * NopSize + 4)));
498 const int64_t
Type =
MI.getOperand(1).getImm();
499 const int64_t Hi20 = ((
Type + 0x800) >> 12) & 0xFFFFF;
500 const int64_t Lo12 = SignExtend64<12>(
Type);
504 MCInstBuilder(RISCV::LUI).addReg(ScratchRegs[1]).addImm(Hi20));
506 if (Lo12 || Hi20 == 0) {
507 EmitToStreamer(*OutStreamer,
518 EmitToStreamer(*OutStreamer,
520 .addReg(ScratchRegs[0])
521 .addReg(ScratchRegs[1])
527 emitKCFITrapEntry(*
MI.getMF(),
Trap);
531void RISCVAsmPrinter::EmitHwasanMemaccessSymbols(
Module &M) {
532 if (HwasanMemaccessSymbols.empty())
535 assert(
TM.getTargetTriple().isOSBinFormatELF());
542 OutContext.getOrCreateSymbol(
"__hwasan_tag_mismatch_v2");
554 for (
auto &
P : HwasanMemaccessSymbols) {
555 unsigned Reg = std::get<0>(
P.first);
556 uint32_t AccessInfo = std::get<1>(
P.first);
593 MCSymbol *HandleMismatchOrPartialSym = OutContext.createTempSymbol();
602 MCSymbol *ReturnSym = OutContext.createTempSymbol();
609 OutStreamer->
emitLabel(HandleMismatchOrPartialSym);
616 MCSymbol *HandleMismatchSym = OutContext.createTempSymbol();
654 OutStreamer->
emitLabel(HandleMismatchSym);
720 if (Reg != RISCV::X10)
846 RISCVVPseudosTable::getPseudoInfo(
MI->getOpcode());
853 assert(
MBB &&
"MI expected to be in a basic block");
855 assert(MF &&
"MBB expected to be in a machine function");
860 assert(
TRI &&
"TargetRegisterInfo expected");
864 unsigned NumOps =
MI->getNumExplicitOperands();
878 for (
unsigned OpNo = 0; OpNo != NumOps; ++OpNo) {
881 if (hasVLOutput && OpNo == 1)
885 if (OpNo ==
MI->getNumExplicitDefs() && MO.
isReg() && MO.
isTied()) {
887 "Expected tied to first def.");
904 if (RISCV::VRM2RegClass.
contains(Reg) ||
905 RISCV::VRM4RegClass.
contains(Reg) ||
906 RISCV::VRM8RegClass.
contains(Reg)) {
907 Reg =
TRI->getSubReg(Reg, RISCV::sub_vrm1_0);
908 assert(Reg &&
"Subregister does not exist");
909 }
else if (RISCV::FPR16RegClass.
contains(Reg)) {
911 TRI->getMatchingSuperReg(Reg, RISCV::sub_16, &RISCV::FPR32RegClass);
912 assert(Reg &&
"Subregister does not exist");
913 }
else if (RISCV::FPR64RegClass.
contains(Reg)) {
914 Reg =
TRI->getSubReg(Reg, RISCV::sub_32);
915 assert(Reg &&
"Superregister does not exist");
916 }
else if (RISCV::VRN2M1RegClass.
contains(Reg) ||
917 RISCV::VRN2M2RegClass.
contains(Reg) ||
918 RISCV::VRN2M4RegClass.
contains(Reg) ||
919 RISCV::VRN3M1RegClass.
contains(Reg) ||
920 RISCV::VRN3M2RegClass.
contains(Reg) ||
921 RISCV::VRN4M1RegClass.
contains(Reg) ||
922 RISCV::VRN4M2RegClass.
contains(Reg) ||
923 RISCV::VRN5M1RegClass.
contains(Reg) ||
924 RISCV::VRN6M1RegClass.
contains(Reg) ||
925 RISCV::VRN7M1RegClass.
contains(Reg) ||
926 RISCV::VRN8M1RegClass.
contains(Reg)) {
927 Reg =
TRI->getSubReg(Reg, RISCV::sub_vrm1_0);
928 assert(Reg &&
"Subregister does not exist");
946 RISCV::VMV0RegClassID &&
947 "Expected only mask operand to be missing");
963 if (lowerOperand(MO, MCOp))
968 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
969 const Function &
F =
MI->getParent()->getParent()->getFunction();
970 if (
F.hasFnAttribute(
"patchable-function-entry")) {
972 if (
F.getFnAttribute(
"patchable-function-entry")
974 .getAsInteger(10, Num))
This file implements a class to represent arbitrary precision integral constant values and operations...
#define LLVM_EXTERNAL_VISIBILITY
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
const HexagonInstrInfo * TII
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
unsigned const TargetRegisterInfo * TRI
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
const char LLVMTargetMachineRef TM
LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVAsmPrinter()
static MCOperand lowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym, const AsmPrinter &AP)
static bool lowerRISCVVMachineInstrToMCInst(const MachineInstr *MI, MCInst &OutMI)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
This class is intended to be used as a driving class for all asm writers.
virtual void emitInstruction(const MachineInstr *)
Targets should implement this to emit instructions.
void EmitToStreamer(MCStreamer &S, const MCInst &Inst)
virtual void emitStartOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the start of their fi...
virtual void emitEndOfAsmFile(Module &)
This virtual method can be overridden by targets that want to emit something at the end of their file...
MCContext & OutContext
This is the context for the output file that we are streaming.
bool runOnMachineFunction(MachineFunction &MF) override
Emit the specified function out to the OutStreamer.
virtual bool PrintAsmMemoryOperand(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 as...
virtual void emitFunctionEntryLabel()
EmitFunctionEntryLabel - Emit the label that is the entrypoint for the function.
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.
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Context object for machine code objects.
Base class for the full range of assembler expressions which are needed for parsing.
MCInstBuilder & addReg(unsigned Reg)
Add a new register operand.
MCInstBuilder & addImm(int64_t Val)
Add a new integer immediate operand.
MCInstBuilder & addExpr(const MCExpr *Val)
Add a new MCExpr operand.
Instances of this class represent a single low-level machine instruction.
unsigned getNumOperands() const
unsigned getOpcode() const
void addOperand(const MCOperand Op)
void setOpcode(unsigned Op)
Describe properties that are true of each instruction in the target description file.
unsigned getNumOperands() const
Return the number of declared MachineOperands for this MachineInstruction.
ArrayRef< MCOperandInfo > operands() const
int getOperandConstraint(unsigned OpNum, MCOI::OperandConstraint Constraint) const
Returns the value of the specified operand constraint if it is present.
Instances of this class represent operands of the MCInst class.
static MCOperand createReg(unsigned Reg)
static MCOperand createExpr(const MCExpr *Val)
static MCOperand createImm(int64_t Val)
const MCExpr * getExpr() const
Streaming machine code generation interface.
virtual void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
virtual bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute)=0
Add the given Attribute to Symbol.
MCContext & getContext() const
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
MCTargetStreamer * getTargetStreamer()
virtual void switchSection(MCSection *Section, const MCExpr *Subsection=nullptr)
Set the current section where code is being emitted to Section.
Generic base class for all target subtargets.
bool hasFeature(unsigned Feature) const
Represent a reference to a symbol from inside an expression.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Representation of each machine instruction.
A description of a memory reference used in the backend.
bool isNonTemporal() const
Flags getFlags() const
Return the raw flags of the source value,.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
MachineBasicBlock * getMBB() const
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
bool isJTI() const
isJTI - Tests if this is a MO_JumpTableIndex operand.
const BlockAddress * getBlockAddress() const
unsigned getTargetFlags() const
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
MCSymbol * getMCSymbol() const
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_GlobalAddress
Address of a global value.
@ MO_RegisterMask
Mask of preserved registers.
@ MO_BlockAddress
Address of a basic block.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
int64_t getOffset() const
Return the offset from the symbol in this operand.
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
A Module instance is used to store all the information related to an LLVM module.
Pass interface - Implemented by all 'passes'.
virtual StringRef getPassName() const
getPassName - Return a nice clean name for a pass.
MI-level patchpoint operands.
static bool isSupportedExtensionFeature(StringRef Ext)
static const char * getRegisterName(MCRegister Reg)
static const RISCVMCExpr * create(const MCExpr *Expr, VariantKind Kind, MCContext &Ctx)
RISCVMachineFunctionInfo - This class is derived from MachineFunctionInfo and contains private RISCV-...
const RISCVRegisterInfo * getRegisterInfo() const override
const RISCVInstrInfo * getInstrInfo() const override
virtual void emitDirectiveVariantCC(MCSymbol &Symbol)
void emitTargetAttributes(const MCSubtargetInfo &STI, bool EmitStackAlign)
void setTargetABI(RISCVABI::ABI ABI)
virtual void emitDirectiveOptionArch(ArrayRef< RISCVOptionArchArg > Args)
virtual void finishAttributeSection()
virtual void emitDirectiveOptionPush()
Wrapper class representing virtual and physical registers.
reference emplace_back(ArgTypes &&... Args)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
MI-level stackmap operands.
uint32_t getNumPatchBytes() const
Return the number of patchable bytes the given stackmap should emit.
void recordStatepoint(const MCSymbol &L, const MachineInstr &MI)
Generate a stackmap record for a statepoint instruction.
void recordPatchPoint(const MCSymbol &L, const MachineInstr &MI)
Generate a stackmap record for a patchpoint instruction.
void recordStackMap(const MCSymbol &L, const MachineInstr &MI)
Generate a stackmap record for a stackmap instruction.
MI-level Statepoint operands.
StringRef - Represent a constant reference to a string, i.e.
TargetInstrInfo - Interface to description of machine instruction set.
Primary interface to the complete machine description for the target machine.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
The instances of the Type class are immutable: once they are created, they are never changed.
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ABI getTargetABI(StringRef ABIName)
static bool hasRoundModeOp(uint64_t TSFlags)
static bool isTiedPseudo(uint64_t TSFlags)
static bool hasVLOp(uint64_t TSFlags)
static bool hasVecPolicyOp(uint64_t TSFlags)
static bool hasSEWOp(uint64_t TSFlags)
bool compress(MCInst &OutInst, const MCInst &MI, const MCSubtargetInfo &STI)
bool isFaultFirstLoad(const MachineInstr &MI)
Reg
All possible values of the reg field in the ModR/M byte.
This is an optimization pass for GlobalISel generic memory operations.
static const MachineMemOperand::Flags MONontemporalBit1
Target & getTheRISCV32Target()
static const MachineMemOperand::Flags MONontemporalBit0
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Target & getTheRISCV64Target()
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures]
@ MCSA_ELF_TypeFunction
.type _foo, STT_FUNC # aka @function
@ MCSA_Hidden
.hidden (ELF)
Implement std::hash so that hash_code can be used in STL containers.
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...
Used to provide key value pairs for feature and CPU bit flags.