LLVM 24.0.0git
AArch64Arm64ECCallLowering.cpp
Go to the documentation of this file.
1//===-- AArch64Arm64ECCallLowering.cpp - Lower Arm64EC calls ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file contains the IR transform to lower external or indirect calls for
11/// the ARM64EC calling convention. Such calls must go through the runtime, so
12/// we can translate the calling convention for calls into the emulator.
13///
14/// This subsumes Control Flow Guard handling.
15///
16//===----------------------------------------------------------------------===//
17
18#include "AArch64.h"
19#include "AArch64Subtarget.h"
20#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/IR/CallingConv.h"
26#include "llvm/IR/GlobalAlias.h"
27#include "llvm/IR/IRBuilder.h"
28#include "llvm/IR/Instruction.h"
29#include "llvm/IR/Mangler.h"
30#include "llvm/IR/Module.h"
31#include "llvm/Object/COFF.h"
32#include "llvm/Pass.h"
34
35using namespace llvm;
36using namespace llvm::COFF;
37
39
40#define DEBUG_TYPE "arm64eccalllowering"
41
42STATISTIC(Arm64ECCallsLowered, "Number of Arm64EC calls lowered");
43
44namespace {
45
46enum ThunkArgTranslation : uint8_t {
47 Direct,
48 Bitcast,
49 PointerIndirection,
50};
51
52struct ThunkArgInfo {
53 Type *Arm64Ty;
54 Type *X64Ty;
55 ThunkArgTranslation Translation;
56};
57
58class AArch64Arm64ECCallLowering : public ModulePass {
59public:
60 static char ID;
61 AArch64Arm64ECCallLowering() : ModulePass(ID) {}
62
63 Function *buildExitThunk(FunctionType *FnTy, AttributeList Attrs);
64 Function *buildEntryThunk(Function *F);
65 void lowerCall(CallBase *CB);
66 Function *buildGuestExitThunk(Function *F);
67 Function *buildPatchableThunk(GlobalAlias *UnmangledAlias,
68 GlobalAlias *MangledAlias);
69 bool processFunction(Function &F, SetVector<GlobalValue *> &DirectCalledFns,
70 DenseMap<GlobalAlias *, GlobalAlias *> &FnsMap);
71 bool runOnModule(Module &M) override;
72
73private:
74 const AArch64Options *CLOpts = nullptr;
75 ControlFlowGuardMode CFGuardModuleFlag = ControlFlowGuardMode::Disabled;
76 FunctionType *GuardFnType = nullptr;
77 FunctionType *DispatchFnType = nullptr;
78 Constant *GuardFnCFGlobal = nullptr;
79 Constant *GuardFnGlobal = nullptr;
80 Constant *DispatchFnGlobal = nullptr;
81 Module *M = nullptr;
82
83 Type *PtrTy;
84 Type *I64Ty;
85 Type *VoidTy;
86
87 void getThunkType(FunctionType *FT, AttributeList AttrList,
88 Arm64ECThunkType TT, raw_ostream &Out,
89 FunctionType *&Arm64Ty, FunctionType *&X64Ty,
90 SmallVector<ThunkArgTranslation> &ArgTranslations);
91 void getThunkRetType(FunctionType *FT, AttributeList AttrList,
92 raw_ostream &Out, Type *&Arm64RetTy, Type *&X64RetTy,
93 SmallVectorImpl<Type *> &Arm64ArgTypes,
94 SmallVectorImpl<Type *> &X64ArgTypes,
95 SmallVector<ThunkArgTranslation> &ArgTranslations,
96 bool &HasSretPtr);
97 void getThunkArgTypes(FunctionType *FT, AttributeList AttrList,
98 Arm64ECThunkType TT, raw_ostream &Out,
99 SmallVectorImpl<Type *> &Arm64ArgTypes,
100 SmallVectorImpl<Type *> &X64ArgTypes,
101 SmallVectorImpl<ThunkArgTranslation> &ArgTranslations,
102 bool HasSretPtr);
103 ThunkArgInfo canonicalizeThunkType(Type *T, Align Alignment, bool Ret,
104 uint64_t ArgSizeBytes, raw_ostream &Out);
105};
106
107} // end anonymous namespace
108
109void AArch64Arm64ECCallLowering::getThunkType(
111 raw_ostream &Out, FunctionType *&Arm64Ty, FunctionType *&X64Ty,
112 SmallVector<ThunkArgTranslation> &ArgTranslations) {
113 Out << (TT == Arm64ECThunkType::Entry ? "$ientry_thunk$cdecl$"
114 : "$iexit_thunk$cdecl$");
115
116 Type *Arm64RetTy;
117 Type *X64RetTy;
118
119 SmallVector<Type *> Arm64ArgTypes;
120 SmallVector<Type *> X64ArgTypes;
121
122 // The first argument to a thunk is the called function, stored in x9.
123 // For exit thunks, we pass the called function down to the emulator;
124 // for entry/guest exit thunks, we just call the Arm64 function directly.
125 if (TT == Arm64ECThunkType::Exit)
126 Arm64ArgTypes.push_back(PtrTy);
127 X64ArgTypes.push_back(PtrTy);
128
129 bool HasSretPtr = false;
130 getThunkRetType(FT, AttrList, Out, Arm64RetTy, X64RetTy, Arm64ArgTypes,
131 X64ArgTypes, ArgTranslations, HasSretPtr);
132
133 getThunkArgTypes(FT, AttrList, TT, Out, Arm64ArgTypes, X64ArgTypes,
134 ArgTranslations, HasSretPtr);
135
136 Arm64Ty = FunctionType::get(Arm64RetTy, Arm64ArgTypes, false);
137
138 X64Ty = FunctionType::get(X64RetTy, X64ArgTypes, false);
139}
140
141void AArch64Arm64ECCallLowering::getThunkArgTypes(
142 FunctionType *FT, AttributeList AttrList, Arm64ECThunkType TT,
143 raw_ostream &Out, SmallVectorImpl<Type *> &Arm64ArgTypes,
144 SmallVectorImpl<Type *> &X64ArgTypes,
145 SmallVectorImpl<ThunkArgTranslation> &ArgTranslations, bool HasSretPtr) {
146
147 Out << "$";
148 if (FT->isVarArg()) {
149 // We treat the variadic function's thunk as a normal function
150 // with the following type on the ARM side:
151 // rettype exitthunk(
152 // ptr x9, ptr x0, i64 x1, i64 x2, i64 x3, ptr x4, i64 x5)
153 //
154 // that can coverage all types of variadic function.
155 // x9 is similar to normal exit thunk, store the called function.
156 // x0-x3 is the arguments be stored in registers.
157 // x4 is the address of the arguments on the stack.
158 // x5 is the size of the arguments on the stack.
159 //
160 // On the x64 side, it's the same except that x5 isn't set.
161 //
162 // If both the ARM and X64 sides are sret, there are only three
163 // arguments in registers.
164 //
165 // If the X64 side is sret, but the ARM side isn't, we pass an extra value
166 // to/from the X64 side, and let SelectionDAG transform it into a memory
167 // location.
168 Out << "varargs";
169
170 // x0-x3
171 for (int i = HasSretPtr ? 1 : 0; i < 4; i++) {
172 Arm64ArgTypes.push_back(I64Ty);
173 X64ArgTypes.push_back(I64Ty);
174 ArgTranslations.push_back(ThunkArgTranslation::Direct);
175 }
176
177 // x4
178 Arm64ArgTypes.push_back(PtrTy);
179 X64ArgTypes.push_back(PtrTy);
180 ArgTranslations.push_back(ThunkArgTranslation::Direct);
181 // x5
182 Arm64ArgTypes.push_back(I64Ty);
183 if (TT != Arm64ECThunkType::Entry) {
184 // FIXME: x5 isn't actually used by the x64 side; revisit once we
185 // have proper isel for varargs
186 X64ArgTypes.push_back(I64Ty);
187 ArgTranslations.push_back(ThunkArgTranslation::Direct);
188 }
189 return;
190 }
191
192 unsigned I = 0;
193 if (HasSretPtr)
194 I++;
195
196 if (I == FT->getNumParams()) {
197 Out << "v";
198 return;
199 }
200
201 for (unsigned E = FT->getNumParams(); I != E; ++I) {
202#if 0
203 // FIXME: Need more information about argument size; see
204 // https://reviews.llvm.org/D132926
205 uint64_t ArgSizeBytes = AttrList.getParamArm64ECArgSizeBytes(I);
206 Align ParamAlign = AttrList.getParamAlignment(I).valueOrOne();
207#else
208 uint64_t ArgSizeBytes = 0;
209 Align ParamAlign = M->getDataLayout().getABITypeAlign(FT->getParamType(I));
210#endif
211 auto [Arm64Ty, X64Ty, ArgTranslation] =
212 canonicalizeThunkType(FT->getParamType(I), ParamAlign,
213 /*Ret*/ false, ArgSizeBytes, Out);
214 Arm64ArgTypes.push_back(Arm64Ty);
215 X64ArgTypes.push_back(X64Ty);
216 ArgTranslations.push_back(ArgTranslation);
217 }
218}
219
220void AArch64Arm64ECCallLowering::getThunkRetType(
221 FunctionType *FT, AttributeList AttrList, raw_ostream &Out,
222 Type *&Arm64RetTy, Type *&X64RetTy, SmallVectorImpl<Type *> &Arm64ArgTypes,
223 SmallVectorImpl<Type *> &X64ArgTypes,
224 SmallVector<ThunkArgTranslation> &ArgTranslations, bool &HasSretPtr) {
225 Type *T = FT->getReturnType();
226#if 0
227 // FIXME: Need more information about argument size; see
228 // https://reviews.llvm.org/D132926
229 uint64_t ArgSizeBytes = AttrList.getRetArm64ECArgSizeBytes();
230#else
231 int64_t ArgSizeBytes = 0;
232#endif
233 if (T->isVoidTy()) {
234 if (FT->getNumParams()) {
235 Attribute SRetAttr0 = AttrList.getParamAttr(0, Attribute::StructRet);
236 Attribute InRegAttr0 = AttrList.getParamAttr(0, Attribute::InReg);
237 Attribute SRetAttr1, InRegAttr1;
238 if (FT->getNumParams() > 1) {
239 // Also check the second parameter (for class methods, the first
240 // parameter is "this", and the second parameter is the sret pointer.)
241 // It doesn't matter which one is sret.
242 SRetAttr1 = AttrList.getParamAttr(1, Attribute::StructRet);
243 InRegAttr1 = AttrList.getParamAttr(1, Attribute::InReg);
244 }
245 if ((SRetAttr0.isValid() && InRegAttr0.isValid()) ||
246 (SRetAttr1.isValid() && InRegAttr1.isValid())) {
247 // sret+inreg indicates a call that returns a C++ class value. This is
248 // actually equivalent to just passing and returning a void* pointer
249 // as the first or second argument. Translate it that way, instead of
250 // trying to model "inreg" in the thunk's calling convention; this
251 // simplfies the rest of the code, and matches MSVC mangling.
252 Out << "i8";
253 Arm64RetTy = I64Ty;
254 X64RetTy = I64Ty;
255 return;
256 }
257 if (SRetAttr0.isValid()) {
258 // FIXME: Sanity-check the sret type; if it's an integer or pointer,
259 // we'll get screwy mangling/codegen.
260 // FIXME: For large struct types, mangle as an integer argument and
261 // integer return, so we can reuse more thunks, instead of "m" syntax.
262 // (MSVC mangles this case as an integer return with no argument, but
263 // that's a miscompile.)
264 Type *SRetType = SRetAttr0.getValueAsType();
265 Align SRetAlign = AttrList.getParamAlignment(0).valueOrOne();
266 canonicalizeThunkType(SRetType, SRetAlign, /*Ret*/ true, ArgSizeBytes,
267 Out);
268 Arm64RetTy = VoidTy;
269 X64RetTy = VoidTy;
270 Arm64ArgTypes.push_back(FT->getParamType(0));
271 X64ArgTypes.push_back(FT->getParamType(0));
272 ArgTranslations.push_back(ThunkArgTranslation::Direct);
273 HasSretPtr = true;
274 return;
275 }
276 }
277
278 Out << "v";
279 Arm64RetTy = VoidTy;
280 X64RetTy = VoidTy;
281 return;
282 }
283
284 auto info =
285 canonicalizeThunkType(T, Align(), /*Ret*/ true, ArgSizeBytes, Out);
286 Arm64RetTy = info.Arm64Ty;
287 X64RetTy = info.X64Ty;
288 if (X64RetTy->isPointerTy()) {
289 // If the X64 type is canonicalized to a pointer, that means it's
290 // passed/returned indirectly. For a return value, that means it's an
291 // sret pointer.
292 X64ArgTypes.push_back(X64RetTy);
293 X64RetTy = VoidTy;
294 }
295}
296
297ThunkArgInfo AArch64Arm64ECCallLowering::canonicalizeThunkType(
298 Type *T, Align Alignment, bool Ret, uint64_t ArgSizeBytes,
299 raw_ostream &Out) {
300
301 auto direct = [](Type *T) {
302 return ThunkArgInfo{T, T, ThunkArgTranslation::Direct};
303 };
304
305 auto bitcast = [this](Type *Arm64Ty, uint64_t SizeInBytes) {
306 return ThunkArgInfo{Arm64Ty,
307 llvm::Type::getIntNTy(M->getContext(), SizeInBytes * 8),
308 ThunkArgTranslation::Bitcast};
309 };
310
311 auto pointerIndirection = [this](Type *Arm64Ty) {
312 return ThunkArgInfo{Arm64Ty, PtrTy,
313 ThunkArgTranslation::PointerIndirection};
314 };
315
316 if (T->isHalfTy()) {
317 // Prefix with `llvm` since MSVC doesn't specify `_Float16`
318 Out << "__llvm_h__";
319 return direct(T);
320 }
321
322 if (T->isBFloatTy()) {
323 // Prefix with `llvm` since MSVC doesn't specify `__bf16`
324 Out << "__llvm_bf16__";
325 return direct(T);
326 }
327
328 if (T->isFloatTy()) {
329 Out << "f";
330 return direct(T);
331 }
332
333 if (T->isDoubleTy()) {
334 Out << "d";
335 return direct(T);
336 }
337
338 if (T->isFP128Ty()) {
339 // Prefix with `llvm` since MSVC doesn't specify `_Float128`
340 Out << "__llvm_q__";
341 // On windows f128 is passed indirectly, and Clang/LLVM
342 // returns using sret for compatibility with GCC.
343 return pointerIndirection(T);
344 }
345
346 if (T->isFloatingPointTy()) {
348 "Only half, bfloat16, float, double, and fp128 are supported "
349 "for ARM64EC thunks");
350 }
351
352 auto &DL = M->getDataLayout();
353
354 if (auto *StructTy = dyn_cast<StructType>(T))
355 if (StructTy->getNumElements() == 1)
356 T = StructTy->getElementType(0);
357
358 if (T->isArrayTy()) {
359 Type *ElementTy = T->getArrayElementType();
360 uint64_t ElementCnt = T->getArrayNumElements();
361 uint64_t ElementSizePerBytes = DL.getTypeSizeInBits(ElementTy) / 8;
362 uint64_t TotalSizeBytes = ElementCnt * ElementSizePerBytes;
363 if (ElementTy->isHalfTy() || ElementTy->isBFloatTy() ||
364 ElementTy->isFloatTy() || ElementTy->isDoubleTy() ||
365 ElementTy->isFP128Ty()) {
366 if (ElementTy->isHalfTy())
367 // Prefix with `llvm` since MSVC doesn't specify `_Float16`
368 Out << "__llvm_H__";
369 else if (ElementTy->isBFloatTy())
370 // Prefix with `llvm` since MSVC doesn't specify `__bf16`
371 Out << "__llvm_BF16__";
372 else if (ElementTy->isFloatTy())
373 Out << "F";
374 else if (ElementTy->isDoubleTy())
375 Out << "D";
376 else if (ElementTy->isFP128Ty())
377 // Prefix with `llvm` since MSVC doesn't specify `_Float128`
378 Out << "__llvm_Q__";
379 Out << TotalSizeBytes;
380 if (Alignment.value() >= 16 && !Ret)
381 Out << "a" << Alignment.value();
382 if (TotalSizeBytes <= 8) {
383 // Arm64 returns small structs of float/double in float registers;
384 // X64 uses RAX.
385 return bitcast(T, TotalSizeBytes);
386 } else {
387 // Struct is passed directly on Arm64, but indirectly on X64.
388 return pointerIndirection(T);
389 }
390 } else if (ElementTy->isFloatingPointTy()) {
392 "Only half, bfloat16, float, double, and fp128 are supported "
393 "for ARM64EC thunks");
394 }
395 }
396
397 if ((T->isIntegerTy() || T->isPointerTy()) && DL.getTypeSizeInBits(T) <= 64) {
398 Out << "i8";
399 return direct(I64Ty);
400 }
401
402 unsigned TypeSize = ArgSizeBytes;
403 if (TypeSize == 0)
404 TypeSize = DL.getTypeSizeInBits(T) / 8;
405 Out << "m";
406 if (TypeSize != 4)
407 Out << TypeSize;
408 if (Alignment.value() >= 16 && !Ret)
409 Out << "a" << Alignment.value();
410 // FIXME: Try to canonicalize Arm64Ty more thoroughly?
411 if (TypeSize == 1 || TypeSize == 2 || TypeSize == 4 || TypeSize == 8) {
412 // Pass directly in an integer register
413 return bitcast(T, TypeSize);
414 } else {
415 // Passed directly on Arm64, but indirectly on X64.
416 return pointerIndirection(T);
417 }
418}
419
420// This function builds the "exit thunk", a function which translates
421// arguments and return values when calling x64 code from AArch64 code.
422Function *AArch64Arm64ECCallLowering::buildExitThunk(FunctionType *FT,
423 AttributeList Attrs) {
424 SmallString<256> ExitThunkName;
425 llvm::raw_svector_ostream ExitThunkStream(ExitThunkName);
426 FunctionType *Arm64Ty, *X64Ty;
427 SmallVector<ThunkArgTranslation> ArgTranslations;
428 getThunkType(FT, Attrs, Arm64ECThunkType::Exit, ExitThunkStream, Arm64Ty,
429 X64Ty, ArgTranslations);
430 if (Function *F = M->getFunction(ExitThunkName))
431 return F;
432
434 ExitThunkName, M);
435 F->setCallingConv(CallingConv::ARM64EC_Thunk_Native);
436 F->setSection(".wowthk$aa");
437 F->setComdat(M->getOrInsertComdat(ExitThunkName));
438 // Copy MSVC, and always set up a frame pointer. (Maybe this isn't necessary.)
439 F->addFnAttr("frame-pointer", "all");
440 // Only copy sret from the first argument. For C++ instance methods, clang can
441 // stick an sret marking on a later argument, but it doesn't actually affect
442 // the ABI, so we can omit it. This avoids triggering a verifier assertion.
443 if (FT->getNumParams()) {
444 auto SRet = Attrs.getParamAttr(0, Attribute::StructRet);
445 auto InReg = Attrs.getParamAttr(0, Attribute::InReg);
446 if (SRet.isValid() && !InReg.isValid())
447 F->addParamAttr(1, SRet);
448 }
449 // FIXME: Copy anything other than sret? Shouldn't be necessary for normal
450 // C ABI, but might show up in other cases.
451 BasicBlock *BB = BasicBlock::Create(M->getContext(), "", F);
452 IRBuilder<> IRB(BB);
453 Value *CalleePtr =
454 M->getOrInsertGlobal("__os_arm64x_dispatch_call_no_redirect", PtrTy);
455 Value *Callee = IRB.CreateLoad(PtrTy, CalleePtr);
456 auto &DL = M->getDataLayout();
458 FunctionType *DispatcherCallTy = X64Ty;
459 // If we have a vararg function, the SelectionDAG lowering will need to
460 // recognize this so it can copy the arguments described by x4 (pointer) and
461 // x5 (length) to set up the x86-64 context correctly.
462 if (FT->isVarArg())
463 DispatcherCallTy =
464 FunctionType::get(X64Ty->getReturnType(), X64Ty->params(),
465 /*isVarArg=*/true);
466
467 // Pass the called function in x9.
468 auto X64TyOffset = 1;
469 Args.push_back(F->arg_begin());
470
471 Type *RetTy = Arm64Ty->getReturnType();
472 if (RetTy != X64Ty->getReturnType()) {
473 // If the return type is an array or struct, translate it. Values of size
474 // 8 or less go into RAX; bigger values go into memory, and we pass a
475 // pointer.
476 if (DL.getTypeStoreSize(RetTy) > 8) {
477 Args.push_back(IRB.CreateAlloca(RetTy));
478 X64TyOffset++;
479 }
480 }
481
482 for (auto [Arg, X64ArgType, ArgTranslation] : llvm::zip_equal(
483 make_range(F->arg_begin() + 1, F->arg_end()),
484 make_range(X64Ty->param_begin() + X64TyOffset, X64Ty->param_end()),
485 ArgTranslations)) {
486 // Translate arguments from AArch64 calling convention to x86 calling
487 // convention.
488 //
489 // For simple types, we don't need to do any translation: they're
490 // represented the same way. (Implicit sign extension is not part of
491 // either convention.)
492 //
493 // The big thing we have to worry about is struct types... but
494 // fortunately AArch64 clang is pretty friendly here: the cases that need
495 // translation are always passed as a struct or array. (If we run into
496 // some cases where this doesn't work, we can teach clang to mark it up
497 // with an attribute.)
498 //
499 // The first argument is the called function, stored in x9.
500 if (ArgTranslation != ThunkArgTranslation::Direct) {
501 Value *Mem = IRB.CreateAlloca(Arg.getType());
502 IRB.CreateStore(&Arg, Mem);
503 if (ArgTranslation == ThunkArgTranslation::Bitcast) {
504 Type *IntTy = IRB.getIntNTy(DL.getTypeStoreSizeInBits(Arg.getType()));
505 Args.push_back(IRB.CreateLoad(IntTy, Mem));
506 } else {
507 assert(ArgTranslation == ThunkArgTranslation::PointerIndirection);
508 Args.push_back(Mem);
509 }
510 } else {
511 Args.push_back(&Arg);
512 }
513 assert(Args.back()->getType() == X64ArgType);
514 }
515 // FIXME: Transfer necessary attributes? sret? anything else?
516
517 CallInst *Call = IRB.CreateCall(DispatcherCallTy, Callee, Args);
518 Call->setCallingConv(CallingConv::ARM64EC_Thunk_X64);
519
520 Value *RetVal = Call;
521 if (RetTy != X64Ty->getReturnType()) {
522 // If we rewrote the return type earlier, convert the return value to
523 // the proper type.
524 if (DL.getTypeStoreSize(RetTy) > 8) {
525 RetVal = IRB.CreateLoad(RetTy, Args[1]);
526 } else {
527 Value *CastAlloca = IRB.CreateAlloca(RetTy);
528 IRB.CreateStore(Call, CastAlloca);
529 RetVal = IRB.CreateLoad(RetTy, CastAlloca);
530 }
531 }
532
533 if (RetTy->isVoidTy())
534 IRB.CreateRetVoid();
535 else
536 IRB.CreateRet(RetVal);
537 return F;
538}
539
540// This function builds the "entry thunk", a function which translates
541// arguments and return values when calling AArch64 code from x64 code.
542Function *AArch64Arm64ECCallLowering::buildEntryThunk(Function *F) {
543 SmallString<256> EntryThunkName;
544 llvm::raw_svector_ostream EntryThunkStream(EntryThunkName);
545 FunctionType *Arm64Ty, *X64Ty;
546 SmallVector<ThunkArgTranslation> ArgTranslations;
547 getThunkType(F->getFunctionType(), F->getAttributes(),
548 Arm64ECThunkType::Entry, EntryThunkStream, Arm64Ty, X64Ty,
549 ArgTranslations);
550 if (Function *F = M->getFunction(EntryThunkName))
551 return F;
552
554 EntryThunkName, M);
555 Thunk->setCallingConv(CallingConv::ARM64EC_Thunk_X64);
556 Thunk->setSection(".wowthk$aa");
557 Thunk->setComdat(M->getOrInsertComdat(EntryThunkName));
558 // Copy MSVC, and always set up a frame pointer. (Maybe this isn't necessary.)
559 Thunk->addFnAttr("frame-pointer", "all");
560
561 BasicBlock *BB = BasicBlock::Create(M->getContext(), "", Thunk);
562 IRBuilder<> IRB(BB);
563
564 Type *RetTy = Arm64Ty->getReturnType();
565 Type *X64RetType = X64Ty->getReturnType();
566
567 bool TransformDirectToSRet = X64RetType->isVoidTy() && !RetTy->isVoidTy();
568 unsigned ThunkArgOffset = TransformDirectToSRet ? 2 : 1;
569 unsigned PassthroughArgSize =
570 Thunk->arg_size() - F->isVarArg() - ThunkArgOffset;
571 assert(ArgTranslations.size() == PassthroughArgSize + F->isVarArg());
572
573 // Translate arguments to call.
575 for (unsigned i = 0; i != PassthroughArgSize; ++i) {
576 Value *Arg = Thunk->getArg(i + ThunkArgOffset);
577 Type *ArgTy = Arm64Ty->getParamType(i);
578 ThunkArgTranslation ArgTranslation = ArgTranslations[i];
579 if (ArgTranslation != ThunkArgTranslation::Direct) {
580 // Translate array/struct arguments to the expected type.
581 if (ArgTranslation == ThunkArgTranslation::Bitcast) {
582 Value *CastAlloca = IRB.CreateAlloca(ArgTy);
583 IRB.CreateStore(Arg, CastAlloca);
584 Arg = IRB.CreateLoad(ArgTy, CastAlloca);
585 } else {
586 assert(ArgTranslation == ThunkArgTranslation::PointerIndirection);
587 Arg = IRB.CreateLoad(ArgTy, Arg);
588 }
589 }
590 assert(Arg->getType() == ArgTy);
591 Args.push_back(Arg);
592 }
593
594 if (F->isVarArg()) {
595 // The last argument to variadic entry thunks is used to model the x64 sp
596 // which is passed to the thunk in x4, this can be passed to the callee as
597 // the variadic argument start address after skipping over the 32 byte
598 // shadow store.
599
600 // The EC thunk CC will assign any argument marked as InReg to x4.
601 Thunk->addParamAttr(Thunk->arg_size() - 1, Attribute::InReg);
602 Value *StackArgs = Thunk->getArg(Thunk->arg_size() - 1);
603
604 // The first variadic stack argument is at X4+0x20, or X4+0x28 if the x64
605 // hidden sret pointer pushed the 4th integer argument onto the stack.
606 uint64_t StackOffset = TransformDirectToSRet ? 0x28 : 0x20;
607 Args.push_back(IRB.CreatePtrAddWithUnsignedOffset(StackArgs, StackOffset));
608
609 // Pass in a zero variadic argument size (in x5).
610 Args.push_back(IRB.getInt64(0));
611 }
612
613 // Call the function passed to the thunk.
614 Value *Callee = Thunk->getArg(0);
615 CallInst *Call = IRB.CreateCall(Arm64Ty, Callee, Args);
616
617 auto SRetAttr = F->getAttributes().getParamAttr(0, Attribute::StructRet);
618 auto InRegAttr = F->getAttributes().getParamAttr(0, Attribute::InReg);
619 if (SRetAttr.isValid() && !InRegAttr.isValid()) {
620 Thunk->addParamAttr(1, SRetAttr);
621 Call->addParamAttr(0, SRetAttr);
622 }
623
624 Value *RetVal = Call;
625 if (TransformDirectToSRet) {
626 // The x64 side returns this value indirectly via a hidden pointer (sret).
627 // Mark the thunk's pointer arg with sret so that ISel saves it and copies
628 // it into x8 (RAX) on return, matching the x64 calling convention.
629 Thunk->addParamAttr(
630 1, Attribute::getWithStructRetType(M->getContext(), RetTy));
631 IRB.CreateStore(RetVal, Thunk->getArg(1));
632 } else if (X64RetType != RetTy) {
633 Value *CastAlloca = IRB.CreateAlloca(X64RetType);
634 IRB.CreateStore(Call, CastAlloca);
635 RetVal = IRB.CreateLoad(X64RetType, CastAlloca);
636 }
637
638 // Return to the caller. Note that the isel has code to translate this
639 // "ret" to a tail call to __os_arm64x_dispatch_ret. (Alternatively, we
640 // could emit a tail call here, but that would require a dedicated calling
641 // convention, which seems more complicated overall.)
642 if (X64RetType->isVoidTy())
643 IRB.CreateRetVoid();
644 else
645 IRB.CreateRet(RetVal);
646
647 return Thunk;
648}
649
650std::optional<std::string> getArm64ECMangledFunctionName(GlobalValue &GV) {
651 if (!GV.hasName()) {
652 GV.setName("__unnamed");
653 }
654
656}
657
658// Builds the "guest exit thunk", a helper to call a function which may or may
659// not be an exit thunk. (We optimistically assume non-dllimport function
660// declarations refer to functions defined in AArch64 code; if the linker
661// can't prove that, we use this routine instead.)
662Function *AArch64Arm64ECCallLowering::buildGuestExitThunk(Function *F) {
663 llvm::raw_null_ostream NullThunkName;
664 FunctionType *Arm64Ty, *X64Ty;
665 SmallVector<ThunkArgTranslation> ArgTranslations;
666 getThunkType(F->getFunctionType(), F->getAttributes(),
667 Arm64ECThunkType::GuestExit, NullThunkName, Arm64Ty, X64Ty,
668 ArgTranslations);
669 auto MangledName = getArm64ECMangledFunctionName(*F);
670 assert(MangledName && "Can't guest exit to function that's already native");
671 std::string ThunkName = *MangledName;
672 if (ThunkName[0] == '?' && ThunkName.find("@") != std::string::npos) {
673 ThunkName.insert(ThunkName.find("@"), "$exit_thunk");
674 } else {
675 ThunkName.append("$exit_thunk");
676 }
678 Function::Create(Arm64Ty, GlobalValue::WeakODRLinkage, 0, ThunkName, M);
679 GuestExit->setComdat(M->getOrInsertComdat(ThunkName));
680 GuestExit->setSection(".wowthk$aa");
681 GuestExit->addMetadata(
682 "arm64ec_unmangled_name",
684 MDString::get(M->getContext(), F->getName())));
685 GuestExit->setMetadata(
686 "arm64ec_ecmangled_name",
688 MDString::get(M->getContext(), *MangledName)));
689 F->setMetadata("arm64ec_hasguestexit", MDNode::get(M->getContext(), {}));
691 IRBuilder<> B(BB);
692
693 // Create new call instruction. The call check should always be a call,
694 // even if the original CallBase is an Invoke or CallBr instructio.
695 // This is treated as a direct call, so do not use GuardFnCFGlobal.
696 LoadInst *GuardCheckLoad = B.CreateLoad(PtrTy, GuardFnGlobal);
697 Function *Thunk = buildExitThunk(F->getFunctionType(), F->getAttributes());
698 CallInst *GuardCheck = B.CreateCall(
699 GuardFnType, GuardCheckLoad, {F, Thunk});
700 Value *GuardCheckDest = B.CreateExtractValue(GuardCheck, 0);
701 Value *GuardFinalDest = B.CreateExtractValue(GuardCheck, 1);
702
703 // Ensure that the first argument is passed in the correct register.
704 GuardCheck->setCallingConv(CallingConv::CFGuard_Check);
705
707 OperandBundleDef OB("cfguardtarget", GuardFinalDest);
708 CallInst *Call = B.CreateCall(Arm64Ty, GuardCheckDest, Args, OB);
710
711 if (Call->getType()->isVoidTy())
712 B.CreateRetVoid();
713 else
714 B.CreateRet(Call);
715
716 auto SRetAttr = F->getAttributes().getParamAttr(0, Attribute::StructRet);
717 auto InRegAttr = F->getAttributes().getParamAttr(0, Attribute::InReg);
718 if (SRetAttr.isValid() && !InRegAttr.isValid()) {
719 GuestExit->addParamAttr(0, SRetAttr);
720 Call->addParamAttr(0, SRetAttr);
721 }
722
723 return GuestExit;
724}
725
726Function *
727AArch64Arm64ECCallLowering::buildPatchableThunk(GlobalAlias *UnmangledAlias,
728 GlobalAlias *MangledAlias) {
729 llvm::raw_null_ostream NullThunkName;
730 FunctionType *Arm64Ty, *X64Ty;
731 Function *F = cast<Function>(MangledAlias->getAliasee());
732 SmallVector<ThunkArgTranslation> ArgTranslations;
733 getThunkType(F->getFunctionType(), F->getAttributes(),
734 Arm64ECThunkType::GuestExit, NullThunkName, Arm64Ty, X64Ty,
735 ArgTranslations);
736 std::string ThunkName(MangledAlias->getName());
737 if (ThunkName[0] == '?' && ThunkName.find("@") != std::string::npos) {
738 ThunkName.insert(ThunkName.find("@"), "$hybpatch_thunk");
739 } else {
740 ThunkName.append("$hybpatch_thunk");
741 }
742
744 Function::Create(Arm64Ty, GlobalValue::WeakODRLinkage, 0, ThunkName, M);
745 GuestExit->setComdat(M->getOrInsertComdat(ThunkName));
746 GuestExit->setSection(".wowthk$aa");
748 IRBuilder<> B(BB);
749
750 // Load the global symbol as a pointer to the check function.
751 LoadInst *DispatchLoad = B.CreateLoad(PtrTy, DispatchFnGlobal);
752
753 // Create new dispatch call instruction.
754 Function *ExitThunk =
755 buildExitThunk(F->getFunctionType(), F->getAttributes());
756 CallInst *Dispatch =
757 B.CreateCall(DispatchFnType, DispatchLoad,
758 {UnmangledAlias, ExitThunk, UnmangledAlias->getAliasee()});
759
760 // Ensure that the first arguments are passed in the correct registers.
761 Dispatch->setCallingConv(CallingConv::CFGuard_Check);
762
764 CallInst *Call = B.CreateCall(Arm64Ty, Dispatch, Args);
766
767 if (Call->getType()->isVoidTy())
768 B.CreateRetVoid();
769 else
770 B.CreateRet(Call);
771
772 auto SRetAttr = F->getAttributes().getParamAttr(0, Attribute::StructRet);
773 auto InRegAttr = F->getAttributes().getParamAttr(0, Attribute::InReg);
774 if (SRetAttr.isValid() && !InRegAttr.isValid()) {
775 GuestExit->addParamAttr(0, SRetAttr);
776 Call->addParamAttr(0, SRetAttr);
777 }
778
779 MangledAlias->setAliasee(GuestExit);
780 return GuestExit;
781}
782
783// Lower an indirect call with inline code.
784void AArch64Arm64ECCallLowering::lowerCall(CallBase *CB) {
785 IRBuilder<> B(CB);
786 Value *CalledOperand = CB->getCalledOperand();
787
788 // If the indirect call is called within catchpad or cleanuppad,
789 // we need to copy "funclet" bundle of the call.
791 if (auto Bundle = CB->getOperandBundle(LLVMContext::OB_funclet))
792 Bundles.push_back(OperandBundleDef(*Bundle));
793
794 // Load the global symbol as a pointer to the check function.
795 Value *GuardFn;
796 if ((CFGuardModuleFlag == ControlFlowGuardMode::Enabled) &&
797 !CB->hasFnAttr("guard_nocf"))
798 GuardFn = GuardFnCFGlobal;
799 else
800 GuardFn = GuardFnGlobal;
801 LoadInst *GuardCheckLoad = B.CreateLoad(PtrTy, GuardFn);
802
803 // Create new call instruction. The CFGuard check should always be a call,
804 // even if the original CallBase is an Invoke or CallBr instruction.
805 Function *Thunk = buildExitThunk(CB->getFunctionType(), CB->getAttributes());
806 CallInst *GuardCheck =
807 B.CreateCall(GuardFnType, GuardCheckLoad, {CalledOperand, Thunk},
808 Bundles);
809 Value *GuardCheckDest = B.CreateExtractValue(GuardCheck, 0);
810 Value *GuardFinalDest = B.CreateExtractValue(GuardCheck, 1);
811
812 // Ensure that the first argument is passed in the correct register.
813 GuardCheck->setCallingConv(CallingConv::CFGuard_Check);
814
815 // Update the call: set the callee, and add a bundle with the final
816 // destination,
817 CB->setCalledOperand(GuardCheckDest);
818 OperandBundleDef OB("cfguardtarget", GuardFinalDest);
820 OB, CB->getIterator());
821 NewCall->copyMetadata(*CB);
822 CB->replaceAllUsesWith(NewCall);
823 CB->eraseFromParent();
824}
825
826bool AArch64Arm64ECCallLowering::runOnModule(Module &Mod) {
827 CLOpts = &Mod.getContext().getLibraryOptions().get<AArch64Options>();
828 if (!CLOpts->arm64ec_generate_thunks)
829 return false;
830
831 M = &Mod;
832
833 // Check if this module has the cfguard flag and read its value.
834 CFGuardModuleFlag = M->getControlFlowGuardMode();
835
836 // Warn if the module flag requests an unsupported CFGuard mechanism.
837 if (CFGuardModuleFlag == ControlFlowGuardMode::Enabled) {
839 Mod.getModuleFlag("cfguard-mechanism"))) {
840 auto MechanismOverride =
841 static_cast<ControlFlowGuardMechanism>(CI->getZExtValue());
842 if (MechanismOverride != ControlFlowGuardMechanism::Automatic &&
843 MechanismOverride != ControlFlowGuardMechanism::Check)
844 Mod.getContext().diagnose(
845 DiagnosticInfoGeneric("only the Check Control Flow Guard mechanism "
846 "is supported for Arm64EC",
847 DS_Warning));
848 }
849 }
850
851 PtrTy = PointerType::getUnqual(M->getContext());
852 I64Ty = Type::getInt64Ty(M->getContext());
853 VoidTy = Type::getVoidTy(M->getContext());
854
855 GuardFnType =
856 FunctionType::get(StructType::get(PtrTy, PtrTy), {PtrTy, PtrTy}, false);
857 DispatchFnType = FunctionType::get(PtrTy, {PtrTy, PtrTy, PtrTy}, false);
858 GuardFnCFGlobal = M->getOrInsertGlobal("__os_arm64x_check_icall_cfg", PtrTy);
859 GuardFnGlobal = M->getOrInsertGlobal("__os_arm64x_check_icall", PtrTy);
860 DispatchFnGlobal = M->getOrInsertGlobal("__os_arm64x_dispatch_call", PtrTy);
861
862 // Mangle names of function aliases and add the alias name to
863 // arm64ec_unmangled_name metadata to ensure a weak anti-dependency symbol is
864 // emitted for the alias as well. Do this early, before handling
865 // hybrid_patchable functions, to avoid mangling their aliases.
866 for (GlobalAlias &A : Mod.aliases()) {
867 auto F = dyn_cast_or_null<Function>(A.getAliaseeObject());
868 if (!F)
869 continue;
870 if (std::optional<std::string> MangledName =
872 F->addMetadata("arm64ec_unmangled_name",
874 MDString::get(M->getContext(), A.getName())));
875 A.setName(MangledName.value());
876 }
877 }
878
879 DenseMap<GlobalAlias *, GlobalAlias *> FnsMap;
880 SetVector<GlobalAlias *> PatchableFns;
881
882 for (Function &F : Mod) {
883 if (F.hasPersonalityFn()) {
884 GlobalValue *PersFn =
885 cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
886 if (PersFn->getValueType() && PersFn->getValueType()->isFunctionTy()) {
887 if (std::optional<std::string> MangledName =
889 PersFn->setName(MangledName.value());
890 }
891 }
892 }
893
894 if (!F.hasFnAttribute(Attribute::HybridPatchable) ||
895 F.isDeclarationForLinker() || F.hasLocalLinkage() ||
896 F.getName().ends_with(HybridPatchableTargetSuffix))
897 continue;
898
899 // Rename hybrid patchable functions and change callers to use a global
900 // alias instead.
901 if (std::optional<std::string> MangledName =
903 std::string OrigName(F.getName());
904 F.setName(MangledName.value() + HybridPatchableTargetSuffix);
905
906 // The unmangled symbol is a weak alias to an undefined symbol with the
907 // "EXP+" prefix. This undefined symbol is resolved by the linker by
908 // creating an x86 thunk that jumps back to the actual EC target. Since we
909 // can't represent that in IR, we create an alias to the target instead.
910 // The "EXP+" symbol is set as metadata, which is then used by
911 // emitGlobalAlias to emit the right alias.
912 auto *A =
915 MangledName.value(), &F);
916 F.replaceUsesWithIf(AM,
917 [](Use &U) { return isa<GlobalAlias>(U.getUser()); });
918 F.replaceAllUsesWith(A);
919 F.setMetadata("arm64ec_exp_name",
922 "EXP+" + MangledName.value())));
923 A->setAliasee(&F);
924 AM->setAliasee(&F);
925
926 if (F.hasDLLExportStorageClass()) {
927 A->setDLLStorageClass(GlobalValue::DLLExportStorageClass);
928 F.setDLLStorageClass(GlobalValue::DefaultStorageClass);
929 }
930
931 FnsMap[A] = AM;
932 PatchableFns.insert(A);
933 }
934 }
935
936 SetVector<GlobalValue *> DirectCalledFns;
937 for (Function &F : Mod)
938 if (!F.isDeclarationForLinker() &&
939 F.getCallingConv() != CallingConv::ARM64EC_Thunk_Native &&
940 F.getCallingConv() != CallingConv::ARM64EC_Thunk_X64)
941 processFunction(F, DirectCalledFns, FnsMap);
942
943 struct ThunkInfo {
944 Constant *Src;
945 Constant *Dst;
947 };
948 SmallVector<ThunkInfo> ThunkMapping;
949 for (Function &F : Mod) {
950 if (!F.isDeclarationForLinker() &&
951 (!F.hasLocalLinkage() || F.hasAddressTaken()) &&
952 F.getCallingConv() != CallingConv::ARM64EC_Thunk_Native &&
953 F.getCallingConv() != CallingConv::ARM64EC_Thunk_X64) {
954 if (!F.hasComdat())
955 F.setComdat(Mod.getOrInsertComdat(F.getName()));
956 ThunkMapping.push_back(
957 {&F, buildEntryThunk(&F), Arm64ECThunkType::Entry});
958 }
959 }
960 for (GlobalValue *O : DirectCalledFns) {
961 auto GA = dyn_cast<GlobalAlias>(O);
962 auto F = dyn_cast<Function>(GA ? GA->getAliasee() : O);
963 ThunkMapping.push_back(
964 {O, buildExitThunk(F->getFunctionType(), F->getAttributes()),
965 Arm64ECThunkType::Exit});
966 if (!GA && !F->hasDLLImportStorageClass())
967 ThunkMapping.push_back(
968 {buildGuestExitThunk(F), F, Arm64ECThunkType::GuestExit});
969 }
970 for (GlobalAlias *A : PatchableFns) {
971 Function *Thunk = buildPatchableThunk(A, FnsMap[A]);
972 ThunkMapping.push_back({Thunk, A, Arm64ECThunkType::GuestExit});
973 }
974
975 if (!ThunkMapping.empty()) {
976 SmallVector<Constant *> ThunkMappingArrayElems;
977 for (ThunkInfo &Thunk : ThunkMapping) {
978 ThunkMappingArrayElems.push_back(ConstantStruct::getAnon(
979 {Thunk.Src, Thunk.Dst,
980 ConstantInt::get(M->getContext(), APInt(32, uint8_t(Thunk.Kind)))}));
981 }
982 Constant *ThunkMappingArray = ConstantArray::get(
983 llvm::ArrayType::get(ThunkMappingArrayElems[0]->getType(),
984 ThunkMappingArrayElems.size()),
985 ThunkMappingArrayElems);
986 new GlobalVariable(Mod, ThunkMappingArray->getType(), /*isConstant*/ false,
987 GlobalValue::ExternalLinkage, ThunkMappingArray,
988 "llvm.arm64ec.symbolmap");
989 }
990
991 return true;
992}
993
994bool AArch64Arm64ECCallLowering::processFunction(
995 Function &F, SetVector<GlobalValue *> &DirectCalledFns,
996 DenseMap<GlobalAlias *, GlobalAlias *> &FnsMap) {
997 SmallVector<CallBase *, 8> IndirectCalls;
998
999 // For ARM64EC targets, a function definition's name is mangled differently
1000 // from the normal symbol. We currently have no representation of this sort
1001 // of symbol in IR, so we change the name to the mangled name, then store
1002 // the unmangled name as metadata. Later passes that need the unmangled
1003 // name (emitting the definition) can grab it from the metadata.
1004 //
1005 // FIXME: Handle functions with weak linkage?
1006 if (!F.hasLocalLinkage() || F.hasAddressTaken()) {
1007 if (std::optional<std::string> MangledName =
1009 F.addMetadata("arm64ec_unmangled_name",
1010 *MDNode::get(M->getContext(),
1011 MDString::get(M->getContext(), F.getName())));
1012 if (F.hasComdat() && F.getComdat()->getName() == F.getName()) {
1013 Comdat *MangledComdat = M->getOrInsertComdat(MangledName.value());
1014 SmallVector<GlobalObject *> ComdatUsers =
1015 to_vector(F.getComdat()->getUsers());
1016 for (GlobalObject *User : ComdatUsers)
1017 User->setComdat(MangledComdat);
1018 }
1019 F.setName(MangledName.value());
1020 }
1021 }
1022
1023 // Iterate over the instructions to find all indirect call/invoke/callbr
1024 // instructions. Make a separate list of pointers to indirect
1025 // call/invoke/callbr instructions because the original instructions will be
1026 // deleted as the checks are added.
1027 for (BasicBlock &BB : F) {
1028 for (Instruction &I : BB) {
1029 auto *CB = dyn_cast<CallBase>(&I);
1030 if (!CB || CB->getCallingConv() == CallingConv::ARM64EC_Thunk_X64 ||
1031 CB->isInlineAsm())
1032 continue;
1033
1034 // We need to instrument any call that isn't directly calling an
1035 // ARM64 function.
1036 //
1037 // FIXME: getCalledFunction() fails if there's a bitcast (e.g.
1038 // unprototyped functions in C)
1039 if (Function *F = CB->getCalledFunction()) {
1040 if (!CLOpts->arm64ec_lower_direct_to_indirect || F->hasLocalLinkage() ||
1041 F->isIntrinsic() || !F->isDeclarationForLinker())
1042 continue;
1043
1044 DirectCalledFns.insert(F);
1045 continue;
1046 }
1047
1048 // Use mangled global alias for direct calls to patchable functions.
1049 if (GlobalAlias *A = dyn_cast<GlobalAlias>(CB->getCalledOperand())) {
1050 auto I = FnsMap.find(A);
1051 if (I != FnsMap.end()) {
1052 CB->setCalledOperand(I->second);
1053 DirectCalledFns.insert(I->first);
1054 continue;
1055 }
1056 }
1057
1058 IndirectCalls.push_back(CB);
1059 ++Arm64ECCallsLowered;
1060 }
1061 }
1062
1063 if (IndirectCalls.empty())
1064 return false;
1065
1066 for (CallBase *CB : IndirectCalls)
1067 lowerCall(CB);
1068
1069 return true;
1070}
1071
1072char AArch64Arm64ECCallLowering::ID = 0;
1073INITIALIZE_PASS(AArch64Arm64ECCallLowering, "Arm64ECCallLowering",
1074 "AArch64Arm64ECCallLowering", false, false)
1075
1077 return new AArch64Arm64ECCallLowering;
1078}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Module.h This file contains the declarations for the Module class.
lazy value info
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Machine Check Debug Module
#define T
static bool processFunction(Function &F, NVPTXTargetMachine &TM)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file implements a set that has insertion order iteration characteristics.
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 SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:263
LLVM_ABI Type * getValueAsType() const
Return the attribute's value as a Type.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
bool isInlineAsm() const
Check if this call is an inline asm statement.
void setCallingConv(CallingConv::ID CC)
std::optional< OperandBundleUse > getOperandBundle(StringRef Name) const
Return an operand bundle by name, if present.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
CallingConv::ID getCallingConv() const
static LLVM_ABI CallBase * addOperandBundle(CallBase *CB, uint32_t ID, OperandBundleDef OB, InsertPosition InsertPt=nullptr)
Create a clone of CB with operand bundle OB added.
Value * getCalledOperand() const
FunctionType * getFunctionType() const
void setCalledOperand(Value *V)
AttributeList getAttributes() const
Return the attributes for this call.
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
void setTailCallKind(TailCallKind TCK)
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static Constant * getAnon(ArrayRef< Constant * > V, bool Packed=false)
Return an anonymous struct that has the specified elements.
Definition Constants.h:643
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
LLVM_ABI void setAliasee(Constant *Aliasee)
These methods retrieve and set alias target.
Definition Globals.cpp:724
const Constant * getAliasee() const
Definition GlobalAlias.h:87
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition Globals.cpp:692
@ DLLExportStorageClass
Function to be accessible from DLL.
Definition GlobalValue.h:77
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
Type * getValueType() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition Module.cpp:254
ControlFlowGuardMode getControlFlowGuardMode() const
Gets the Control Flow Guard mode.
Definition Module.cpp:1066
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition Module.cpp:650
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition Module.h:325
GlobalVariable * getOrInsertGlobal(StringRef Name, Type *Ty, function_ref< GlobalVariable *()> CreateGlobalCallback)
Look up the specified global in the module symbol table.
Definition Module.cpp:281
A container for an operand bundle being viewed as a set of values rather than a set of uses.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static LLVM_ABI StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition Type.cpp:462
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
bool isBFloatTy() const
Return true if this is 'bfloat', a 16-bit bfloat type.
Definition Type.h:147
bool isFP128Ty() const
Return true if this is 'fp128'.
Definition Type.h:164
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:268
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
self_iterator getIterator()
Definition ilist_node.h:123
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
CallInst * Call
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Arm64ECThunkType
Definition COFF.h:860
@ GuestExit
Definition COFF.h:861
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
@ OB
OB - OneByte - Set if this instruction has a one byte opcode.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract_or_null(Y &&MD)
Extract a Value from Metadata, if any, allowing null.
Definition Metadata.h:721
@ User
could "use" a pointer
This is an optimization pass for GlobalISel generic memory operations.
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
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
ControlFlowGuardMode
Definition CodeGen.h:385
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
ModulePass * createAArch64Arm64ECCallLoweringPass()
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
SmallVector< ValueTypeFromRangeType< R >, Size > to_vector(R &&Range)
Given a range of type R, iterate the entire range and return a SmallVector with elements of the vecto...
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
constexpr std::string_view HybridPatchableTargetSuffix
Definition Mangler.h:37
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:35
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
ControlFlowGuardMechanism
Definition CodeGen.h:395