LLVM 23.0.0git
ExpandVariadics.cpp
Go to the documentation of this file.
1//===-- ExpandVariadicsPass.cpp --------------------------------*- C++ -*-=//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This is an optimization pass for variadic functions. If called from codegen,
10// it can serve as the implementation of variadic functions for a given target.
11//
12// The strategy is to turn the ... part of a variadic function into a va_list
13// and fix up the call sites. The majority of the pass is target independent.
14// The exceptions are the va_list type itself and the rules for where to store
15// variables in memory such that va_arg can iterate over them given a va_list.
16//
17// The majority of the plumbing is splitting the variadic function into a
18// single basic block that packs the variadic arguments into a va_list and
19// a second function that does the work of the original. That packing is
20// exactly what is done by va_start. Further, the transform from ... to va_list
21// replaced va_start with an operation to copy a va_list from the new argument,
22// which is exactly a va_copy. This is useful for reducing target-dependence.
23//
24// A va_list instance is a forward iterator, where the primary operation va_arg
25// is dereference-then-increment. This interface forces significant convergent
26// evolution between target specific implementations. The variation in runtime
27// data layout is limited to that representable by the iterator, parameterised
28// by the type passed to the va_arg instruction.
29//
30// Therefore the majority of the target specific subtlety is packing arguments
31// into a stack allocated buffer such that a va_list can be initialised with it
32// and the va_arg expansion for the target will find the arguments at runtime.
33//
34// The aggregate effect is to unblock other transforms, most critically the
35// general purpose inliner. Known calls to variadic functions become zero cost.
36//
37// Consistency with clang is primarily tested by emitting va_arg using clang
38// then expanding the variadic functions using this pass, followed by trying
39// to constant fold the functions to no-ops.
40//
41// Target specific behaviour is tested in IR - mainly checking that values are
42// put into positions in call frames that make sense for that particular target.
43//
44// There is one "clever" invariant in use. va_start intrinsics that are not
45// within a varidic functions are an error in the IR verifier. When this
46// transform moves blocks from a variadic function into a fixed arity one, it
47// moves va_start intrinsics along with everything else. That means that the
48// va_start intrinsics that need to be rewritten to use the trailing argument
49// are exactly those that are in non-variadic functions so no further state
50// is needed to distinguish those that need to be rewritten.
51//
52//===----------------------------------------------------------------------===//
53
57#include "llvm/IR/IRBuilder.h"
59#include "llvm/IR/Module.h"
60#include "llvm/IR/PassManager.h"
62#include "llvm/Pass.h"
67
68#define DEBUG_TYPE "expand-variadics"
69
70using namespace llvm;
71
72namespace {
73
74cl::opt<ExpandVariadicsMode> ExpandVariadicsModeOption(
75 DEBUG_TYPE "-override", cl::desc("Override the behaviour of " DEBUG_TYPE),
78 "Use the implementation defaults"),
80 "Disable the pass entirely"),
82 "Optimise without changing ABI"),
84 "Change variadic calling convention")));
85
86bool commandLineOverride() {
87 return ExpandVariadicsModeOption != ExpandVariadicsMode::Unspecified;
88}
89
90// Instances of this class encapsulate the target-dependant behaviour as a
91// function of triple. Implementing a new ABI is adding a case to the switch
92// in create(llvm::Triple) at the end of this file.
93// This class may end up instantiated in TargetMachine instances, keeping it
94// here for now until enough targets are implemented for the API to evolve.
95class VariadicABIInfo {
96protected:
97 VariadicABIInfo() = default;
98
99public:
100 static std::unique_ptr<VariadicABIInfo> create(const Triple &T);
101
102 // Allow overriding whether the pass runs on a per-target basis
103 virtual bool enableForTarget() = 0;
104
105 // Whether a valist instance is passed by value or by address
106 // I.e. does it need to be alloca'ed and stored into, or can
107 // it be passed directly in a SSA register
108 virtual bool vaListPassedInSSARegister() = 0;
109
110 // The type of a va_list iterator object
111 virtual Type *vaListType(LLVMContext &Ctx) = 0;
112
113 // The type of a va_list as a function argument as lowered by C
114 virtual Type *vaListParameterType(Module &M) = 0;
115
116 // Initialize an allocated va_list object to point to an already
117 // initialized contiguous memory region.
118 // Return the value to pass as the va_list argument
119 virtual Value *initializeVaList(Module &M, LLVMContext &Ctx,
120 IRBuilder<> &Builder, AllocaInst *VaList,
121 Value *Buffer) = 0;
122
123 struct VAArgSlotInfo {
124 Align DataAlign; // With respect to the call frame
125 bool Indirect; // Passed via a pointer
126 };
127 virtual VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) = 0;
128
129 // Targets implemented so far all have the same trivial lowering for these
130 bool vaEndIsNop() { return true; }
131 bool vaCopyIsMemcpy() { return true; }
132
133 // Per-target overrides of special symbols.
134 virtual bool ignoreFunction(const Function *F) { return false; }
135
136 // Any additional address spaces used in va intrinsics that should be
137 // expanded.
138 virtual SmallVector<unsigned> getTargetSpecificVaIntrinAddrSpaces() const {
139 return {};
140 }
141
142 virtual ~VariadicABIInfo() = default;
143};
144
145class ExpandVariadics : public ModulePass {
146
147 // The pass construction sets the default to optimize when called from middle
148 // end and lowering when called from the backend. The command line variable
149 // overrides that. This is useful for testing and debugging. It also allows
150 // building an applications with variadic functions wholly removed if one
151 // has sufficient control over the dependencies, e.g. a statically linked
152 // clang that has no variadic function calls remaining in the binary.
153
154public:
155 static char ID;
157 std::unique_ptr<VariadicABIInfo> ABI;
158
159 ExpandVariadics(ExpandVariadicsMode Mode)
160 : ModulePass(ID),
161 Mode(commandLineOverride() ? ExpandVariadicsModeOption : Mode) {}
162
163 StringRef getPassName() const override { return "Expand variadic functions"; }
164
165 bool rewriteABI() { return Mode == ExpandVariadicsMode::Lowering; }
166
167 template <typename T> bool isValidCallingConv(T *F) {
168 return F->getCallingConv() == CallingConv::C ||
169 F->getCallingConv() == CallingConv::SPIR_FUNC;
170 }
171
172 bool runOnModule(Module &M) override;
173
174 bool runOnFunction(Module &M, IRBuilder<> &Builder, Function *F);
175
176 Function *replaceAllUsesWithNewDeclaration(Module &M,
177 Function *OriginalFunction);
178
179 Function *deriveFixedArityReplacement(Module &M, IRBuilder<> &Builder,
180 Function *OriginalFunction);
181
182 Function *defineVariadicWrapper(Module &M, IRBuilder<> &Builder,
183 Function *VariadicWrapper,
184 Function *FixedArityReplacement);
185
186 bool expandCall(Module &M, IRBuilder<> &Builder, CallBase *CB, FunctionType *,
187 Function *NF);
188
189 // The intrinsic functions va_copy and va_end are removed unconditionally.
190 // They correspond to a memcpy and a no-op on all implemented targets.
191 // The va_start intrinsic is removed from basic blocks that were not created
192 // by this pass, some may remain if needed to maintain the external ABI.
193
194 template <Intrinsic::ID ID, typename InstructionType>
195 bool expandIntrinsicUsers(Module &M, IRBuilder<> &Builder,
196 PointerType *IntrinsicArgType) {
197 bool Changed = false;
198 const DataLayout &DL = M.getDataLayout();
199 if (Function *Intrinsic =
200 Intrinsic::getDeclarationIfExists(&M, ID, {IntrinsicArgType})) {
201 for (User *U : make_early_inc_range(Intrinsic->users()))
202 if (auto *I = dyn_cast<InstructionType>(U))
203 Changed |= expandVAIntrinsicCall(Builder, DL, I);
204
205 if (Intrinsic->use_empty())
206 Intrinsic->eraseFromParent();
207 }
208 return Changed;
209 }
210
211 bool expandVAIntrinsicUsersWithAddrspace(Module &M, IRBuilder<> &Builder,
212 unsigned Addrspace) {
213 auto &Ctx = M.getContext();
214 PointerType *IntrinsicArgType = PointerType::get(Ctx, Addrspace);
215 bool Changed = false;
216
217 // expand vastart before vacopy as vastart may introduce a vacopy
218 Changed |= expandIntrinsicUsers<Intrinsic::vastart, VAStartInst>(
219 M, Builder, IntrinsicArgType);
220 Changed |= expandIntrinsicUsers<Intrinsic::vaend, VAEndInst>(
221 M, Builder, IntrinsicArgType);
222 Changed |= expandIntrinsicUsers<Intrinsic::vacopy, VACopyInst>(
223 M, Builder, IntrinsicArgType);
224 return Changed;
225 }
226
227 bool expandVAIntrinsicCall(IRBuilder<> &Builder, const DataLayout &DL,
228 VAStartInst *Inst);
229
230 bool expandVAIntrinsicCall(IRBuilder<> &, const DataLayout &,
231 VAEndInst *Inst);
232
233 bool expandVAIntrinsicCall(IRBuilder<> &Builder, const DataLayout &DL,
234 VACopyInst *Inst);
235
236 FunctionType *inlinableVariadicFunctionType(Module &M, FunctionType *FTy) {
237 // The type of "FTy" with the ... removed and a va_list appended
238 SmallVector<Type *> ArgTypes(FTy->params());
239 ArgTypes.push_back(ABI->vaListParameterType(M));
240 return FunctionType::get(FTy->getReturnType(), ArgTypes,
241 /*IsVarArgs=*/false);
242 }
243
244 bool expansionApplicableToFunction(Module &M, Function *F) {
245 if (F->isIntrinsic() || !F->isVarArg() ||
246 F->hasFnAttribute(Attribute::Naked))
247 return false;
248
249 if (ABI->ignoreFunction(F))
250 return false;
251
252 if (!isValidCallingConv(F))
253 return false;
254
255 if (rewriteABI())
256 return true;
257
258 if (!F->hasExactDefinition())
259 return false;
260
261 return true;
262 }
263
264 bool expansionApplicableToFunctionCall(CallBase *CB) {
265 if (CallInst *CI = dyn_cast<CallInst>(CB)) {
266 if (CI->isMustTailCall()) {
267 // Cannot expand musttail calls
268 return false;
269 }
270
271 if (!isValidCallingConv(CI))
272 return false;
273
274 return true;
275 }
276
277 if (isa<InvokeInst>(CB)) {
278 // Invoke not implemented in initial implementation of pass
279 return false;
280 }
281
282 // Other unimplemented derivative of CallBase
283 return false;
284 }
285
286 class ExpandedCallFrame {
287 // Helper for constructing an alloca instance containing the arguments bound
288 // to the variadic ... parameter, rearranged to allow indexing through a
289 // va_list iterator
290 enum { N = 4 };
291 SmallVector<Type *, N> FieldTypes;
292 enum Tag { Store, Memcpy, Padding };
294
295 template <Tag tag> void append(Type *FieldType, Value *V, uint64_t Bytes) {
296 FieldTypes.push_back(FieldType);
297 Source.push_back({V, Bytes, tag});
298 }
299
300 public:
301 void store(LLVMContext &Ctx, Type *T, Value *V) { append<Store>(T, V, 0); }
302
303 void memcpy(LLVMContext &Ctx, Type *T, Value *V, uint64_t Bytes) {
304 append<Memcpy>(T, V, Bytes);
305 }
306
307 void padding(LLVMContext &Ctx, uint64_t By) {
308 append<Padding>(ArrayType::get(Type::getInt8Ty(Ctx), By), nullptr, 0);
309 }
310
311 size_t size() const { return FieldTypes.size(); }
312 bool empty() const { return FieldTypes.empty(); }
313
314 StructType *asStruct(LLVMContext &Ctx, StringRef Name) {
315 const bool IsPacked = true;
316 return StructType::create(Ctx, FieldTypes,
317 (Twine(Name) + ".vararg").str(), IsPacked);
318 }
319
320 void initializeStructAlloca(const DataLayout &DL, IRBuilder<> &Builder,
321 AllocaInst *Alloced, StructType *VarargsTy) {
322
323 for (size_t I = 0; I < size(); I++) {
324
325 auto [V, bytes, tag] = Source[I];
326
327 if (tag == Padding) {
328 assert(V == nullptr);
329 continue;
330 }
331
332 auto Dst = Builder.CreateStructGEP(VarargsTy, Alloced, I);
333
334 assert(V != nullptr);
335
336 if (tag == Store)
337 Builder.CreateStore(V, Dst);
338
339 if (tag == Memcpy)
340 Builder.CreateMemCpy(Dst, {}, V, {}, bytes);
341 }
342 }
343 };
344};
345
346bool ExpandVariadics::runOnModule(Module &M) {
347 bool Changed = false;
349 return Changed;
350
351 Triple TT(M.getTargetTriple());
352 ABI = VariadicABIInfo::create(TT);
353 if (!ABI)
354 return Changed;
355
356 if (!ABI->enableForTarget())
357 return Changed;
358
359 auto &Ctx = M.getContext();
360 const DataLayout &DL = M.getDataLayout();
361 IRBuilder<> Builder(Ctx);
362
363 // Lowering needs to run on all functions exactly once.
364 // Optimize could run on functions containing va_start exactly once.
366 Changed |= runOnFunction(M, Builder, &F);
367
368 // After runOnFunction, all known calls to known variadic functions have been
369 // replaced. va_start intrinsics are presently (and invalidly!) only present
370 // in functions that used to be variadic and have now been replaced to take a
371 // va_list instead. If lowering as opposed to optimising, calls to unknown
372 // variadic functions have also been replaced.
373
374 {
375 unsigned Addrspace = 0;
376 Changed |= expandVAIntrinsicUsersWithAddrspace(M, Builder, Addrspace);
377
378 Addrspace = DL.getAllocaAddrSpace();
379 if (Addrspace != 0)
380 Changed |= expandVAIntrinsicUsersWithAddrspace(M, Builder, Addrspace);
381
382 // Process any addrspaces targets declare to be important.
383 const SmallVector<unsigned> &TargetASVec =
384 ABI->getTargetSpecificVaIntrinAddrSpaces();
385 for (unsigned TargetAS : TargetASVec) {
386 if (TargetAS == 0 || TargetAS == DL.getAllocaAddrSpace())
387 continue;
388 Changed |= expandVAIntrinsicUsersWithAddrspace(M, Builder, TargetAS);
389 }
390 }
391
393 return Changed;
394
395 for (Function &F : make_early_inc_range(M)) {
396 if (F.isDeclaration())
397 continue;
398
399 // Now need to track down indirect calls. Can't find those
400 // by walking uses of variadic functions, need to crawl the instruction
401 // stream. Fortunately this is only necessary for the ABI rewrite case.
402 for (BasicBlock &BB : F) {
403 for (Instruction &I : make_early_inc_range(BB)) {
404 if (CallBase *CB = dyn_cast<CallBase>(&I)) {
405 if (CB->isIndirectCall()) {
406 FunctionType *FTy = CB->getFunctionType();
407 if (FTy->isVarArg())
408 Changed |= expandCall(M, Builder, CB, FTy, /*NF=*/nullptr);
409 }
410 }
411 }
412 }
413 }
414
415 return Changed;
416}
417
418bool ExpandVariadics::runOnFunction(Module &M, IRBuilder<> &Builder,
419 Function *OriginalFunction) {
420 bool Changed = false;
421
422 if (!expansionApplicableToFunction(M, OriginalFunction))
423 return Changed;
424
425 [[maybe_unused]] const bool OriginalFunctionIsDeclaration =
426 OriginalFunction->isDeclaration();
427 assert(rewriteABI() || !OriginalFunctionIsDeclaration);
428
429 // Declare a new function and redirect every use to that new function
430 Function *VariadicWrapper =
431 replaceAllUsesWithNewDeclaration(M, OriginalFunction);
432 assert(VariadicWrapper->isDeclaration());
433 assert(OriginalFunction->use_empty());
434
435 // Create a new function taking va_list containing the implementation of the
436 // original
437 Function *FixedArityReplacement =
438 deriveFixedArityReplacement(M, Builder, OriginalFunction);
439 assert(OriginalFunction->isDeclaration());
440 assert(FixedArityReplacement->isDeclaration() ==
441 OriginalFunctionIsDeclaration);
442 assert(VariadicWrapper->isDeclaration());
443
444 // Create a single block forwarding wrapper that turns a ... into a va_list
445 [[maybe_unused]] Function *VariadicWrapperDefine =
446 defineVariadicWrapper(M, Builder, VariadicWrapper, FixedArityReplacement);
447 assert(VariadicWrapperDefine == VariadicWrapper);
448 assert(!VariadicWrapper->isDeclaration());
449
450 // Add the prof metadata from the original function to the wrapper. Because
451 // FixedArityReplacement is the owner of original function's prof metadata
452 // after the splice, we need to transfer it to VariadicWrapper.
453 VariadicWrapper->setMetadata(
454 LLVMContext::MD_prof,
455 FixedArityReplacement->getMetadata(LLVMContext::MD_prof));
456
457 // We now have:
458 // 1. the original function, now as a declaration with no uses
459 // 2. a variadic function that unconditionally calls a fixed arity replacement
460 // 3. a fixed arity function equivalent to the original function
461
462 // Replace known calls to the variadic with calls to the va_list equivalent
463 for (User *U : make_early_inc_range(VariadicWrapper->users())) {
464 if (CallBase *CB = dyn_cast<CallBase>(U)) {
465 Value *CalledOperand = CB->getCalledOperand();
466 if (VariadicWrapper == CalledOperand)
467 Changed |=
468 expandCall(M, Builder, CB, VariadicWrapper->getFunctionType(),
469 FixedArityReplacement);
470 }
471 }
472
473 // The original function will be erased.
474 // One of the two new functions will become a replacement for the original.
475 // When preserving the ABI, the other is an internal implementation detail.
476 // When rewriting the ABI, RAUW then the variadic one.
477 Function *const ExternallyAccessible =
478 rewriteABI() ? FixedArityReplacement : VariadicWrapper;
479 Function *const InternalOnly =
480 rewriteABI() ? VariadicWrapper : FixedArityReplacement;
481
482 // The external function is the replacement for the original
483 ExternallyAccessible->setLinkage(OriginalFunction->getLinkage());
484 ExternallyAccessible->setVisibility(OriginalFunction->getVisibility());
485 ExternallyAccessible->setComdat(OriginalFunction->getComdat());
486 ExternallyAccessible->takeName(OriginalFunction);
487
488 // Annotate the internal one as internal
491
492 // The original is unused and obsolete
493 OriginalFunction->eraseFromParent();
494
495 InternalOnly->removeDeadConstantUsers();
496
497 if (rewriteABI()) {
498 // All known calls to the function have been removed by expandCall
499 // Resolve everything else by replaceAllUsesWith
500 VariadicWrapper->replaceAllUsesWith(FixedArityReplacement);
501 VariadicWrapper->eraseFromParent();
502 }
503
504 return Changed;
505}
506
507Function *
508ExpandVariadics::replaceAllUsesWithNewDeclaration(Module &M,
509 Function *OriginalFunction) {
510 auto &Ctx = M.getContext();
511 Function &F = *OriginalFunction;
512 FunctionType *FTy = F.getFunctionType();
513 Function *NF = Function::Create(FTy, F.getLinkage(), F.getAddressSpace());
514
515 NF->setName(F.getName() + ".varargs");
516
517 F.getParent()->getFunctionList().insert(F.getIterator(), NF);
518
519 AttrBuilder ParamAttrs(Ctx);
520 AttributeList Attrs = NF->getAttributes();
521 Attrs = Attrs.addParamAttributes(Ctx, FTy->getNumParams(), ParamAttrs);
522 NF->setAttributes(Attrs);
523
524 OriginalFunction->replaceAllUsesWith(NF);
525 return NF;
526}
527
528Function *
529ExpandVariadics::deriveFixedArityReplacement(Module &M, IRBuilder<> &Builder,
530 Function *OriginalFunction) {
531 Function &F = *OriginalFunction;
532 // The purpose here is split the variadic function F into two functions
533 // One is a variadic function that bundles the passed argument into a va_list
534 // and passes it to the second function. The second function does whatever
535 // the original F does, except that it takes a va_list instead of the ...
536
537 assert(expansionApplicableToFunction(M, &F));
538
539 auto &Ctx = M.getContext();
540
541 // Returned value isDeclaration() is equal to F.isDeclaration()
542 // but that property is not invariant throughout this function
543 const bool FunctionIsDefinition = !F.isDeclaration();
544
545 FunctionType *FTy = F.getFunctionType();
546 SmallVector<Type *> ArgTypes(FTy->params());
547 ArgTypes.push_back(ABI->vaListParameterType(M));
548
549 FunctionType *NFTy = inlinableVariadicFunctionType(M, FTy);
550 Function *NF = Function::Create(NFTy, F.getLinkage(), F.getAddressSpace());
551
552 // Note - same attribute handling as DeadArgumentElimination
553 NF->copyAttributesFrom(&F);
554 NF->setComdat(F.getComdat());
555 F.getParent()->getFunctionList().insert(F.getIterator(), NF);
556 NF->setName(F.getName() + ".valist");
557
558 AttrBuilder ParamAttrs(Ctx);
559
560 AttributeList Attrs = NF->getAttributes();
561 Attrs = Attrs.addParamAttributes(Ctx, NFTy->getNumParams() - 1, ParamAttrs);
562 NF->setAttributes(Attrs);
563
564 // Splice the implementation into the new function with minimal changes
565 if (FunctionIsDefinition) {
566 NF->splice(NF->begin(), &F);
567
568 auto NewArg = NF->arg_begin();
569 for (Argument &Arg : F.args()) {
570 Arg.replaceAllUsesWith(NewArg);
571 NewArg->setName(Arg.getName()); // takeName without killing the old one
572 ++NewArg;
573 }
574 NewArg->setName("varargs");
575 }
576
578 F.getAllMetadata(MDs);
579 for (auto [KindID, Node] : MDs)
580 NF->addMetadata(KindID, *Node);
581 F.clearMetadata();
582
583 return NF;
584}
585
586Function *
587ExpandVariadics::defineVariadicWrapper(Module &M, IRBuilder<> &Builder,
588 Function *VariadicWrapper,
589 Function *FixedArityReplacement) {
590 auto &Ctx = Builder.getContext();
591 const DataLayout &DL = M.getDataLayout();
592 assert(VariadicWrapper->isDeclaration());
593 Function &F = *VariadicWrapper;
594
595 assert(F.isDeclaration());
596 Type *VaListTy = ABI->vaListType(Ctx);
597
598 auto *BB = BasicBlock::Create(Ctx, "entry", &F);
599 Builder.SetInsertPoint(BB);
600
601 AllocaInst *VaListInstance =
602 Builder.CreateAlloca(VaListTy, nullptr, "va_start");
603
604 Builder.CreateLifetimeStart(VaListInstance);
605
606 Builder.CreateIntrinsic(Intrinsic::vastart, {DL.getAllocaPtrType(Ctx)},
607 {VaListInstance});
608
610
611 Type *ParameterType = ABI->vaListParameterType(M);
612 if (ABI->vaListPassedInSSARegister())
613 Args.push_back(Builder.CreateLoad(ParameterType, VaListInstance));
614 else
615 Args.push_back(Builder.CreateAddrSpaceCast(VaListInstance, ParameterType));
616
617 CallInst *Result = Builder.CreateCall(FixedArityReplacement, Args);
618
619 Builder.CreateIntrinsic(Intrinsic::vaend, {DL.getAllocaPtrType(Ctx)},
620 {VaListInstance});
621 Builder.CreateLifetimeEnd(VaListInstance);
622
623 if (Result->getType()->isVoidTy())
624 Builder.CreateRetVoid();
625 else
626 Builder.CreateRet(Result);
627
628 return VariadicWrapper;
629}
630
631bool ExpandVariadics::expandCall(Module &M, IRBuilder<> &Builder, CallBase *CB,
632 FunctionType *VarargFunctionType,
633 Function *NF) {
634 bool Changed = false;
635 const DataLayout &DL = M.getDataLayout();
636
637 if (ABI->ignoreFunction(CB->getCalledFunction()))
638 return Changed;
639
640 if (!expansionApplicableToFunctionCall(CB)) {
641 if (rewriteABI())
642 report_fatal_error("Cannot lower callbase instruction");
643 return Changed;
644 }
645
646 // This is tricky. The call instruction's function type might not match
647 // the type of the caller. When optimising, can leave it unchanged.
648 // Webassembly detects that inconsistency and repairs it.
649 FunctionType *FuncType = CB->getFunctionType();
650 if (FuncType != VarargFunctionType) {
651 if (!rewriteABI())
652 return Changed;
653 FuncType = VarargFunctionType;
654 }
655
656 auto &Ctx = CB->getContext();
657
658 Align MaxFieldAlign(1);
659
660 // The strategy is to allocate a call frame containing the variadic
661 // arguments laid out such that a target specific va_list can be initialized
662 // with it, such that target specific va_arg instructions will correctly
663 // iterate over it. This means getting the alignment right and sometimes
664 // embedding a pointer to the value instead of embedding the value itself.
665
666 Function *CBF = CB->getParent()->getParent();
667
668 ExpandedCallFrame Frame;
669
670 uint64_t CurrentOffset = 0;
671
672 for (unsigned I = FuncType->getNumParams(), E = CB->arg_size(); I < E; ++I) {
673 Value *ArgVal = CB->getArgOperand(I);
674 const bool IsByVal = CB->paramHasAttr(I, Attribute::ByVal);
675 const bool IsByRef = CB->paramHasAttr(I, Attribute::ByRef);
676
677 // The type of the value being passed, decoded from byval/byref metadata if
678 // required
679 Type *const UnderlyingType = IsByVal ? CB->getParamByValType(I)
680 : IsByRef ? CB->getParamByRefType(I)
681 : ArgVal->getType();
682 const uint64_t UnderlyingSize =
683 DL.getTypeAllocSize(UnderlyingType).getFixedValue();
684
685 // The type to be written into the call frame
686 Type *FrameFieldType = UnderlyingType;
687
688 // The value to copy from when initialising the frame alloca
689 Value *SourceValue = ArgVal;
690
691 VariadicABIInfo::VAArgSlotInfo SlotInfo = ABI->slotInfo(DL, UnderlyingType);
692
693 if (SlotInfo.Indirect) {
694 // The va_arg lowering loads through a pointer. Set up an alloca to aim
695 // that pointer at.
696 Builder.SetInsertPointPastAllocas(CBF);
697 Builder.SetCurrentDebugLocation(CB->getStableDebugLoc());
698 Value *CallerCopy =
699 Builder.CreateAlloca(UnderlyingType, nullptr, "IndirectAlloca");
700
701 Builder.SetInsertPoint(CB);
702 if (IsByVal)
703 Builder.CreateMemCpy(CallerCopy, {}, ArgVal, {}, UnderlyingSize);
704 else
705 Builder.CreateStore(ArgVal, CallerCopy);
706
707 // Indirection now handled, pass the alloca ptr by value
708 FrameFieldType = DL.getAllocaPtrType(Ctx);
709 SourceValue = CallerCopy;
710 }
711
712 // Alignment of the value within the frame
713 // This probably needs to be controllable as a function of type
714 Align DataAlign = SlotInfo.DataAlign;
715
716 MaxFieldAlign = std::max(MaxFieldAlign, DataAlign);
717
718 uint64_t DataAlignV = DataAlign.value();
719 if (uint64_t Rem = CurrentOffset % DataAlignV) {
720 // Inject explicit padding to deal with alignment requirements
721 uint64_t Padding = DataAlignV - Rem;
722 Frame.padding(Ctx, Padding);
723 CurrentOffset += Padding;
724 }
725
726 if (SlotInfo.Indirect) {
727 Frame.store(Ctx, FrameFieldType, SourceValue);
728 } else {
729 if (IsByVal)
730 Frame.memcpy(Ctx, FrameFieldType, SourceValue, UnderlyingSize);
731 else
732 Frame.store(Ctx, FrameFieldType, SourceValue);
733 }
734
735 CurrentOffset += DL.getTypeAllocSize(FrameFieldType).getFixedValue();
736 }
737
738 if (Frame.empty()) {
739 // Not passing any arguments, hopefully va_arg won't try to read any
740 // Creating a single byte frame containing nothing to point the va_list
741 // instance as that is less special-casey in the compiler and probably
742 // easier to interpret in a debugger.
743 Frame.padding(Ctx, 1);
744 }
745
746 StructType *VarargsTy = Frame.asStruct(Ctx, CBF->getName());
747
748 // The struct instance needs to be at least MaxFieldAlign for the alignment of
749 // the fields to be correct at runtime. Use the native stack alignment instead
750 // if that's greater as that tends to give better codegen.
751 // This is an awkward way to guess whether there is a known stack alignment
752 // without hitting an assert in DL.getStackAlignment, 1024 is an arbitrary
753 // number likely to be greater than the natural stack alignment.
754 Align AllocaAlign = MaxFieldAlign;
755 if (MaybeAlign StackAlign = DL.getStackAlignment();
756 StackAlign && *StackAlign > AllocaAlign)
757 AllocaAlign = *StackAlign;
758
759 // Put the alloca to hold the variadic args in the entry basic block.
760 Builder.SetInsertPointPastAllocas(CBF);
761
762 // SetCurrentDebugLocation when the builder SetInsertPoint method does not
763 Builder.SetCurrentDebugLocation(CB->getStableDebugLoc());
764
765 // The awkward construction here is to set the alignment on the instance
766 AllocaInst *Alloced = Builder.Insert(
767 new AllocaInst(VarargsTy, DL.getAllocaAddrSpace(), nullptr, AllocaAlign),
768 "vararg_buffer");
769 Changed = true;
770 assert(Alloced->getAllocatedType() == VarargsTy);
771
772 // Initialize the fields in the struct
773 Builder.SetInsertPoint(CB);
774 Builder.CreateLifetimeStart(Alloced);
775 Frame.initializeStructAlloca(DL, Builder, Alloced, VarargsTy);
776
777 const unsigned NumArgs = FuncType->getNumParams();
778 SmallVector<Value *> Args(CB->arg_begin(), CB->arg_begin() + NumArgs);
779
780 // Initialize a va_list pointing to that struct and pass it as the last
781 // argument
782 AllocaInst *VaList = nullptr;
783 {
784 if (!ABI->vaListPassedInSSARegister()) {
785 Type *VaListTy = ABI->vaListType(Ctx);
786 Builder.SetInsertPointPastAllocas(CBF);
787 Builder.SetCurrentDebugLocation(CB->getStableDebugLoc());
788 VaList = Builder.CreateAlloca(VaListTy, nullptr, "va_argument");
789 Builder.SetInsertPoint(CB);
790 Builder.CreateLifetimeStart(VaList);
791 }
792 Builder.SetInsertPoint(CB);
793 Args.push_back(ABI->initializeVaList(M, Ctx, Builder, VaList, Alloced));
794 }
795
796 // Attributes excluding any on the vararg arguments
797 AttributeList PAL = CB->getAttributes();
798 if (!PAL.isEmpty()) {
800 for (unsigned ArgNo = 0; ArgNo < NumArgs; ArgNo++)
801 ArgAttrs.push_back(PAL.getParamAttrs(ArgNo));
802 PAL =
803 AttributeList::get(Ctx, PAL.getFnAttrs(), PAL.getRetAttrs(), ArgAttrs);
804 }
805
807 CB->getOperandBundlesAsDefs(OpBundles);
808
809 CallBase *NewCB = nullptr;
810
811 if (CallInst *CI = dyn_cast<CallInst>(CB)) {
812 Value *Dst = NF ? NF : CI->getCalledOperand();
813 FunctionType *NFTy = inlinableVariadicFunctionType(M, VarargFunctionType);
814
815 NewCB = CallInst::Create(NFTy, Dst, Args, OpBundles, "", CI->getIterator());
816
817 CallInst::TailCallKind TCK = CI->getTailCallKind();
819
820 // Can't tail call a function that is being passed a pointer to an alloca
821 if (TCK == CallInst::TCK_Tail)
822 TCK = CallInst::TCK_None;
823 CI->setTailCallKind(TCK);
824
825 } else {
826 llvm_unreachable("Unreachable when !expansionApplicableToFunctionCall()");
827 }
828
829 if (VaList)
830 Builder.CreateLifetimeEnd(VaList);
831
832 Builder.CreateLifetimeEnd(Alloced);
833
834 NewCB->setAttributes(PAL);
835 NewCB->takeName(CB);
836 NewCB->setCallingConv(CB->getCallingConv());
837 NewCB->setDebugLoc(DebugLoc());
838
839 // DeadArgElim and ArgPromotion copy exactly this metadata
840 NewCB->copyMetadata(*CB, {LLVMContext::MD_prof, LLVMContext::MD_dbg});
841
842 CB->replaceAllUsesWith(NewCB);
843 CB->eraseFromParent();
844 return Changed;
845}
846
847bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &Builder,
848 const DataLayout &DL,
849 VAStartInst *Inst) {
850 // Only removing va_start instructions that are not in variadic functions.
851 // Those would be rejected by the IR verifier before this pass.
852 // After splicing basic blocks from a variadic function into a fixed arity
853 // one the va_start that used to refer to the ... parameter still exist.
854 // There are also variadic functions that this pass did not change and
855 // va_start instances in the created single block wrapper functions.
856 // Replace exactly the instances in non-variadic functions as those are
857 // the ones to be fixed up to use the va_list passed as the final argument.
858
859 Function *ContainingFunction = Inst->getFunction();
860 if (ContainingFunction->isVarArg()) {
861 return false;
862 }
863
864 // The last argument is a vaListParameterType, either a va_list
865 // or a pointer to one depending on the target.
866 bool PassedByValue = ABI->vaListPassedInSSARegister();
867 Argument *PassedVaList =
868 ContainingFunction->getArg(ContainingFunction->arg_size() - 1);
869
870 // va_start takes a pointer to a va_list, e.g. one on the stack
871 Value *VaStartArg = Inst->getArgList();
872
873 Builder.SetInsertPoint(Inst);
874
875 if (PassedByValue) {
876 // The general thing to do is create an alloca, store the va_list argument
877 // to it, then create a va_copy. When vaCopyIsMemcpy(), this optimises to a
878 // store to the VaStartArg.
879 assert(ABI->vaCopyIsMemcpy());
880 Builder.CreateStore(PassedVaList, VaStartArg);
881 } else {
882
883 // Otherwise emit a vacopy to pick up target-specific handling if any
884 auto &Ctx = Builder.getContext();
885
886 Builder.CreateIntrinsic(Intrinsic::vacopy, {DL.getAllocaPtrType(Ctx)},
887 {VaStartArg, PassedVaList});
888 }
889
890 Inst->eraseFromParent();
891 return true;
892}
893
894bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &, const DataLayout &,
895 VAEndInst *Inst) {
896 assert(ABI->vaEndIsNop());
897 Inst->eraseFromParent();
898 return true;
899}
900
901bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &Builder,
902 const DataLayout &DL,
903 VACopyInst *Inst) {
904 assert(ABI->vaCopyIsMemcpy());
905 Builder.SetInsertPoint(Inst);
906
907 auto &Ctx = Builder.getContext();
908 Type *VaListTy = ABI->vaListType(Ctx);
909 uint64_t Size = DL.getTypeAllocSize(VaListTy).getFixedValue();
910
911 Builder.CreateMemCpy(Inst->getDest(), {}, Inst->getSrc(), {},
912 Builder.getInt32(Size));
913
914 Inst->eraseFromParent();
915 return true;
916}
917
918struct Amdgpu final : public VariadicABIInfo {
919
920 bool enableForTarget() override { return true; }
921
922 bool vaListPassedInSSARegister() override { return true; }
923
924 Type *vaListType(LLVMContext &Ctx) override {
925 return PointerType::getUnqual(Ctx);
926 }
927
928 Type *vaListParameterType(Module &M) override {
929 return PointerType::getUnqual(M.getContext());
930 }
931
932 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
933 AllocaInst * /*va_list*/, Value *Buffer) override {
934 // Given Buffer, which is an AllocInst of vararg_buffer
935 // need to return something usable as parameter type
936 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
937 }
938
939 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
940 return {Align(4), false};
941 }
942};
943
944struct NVPTX final : public VariadicABIInfo {
945
946 bool enableForTarget() override { return true; }
947
948 bool vaListPassedInSSARegister() override { return true; }
949
950 Type *vaListType(LLVMContext &Ctx) override {
952 }
953
954 Type *vaListParameterType(Module &M) override {
955 return PointerType::get(M.getContext(), NVPTXAS::ADDRESS_SPACE_LOCAL);
956 }
957
958 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
959 AllocaInst *, Value *Buffer) override {
960 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
961 }
962
963 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
964 // NVPTX expects natural alignment in all cases. The variadic call ABI will
965 // handle promoting types to their appropriate size and alignment.
966 Align A = DL.getABITypeAlign(Parameter);
967 return {A, false};
968 }
969};
970
971struct SPIRV final : public VariadicABIInfo {
972
973 bool enableForTarget() override { return true; }
974
975 bool vaListPassedInSSARegister() override { return true; }
976
977 Type *vaListType(LLVMContext &Ctx) override {
978 return PointerType::getUnqual(Ctx);
979 }
980
981 Type *vaListParameterType(Module &M) override {
982 return PointerType::getUnqual(M.getContext());
983 }
984
985 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
986 AllocaInst *, Value *Buffer) override {
987 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
988 }
989
990 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
991 // Expects natural alignment in all cases. The variadic call ABI will handle
992 // promoting types to their appropriate size and alignment.
993 Align A = DL.getABITypeAlign(Parameter);
994 return {A, false};
995 }
996
997 // The SPIR-V backend has special handling for builtins.
998 bool ignoreFunction(const Function *F) override {
999 if (!F->isDeclaration())
1000 return false;
1001
1002 std::string Demangled = llvm::demangle(F->getName());
1003 StringRef DemangledName(Demangled);
1004
1005 // Skip any SPIR-V builtins.
1006 if (DemangledName.starts_with("__spirv_") ||
1007 DemangledName.starts_with("printf("))
1008 return true;
1009
1010 return false;
1011 }
1012
1013 // We will likely see va intrinsics in the generic addrspace (4).
1014 SmallVector<unsigned> getTargetSpecificVaIntrinAddrSpaces() const override {
1015 return {4};
1016 }
1017};
1018
1019struct Wasm final : public VariadicABIInfo {
1020
1021 bool enableForTarget() override {
1022 // Currently wasm is only used for testing.
1023 return commandLineOverride();
1024 }
1025
1026 bool vaListPassedInSSARegister() override { return true; }
1027
1028 Type *vaListType(LLVMContext &Ctx) override {
1029 return PointerType::getUnqual(Ctx);
1030 }
1031
1032 Type *vaListParameterType(Module &M) override {
1033 return PointerType::getUnqual(M.getContext());
1034 }
1035
1036 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
1037 AllocaInst * /*va_list*/, Value *Buffer) override {
1038 return Buffer;
1039 }
1040
1041 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
1042 LLVMContext &Ctx = Parameter->getContext();
1043 const unsigned MinAlign = 4;
1044 Align A = DL.getABITypeAlign(Parameter);
1045 if (A < MinAlign)
1046 A = Align(MinAlign);
1047
1048 if (auto *S = dyn_cast<StructType>(Parameter)) {
1049 if (S->getNumElements() > 1) {
1050 return {DL.getABITypeAlign(PointerType::getUnqual(Ctx)), true};
1051 }
1052 }
1053
1054 return {A, false};
1055 }
1056};
1057
1058std::unique_ptr<VariadicABIInfo> VariadicABIInfo::create(const Triple &T) {
1059 switch (T.getArch()) {
1060 case Triple::r600:
1061 case Triple::amdgcn: {
1062 return std::make_unique<Amdgpu>();
1063 }
1064
1065 case Triple::wasm32: {
1066 return std::make_unique<Wasm>();
1067 }
1068
1069 case Triple::nvptx:
1070 case Triple::nvptx64: {
1071 return std::make_unique<NVPTX>();
1072 }
1073
1074 case Triple::spirv:
1075 case Triple::spirv32:
1076 case Triple::spirv64: {
1077 return std::make_unique<SPIRV>();
1078 }
1079
1080 default:
1081 return {};
1082 }
1083}
1084
1085} // namespace
1086
1087char ExpandVariadics::ID = 0;
1088
1089INITIALIZE_PASS(ExpandVariadics, DEBUG_TYPE, "Expand variadic functions", false,
1090 false)
1091
1093 return new ExpandVariadics(M);
1094}
1095
1097 return ExpandVariadics(Mode).runOnModule(M) ? PreservedAnalyses::none()
1099}
1100
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
NVPTX address space definition.
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
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")))
This file defines the SmallVector class.
an instruction to allocate memory on the stack
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
Type * getParamByRefType(unsigned ArgNo) const
Extract the byref type for a call or parameter.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
CallingConv::ID getCallingConv() const
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
Type * getParamByValType(unsigned ArgNo) const
Extract the byval type for a call or parameter.
void setAttributes(AttributeList A)
Set the attributes for this call.
Value * getArgOperand(unsigned i) const
FunctionType * getFunctionType() const
unsigned arg_size() const
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
ExpandVariadicsPass(ExpandVariadicsMode Mode)
static LLVM_ABI FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:168
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Definition Function.h:761
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:211
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:354
iterator begin()
Definition Function.h:853
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Function.cpp:449
arg_iterator arg_begin()
Definition Function.h:868
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:357
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:358
size_t arg_size() const
Definition Function.h:901
Argument * getArg(unsigned i) const
Definition Function.h:886
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:229
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:843
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:223
const Comdat * getComdat() const
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
VisibilityTypes getVisibility() const
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition Globals.cpp:337
LinkageTypes getLinkage() const
void setLinkage(LinkageTypes LT)
@ DefaultVisibility
The GV is visible.
Definition GlobalValue.h:68
void setVisibility(VisibilityTypes V)
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2858
LLVM_ABI const DebugLoc & getStableDebugLoc() const
Fetch the debug location for this node, unless this is a debug intrinsic, in which case fetch the deb...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:255
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
static LLVM_ABI PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
Class to represent struct types.
static LLVM_ABI StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition Type.cpp:689
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:311
This represents the llvm.va_copy intrinsic.
Value * getSrc() const
Value * getDest() const
This represents the llvm.va_end intrinsic.
This represents the llvm.va_start intrinsic.
Value * getArgList() const
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:393
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:549
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
bool use_empty() const
Definition Value.h:346
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:318
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:399
const ParentTy * getParent() const
Definition ilist_node.h:34
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ SPIR_FUNC
Used for SPIR non-kernel device functions.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
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:1668
ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
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< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:633
ExpandVariadicsMode
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:357
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
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
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
DEMANGLE_ABI std::string demangle(std::string_view MangledName)
Attempt to demangle a string using different demangling schemes.
Definition Demangle.cpp:21
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106