LLVM 24.0.0git
AArch64AsmPrinter.cpp
Go to the documentation of this file.
1//===- AArch64AsmPrinter.cpp - AArch64 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 AArch64 assembly language.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AArch64.h"
15#include "AArch64MCInstLower.h"
17#include "AArch64RegisterInfo.h"
18#include "AArch64Subtarget.h"
27#include "llvm/ADT/DenseMap.h"
28#include "llvm/ADT/ScopeExit.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/ADT/Twine.h"
47#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/Mangler.h"
50#include "llvm/IR/Module.h"
51#include "llvm/MC/MCAsmInfo.h"
52#include "llvm/MC/MCContext.h"
53#include "llvm/MC/MCExpr.h"
54#include "llvm/MC/MCInst.h"
58#include "llvm/MC/MCStreamer.h"
59#include "llvm/MC/MCSymbol.h"
60#include "llvm/MC/MCValue.h"
70#include <cassert>
71#include <cstdint>
72#include <map>
73#include <memory>
74
75using namespace llvm;
76
77#define DEBUG_TYPE "AArch64AsmPrinter"
78
79// Doesn't count FPR128 ZCZ instructions which are handled
80// by TableGen pattern matching
81STATISTIC(NumZCZeroingInstrsFPR,
82 "Number of zero-cycle FPR zeroing instructions expanded from "
83 "canonical pseudo instructions");
84
87 "aarch64-ptrauth-auth-checks", cl::Hidden,
88 cl::values(clEnumValN(Unchecked, "none", "don't test for failure"),
89 clEnumValN(Poison, "poison", "poison on failure"),
90 clEnumValN(Trap, "trap", "trap on failure")),
91 cl::desc("Check pointer authentication auth/resign failures"));
92
93namespace {
94
95class AArch64AsmPrinter : public AsmPrinter {
96 AArch64MCInstLower MCInstLowering;
97 FaultMaps FM;
98 const AArch64Subtarget *STI;
99 bool ShouldEmitWeakSwiftAsyncExtendedFramePointerFlags = false;
100 bool PtrauthInitFini = false;
101 bool PtrauthInitFiniAddressDisc = false;
102#ifndef NDEBUG
103 unsigned InstsEmitted;
104#endif
105 bool EnableImportCallOptimization = false;
107 SectionToImportedFunctionCalls;
108 unsigned PAuthIFuncNextUniqueID = 1;
109
110public:
111 static char ID;
112
113 AArch64AsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
114 : AsmPrinter(TM, std::move(Streamer), ID),
115 MCInstLowering(OutContext, *this), FM(*this) {}
116
117 StringRef getPassName() const override { return "AArch64 Assembly Printer"; }
118
119 /// Wrapper for MCInstLowering.lowerOperand() for the
120 /// tblgen'erated pseudo lowering.
121 bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp) const {
122 return MCInstLowering.lowerOperand(MO, MCOp);
123 }
124
125 const MCExpr *lowerConstantPtrAuth(const ConstantPtrAuth &CPA) override;
126
127 const MCExpr *lowerBlockAddressConstant(const BlockAddress &BA) override;
128
129 void emitStartOfAsmFile(Module &M) override;
130 void emitJumpTableImpl(const MachineJumpTableInfo &MJTI,
131 ArrayRef<unsigned> JumpTableIndices) override;
132 std::tuple<const MCSymbol *, uint64_t, const MCSymbol *,
134 getCodeViewJumpTableInfo(int JTI, const MachineInstr *BranchInstr,
135 const MCSymbol *BranchLabel) const override;
136
137 void emitFunctionEntryLabel() override;
138
139 void emitXXStructor(const DataLayout &DL, const Constant *CV) override;
140
141 void LowerJumpTableDest(MCStreamer &OutStreamer, const MachineInstr &MI);
142
143 void LowerHardenedBRJumpTable(const MachineInstr &MI);
144
145 void LowerMOPS(MCStreamer &OutStreamer, const MachineInstr &MI);
146
147 void LowerSTACKMAP(MCStreamer &OutStreamer, StackMaps &SM,
148 const MachineInstr &MI);
149 void LowerPATCHPOINT(MCStreamer &OutStreamer, StackMaps &SM,
150 const MachineInstr &MI);
151 void LowerSTATEPOINT(MCStreamer &OutStreamer, StackMaps &SM,
152 const MachineInstr &MI);
153 void LowerFAULTING_OP(const MachineInstr &MI);
154
155 void LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI);
156 void LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr &MI);
157 void LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI);
158 void LowerPATCHABLE_EVENT_CALL(const MachineInstr &MI, bool Typed);
159
160 typedef std::tuple<unsigned, bool, uint32_t, bool, uint64_t>
161 HwasanMemaccessTuple;
162 std::map<HwasanMemaccessTuple, MCSymbol *> HwasanMemaccessSymbols;
163 void LowerKCFI_CHECK(const MachineInstr &MI);
164 void LowerHWASAN_CHECK_MEMACCESS(const MachineInstr &MI);
165 void emitHwasanMemaccessSymbols(Module &M);
166
167 void emitSled(const MachineInstr &MI, SledKind Kind);
168
169 // Returns whether Reg may be used to store sensitive temporary values when
170 // expanding PtrAuth pseudos. Some OSes may take extra care to protect a
171 // small subset of GPRs on context switches - use these registers then.
172 //
173 // If there are no preferred registers, returns true for any Reg.
174 bool isPtrauthRegSafe(Register Reg) const {
175 if (STI->isX16X17Safer())
176 return Reg == AArch64::X16 || Reg == AArch64::X17;
177
178 return true;
179 }
180
181 // Emit the sequence for BRA/BLRA (authenticate + branch/call).
182 void emitPtrauthBranch(const MachineInstr *MI);
183
184 void emitPtrauthCheckAuthenticatedValue(Register TestedReg,
185 Register ScratchReg,
188 const MCSymbol *OnFailure = nullptr);
189
190 // Check authenticated LR before tail calling.
191 void emitPtrauthTailCallHardening(const MachineInstr *TC);
192
193 struct PtrAuthSchema {
194 static PtrAuthSchema CreateImmReg(AArch64PACKey::ID Key, uint64_t IntDisc,
195 const MachineOperand &AddrDiscOp);
196 static PtrAuthSchema CreateRegReg(AArch64PACKey::ID Key, Register AddrDisc,
197 Register PCDisc);
198
200 uint64_t IntDisc;
201 Register AddrDisc;
202 bool AddrDiscIsKilled;
203 Register PCDisc;
204
205 bool addrDiscIsKilledAndNoneOf(std::initializer_list<Register> Regs) {
206 return AddrDiscIsKilled && !llvm::is_contained(Regs, AddrDisc);
207 }
208 };
209
210 // Helper for emitting AUTRELLOADPAC: increment Pointer by Addend and then by
211 // a 32-bit signed value loaded from memory. The instructions emitted are
212 //
213 // ldrsw Scratch, [Pointer, #Addend]!
214 // add Pointer, Pointer, Scratch
215 //
216 // for small Addend value, with longer sequences required for wider Addend.
217 void emitPtrauthApplyIndirectAddend(Register Pointer, Register Scratch,
218 int64_t Addend);
219
220 // Emit the sequence for AUT or AUTPAC (or their PC-blending variants).
221 // Addend is only used for AUTRELLOADPAC.
222 void emitPtrauthAuthResign(Register Pointer, Register Scratch,
223 PtrAuthSchema AuthSchema,
224 std::optional<PtrAuthSchema> SignSchema,
225 std::optional<int64_t> Addend, Value *DS);
226
227 // Emit R_AARCH64_PATCHINST, the deactivation symbol relocation. Returns true
228 // if no instruction should be emitted because the deactivation symbol is
229 // defined in the current module so this function emitted a NOP instead.
230 bool emitDeactivationSymbolRelocation(Value *DS);
231
232 // Emit the sequence for PAC.
233 void emitPtrauthSign(const MachineInstr *MI);
234
235 // Emit the sequence to compute the discriminator.
236 //
237 // The Scratch register passed to this function must be safe, as returned by
238 // isPtrauthRegSafe(ScratchReg).
239 //
240 // The returned register is either ScratchReg, AddrDisc, or XZR. Furthermore,
241 // it is guaranteed to be safe (or XZR), with the only exception of
242 // passing-through an *unmodified* unsafe AddrDisc register.
243 //
244 // If the expanded pseudo is allowed to clobber AddrDisc register, setting
245 // MayClobberAddrDisc may save one MOV instruction, provided
246 // isPtrauthRegSafe(AddrDisc) is true:
247 //
248 // mov x17, x16
249 // movk x17, #1234, lsl #48
250 // ; x16 is not used anymore
251 //
252 // can be replaced by
253 //
254 // movk x16, #1234, lsl #48
255 Register emitPtrauthDiscriminator(uint64_t Disc, Register AddrDisc,
256 Register ScratchReg,
257 bool MayClobberAddrDisc = false);
258
259 // Emit the sequence for LOADauthptrstatic
260 void LowerLOADauthptrstatic(const MachineInstr &MI);
261
262 // Emit the sequence for LOADgotPAC/MOVaddrPAC (either GOT adrp-ldr or
263 // adrp-add followed by PAC sign)
264 void LowerMOVaddrPAC(const MachineInstr &MI);
265
266 // Emit the sequence for LOADgotAUTH (load signed pointer from signed ELF GOT
267 // and authenticate it with, if FPAC bit is not set, check+trap sequence after
268 // authenticating)
269 void LowerLOADgotAUTH(const MachineInstr &MI);
270
271 void emitAddImm(MCRegister Val, int64_t Addend, MCRegister Tmp);
272 void emitAddress(MCRegister Reg, const MCExpr *Expr, MCRegister Tmp,
273 bool DSOLocal, const MCSubtargetInfo &STI);
274
275 const MCExpr *emitPAuthRelocationAsIRelative(
276 const MCExpr *Target, uint64_t Disc, AArch64PACKey::ID KeyID,
277 bool HasAddressDiversity, bool IsDSOLocal, const MCExpr *DSExpr);
278
279 /// tblgen'erated driver function for lowering simple MI->MC
280 /// pseudo instructions.
281 bool lowerPseudoInstExpansion(const MachineInstr *MI, MCInst &Inst);
282
283 // Emit Build Attributes
284 void emitAttributes(unsigned Flags, uint64_t PAuthABIPlatform,
285 uint64_t PAuthABIVersion, AArch64TargetStreamer *TS);
286
287 // Emit expansion of Compare-and-branch pseudo instructions
288 void emitCBPseudoExpansion(const MachineInstr *MI);
289
290 void EmitToStreamer(MCStreamer &S, const MCInst &Inst);
291 void EmitToStreamer(const MCInst &Inst) {
292 EmitToStreamer(*OutStreamer, Inst);
293 }
294
295 void emitInstruction(const MachineInstr *MI) override;
296
297 void emitFunctionHeaderComment() override;
298
299 void getAnalysisUsage(AnalysisUsage &AU) const override {
301 AU.setPreservesAll();
302 }
303
304 bool runOnMachineFunction(MachineFunction &MF) override {
305 if (auto *PSIW = getAnalysisIfAvailable<ProfileSummaryInfoWrapperPass>())
306 PSI = &PSIW->getPSI();
307 if (auto *SDPIW =
308 getAnalysisIfAvailable<StaticDataProfileInfoWrapperPass>())
309 SDPI = &SDPIW->getStaticDataProfileInfo();
310
311 AArch64FI = MF.getInfo<AArch64FunctionInfo>();
312 STI = &MF.getSubtarget<AArch64Subtarget>();
313
314 SetupMachineFunction(MF);
315
316 if (STI->isTargetCOFF()) {
317 bool Local = MF.getFunction().hasLocalLinkage();
320 int Type =
322
323 OutStreamer->beginCOFFSymbolDef(CurrentFnSym);
324 OutStreamer->emitCOFFSymbolStorageClass(Scl);
325 OutStreamer->emitCOFFSymbolType(Type);
326 OutStreamer->endCOFFSymbolDef();
327 }
328
329 // Emit the rest of the function body.
330 emitFunctionBody();
331
332 // Emit the XRay table for this function.
333 emitXRayTable();
334
335 // We didn't modify anything.
336 return false;
337 }
338
339 const MCExpr *lowerConstant(const Constant *CV,
340 const Constant *BaseCV = nullptr,
341 uint64_t Offset = 0) override;
342
343private:
344 void printOperand(const MachineInstr *MI, unsigned OpNum, raw_ostream &O);
345 bool printAsmMRegister(const MachineOperand &MO, char Mode, raw_ostream &O);
346 bool printAsmRegInClass(const MachineOperand &MO,
347 const TargetRegisterClass *RC, unsigned AltName,
348 raw_ostream &O);
349
350 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
351 const char *ExtraCode, raw_ostream &O) override;
352 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum,
353 const char *ExtraCode, raw_ostream &O) override;
354
355 void PrintDebugValueComment(const MachineInstr *MI, raw_ostream &OS);
356
357 void emitFunctionBodyEnd() override;
358 void emitGlobalAlias(const Module &M, const GlobalAlias &GA) override;
359
360 MCSymbol *GetCPISymbol(unsigned CPID) const override;
361 void emitEndOfAsmFile(Module &M) override;
362
363 AArch64FunctionInfo *AArch64FI = nullptr;
364
365 /// Emit the LOHs contained in AArch64FI.
366 void emitLOHs();
367
368 void emitMovXReg(Register Dest, Register Src);
369 void emitMOVZ(Register Dest, uint64_t Imm, unsigned Shift);
370 void emitMOVK(Register Dest, uint64_t Imm, unsigned Shift);
371
372 void emitAUT(AArch64PACKey::ID Key, Register Pointer, Register Disc);
373 void emitPAC(AArch64PACKey::ID Key, Register Pointer, Register Disc);
374 void emitBLRA(bool IsCall, AArch64PACKey::ID Key, Register Target,
375 Register Disc);
376
377 /// Emit instruction to set float register to zero.
378 void emitFMov0(const MachineInstr &MI);
379 void emitFMov0AsFMov(const MachineInstr &MI, Register DestReg);
380
381 using MInstToMCSymbol = std::map<const MachineInstr *, MCSymbol *>;
382
383 MInstToMCSymbol LOHInstToLabel;
384
385 bool shouldEmitWeakSwiftAsyncExtendedFramePointerFlags() const override {
386 return ShouldEmitWeakSwiftAsyncExtendedFramePointerFlags;
387 }
388
389 const MCSubtargetInfo *getIFuncMCSubtargetInfo() const override {
390 assert(STI);
391 return STI;
392 }
393 void emitMachOIFuncStubBody(Module &M, const GlobalIFunc &GI,
394 MCSymbol *LazyPointer) override;
395 void emitMachOIFuncStubHelperBody(Module &M, const GlobalIFunc &GI,
396 MCSymbol *LazyPointer) override;
397
398 /// Checks if this instruction is part of a sequence that is eligle for import
399 /// call optimization and, if so, records it to be emitted in the import call
400 /// section.
401 void recordIfImportCall(const MachineInstr *BranchInst);
402};
403
404} // end anonymous namespace
405
406// Get boolean module flag (0 or 1), treating absent flag as having value 0.
408 Metadata *Flag = M.getModuleFlag(Name);
409 if (!Flag)
410 return false;
411
412 uint64_t Value = mdconst::extract<ConstantInt>(Flag)->getZExtValue();
413 assert((Value == 0 || Value == 1) && "Boolean flag is expected, if present");
414 return Value;
415}
416
417void AArch64AsmPrinter::emitStartOfAsmFile(Module &M) {
418 const Triple &TT = TM.getTargetTriple();
419
420 if (TT.isOSBinFormatCOFF()) {
421 emitCOFFFeatureSymbol(M);
422 emitCOFFReplaceableFunctionData(M);
423
424 if (M.getModuleFlag("import-call-optimization"))
425 EnableImportCallOptimization = true;
426 }
427
428 PtrauthInitFini = getOptionalBooleanModuleFlag(M, "ptrauth-init-fini");
429 PtrauthInitFiniAddressDisc = getOptionalBooleanModuleFlag(
430 M, "ptrauth-init-fini-address-discrimination");
431
432 if (!TT.isOSBinFormatELF())
433 return;
434
435 // For emitting build attributes and .note.gnu.property section
436 auto *TS =
437 static_cast<AArch64TargetStreamer *>(OutStreamer->getTargetStreamer());
438 // Assemble feature flags that may require creation of build attributes and a
439 // note section.
440 unsigned BAFlags = 0;
441 unsigned GNUFlags = 0;
442 if (const auto *BTE = mdconst::extract_or_null<ConstantInt>(
443 M.getModuleFlag("branch-target-enforcement"))) {
444 if (!BTE->isZero()) {
445 BAFlags |= AArch64BuildAttributes::FeatureAndBitsFlag::Feature_BTI_Flag;
447 }
448 }
449
450 if (const auto *GCS = mdconst::extract_or_null<ConstantInt>(
451 M.getModuleFlag("guarded-control-stack"))) {
452 if (!GCS->isZero()) {
453 BAFlags |= AArch64BuildAttributes::FeatureAndBitsFlag::Feature_GCS_Flag;
455 }
456 }
457
458 if (const auto *Sign = mdconst::extract_or_null<ConstantInt>(
459 M.getModuleFlag("sign-return-address"))) {
460 if (!Sign->isZero()) {
461 BAFlags |= AArch64BuildAttributes::FeatureAndBitsFlag::Feature_PAC_Flag;
463 }
464 }
465
466 uint64_t PAuthABIPlatform = -1;
467 if (const auto *PAP = mdconst::extract_or_null<ConstantInt>(
468 M.getModuleFlag("aarch64-elf-pauthabi-platform"))) {
469 PAuthABIPlatform = PAP->getZExtValue();
470 }
471
472 uint64_t PAuthABIVersion = -1;
473 if (const auto *PAV = mdconst::extract_or_null<ConstantInt>(
474 M.getModuleFlag("aarch64-elf-pauthabi-version"))) {
475 PAuthABIVersion = PAV->getZExtValue();
476 }
477
478 // For LLVM_LINUX experimental platform, version value of 0 means no PAuth
479 // support. Do not emit corresponding PAuthABI GNU property note and AArch64
480 // build attributes for this case to keep Linux binaries not using PAuth
481 // unaffected.
482 if (PAuthABIPlatform == ELF::AARCH64_PAUTH_PLATFORM_LLVM_LINUX &&
483 PAuthABIVersion == 0) {
484 PAuthABIPlatform = uint64_t(-1);
485 PAuthABIVersion = uint64_t(-1);
486 }
487
488 // Emit AArch64 Build Attributes
489 emitAttributes(BAFlags, PAuthABIPlatform, PAuthABIVersion, TS);
490 // Emit a .note.gnu.property section with the flags.
491 TS->emitNoteSection(GNUFlags, PAuthABIPlatform, PAuthABIVersion);
492}
493
494void AArch64AsmPrinter::emitFunctionHeaderComment() {
495 const AArch64FunctionInfo *FI = MF->getInfo<AArch64FunctionInfo>();
496 std::optional<std::string> OutlinerString = FI->getOutliningStyle();
497 if (OutlinerString != std::nullopt)
498 OutStreamer->getCommentOS() << ' ' << OutlinerString;
499}
500
501void AArch64AsmPrinter::LowerPATCHABLE_FUNCTION_ENTER(const MachineInstr &MI)
502{
503 const Function &F = MF->getFunction();
504 if (F.hasFnAttribute("patchable-function-entry")) {
505 unsigned Num;
506 if (F.getFnAttribute("patchable-function-entry")
507 .getValueAsString()
508 .getAsInteger(10, Num))
509 return;
510 emitNops(Num);
511 return;
512 }
513
514 emitSled(MI, SledKind::FUNCTION_ENTER);
515}
516
517void AArch64AsmPrinter::LowerPATCHABLE_FUNCTION_EXIT(const MachineInstr &MI) {
518 emitSled(MI, SledKind::FUNCTION_EXIT);
519}
520
521void AArch64AsmPrinter::LowerPATCHABLE_TAIL_CALL(const MachineInstr &MI) {
522 emitSled(MI, SledKind::TAIL_CALL);
523}
524
525void AArch64AsmPrinter::emitSled(const MachineInstr &MI, SledKind Kind) {
526 static const int8_t NoopsInSledCount = 7;
527 // We want to emit the following pattern:
528 //
529 // .Lxray_sled_N:
530 // ALIGN
531 // B #32
532 // ; 7 NOP instructions (28 bytes)
533 // .tmpN
534 //
535 // We need the 28 bytes (7 instructions) because at runtime, we'd be patching
536 // over the full 32 bytes (8 instructions) with the following pattern:
537 //
538 // STP X0, X30, [SP, #-16]! ; push X0 and the link register to the stack
539 // LDR W17, #12 ; W17 := function ID
540 // LDR X16,#12 ; X16 := addr of __xray_FunctionEntry or __xray_FunctionExit
541 // BLR X16 ; call the tracing trampoline
542 // ;DATA: 32 bits of function ID
543 // ;DATA: lower 32 bits of the address of the trampoline
544 // ;DATA: higher 32 bits of the address of the trampoline
545 // LDP X0, X30, [SP], #16 ; pop X0 and the link register from the stack
546 //
547 OutStreamer->emitCodeAlignment(Align(4), getSubtargetInfo());
548 auto CurSled = OutContext.createTempSymbol("xray_sled_", true);
549 OutStreamer->emitLabel(CurSled);
550 auto Target = OutContext.createTempSymbol();
551
552 // Emit "B #32" instruction, which jumps over the next 28 bytes.
553 // The operand has to be the number of 4-byte instructions to jump over,
554 // including the current instruction.
555 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::B).addImm(8));
556
557 for (int8_t I = 0; I < NoopsInSledCount; I++)
558 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::NOP));
559
560 OutStreamer->emitLabel(Target);
561 recordSled(CurSled, MI, Kind, 2);
562}
563
564void AArch64AsmPrinter::emitAttributes(unsigned Flags,
565 uint64_t PAuthABIPlatform,
566 uint64_t PAuthABIVersion,
567 AArch64TargetStreamer *TS) {
568
569 PAuthABIPlatform = (uint64_t(-1) == PAuthABIPlatform) ? 0 : PAuthABIPlatform;
570 PAuthABIVersion = (uint64_t(-1) == PAuthABIVersion) ? 0 : PAuthABIVersion;
571
572 if (PAuthABIPlatform || PAuthABIVersion) {
576 AArch64BuildAttributes::SubsectionOptional::REQUIRED,
577 AArch64BuildAttributes::SubsectionType::ULEB128);
581 PAuthABIPlatform, "");
585 "");
586 }
587
588 unsigned BTIValue =
590 unsigned PACValue =
592 unsigned GCSValue =
594
595 if (BTIValue || PACValue || GCSValue) {
599 AArch64BuildAttributes::SubsectionOptional::OPTIONAL,
600 AArch64BuildAttributes::SubsectionType::ULEB128);
610 }
611}
612
613// Emit the following code for Intrinsic::{xray_customevent,xray_typedevent}
614// (built-in functions __xray_customevent/__xray_typedevent).
615//
616// .Lxray_event_sled_N:
617// b 1f
618// save x0 and x1 (and also x2 for TYPED_EVENT_CALL)
619// set up x0 and x1 (and also x2 for TYPED_EVENT_CALL)
620// bl __xray_CustomEvent or __xray_TypedEvent
621// restore x0 and x1 (and also x2 for TYPED_EVENT_CALL)
622// 1:
623//
624// There are 6 instructions for EVENT_CALL and 9 for TYPED_EVENT_CALL.
625//
626// Then record a sled of kind CUSTOM_EVENT or TYPED_EVENT.
627// After patching, b .+N will become a nop.
628void AArch64AsmPrinter::LowerPATCHABLE_EVENT_CALL(const MachineInstr &MI,
629 bool Typed) {
630 auto &O = *OutStreamer;
631 MCSymbol *CurSled = OutContext.createTempSymbol("xray_sled_", true);
632 O.emitLabel(CurSled);
633 bool MachO = TM.getTargetTriple().isOSBinFormatMachO();
634 auto *Sym = MCSymbolRefExpr::create(
635 OutContext.getOrCreateSymbol(
636 Twine(MachO ? "_" : "") +
637 (Typed ? "__xray_TypedEvent" : "__xray_CustomEvent")),
638 OutContext);
639 if (Typed) {
640 O.AddComment("Begin XRay typed event");
641 EmitToStreamer(O, MCInstBuilder(AArch64::B).addImm(9));
642 EmitToStreamer(O, MCInstBuilder(AArch64::STPXpre)
643 .addReg(AArch64::SP)
644 .addReg(AArch64::X0)
645 .addReg(AArch64::X1)
646 .addReg(AArch64::SP)
647 .addImm(-4));
648 EmitToStreamer(O, MCInstBuilder(AArch64::STRXui)
649 .addReg(AArch64::X2)
650 .addReg(AArch64::SP)
651 .addImm(2));
652 emitMovXReg(AArch64::X0, MI.getOperand(0).getReg());
653 emitMovXReg(AArch64::X1, MI.getOperand(1).getReg());
654 emitMovXReg(AArch64::X2, MI.getOperand(2).getReg());
655 EmitToStreamer(O, MCInstBuilder(AArch64::BL).addExpr(Sym));
656 EmitToStreamer(O, MCInstBuilder(AArch64::LDRXui)
657 .addReg(AArch64::X2)
658 .addReg(AArch64::SP)
659 .addImm(2));
660 O.AddComment("End XRay typed event");
661 EmitToStreamer(O, MCInstBuilder(AArch64::LDPXpost)
662 .addReg(AArch64::SP)
663 .addReg(AArch64::X0)
664 .addReg(AArch64::X1)
665 .addReg(AArch64::SP)
666 .addImm(4));
667
668 recordSled(CurSled, MI, SledKind::TYPED_EVENT, 2);
669 } else {
670 O.AddComment("Begin XRay custom event");
671 EmitToStreamer(O, MCInstBuilder(AArch64::B).addImm(6));
672 EmitToStreamer(O, MCInstBuilder(AArch64::STPXpre)
673 .addReg(AArch64::SP)
674 .addReg(AArch64::X0)
675 .addReg(AArch64::X1)
676 .addReg(AArch64::SP)
677 .addImm(-2));
678 emitMovXReg(AArch64::X0, MI.getOperand(0).getReg());
679 emitMovXReg(AArch64::X1, MI.getOperand(1).getReg());
680 EmitToStreamer(O, MCInstBuilder(AArch64::BL).addExpr(Sym));
681 O.AddComment("End XRay custom event");
682 EmitToStreamer(O, MCInstBuilder(AArch64::LDPXpost)
683 .addReg(AArch64::SP)
684 .addReg(AArch64::X0)
685 .addReg(AArch64::X1)
686 .addReg(AArch64::SP)
687 .addImm(2));
688
689 recordSled(CurSled, MI, SledKind::CUSTOM_EVENT, 2);
690 }
691}
692
693void AArch64AsmPrinter::LowerKCFI_CHECK(const MachineInstr &MI) {
694 Register AddrReg = MI.getOperand(0).getReg();
695 assert(std::next(MI.getIterator())->isCall() &&
696 "KCFI_CHECK not followed by a call instruction");
697 assert(std::next(MI.getIterator())->getOperand(0).getReg() == AddrReg &&
698 "KCFI_CHECK call target doesn't match call operand");
699
700 // Default to using the intra-procedure-call temporary registers for
701 // comparing the hashes.
702 unsigned ScratchRegs[] = {AArch64::W16, AArch64::W17};
703 if (AddrReg == AArch64::XZR) {
704 // Checking XZR makes no sense. Instead of emitting a load, zero
705 // ScratchRegs[0] and use it for the ESR AddrIndex below.
706 AddrReg = getXRegFromWReg(ScratchRegs[0]);
707 emitMovXReg(AddrReg, AArch64::XZR);
708 } else {
709 // If one of the scratch registers is used for the call target (e.g.
710 // with AArch64::TCRETURNriBTI), we can clobber another caller-saved
711 // temporary register instead (in this case, AArch64::W9) as the check
712 // is immediately followed by the call instruction.
713 for (auto &Reg : ScratchRegs) {
714 if (Reg == getWRegFromXReg(AddrReg)) {
715 Reg = AArch64::W9;
716 break;
717 }
718 }
719 assert(ScratchRegs[0] != AddrReg && ScratchRegs[1] != AddrReg &&
720 "Invalid scratch registers for KCFI_CHECK");
721
722 // Adjust the offset for patchable-function-prefix. This assumes that
723 // patchable-function-prefix is the same for all functions.
724 int64_t PrefixNops =
725 MI.getMF()->getFunction().getFnAttributeAsParsedInteger(
726 "patchable-function-prefix");
727
728 // Load the target function type hash.
729 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::LDURWi)
730 .addReg(ScratchRegs[0])
731 .addReg(AddrReg)
732 .addImm(-(PrefixNops * 4 + 4)));
733 }
734
735 // Load the expected type hash.
736 const int64_t Type = MI.getOperand(1).getImm();
737 emitMOVK(ScratchRegs[1], Type & 0xFFFF, 0);
738 emitMOVK(ScratchRegs[1], (Type >> 16) & 0xFFFF, 16);
739
740 // Compare the hashes and trap if there's a mismatch.
741 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::SUBSWrs)
742 .addReg(AArch64::WZR)
743 .addReg(ScratchRegs[0])
744 .addReg(ScratchRegs[1])
745 .addImm(0));
746
747 MCSymbol *Pass = OutContext.createTempSymbol();
748 EmitToStreamer(*OutStreamer,
749 MCInstBuilder(AArch64::Bcc)
750 .addImm(AArch64CC::EQ)
751 .addExpr(MCSymbolRefExpr::create(Pass, OutContext)));
752
753 // The base ESR is 0x8000 and the register information is encoded in bits
754 // 0-9 as follows:
755 // - 0-4: n, where the register Xn contains the target address
756 // - 5-9: m, where the register Wm contains the expected type hash
757 // Where n, m are in [0, 30].
758 unsigned TypeIndex = ScratchRegs[1] - AArch64::W0;
759 unsigned AddrIndex;
760 switch (AddrReg) {
761 default:
762 AddrIndex = AddrReg - AArch64::X0;
763 break;
764 case AArch64::FP:
765 AddrIndex = 29;
766 break;
767 case AArch64::LR:
768 AddrIndex = 30;
769 break;
770 }
771
772 assert(AddrIndex < 31 && TypeIndex < 31);
773
774 unsigned ESR = 0x8000 | ((TypeIndex & 31) << 5) | (AddrIndex & 31);
775 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::BRK).addImm(ESR));
776 OutStreamer->emitLabel(Pass);
777}
778
779void AArch64AsmPrinter::LowerHWASAN_CHECK_MEMACCESS(const MachineInstr &MI) {
780 Register Reg = MI.getOperand(0).getReg();
781
782 // The HWASan pass won't emit a CHECK_MEMACCESS intrinsic with a pointer
783 // statically known to be zero. However, conceivably, the HWASan pass may
784 // encounter a "cannot currently statically prove to be null" pointer (and is
785 // therefore unable to omit the intrinsic) that later optimization passes
786 // convert into a statically known-null pointer.
787 if (Reg == AArch64::XZR)
788 return;
789
790 bool IsShort =
791 ((MI.getOpcode() == AArch64::HWASAN_CHECK_MEMACCESS_SHORTGRANULES) ||
792 (MI.getOpcode() ==
793 AArch64::HWASAN_CHECK_MEMACCESS_SHORTGRANULES_FIXEDSHADOW));
794 uint32_t AccessInfo = MI.getOperand(1).getImm();
795 bool IsFixedShadow =
796 ((MI.getOpcode() == AArch64::HWASAN_CHECK_MEMACCESS_FIXEDSHADOW) ||
797 (MI.getOpcode() ==
798 AArch64::HWASAN_CHECK_MEMACCESS_SHORTGRANULES_FIXEDSHADOW));
799 uint64_t FixedShadowOffset = IsFixedShadow ? MI.getOperand(2).getImm() : 0;
800
801 MCSymbol *&Sym = HwasanMemaccessSymbols[HwasanMemaccessTuple(
802 Reg, IsShort, AccessInfo, IsFixedShadow, FixedShadowOffset)];
803 if (!Sym) {
804 // FIXME: Make this work on non-ELF.
805 if (!TM.getTargetTriple().isOSBinFormatELF())
806 report_fatal_error("llvm.hwasan.check.memaccess only supported on ELF");
807
808 std::string SymName = "__hwasan_check_x" + utostr(Reg - AArch64::X0) + "_" +
809 utostr(AccessInfo);
810 if (IsFixedShadow)
811 SymName += "_fixed_" + utostr(FixedShadowOffset);
812 if (IsShort)
813 SymName += "_short_v2";
814 Sym = OutContext.getOrCreateSymbol(SymName);
815 }
816
817 EmitToStreamer(*OutStreamer,
818 MCInstBuilder(AArch64::BL)
819 .addExpr(MCSymbolRefExpr::create(Sym, OutContext)));
820}
821
822void AArch64AsmPrinter::emitHwasanMemaccessSymbols(Module &M) {
823 if (HwasanMemaccessSymbols.empty())
824 return;
825
826 const Triple &TT = TM.getTargetTriple();
827 assert(TT.isOSBinFormatELF());
828 // AArch64Subtarget is huge, so heap allocate it so we don't run out of stack
829 // space.
830 auto STI = std::make_unique<AArch64Subtarget>(
831 TT, TM.getTargetCPU(), TM.getTargetCPU(), TM.getTargetFeatureString(), TM,
832 true);
833 this->STI = STI.get();
834
835 MCSymbol *HwasanTagMismatchV1Sym =
836 OutContext.getOrCreateSymbol("__hwasan_tag_mismatch");
837 MCSymbol *HwasanTagMismatchV2Sym =
838 OutContext.getOrCreateSymbol("__hwasan_tag_mismatch_v2");
839
840 const MCSymbolRefExpr *HwasanTagMismatchV1Ref =
841 MCSymbolRefExpr::create(HwasanTagMismatchV1Sym, OutContext);
842 const MCSymbolRefExpr *HwasanTagMismatchV2Ref =
843 MCSymbolRefExpr::create(HwasanTagMismatchV2Sym, OutContext);
844
845 for (auto &P : HwasanMemaccessSymbols) {
846 unsigned Reg = std::get<0>(P.first);
847 bool IsShort = std::get<1>(P.first);
848 uint32_t AccessInfo = std::get<2>(P.first);
849 bool IsFixedShadow = std::get<3>(P.first);
850 uint64_t FixedShadowOffset = std::get<4>(P.first);
851 const MCSymbolRefExpr *HwasanTagMismatchRef =
852 IsShort ? HwasanTagMismatchV2Ref : HwasanTagMismatchV1Ref;
853 MCSymbol *Sym = P.second;
854
855 bool HasMatchAllTag =
856 (AccessInfo >> HWASanAccessInfo::HasMatchAllShift) & 1;
857 uint8_t MatchAllTag =
858 (AccessInfo >> HWASanAccessInfo::MatchAllShift) & 0xff;
859 unsigned Size =
860 1 << ((AccessInfo >> HWASanAccessInfo::AccessSizeShift) & 0xf);
861 bool CompileKernel =
862 (AccessInfo >> HWASanAccessInfo::CompileKernelShift) & 1;
863
864 OutStreamer->switchSection(OutContext.getELFSection(
865 ".text.hot", ELF::SHT_PROGBITS,
867 /*IsComdat=*/true));
868
869 OutStreamer->emitSymbolAttribute(Sym, MCSA_ELF_TypeFunction);
870 OutStreamer->emitSymbolAttribute(Sym, MCSA_Weak);
871 OutStreamer->emitSymbolAttribute(Sym, MCSA_Hidden);
872 OutStreamer->emitLabel(Sym);
873
874 EmitToStreamer(MCInstBuilder(AArch64::SBFMXri)
875 .addReg(AArch64::X16)
876 .addReg(Reg)
877 .addImm(4)
878 .addImm(55));
879
880 if (IsFixedShadow) {
881 // Aarch64 makes it difficult to embed large constants in the code.
882 // Fortuitously, kShadowBaseAlignment == 32, so we use the 32-bit
883 // left-shift option in the MOV instruction. Combined with the 16-bit
884 // immediate, this is enough to represent any offset up to 2**48.
885 emitMOVZ(AArch64::X17, FixedShadowOffset >> 32, 32);
886 EmitToStreamer(MCInstBuilder(AArch64::LDRBBroX)
887 .addReg(AArch64::W16)
888 .addReg(AArch64::X17)
889 .addReg(AArch64::X16)
890 .addImm(0)
891 .addImm(0));
892 } else {
893 EmitToStreamer(MCInstBuilder(AArch64::LDRBBroX)
894 .addReg(AArch64::W16)
895 .addReg(IsShort ? AArch64::X20 : AArch64::X9)
896 .addReg(AArch64::X16)
897 .addImm(0)
898 .addImm(0));
899 }
900
901 EmitToStreamer(MCInstBuilder(AArch64::SUBSXrs)
902 .addReg(AArch64::XZR)
903 .addReg(AArch64::X16)
904 .addReg(Reg)
906 MCSymbol *HandleMismatchOrPartialSym = OutContext.createTempSymbol();
907 EmitToStreamer(MCInstBuilder(AArch64::Bcc)
908 .addImm(AArch64CC::NE)
910 HandleMismatchOrPartialSym, OutContext)));
911 MCSymbol *ReturnSym = OutContext.createTempSymbol();
912 OutStreamer->emitLabel(ReturnSym);
913 EmitToStreamer(MCInstBuilder(AArch64::RET).addReg(AArch64::LR));
914 OutStreamer->emitLabel(HandleMismatchOrPartialSym);
915
916 if (HasMatchAllTag) {
917 EmitToStreamer(MCInstBuilder(AArch64::UBFMXri)
918 .addReg(AArch64::X17)
919 .addReg(Reg)
920 .addImm(56)
921 .addImm(63));
922 EmitToStreamer(MCInstBuilder(AArch64::SUBSXri)
923 .addReg(AArch64::XZR)
924 .addReg(AArch64::X17)
925 .addImm(MatchAllTag)
926 .addImm(0));
927 EmitToStreamer(
928 MCInstBuilder(AArch64::Bcc)
929 .addImm(AArch64CC::EQ)
930 .addExpr(MCSymbolRefExpr::create(ReturnSym, OutContext)));
931 }
932
933 if (IsShort) {
934 EmitToStreamer(MCInstBuilder(AArch64::SUBSWri)
935 .addReg(AArch64::WZR)
936 .addReg(AArch64::W16)
937 .addImm(15)
938 .addImm(0));
939 MCSymbol *HandleMismatchSym = OutContext.createTempSymbol();
940 EmitToStreamer(
941 MCInstBuilder(AArch64::Bcc)
942 .addImm(AArch64CC::HI)
943 .addExpr(MCSymbolRefExpr::create(HandleMismatchSym, OutContext)));
944
945 EmitToStreamer(MCInstBuilder(AArch64::ANDXri)
946 .addReg(AArch64::X17)
947 .addReg(Reg)
948 .addImm(AArch64_AM::encodeLogicalImmediate(0xf, 64)));
949 if (Size != 1)
950 EmitToStreamer(MCInstBuilder(AArch64::ADDXri)
951 .addReg(AArch64::X17)
952 .addReg(AArch64::X17)
953 .addImm(Size - 1)
954 .addImm(0));
955 EmitToStreamer(MCInstBuilder(AArch64::SUBSWrs)
956 .addReg(AArch64::WZR)
957 .addReg(AArch64::W16)
958 .addReg(AArch64::W17)
959 .addImm(0));
960 EmitToStreamer(
961 MCInstBuilder(AArch64::Bcc)
962 .addImm(AArch64CC::LS)
963 .addExpr(MCSymbolRefExpr::create(HandleMismatchSym, OutContext)));
964
965 EmitToStreamer(MCInstBuilder(AArch64::ORRXri)
966 .addReg(AArch64::X16)
967 .addReg(Reg)
968 .addImm(AArch64_AM::encodeLogicalImmediate(0xf, 64)));
969 EmitToStreamer(MCInstBuilder(AArch64::LDRBBui)
970 .addReg(AArch64::W16)
971 .addReg(AArch64::X16)
972 .addImm(0));
973 EmitToStreamer(
974 MCInstBuilder(AArch64::SUBSXrs)
975 .addReg(AArch64::XZR)
976 .addReg(AArch64::X16)
977 .addReg(Reg)
979 EmitToStreamer(
980 MCInstBuilder(AArch64::Bcc)
981 .addImm(AArch64CC::EQ)
982 .addExpr(MCSymbolRefExpr::create(ReturnSym, OutContext)));
983
984 OutStreamer->emitLabel(HandleMismatchSym);
985 }
986
987 EmitToStreamer(MCInstBuilder(AArch64::STPXpre)
988 .addReg(AArch64::SP)
989 .addReg(AArch64::X0)
990 .addReg(AArch64::X1)
991 .addReg(AArch64::SP)
992 .addImm(-32));
993 EmitToStreamer(MCInstBuilder(AArch64::STPXi)
994 .addReg(AArch64::FP)
995 .addReg(AArch64::LR)
996 .addReg(AArch64::SP)
997 .addImm(29));
998
999 if (Reg != AArch64::X0)
1000 emitMovXReg(AArch64::X0, Reg);
1001 emitMOVZ(AArch64::X1, AccessInfo & HWASanAccessInfo::RuntimeMask, 0);
1002
1003 if (CompileKernel) {
1004 // The Linux kernel's dynamic loader doesn't support GOT relative
1005 // relocations, but it doesn't support late binding either, so just call
1006 // the function directly.
1007 EmitToStreamer(MCInstBuilder(AArch64::B).addExpr(HwasanTagMismatchRef));
1008 } else {
1009 // Intentionally load the GOT entry and branch to it, rather than possibly
1010 // late binding the function, which may clobber the registers before we
1011 // have a chance to save them.
1012 EmitToStreamer(MCInstBuilder(AArch64::ADRP)
1013 .addReg(AArch64::X16)
1014 .addExpr(MCSpecifierExpr::create(HwasanTagMismatchRef,
1016 OutContext)));
1017 EmitToStreamer(MCInstBuilder(AArch64::LDRXui)
1018 .addReg(AArch64::X16)
1019 .addReg(AArch64::X16)
1020 .addExpr(MCSpecifierExpr::create(HwasanTagMismatchRef,
1022 OutContext)));
1023 EmitToStreamer(MCInstBuilder(AArch64::BR).addReg(AArch64::X16));
1024 }
1025 }
1026 this->STI = nullptr;
1027}
1028
1029static void emitAuthenticatedPointer(MCStreamer &OutStreamer,
1030 MCSymbol *StubLabel,
1031 const MCExpr *StubAuthPtrRef) {
1032 // sym$auth_ptr$key$disc:
1033 OutStreamer.emitLabel(StubLabel);
1034 OutStreamer.emitValue(StubAuthPtrRef, /*size=*/8);
1035}
1036
1037void AArch64AsmPrinter::emitEndOfAsmFile(Module &M) {
1038 emitHwasanMemaccessSymbols(M);
1039
1040 const Triple &TT = TM.getTargetTriple();
1041 if (TT.isOSBinFormatMachO()) {
1042 // Output authenticated pointers as indirect symbols, if we have any.
1043 MachineModuleInfoMachO &MMIMacho =
1044 MMI->getObjFileInfo<MachineModuleInfoMachO>();
1045
1046 auto Stubs = MMIMacho.getAuthGVStubList();
1047
1048 if (!Stubs.empty()) {
1049 // Switch to the "__auth_ptr" section.
1050 OutStreamer->switchSection(
1051 OutContext.getMachOSection("__DATA", "__auth_ptr", MachO::S_REGULAR,
1053 emitAlignment(Align(8));
1054
1055 for (const auto &Stub : Stubs)
1056 emitAuthenticatedPointer(*OutStreamer, Stub.first, Stub.second);
1057
1058 OutStreamer->addBlankLine();
1059 }
1060
1061 // Funny Darwin hack: This flag tells the linker that no global symbols
1062 // contain code that falls through to other global symbols (e.g. the obvious
1063 // implementation of multiple entry points). If this doesn't occur, the
1064 // linker can safely perform dead code stripping. Since LLVM never
1065 // generates code that does this, it is always safe to set.
1066 OutStreamer->emitSubsectionsViaSymbols();
1067 }
1068
1069 if (TT.isOSBinFormatELF()) {
1070 // Output authenticated pointers as indirect symbols, if we have any.
1071 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
1072
1073 auto Stubs = MMIELF.getAuthGVStubList();
1074
1075 if (!Stubs.empty()) {
1076 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1077 OutStreamer->switchSection(TLOF.getDataSection());
1078 emitAlignment(Align(8));
1079
1080 for (const auto &Stub : Stubs)
1081 emitAuthenticatedPointer(*OutStreamer, Stub.first, Stub.second);
1082
1083 OutStreamer->addBlankLine();
1084 }
1085
1086 // With signed ELF GOT enabled, the linker looks at the symbol type to
1087 // choose between keys IA (for STT_FUNC) and DA (for other types). Symbols
1088 // for functions not defined in the module have STT_NOTYPE type by default.
1089 // This makes linker to emit signing schema with DA key (instead of IA) for
1090 // corresponding R_AARCH64_AUTH_GLOB_DAT dynamic reloc. To avoid that, force
1091 // all function symbols used in the module to have STT_FUNC type. See
1092 // https://github.com/ARM-software/abi-aa/blob/main/pauthabielf64/pauthabielf64.rst#default-signing-schema
1093 const auto *PtrAuthELFGOTFlag = mdconst::extract_or_null<ConstantInt>(
1094 M.getModuleFlag("ptrauth-elf-got"));
1095 if (PtrAuthELFGOTFlag && PtrAuthELFGOTFlag->getZExtValue() == 1)
1096 for (const GlobalValue &GV : M.global_values())
1097 if (!GV.use_empty() && isa<Function>(GV) &&
1098 !GV.getName().starts_with("llvm."))
1099 OutStreamer->emitSymbolAttribute(getSymbol(&GV),
1101 }
1102
1103 // Emit stack and fault map information.
1105
1106 // If import call optimization is enabled, emit the appropriate section.
1107 // We do this whether or not we recorded any import calls.
1108 if (EnableImportCallOptimization && TT.isOSBinFormatCOFF()) {
1109 OutStreamer->switchSection(getObjFileLowering().getImportCallSection());
1110
1111 // Section always starts with some magic.
1112 constexpr char ImpCallMagic[12] = "Imp_Call_V1";
1113 OutStreamer->emitBytes(StringRef{ImpCallMagic, sizeof(ImpCallMagic)});
1114
1115 // Layout of this section is:
1116 // Per section that contains calls to imported functions:
1117 // uint32_t SectionSize: Size in bytes for information in this section.
1118 // uint32_t Section Number
1119 // Per call to imported function in section:
1120 // uint32_t Kind: the kind of imported function.
1121 // uint32_t BranchOffset: the offset of the branch instruction in its
1122 // parent section.
1123 // uint32_t TargetSymbolId: the symbol id of the called function.
1124 for (auto &[Section, CallsToImportedFuncs] :
1125 SectionToImportedFunctionCalls) {
1126 unsigned SectionSize =
1127 sizeof(uint32_t) * (2 + 3 * CallsToImportedFuncs.size());
1128 OutStreamer->emitInt32(SectionSize);
1129 OutStreamer->emitCOFFSecNumber(Section->getBeginSymbol());
1130 for (auto &[CallsiteSymbol, CalledSymbol] : CallsToImportedFuncs) {
1131 // Kind is always IMAGE_REL_ARM64_DYNAMIC_IMPORT_CALL (0x13).
1132 OutStreamer->emitInt32(0x13);
1133 OutStreamer->emitCOFFSecOffset(CallsiteSymbol);
1134 OutStreamer->emitCOFFSymbolIndex(CalledSymbol);
1135 }
1136 }
1137 }
1138}
1139
1140void AArch64AsmPrinter::emitLOHs() {
1142
1143 for (const auto &D : AArch64FI->getLOHContainer()) {
1144 for (const MachineInstr *MI : D.getArgs()) {
1145 MInstToMCSymbol::iterator LabelIt = LOHInstToLabel.find(MI);
1146 assert(LabelIt != LOHInstToLabel.end() &&
1147 "Label hasn't been inserted for LOH related instruction");
1148 MCArgs.push_back(LabelIt->second);
1149 }
1150 OutStreamer->emitLOHDirective(D.getKind(), MCArgs);
1151 MCArgs.clear();
1152 }
1153}
1154
1155void AArch64AsmPrinter::emitFunctionBodyEnd() {
1156 if (!AArch64FI->getLOHRelated().empty())
1157 emitLOHs();
1158}
1159
1160/// GetCPISymbol - Return the symbol for the specified constant pool entry.
1161MCSymbol *AArch64AsmPrinter::GetCPISymbol(unsigned CPID) const {
1162 // Darwin uses a linker-private symbol name for constant-pools (to
1163 // avoid addends on the relocation?), ELF has no such concept and
1164 // uses a normal private symbol.
1165 if (!getDataLayout().getLinkerPrivateGlobalPrefix().empty())
1166 return OutContext.getOrCreateSymbol(
1167 Twine(getDataLayout().getLinkerPrivateGlobalPrefix()) + "CPI" +
1168 Twine(getFunctionNumber()) + "_" + Twine(CPID));
1169
1170 return AsmPrinter::GetCPISymbol(CPID);
1171}
1172
1173void AArch64AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNum,
1174 raw_ostream &O) {
1175 const MachineOperand &MO = MI->getOperand(OpNum);
1176 switch (MO.getType()) {
1177 default:
1178 llvm_unreachable("<unknown operand type>");
1180 Register Reg = MO.getReg();
1182 assert(!MO.getSubReg() && "Subregs should be eliminated!");
1184 break;
1185 }
1187 O << MO.getImm();
1188 break;
1189 }
1191 PrintSymbolOperand(MO, O);
1192 break;
1193 }
1195 MCSymbol *Sym = GetBlockAddressSymbol(MO.getBlockAddress());
1196 Sym->print(O, MAI);
1197 break;
1198 }
1199 }
1200}
1201
1202bool AArch64AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode,
1203 raw_ostream &O) {
1204 Register Reg = MO.getReg();
1205 switch (Mode) {
1206 default:
1207 return true; // Unknown mode.
1208 case 'w':
1210 break;
1211 case 'x':
1213 break;
1214 case 't':
1216 break;
1217 }
1218
1220 return false;
1221}
1222
1223// Prints the register in MO using class RC using the offset in the
1224// new register class. This should not be used for cross class
1225// printing.
1226bool AArch64AsmPrinter::printAsmRegInClass(const MachineOperand &MO,
1227 const TargetRegisterClass *RC,
1228 unsigned AltName, raw_ostream &O) {
1229 assert(MO.isReg() && "Should only get here with a register!");
1230 const TargetRegisterInfo *RI = STI->getRegisterInfo();
1231 Register Reg = MO.getReg();
1232 MCRegister RegToPrint = RC->getRegister(RI->getEncodingValue(Reg));
1233 if (!RI->regsOverlap(RegToPrint, Reg))
1234 return true;
1235 O << AArch64InstPrinter::getRegisterName(RegToPrint, AltName);
1236 return false;
1237}
1238
1239bool AArch64AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
1240 const char *ExtraCode, raw_ostream &O) {
1241 const MachineOperand &MO = MI->getOperand(OpNum);
1242
1243 // First try the generic code, which knows about modifiers like 'c' and 'n'.
1244 if (!AsmPrinter::PrintAsmOperand(MI, OpNum, ExtraCode, O))
1245 return false;
1246
1247 // Does this asm operand have a single letter operand modifier?
1248 if (ExtraCode && ExtraCode[0]) {
1249 if (ExtraCode[1] != 0)
1250 return true; // Unknown modifier.
1251
1252 switch (ExtraCode[0]) {
1253 default:
1254 return true; // Unknown modifier.
1255 case 'w': // Print W register
1256 case 'x': // Print X register
1257 if (MO.isReg())
1258 return printAsmMRegister(MO, ExtraCode[0], O);
1259 if (MO.isImm() && MO.getImm() == 0) {
1260 unsigned Reg = ExtraCode[0] == 'w' ? AArch64::WZR : AArch64::XZR;
1262 return false;
1263 }
1264 printOperand(MI, OpNum, O);
1265 return false;
1266 case 'b': // Print B register.
1267 case 'h': // Print H register.
1268 case 's': // Print S register.
1269 case 'd': // Print D register.
1270 case 'q': // Print Q register.
1271 case 'z': // Print Z register.
1272 if (MO.isReg()) {
1273 const TargetRegisterClass *RC;
1274 switch (ExtraCode[0]) {
1275 case 'b':
1276 RC = &AArch64::FPR8RegClass;
1277 break;
1278 case 'h':
1279 RC = &AArch64::FPR16RegClass;
1280 break;
1281 case 's':
1282 RC = &AArch64::FPR32RegClass;
1283 break;
1284 case 'd':
1285 RC = &AArch64::FPR64RegClass;
1286 break;
1287 case 'q':
1288 RC = &AArch64::FPR128RegClass;
1289 break;
1290 case 'z':
1291 RC = &AArch64::ZPRRegClass;
1292 break;
1293 default:
1294 return true;
1295 }
1296 return printAsmRegInClass(MO, RC, AArch64::NoRegAltName, O);
1297 }
1298 printOperand(MI, OpNum, O);
1299 return false;
1300 }
1301 }
1302
1303 // According to ARM, we should emit x and v registers unless we have a
1304 // modifier.
1305 if (MO.isReg()) {
1306 Register Reg = MO.getReg();
1307
1308 // If this is a w or x register, print an x register.
1309 if (AArch64::GPR32allRegClass.contains(Reg) ||
1310 AArch64::GPR64allRegClass.contains(Reg))
1311 return printAsmMRegister(MO, 'x', O);
1312
1313 // If this is an x register tuple, print an x register.
1314 if (AArch64::GPR64x8ClassRegClass.contains(Reg))
1315 return printAsmMRegister(MO, 't', O);
1316
1317 unsigned AltName = AArch64::NoRegAltName;
1318 const TargetRegisterClass *RegClass;
1319 if (AArch64::ZPRRegClass.contains(Reg)) {
1320 RegClass = &AArch64::ZPRRegClass;
1321 } else if (AArch64::PPRRegClass.contains(Reg)) {
1322 RegClass = &AArch64::PPRRegClass;
1323 } else if (AArch64::PNRRegClass.contains(Reg)) {
1324 RegClass = &AArch64::PNRRegClass;
1325 } else {
1326 RegClass = &AArch64::FPR128RegClass;
1327 AltName = AArch64::vreg;
1328 }
1329
1330 // If this is a b, h, s, d, or q register, print it as a v register.
1331 return printAsmRegInClass(MO, RegClass, AltName, O);
1332 }
1333
1334 printOperand(MI, OpNum, O);
1335 return false;
1336}
1337
1338bool AArch64AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1339 unsigned OpNum,
1340 const char *ExtraCode,
1341 raw_ostream &O) {
1342 if (ExtraCode && ExtraCode[0] && ExtraCode[0] != 'a')
1343 return true; // Unknown modifier.
1344
1345 const MachineOperand &MO = MI->getOperand(OpNum);
1346 assert(MO.isReg() && "unexpected inline asm memory operand");
1347 O << "[" << AArch64InstPrinter::getRegisterName(MO.getReg()) << "]";
1348 return false;
1349}
1350
1351void AArch64AsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
1352 raw_ostream &OS) {
1353 unsigned NOps = MI->getNumOperands();
1354 assert(NOps == 4);
1355 OS << '\t' << MAI.getCommentString() << "DEBUG_VALUE: ";
1356 // cast away const; DIetc do not take const operands for some reason.
1357 OS << MI->getDebugVariable()->getName();
1358 OS << " <- ";
1359 // Frame address. Currently handles register +- offset only.
1360 assert(MI->isIndirectDebugValue());
1361 OS << '[';
1362 for (unsigned I = 0, E = llvm::size(MI->debug_operands()); I < E; ++I) {
1363 if (I != 0)
1364 OS << ", ";
1365 printOperand(MI, I, OS);
1366 }
1367 OS << ']';
1368 OS << "+";
1369 printOperand(MI, NOps - 2, OS);
1370}
1371
1372void AArch64AsmPrinter::emitJumpTableImpl(const MachineJumpTableInfo &MJTI,
1373 ArrayRef<unsigned> JumpTableIndices) {
1374 // Fast return if there is nothing to emit to avoid creating empty sections.
1375 if (JumpTableIndices.empty())
1376 return;
1377 const TargetLoweringObjectFile &TLOF = getObjFileLowering();
1378 const auto &F = MF->getFunction();
1380
1381 MCSection *ReadOnlySec = nullptr;
1382 if (TM.Options.EnableStaticDataPartitioning) {
1383 ReadOnlySec =
1384 TLOF.getSectionForJumpTable(F, TM, &JT[JumpTableIndices.front()]);
1385 } else {
1386 ReadOnlySec = TLOF.getSectionForJumpTable(F, TM);
1387 }
1388 OutStreamer->switchSection(ReadOnlySec);
1389
1390 auto AFI = MF->getInfo<AArch64FunctionInfo>();
1391 for (unsigned JTI : JumpTableIndices) {
1392 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1393
1394 // If this jump table was deleted, ignore it.
1395 if (JTBBs.empty()) continue;
1396
1397 unsigned Size = AFI->getJumpTableEntrySize(JTI);
1398 emitAlignment(Align(Size));
1399 OutStreamer->emitLabel(GetJTISymbol(JTI));
1400
1401 const MCSymbol *BaseSym = AArch64FI->getJumpTableEntryPCRelSymbol(JTI);
1402 const MCExpr *Base = MCSymbolRefExpr::create(BaseSym, OutContext);
1403
1404 for (auto *JTBB : JTBBs) {
1405 const MCExpr *Value =
1406 MCSymbolRefExpr::create(JTBB->getSymbol(), OutContext);
1407
1408 // Each entry is:
1409 // .byte/.hword (LBB - Lbase)>>2
1410 // or plain:
1411 // .word LBB - Lbase
1412 Value = MCBinaryExpr::createSub(Value, Base, OutContext);
1413 if (Size != 4)
1415 Value, MCConstantExpr::create(2, OutContext), OutContext);
1416
1417 OutStreamer->emitValue(Value, Size);
1418 }
1419 }
1420}
1421
1422std::tuple<const MCSymbol *, uint64_t, const MCSymbol *,
1424AArch64AsmPrinter::getCodeViewJumpTableInfo(int JTI,
1425 const MachineInstr *BranchInstr,
1426 const MCSymbol *BranchLabel) const {
1427 const auto AFI = MF->getInfo<AArch64FunctionInfo>();
1428 const auto Base = AArch64FI->getJumpTableEntryPCRelSymbol(JTI);
1430 switch (AFI->getJumpTableEntrySize(JTI)) {
1431 case 1:
1432 EntrySize = codeview::JumpTableEntrySize::UInt8ShiftLeft;
1433 break;
1434 case 2:
1435 EntrySize = codeview::JumpTableEntrySize::UInt16ShiftLeft;
1436 break;
1437 case 4:
1438 EntrySize = codeview::JumpTableEntrySize::Int32;
1439 break;
1440 default:
1441 llvm_unreachable("Unexpected jump table entry size");
1442 }
1443 return std::make_tuple(Base, 0, BranchLabel, EntrySize);
1444}
1445
1446void AArch64AsmPrinter::emitFunctionEntryLabel() {
1447 const Triple &TT = TM.getTargetTriple();
1448 if (TT.isOSBinFormatELF() &&
1449 (MF->getFunction().getCallingConv() == CallingConv::AArch64_VectorCall ||
1450 MF->getFunction().getCallingConv() ==
1451 CallingConv::AArch64_SVE_VectorCall ||
1452 MF->getInfo<AArch64FunctionInfo>()->isSVECC())) {
1453 auto *TS =
1454 static_cast<AArch64TargetStreamer *>(OutStreamer->getTargetStreamer());
1455 TS->emitDirectiveVariantPCS(CurrentFnSym);
1456 }
1457
1459
1460 if (TT.isWindowsArm64EC() && !MF->getFunction().hasLocalLinkage()) {
1461 // For ARM64EC targets, a function definition's name is mangled differently
1462 // from the normal symbol, emit required aliases here.
1463 auto emitFunctionAlias = [&](MCSymbol *Src, MCSymbol *Dst) {
1464 OutStreamer->emitSymbolAttribute(Src, MCSA_WeakAntiDep);
1465 OutStreamer->emitAssignment(
1466 Src, MCSymbolRefExpr::create(Dst, MMI->getContext()));
1467 };
1468
1469 auto getSymbolFromMetadata = [&](StringRef Name) {
1470 MCSymbol *Sym = nullptr;
1471 if (MDNode *Node = MF->getFunction().getMetadata(Name)) {
1472 StringRef NameStr = cast<MDString>(Node->getOperand(0))->getString();
1473 Sym = MMI->getContext().getOrCreateSymbol(NameStr);
1474 }
1475 return Sym;
1476 };
1477
1478 SmallVector<MDNode *> UnmangledNames;
1479 MF->getFunction().getMetadata("arm64ec_unmangled_name", UnmangledNames);
1480 for (MDNode *Node : UnmangledNames) {
1481 StringRef NameStr = cast<MDString>(Node->getOperand(0))->getString();
1482 MCSymbol *UnmangledSym = MMI->getContext().getOrCreateSymbol(NameStr);
1483 if (std::optional<std::string> MangledName =
1484 getArm64ECMangledFunctionName(UnmangledSym->getName())) {
1485 MCSymbol *ECMangledSym =
1486 MMI->getContext().getOrCreateSymbol(*MangledName);
1487 emitFunctionAlias(UnmangledSym, ECMangledSym);
1488 }
1489 }
1490 if (MCSymbol *ECMangledSym =
1491 getSymbolFromMetadata("arm64ec_ecmangled_name"))
1492 emitFunctionAlias(ECMangledSym, CurrentFnSym);
1493 }
1494}
1495
1496void AArch64AsmPrinter::emitXXStructor(const DataLayout &DL,
1497 const Constant *CV) {
1498 LLVMContext &C = CV->getContext();
1500 "ctors/dtors are to be signed by asm printer");
1501
1502 if (PtrauthInitFini) {
1503 IntegerType *Int32Ty = IntegerType::get(C, 32);
1504 IntegerType *Int64Ty = IntegerType::get(C, 64);
1505 PointerType *PtrTy = PointerType::get(C, 0);
1506
1507 ConstantInt *Key = ConstantInt::get(Int32Ty, AArch64PAuth::InitFiniKey);
1508 ConstantInt *IntDisc = ConstantInt::get(
1511 Constant *AddressDisc = Null;
1512 if (PtrauthInitFiniAddressDisc) {
1514 AddressDisc =
1515 ConstantExpr::getIntToPtr(ConstantInt::get(Int64Ty, Marker), PtrTy);
1516 }
1517
1518 CV = ConstantPtrAuth::get(const_cast<Constant *>(CV), Key, IntDisc,
1519 AddressDisc, /*DeactivationSymbol=*/Null);
1520 }
1521
1522 // Signed pointers will be lowered by AArch64AsmPrinter::lowerConstantPtrAuth.
1524}
1525
1526void AArch64AsmPrinter::emitGlobalAlias(const Module &M,
1527 const GlobalAlias &GA) {
1528 if (auto F = dyn_cast_or_null<Function>(GA.getAliasee())) {
1529 // Global aliases must point to a definition, but unmangled patchable
1530 // symbols are special and need to point to an undefined symbol with "EXP+"
1531 // prefix. Such undefined symbol is resolved by the linker by creating
1532 // x86 thunk that jumps back to the actual EC target.
1533 if (MDNode *Node = F->getMetadata("arm64ec_exp_name")) {
1534 StringRef ExpStr = cast<MDString>(Node->getOperand(0))->getString();
1535 MCSymbol *ExpSym = MMI->getContext().getOrCreateSymbol(ExpStr);
1536 MCSymbol *Sym = MMI->getContext().getOrCreateSymbol(GA.getName());
1537
1538 OutStreamer->beginCOFFSymbolDef(ExpSym);
1539 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
1540 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
1542 OutStreamer->endCOFFSymbolDef();
1543
1544 OutStreamer->beginCOFFSymbolDef(Sym);
1545 OutStreamer->emitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
1546 OutStreamer->emitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
1548 OutStreamer->endCOFFSymbolDef();
1549 OutStreamer->emitSymbolAttribute(Sym, MCSA_Weak);
1550 OutStreamer->emitAssignment(
1551 Sym, MCSymbolRefExpr::create(ExpSym, MMI->getContext()));
1552 return;
1553 }
1554 }
1556}
1557
1558/// Small jump tables contain an unsigned byte or half, representing the offset
1559/// from the lowest-addressed possible destination to the desired basic
1560/// block. Since all instructions are 4-byte aligned, this is further compressed
1561/// by counting in instructions rather than bytes (i.e. divided by 4). So, to
1562/// materialize the correct destination we need:
1563///
1564/// adr xDest, .LBB0_0
1565/// ldrb wScratch, [xTable, xEntry] (with "lsl #1" for ldrh).
1566/// add xDest, xDest, xScratch (with "lsl #2" for smaller entries)
1567void AArch64AsmPrinter::LowerJumpTableDest(llvm::MCStreamer &OutStreamer,
1568 const llvm::MachineInstr &MI) {
1569 Register DestReg = MI.getOperand(0).getReg();
1570 Register ScratchReg = MI.getOperand(1).getReg();
1571 Register ScratchRegW =
1572 STI->getRegisterInfo()->getSubReg(ScratchReg, AArch64::sub_32);
1573 Register TableReg = MI.getOperand(2).getReg();
1574 Register EntryReg = MI.getOperand(3).getReg();
1575 int JTIdx = MI.getOperand(4).getIndex();
1576 int Size = AArch64FI->getJumpTableEntrySize(JTIdx);
1577
1578 // This has to be first because the compression pass based its reachability
1579 // calculations on the start of the JumpTableDest instruction.
1580 auto Label =
1581 MF->getInfo<AArch64FunctionInfo>()->getJumpTableEntryPCRelSymbol(JTIdx);
1582
1583 // If we don't already have a symbol to use as the base, use the ADR
1584 // instruction itself.
1585 if (!Label) {
1587 AArch64FI->setJumpTableEntryInfo(JTIdx, Size, Label);
1588 OutStreamer.emitLabel(Label);
1589 }
1590
1591 auto LabelExpr = MCSymbolRefExpr::create(Label, MF->getContext());
1592 EmitToStreamer(OutStreamer, MCInstBuilder(AArch64::ADR)
1593 .addReg(DestReg)
1594 .addExpr(LabelExpr));
1595
1596 // Load the number of instruction-steps to offset from the label.
1597 unsigned LdrOpcode;
1598 switch (Size) {
1599 case 1: LdrOpcode = AArch64::LDRBBroX; break;
1600 case 2: LdrOpcode = AArch64::LDRHHroX; break;
1601 case 4: LdrOpcode = AArch64::LDRSWroX; break;
1602 default:
1603 llvm_unreachable("Unknown jump table size");
1604 }
1605
1606 EmitToStreamer(OutStreamer, MCInstBuilder(LdrOpcode)
1607 .addReg(Size == 4 ? ScratchReg : ScratchRegW)
1608 .addReg(TableReg)
1609 .addReg(EntryReg)
1610 .addImm(0)
1611 .addImm(Size == 1 ? 0 : 1));
1612
1613 // Add to the already materialized base label address, multiplying by 4 if
1614 // compressed.
1615 EmitToStreamer(OutStreamer, MCInstBuilder(AArch64::ADDXrs)
1616 .addReg(DestReg)
1617 .addReg(DestReg)
1618 .addReg(ScratchReg)
1619 .addImm(Size == 4 ? 0 : 2));
1620}
1621
1622void AArch64AsmPrinter::LowerHardenedBRJumpTable(const MachineInstr &MI) {
1623 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1624 assert(MJTI && "Can't lower jump-table dispatch without JTI");
1625
1626 const std::vector<MachineJumpTableEntry> &JTs = MJTI->getJumpTables();
1627 assert(!JTs.empty() && "Invalid JT index for jump-table dispatch");
1628
1629 // Emit:
1630 // mov x17, #<size of table> ; depending on table size, with MOVKs
1631 // cmp x16, x17 ; or #imm if table size fits in 12-bit
1632 // csel x16, x16, xzr, ls ; check for index overflow
1633 //
1634 // adrp x17, Ltable@PAGE ; materialize table address
1635 // add x17, Ltable@PAGEOFF
1636 // ldrsw x16, [x17, x16, lsl #2] ; load table entry
1637 //
1638 // Lanchor:
1639 // adr x17, Lanchor ; compute target address
1640 // add x16, x17, x16
1641 // br x16 ; branch to target
1642
1643 MachineOperand JTOp = MI.getOperand(0);
1644
1645 unsigned JTI = JTOp.getIndex();
1646 assert(!AArch64FI->getJumpTableEntryPCRelSymbol(JTI) &&
1647 "unsupported compressed jump table");
1648
1649 const uint64_t NumTableEntries = JTs[JTI].MBBs.size();
1650
1651 // cmp only supports a 12-bit immediate. If we need more, materialize the
1652 // immediate, using x17 as a scratch register.
1653 uint64_t MaxTableEntry = NumTableEntries - 1;
1654 if (isUInt<12>(MaxTableEntry)) {
1655 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::SUBSXri)
1656 .addReg(AArch64::XZR)
1657 .addReg(AArch64::X16)
1658 .addImm(MaxTableEntry)
1659 .addImm(0));
1660 } else {
1661 emitMOVZ(AArch64::X17, static_cast<uint16_t>(MaxTableEntry), 0);
1662 // It's sad that we have to manually materialize instructions, but we can't
1663 // trivially reuse the main pseudo expansion logic.
1664 // A MOVK sequence is easy enough to generate and handles the general case.
1665 for (int Offset = 16; Offset < 64; Offset += 16) {
1666 if ((MaxTableEntry >> Offset) == 0)
1667 break;
1668 emitMOVK(AArch64::X17, static_cast<uint16_t>(MaxTableEntry >> Offset),
1669 Offset);
1670 }
1671 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::SUBSXrs)
1672 .addReg(AArch64::XZR)
1673 .addReg(AArch64::X16)
1674 .addReg(AArch64::X17)
1675 .addImm(0));
1676 }
1677
1678 // This picks entry #0 on failure.
1679 // We might want to trap instead.
1680 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::CSELXr)
1681 .addReg(AArch64::X16)
1682 .addReg(AArch64::X16)
1683 .addReg(AArch64::XZR)
1684 .addImm(AArch64CC::LS));
1685
1686 // Prepare the @PAGE/@PAGEOFF low/high operands.
1687 MachineOperand JTMOHi(JTOp), JTMOLo(JTOp);
1688 MCOperand JTMCHi, JTMCLo;
1689
1690 JTMOHi.setTargetFlags(AArch64II::MO_PAGE);
1691 JTMOLo.setTargetFlags(AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
1692
1693 MCInstLowering.lowerOperand(JTMOHi, JTMCHi);
1694 MCInstLowering.lowerOperand(JTMOLo, JTMCLo);
1695
1696 EmitToStreamer(
1697 *OutStreamer,
1698 MCInstBuilder(AArch64::ADRP).addReg(AArch64::X17).addOperand(JTMCHi));
1699
1700 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::ADDXri)
1701 .addReg(AArch64::X17)
1702 .addReg(AArch64::X17)
1703 .addOperand(JTMCLo)
1704 .addImm(0));
1705
1706 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::LDRSWroX)
1707 .addReg(AArch64::X16)
1708 .addReg(AArch64::X17)
1709 .addReg(AArch64::X16)
1710 .addImm(0)
1711 .addImm(1));
1712
1713 MCSymbol *AdrLabel = MF->getContext().createTempSymbol();
1714 const auto *AdrLabelE = MCSymbolRefExpr::create(AdrLabel, MF->getContext());
1715 AArch64FI->setJumpTableEntryInfo(JTI, 4, AdrLabel);
1716
1717 OutStreamer->emitLabel(AdrLabel);
1718 EmitToStreamer(
1719 *OutStreamer,
1720 MCInstBuilder(AArch64::ADR).addReg(AArch64::X17).addExpr(AdrLabelE));
1721
1722 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::ADDXrs)
1723 .addReg(AArch64::X16)
1724 .addReg(AArch64::X17)
1725 .addReg(AArch64::X16)
1726 .addImm(0));
1727
1728 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::BR).addReg(AArch64::X16));
1729}
1730
1731void AArch64AsmPrinter::LowerMOPS(llvm::MCStreamer &OutStreamer,
1732 const llvm::MachineInstr &MI) {
1733 unsigned Opcode = MI.getOpcode();
1734 assert(STI->hasMOPS());
1735 assert(STI->hasMTE() || Opcode != AArch64::MOPSMemorySetTaggingPseudo);
1736
1737 const auto Ops = [Opcode]() -> std::array<unsigned, 3> {
1738 if (Opcode == AArch64::MOPSMemoryCopyPseudo)
1739 return {AArch64::CPYFP, AArch64::CPYFM, AArch64::CPYFE};
1740 if (Opcode == AArch64::MOPSMemoryMovePseudo)
1741 return {AArch64::CPYP, AArch64::CPYM, AArch64::CPYE};
1742 if (Opcode == AArch64::MOPSMemorySetPseudo)
1743 return {AArch64::SETP, AArch64::SETM, AArch64::SETE};
1744 if (Opcode == AArch64::MOPSMemorySetTaggingPseudo)
1745 return {AArch64::SETGP, AArch64::SETGM, AArch64::MOPSSETGE};
1746 llvm_unreachable("Unhandled memory operation pseudo");
1747 }();
1748 const bool IsSet = Opcode == AArch64::MOPSMemorySetPseudo ||
1749 Opcode == AArch64::MOPSMemorySetTaggingPseudo;
1750
1751 for (auto Op : Ops) {
1752 int i = 0;
1753 auto MCIB = MCInstBuilder(Op);
1754 // Destination registers
1755 MCIB.addReg(MI.getOperand(i++).getReg());
1756 MCIB.addReg(MI.getOperand(i++).getReg());
1757 if (!IsSet)
1758 MCIB.addReg(MI.getOperand(i++).getReg());
1759 // Input registers
1760 MCIB.addReg(MI.getOperand(i++).getReg());
1761 MCIB.addReg(MI.getOperand(i++).getReg());
1762 MCIB.addReg(MI.getOperand(i++).getReg());
1763
1764 EmitToStreamer(OutStreamer, MCIB);
1765 }
1766}
1767
1768void AArch64AsmPrinter::LowerSTACKMAP(MCStreamer &OutStreamer, StackMaps &SM,
1769 const MachineInstr &MI) {
1770 unsigned NumNOPBytes = StackMapOpers(&MI).getNumPatchBytes();
1771
1772 auto &Ctx = OutStreamer.getContext();
1773 MCSymbol *MILabel = Ctx.createTempSymbol();
1774 OutStreamer.emitLabel(MILabel);
1775
1776 SM.recordStackMap(*MILabel, MI);
1777 assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
1778
1779 // Scan ahead to trim the shadow.
1780 const MachineBasicBlock &MBB = *MI.getParent();
1782 ++MII;
1783 while (NumNOPBytes > 0) {
1784 if (MII == MBB.end() || MII->isCall() ||
1785 MII->getOpcode() == AArch64::DBG_VALUE ||
1786 MII->getOpcode() == TargetOpcode::PATCHPOINT ||
1787 MII->getOpcode() == TargetOpcode::STACKMAP)
1788 break;
1789 ++MII;
1790 NumNOPBytes -= 4;
1791 }
1792
1793 // Emit nops.
1794 for (unsigned i = 0; i < NumNOPBytes; i += 4)
1795 EmitToStreamer(OutStreamer, MCInstBuilder(AArch64::NOP));
1796}
1797
1798// Lower a patchpoint of the form:
1799// [<def>], <id>, <numBytes>, <target>, <numArgs>
1800void AArch64AsmPrinter::LowerPATCHPOINT(MCStreamer &OutStreamer, StackMaps &SM,
1801 const MachineInstr &MI) {
1802 auto &Ctx = OutStreamer.getContext();
1803 MCSymbol *MILabel = Ctx.createTempSymbol();
1804 OutStreamer.emitLabel(MILabel);
1805 SM.recordPatchPoint(*MILabel, MI);
1806
1807 PatchPointOpers Opers(&MI);
1808
1809 int64_t CallTarget = Opers.getCallTarget().getImm();
1810 unsigned EncodedBytes = 0;
1811 if (CallTarget) {
1812 assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
1813 "High 16 bits of call target should be zero.");
1814 Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
1815 EncodedBytes = 16;
1816 // Materialize the jump address:
1817 emitMOVZ(ScratchReg, (CallTarget >> 32) & 0xFFFF, 32);
1818 emitMOVK(ScratchReg, (CallTarget >> 16) & 0xFFFF, 16);
1819 emitMOVK(ScratchReg, CallTarget & 0xFFFF, 0);
1820 EmitToStreamer(OutStreamer, MCInstBuilder(AArch64::BLR).addReg(ScratchReg));
1821 }
1822 // Emit padding.
1823 unsigned NumBytes = Opers.getNumPatchBytes();
1824 assert(NumBytes >= EncodedBytes &&
1825 "Patchpoint can't request size less than the length of a call.");
1826 assert((NumBytes - EncodedBytes) % 4 == 0 &&
1827 "Invalid number of NOP bytes requested!");
1828 for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
1829 EmitToStreamer(OutStreamer, MCInstBuilder(AArch64::NOP));
1830}
1831
1832void AArch64AsmPrinter::LowerSTATEPOINT(MCStreamer &OutStreamer, StackMaps &SM,
1833 const MachineInstr &MI) {
1834 StatepointOpers SOpers(&MI);
1835 if (unsigned PatchBytes = SOpers.getNumPatchBytes()) {
1836 assert(PatchBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
1837 for (unsigned i = 0; i < PatchBytes; i += 4)
1838 EmitToStreamer(OutStreamer, MCInstBuilder(AArch64::NOP));
1839 } else {
1840 // Lower call target and choose correct opcode
1841 const MachineOperand &CallTarget = SOpers.getCallTarget();
1842 MCOperand CallTargetMCOp;
1843 unsigned CallOpcode;
1844 switch (CallTarget.getType()) {
1847 MCInstLowering.lowerOperand(CallTarget, CallTargetMCOp);
1848 CallOpcode = AArch64::BL;
1849 break;
1851 CallTargetMCOp = MCOperand::createImm(CallTarget.getImm());
1852 CallOpcode = AArch64::BL;
1853 break;
1855 CallTargetMCOp = MCOperand::createReg(CallTarget.getReg());
1856 CallOpcode = AArch64::BLR;
1857 break;
1858 default:
1859 llvm_unreachable("Unsupported operand type in statepoint call target");
1860 break;
1861 }
1862
1863 EmitToStreamer(OutStreamer,
1864 MCInstBuilder(CallOpcode).addOperand(CallTargetMCOp));
1865 }
1866
1867 auto &Ctx = OutStreamer.getContext();
1868 MCSymbol *MILabel = Ctx.createTempSymbol();
1869 OutStreamer.emitLabel(MILabel);
1870 SM.recordStatepoint(*MILabel, MI);
1871}
1872
1873void AArch64AsmPrinter::LowerFAULTING_OP(const MachineInstr &FaultingMI) {
1874 // FAULTING_LOAD_OP <def>, <faltinf type>, <MBB handler>,
1875 // <opcode>, <operands>
1876
1877 Register DefRegister = FaultingMI.getOperand(0).getReg();
1879 static_cast<FaultMaps::FaultKind>(FaultingMI.getOperand(1).getImm());
1880 MCSymbol *HandlerLabel = FaultingMI.getOperand(2).getMBB()->getSymbol();
1881 unsigned Opcode = FaultingMI.getOperand(3).getImm();
1882 unsigned OperandsBeginIdx = 4;
1883
1884 auto &Ctx = OutStreamer->getContext();
1885 MCSymbol *FaultingLabel = Ctx.createTempSymbol();
1886 OutStreamer->emitLabel(FaultingLabel);
1887
1888 assert(FK < FaultMaps::FaultKindMax && "Invalid Faulting Kind!");
1889 FM.recordFaultingOp(FK, FaultingLabel, HandlerLabel);
1890
1891 MCInst MI;
1892 MI.setOpcode(Opcode);
1893
1894 if (DefRegister != (Register)0)
1895 MI.addOperand(MCOperand::createReg(DefRegister));
1896
1897 for (const MachineOperand &MO :
1898 llvm::drop_begin(FaultingMI.operands(), OperandsBeginIdx)) {
1899 MCOperand Dest;
1900 lowerOperand(MO, Dest);
1901 MI.addOperand(Dest);
1902 }
1903
1904 OutStreamer->AddComment("on-fault: " + HandlerLabel->getName());
1905 EmitToStreamer(MI);
1906}
1907
1908void AArch64AsmPrinter::emitMovXReg(Register Dest, Register Src) {
1909 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::ORRXrs)
1910 .addReg(Dest)
1911 .addReg(AArch64::XZR)
1912 .addReg(Src)
1913 .addImm(0));
1914}
1915
1916void AArch64AsmPrinter::emitMOVZ(Register Dest, uint64_t Imm, unsigned Shift) {
1917 bool Is64Bit = AArch64::GPR64RegClass.contains(Dest);
1918 EmitToStreamer(*OutStreamer,
1919 MCInstBuilder(Is64Bit ? AArch64::MOVZXi : AArch64::MOVZWi)
1920 .addReg(Dest)
1921 .addImm(Imm)
1922 .addImm(Shift));
1923}
1924
1925void AArch64AsmPrinter::emitMOVK(Register Dest, uint64_t Imm, unsigned Shift) {
1926 bool Is64Bit = AArch64::GPR64RegClass.contains(Dest);
1927 EmitToStreamer(*OutStreamer,
1928 MCInstBuilder(Is64Bit ? AArch64::MOVKXi : AArch64::MOVKWi)
1929 .addReg(Dest)
1930 .addReg(Dest)
1931 .addImm(Imm)
1932 .addImm(Shift));
1933}
1934
1935void AArch64AsmPrinter::emitAUT(AArch64PACKey::ID Key, Register Pointer,
1936 Register Disc) {
1937 bool IsZeroDisc = Disc == AArch64::XZR;
1938 unsigned Opcode = getAUTOpcodeForKey(Key, IsZeroDisc);
1939
1940 // autiza x16 ; if IsZeroDisc
1941 // autia x16, x17 ; if !IsZeroDisc
1942 MCInst AUTInst;
1943 AUTInst.setOpcode(Opcode);
1944 AUTInst.addOperand(MCOperand::createReg(Pointer));
1945 AUTInst.addOperand(MCOperand::createReg(Pointer));
1946 if (!IsZeroDisc)
1947 AUTInst.addOperand(MCOperand::createReg(Disc));
1948
1949 EmitToStreamer(AUTInst);
1950}
1951
1952void AArch64AsmPrinter::emitPAC(AArch64PACKey::ID Key, Register Pointer,
1953 Register Disc) {
1954 bool IsZeroDisc = Disc == AArch64::XZR;
1955 unsigned Opcode = getPACOpcodeForKey(Key, IsZeroDisc);
1956
1957 // paciza x16 ; if IsZeroDisc
1958 // pacia x16, x17 ; if !IsZeroDisc
1959 MCInst PACInst;
1960 PACInst.setOpcode(Opcode);
1961 PACInst.addOperand(MCOperand::createReg(Pointer));
1962 PACInst.addOperand(MCOperand::createReg(Pointer));
1963 if (!IsZeroDisc)
1964 PACInst.addOperand(MCOperand::createReg(Disc));
1965
1966 EmitToStreamer(PACInst);
1967}
1968
1969void AArch64AsmPrinter::emitBLRA(bool IsCall, AArch64PACKey::ID Key,
1970 Register Target, Register Disc) {
1971 bool IsZeroDisc = Disc == AArch64::XZR;
1972 unsigned Opcode = getBranchOpcodeForKey(IsCall, Key, IsZeroDisc);
1973
1974 // blraaz x16 ; if IsZeroDisc
1975 // blraa x16, x17 ; if !IsZeroDisc
1976 MCInst Inst;
1977 Inst.setOpcode(Opcode);
1978 Inst.addOperand(MCOperand::createReg(Target));
1979 if (!IsZeroDisc)
1980 Inst.addOperand(MCOperand::createReg(Disc));
1981 EmitToStreamer(Inst);
1982}
1983
1984void AArch64AsmPrinter::emitFMov0(const MachineInstr &MI) {
1985 Register DestReg = MI.getOperand(0).getReg();
1986 if (!STI->hasZeroCycleZeroingFPWorkaround() && STI->isNeonAvailable()) {
1987 if (STI->hasZeroCycleZeroingFPR64()) {
1988 // Convert H/S register to corresponding D register
1989 const AArch64RegisterInfo *TRI = STI->getRegisterInfo();
1990 if (AArch64::FPR16RegClass.contains(DestReg))
1991 DestReg = TRI->getMatchingSuperReg(DestReg, AArch64::hsub,
1992 &AArch64::FPR64RegClass);
1993 else if (AArch64::FPR32RegClass.contains(DestReg))
1994 DestReg = TRI->getMatchingSuperReg(DestReg, AArch64::ssub,
1995 &AArch64::FPR64RegClass);
1996 else
1997 assert(AArch64::FPR64RegClass.contains(DestReg));
1998
1999 MCInst MOVI;
2000 MOVI.setOpcode(AArch64::MOVID);
2001 MOVI.addOperand(MCOperand::createReg(DestReg));
2003 EmitToStreamer(*OutStreamer, MOVI);
2004 ++NumZCZeroingInstrsFPR;
2005 } else if (STI->hasZeroCycleZeroingFPR128()) {
2006 // Convert H/S/D register to corresponding Q register
2007 const AArch64RegisterInfo *TRI = STI->getRegisterInfo();
2008 if (AArch64::FPR16RegClass.contains(DestReg)) {
2009 DestReg = TRI->getMatchingSuperReg(DestReg, AArch64::hsub,
2010 &AArch64::FPR128RegClass);
2011 } else if (AArch64::FPR32RegClass.contains(DestReg)) {
2012 DestReg = TRI->getMatchingSuperReg(DestReg, AArch64::ssub,
2013 &AArch64::FPR128RegClass);
2014 } else {
2015 assert(AArch64::FPR64RegClass.contains(DestReg));
2016 DestReg = TRI->getMatchingSuperReg(DestReg, AArch64::dsub,
2017 &AArch64::FPR128RegClass);
2018 }
2019
2020 MCInst MOVI;
2021 MOVI.setOpcode(AArch64::MOVIv2d_ns);
2022 MOVI.addOperand(MCOperand::createReg(DestReg));
2024 EmitToStreamer(*OutStreamer, MOVI);
2025 ++NumZCZeroingInstrsFPR;
2026 } else {
2027 emitFMov0AsFMov(MI, DestReg);
2028 }
2029 } else {
2030 emitFMov0AsFMov(MI, DestReg);
2031 }
2032}
2033
2034void AArch64AsmPrinter::emitFMov0AsFMov(const MachineInstr &MI,
2035 Register DestReg) {
2036 MCInst FMov;
2037 switch (MI.getOpcode()) {
2038 default:
2039 llvm_unreachable("Unexpected opcode");
2040 case AArch64::FMOVH0:
2041 FMov.setOpcode(STI->hasFullFP16() ? AArch64::FMOVWHr : AArch64::FMOVWSr);
2042 if (!STI->hasFullFP16())
2043 DestReg = (AArch64::S0 + (DestReg - AArch64::H0));
2044 FMov.addOperand(MCOperand::createReg(DestReg));
2045 FMov.addOperand(MCOperand::createReg(AArch64::WZR));
2046 break;
2047 case AArch64::FMOVS0:
2048 FMov.setOpcode(AArch64::FMOVWSr);
2049 FMov.addOperand(MCOperand::createReg(DestReg));
2050 FMov.addOperand(MCOperand::createReg(AArch64::WZR));
2051 break;
2052 case AArch64::FMOVD0:
2053 FMov.setOpcode(AArch64::FMOVXDr);
2054 FMov.addOperand(MCOperand::createReg(DestReg));
2055 FMov.addOperand(MCOperand::createReg(AArch64::XZR));
2056 break;
2057 }
2058 EmitToStreamer(*OutStreamer, FMov);
2059}
2060
2061Register AArch64AsmPrinter::emitPtrauthDiscriminator(uint64_t Disc,
2062 Register AddrDisc,
2063 Register ScratchReg,
2064 bool MayClobberAddrDisc) {
2065 assert(isPtrauthRegSafe(ScratchReg) &&
2066 "Safe scratch register must be provided by the caller");
2067 assert(isUInt<16>(Disc) && "Constant discriminator is too wide");
2068
2069 // So far we've used NoRegister in pseudos. Now we need real encodings.
2070 if (AddrDisc == AArch64::NoRegister)
2071 AddrDisc = AArch64::XZR;
2072
2073 // If there is no constant discriminator, there's no blend involved:
2074 // just use the address discriminator register as-is (XZR or not).
2075 if (!Disc)
2076 return AddrDisc;
2077
2078 // If there's only a constant discriminator, MOV it into the scratch register.
2079 if (AddrDisc == AArch64::XZR) {
2080 emitMOVZ(ScratchReg, Disc, 0);
2081 return ScratchReg;
2082 }
2083
2084 // If there are both, emit a blend into the scratch register.
2085
2086 // Check if we can save one MOV instruction.
2087 if (MayClobberAddrDisc && isPtrauthRegSafe(AddrDisc)) {
2088 ScratchReg = AddrDisc;
2089 } else {
2090 emitMovXReg(ScratchReg, AddrDisc);
2091 assert(ScratchReg != AddrDisc &&
2092 "Forbidden to clobber AddrDisc, but have to");
2093 }
2094
2095 emitMOVK(ScratchReg, Disc, 48);
2096 return ScratchReg;
2097}
2098
2099/// Emit a code sequence to check an authenticated pointer value.
2100///
2101/// This function emits a sequence of instructions that checks if TestedReg was
2102/// authenticated successfully. On success, execution continues at the next
2103/// instruction after the sequence.
2104///
2105/// The action performed on failure depends on the OnFailure argument:
2106/// * if OnFailure is not nullptr, control is transferred to that label after
2107/// clearing the PAC field
2108/// * otherwise, BRK instruction is emitted to generate an error
2109void AArch64AsmPrinter::emitPtrauthCheckAuthenticatedValue(
2110 Register TestedReg, Register ScratchReg, AArch64PACKey::ID Key,
2111 AArch64PAuth::AuthCheckMethod Method, const MCSymbol *OnFailure) {
2112 // Insert a sequence to check if authentication of TestedReg succeeded,
2113 // such as:
2114 //
2115 // - checked and clearing:
2116 // ; x16 is TestedReg, x17 is ScratchReg
2117 // mov x17, x16
2118 // xpaci x17
2119 // cmp x16, x17
2120 // b.eq Lsuccess
2121 // mov x16, x17
2122 // b Lend
2123 // Lsuccess:
2124 // ; skipped if authentication failed
2125 // Lend:
2126 // ...
2127 //
2128 // - checked and trapping:
2129 // mov x17, x16
2130 // xpaci x17
2131 // cmp x16, x17
2132 // b.eq Lsuccess
2133 // brk #<0xc470 + aut key>
2134 // Lsuccess:
2135 // ...
2136 //
2137 // See the documentation on AuthCheckMethod enumeration constants for
2138 // the specific code sequences that can be used to perform the check.
2140
2141 if (Method == AuthCheckMethod::None)
2142 return;
2143 if (Method == AuthCheckMethod::DummyLoad) {
2144 EmitToStreamer(MCInstBuilder(AArch64::LDRWui)
2145 .addReg(getWRegFromXReg(ScratchReg))
2146 .addReg(TestedReg)
2147 .addImm(0));
2148 assert(!OnFailure && "DummyLoad always traps on error");
2149 return;
2150 }
2151
2152 MCSymbol *SuccessSym = createTempSymbol("auth_success_");
2153 if (Method == AuthCheckMethod::XPAC || Method == AuthCheckMethod::XPACHint) {
2154 // mov Xscratch, Xtested
2155 emitMovXReg(ScratchReg, TestedReg);
2156
2157 if (Method == AuthCheckMethod::XPAC) {
2158 // xpac(i|d) Xscratch
2159 unsigned XPACOpc = getXPACOpcodeForKey(Key);
2160 EmitToStreamer(
2161 MCInstBuilder(XPACOpc).addReg(ScratchReg).addReg(ScratchReg));
2162 } else {
2163 // xpaclri
2164
2165 // Note that this method applies XPAC to TestedReg instead of ScratchReg.
2166 assert(TestedReg == AArch64::LR &&
2167 "XPACHint mode is only compatible with checking the LR register");
2169 "XPACHint mode is only compatible with I-keys");
2170 EmitToStreamer(MCInstBuilder(AArch64::XPACLRI));
2171 }
2172
2173 // cmp Xtested, Xscratch
2174 EmitToStreamer(MCInstBuilder(AArch64::SUBSXrs)
2175 .addReg(AArch64::XZR)
2176 .addReg(TestedReg)
2177 .addReg(ScratchReg)
2178 .addImm(0));
2179
2180 // b.eq Lsuccess
2181 EmitToStreamer(
2182 MCInstBuilder(AArch64::Bcc)
2183 .addImm(AArch64CC::EQ)
2184 .addExpr(MCSymbolRefExpr::create(SuccessSym, OutContext)));
2185 } else if (Method == AuthCheckMethod::HighBitsNoTBI) {
2186 // eor Xscratch, Xtested, Xtested, lsl #1
2187 EmitToStreamer(MCInstBuilder(AArch64::EORXrs)
2188 .addReg(ScratchReg)
2189 .addReg(TestedReg)
2190 .addReg(TestedReg)
2191 .addImm(1));
2192 // tbz Xscratch, #62, Lsuccess
2193 EmitToStreamer(
2194 MCInstBuilder(AArch64::TBZX)
2195 .addReg(ScratchReg)
2196 .addImm(62)
2197 .addExpr(MCSymbolRefExpr::create(SuccessSym, OutContext)));
2198 } else {
2199 llvm_unreachable("Unsupported check method");
2200 }
2201
2202 if (!OnFailure) {
2203 // Trapping sequences do a 'brk'.
2204 // brk #<0xc470 + aut key>
2205 EmitToStreamer(MCInstBuilder(AArch64::BRK).addImm(0xc470 | Key));
2206 } else {
2207 // Non-trapping checked sequences return the stripped result in TestedReg,
2208 // skipping over success-only code (such as re-signing the pointer) by
2209 // jumping to OnFailure label.
2210 // Note that this can introduce an authentication oracle (such as based on
2211 // the high bits of the re-signed value).
2212
2213 // FIXME: The XPAC method can be optimized by applying XPAC to TestedReg
2214 // instead of ScratchReg, thus eliminating one `mov` instruction.
2215 // Both XPAC and XPACHint can be further optimized by not using a
2216 // conditional branch jumping over an unconditional one.
2217
2218 switch (Method) {
2219 case AuthCheckMethod::XPACHint:
2220 // LR is already XPAC-ed at this point.
2221 break;
2222 case AuthCheckMethod::XPAC:
2223 // mov Xtested, Xscratch
2224 emitMovXReg(TestedReg, ScratchReg);
2225 break;
2226 default:
2227 // If Xtested was not XPAC-ed so far, emit XPAC here.
2228 // xpac(i|d) Xtested
2229 unsigned XPACOpc = getXPACOpcodeForKey(Key);
2230 EmitToStreamer(
2231 MCInstBuilder(XPACOpc).addReg(TestedReg).addReg(TestedReg));
2232 }
2233
2234 // b Lend
2235 const auto *OnFailureExpr = MCSymbolRefExpr::create(OnFailure, OutContext);
2236 EmitToStreamer(MCInstBuilder(AArch64::B).addExpr(OnFailureExpr));
2237 }
2238
2239 // If the auth check succeeds, we can continue.
2240 // Lsuccess:
2241 OutStreamer->emitLabel(SuccessSym);
2242}
2243
2244// With Pointer Authentication, it may be needed to explicitly check the
2245// authenticated value in LR before performing a tail call.
2246// Otherwise, the callee may re-sign the invalid return address,
2247// introducing a signing oracle.
2248void AArch64AsmPrinter::emitPtrauthTailCallHardening(const MachineInstr *TC) {
2249 if (!AArch64FI->shouldSignReturnAddress(*MF))
2250 return;
2251
2252 auto LRCheckMethod = STI->getAuthenticatedLRCheckMethod(*MF);
2253 if (LRCheckMethod == AArch64PAuth::AuthCheckMethod::None)
2254 return;
2255
2256 const AArch64RegisterInfo *TRI = STI->getRegisterInfo();
2257 Register ScratchReg =
2258 TC->readsRegister(AArch64::X16, TRI) ? AArch64::X17 : AArch64::X16;
2259 assert(!TC->readsRegister(ScratchReg, TRI) &&
2260 "Neither x16 nor x17 is available as a scratch register");
2263 emitPtrauthCheckAuthenticatedValue(AArch64::LR, ScratchReg, Key,
2264 LRCheckMethod);
2265}
2266
2267bool AArch64AsmPrinter::emitDeactivationSymbolRelocation(Value *DS) {
2268 if (!DS)
2269 return false;
2270
2271 if (isa<GlobalAlias>(DS)) {
2272 // Just emit the nop directly.
2273 EmitToStreamer(MCInstBuilder(AArch64::NOP));
2274 return true;
2275 }
2276 MCSymbol *Dot = OutContext.createTempSymbol();
2277 OutStreamer->emitLabel(Dot);
2278 const MCExpr *DeactDotExpr = MCSymbolRefExpr::create(Dot, OutContext);
2279
2280 const MCExpr *DSExpr = MCSymbolRefExpr::create(
2281 OutContext.getOrCreateSymbol(DS->getName()), OutContext);
2282 OutStreamer->emitRelocDirective(*DeactDotExpr, "R_AARCH64_PATCHINST", DSExpr,
2283 SMLoc());
2284 return false;
2285}
2286
2287AArch64AsmPrinter::PtrAuthSchema AArch64AsmPrinter::PtrAuthSchema::CreateImmReg(
2288 AArch64PACKey::ID Key, uint64_t IntDisc, const MachineOperand &AddrDiscOp) {
2289 PtrAuthSchema Schema;
2290 Schema.Key = Key;
2291 Schema.IntDisc = IntDisc;
2292 Schema.AddrDisc = AddrDiscOp.getReg();
2293 Schema.AddrDiscIsKilled = AddrDiscOp.isKill();
2294 Schema.PCDisc = AArch64::NoRegister;
2295 return Schema;
2296}
2297
2298AArch64AsmPrinter::PtrAuthSchema AArch64AsmPrinter::PtrAuthSchema::CreateRegReg(
2299 AArch64PACKey::ID Key, Register AddrDisc, Register PCDisc) {
2300 assert(PCDisc != AArch64::NoRegister &&
2301 "Use CreateImmReg for non-PC schemas");
2302 PtrAuthSchema Schema;
2303 Schema.Key = Key;
2304 Schema.IntDisc = 0;
2305 Schema.AddrDisc = AddrDisc;
2306 Schema.AddrDiscIsKilled = false;
2307 Schema.PCDisc = PCDisc;
2308 return Schema;
2309}
2310
2311void AArch64AsmPrinter::emitPtrauthApplyIndirectAddend(Register Pointer,
2312 Register Scratch,
2313 int64_t Addend) {
2314 if (isInt<9>(Addend)) {
2315 // ldrsw Scratch, [Pointer, #Addend]! ; note: Pointer+Addend is used later.
2316 EmitToStreamer(MCInstBuilder(AArch64::LDRSWpre)
2317 .addReg(Pointer)
2318 .addReg(Scratch)
2319 .addReg(Pointer)
2320 .addImm(/*simm9:*/ Addend));
2321 } else {
2322 // Pointer += Addend computation has 2 variants
2323 if (isUInt<24>(Addend)) {
2324 // Variant 1: add Pointer, Pointer, (Addend >> shift12) lsl shift12
2325 // This can take up to 2 instructions.
2326 for (int BitPos = 0; BitPos != 24 && (Addend >> BitPos); BitPos += 12) {
2327 EmitToStreamer(
2328 MCInstBuilder(AArch64::ADDXri)
2329 .addReg(Pointer)
2330 .addReg(Pointer)
2331 .addImm((Addend >> BitPos) & 0xfff)
2332 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, BitPos)));
2333 }
2334 } else {
2335 // Variant 2: accumulate constant in Scratch 16 bits at a time,
2336 // and add it to Pointer. This can take 2-5 instructions.
2337 emitMOVZ(Scratch, Addend & 0xffff, 0);
2338 for (int Offset = 16; Offset < 64; Offset += 16) {
2339 if (unsigned Fragment = (Addend >> Offset) & 0xffff)
2340 emitMOVK(Scratch, Fragment, Offset);
2341 }
2342
2343 // add Pointer, Pointer, Scratch
2344 EmitToStreamer(MCInstBuilder(AArch64::ADDXrs)
2345 .addReg(Pointer)
2346 .addReg(Pointer)
2347 .addReg(Scratch)
2348 .addImm(0));
2349 }
2350 // ldrsw Scratch, [Pointer]
2351 EmitToStreamer(MCInstBuilder(AArch64::LDRSWui)
2352 .addReg(Scratch)
2353 .addReg(Pointer)
2354 .addImm(0));
2355 }
2356 // add Pointer, Pointer, Scratch
2357 EmitToStreamer(MCInstBuilder(AArch64::ADDXrs)
2358 .addReg(Pointer)
2359 .addReg(Pointer)
2360 .addReg(Scratch)
2361 .addImm(0));
2362}
2363
2366
2367 // If an override is passed via command line argument, just use that value.
2368 if (PtrauthAuthChecks.getNumOccurrences())
2369 return PtrauthAuthChecks;
2370
2371 // Otherwise, on an FPAC CPU, you get traps whether you want them or not:
2372 // there's no point in emitting checks or traps.
2373 if (STI.hasFPAC())
2375
2376 bool ShouldTrap = MF->getFunction().hasFnAttribute("ptrauth-auth-traps");
2378}
2379
2380// We expand non-signing AUT* pseudo instructions into a sequence of the form
2381//
2382// ; 1. Authenticate Pointer
2383//
2384// or
2385//
2386// ; 1. Authenticate Pointer
2387// ; 2. Check that Pointer is valid, trap otherwise
2388//
2389// We expand AUT*PAC pseudo instructions into a sequence of the form
2390// (with addend only applied if Addend argument is given):
2391//
2392// ; 1. Authenticate Pointer
2393// ; 3. Apply addend and sign Pointer
2394//
2395// or
2396//
2397// ; 1. Authenticate Pointer
2398// ; 2. Check that Pointer is valid, trap otherwise
2399// ; 3. Apply addend and sign Pointer
2400//
2401// or
2402//
2403// ; 1. Authenticate Pointer
2404// ; 2. Check that Pointer is valid, jump to .Lon_failure otherwise
2405// ; 3. Apply addend and sign Pointer
2406// .Lon_failure:
2407//
2408void AArch64AsmPrinter::emitPtrauthAuthResign(
2409 Register Pointer, Register Scratch, PtrAuthSchema AuthSchema,
2410 std::optional<PtrAuthSchema> SignSchema, std::optional<int64_t> Addend,
2411 Value *DS) {
2412 const PtrauthCheckMode CheckMode = getCheckMode(MF);
2413 const bool IsAuthWithPC = AuthSchema.PCDisc != AArch64::NoRegister;
2414 assert(!SignSchema || SignSchema->PCDisc == AArch64::NoRegister);
2415
2416 Register SignAddrDiscOrNone =
2417 SignSchema ? SignSchema->AddrDisc : AArch64::NoRegister;
2418
2419 // 1. Authenticate Pointer - this is the only common step.
2420 // It is more complex than signing because AUTI[AB]171615 may be used.
2421
2422 if (IsAuthWithPC) {
2423 assert(Pointer == AArch64::X17 && Scratch == AArch64::X16 &&
2424 "AUTPCPAC must use x17/x16 as Pointer/Scratch");
2425
2426 assert(AuthSchema.AddrDisc == AArch64::X16 &&
2427 "AUTPCPAC requires address discriminator in X16");
2428
2429 assert(AuthSchema.PCDisc == AArch64::X15 &&
2430 "AUTPCPAC requires PC discriminator in X15");
2431
2432 assert(AuthSchema.IntDisc == 0 && "AUTPCPAC does not support IntDisc");
2433
2434 assert((AuthSchema.Key == AArch64PACKey::IB ||
2435 AuthSchema.Key == AArch64PACKey::IA) &&
2436 "AUTPCPAC only supports AUT-ing with IA/IB");
2437
2438 if (!emitDeactivationSymbolRelocation(DS)) {
2439 unsigned AutOpc = (AuthSchema.Key == AArch64PACKey::IB)
2440 ? AArch64::AUTIB171615
2441 : AArch64::AUTIA171615;
2442 EmitToStreamer(MCInstBuilder(AutOpc));
2443 }
2444 } else {
2445 // emitPtrauthDiscriminator is allowed to clobber AuthSchema.AddrDisc as
2446 // long as it is not used past this point neither externally (the register
2447 // operand is "killed"), nor internally (it does not alias anything being
2448 // used later by this pseudo instruction).
2449 //
2450 // Note that, while rather unlikely, it is technically possible to use the
2451 // Pointer to compute its own discriminator.
2452 Register AUTDiscReg = emitPtrauthDiscriminator(
2453 AuthSchema.IntDisc, AuthSchema.AddrDisc, Scratch,
2454 AuthSchema.addrDiscIsKilledAndNoneOf({Pointer, SignAddrDiscOrNone}));
2455 if (!emitDeactivationSymbolRelocation(DS))
2456 emitAUT(AuthSchema.Key, Pointer, AUTDiscReg);
2457 }
2458
2459 // The other two steps are optional, define lambdas for them:
2460 // 2. Check that Pointer is valid, on failure jump to label or trap.
2461 auto EmitCheck = [&](MCSymbol *OnFailure = nullptr) {
2462 emitPtrauthCheckAuthenticatedValue(Pointer, Scratch, AuthSchema.Key,
2463 AArch64PAuth::AuthCheckMethod::XPAC,
2464 OnFailure);
2465 };
2466 // 3. Apply addend and sign Pointer.
2467 auto EmitResignOnSuccess = [&]() {
2468 if (Addend.has_value())
2469 emitPtrauthApplyIndirectAddend(Pointer, Scratch, *Addend);
2470
2471 assert(Pointer != SignSchema->AddrDisc && "Pointer is early-clobbered");
2472 Register PACDiscReg =
2473 emitPtrauthDiscriminator(SignSchema->IntDisc, SignSchema->AddrDisc,
2474 Scratch, SignSchema->AddrDiscIsKilled);
2475 emitPAC(SignSchema->Key, Pointer, PACDiscReg);
2476 };
2477
2478 // Emit checking and resigning as needed.
2479
2480 if (!SignSchema) {
2481 if (CheckMode == PtrauthCheckMode::Trap)
2482 EmitCheck();
2483 // For authentication-only pseudos, Poison is demoted to Unchecked.
2484 return;
2485 }
2486
2487 switch (CheckMode) {
2488 case Unchecked:
2489 EmitResignOnSuccess();
2490 break;
2491 case Trap:
2492 EmitCheck();
2493 EmitResignOnSuccess();
2494 break;
2495 case Poison:
2496 MCSymbol *OnFailure = createTempSymbol("resign_end_");
2497 EmitCheck(OnFailure);
2498 EmitResignOnSuccess();
2499 OutStreamer->emitLabel(OnFailure);
2500 break;
2501 }
2502}
2503
2504void AArch64AsmPrinter::emitPtrauthSign(const MachineInstr *MI) {
2505 Register Val = MI->getOperand(1).getReg();
2506 auto Key = (AArch64PACKey::ID)MI->getOperand(2).getImm();
2507 uint64_t Disc = MI->getOperand(3).getImm();
2508 Register AddrDisc = MI->getOperand(4).getReg();
2509 bool AddrDiscKilled = MI->getOperand(4).isKill();
2510
2511 // As long as at least one of Val and AddrDisc is in GPR64noip, a scratch
2512 // register is available.
2513 Register ScratchReg = Val == AArch64::X16 ? AArch64::X17 : AArch64::X16;
2514 assert(ScratchReg != AddrDisc &&
2515 "Neither X16 nor X17 is available as a scratch register");
2516
2517 // Compute pac discriminator
2518 Register DiscReg = emitPtrauthDiscriminator(
2519 Disc, AddrDisc, ScratchReg, /*MayClobberAddrDisc=*/AddrDiscKilled);
2520
2521 if (emitDeactivationSymbolRelocation(MI->getDeactivationSymbol()))
2522 return;
2523
2524 emitPAC(Key, Val, DiscReg);
2525}
2526
2527void AArch64AsmPrinter::emitPtrauthBranch(const MachineInstr *MI) {
2528 bool IsCall = MI->getOpcode() == AArch64::BLRA;
2529 unsigned BrTarget = MI->getOperand(0).getReg();
2530
2531 auto Key = (AArch64PACKey::ID)MI->getOperand(1).getImm();
2532 uint64_t Disc = MI->getOperand(2).getImm();
2533
2534 unsigned AddrDisc = MI->getOperand(3).getReg();
2535
2536 // Make sure AddrDisc is solely used to compute the discriminator.
2537 // While hardly meaningful, it is still possible to describe an authentication
2538 // of a pointer against its own value (instead of storage address) with
2539 // intrinsics, so use report_fatal_error instead of assert.
2540 if (BrTarget == AddrDisc)
2541 report_fatal_error("Branch target is signed with its own value");
2542
2543 // If we are printing BLRA pseudo, try to save one MOV by making use of the
2544 // fact that x16 and x17 are described as clobbered by the MI instruction and
2545 // AddrDisc is not used as any other input.
2546 //
2547 // Back in the day, emitPtrauthDiscriminator was restricted to only returning
2548 // either x16 or x17, meaning the returned register is always among the
2549 // implicit-def'ed registers of BLRA pseudo. Now this property can be violated
2550 // if isX16X17Safer predicate is false, thus manually check if AddrDisc is
2551 // among x16 and x17 to prevent clobbering unexpected registers.
2552 //
2553 // Unlike BLRA, BRA pseudo is used to perform computed goto, and thus not
2554 // declared as clobbering x16/x17.
2555 //
2556 // FIXME: Make use of `killed` flags and register masks instead.
2557 bool AddrDiscIsImplicitDef =
2558 IsCall && (AddrDisc == AArch64::X16 || AddrDisc == AArch64::X17);
2559 Register DiscReg = emitPtrauthDiscriminator(Disc, AddrDisc, AArch64::X17,
2560 AddrDiscIsImplicitDef);
2561 emitBLRA(IsCall, Key, BrTarget, DiscReg);
2562}
2563
2564void AArch64AsmPrinter::emitAddImm(MCRegister Reg, int64_t Addend,
2565 MCRegister Tmp) {
2566 if (Addend != 0) {
2567 const uint64_t AbsOffset = (Addend > 0 ? Addend : -((uint64_t)Addend));
2568 const bool IsNeg = Addend < 0;
2569 if (isUInt<24>(AbsOffset)) {
2570 for (int BitPos = 0; BitPos != 24 && (AbsOffset >> BitPos);
2571 BitPos += 12) {
2572 EmitToStreamer(
2573 MCInstBuilder(IsNeg ? AArch64::SUBXri : AArch64::ADDXri)
2574 .addReg(Reg)
2575 .addReg(Reg)
2576 .addImm((AbsOffset >> BitPos) & 0xfff)
2577 .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, BitPos)));
2578 }
2579 } else {
2580 const uint64_t UAddend = Addend;
2581 EmitToStreamer(MCInstBuilder(IsNeg ? AArch64::MOVNXi : AArch64::MOVZXi)
2582 .addReg(Tmp)
2583 .addImm((IsNeg ? ~UAddend : UAddend) & 0xffff)
2584 .addImm(/*shift=*/0));
2585 auto NeedMovk = [IsNeg, UAddend](int BitPos) -> bool {
2586 assert(BitPos == 16 || BitPos == 32 || BitPos == 48);
2587 uint64_t Shifted = UAddend >> BitPos;
2588 if (!IsNeg)
2589 return Shifted != 0;
2590 for (int I = 0; I != 64 - BitPos; I += 16)
2591 if (((Shifted >> I) & 0xffff) != 0xffff)
2592 return true;
2593 return false;
2594 };
2595 for (int BitPos = 16; BitPos != 64 && NeedMovk(BitPos); BitPos += 16)
2596 emitMOVK(Tmp, (UAddend >> BitPos) & 0xffff, BitPos);
2597
2598 EmitToStreamer(MCInstBuilder(AArch64::ADDXrs)
2599 .addReg(Reg)
2600 .addReg(Reg)
2601 .addReg(Tmp)
2602 .addImm(/*shift=*/0));
2603 }
2604 }
2605}
2606
2607void AArch64AsmPrinter::emitAddress(MCRegister Reg, const MCExpr *Expr,
2608 MCRegister Tmp, bool DSOLocal,
2609 const MCSubtargetInfo &STI) {
2610 MCValue Val;
2611 if (!Expr->evaluateAsRelocatable(Val, nullptr))
2612 report_fatal_error("emitAddress could not evaluate");
2613 if (DSOLocal) {
2614 EmitToStreamer(
2615 MCInstBuilder(AArch64::ADRP)
2616 .addReg(Reg)
2618 OutStreamer->getContext())));
2619 EmitToStreamer(MCInstBuilder(AArch64::ADDXri)
2620 .addReg(Reg)
2621 .addReg(Reg)
2622 .addExpr(MCSpecifierExpr::create(
2623 Expr, AArch64::S_LO12, OutStreamer->getContext()))
2624 .addImm(0));
2625 } else {
2626 auto *SymRef =
2627 MCSymbolRefExpr::create(Val.getAddSym(), OutStreamer->getContext());
2628 EmitToStreamer(
2629 MCInstBuilder(AArch64::ADRP)
2630 .addReg(Reg)
2632 OutStreamer->getContext())));
2633 EmitToStreamer(
2634 MCInstBuilder(AArch64::LDRXui)
2635 .addReg(Reg)
2636 .addReg(Reg)
2638 OutStreamer->getContext())));
2639 emitAddImm(Reg, Val.getConstant(), Tmp);
2640 }
2641}
2642
2644 // IFUNCs are ELF-only.
2645 if (!TT.isOSBinFormatELF())
2646 return false;
2647
2648 // IFUNCs are supported on glibc, bionic, and some but not all of the BSDs.
2649 return TT.isOSGlibc() || TT.isAndroid() || TT.isOSFreeBSD() ||
2650 TT.isOSDragonFly() || TT.isOSNetBSD();
2651}
2652
2653// Emit an ifunc resolver that returns a signed pointer to the specified target,
2654// and return a FUNCINIT reference to the resolver. In the linked binary, this
2655// function becomes the target of an IRELATIVE relocation. This resolver is used
2656// to relocate signed pointers in global variable initializers in special cases
2657// where the standard R_AARCH64_AUTH_ABS64 relocation would not work.
2658//
2659// Example (signed null pointer, not address discriminated):
2660//
2661// .8byte .Lpauth_ifunc0
2662// .pushsection .text.startup,"ax",@progbits
2663// .Lpauth_ifunc0:
2664// mov x0, #0
2665// mov x1, #12345
2666// b __emupac_pacda
2667//
2668// Example (signed null pointer, address discriminated):
2669//
2670// .Ltmp:
2671// .8byte .Lpauth_ifunc0
2672// .pushsection .text.startup,"ax",@progbits
2673// .Lpauth_ifunc0:
2674// mov x0, #0
2675// adrp x1, .Ltmp
2676// add x1, x1, :lo12:.Ltmp
2677// b __emupac_pacda
2678// .popsection
2679//
2680// Example (signed pointer to symbol, not address discriminated):
2681//
2682// .Ltmp:
2683// .8byte .Lpauth_ifunc0
2684// .pushsection .text.startup,"ax",@progbits
2685// .Lpauth_ifunc0:
2686// adrp x0, symbol
2687// add x0, x0, :lo12:symbol
2688// mov x1, #12345
2689// b __emupac_pacda
2690// .popsection
2691//
2692// Example (signed null pointer, not address discriminated, with deactivation
2693// symbol ds):
2694//
2695// .8byte .Lpauth_ifunc0
2696// .pushsection .text.startup,"ax",@progbits
2697// .Lpauth_ifunc0:
2698// mov x0, #0
2699// mov x1, #12345
2700// .reloc ., R_AARCH64_PATCHINST, ds
2701// b __emupac_pacda
2702// ret
2703// .popsection
2704const MCExpr *AArch64AsmPrinter::emitPAuthRelocationAsIRelative(
2705 const MCExpr *Target, uint64_t Disc, AArch64PACKey::ID KeyID,
2706 bool HasAddressDiversity, bool IsDSOLocal, const MCExpr *DSExpr) {
2707 const Triple &TT = TM.getTargetTriple();
2708
2709 // We only emit an IRELATIVE relocation if the target supports IRELATIVE.
2711 return nullptr;
2712
2713 // For now, only the DA key is supported.
2714 if (KeyID != AArch64PACKey::DA)
2715 return nullptr;
2716
2717 // AArch64Subtarget is huge, so heap allocate it so we don't run out of stack
2718 // space.
2719 auto STI = std::make_unique<AArch64Subtarget>(
2720 TT, TM.getTargetCPU(), TM.getTargetCPU(), TM.getTargetFeatureString(), TM,
2721 true);
2722 this->STI = STI.get();
2723
2724 MCSymbol *Place = OutStreamer->getContext().createTempSymbol();
2725 OutStreamer->emitLabel(Place);
2726 OutStreamer->pushSection();
2727
2728 const MCSymbolELF *Group =
2729 static_cast<MCSectionELF *>(OutStreamer->getCurrentSectionOnly())
2730 ->getGroup();
2732 if (Group)
2734 OutStreamer->switchSection(OutStreamer->getContext().getELFSection(
2735 ".text.startup", ELF::SHT_PROGBITS, Flags, 0, Group, true,
2736 Group ? MCSection::NonUniqueID : PAuthIFuncNextUniqueID++, nullptr));
2737
2738 MCSymbol *IRelativeSym =
2739 OutStreamer->getContext().createLinkerPrivateSymbol("pauth_ifunc");
2740 OutStreamer->emitLabel(IRelativeSym);
2741 if (isa<MCConstantExpr>(Target)) {
2742 OutStreamer->emitInstruction(MCInstBuilder(AArch64::MOVZXi)
2743 .addReg(AArch64::X0)
2744 .addExpr(Target)
2745 .addImm(0),
2746 *STI);
2747 } else {
2748 emitAddress(AArch64::X0, Target, AArch64::X16, IsDSOLocal, *STI);
2749 }
2750 if (HasAddressDiversity) {
2751 auto *PlacePlusDisc = MCBinaryExpr::createAdd(
2752 MCSymbolRefExpr::create(Place, OutStreamer->getContext()),
2753 MCConstantExpr::create(Disc, OutStreamer->getContext()),
2754 OutStreamer->getContext());
2755 emitAddress(AArch64::X1, PlacePlusDisc, AArch64::X16, /*IsDSOLocal=*/true,
2756 *STI);
2757 } else {
2758 if (!isUInt<16>(Disc)) {
2759 OutContext.reportError(SMLoc(), "AArch64 PAC Discriminator '" +
2760 Twine(Disc) +
2761 "' out of range [0, 0xFFFF]");
2762 }
2763 emitMOVZ(AArch64::X1, Disc, 0);
2764 }
2765
2766 if (DSExpr) {
2767 MCSymbol *PrePACInst = OutStreamer->getContext().createTempSymbol();
2768 OutStreamer->emitLabel(PrePACInst);
2769
2770 auto *PrePACInstExpr =
2771 MCSymbolRefExpr::create(PrePACInst, OutStreamer->getContext());
2772 OutStreamer->emitRelocDirective(*PrePACInstExpr, "R_AARCH64_PATCHINST",
2773 DSExpr, SMLoc());
2774 }
2775
2776 // We don't know the subtarget because this is being emitted for a global
2777 // initializer. Because the performance of IFUNC resolvers is unimportant, we
2778 // always call the EmuPAC runtime, which will end up using the PAC instruction
2779 // if the target supports PAC.
2780 MCSymbol *EmuPAC =
2781 OutStreamer->getContext().getOrCreateSymbol("__emupac_pacda");
2782 const MCSymbolRefExpr *EmuPACRef =
2783 MCSymbolRefExpr::create(EmuPAC, OutStreamer->getContext());
2784 OutStreamer->emitInstruction(MCInstBuilder(AArch64::B).addExpr(EmuPACRef),
2785 *STI);
2786
2787 // We need a RET despite the above tail call because the deactivation symbol
2788 // may replace the tail call with a NOP.
2789 if (DSExpr)
2790 OutStreamer->emitInstruction(
2791 MCInstBuilder(AArch64::RET).addReg(AArch64::LR), *STI);
2792 OutStreamer->popSection();
2793
2795 MCSymbolRefExpr::create(IRelativeSym, OutStreamer->getContext()),
2796 AArch64::S_FUNCINIT, OutStreamer->getContext());
2797}
2798
2799const MCExpr *
2800AArch64AsmPrinter::lowerConstantPtrAuth(const ConstantPtrAuth &CPA) {
2801 MCContext &Ctx = OutContext;
2802
2803 // Figure out the base symbol and the addend, if any.
2804 APInt Offset(64, 0);
2805 const Value *BaseGV = CPA.getPointer()->stripAndAccumulateConstantOffsets(
2806 getDataLayout(), Offset, /*AllowNonInbounds=*/true);
2807
2808 auto *BaseGVB = dyn_cast<GlobalValue>(BaseGV);
2809
2810 const MCExpr *Sym;
2811 if (BaseGVB) {
2812 // If there is an addend, turn that into the appropriate MCExpr.
2813 Sym = MCSymbolRefExpr::create(getSymbol(BaseGVB), Ctx);
2814 if (Offset.sgt(0))
2816 Sym, MCConstantExpr::create(Offset.getSExtValue(), Ctx), Ctx);
2817 else if (Offset.slt(0))
2819 Sym, MCConstantExpr::create((-Offset).getSExtValue(), Ctx), Ctx);
2820 } else if (isa<ConstantPointerNull>(BaseGV)) {
2821 Sym = MCConstantExpr::create(Offset.getSExtValue(), Ctx);
2822 } else {
2823 reportFatalUsageError("unsupported constant expression in ptrauth pointer");
2824 }
2825
2826 const MCExpr *DSExpr = nullptr;
2827 if (auto *DS = dyn_cast<GlobalValue>(CPA.getDeactivationSymbol())) {
2828 if (isa<GlobalAlias>(DS))
2829 return Sym;
2830 DSExpr = MCSymbolRefExpr::create(getSymbol(DS), Ctx);
2831 }
2832
2833 uint64_t KeyID = CPA.getKey()->getZExtValue();
2834 // We later rely on valid KeyID value in AArch64PACKeyIDToString call from
2835 // AArch64AuthMCExpr::printImpl, so fail fast.
2836 if (KeyID > AArch64PACKey::LAST) {
2837 CPA.getContext().emitError("AArch64 PAC Key ID '" + Twine(KeyID) +
2838 "' out of range [0, " +
2839 Twine((unsigned)AArch64PACKey::LAST) + "]");
2840 KeyID = 0;
2841 }
2842
2843 uint64_t Disc = CPA.getDiscriminator()->getZExtValue();
2844
2845 // Check if we can represent this with an IRELATIVE and emit it if so.
2846 if (auto *IFuncSym = emitPAuthRelocationAsIRelative(
2847 Sym, Disc, AArch64PACKey::ID(KeyID), CPA.hasAddressDiscriminator(),
2848 BaseGVB && BaseGVB->isDSOLocal(), DSExpr))
2849 return IFuncSym;
2850
2851 if (!isUInt<16>(Disc)) {
2852 CPA.getContext().emitError("AArch64 PAC Discriminator '" + Twine(Disc) +
2853 "' out of range [0, 0xFFFF]");
2854 Disc = 0;
2855 }
2856
2857 if (DSExpr)
2858 report_fatal_error("deactivation symbols unsupported in constant "
2859 "expressions on this target");
2860
2861 // Finally build the complete @AUTH expr.
2862 return AArch64AuthMCExpr::create(Sym, Disc, AArch64PACKey::ID(KeyID),
2863 CPA.hasAddressDiscriminator(), Ctx);
2864}
2865
2866void AArch64AsmPrinter::LowerLOADauthptrstatic(const MachineInstr &MI) {
2867 unsigned DstReg = MI.getOperand(0).getReg();
2868 const MachineOperand &GAOp = MI.getOperand(1);
2869 const uint64_t KeyC = MI.getOperand(2).getImm();
2870 assert(KeyC <= AArch64PACKey::LAST &&
2871 "key is out of range [0, AArch64PACKey::LAST]");
2872 const auto Key = (AArch64PACKey::ID)KeyC;
2873 const uint64_t Disc = MI.getOperand(3).getImm();
2874 assert(isUInt<16>(Disc) &&
2875 "constant discriminator is out of range [0, 0xffff]");
2876
2877 // Emit instruction sequence like the following:
2878 // ADRP x16, symbol$auth_ptr$key$disc
2879 // LDR x16, [x16, :lo12:symbol$auth_ptr$key$disc]
2880 //
2881 // Where the $auth_ptr$ symbol is the stub slot containing the signed pointer
2882 // to symbol.
2883 MCSymbol *AuthPtrStubSym;
2884 if (TM.getTargetTriple().isOSBinFormatELF()) {
2885 const auto &TLOF =
2886 static_cast<const AArch64_ELFTargetObjectFile &>(getObjFileLowering());
2887
2888 assert(GAOp.getOffset() == 0 &&
2889 "non-zero offset for $auth_ptr$ stub slots is not supported");
2890 const MCSymbol *GASym = TM.getSymbol(GAOp.getGlobal());
2891 AuthPtrStubSym = TLOF.getAuthPtrSlotSymbol(TM, MMI, GASym, Key, Disc);
2892 } else {
2893 assert(TM.getTargetTriple().isOSBinFormatMachO() &&
2894 "LOADauthptrstatic is implemented only for MachO/ELF");
2895
2896 const auto &TLOF = static_cast<const AArch64_MachoTargetObjectFile &>(
2897 getObjFileLowering());
2898
2899 assert(GAOp.getOffset() == 0 &&
2900 "non-zero offset for $auth_ptr$ stub slots is not supported");
2901 const MCSymbol *GASym = TM.getSymbol(GAOp.getGlobal());
2902 AuthPtrStubSym = TLOF.getAuthPtrSlotSymbol(TM, MMI, GASym, Key, Disc);
2903 }
2904
2905 MachineOperand StubMOHi =
2907 MachineOperand StubMOLo = MachineOperand::CreateMCSymbol(
2908 AuthPtrStubSym, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
2909 MCOperand StubMCHi, StubMCLo;
2910
2911 MCInstLowering.lowerOperand(StubMOHi, StubMCHi);
2912 MCInstLowering.lowerOperand(StubMOLo, StubMCLo);
2913
2914 EmitToStreamer(
2915 *OutStreamer,
2916 MCInstBuilder(AArch64::ADRP).addReg(DstReg).addOperand(StubMCHi));
2917
2918 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::LDRXui)
2919 .addReg(DstReg)
2920 .addReg(DstReg)
2921 .addOperand(StubMCLo));
2922}
2923
2924void AArch64AsmPrinter::LowerMOVaddrPAC(const MachineInstr &MI) {
2925 const bool IsGOTLoad = MI.getOpcode() == AArch64::LOADgotPAC;
2926 const bool IsELFSignedGOT = MI.getParent()
2927 ->getParent()
2928 ->getInfo<AArch64FunctionInfo>()
2929 ->hasELFSignedGOT();
2930 MachineOperand GAOp = MI.getOperand(0);
2931 const uint64_t KeyC = MI.getOperand(1).getImm();
2932 assert(KeyC <= AArch64PACKey::LAST &&
2933 "key is out of range [0, AArch64PACKey::LAST]");
2934 const auto Key = (AArch64PACKey::ID)KeyC;
2935 const unsigned AddrDisc = MI.getOperand(2).getReg();
2936 const uint64_t Disc = MI.getOperand(3).getImm();
2937
2938 const int64_t Offset = GAOp.getOffset();
2939 GAOp.setOffset(0);
2940
2941 // Emit:
2942 // target materialization:
2943 // - via GOT:
2944 // - unsigned GOT:
2945 // adrp x16, :got:target
2946 // ldr x16, [x16, :got_lo12:target]
2947 // add offset to x16 if offset != 0
2948 // - ELF signed GOT:
2949 // adrp x17, :got:target
2950 // add x17, x17, :got_auth_lo12:target
2951 // ldr x16, [x17]
2952 // aut{i|d}a x16, x17
2953 // check+trap sequence (if no FPAC)
2954 // add offset to x16 if offset != 0
2955 //
2956 // - direct:
2957 // adrp x16, target
2958 // add x16, x16, :lo12:target
2959 // add offset to x16 if offset != 0
2960 //
2961 // add offset to x16:
2962 // - abs(offset) fits 24 bits:
2963 // add/sub x16, x16, #<offset>[, #lsl 12] (up to 2 instructions)
2964 // - abs(offset) does not fit 24 bits:
2965 // - offset < 0:
2966 // movn+movk sequence filling x17 register with the offset (up to 4
2967 // instructions)
2968 // add x16, x16, x17
2969 // - offset > 0:
2970 // movz+movk sequence filling x17 register with the offset (up to 4
2971 // instructions)
2972 // add x16, x16, x17
2973 //
2974 // signing:
2975 // - 0 discriminator:
2976 // paciza x16
2977 // - Non-0 discriminator, no address discriminator:
2978 // mov x17, #Disc
2979 // pacia x16, x17
2980 // - address discriminator (with potentially folded immediate discriminator):
2981 // pacia x16, xAddrDisc
2982
2983 MachineOperand GAMOHi(GAOp), GAMOLo(GAOp);
2984 MCOperand GAMCHi, GAMCLo;
2985
2986 GAMOHi.setTargetFlags(AArch64II::MO_PAGE);
2987 GAMOLo.setTargetFlags(AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
2988 if (IsGOTLoad) {
2989 GAMOHi.addTargetFlag(AArch64II::MO_GOT);
2990 GAMOLo.addTargetFlag(AArch64II::MO_GOT);
2991 }
2992
2993 MCInstLowering.lowerOperand(GAMOHi, GAMCHi);
2994 MCInstLowering.lowerOperand(GAMOLo, GAMCLo);
2995
2996 EmitToStreamer(
2997 MCInstBuilder(AArch64::ADRP)
2998 .addReg(IsGOTLoad && IsELFSignedGOT ? AArch64::X17 : AArch64::X16)
2999 .addOperand(GAMCHi));
3000
3001 if (IsGOTLoad) {
3002 if (IsELFSignedGOT) {
3003 EmitToStreamer(MCInstBuilder(AArch64::ADDXri)
3004 .addReg(AArch64::X17)
3005 .addReg(AArch64::X17)
3006 .addOperand(GAMCLo)
3007 .addImm(0));
3008
3009 EmitToStreamer(MCInstBuilder(AArch64::LDRXui)
3010 .addReg(AArch64::X16)
3011 .addReg(AArch64::X17)
3012 .addImm(0));
3013
3014 assert(GAOp.isGlobal());
3015 assert(GAOp.getGlobal()->getValueType() != nullptr);
3016
3017 bool IsFunctionTy = GAOp.getGlobal()->getValueType()->isFunctionTy();
3018 auto AuthKey = IsFunctionTy ? AArch64PACKey::IA : AArch64PACKey::DA;
3019 emitAUT(AuthKey, AArch64::X16, AArch64::X17);
3020
3021 if (!STI->hasFPAC())
3022 emitPtrauthCheckAuthenticatedValue(AArch64::X16, AArch64::X17, AuthKey,
3023 AArch64PAuth::AuthCheckMethod::XPAC);
3024 } else {
3025 EmitToStreamer(MCInstBuilder(AArch64::LDRXui)
3026 .addReg(AArch64::X16)
3027 .addReg(AArch64::X16)
3028 .addOperand(GAMCLo));
3029 }
3030 } else {
3031 EmitToStreamer(MCInstBuilder(AArch64::ADDXri)
3032 .addReg(AArch64::X16)
3033 .addReg(AArch64::X16)
3034 .addOperand(GAMCLo)
3035 .addImm(0));
3036 }
3037
3038 emitAddImm(AArch64::X16, Offset, AArch64::X17);
3039 Register DiscReg = emitPtrauthDiscriminator(Disc, AddrDisc, AArch64::X17);
3040
3041 emitPAC(Key, AArch64::X16, DiscReg);
3042}
3043
3044void AArch64AsmPrinter::LowerLOADgotAUTH(const MachineInstr &MI) {
3045 Register DstReg = MI.getOperand(0).getReg();
3046 Register AuthResultReg = STI->hasFPAC() ? DstReg : AArch64::X16;
3047 const MachineOperand &GAMO = MI.getOperand(1);
3048 assert(GAMO.getOffset() == 0);
3049
3050 if (MI.getMF()->getTarget().getCodeModel() == CodeModel::Tiny) {
3051 MCOperand GAMC;
3052 MCInstLowering.lowerOperand(GAMO, GAMC);
3053 EmitToStreamer(
3054 MCInstBuilder(AArch64::ADR).addReg(AArch64::X17).addOperand(GAMC));
3055 EmitToStreamer(MCInstBuilder(AArch64::LDRXui)
3056 .addReg(AuthResultReg)
3057 .addReg(AArch64::X17)
3058 .addImm(0));
3059 } else {
3060 MachineOperand GAHiOp(GAMO);
3061 MachineOperand GALoOp(GAMO);
3062 GAHiOp.addTargetFlag(AArch64II::MO_PAGE);
3063 GALoOp.addTargetFlag(AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3064
3065 MCOperand GAMCHi, GAMCLo;
3066 MCInstLowering.lowerOperand(GAHiOp, GAMCHi);
3067 MCInstLowering.lowerOperand(GALoOp, GAMCLo);
3068
3069 EmitToStreamer(
3070 MCInstBuilder(AArch64::ADRP).addReg(AArch64::X17).addOperand(GAMCHi));
3071
3072 EmitToStreamer(MCInstBuilder(AArch64::ADDXri)
3073 .addReg(AArch64::X17)
3074 .addReg(AArch64::X17)
3075 .addOperand(GAMCLo)
3076 .addImm(0));
3077
3078 EmitToStreamer(MCInstBuilder(AArch64::LDRXui)
3079 .addReg(AuthResultReg)
3080 .addReg(AArch64::X17)
3081 .addImm(0));
3082 }
3083
3084 assert(GAMO.isGlobal());
3085 MCSymbol *UndefWeakSym;
3086 if (GAMO.getGlobal()->hasExternalWeakLinkage()) {
3087 UndefWeakSym = createTempSymbol("undef_weak");
3088 EmitToStreamer(
3089 MCInstBuilder(AArch64::CBZX)
3090 .addReg(AuthResultReg)
3091 .addExpr(MCSymbolRefExpr::create(UndefWeakSym, OutContext)));
3092 }
3093
3094 assert(GAMO.getGlobal()->getValueType() != nullptr);
3095
3096 bool IsFunctionTy = GAMO.getGlobal()->getValueType()->isFunctionTy();
3097 auto AuthKey = IsFunctionTy ? AArch64PACKey::IA : AArch64PACKey::DA;
3098 emitAUT(AuthKey, AuthResultReg, AArch64::X17);
3099
3100 if (GAMO.getGlobal()->hasExternalWeakLinkage())
3101 OutStreamer->emitLabel(UndefWeakSym);
3102
3103 if (!STI->hasFPAC()) {
3104 emitPtrauthCheckAuthenticatedValue(AuthResultReg, AArch64::X17, AuthKey,
3105 AArch64PAuth::AuthCheckMethod::XPAC);
3106
3107 emitMovXReg(DstReg, AuthResultReg);
3108 }
3109}
3110
3111const MCExpr *
3112AArch64AsmPrinter::lowerBlockAddressConstant(const BlockAddress &BA) {
3113 const MCExpr *BAE = AsmPrinter::lowerBlockAddressConstant(BA);
3114 const Function &Fn = *BA.getFunction();
3115
3116 if (std::optional<uint16_t> BADisc =
3117 STI->getPtrAuthBlockAddressDiscriminatorIfEnabled(Fn))
3118 return AArch64AuthMCExpr::create(BAE, *BADisc, AArch64PACKey::IA,
3119 /*HasAddressDiversity=*/false, OutContext);
3120
3121 return BAE;
3122}
3123
3124void AArch64AsmPrinter::emitCBPseudoExpansion(const MachineInstr *MI) {
3125 bool IsImm = false;
3126 unsigned Width = 0;
3127
3128 switch (MI->getOpcode()) {
3129 default:
3130 llvm_unreachable("This is not a CB pseudo instruction");
3131 case AArch64::CBBAssertExt:
3132 IsImm = false;
3133 Width = 8;
3134 break;
3135 case AArch64::CBHAssertExt:
3136 IsImm = false;
3137 Width = 16;
3138 break;
3139 case AArch64::CBWPrr:
3140 Width = 32;
3141 break;
3142 case AArch64::CBXPrr:
3143 Width = 64;
3144 break;
3145 case AArch64::CBWPri:
3146 IsImm = true;
3147 Width = 32;
3148 break;
3149 case AArch64::CBXPri:
3150 IsImm = true;
3151 Width = 64;
3152 break;
3153 }
3154
3156 static_cast<AArch64CC::CondCode>(MI->getOperand(0).getImm());
3157 bool NeedsRegSwap = false;
3158 bool NeedsImmDec = false;
3159 bool NeedsImmInc = false;
3160
3161#define GET_CB_OPC(IsImm, Width, ImmCond, RegCond) \
3162 (IsImm \
3163 ? (Width == 32 ? AArch64::CB##ImmCond##Wri : AArch64::CB##ImmCond##Xri) \
3164 : (Width == 8 \
3165 ? AArch64::CBB##RegCond##Wrr \
3166 : (Width == 16 ? AArch64::CBH##RegCond##Wrr \
3167 : (Width == 32 ? AArch64::CB##RegCond##Wrr \
3168 : AArch64::CB##RegCond##Xrr))))
3169 unsigned MCOpC;
3170
3171 // Decide if we need to either swap register operands or increment/decrement
3172 // immediate operands
3173 switch (CC) {
3174 default:
3175 llvm_unreachable("Invalid CB condition code");
3176 case AArch64CC::EQ:
3177 MCOpC = GET_CB_OPC(IsImm, Width, /* Reg-Imm */ EQ, /* Reg-Reg */ EQ);
3178 break;
3179 case AArch64CC::NE:
3180 MCOpC = GET_CB_OPC(IsImm, Width, /* Reg-Imm */ NE, /* Reg-Reg */ NE);
3181 break;
3182 case AArch64CC::HS:
3183 MCOpC = GET_CB_OPC(IsImm, Width, /* Reg-Imm */ HI, /* Reg-Reg */ HS);
3184 NeedsImmDec = IsImm;
3185 break;
3186 case AArch64CC::LO:
3187 MCOpC = GET_CB_OPC(IsImm, Width, /* Reg-Imm */ LO, /* Reg-Reg */ HI);
3188 NeedsRegSwap = !IsImm;
3189 break;
3190 case AArch64CC::HI:
3191 MCOpC = GET_CB_OPC(IsImm, Width, /* Reg-Imm */ HI, /* Reg-Reg */ HI);
3192 break;
3193 case AArch64CC::LS:
3194 MCOpC = GET_CB_OPC(IsImm, Width, /* Reg-Imm */ LO, /* Reg-Reg */ HS);
3195 NeedsRegSwap = !IsImm;
3196 NeedsImmInc = IsImm;
3197 break;
3198 case AArch64CC::GE:
3199 MCOpC = GET_CB_OPC(IsImm, Width, /* Reg-Imm */ GT, /* Reg-Reg */ GE);
3200 NeedsImmDec = IsImm;
3201 break;
3202 case AArch64CC::LT:
3203 MCOpC = GET_CB_OPC(IsImm, Width, /* Reg-Imm */ LT, /* Reg-Reg */ GT);
3204 NeedsRegSwap = !IsImm;
3205 break;
3206 case AArch64CC::GT:
3207 MCOpC = GET_CB_OPC(IsImm, Width, /* Reg-Imm */ GT, /* Reg-Reg */ GT);
3208 break;
3209 case AArch64CC::LE:
3210 MCOpC = GET_CB_OPC(IsImm, Width, /* Reg-Imm */ LT, /* Reg-Reg */ GE);
3211 NeedsRegSwap = !IsImm;
3212 NeedsImmInc = IsImm;
3213 break;
3214 }
3215#undef GET_CB_OPC
3216
3217 MCInst Inst;
3218 Inst.setOpcode(MCOpC);
3219
3220 MCOperand Lhs, Rhs, Trgt;
3221 lowerOperand(MI->getOperand(1), Lhs);
3222 lowerOperand(MI->getOperand(2), Rhs);
3223 lowerOperand(MI->getOperand(3), Trgt);
3224
3225 // Now swap, increment or decrement
3226 if (NeedsRegSwap) {
3227 assert(Lhs.isReg() && "Expected register operand for CB");
3228 assert(Rhs.isReg() && "Expected register operand for CB");
3229 Inst.addOperand(Rhs);
3230 Inst.addOperand(Lhs);
3231 } else if (NeedsImmDec) {
3232 Rhs.setImm(Rhs.getImm() - 1);
3233 Inst.addOperand(Lhs);
3234 Inst.addOperand(Rhs);
3235 } else if (NeedsImmInc) {
3236 Rhs.setImm(Rhs.getImm() + 1);
3237 Inst.addOperand(Lhs);
3238 Inst.addOperand(Rhs);
3239 } else {
3240 Inst.addOperand(Lhs);
3241 Inst.addOperand(Rhs);
3242 }
3243
3244 assert((!IsImm || (Rhs.getImm() >= 0 && Rhs.getImm() < 64)) &&
3245 "CB immediate operand out-of-bounds");
3246
3247 Inst.addOperand(Trgt);
3248 EmitToStreamer(*OutStreamer, Inst);
3249}
3250
3251// Simple pseudo-instructions have their lowering (with expansion to real
3252// instructions) auto-generated.
3253#include "AArch64GenMCPseudoLowering.inc"
3254
3255void AArch64AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
3256 S.emitInstruction(Inst, *STI);
3257#ifndef NDEBUG
3258 ++InstsEmitted;
3259#endif
3260}
3261
3262void AArch64AsmPrinter::emitInstruction(const MachineInstr *MI) {
3263 AArch64_MC::verifyInstructionPredicates(MI->getOpcode(), STI->getFeatureBits());
3264
3265#ifndef NDEBUG
3266 InstsEmitted = 0;
3267 llvm::scope_exit CheckMISize([&]() {
3268 assert(STI->getInstrInfo()->getInstSizeInBytes(*MI) >= InstsEmitted * 4);
3269 });
3270#endif
3271
3272 // Do any auto-generated pseudo lowerings.
3273 if (MCInst OutInst; lowerPseudoInstExpansion(MI, OutInst)) {
3274 EmitToStreamer(*OutStreamer, OutInst);
3275 return;
3276 }
3277
3278 if (MI->getOpcode() == AArch64::ADRP) {
3279 for (auto &Opd : MI->operands()) {
3280 if (Opd.isSymbol() && StringRef(Opd.getSymbolName()) ==
3281 "swift_async_extendedFramePointerFlags") {
3282 ShouldEmitWeakSwiftAsyncExtendedFramePointerFlags = true;
3283 }
3284 }
3285 }
3286
3287 if (AArch64FI->getLOHRelated().count(MI)) {
3288 // Generate a label for LOH related instruction
3289 MCSymbol *LOHLabel = createTempSymbol("loh");
3290 // Associate the instruction with the label
3291 LOHInstToLabel[MI] = LOHLabel;
3292 OutStreamer->emitLabel(LOHLabel);
3293 }
3294
3295 AArch64TargetStreamer *TS =
3296 static_cast<AArch64TargetStreamer *>(OutStreamer->getTargetStreamer());
3297 // Do any manual lowerings.
3298 switch (MI->getOpcode()) {
3299 default:
3301 "Unhandled tail call instruction");
3302 break;
3303 case AArch64::READ_REGISTER_GPR64:
3304 // Read of a named GPR: emit "mov Xt, Xn" (ORR Xt, XZR, Xn). The source
3305 // register is encoded as an immediate operand so that earlier passes do not
3306 // see a use of an undefined physical register.
3307 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::ORRXrs)
3308 .addReg(MI->getOperand(0).getReg())
3309 .addReg(AArch64::XZR)
3310 .addReg(MI->getOperand(1).getImm())
3311 .addImm(0));
3312 return;
3313 case AArch64::READ_REGISTER_FPR64:
3314 // Read of a named FP/SIMD d-register: emit "fmov Dt, Dn".
3315 EmitToStreamer(*OutStreamer, MCInstBuilder(AArch64::FMOVDr)
3316 .addReg(MI->getOperand(0).getReg())
3317 .addReg(MI->getOperand(1).getImm()));
3318 return;
3319 case AArch64::HINT: {
3320 // CurrentPatchableFunctionEntrySym can be CurrentFnBegin only for
3321 // -fpatchable-function-entry=N,0. The entry MBB is guaranteed to be
3322 // non-empty. If MI is the initial BTI, place the
3323 // __patchable_function_entries label after BTI.
3324 if (CurrentPatchableFunctionEntrySym &&
3325 CurrentPatchableFunctionEntrySym == CurrentFnBegin &&
3326 MI == &MF->front().front()) {
3327 int64_t Imm = MI->getOperand(0).getImm();
3328 if (Imm == 32 || Imm == 34 || Imm == 36 || Imm == 38) {
3329 MCInst Inst;
3330 MCInstLowering.Lower(MI, Inst);
3331 EmitToStreamer(*OutStreamer, Inst);
3332 CurrentPatchableFunctionEntrySym = createTempSymbol("patch");
3333 OutStreamer->emitLabel(CurrentPatchableFunctionEntrySym);
3334 return;
3335 }
3336 }
3337 break;
3338 }
3339 case AArch64::MOVMCSym: {
3340 Register DestReg = MI->getOperand(0).getReg();
3341 const MachineOperand &MO_Sym = MI->getOperand(1);
3342 MachineOperand Hi_MOSym(MO_Sym), Lo_MOSym(MO_Sym);
3343 MCOperand Hi_MCSym, Lo_MCSym;
3344
3345 Hi_MOSym.setTargetFlags(AArch64II::MO_G1 | AArch64II::MO_S);
3346 Lo_MOSym.setTargetFlags(AArch64II::MO_G0 | AArch64II::MO_NC);
3347
3348 MCInstLowering.lowerOperand(Hi_MOSym, Hi_MCSym);
3349 MCInstLowering.lowerOperand(Lo_MOSym, Lo_MCSym);
3350
3351 MCInst MovZ;
3352 MovZ.setOpcode(AArch64::MOVZXi);
3353 MovZ.addOperand(MCOperand::createReg(DestReg));
3354 MovZ.addOperand(Hi_MCSym);
3356 EmitToStreamer(*OutStreamer, MovZ);
3357
3358 MCInst MovK;
3359 MovK.setOpcode(AArch64::MOVKXi);
3360 MovK.addOperand(MCOperand::createReg(DestReg));
3361 MovK.addOperand(MCOperand::createReg(DestReg));
3362 MovK.addOperand(Lo_MCSym);
3364 EmitToStreamer(*OutStreamer, MovK);
3365 return;
3366 }
3367 case AArch64::MOVIv2d_ns:
3368 // It is generally beneficial to rewrite "fmov s0, wzr" to "movi d0, #0".
3369 // as movi is more efficient across all cores. Newer cores can eliminate
3370 // fmovs early and there is no difference with movi, but this not true for
3371 // all implementations.
3372 //
3373 // The floating-point version doesn't quite work in rare cases on older
3374 // CPUs, so on those targets we lower this instruction to movi.16b instead.
3375 if (STI->hasZeroCycleZeroingFPWorkaround() &&
3376 MI->getOperand(1).getImm() == 0) {
3377 MCInst TmpInst;
3378 TmpInst.setOpcode(AArch64::MOVIv16b_ns);
3379 TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
3380 TmpInst.addOperand(MCOperand::createImm(0));
3381 EmitToStreamer(*OutStreamer, TmpInst);
3382 return;
3383 }
3384 break;
3385
3386 case AArch64::DBG_VALUE:
3387 case AArch64::DBG_VALUE_LIST:
3388 if (isVerbose() && OutStreamer->hasRawTextSupport()) {
3389 SmallString<128> TmpStr;
3390 raw_svector_ostream OS(TmpStr);
3391 PrintDebugValueComment(MI, OS);
3392 OutStreamer->emitRawText(StringRef(OS.str()));
3393 }
3394 return;
3395
3396 case AArch64::EMITBKEY: {
3397 ExceptionHandling ExceptionHandlingType = MAI.getExceptionHandlingType();
3398 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
3399 ExceptionHandlingType != ExceptionHandling::ARM)
3400 return;
3401
3402 if (getFunctionCFISectionType(*MF) == CFISection::None)
3403 return;
3404
3405 OutStreamer->emitCFIBKeyFrame();
3406 return;
3407 }
3408
3409 case AArch64::EMITMTETAGGED: {
3410 ExceptionHandling ExceptionHandlingType = MAI.getExceptionHandlingType();
3411 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
3412 ExceptionHandlingType != ExceptionHandling::ARM)
3413 return;
3414
3415 if (getFunctionCFISectionType(*MF) != CFISection::None)
3416 OutStreamer->emitCFIMTETaggedFrame();
3417 return;
3418 }
3419
3420 case AArch64::AUTx16x17: {
3421 const Register Pointer = AArch64::X16;
3422 const Register Scratch = AArch64::X17;
3423
3424 auto AuthSchema = PtrAuthSchema::CreateImmReg(
3425 (AArch64PACKey::ID)MI->getOperand(0).getImm(),
3426 MI->getOperand(1).getImm(), MI->getOperand(2));
3427
3428 emitPtrauthAuthResign(Pointer, Scratch, AuthSchema, std::nullopt,
3429 std::nullopt, MI->getDeactivationSymbol());
3430 return;
3431 }
3432
3433 case AArch64::AUTxMxN: {
3434 const Register Pointer = MI->getOperand(0).getReg();
3435 const Register Scratch = MI->getOperand(1).getReg();
3436
3437 auto AuthSchema = PtrAuthSchema::CreateImmReg(
3438 (AArch64PACKey::ID)MI->getOperand(3).getImm(),
3439 MI->getOperand(4).getImm(), MI->getOperand(5));
3440
3441 emitPtrauthAuthResign(Pointer, Scratch, AuthSchema, std::nullopt,
3442 std::nullopt, MI->getDeactivationSymbol());
3443 return;
3444 }
3445
3446 case AArch64::AUTPAC: {
3447 const Register Pointer = AArch64::X16;
3448 const Register Scratch = AArch64::X17;
3449
3450 auto AuthSchema = PtrAuthSchema::CreateImmReg(
3451 (AArch64PACKey::ID)MI->getOperand(0).getImm(),
3452 MI->getOperand(1).getImm(), MI->getOperand(2));
3453
3454 auto SignSchema = PtrAuthSchema::CreateImmReg(
3455 (AArch64PACKey::ID)MI->getOperand(3).getImm(),
3456 MI->getOperand(4).getImm(), MI->getOperand(5));
3457
3458 emitPtrauthAuthResign(Pointer, Scratch, AuthSchema, SignSchema,
3459 std::nullopt, MI->getDeactivationSymbol());
3460 return;
3461 }
3462
3463 case AArch64::AUTPCPAC: {
3464 auto AuthSchema = PtrAuthSchema::CreateRegReg(
3465 (AArch64PACKey::ID)MI->getOperand(0).getImm(), AArch64::X16,
3466 AArch64::X15);
3467
3468 auto SignSchema = PtrAuthSchema::CreateImmReg(
3469 (AArch64PACKey::ID)MI->getOperand(1).getImm(),
3470 MI->getOperand(2).getImm(), MI->getOperand(3));
3471
3472 emitPtrauthAuthResign(/*Pointer=*/AArch64::X17, /*Scratch=*/AArch64::X16,
3473 AuthSchema, SignSchema, std::nullopt,
3474 MI->getDeactivationSymbol());
3475 return;
3476 }
3477
3478 case AArch64::AUTRELLOADPAC: {
3479 const Register Pointer = AArch64::X16;
3480 const Register Scratch = AArch64::X17;
3481
3482 auto AuthSchema = PtrAuthSchema::CreateImmReg(
3483 (AArch64PACKey::ID)MI->getOperand(0).getImm(),
3484 MI->getOperand(1).getImm(), MI->getOperand(2));
3485
3486 auto SignSchema = PtrAuthSchema::CreateImmReg(
3487 (AArch64PACKey::ID)MI->getOperand(3).getImm(),
3488 MI->getOperand(4).getImm(), MI->getOperand(5));
3489
3490 emitPtrauthAuthResign(Pointer, Scratch, AuthSchema, SignSchema,
3491 MI->getOperand(6).getImm(),
3492 MI->getDeactivationSymbol());
3493
3494 return;
3495 }
3496
3497 case AArch64::PAC:
3498 emitPtrauthSign(MI);
3499 return;
3500
3501 case AArch64::LOADauthptrstatic:
3502 LowerLOADauthptrstatic(*MI);
3503 return;
3504
3505 case AArch64::LOADgotPAC:
3506 case AArch64::MOVaddrPAC:
3507 LowerMOVaddrPAC(*MI);
3508 return;
3509
3510 case AArch64::LOADgotAUTH:
3511 LowerLOADgotAUTH(*MI);
3512 return;
3513
3514 case AArch64::BRA:
3515 case AArch64::BLRA:
3516 emitPtrauthBranch(MI);
3517 return;
3518
3519 // Tail calls use pseudo instructions so they have the proper code-gen
3520 // attributes (isCall, isReturn, etc.). We lower them to the real
3521 // instruction here.
3522 case AArch64::AUTH_TCRETURN:
3523 case AArch64::AUTH_TCRETURN_BTI: {
3524 Register Callee = MI->getOperand(0).getReg();
3525 const auto Key = (AArch64PACKey::ID)MI->getOperand(2).getImm();
3526 const uint64_t Disc = MI->getOperand(3).getImm();
3527
3528 Register AddrDisc = MI->getOperand(4).getReg();
3529
3530 Register ScratchReg = Callee == AArch64::X16 ? AArch64::X17 : AArch64::X16;
3531
3532 emitPtrauthTailCallHardening(MI);
3533
3534 // See the comments in emitPtrauthBranch.
3535 if (Callee == AddrDisc)
3536 report_fatal_error("Call target is signed with its own value");
3537
3538 // After isX16X17Safer predicate was introduced, emitPtrauthDiscriminator is
3539 // no longer restricted to only reusing AddrDisc when it is X16 or X17
3540 // (which are implicit-def'ed by AUTH_TCRETURN pseudos), thus impose this
3541 // restriction manually not to clobber an unexpected register.
3542 bool AddrDiscIsImplicitDef =
3543 AddrDisc == AArch64::X16 || AddrDisc == AArch64::X17;
3544 Register DiscReg = emitPtrauthDiscriminator(Disc, AddrDisc, ScratchReg,
3545 AddrDiscIsImplicitDef);
3546 emitBLRA(/*IsCall*/ false, Key, Callee, DiscReg);
3547 return;
3548 }
3549
3550 case AArch64::TCRETURNri:
3551 case AArch64::TCRETURNrix16x17:
3552 case AArch64::TCRETURNrix17:
3553 case AArch64::TCRETURNrinotx16:
3554 case AArch64::TCRETURNriALL: {
3555 emitPtrauthTailCallHardening(MI);
3556
3557 recordIfImportCall(MI);
3558 MCInst TmpInst;
3559 TmpInst.setOpcode(AArch64::BR);
3560 TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
3561 EmitToStreamer(*OutStreamer, TmpInst);
3562 return;
3563 }
3564 case AArch64::TCRETURNdi: {
3565 emitPtrauthTailCallHardening(MI);
3566
3567 MCOperand Dest;
3568 MCInstLowering.lowerOperand(MI->getOperand(0), Dest);
3569 recordIfImportCall(MI);
3570 MCInst TmpInst;
3571 TmpInst.setOpcode(AArch64::B);
3572 TmpInst.addOperand(Dest);
3573 EmitToStreamer(*OutStreamer, TmpInst);
3574 return;
3575 }
3576 case AArch64::SpeculationBarrierISBDSBEndBB: {
3577 // Print DSB SYS + ISB
3578 MCInst TmpInstDSB;
3579 TmpInstDSB.setOpcode(AArch64::DSB);
3580 TmpInstDSB.addOperand(MCOperand::createImm(0xf));
3581 EmitToStreamer(*OutStreamer, TmpInstDSB);
3582 MCInst TmpInstISB;
3583 TmpInstISB.setOpcode(AArch64::ISB);
3584 TmpInstISB.addOperand(MCOperand::createImm(0xf));
3585 EmitToStreamer(*OutStreamer, TmpInstISB);
3586 return;
3587 }
3588 case AArch64::SpeculationBarrierSBEndBB: {
3589 // Print SB
3590 MCInst TmpInstSB;
3591 TmpInstSB.setOpcode(AArch64::SB);
3592 EmitToStreamer(*OutStreamer, TmpInstSB);
3593 return;
3594 }
3595 case AArch64::TLSDESC_AUTH_CALLSEQ: {
3596 /// lower this to:
3597 /// adrp x0, :tlsdesc_auth:var
3598 /// ldr x16, [x0, #:tlsdesc_auth_lo12:var]
3599 /// add x0, x0, #:tlsdesc_auth_lo12:var
3600 /// blraa x16, x0
3601 /// (TPIDR_EL0 offset now in x0)
3602 const MachineOperand &MO_Sym = MI->getOperand(0);
3603 MachineOperand MO_TLSDESC_LO12(MO_Sym), MO_TLSDESC(MO_Sym);
3604 MCOperand SymTLSDescLo12, SymTLSDesc;
3605 MO_TLSDESC_LO12.setTargetFlags(AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
3606 MO_TLSDESC.setTargetFlags(AArch64II::MO_TLS | AArch64II::MO_PAGE);
3607 MCInstLowering.lowerOperand(MO_TLSDESC_LO12, SymTLSDescLo12);
3608 MCInstLowering.lowerOperand(MO_TLSDESC, SymTLSDesc);
3609
3610 MCInst Adrp;
3611 Adrp.setOpcode(AArch64::ADRP);
3612 Adrp.addOperand(MCOperand::createReg(AArch64::X0));
3613 Adrp.addOperand(SymTLSDesc);
3614 EmitToStreamer(*OutStreamer, Adrp);
3615
3616 MCInst Ldr;
3617 Ldr.setOpcode(AArch64::LDRXui);
3618 Ldr.addOperand(MCOperand::createReg(AArch64::X16));
3619 Ldr.addOperand(MCOperand::createReg(AArch64::X0));
3620 Ldr.addOperand(SymTLSDescLo12);
3622 EmitToStreamer(*OutStreamer, Ldr);
3623
3624 MCInst Add;
3625 Add.setOpcode(AArch64::ADDXri);
3626 Add.addOperand(MCOperand::createReg(AArch64::X0));
3627 Add.addOperand(MCOperand::createReg(AArch64::X0));
3628 Add.addOperand(SymTLSDescLo12);
3630 EmitToStreamer(*OutStreamer, Add);
3631
3632 // Authenticated TLSDESC accesses are not relaxed.
3633 // Thus, do not emit .tlsdesccall for AUTH TLSDESC.
3634
3635 MCInst Blraa;
3636 Blraa.setOpcode(AArch64::BLRAA);
3637 Blraa.addOperand(MCOperand::createReg(AArch64::X16));
3638 Blraa.addOperand(MCOperand::createReg(AArch64::X0));
3639 EmitToStreamer(*OutStreamer, Blraa);
3640
3641 return;
3642 }
3643 case AArch64::TLSDESC_CALLSEQ: {
3644 /// lower this to:
3645 /// adrp x0, :tlsdesc:var
3646 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3647 /// add x0, x0, #:tlsdesc_lo12:var
3648 /// .tlsdesccall var
3649 /// blr x1
3650 /// (TPIDR_EL0 offset now in x0)
3651 const MachineOperand &MO_Sym = MI->getOperand(0);
3652 MachineOperand MO_TLSDESC_LO12(MO_Sym), MO_TLSDESC(MO_Sym);
3653 MCOperand Sym, SymTLSDescLo12, SymTLSDesc;
3654 MO_TLSDESC_LO12.setTargetFlags(AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
3655 MO_TLSDESC.setTargetFlags(AArch64II::MO_TLS | AArch64II::MO_PAGE);
3656 MCInstLowering.lowerOperand(MO_Sym, Sym);
3657 MCInstLowering.lowerOperand(MO_TLSDESC_LO12, SymTLSDescLo12);
3658 MCInstLowering.lowerOperand(MO_TLSDESC, SymTLSDesc);
3659
3660 MCInst Adrp;
3661 Adrp.setOpcode(AArch64::ADRP);
3662 Adrp.addOperand(MCOperand::createReg(AArch64::X0));
3663 Adrp.addOperand(SymTLSDesc);
3664 EmitToStreamer(*OutStreamer, Adrp);
3665
3666 MCInst Ldr;
3667 if (STI->isTargetILP32()) {
3668 Ldr.setOpcode(AArch64::LDRWui);
3669 Ldr.addOperand(MCOperand::createReg(AArch64::W1));
3670 } else {
3671 Ldr.setOpcode(AArch64::LDRXui);
3672 Ldr.addOperand(MCOperand::createReg(AArch64::X1));
3673 }
3674 Ldr.addOperand(MCOperand::createReg(AArch64::X0));
3675 Ldr.addOperand(SymTLSDescLo12);
3677 EmitToStreamer(*OutStreamer, Ldr);
3678
3679 MCInst Add;
3680 if (STI->isTargetILP32()) {
3681 Add.setOpcode(AArch64::ADDWri);
3682 Add.addOperand(MCOperand::createReg(AArch64::W0));
3683 Add.addOperand(MCOperand::createReg(AArch64::W0));
3684 } else {
3685 Add.setOpcode(AArch64::ADDXri);
3686 Add.addOperand(MCOperand::createReg(AArch64::X0));
3687 Add.addOperand(MCOperand::createReg(AArch64::X0));
3688 }
3689 Add.addOperand(SymTLSDescLo12);
3691 EmitToStreamer(*OutStreamer, Add);
3692
3693 // Emit a relocation-annotation. This expands to no code, but requests
3694 // the following instruction gets an R_AARCH64_TLSDESC_CALL.
3695 MCInst TLSDescCall;
3696 TLSDescCall.setOpcode(AArch64::TLSDESCCALL);
3697 TLSDescCall.addOperand(Sym);
3698 EmitToStreamer(*OutStreamer, TLSDescCall);
3699#ifndef NDEBUG
3700 --InstsEmitted; // no code emitted
3701#endif
3702
3703 MCInst Blr;
3704 Blr.setOpcode(AArch64::BLR);
3705 Blr.addOperand(MCOperand::createReg(AArch64::X1));
3706 EmitToStreamer(*OutStreamer, Blr);
3707
3708 return;
3709 }
3710
3711 case AArch64::JumpTableDest32:
3712 case AArch64::JumpTableDest16:
3713 case AArch64::JumpTableDest8:
3714 LowerJumpTableDest(*OutStreamer, *MI);
3715 return;
3716
3717 case AArch64::BR_JumpTable:
3718 LowerHardenedBRJumpTable(*MI);
3719 return;
3720
3721 case AArch64::FMOVH0:
3722 case AArch64::FMOVS0:
3723 case AArch64::FMOVD0:
3724 emitFMov0(*MI);
3725 return;
3726
3727 case AArch64::MOPSMemoryCopyPseudo:
3728 case AArch64::MOPSMemoryMovePseudo:
3729 case AArch64::MOPSMemorySetPseudo:
3730 case AArch64::MOPSMemorySetTaggingPseudo:
3731 LowerMOPS(*OutStreamer, *MI);
3732 return;
3733
3734 case TargetOpcode::STACKMAP:
3735 return LowerSTACKMAP(*OutStreamer, SM, *MI);
3736
3737 case TargetOpcode::PATCHPOINT:
3738 return LowerPATCHPOINT(*OutStreamer, SM, *MI);
3739
3740 case TargetOpcode::STATEPOINT:
3741 return LowerSTATEPOINT(*OutStreamer, SM, *MI);
3742
3743 case TargetOpcode::FAULTING_OP:
3744 return LowerFAULTING_OP(*MI);
3745
3746 case TargetOpcode::PATCHABLE_FUNCTION_ENTER:
3747 LowerPATCHABLE_FUNCTION_ENTER(*MI);
3748 return;
3749
3750 case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
3751 LowerPATCHABLE_FUNCTION_EXIT(*MI);
3752 return;
3753
3754 case TargetOpcode::PATCHABLE_TAIL_CALL:
3755 LowerPATCHABLE_TAIL_CALL(*MI);
3756 return;
3757 case TargetOpcode::PATCHABLE_EVENT_CALL:
3758 return LowerPATCHABLE_EVENT_CALL(*MI, false);
3759 case TargetOpcode::PATCHABLE_TYPED_EVENT_CALL:
3760 return LowerPATCHABLE_EVENT_CALL(*MI, true);
3761
3762 case AArch64::KCFI_CHECK:
3763 LowerKCFI_CHECK(*MI);
3764 return;
3765
3766 case AArch64::HWASAN_CHECK_MEMACCESS:
3767 case AArch64::HWASAN_CHECK_MEMACCESS_SHORTGRANULES:
3768 case AArch64::HWASAN_CHECK_MEMACCESS_FIXEDSHADOW:
3769 case AArch64::HWASAN_CHECK_MEMACCESS_SHORTGRANULES_FIXEDSHADOW:
3770 LowerHWASAN_CHECK_MEMACCESS(*MI);
3771 return;
3772
3773 case AArch64::SEH_StackAlloc:
3774 TS->emitARM64WinCFIAllocStack(MI->getOperand(0).getImm());
3775 return;
3776
3777 case AArch64::SEH_SaveFPLR:
3778 TS->emitARM64WinCFISaveFPLR(MI->getOperand(0).getImm());
3779 return;
3780
3781 case AArch64::SEH_SaveFPLR_X:
3782 assert(MI->getOperand(0).getImm() < 0 &&
3783 "Pre increment SEH opcode must have a negative offset");
3784 TS->emitARM64WinCFISaveFPLRX(-MI->getOperand(0).getImm());
3785 return;
3786
3787 case AArch64::SEH_SaveReg:
3788 TS->emitARM64WinCFISaveReg(MI->getOperand(0).getImm(),
3789 MI->getOperand(1).getImm());
3790 return;
3791
3792 case AArch64::SEH_SaveReg_X:
3793 assert(MI->getOperand(1).getImm() < 0 &&
3794 "Pre increment SEH opcode must have a negative offset");
3795 TS->emitARM64WinCFISaveRegX(MI->getOperand(0).getImm(),
3796 -MI->getOperand(1).getImm());
3797 return;
3798
3799 case AArch64::SEH_SaveRegP:
3800 if (MI->getOperand(1).getImm() == 30 && MI->getOperand(0).getImm() >= 19 &&
3801 MI->getOperand(0).getImm() <= 28) {
3802 assert((MI->getOperand(0).getImm() - 19) % 2 == 0 &&
3803 "Register paired with LR must be odd");
3804 TS->emitARM64WinCFISaveLRPair(MI->getOperand(0).getImm(),
3805 MI->getOperand(2).getImm());
3806 return;
3807 }
3808 assert((MI->getOperand(1).getImm() - MI->getOperand(0).getImm() == 1) &&
3809 "Non-consecutive registers not allowed for save_regp");
3810 TS->emitARM64WinCFISaveRegP(MI->getOperand(0).getImm(),
3811 MI->getOperand(2).getImm());
3812 return;
3813
3814 case AArch64::SEH_SaveRegP_X:
3815 assert((MI->getOperand(1).getImm() - MI->getOperand(0).getImm() == 1) &&
3816 "Non-consecutive registers not allowed for save_regp_x");
3817 assert(MI->getOperand(2).getImm() < 0 &&
3818 "Pre increment SEH opcode must have a negative offset");
3819 TS->emitARM64WinCFISaveRegPX(MI->getOperand(0).getImm(),
3820 -MI->getOperand(2).getImm());
3821 return;
3822
3823 case AArch64::SEH_SaveFReg:
3824 TS->emitARM64WinCFISaveFReg(MI->getOperand(0).getImm(),
3825 MI->getOperand(1).getImm());
3826 return;
3827
3828 case AArch64::SEH_SaveFReg_X:
3829 assert(MI->getOperand(1).getImm() < 0 &&
3830 "Pre increment SEH opcode must have a negative offset");
3831 TS->emitARM64WinCFISaveFRegX(MI->getOperand(0).getImm(),
3832 -MI->getOperand(1).getImm());
3833 return;
3834
3835 case AArch64::SEH_SaveFRegP:
3836 assert((MI->getOperand(1).getImm() - MI->getOperand(0).getImm() == 1) &&
3837 "Non-consecutive registers not allowed for save_regp");
3838 TS->emitARM64WinCFISaveFRegP(MI->getOperand(0).getImm(),
3839 MI->getOperand(2).getImm());
3840 return;
3841
3842 case AArch64::SEH_SaveFRegP_X:
3843 assert((MI->getOperand(1).getImm() - MI->getOperand(0).getImm() == 1) &&
3844 "Non-consecutive registers not allowed for save_regp_x");
3845 assert(MI->getOperand(2).getImm() < 0 &&
3846 "Pre increment SEH opcode must have a negative offset");
3847 TS->emitARM64WinCFISaveFRegPX(MI->getOperand(0).getImm(),
3848 -MI->getOperand(2).getImm());
3849 return;
3850
3851 case AArch64::SEH_SetFP:
3853 return;
3854
3855 case AArch64::SEH_AddFP:
3856 TS->emitARM64WinCFIAddFP(MI->getOperand(0).getImm());
3857 return;
3858
3859 case AArch64::SEH_Nop:
3860 TS->emitARM64WinCFINop();
3861 return;
3862
3863 case AArch64::SEH_PrologEnd:
3865 return;
3866
3867 case AArch64::SEH_EpilogStart:
3869 return;
3870
3871 case AArch64::SEH_EpilogEnd:
3873 return;
3874
3875 case AArch64::SEH_PACSignLR:
3877 return;
3878
3879 case AArch64::SEH_SaveAnyRegI:
3880 assert(MI->getOperand(1).getImm() <= 1008 &&
3881 "SaveAnyRegQP SEH opcode offset must fit into 6 bits");
3882 TS->emitARM64WinCFISaveAnyRegI(MI->getOperand(0).getImm(),
3883 MI->getOperand(1).getImm());
3884 return;
3885
3886 case AArch64::SEH_SaveAnyRegIP:
3887 assert(MI->getOperand(1).getImm() - MI->getOperand(0).getImm() == 1 &&
3888 "Non-consecutive registers not allowed for save_any_reg");
3889 assert(MI->getOperand(2).getImm() <= 1008 &&
3890 "SaveAnyRegQP SEH opcode offset must fit into 6 bits");
3891 TS->emitARM64WinCFISaveAnyRegIP(MI->getOperand(0).getImm(),
3892 MI->getOperand(2).getImm());
3893 return;
3894
3895 case AArch64::SEH_SaveAnyRegQP:
3896 assert(MI->getOperand(1).getImm() - MI->getOperand(0).getImm() == 1 &&
3897 "Non-consecutive registers not allowed for save_any_reg");
3898 assert(MI->getOperand(2).getImm() >= 0 &&
3899 "SaveAnyRegQP SEH opcode offset must be non-negative");
3900 assert(MI->getOperand(2).getImm() <= 1008 &&
3901 "SaveAnyRegQP SEH opcode offset must fit into 6 bits");
3902 TS->emitARM64WinCFISaveAnyRegQP(MI->getOperand(0).getImm(),
3903 MI->getOperand(2).getImm());
3904 return;
3905
3906 case AArch64::SEH_SaveAnyRegQPX:
3907 assert(MI->getOperand(1).getImm() - MI->getOperand(0).getImm() == 1 &&
3908 "Non-consecutive registers not allowed for save_any_reg");
3909 assert(MI->getOperand(2).getImm() < 0 &&
3910 "SaveAnyRegQPX SEH opcode offset must be negative");
3911 assert(MI->getOperand(2).getImm() >= -1008 &&
3912 "SaveAnyRegQPX SEH opcode offset must fit into 6 bits");
3913 TS->emitARM64WinCFISaveAnyRegQPX(MI->getOperand(0).getImm(),
3914 -MI->getOperand(2).getImm());
3915 return;
3916
3917 case AArch64::SEH_AllocZ:
3918 assert(MI->getOperand(0).getImm() >= 0 &&
3919 "AllocZ SEH opcode offset must be non-negative");
3920 assert(MI->getOperand(0).getImm() <= 255 &&
3921 "AllocZ SEH opcode offset must fit into 8 bits");
3922 TS->emitARM64WinCFIAllocZ(MI->getOperand(0).getImm());
3923 return;
3924
3925 case AArch64::SEH_SaveZReg:
3926 assert(MI->getOperand(1).getImm() >= 0 &&
3927 "SaveZReg SEH opcode offset must be non-negative");
3928 assert(MI->getOperand(1).getImm() <= 255 &&
3929 "SaveZReg SEH opcode offset must fit into 8 bits");
3930 TS->emitARM64WinCFISaveZReg(MI->getOperand(0).getImm(),
3931 MI->getOperand(1).getImm());
3932 return;
3933
3934 case AArch64::SEH_SavePReg:
3935 assert(MI->getOperand(1).getImm() >= 0 &&
3936 "SavePReg SEH opcode offset must be non-negative");
3937 assert(MI->getOperand(1).getImm() <= 255 &&
3938 "SavePReg SEH opcode offset must fit into 8 bits");
3939 TS->emitARM64WinCFISavePReg(MI->getOperand(0).getImm(),
3940 MI->getOperand(1).getImm());
3941 return;
3942
3943 case AArch64::BLR:
3944 case AArch64::BR: {
3945 recordIfImportCall(MI);
3946 MCInst TmpInst;
3947 MCInstLowering.Lower(MI, TmpInst);
3948 EmitToStreamer(*OutStreamer, TmpInst);
3949 return;
3950 }
3951 case AArch64::CBWPri:
3952 case AArch64::CBXPri:
3953 case AArch64::CBBAssertExt:
3954 case AArch64::CBHAssertExt:
3955 case AArch64::CBWPrr:
3956 case AArch64::CBXPrr:
3957 emitCBPseudoExpansion(MI);
3958 return;
3959 }
3960
3961 if (emitDeactivationSymbolRelocation(MI->getDeactivationSymbol()))
3962 return;
3963
3964 // Finally, do the automated lowerings for everything else.
3965 MCInst TmpInst;
3966 MCInstLowering.Lower(MI, TmpInst);
3967 EmitToStreamer(*OutStreamer, TmpInst);
3968}
3969
3970void AArch64AsmPrinter::recordIfImportCall(
3971 const llvm::MachineInstr *BranchInst) {
3972 if (!EnableImportCallOptimization)
3973 return;
3974
3975 auto [GV, OpFlags] = BranchInst->getMF()->tryGetCalledGlobal(BranchInst);
3976 if (GV && GV->hasDLLImportStorageClass()) {
3977 auto *CallSiteSymbol = MMI->getContext().createNamedTempSymbol("impcall");
3978 OutStreamer->emitLabel(CallSiteSymbol);
3979
3980 auto *CalledSymbol = MCInstLowering.GetGlobalValueSymbol(GV, OpFlags);
3981 SectionToImportedFunctionCalls[OutStreamer->getCurrentSectionOnly()]
3982 .push_back({CallSiteSymbol, CalledSymbol});
3983 }
3984}
3985
3986void AArch64AsmPrinter::emitMachOIFuncStubBody(Module &M, const GlobalIFunc &GI,
3987 MCSymbol *LazyPointer) {
3988 // _ifunc:
3989 // adrp x16, lazy_pointer@GOTPAGE
3990 // ldr x16, [x16, lazy_pointer@GOTPAGEOFF]
3991 // ldr x16, [x16]
3992 // br x16
3993
3994 {
3995 MCInst Adrp;
3996 Adrp.setOpcode(AArch64::ADRP);
3997 Adrp.addOperand(MCOperand::createReg(AArch64::X16));
3998 MCOperand SymPage;
3999 MCInstLowering.lowerOperand(
4002 SymPage);
4003 Adrp.addOperand(SymPage);
4004 EmitToStreamer(Adrp);
4005 }
4006
4007 {
4008 MCInst Ldr;
4009 Ldr.setOpcode(AArch64::LDRXui);
4010 Ldr.addOperand(MCOperand::createReg(AArch64::X16));
4011 Ldr.addOperand(MCOperand::createReg(AArch64::X16));
4012 MCOperand SymPageOff;
4013 MCInstLowering.lowerOperand(
4016 SymPageOff);
4017 Ldr.addOperand(SymPageOff);
4019 EmitToStreamer(Ldr);
4020 }
4021
4022 EmitToStreamer(MCInstBuilder(AArch64::LDRXui)
4023 .addReg(AArch64::X16)
4024 .addReg(AArch64::X16)
4025 .addImm(0));
4026
4027 EmitToStreamer(MCInstBuilder(TM.getTargetTriple().isArm64e() ? AArch64::BRAAZ
4028 : AArch64::BR)
4029 .addReg(AArch64::X16));
4030}
4031
4032void AArch64AsmPrinter::emitMachOIFuncStubHelperBody(Module &M,
4033 const GlobalIFunc &GI,
4034 MCSymbol *LazyPointer) {
4035 // These stub helpers are only ever called once, so here we're optimizing for
4036 // minimum size by using the pre-indexed store variants, which saves a few
4037 // bytes of instructions to bump & restore sp.
4038
4039 // _ifunc.stub_helper:
4040 // stp fp, lr, [sp, #-16]!
4041 // mov fp, sp
4042 // stp x1, x0, [sp, #-16]!
4043 // stp x3, x2, [sp, #-16]!
4044 // stp x5, x4, [sp, #-16]!
4045 // stp x7, x6, [sp, #-16]!
4046 // stp d1, d0, [sp, #-16]!
4047 // stp d3, d2, [sp, #-16]!
4048 // stp d5, d4, [sp, #-16]!
4049 // stp d7, d6, [sp, #-16]!
4050 // bl _resolver
4051 // adrp x16, lazy_pointer@GOTPAGE
4052 // ldr x16, [x16, lazy_pointer@GOTPAGEOFF]
4053 // str x0, [x16]
4054 // mov x16, x0
4055 // ldp d7, d6, [sp], #16
4056 // ldp d5, d4, [sp], #16
4057 // ldp d3, d2, [sp], #16
4058 // ldp d1, d0, [sp], #16
4059 // ldp x7, x6, [sp], #16
4060 // ldp x5, x4, [sp], #16
4061 // ldp x3, x2, [sp], #16
4062 // ldp x1, x0, [sp], #16
4063 // ldp fp, lr, [sp], #16
4064 // br x16
4065
4066 EmitToStreamer(MCInstBuilder(AArch64::STPXpre)
4067 .addReg(AArch64::SP)
4068 .addReg(AArch64::FP)
4069 .addReg(AArch64::LR)
4070 .addReg(AArch64::SP)
4071 .addImm(-2));
4072
4073 EmitToStreamer(MCInstBuilder(AArch64::ADDXri)
4074 .addReg(AArch64::FP)
4075 .addReg(AArch64::SP)
4076 .addImm(0)
4077 .addImm(0));
4078
4079 for (int I = 0; I != 4; ++I)
4080 EmitToStreamer(MCInstBuilder(AArch64::STPXpre)
4081 .addReg(AArch64::SP)
4082 .addReg(AArch64::X1 + 2 * I)
4083 .addReg(AArch64::X0 + 2 * I)
4084 .addReg(AArch64::SP)
4085 .addImm(-2));
4086
4087 for (int I = 0; I != 4; ++I)
4088 EmitToStreamer(MCInstBuilder(AArch64::STPDpre)
4089 .addReg(AArch64::SP)
4090 .addReg(AArch64::D1 + 2 * I)
4091 .addReg(AArch64::D0 + 2 * I)
4092 .addReg(AArch64::SP)
4093 .addImm(-2));
4094
4095 EmitToStreamer(
4096 MCInstBuilder(AArch64::BL)
4098
4099 {
4100 MCInst Adrp;
4101 Adrp.setOpcode(AArch64::ADRP);
4102 Adrp.addOperand(MCOperand::createReg(AArch64::X16));
4103 MCOperand SymPage;
4104 MCInstLowering.lowerOperand(
4105 MachineOperand::CreateES(LazyPointer->getName().data() + 1,
4107 SymPage);
4108 Adrp.addOperand(SymPage);
4109 EmitToStreamer(Adrp);
4110 }
4111
4112 {
4113 MCInst Ldr;
4114 Ldr.setOpcode(AArch64::LDRXui);
4115 Ldr.addOperand(MCOperand::createReg(AArch64::X16));
4116 Ldr.addOperand(MCOperand::createReg(AArch64::X16));
4117 MCOperand SymPageOff;
4118 MCInstLowering.lowerOperand(
4119 MachineOperand::CreateES(LazyPointer->getName().data() + 1,
4121 SymPageOff);
4122 Ldr.addOperand(SymPageOff);
4124 EmitToStreamer(Ldr);
4125 }
4126
4127 EmitToStreamer(MCInstBuilder(AArch64::STRXui)
4128 .addReg(AArch64::X0)
4129 .addReg(AArch64::X16)
4130 .addImm(0));
4131
4132 EmitToStreamer(MCInstBuilder(AArch64::ADDXri)
4133 .addReg(AArch64::X16)
4134 .addReg(AArch64::X0)
4135 .addImm(0)
4136 .addImm(0));
4137
4138 for (int I = 3; I != -1; --I)
4139 EmitToStreamer(MCInstBuilder(AArch64::LDPDpost)
4140 .addReg(AArch64::SP)
4141 .addReg(AArch64::D1 + 2 * I)
4142 .addReg(AArch64::D0 + 2 * I)
4143 .addReg(AArch64::SP)
4144 .addImm(2));
4145
4146 for (int I = 3; I != -1; --I)
4147 EmitToStreamer(MCInstBuilder(AArch64::LDPXpost)
4148 .addReg(AArch64::SP)
4149 .addReg(AArch64::X1 + 2 * I)
4150 .addReg(AArch64::X0 + 2 * I)
4151 .addReg(AArch64::SP)
4152 .addImm(2));
4153
4154 EmitToStreamer(MCInstBuilder(AArch64::LDPXpost)
4155 .addReg(AArch64::SP)
4156 .addReg(AArch64::FP)
4157 .addReg(AArch64::LR)
4158 .addReg(AArch64::SP)
4159 .addImm(2));
4160
4161 EmitToStreamer(MCInstBuilder(TM.getTargetTriple().isArm64e() ? AArch64::BRAAZ
4162 : AArch64::BR)
4163 .addReg(AArch64::X16));
4164}
4165
4166const MCExpr *AArch64AsmPrinter::lowerConstant(const Constant *CV,
4167 const Constant *BaseCV,
4168 uint64_t Offset) {
4169 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
4170 return MCSymbolRefExpr::create(MCInstLowering.GetGlobalValueSymbol(GV, 0),
4171 OutContext);
4172 }
4173
4174 return AsmPrinter::lowerConstant(CV, BaseCV, Offset);
4175}
4176
4177char AArch64AsmPrinter::ID = 0;
4178
4179INITIALIZE_PASS(AArch64AsmPrinter, "aarch64-asm-printer",
4180 "AArch64 Assembly Printer", false, false)
4181
4182// Force static initialization.
4183extern "C" LLVM_ABI LLVM_EXTERNAL_VISIBILITY void
4184LLVMInitializeAArch64AsmPrinter() {
4190}
PtrauthCheckMode
@ Unchecked
#define GET_CB_OPC(IsImm, Width, ImmCond, RegCond)
static void emitAuthenticatedPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel, const MCExpr *StubAuthPtrRef)
static bool getOptionalBooleanModuleFlag(Module &M, StringRef Name)
static cl::opt< PtrauthCheckMode > PtrauthAuthChecks("aarch64-ptrauth-auth-checks", cl::Hidden, cl::values(clEnumValN(Unchecked, "none", "don't test for failure"), clEnumValN(Poison, "poison", "poison on failure"), clEnumValN(Trap, "trap", "trap on failure")), cl::desc("Check pointer authentication auth/resign failures"))
static bool targetSupportsIRelativeRelocation(const Triple &TT)
static PtrauthCheckMode getCheckMode(const MachineFunction *MF)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static MCDisassembler::DecodeStatus addOperand(MCInst &Inst, const MCOperand &Opnd)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define LLVM_ABI
Definition Compiler.h:215
#define LLVM_EXTERNAL_VISIBILITY
Definition Compiler.h:132
This file defines the DenseMap class.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#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
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 SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, const RISCVSubtarget &Subtarget)
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:484
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
static bool printOperand(raw_ostream &OS, const SelectionDAG *G, const SDValue Value)
This file defines the SmallString class.
This file defines the SmallVector class.
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")
static bool printAsmMRegister(const X86AsmPrinter &P, const MachineOperand &MO, char Mode, raw_ostream &O)
static const AArch64AuthMCExpr * create(const MCExpr *Expr, uint16_t Discriminator, AArch64PACKey::ID Key, bool HasAddressDiversity, MCContext &Ctx, SMLoc Loc=SMLoc())
const SetOfInstructions & getLOHRelated() const
unsigned getJumpTableEntrySize(int Idx) const
MCSymbol * getJumpTableEntryPCRelSymbol(int Idx) const
static bool shouldSignReturnAddress(SignReturnAddress Condition, bool IsLRSpilled)
std::optional< std::string > getOutliningStyle() const
const MILOHContainer & getLOHContainer() const
void setJumpTableEntryInfo(int Idx, unsigned Size, MCSymbol *PCRelSym)
static const char * getRegisterName(MCRegister Reg, unsigned AltIdx=AArch64::NoRegAltName)
static bool isTailCallReturnInst(const MachineInstr &MI)
Returns true if MI is one of the TCRETURN* instructions.
AArch64MCInstLower - This class is used to lower an MachineInstr into an MCInst.
MCSymbol * GetGlobalValueSymbol(const GlobalValue *GV, unsigned TargetFlags) const
void Lower(const MachineInstr *MI, MCInst &OutMI) const
bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp) const
virtual void emitARM64WinCFISaveRegP(unsigned Reg, int Offset)
virtual void emitARM64WinCFISaveRegPX(unsigned Reg, int Offset)
virtual void emitARM64WinCFISaveAnyRegQP(unsigned Reg, int Offset)
virtual void emitAttributesSubsection(StringRef VendorName, AArch64BuildAttributes::SubsectionOptional IsOptional, AArch64BuildAttributes::SubsectionType ParameterType)
Build attributes implementation.
virtual void emitARM64WinCFISavePReg(unsigned Reg, int Offset)
virtual void emitARM64WinCFISaveFReg(unsigned Reg, int Offset)
virtual void emitARM64WinCFISaveAnyRegI(unsigned Reg, int Offset)
virtual void emitARM64WinCFISaveFRegPX(unsigned Reg, int Offset)
virtual void emitARM64WinCFISaveRegX(unsigned Reg, int Offset)
virtual void emitARM64WinCFIAllocStack(unsigned Size)
virtual void emitARM64WinCFISaveFPLRX(int Offset)
virtual void emitARM64WinCFIAllocZ(int Offset)
virtual void emitDirectiveVariantPCS(MCSymbol *Symbol)
Callback used to implement the .variant_pcs directive.
virtual void emitARM64WinCFIAddFP(unsigned Size)
virtual void emitARM64WinCFISaveFPLR(int Offset)
virtual void emitARM64WinCFISaveFRegP(unsigned Reg, int Offset)
virtual void emitARM64WinCFISaveAnyRegQPX(unsigned Reg, int Offset)
virtual void emitARM64WinCFISaveFRegX(unsigned Reg, int Offset)
virtual void emitARM64WinCFISaveZReg(unsigned Reg, int Offset)
virtual void emitARM64WinCFISaveReg(unsigned Reg, int Offset)
virtual void emitARM64WinCFISaveLRPair(unsigned Reg, int Offset)
virtual void emitAttribute(StringRef VendorName, unsigned Tag, unsigned Value, std::string String)
virtual void emitARM64WinCFISaveAnyRegIP(unsigned Reg, int Offset)
void setPreservesAll()
Set by analyses that do not transform their input at all.
const T & front() const
Get the first element.
Definition ArrayRef.h:144
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
This class is intended to be used as a driving class for all asm writers.
Definition AsmPrinter.h:91
virtual void emitGlobalAlias(const Module &M, const GlobalAlias &GA)
virtual MCSymbol * GetCPISymbol(unsigned CPID) const
Return the symbol for the specified constant pool entry.
virtual const MCExpr * lowerConstant(const Constant *CV, const Constant *BaseCV=nullptr, uint64_t Offset=0)
Lower the specified LLVM Constant to an MCExpr.
void getAnalysisUsage(AnalysisUsage &AU) const override
Record analysis usage.
virtual void emitXXStructor(const DataLayout &DL, const Constant *CV)
Targets can override this to change how global constants that are part of a C++ static/global constru...
Definition AsmPrinter.h:655
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.
virtual const MCExpr * lowerBlockAddressConstant(const BlockAddress &BA)
Lower the specified BlockAddress to an MCExpr.
Function * getFunction() const
Definition Constants.h:1126
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
Constant * getPointer() const
The pointer that is signed in this ptrauth signed pointer.
Definition Constants.h:1251
static LLVM_ABI ConstantPtrAuth * get(Constant *Ptr, ConstantInt *Key, ConstantInt *Disc, Constant *AddrDisc, Constant *DeactivationSymbol)
Return a pointer signed with the specified parameters.
ConstantInt * getKey() const
The Key ID, an i32 constant.
Definition Constants.h:1254
Constant * getDeactivationSymbol() const
Definition Constants.h:1273
bool hasAddressDiscriminator() const
Whether there is any non-null address discriminator.
Definition Constants.h:1269
ConstantInt * getDiscriminator() const
The integer discriminator, an i64 constant, or 0.
Definition Constants.h:1257
LLVM_ABI void recordFaultingOp(FaultKind FaultTy, const MCSymbol *FaultingLabel, const MCSymbol *HandlerLabel)
Definition FaultMaps.cpp:28
LLVM_ABI void serializeToFaultMapSection()
Definition FaultMaps.cpp:45
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:272
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:723
const Constant * getAliasee() const
Definition GlobalAlias.h:87
const Constant * getResolver() const
Definition GlobalIFunc.h:73
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
bool hasLocalLinkage() const
bool hasExternalWeakLinkage() const
Type * getValueType() const
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
LLVM_ABI void emitError(const Instruction *I, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
static const MCBinaryExpr * createLShr(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:422
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:342
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:427
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
LLVM_ABI MCSymbol * createTempSymbol()
Create a temporary symbol with a unique name.
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition MCContext.h:550
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
LLVM_ABI MCSymbol * createLinkerPrivateSymbol(const Twine &Name)
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
LLVM_ABI bool evaluateAsRelocatable(MCValue &Res, const MCAssembler *Asm) const
Try to evaluate the expression to a relocatable value, i.e.
Definition MCExpr.cpp:450
void addOperand(const MCOperand Op)
Definition MCInst.h:215
void setOpcode(unsigned Op)
Definition MCInst.h:201
MCSection * getDataSection() const
void setImm(int64_t Val)
Definition MCInst.h:89
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
bool isReg() const
Definition MCInst.h:65
MCRegister getRegister(unsigned i) const
getRegister - Return the specified register in the class.
uint16_t getEncodingValue(MCRegister Reg) const
Returns the encoding for Reg.
static constexpr unsigned NonUniqueID
Definition MCSection.h:578
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 emitCFIBKeyFrame()
virtual bool popSection()
Restore the current and previous section from the section stack.
virtual void emitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI)
Emit the given Instruction into the current section.
virtual void emitRelocDirective(const MCExpr &Offset, StringRef Name, const MCExpr *Expr, SMLoc Loc={})
Record a relocation described by the .reloc directive.
virtual bool hasRawTextSupport() const
Return true if this asm streamer supports emitting unformatted text to the .s file with EmitRawText.
Definition MCStreamer.h:385
MCContext & getContext() const
Definition MCStreamer.h:326
virtual void AddComment(const Twine &T, bool EOL=true)
Add a textual comment.
Definition MCStreamer.h:404
virtual void emitCFIMTETaggedFrame()
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:336
void pushSection()
Save the current and previous section on the section stack.
Definition MCStreamer.h:460
virtual void switchSection(MCSection *Section, uint32_t Subsec=0)
Set the current section where code is being emitted to Section.
MCSection * getCurrentSectionOnly() const
Definition MCStreamer.h:438
void emitRawText(const Twine &String)
If this file is backed by a assembly streamer, this dumps the specified string in the output ....
const FeatureBitset & getFeatureBits() const
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
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
const MCSymbol * getAddSym() const
Definition MCValue.h:49
int64_t getConstant() const
Definition MCValue.h:44
MachineInstrBundleIterator< const MachineInstr > const_iterator
LLVM_ABI MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
CalledGlobalInfo tryGetCalledGlobal(const MachineInstr *MI) const
Tries to get the global and target flags for a call site, if the instruction is a call to a global.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MCContext & getContext() const
Function & getFunction()
Return the LLVM function that this machine code represents.
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
const MachineBasicBlock & front() const
const MachineJumpTableInfo * getJumpTableInfo() const
getJumpTableInfo - Return the jump table info object for the current function.
bool readsRegister(Register Reg, const TargetRegisterInfo *TRI) const
Return true if the MachineInstr reads the specified register.
mop_range operands()
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
const MachineOperand & getOperand(unsigned i) const
const std::vector< MachineJumpTableEntry > & getJumpTables() const
unsigned getSubReg() const
static MachineOperand CreateMCSymbol(MCSymbol *Sym, unsigned TargetFlags=0)
const GlobalValue * getGlobal() const
static MachineOperand CreateES(const char *SymName, unsigned TargetFlags=0)
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.
const BlockAddress * getBlockAddress() const
void setOffset(int64_t Offset)
bool isGlobal() const
isGlobal - Tests if this is a MO_GlobalAddress operand.
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
Register getReg() const
getReg - Returns the register number.
@ MO_Immediate
Immediate operand.
@ MO_GlobalAddress
Address of a global value.
@ MO_BlockAddress
Address of a basic block.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
int64_t getOffset() const
Return the offset from the symbol in this operand.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:38
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
static SectionKind getMetadata()
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void push_back(const T &Elt)
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
virtual MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const
Primary interface to the complete machine description for the target machine.
bool regsOverlap(Register RegA, Register RegB) const
Returns true if the two registers are equal or alias each other.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:273
LLVM Value Representation.
Definition Value.h:75
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI StringRef getVendorName(unsigned const Vendor)
@ MO_NC
MO_NC - Indicates whether the linker is expected to check the symbol reference for overflow.
@ MO_G1
MO_G1 - A symbol operand with this flag (granule 1) represents the bits 16-31 of a 64-bit address,...
@ MO_S
MO_S - Indicates that the bits of the symbol operand represented by MO_G0 etc are signed.
@ MO_PAGEOFF
MO_PAGEOFF - A symbol operand with this flag represents the offset of that symbol within a 4K page.
@ MO_GOT
MO_GOT - This flag indicates that a symbol operand represents the address of the GOT entry for the sy...
@ MO_G0
MO_G0 - A symbol operand with this flag (granule 0) represents the bits 0-15 of a 64-bit address,...
@ MO_PAGE
MO_PAGE - A symbol operand with this flag represents the pc-relative offset of the 4K page containing...
@ MO_TLS
MO_TLS - Indicates that the operand being accessed is some kind of thread-local symbol.
constexpr AArch64PACKey::ID InitFiniKey
PAuth key to be used with function pointers in .init_array and .fini_array.
AuthCheckMethod
Variants of check performed on an authenticated pointer.
constexpr unsigned InitFiniPointerConstantDiscriminator
Constant discriminator to be used with function pointers in .init_array and .fini_array.
static unsigned getShiftValue(unsigned Imm)
getShiftValue - Extract the shift value.
static uint64_t encodeLogicalImmediate(uint64_t imm, unsigned regSize)
encodeLogicalImmediate - Return the encoded immediate value for a logical immediate instruction of th...
static unsigned getShifterImm(AArch64_AM::ShiftExtendType ST, unsigned Imm)
getShifterImm - Encode the shift type and amount: imm: 6-bit shift amount shifter: 000 ==> lsl 001 ==...
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ SectionSize
Definition COFF.h:61
SymbolStorageClass
Storage class tells where and what the symbol represents.
Definition COFF.h:218
@ IMAGE_SYM_CLASS_EXTERNAL
External symbol.
Definition COFF.h:224
@ IMAGE_SYM_CLASS_STATIC
Static.
Definition COFF.h:225
@ IMAGE_SYM_DTYPE_FUNCTION
A function that returns a base type.
Definition COFF.h:276
@ SCT_COMPLEX_TYPE_SHIFT
Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))
Definition COFF.h:280
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ AARCH64_PAUTH_PLATFORM_LLVM_LINUX
Definition ELF.h:1876
@ SHF_ALLOC
Definition ELF.h:1256
@ SHF_GROUP
Definition ELF.h:1278
@ SHF_EXECINSTR
Definition ELF.h:1259
@ GNU_PROPERTY_AARCH64_FEATURE_1_BTI
Definition ELF.h:1867
@ GNU_PROPERTY_AARCH64_FEATURE_1_PAC
Definition ELF.h:1868
@ GNU_PROPERTY_AARCH64_FEATURE_1_GCS
Definition ELF.h:1869
@ SHT_PROGBITS
Definition ELF.h:1155
@ S_REGULAR
S_REGULAR - Regular section.
Definition MachO.h:127
void emitInstruction(MCObjectStreamer &, const MCInst &Inst, const MCSubtargetInfo &STI)
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract_or_null(Y &&MD)
Extract a Value from Metadata, allowing null.
Definition Metadata.h:683
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:383
bool empty() const
Definition BasicBlock.h:101
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Offset
Definition DWP.cpp:578
LLVM_ABI std::optional< std::string > getArm64ECMangledFunctionName(StringRef Name)
Returns the ARM64EC mangled function name unless the input is already mangled.
Definition Mangler.cpp:292
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
scope_exit(Callable) -> scope_exit< Callable >
static unsigned getXPACOpcodeForKey(AArch64PACKey::ID K)
Return XPAC opcode to be used for a ptrauth strip using the given key.
ExceptionHandling
Definition CodeGen.h:53
Target & getTheAArch64beTarget()
std::string utostr(uint64_t X, bool isNeg=false)
static unsigned getBranchOpcodeForKey(bool IsCall, AArch64PACKey::ID K, bool Zero)
Return B(L)RA opcode to be used for an authenticated branch or call using the given key,...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
Target & getTheAArch64leTarget()
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
Target & getTheAArch64_32Target()
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
Target & getTheARM64_32Target()
static MCRegister getXRegFromWReg(MCRegister Reg)
@ Add
Sum of integers.
Target & getTheARM64Target()
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
static MCRegister getXRegFromXRegTuple(MCRegister RegTuple)
static unsigned getPACOpcodeForKey(AArch64PACKey::ID K, bool Zero)
Return PAC opcode to be used for a ptrauth sign using the given key, or its PAC*Z variant that doesn'...
static MCRegister getWRegFromXReg(MCRegister Reg)
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
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
static unsigned getAUTOpcodeForKey(AArch64PACKey::ID K, bool Zero)
Return AUT opcode to be used for a ptrauth auth using the given key, or its AUT*Z variant that doesn'...
@ MCSA_Weak
.weak
@ MCSA_WeakAntiDep
.weak_anti_dep (COFF)
@ MCSA_ELF_TypeFunction
.type _foo, STT_FUNC # aka @function
@ MCSA_Hidden
.hidden (ELF)
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:878
#define EQ(a, b)
Definition regexec.c:65
RegisterAsmPrinter - Helper template for registering a target specific assembly printer,...