LLVM 23.0.0git
RISCVAsmPrinter.cpp
Go to the documentation of this file.
1//===-- RISCVAsmPrinter.cpp - RISC-V LLVM assembly writer -----------------===//
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 the RISC-V assembly language.
11//
12//===----------------------------------------------------------------------===//
13
20#include "RISCV.h"
23#include "RISCVRegisterInfo.h"
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/Statistic.h"
32#include "llvm/IR/Module.h"
33#include "llvm/MC/MCAsmInfo.h"
34#include "llvm/MC/MCContext.h"
35#include "llvm/MC/MCInst.h"
39#include "llvm/MC/MCStreamer.h"
40#include "llvm/MC/MCSymbol.h"
46
47using namespace llvm;
48
49#define DEBUG_TYPE "asm-printer"
50
51STATISTIC(RISCVNumInstrsCompressed,
52 "Number of RISC-V Compressed instructions emitted");
53
54namespace llvm {
55extern const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures];
56} // namespace llvm
57
58namespace {
59class RISCVAsmPrinter : public AsmPrinter {
60public:
61 static char ID;
62
63private:
64 const RISCVSubtarget *STI;
65
66public:
67 explicit RISCVAsmPrinter(TargetMachine &TM,
68 std::unique_ptr<MCStreamer> Streamer)
69 : AsmPrinter(TM, std::move(Streamer), ID) {}
70
71 StringRef getPassName() const override { return "RISC-V Assembly Printer"; }
72
73 RISCVTargetStreamer &getTargetStreamer() const {
74 return static_cast<RISCVTargetStreamer &>(
75 *OutStreamer->getTargetStreamer());
76 }
77
78 void LowerSTACKMAP(MCStreamer &OutStreamer, StackMaps &SM,
79 const MachineInstr &MI);
80
81 void LowerPATCHPOINT(MCStreamer &OutStreamer, StackMaps &SM,
82 const MachineInstr &MI);
83
84 void LowerSTATEPOINT(MCStreamer &OutStreamer, StackMaps &SM,
85 const MachineInstr &MI);
86
87 bool runOnMachineFunction(MachineFunction &MF) override;
88
89 void emitInstruction(const MachineInstr *MI) override;
90
91 void emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) override;
92
93 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
94 const char *ExtraCode, raw_ostream &OS) override;
95 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
96 const char *ExtraCode, raw_ostream &OS) override;
97
98 // Returns whether Inst is compressed.
99 bool EmitToStreamer(MCStreamer &S, const MCInst &Inst,
100 const MCSubtargetInfo &SubtargetInfo);
101 bool EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
102 return EmitToStreamer(S, Inst, *STI);
103 }
104
105 bool lowerPseudoInstExpansion(const MachineInstr *MI, MCInst &Inst);
106
107 typedef std::tuple<unsigned, uint32_t> HwasanMemaccessTuple;
108 std::map<HwasanMemaccessTuple, MCSymbol *> HwasanMemaccessSymbols;
109 void LowerHWASAN_CHECK_MEMACCESS(const MachineInstr &MI);
110 void LowerKCFI_CHECK(const MachineInstr &MI);
111 void EmitHwasanMemaccessSymbols(Module &M);
112
113 // Wrapper needed for tblgenned pseudo lowering.
114 bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp) const;
115
116 void emitStartOfAsmFile(Module &M) override;
117 void emitEndOfAsmFile(Module &M) override;
118
119 void emitFunctionEntryLabel() override;
120 bool emitDirectiveOptionArch();
121
122 void emitNoteGnuProperty(const Module &M);
123
124private:
125 void emitAttributes(const MCSubtargetInfo &SubtargetInfo);
126
127 void emitNTLHint(const MachineInstr *MI);
128
129 // XRay Support
130 void LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr *MI);
131 void LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr *MI);
132 void LowerPATCHABLE_TAIL_CALL(const MachineInstr *MI);
133 void emitSled(const MachineInstr *MI, SledKind Kind);
134
135 void lowerToMCInst(const MachineInstr *MI, MCInst &OutMI);
136};
137}
138
139void RISCVAsmPrinter::LowerSTACKMAP(MCStreamer &OutStreamer, StackMaps &SM,
140 const MachineInstr &MI) {
141 unsigned NOPBytes = STI->hasStdExtZca() ? 2 : 4;
142 unsigned NumNOPBytes = StackMapOpers(&MI).getNumPatchBytes();
143
144 auto &Ctx = OutStreamer.getContext();
145 MCSymbol *MILabel = Ctx.createTempSymbol();
146 OutStreamer.emitLabel(MILabel);
147
148 SM.recordStackMap(*MILabel, MI);
149 assert(NumNOPBytes % NOPBytes == 0 &&
150 "Invalid number of NOP bytes requested!");
151
152 // Scan ahead to trim the shadow.
153 const MachineBasicBlock &MBB = *MI.getParent();
155 ++MII;
156 while (NumNOPBytes > 0) {
157 if (MII == MBB.end() || MII->isCall() ||
158 MII->getOpcode() == RISCV::DBG_VALUE ||
159 MII->getOpcode() == TargetOpcode::PATCHPOINT ||
160 MII->getOpcode() == TargetOpcode::STACKMAP)
161 break;
162 ++MII;
163 NumNOPBytes -= NOPBytes;
164 }
165
166 // Emit nops.
167 emitNops(NumNOPBytes / NOPBytes);
168}
169
170// Lower a patchpoint of the form:
171// [<def>], <id>, <numBytes>, <target>, <numArgs>
172void RISCVAsmPrinter::LowerPATCHPOINT(MCStreamer &OutStreamer, StackMaps &SM,
173 const MachineInstr &MI) {
174 unsigned NOPBytes = STI->hasStdExtZca() ? 2 : 4;
175
176 auto &Ctx = OutStreamer.getContext();
177 MCSymbol *MILabel = Ctx.createTempSymbol();
178 OutStreamer.emitLabel(MILabel);
179 SM.recordPatchPoint(*MILabel, MI);
180
181 PatchPointOpers Opers(&MI);
182
183 const MachineOperand &CalleeMO = Opers.getCallTarget();
184 unsigned EncodedBytes = 0;
185
186 if (CalleeMO.isImm()) {
187 uint64_t CallTarget = CalleeMO.getImm();
188 if (CallTarget) {
189 assert((CallTarget & 0xFFFF'FFFF'FFFF) == CallTarget &&
190 "High 16 bits of call target should be zero.");
191 // Materialize the jump address:
193 RISCVMatInt::generateMCInstSeq(CallTarget, *STI, RISCV::X1, Seq);
194 for (MCInst &Inst : Seq) {
195 bool Compressed = EmitToStreamer(OutStreamer, Inst);
196 EncodedBytes += Compressed ? 2 : 4;
197 }
198 bool Compressed = EmitToStreamer(OutStreamer, MCInstBuilder(RISCV::JALR)
199 .addReg(RISCV::X1)
200 .addReg(RISCV::X1)
201 .addImm(0));
202 EncodedBytes += Compressed ? 2 : 4;
203 }
204 } else if (CalleeMO.isGlobal()) {
205 MCOperand CallTargetMCOp;
206 lowerOperand(CalleeMO, CallTargetMCOp);
207 EmitToStreamer(OutStreamer,
208 MCInstBuilder(RISCV::PseudoCALL).addOperand(CallTargetMCOp));
209 EncodedBytes += 8;
210 }
211
212 // Emit padding.
213 unsigned NumBytes = Opers.getNumPatchBytes();
214 assert(NumBytes >= EncodedBytes &&
215 "Patchpoint can't request size less than the length of a call.");
216 assert((NumBytes - EncodedBytes) % NOPBytes == 0 &&
217 "Invalid number of NOP bytes requested!");
218 emitNops((NumBytes - EncodedBytes) / NOPBytes);
219}
220
221void RISCVAsmPrinter::LowerSTATEPOINT(MCStreamer &OutStreamer, StackMaps &SM,
222 const MachineInstr &MI) {
223 unsigned NOPBytes = STI->hasStdExtZca() ? 2 : 4;
224
225 StatepointOpers SOpers(&MI);
226 if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
227 assert(PatchBytes % NOPBytes == 0 &&
228 "Invalid number of NOP bytes requested!");
229 emitNops(PatchBytes / NOPBytes);
230 } else {
231 // Lower call target and choose correct opcode
232 const MachineOperand &CallTarget = SOpers.getCallTarget();
233 MCOperand CallTargetMCOp;
234 switch (CallTarget.getType()) {
237 lowerOperand(CallTarget, CallTargetMCOp);
238 EmitToStreamer(
239 OutStreamer,
240 MCInstBuilder(RISCV::PseudoCALL).addOperand(CallTargetMCOp));
241 break;
243 CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
244 EmitToStreamer(OutStreamer, MCInstBuilder(RISCV::JAL)
245 .addReg(RISCV::X1)
246 .addOperand(CallTargetMCOp));
247 break;
249 CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
250 EmitToStreamer(OutStreamer, MCInstBuilder(RISCV::JALR)
251 .addReg(RISCV::X1)
252 .addOperand(CallTargetMCOp)
253 .addImm(0));
254 break;
255 default:
256 llvm_unreachable("Unsupported operand type in statepoint call target");
257 break;
258 }
259 }
260
261 auto &Ctx = OutStreamer.getContext();
262 MCSymbol *MILabel = Ctx.createTempSymbol();
263 OutStreamer.emitLabel(MILabel);
264 SM.recordStatepoint(*MILabel, MI);
265}
266
267bool RISCVAsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst,
268 const MCSubtargetInfo &SubtargetInfo) {
269 MCInst CInst;
270 bool Res = RISCVRVC::compress(CInst, Inst, SubtargetInfo);
271 if (Res)
272 ++RISCVNumInstrsCompressed;
273 S.emitInstruction(Res ? CInst : Inst, SubtargetInfo);
274 return Res;
275}
276
277// Simple pseudo-instructions have their lowering (with expansion to real
278// instructions) auto-generated.
279#include "RISCVGenMCPseudoLowering.inc"
280
281// If the instruction has a nontemporal MachineMemOperand, emit an NTL hint
282// instruction before it. NTL hints are always safe to emit since they use
283// HINT encodings that are guaranteed not to trap
284// (riscv-non-isa/riscv-elf-psabi-doc#474).
285void RISCVAsmPrinter::emitNTLHint(const MachineInstr *MI) {
286 if (!STI->getInstrInfo()->requiresNTLHint(*MI))
287 return;
288
289 assert(!MI->memoperands_empty());
290
291 MachineMemOperand *MMO = *(MI->memoperands_begin());
292
293 assert(MMO->isNonTemporal());
294
295 unsigned NontemporalMode = 0;
296 if (MMO->getFlags() & MONontemporalBit0)
297 NontemporalMode += 0b1;
298 if (MMO->getFlags() & MONontemporalBit1)
299 NontemporalMode += 0b10;
300
301 MCInst Hint;
302 if (STI->hasStdExtZca())
303 Hint.setOpcode(RISCV::C_ADD);
304 else
305 Hint.setOpcode(RISCV::ADD);
306
307 Hint.addOperand(MCOperand::createReg(RISCV::X0));
308 Hint.addOperand(MCOperand::createReg(RISCV::X0));
309 Hint.addOperand(MCOperand::createReg(RISCV::X2 + NontemporalMode));
310
311 EmitToStreamer(*OutStreamer, Hint);
312}
313
314void RISCVAsmPrinter::emitInstruction(const MachineInstr *MI) {
315 RISCV_MC::verifyInstructionPredicates(MI->getOpcode(), STI->getFeatureBits());
316
317 emitNTLHint(MI);
318
319 // Do any auto-generated pseudo lowerings.
320 if (MCInst OutInst; lowerPseudoInstExpansion(MI, OutInst)) {
321 EmitToStreamer(*OutStreamer, OutInst);
322 return;
323 }
324
325 switch (MI->getOpcode()) {
326 case RISCV::HWASAN_CHECK_MEMACCESS_SHORTGRANULES:
327 LowerHWASAN_CHECK_MEMACCESS(*MI);
328 return;
329 case RISCV::KCFI_CHECK:
330 LowerKCFI_CHECK(*MI);
331 return;
332 case TargetOpcode::STACKMAP:
333 return LowerSTACKMAP(*OutStreamer, SM, *MI);
334 case TargetOpcode::PATCHPOINT:
335 return LowerPATCHPOINT(*OutStreamer, SM, *MI);
336 case TargetOpcode::STATEPOINT:
337 return LowerSTATEPOINT(*OutStreamer, SM, *MI);
338 case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
339 const Function &F = MI->getParent()->getParent()->getFunction();
340 if (F.hasFnAttribute("patchable-function-entry")) {
341 unsigned Num;
342 [[maybe_unused]] bool Result =
343 F.getFnAttribute("patchable-function-entry")
344 .getValueAsString()
345 .getAsInteger(10, Num);
346 assert(!Result && "Enforced by the verifier");
347 emitNops(Num);
348 return;
349 }
350 LowerPATCHABLE_FUNCTION_ENTER(MI);
351 return;
352 }
353 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
354 LowerPATCHABLE_FUNCTION_EXIT(MI);
355 return;
356 case TargetOpcode::PATCHABLE_TAIL_CALL:
357 LowerPATCHABLE_TAIL_CALL(MI);
358 return;
359 }
360
361 MCInst OutInst;
362 lowerToMCInst(MI, OutInst);
363 EmitToStreamer(*OutStreamer, OutInst);
364}
365
366bool RISCVAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
367 const char *ExtraCode, raw_ostream &OS) {
368 // First try the generic code, which knows about modifiers like 'c' and 'n'.
369 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, OS))
370 return false;
371
372 const MachineOperand &MO = MI->getOperand(OpNo);
373 if (ExtraCode && ExtraCode[0]) {
374 if (ExtraCode[1] != 0)
375 return true; // Unknown modifier.
376
377 switch (ExtraCode[0]) {
378 default:
379 return true; // Unknown modifier.
380 case 'z': // Print zero register if zero, regular printing otherwise.
381 if (MO.isImm() && MO.getImm() == 0) {
382 OS << RISCVInstPrinter::getRegisterName(RISCV::X0);
383 return false;
384 }
385 break;
386 case 'i': // Literal 'i' if operand is not a register.
387 if (!MO.isReg())
388 OS << 'i';
389 return false;
390 case 'N': // Print the register encoding as an integer (0-31)
391 if (!MO.isReg())
392 return true;
393
394 const RISCVRegisterInfo *TRI = STI->getRegisterInfo();
395 OS << TRI->getEncodingValue(MO.getReg());
396 return false;
397 }
398 }
399
400 switch (MO.getType()) {
402 OS << MO.getImm();
403 return false;
406 return false;
408 PrintSymbolOperand(MO, OS);
409 return false;
411 MCSymbol *Sym = GetBlockAddressSymbol(MO.getBlockAddress());
412 Sym->print(OS, MAI);
413 return false;
414 }
415 default:
416 break;
417 }
418
419 return true;
420}
421
422bool RISCVAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
423 unsigned OpNo,
424 const char *ExtraCode,
425 raw_ostream &OS) {
426 if (ExtraCode)
427 return AsmPrinter::PrintAsmMemoryOperand(MI, OpNo, ExtraCode, OS);
428
429 const MachineOperand &AddrReg = MI->getOperand(OpNo);
430 assert(MI->getNumOperands() > OpNo + 1 && "Expected additional operand");
431 const MachineOperand &Offset = MI->getOperand(OpNo + 1);
432 // All memory operands should have a register and an immediate operand (see
433 // RISCVDAGToDAGISel::SelectInlineAsmMemoryOperand).
434 if (!AddrReg.isReg())
435 return true;
436 if (!Offset.isImm() && !Offset.isGlobal() && !Offset.isBlockAddress() &&
437 !Offset.isMCSymbol())
438 return true;
439
440 MCOperand MCO;
441 if (!lowerOperand(Offset, MCO))
442 return true;
443
444 if (Offset.isImm())
445 OS << MCO.getImm();
446 else if (Offset.isGlobal() || Offset.isBlockAddress() || Offset.isMCSymbol())
447 MAI->printExpr(OS, *MCO.getExpr());
448
449 if (Offset.isMCSymbol())
450 MMI->getContext().registerInlineAsmLabel(Offset.getMCSymbol());
451 if (Offset.isBlockAddress()) {
452 const BlockAddress *BA = Offset.getBlockAddress();
453 MCSymbol *Sym = GetBlockAddressSymbol(BA);
454 MMI->getContext().registerInlineAsmLabel(Sym);
455 }
456
457 OS << "(" << RISCVInstPrinter::getRegisterName(AddrReg.getReg()) << ")";
458 return false;
459}
460
461bool RISCVAsmPrinter::emitDirectiveOptionArch() {
462 RISCVTargetStreamer &RTS = getTargetStreamer();
463 SmallVector<RISCVOptionArchArg> NeedEmitStdOptionArgs;
464 const MCSubtargetInfo &MCSTI = *TM.getMCSubtargetInfo();
465 for (const auto &Feature : RISCVFeatureKV) {
466 if (STI->hasFeature(Feature.Value) == MCSTI.hasFeature(Feature.Value))
467 continue;
468
470 continue;
471
472 auto Delta = STI->hasFeature(Feature.Value) ? RISCVOptionArchArgType::Plus
473 : RISCVOptionArchArgType::Minus;
474 NeedEmitStdOptionArgs.emplace_back(Delta, Feature.Key);
475 }
476 if (!NeedEmitStdOptionArgs.empty()) {
478 RTS.emitDirectiveOptionArch(NeedEmitStdOptionArgs);
479 return true;
480 }
481
482 return false;
483}
484
485bool RISCVAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
486 STI = &MF.getSubtarget<RISCVSubtarget>();
487 RISCVTargetStreamer &RTS = getTargetStreamer();
488
489 bool EmittedOptionArch = emitDirectiveOptionArch();
490
491 SetupMachineFunction(MF);
492 emitFunctionBody();
493
494 // Emit the XRay table
495 emitXRayTable();
496
497 if (EmittedOptionArch)
498 RTS.emitDirectiveOptionPop();
499 return false;
500}
501
502void RISCVAsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr *MI) {
503 emitSled(MI, SledKind::FUNCTION_ENTER);
504}
505
506void RISCVAsmPrinter::LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr *MI) {
507 emitSled(MI, SledKind::FUNCTION_EXIT);
508}
509
510void RISCVAsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr *MI) {
511 emitSled(MI, SledKind::TAIL_CALL);
512}
513
514void RISCVAsmPrinter::emitSled(const MachineInstr *MI, SledKind Kind) {
515 // We want to emit the jump instruction and the nops constituting the sled.
516 // The format is as follows:
517 // .Lxray_sled_N
518 // ALIGN
519 // J .tmpN
520 // 21 or 33 C.NOP instructions
521 // .tmpN
522
523 // The following variable holds the count of the number of NOPs to be patched
524 // in for XRay instrumentation during compilation.
525 // Note that RV64 and RV32 each has a sled of 68 and 44 bytes, respectively.
526 // Assuming we're using JAL to jump to .tmpN, then we only need
527 // (68 - 4)/2 = 32 NOPs for RV64 and (44 - 4)/2 = 20 for RV32. However, there
528 // is a chance that we'll use C.JAL instead, so an additional NOP is needed.
529 const uint8_t NoopsInSledCount = STI->is64Bit() ? 33 : 21;
530
531 OutStreamer->emitCodeAlignment(Align(4), STI);
532 auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
533 OutStreamer->emitLabel(CurSled);
534 auto Target = OutContext.createTempSymbol();
535
536 const MCExpr *TargetExpr = MCSymbolRefExpr::create(Target, OutContext);
537
538 // Emit "J bytes" instruction, which jumps over the nop sled to the actual
539 // start of function.
540 EmitToStreamer(
541 *OutStreamer,
542 MCInstBuilder(RISCV::JAL).addReg(RISCV::X0).addExpr(TargetExpr));
543
544 // Emit NOP instructions
545 for (int8_t I = 0; I < NoopsInSledCount; ++I)
546 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::ADDI)
547 .addReg(RISCV::X0)
548 .addReg(RISCV::X0)
549 .addImm(0));
550
551 OutStreamer->emitLabel(Target);
552 recordSled(CurSled, *MI, Kind, 2);
553}
554
555void RISCVAsmPrinter::emitStartOfAsmFile(Module &M) {
556 assert(OutStreamer->getTargetStreamer() &&
557 "target streamer is uninitialized");
558 RISCVTargetStreamer &RTS = getTargetStreamer();
559 if (const MDString *ModuleTargetABI =
560 dyn_cast_or_null<MDString>(M.getModuleFlag("target-abi")))
561 RTS.setTargetABI(RISCVABI::getTargetABI(ModuleTargetABI->getString()));
562
563 MCSubtargetInfo SubtargetInfo = *TM.getMCSubtargetInfo();
564
565 // Use module flag to update feature bits.
566 if (auto *MD = dyn_cast_or_null<MDNode>(M.getModuleFlag("riscv-isa"))) {
567 for (auto &ISA : MD->operands()) {
568 if (auto *ISAString = dyn_cast_or_null<MDString>(ISA)) {
569 auto ParseResult = llvm::RISCVISAInfo::parseArchString(
570 ISAString->getString(), /*EnableExperimentalExtension=*/true,
571 /*ExperimentalExtensionVersionCheck=*/true);
572 if (!errorToBool(ParseResult.takeError())) {
573 auto &ISAInfo = *ParseResult;
574 for (const auto &Feature : RISCVFeatureKV) {
575 if (ISAInfo->hasExtension(Feature.Key) &&
576 !SubtargetInfo.hasFeature(Feature.Value))
577 SubtargetInfo.ToggleFeature(Feature.Key);
578 }
579 }
580 }
581 }
582
583 RTS.setFlagsFromFeatures(SubtargetInfo);
584 }
585
586 if (TM.getTargetTriple().isOSBinFormatELF())
587 emitAttributes(SubtargetInfo);
588}
589
590void RISCVAsmPrinter::emitEndOfAsmFile(Module &M) {
591 RISCVTargetStreamer &RTS = getTargetStreamer();
592
593 if (TM.getTargetTriple().isOSBinFormatELF()) {
595 emitNoteGnuProperty(M);
596 }
597 EmitHwasanMemaccessSymbols(M);
598}
599
600void RISCVAsmPrinter::emitAttributes(const MCSubtargetInfo &SubtargetInfo) {
601 RISCVTargetStreamer &RTS = getTargetStreamer();
602 // Use MCSubtargetInfo from TargetMachine. Individual functions may have
603 // attributes that differ from other functions in the module and we have no
604 // way to know which function is correct.
605 RTS.emitTargetAttributes(SubtargetInfo, /*EmitStackAlign*/ true);
606}
607
608void RISCVAsmPrinter::emitFunctionEntryLabel() {
609 const auto *RMFI = MF->getInfo<RISCVMachineFunctionInfo>();
610 if (RMFI->isVectorCall()) {
611 RISCVTargetStreamer &RTS = getTargetStreamer();
612 RTS.emitDirectiveVariantCC(*CurrentFnSym);
613 }
615}
616
617// Force static initialization.
625
626void RISCVAsmPrinter::LowerHWASAN_CHECK_MEMACCESS(const MachineInstr &MI) {
627 Register Reg = MI.getOperand(0).getReg();
628 uint32_t AccessInfo = MI.getOperand(1).getImm();
629 MCSymbol *&Sym =
630 HwasanMemaccessSymbols[HwasanMemaccessTuple(Reg, AccessInfo)];
631 if (!Sym) {
632 // FIXME: Make this work on non-ELF.
633 if (!TM.getTargetTriple().isOSBinFormatELF())
634 report_fatal_error("llvm.hwasan.check.memaccess only supported on ELF");
635
636 std::string SymName = "__hwasan_check_x" + utostr(Reg - RISCV::X0) + "_" +
637 utostr(AccessInfo) + "_short";
638 Sym = OutContext.getOrCreateSymbol(SymName);
639 }
640 auto Res = MCSymbolRefExpr::create(Sym, OutContext);
641 auto Expr = MCSpecifierExpr::create(Res, RISCV::S_CALL_PLT, OutContext);
642
643 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::PseudoCALL).addExpr(Expr));
644}
645
646void RISCVAsmPrinter::LowerKCFI_CHECK(const MachineInstr &MI) {
647 Register AddrReg = MI.getOperand(0).getReg();
648 assert(std::next(MI.getIterator())->isCall() &&
649 "KCFI_CHECK not followed by a call instruction");
650 assert(std::next(MI.getIterator())->getOperand(0).getReg() == AddrReg &&
651 "KCFI_CHECK call target doesn't match call operand");
652
653 // Temporary registers for comparing the hashes. If a register is used
654 // for the call target, or reserved by the user, we can clobber another
655 // temporary register as the check is immediately followed by the
656 // call. The check defaults to X6/X7, but can fall back to X28-X31 if
657 // needed.
658 unsigned ScratchRegs[] = {RISCV::X6, RISCV::X7};
659 unsigned NextReg = RISCV::X28;
660 auto isRegAvailable = [&](unsigned Reg) {
661 return Reg != AddrReg && !STI->isRegisterReservedByUser(Reg);
662 };
663 for (auto &Reg : ScratchRegs) {
664 if (isRegAvailable(Reg))
665 continue;
666 while (!isRegAvailable(NextReg))
667 ++NextReg;
668 Reg = NextReg++;
669 if (Reg > RISCV::X31)
670 report_fatal_error("Unable to find scratch registers for KCFI_CHECK");
671 }
672
673 if (AddrReg == RISCV::X0) {
674 // Checking X0 makes no sense. Instead of emitting a load, zero
675 // ScratchRegs[0].
676 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::ADDI)
677 .addReg(ScratchRegs[0])
678 .addReg(RISCV::X0)
679 .addImm(0));
680 } else {
681 // Adjust the offset for patchable-function-prefix. This assumes that
682 // patchable-function-prefix is the same for all functions.
683 int NopSize = STI->hasStdExtZca() ? 2 : 4;
684 int64_t PrefixNops = 0;
685 (void)MI.getMF()
686 ->getFunction()
687 .getFnAttribute("patchable-function-prefix")
688 .getValueAsString()
689 .getAsInteger(10, PrefixNops);
690
691 // Load the target function type hash.
692 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::LW)
693 .addReg(ScratchRegs[0])
694 .addReg(AddrReg)
695 .addImm(-(PrefixNops * NopSize + 4)));
696 }
697
698 // Load the expected 32-bit type hash.
699 const int64_t Type = MI.getOperand(1).getImm();
700 const int64_t Hi20 = ((Type + 0x800) >> 12) & 0xFFFFF;
701 const int64_t Lo12 = SignExtend64<12>(Type);
702 if (Hi20) {
703 EmitToStreamer(
704 *OutStreamer,
705 MCInstBuilder(RISCV::LUI).addReg(ScratchRegs[1]).addImm(Hi20));
706 }
707 if (Lo12 || Hi20 == 0) {
708 EmitToStreamer(*OutStreamer,
709 MCInstBuilder((STI->hasFeature(RISCV::Feature64Bit) && Hi20)
710 ? RISCV::ADDIW
711 : RISCV::ADDI)
712 .addReg(ScratchRegs[1])
713 .addReg(ScratchRegs[1])
714 .addImm(Lo12));
715 }
716
717 // Compare the hashes and trap if there's a mismatch.
718 MCSymbol *Pass = OutContext.createTempSymbol();
719 EmitToStreamer(*OutStreamer,
720 MCInstBuilder(RISCV::BEQ)
721 .addReg(ScratchRegs[0])
722 .addReg(ScratchRegs[1])
723 .addExpr(MCSymbolRefExpr::create(Pass, OutContext)));
724
725 MCSymbol *Trap = OutContext.createTempSymbol();
726 OutStreamer->emitLabel(Trap);
727 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::EBREAK));
728 emitKCFITrapEntry(*MI.getMF(), Trap);
729 OutStreamer->emitLabel(Pass);
730}
731
732void RISCVAsmPrinter::EmitHwasanMemaccessSymbols(Module &M) {
733 if (HwasanMemaccessSymbols.empty())
734 return;
735
736 assert(TM.getTargetTriple().isOSBinFormatELF());
737 // Use MCSubtargetInfo from TargetMachine. Individual functions may have
738 // attributes that differ from other functions in the module and we have no
739 // way to know which function is correct.
740 const MCSubtargetInfo &MCSTI = *TM.getMCSubtargetInfo();
741
742 MCSymbol *HwasanTagMismatchV2Sym =
743 OutContext.getOrCreateSymbol("__hwasan_tag_mismatch_v2");
744 // Annotate symbol as one having incompatible calling convention, so
745 // run-time linkers can instead eagerly bind this function.
746 RISCVTargetStreamer &RTS = getTargetStreamer();
747 RTS.emitDirectiveVariantCC(*HwasanTagMismatchV2Sym);
748
749 const MCSymbolRefExpr *HwasanTagMismatchV2Ref =
750 MCSymbolRefExpr::create(HwasanTagMismatchV2Sym, OutContext);
751 auto Expr = MCSpecifierExpr::create(HwasanTagMismatchV2Ref, RISCV::S_CALL_PLT,
752 OutContext);
753
754 for (auto &P : HwasanMemaccessSymbols) {
755 unsigned Reg = std::get<0>(P.first);
756 uint32_t AccessInfo = std::get<1>(P.first);
757 MCSymbol *Sym = P.second;
758
759 unsigned Size =
760 1 << ((AccessInfo >> HWASanAccessInfo::AccessSizeShift) & 0xf);
761 OutStreamer->switchSection(OutContext.getELFSection(
762 ".text.hot", ELF::SHT_PROGBITS,
764 /*IsComdat=*/true));
765
767 OutStreamer->emitSymbolAttribute(Sym, MCSA_Weak);
768 OutStreamer->emitSymbolAttribute(Sym, MCSA_Hidden);
769 OutStreamer->emitLabel(Sym);
770
771 // Extract shadow offset from ptr
772 EmitToStreamer(
773 *OutStreamer,
774 MCInstBuilder(RISCV::SLLI).addReg(RISCV::X6).addReg(Reg).addImm(8),
775 MCSTI);
776 EmitToStreamer(*OutStreamer,
777 MCInstBuilder(RISCV::SRLI)
778 .addReg(RISCV::X6)
779 .addReg(RISCV::X6)
780 .addImm(12),
781 MCSTI);
782 // load shadow tag in X6, X5 contains shadow base
783 EmitToStreamer(*OutStreamer,
784 MCInstBuilder(RISCV::ADD)
785 .addReg(RISCV::X6)
786 .addReg(RISCV::X5)
787 .addReg(RISCV::X6),
788 MCSTI);
789 EmitToStreamer(
790 *OutStreamer,
791 MCInstBuilder(RISCV::LBU).addReg(RISCV::X6).addReg(RISCV::X6).addImm(0),
792 MCSTI);
793 // Extract tag from pointer and compare it with loaded tag from shadow
794 EmitToStreamer(
795 *OutStreamer,
796 MCInstBuilder(RISCV::SRLI).addReg(RISCV::X7).addReg(Reg).addImm(56),
797 MCSTI);
798 MCSymbol *HandleMismatchOrPartialSym = OutContext.createTempSymbol();
799 // X7 contains tag from the pointer, while X6 contains tag from memory
800 EmitToStreamer(*OutStreamer,
801 MCInstBuilder(RISCV::BNE)
802 .addReg(RISCV::X7)
803 .addReg(RISCV::X6)
805 HandleMismatchOrPartialSym, OutContext)),
806 MCSTI);
807 MCSymbol *ReturnSym = OutContext.createTempSymbol();
808 OutStreamer->emitLabel(ReturnSym);
809 EmitToStreamer(*OutStreamer,
810 MCInstBuilder(RISCV::JALR)
811 .addReg(RISCV::X0)
812 .addReg(RISCV::X1)
813 .addImm(0),
814 MCSTI);
815 OutStreamer->emitLabel(HandleMismatchOrPartialSym);
816
817 EmitToStreamer(*OutStreamer,
818 MCInstBuilder(RISCV::ADDI)
819 .addReg(RISCV::X28)
820 .addReg(RISCV::X0)
821 .addImm(16),
822 MCSTI);
823 MCSymbol *HandleMismatchSym = OutContext.createTempSymbol();
824 EmitToStreamer(
825 *OutStreamer,
826 MCInstBuilder(RISCV::BGEU)
827 .addReg(RISCV::X6)
828 .addReg(RISCV::X28)
829 .addExpr(MCSymbolRefExpr::create(HandleMismatchSym, OutContext)),
830 MCSTI);
831
832 EmitToStreamer(
833 *OutStreamer,
834 MCInstBuilder(RISCV::ANDI).addReg(RISCV::X28).addReg(Reg).addImm(0xF),
835 MCSTI);
836
837 if (Size != 1)
838 EmitToStreamer(*OutStreamer,
839 MCInstBuilder(RISCV::ADDI)
840 .addReg(RISCV::X28)
841 .addReg(RISCV::X28)
842 .addImm(Size - 1),
843 MCSTI);
844 EmitToStreamer(
845 *OutStreamer,
846 MCInstBuilder(RISCV::BGE)
847 .addReg(RISCV::X28)
848 .addReg(RISCV::X6)
849 .addExpr(MCSymbolRefExpr::create(HandleMismatchSym, OutContext)),
850 MCSTI);
851
852 EmitToStreamer(
853 *OutStreamer,
854 MCInstBuilder(RISCV::ORI).addReg(RISCV::X6).addReg(Reg).addImm(0xF),
855 MCSTI);
856 EmitToStreamer(
857 *OutStreamer,
858 MCInstBuilder(RISCV::LBU).addReg(RISCV::X6).addReg(RISCV::X6).addImm(0),
859 MCSTI);
860 EmitToStreamer(*OutStreamer,
861 MCInstBuilder(RISCV::BEQ)
862 .addReg(RISCV::X6)
863 .addReg(RISCV::X7)
864 .addExpr(MCSymbolRefExpr::create(ReturnSym, OutContext)),
865 MCSTI);
866
867 OutStreamer->emitLabel(HandleMismatchSym);
868
869 // | Previous stack frames... |
870 // +=================================+ <-- [SP + 256]
871 // | ... |
872 // | |
873 // | Stack frame space for x12 - x31.|
874 // | |
875 // | ... |
876 // +---------------------------------+ <-- [SP + 96]
877 // | Saved x11(arg1), as |
878 // | __hwasan_check_* clobbers it. |
879 // +---------------------------------+ <-- [SP + 88]
880 // | Saved x10(arg0), as |
881 // | __hwasan_check_* clobbers it. |
882 // +---------------------------------+ <-- [SP + 80]
883 // | |
884 // | Stack frame space for x9. |
885 // +---------------------------------+ <-- [SP + 72]
886 // | |
887 // | Saved x8(fp), as |
888 // | __hwasan_check_* clobbers it. |
889 // +---------------------------------+ <-- [SP + 64]
890 // | ... |
891 // | |
892 // | Stack frame space for x2 - x7. |
893 // | |
894 // | ... |
895 // +---------------------------------+ <-- [SP + 16]
896 // | Return address (x1) for caller |
897 // | of __hwasan_check_*. |
898 // +---------------------------------+ <-- [SP + 8]
899 // | Reserved place for x0, possibly |
900 // | junk, since we don't save it. |
901 // +---------------------------------+ <-- [x2 / SP]
902
903 // Adjust sp
904 EmitToStreamer(*OutStreamer,
905 MCInstBuilder(RISCV::ADDI)
906 .addReg(RISCV::X2)
907 .addReg(RISCV::X2)
908 .addImm(-256),
909 MCSTI);
910
911 // store x10(arg0) by new sp
912 EmitToStreamer(*OutStreamer,
913 MCInstBuilder(RISCV::SD)
914 .addReg(RISCV::X10)
915 .addReg(RISCV::X2)
916 .addImm(8 * 10),
917 MCSTI);
918 // store x11(arg1) by new sp
919 EmitToStreamer(*OutStreamer,
920 MCInstBuilder(RISCV::SD)
921 .addReg(RISCV::X11)
922 .addReg(RISCV::X2)
923 .addImm(8 * 11),
924 MCSTI);
925
926 // store x8(fp) by new sp
927 EmitToStreamer(
928 *OutStreamer,
929 MCInstBuilder(RISCV::SD).addReg(RISCV::X8).addReg(RISCV::X2).addImm(8 *
930 8),
931 MCSTI);
932 // store x1(ra) by new sp
933 EmitToStreamer(
934 *OutStreamer,
935 MCInstBuilder(RISCV::SD).addReg(RISCV::X1).addReg(RISCV::X2).addImm(1 *
936 8),
937 MCSTI);
938 if (Reg != RISCV::X10)
939 EmitToStreamer(
940 *OutStreamer,
941 MCInstBuilder(RISCV::ADDI).addReg(RISCV::X10).addReg(Reg).addImm(0),
942 MCSTI);
943 EmitToStreamer(*OutStreamer,
944 MCInstBuilder(RISCV::ADDI)
945 .addReg(RISCV::X11)
946 .addReg(RISCV::X0)
947 .addImm(AccessInfo & HWASanAccessInfo::RuntimeMask),
948 MCSTI);
949
950 EmitToStreamer(*OutStreamer, MCInstBuilder(RISCV::PseudoCALL).addExpr(Expr),
951 MCSTI);
952 }
953}
954
955void RISCVAsmPrinter::emitNoteGnuProperty(const Module &M) {
956 assert(TM.getTargetTriple().isOSBinFormatELF() && "invalid binary format");
957 if (const Metadata *const Flag = M.getModuleFlag("cf-protection-return");
958 Flag && !mdconst::extract<ConstantInt>(Flag)->isZero()) {
959 auto &RTS = static_cast<RISCVTargetELFStreamer &>(getTargetStreamer());
960 RTS.emitNoteGnuPropertySection(ELF::GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS);
961 }
962}
963
965 const AsmPrinter &AP) {
966 MCContext &Ctx = AP.OutContext;
967 RISCV::Specifier Kind;
968
969 switch (MO.getTargetFlags()) {
970 default:
971 llvm_unreachable("Unknown target flag on GV operand");
972 case RISCVII::MO_None:
973 Kind = RISCV::S_None;
974 break;
975 case RISCVII::MO_CALL:
976 Kind = RISCV::S_CALL_PLT;
977 break;
978 case RISCVII::MO_LO:
979 Kind = RISCV::S_LO;
980 break;
981 case RISCVII::MO_HI:
982 Kind = ELF::R_RISCV_HI20;
983 break;
985 Kind = RISCV::S_PCREL_LO;
986 break;
988 Kind = RISCV::S_PCREL_HI;
989 break;
991 Kind = RISCV::S_GOT_HI;
992 break;
994 Kind = RISCV::S_TPREL_LO;
995 break;
997 Kind = ELF::R_RISCV_TPREL_HI20;
998 break;
1000 Kind = ELF::R_RISCV_TPREL_ADD;
1001 break;
1003 Kind = ELF::R_RISCV_TLS_GOT_HI20;
1004 break;
1006 Kind = ELF::R_RISCV_TLS_GD_HI20;
1007 break;
1009 Kind = ELF::R_RISCV_TLSDESC_HI20;
1010 break;
1012 Kind = ELF::R_RISCV_TLSDESC_LOAD_LO12;
1013 break;
1015 Kind = ELF::R_RISCV_TLSDESC_ADD_LO12;
1016 break;
1018 Kind = ELF::R_RISCV_TLSDESC_CALL;
1019 break;
1020 }
1021
1022 const MCExpr *ME = MCSymbolRefExpr::create(Sym, Ctx);
1023
1024 if (!MO.isJTI() && !MO.isMBB() && MO.getOffset())
1026 ME, MCConstantExpr::create(MO.getOffset(), Ctx), Ctx);
1027
1028 if (Kind != RISCV::S_None)
1029 ME = MCSpecifierExpr::create(ME, Kind, Ctx);
1030 return MCOperand::createExpr(ME);
1031}
1032
1033bool RISCVAsmPrinter::lowerOperand(const MachineOperand &MO,
1034 MCOperand &MCOp) const {
1035 switch (MO.getType()) {
1036 default:
1037 report_fatal_error("lowerOperand: unknown operand type");
1039 // Ignore all implicit register operands.
1040 if (MO.isImplicit())
1041 return false;
1042 MCOp = MCOperand::createReg(MO.getReg());
1043 break;
1045 // Regmasks are like implicit defs.
1046 return false;
1048 MCOp = MCOperand::createImm(MO.getImm());
1049 break;
1051 MCOp = lowerSymbolOperand(MO, MO.getMBB()->getSymbol(), *this);
1052 break;
1054 MCOp = lowerSymbolOperand(MO, getSymbolPreferLocal(*MO.getGlobal()), *this);
1055 break;
1057 MCOp = lowerSymbolOperand(MO, GetBlockAddressSymbol(MO.getBlockAddress()),
1058 *this);
1059 break;
1061 MCOp = lowerSymbolOperand(MO, GetExternalSymbolSymbol(MO.getSymbolName()),
1062 *this);
1063 break;
1065 MCOp = lowerSymbolOperand(MO, GetCPISymbol(MO.getIndex()), *this);
1066 break;
1068 MCOp = lowerSymbolOperand(MO, GetJTISymbol(MO.getIndex()), *this);
1069 break;
1071 MCOp = lowerSymbolOperand(MO, MO.getMCSymbol(), *this);
1072 break;
1073 }
1074 return true;
1075}
1076
1078 MCInst &OutMI,
1079 const RISCVSubtarget *STI) {
1081 RISCVVPseudosTable::getPseudoInfo(MI->getOpcode());
1082 if (!RVV)
1083 return false;
1084
1085 OutMI.setOpcode(RVV->BaseInstr);
1086
1087 const TargetInstrInfo *TII = STI->getInstrInfo();
1088 const TargetRegisterInfo *TRI = STI->getRegisterInfo();
1089 assert(TRI && "TargetRegisterInfo expected");
1090
1091 const MCInstrDesc &MCID = MI->getDesc();
1092 uint64_t TSFlags = MCID.TSFlags;
1093 unsigned NumOps = MI->getNumExplicitOperands();
1094
1095 // Skip policy, SEW, VL, VXRM/FRM operands which are the last operands if
1096 // present.
1097 if (RISCVII::hasVecPolicyOp(TSFlags))
1098 --NumOps;
1099 if (RISCVII::hasSEWOp(TSFlags))
1100 --NumOps;
1101 if (RISCVII::hasVLOp(TSFlags))
1102 --NumOps;
1103 if (RISCVII::hasRoundModeOp(TSFlags))
1104 --NumOps;
1105 if (RISCVII::hasTWidenOp(TSFlags))
1106 --NumOps;
1107 if (RISCVII::hasTMOp(TSFlags))
1108 --NumOps;
1109 if (RISCVII::hasTKOp(TSFlags))
1110 --NumOps;
1111
1112 bool hasVLOutput = RISCVInstrInfo::isFaultOnlyFirstLoad(*MI);
1113 for (unsigned OpNo = 0; OpNo != NumOps; ++OpNo) {
1114 const MachineOperand &MO = MI->getOperand(OpNo);
1115 // Skip vl output. It should be the second output.
1116 if (hasVLOutput && OpNo == 1)
1117 continue;
1118
1119 // Skip passthru op. It should be the first operand after the defs.
1120 if (OpNo == MI->getNumExplicitDefs() && MO.isReg() && MO.isTied()) {
1121 assert(MCID.getOperandConstraint(OpNo, MCOI::TIED_TO) == 0 &&
1122 "Expected tied to first def.");
1123 const MCInstrDesc &OutMCID = TII->get(OutMI.getOpcode());
1124 // Skip if the next operand in OutMI is not supposed to be tied. Unless it
1125 // is a _TIED instruction.
1126 if (OutMCID.getOperandConstraint(OutMI.getNumOperands(), MCOI::TIED_TO) <
1127 0 &&
1128 !RISCVII::isTiedPseudo(TSFlags))
1129 continue;
1130 }
1131
1132 MCOperand MCOp;
1133 switch (MO.getType()) {
1134 default:
1135 llvm_unreachable("Unknown operand type");
1137 Register Reg = MO.getReg();
1138
1139 if (RISCV::VRM2RegClass.contains(Reg) ||
1140 RISCV::VRM4RegClass.contains(Reg) ||
1141 RISCV::VRM8RegClass.contains(Reg)) {
1142 Reg = TRI->getSubReg(Reg, RISCV::sub_vrm1_0);
1143 assert(Reg && "Subregister does not exist");
1144 } else if (RISCV::FPR16RegClass.contains(Reg)) {
1145 Reg =
1146 TRI->getMatchingSuperReg(Reg, RISCV::sub_16, &RISCV::FPR32RegClass);
1147 assert(Reg && "Subregister does not exist");
1148 } else if (RISCV::FPR64RegClass.contains(Reg)) {
1149 Reg = TRI->getSubReg(Reg, RISCV::sub_32);
1150 assert(Reg && "Superregister does not exist");
1151 } else if (RISCV::VRN2M1RegClass.contains(Reg) ||
1152 RISCV::VRN2M2RegClass.contains(Reg) ||
1153 RISCV::VRN2M4RegClass.contains(Reg) ||
1154 RISCV::VRN3M1RegClass.contains(Reg) ||
1155 RISCV::VRN3M2RegClass.contains(Reg) ||
1156 RISCV::VRN4M1RegClass.contains(Reg) ||
1157 RISCV::VRN4M2RegClass.contains(Reg) ||
1158 RISCV::VRN5M1RegClass.contains(Reg) ||
1159 RISCV::VRN6M1RegClass.contains(Reg) ||
1160 RISCV::VRN7M1RegClass.contains(Reg) ||
1161 RISCV::VRN8M1RegClass.contains(Reg)) {
1162 Reg = TRI->getSubReg(Reg, RISCV::sub_vrm1_0);
1163 assert(Reg && "Subregister does not exist");
1164 }
1165
1166 MCOp = MCOperand::createReg(Reg);
1167 break;
1168 }
1170 MCOp = MCOperand::createImm(MO.getImm());
1171 break;
1172 }
1173 OutMI.addOperand(MCOp);
1174 }
1175
1176 // Unmasked pseudo instructions need to append dummy mask operand to
1177 // V instructions. All V instructions are modeled as the masked version.
1178 const MCInstrDesc &OutMCID = TII->get(OutMI.getOpcode());
1179 if (OutMI.getNumOperands() < OutMCID.getNumOperands()) {
1180 assert(OutMCID.operands()[OutMI.getNumOperands()].OperandType ==
1182 "Expected only mask operand to be missing");
1183 OutMI.addOperand(MCOperand::createReg(RISCV::NoRegister));
1184 }
1185
1186 assert(OutMI.getNumOperands() == OutMCID.getNumOperands());
1187 return true;
1188}
1189
1190void RISCVAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
1191 if (lowerRISCVVMachineInstrToMCInst(MI, OutMI, STI))
1192 return;
1193
1194 OutMI.setOpcode(MI->getOpcode());
1195
1196 for (const MachineOperand &MO : MI->operands()) {
1197 MCOperand MCOp;
1198 if (lowerOperand(MO, MCOp))
1199 OutMI.addOperand(MCOp);
1200 }
1201}
1202
1203void RISCVAsmPrinter::emitMachineConstantPoolValue(
1204 MachineConstantPoolValue *MCPV) {
1205 auto *RCPV = static_cast<RISCVConstantPoolValue *>(MCPV);
1206 MCSymbol *MCSym;
1207
1208 if (RCPV->isGlobalValue()) {
1209 auto *GV = RCPV->getGlobalValue();
1210 MCSym = getSymbol(GV);
1211 } else {
1212 assert(RCPV->isExtSymbol() && "unrecognized constant pool type");
1213 auto Sym = RCPV->getSymbol();
1214 MCSym = GetExternalSymbolSymbol(Sym);
1215 }
1216
1217 const MCExpr *Expr = MCSymbolRefExpr::create(MCSym, OutContext);
1218 uint64_t Size = getDataLayout().getTypeAllocSize(RCPV->getType());
1219 OutStreamer->emitValue(Expr, Size);
1220}
1221
1222char RISCVAsmPrinter::ID = 0;
1223
1224INITIALIZE_PASS(RISCVAsmPrinter, "riscv-asm-printer", "RISC-V Assembly Printer",
1225 false, false)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
#define X(NUM, ENUM, NAME)
Definition ELF.h:851
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
dxil translate DXIL Translate Metadata
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
static MCOperand lowerSymbolOperand(const MachineOperand &MO, MCSymbol *Sym, const AsmPrinter &AP)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
print mir2vec MIR2Vec Vocabulary Printer Pass
Definition MIR2Vec.cpp:598
Machine Check Debug Module
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static constexpr unsigned SM(unsigned Version)
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
static bool lowerRISCVVMachineInstrToMCInst(const MachineInstr *MI, MCInst &OutMI, const RISCVSubtarget *STI)
LLVM_ABI LLVM_EXTERNAL_VISIBILITY void LLVMInitializeRISCVAsmPrinter()
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:483
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
MCContext & OutContext
This is the context for the output file that we are streaming.
Definition AsmPrinter.h:101
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, SMLoc Loc=SMLoc())
Definition MCExpr.h:343
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Context object for machine code objects.
Definition MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:188
unsigned getNumOperands() const
Definition MCInst.h:212
unsigned getOpcode() const
Definition MCInst.h:202
void addOperand(const MCOperand Op)
Definition MCInst.h:215
void setOpcode(unsigned Op)
Definition MCInst.h:201
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.
Definition MCInst.h:40
static MCOperand createExpr(const MCExpr *Val)
Definition MCInst.h:166
int64_t getImm() const
Definition MCInst.h:84
static MCOperand createReg(MCRegister Reg)
Definition MCInst.h:138
static MCOperand createImm(int64_t Val)
Definition MCInst.h:145
const MCExpr * getExpr() const
Definition MCInst.h:118
static const MCSpecifierExpr * create(const MCExpr *Expr, Spec S, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.cpp:743
Streaming machine code generation interface.
Definition MCStreamer.h:222
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
Definition MCStreamer.h:323
void emitValue(const MCExpr *Value, unsigned Size, SMLoc Loc=SMLoc())
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
MCTargetStreamer * getTargetStreamer()
Definition MCStreamer.h:333
virtual void emitCodeAlignment(Align Alignment, const MCSubtargetInfo *STI, unsigned MaxBytesToEmit=0)
Emit nops until the byte alignment ByteAlignment is reached.
virtual void switchSection(MCSection *Section, uint32_t Subsec=0)
Set the current section where code is being emitted to Section.
bool hasFeature(unsigned Feature) const
const FeatureBitset & ToggleFeature(uint64_t FB)
Toggle a feature and return the re-computed feature bits.
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:214
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
LLVM_ABI void print(raw_ostream &OS, const MCAsmInfo *MAI) const
print - Print the value to the stream OS.
Definition MCSymbol.cpp:59
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for 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.
Flags getFlags() const
Return the raw flags of the source value,.
MachineOperand class - Representation of each machine instruction operand.
const GlobalValue * getGlobal() const
int64_t getImm() 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
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
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.
static LLVM_ABI bool isSupportedExtensionFeature(StringRef Ext)
static LLVM_ABI llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseArchString(StringRef Arch, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck=true)
Parse RISC-V ISA info from arch string.
static const char * getRegisterName(MCRegister Reg)
bool requiresNTLHint(const MachineInstr &MI) const
Return true if the instruction requires an NTL hint to be emitted.
bool isRegisterReservedByUser(Register i) const override
const RISCVRegisterInfo * getRegisterInfo() const override
const RISCVInstrInfo * getInstrInfo() const override
virtual void emitDirectiveVariantCC(MCSymbol &Symbol)
void emitTargetAttributes(const MCSubtargetInfo &STI, bool EmitStackAlign)
void setFlagsFromFeatures(const MCSubtargetInfo &STI)
void setTargetABI(RISCVABI::ABI ABI)
virtual void emitDirectiveOptionArch(ArrayRef< RISCVOptionArchArg > Args)
Wrapper class representing virtual and physical registers.
Definition Register.h:20
reference emplace_back(ArgTypes &&... Args)
TargetInstrInfo - Interface to description of machine instruction set.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ SHF_ALLOC
Definition ELF.h:1249
@ SHF_GROUP
Definition ELF.h:1271
@ SHF_EXECINSTR
Definition ELF.h:1252
@ SHT_PROGBITS
Definition ELF.h:1148
@ GNU_PROPERTY_RISCV_FEATURE_1_CFI_SS
Definition ELF.h:1915
ABI getTargetABI(StringRef ABIName)
static bool hasRoundModeOp(uint64_t TSFlags)
static bool hasTWidenOp(uint64_t TSFlags)
static bool isTiedPseudo(uint64_t TSFlags)
static bool hasTKOp(uint64_t TSFlags)
static bool hasVLOp(uint64_t TSFlags)
static bool hasTMOp(uint64_t TSFlags)
static bool hasVecPolicyOp(uint64_t TSFlags)
static bool hasSEWOp(uint64_t TSFlags)
void generateMCInstSeq(int64_t Val, const MCSubtargetInfo &STI, MCRegister DestReg, SmallVectorImpl< MCInst > &Insts)
bool compress(MCInst &OutInst, const MCInst &MI, const MCSubtargetInfo &STI)
uint16_t Specifier
void emitInstruction(MCObjectStreamer &, const MCInst &Inst, const MCSubtargetInfo &STI)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
This is an optimization pass for GlobalISel generic memory operations.
bool errorToBool(Error Err)
Helper for converting an Error to a bool.
Definition Error.h:1129
@ Offset
Definition DWP.cpp:532
static const MachineMemOperand::Flags MONontemporalBit1
Target & getTheRISCV32Target()
static const MachineMemOperand::Flags MONontemporalBit0
std::string utostr(uint64_t X, bool isNeg=false)
Target & getTheRISCV64beTarget()
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
Target & getTheRISCV64Target()
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1917
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
const SubtargetFeatureKV RISCVFeatureKV[RISCV::NumSubtargetFeatures]
@ MCSA_Weak
.weak
@ MCSA_ELF_TypeFunction
.type _foo, STT_FUNC # aka @function
@ MCSA_Hidden
.hidden (ELF)
Target & getTheRISCV32beTarget()
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...
Used to provide key value pairs for feature and CPU bit flags.