LLVM 24.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
55#include "IPOOptions.h"
56#include "llvm/ADT/Sequence.h"
59#include "llvm/IR/IRBuilder.h"
61#include "llvm/IR/Module.h"
62#include "llvm/IR/PassManager.h"
64#include "llvm/Pass.h"
68
69#define DEBUG_TYPE "expand-variadics"
70
71using namespace llvm;
72
73namespace {
74
75// Instances of this class encapsulate the target-dependant behaviour as a
76// function of triple. Implementing a new ABI is adding a case to the switch
77// in create(llvm::Triple) at the end of this file.
78// This class may end up instantiated in TargetMachine instances, keeping it
79// here for now until enough targets are implemented for the API to evolve.
80class VariadicABIInfo {
81protected:
82 VariadicABIInfo() = default;
83
84public:
85 static std::unique_ptr<VariadicABIInfo> create(const Triple &T);
86
87 // Allow overriding whether the pass runs on a per-target basis
88 virtual bool enableForTarget() = 0;
89
90 // Whether a valist instance is passed by value or by address
91 // I.e. does it need to be alloca'ed and stored into, or can
92 // it be passed directly in a SSA register
93 virtual bool vaListPassedInSSARegister() = 0;
94
95 // The type of a va_list iterator object
96 virtual Type *vaListType(LLVMContext &Ctx) = 0;
97
98 // The type of a va_list as a function argument as lowered by C
99 virtual Type *vaListParameterType(Module &M) = 0;
100
101 // Initialize an allocated va_list object to point to an already
102 // initialized contiguous memory region.
103 // Return the value to pass as the va_list argument
104 virtual Value *initializeVaList(Module &M, LLVMContext &Ctx,
105 IRBuilder<> &Builder, AllocaInst *VaList,
106 Value *Buffer) = 0;
107
108 struct VAArgSlotInfo {
109 Align DataAlign; // With respect to the call frame
110 bool Indirect; // Passed via a pointer
111 };
112 virtual VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) = 0;
113
114 // Targets implemented so far all have the same trivial lowering for these
115 bool vaEndIsNop() { return true; }
116 bool vaCopyIsMemcpy() { return true; }
117
118 // Per-target overrides of special symbols.
119 virtual bool ignoreFunction(const Function *F) { return false; }
120
121 // Any additional address spaces used in va intrinsics that should be
122 // expanded.
123 virtual SmallVector<unsigned> getTargetSpecificVaIntrinAddrSpaces() const {
124 return {};
125 }
126
127 virtual ~VariadicABIInfo() = default;
128};
129
130class ExpandVariadics : public ModulePass {
131
132 // The pass construction sets the default to optimize when called from middle
133 // end and lowering when called from the backend. The command line variable
134 // overrides that. This is useful for testing and debugging. It also allows
135 // building an applications with variadic functions wholly removed if one
136 // has sufficient control over the dependencies, e.g. a statically linked
137 // clang that has no variadic function calls remaining in the binary.
138
139public:
140 static char ID;
142 std::unique_ptr<VariadicABIInfo> ABI;
143 FunctionAnalysisManager *FAM = nullptr;
144
145 ExpandVariadics(ExpandVariadicsMode Mode) : ModulePass(ID), Mode(Mode) {}
146
147 void eraseFunction(Function *F) {
148 if (FAM)
149 FAM->clear(*F, F->getName());
150 F->eraseFromParent();
151 }
152
153 StringRef getPassName() const override { return "Expand variadic functions"; }
154
155 bool rewriteABI() { return Mode == ExpandVariadicsMode::Lowering; }
156
157 template <typename T> bool isValidCallingConv(T *F) {
158 return F->getCallingConv() == CallingConv::C ||
159 F->getCallingConv() == CallingConv::SPIR_FUNC;
160 }
161
162 bool runOnModule(Module &M) override;
163
164 bool runOnFunction(Module &M, IRBuilder<> &Builder, Function *F);
165
166 Function *replaceAllUsesWithNewDeclaration(Module &M,
167 Function *OriginalFunction);
168
169 Function *deriveFixedArityReplacement(Module &M, IRBuilder<> &Builder,
170 Function *OriginalFunction);
171
172 Function *defineVariadicWrapper(Module &M, IRBuilder<> &Builder,
173 Function *VariadicWrapper,
174 Function *FixedArityReplacement);
175
176 bool expandCall(Module &M, IRBuilder<> &Builder, CallBase *CB, FunctionType *,
177 Function *NF);
178
179 // The intrinsic functions va_copy and va_end are removed unconditionally.
180 // They correspond to a memcpy and a no-op on all implemented targets.
181 // The va_start intrinsic is removed from basic blocks that were not created
182 // by this pass, some may remain if needed to maintain the external ABI.
183
184 template <Intrinsic::ID ID, typename InstructionType>
185 bool expandIntrinsicUsers(Module &M, IRBuilder<> &Builder,
186 PointerType *IntrinsicArgType) {
187 bool Changed = false;
188 const DataLayout &DL = M.getDataLayout();
189 if (Function *Intrinsic =
190 Intrinsic::getDeclarationIfExists(&M, ID, {IntrinsicArgType})) {
191 for (User *U : make_early_inc_range(Intrinsic->users()))
192 if (auto *I = dyn_cast<InstructionType>(U))
193 Changed |= expandVAIntrinsicCall(Builder, DL, I);
194
195 if (Intrinsic->use_empty())
196 eraseFunction(Intrinsic);
197 }
198 return Changed;
199 }
200
201 bool expandVAIntrinsicUsersWithAddrspace(Module &M, IRBuilder<> &Builder,
202 unsigned Addrspace) {
203 auto &Ctx = M.getContext();
204 PointerType *IntrinsicArgType = PointerType::get(Ctx, Addrspace);
205 bool Changed = false;
206
207 // expand vastart before vacopy as vastart may introduce a vacopy
208 Changed |= expandIntrinsicUsers<Intrinsic::vastart, VAStartInst>(
209 M, Builder, IntrinsicArgType);
210 Changed |= expandIntrinsicUsers<Intrinsic::vaend, VAEndInst>(
211 M, Builder, IntrinsicArgType);
212 Changed |= expandIntrinsicUsers<Intrinsic::vacopy, VACopyInst>(
213 M, Builder, IntrinsicArgType);
214 return Changed;
215 }
216
217 bool expandVAIntrinsicCall(IRBuilder<> &Builder, const DataLayout &DL,
218 VAStartInst *Inst);
219
220 bool expandVAIntrinsicCall(IRBuilder<> &, const DataLayout &,
221 VAEndInst *Inst);
222
223 bool expandVAIntrinsicCall(IRBuilder<> &Builder, const DataLayout &DL,
224 VACopyInst *Inst);
225
226 bool expandVAArgInst(IRBuilder<> &Builder, const DataLayout &DL,
227 VAArgInst *Inst);
228
229 FunctionType *inlinableVariadicFunctionType(Module &M, FunctionType *FTy,
230 Type *ReturnType) {
231 // The type of "FTy" with the ... removed and a va_list appended
232 SmallVector<Type *> ArgTypes(FTy->params());
233 ArgTypes.push_back(ABI->vaListParameterType(M));
234 return FunctionType::get(ReturnType, ArgTypes, /*IsVarArgs=*/false);
235 }
236
237 FunctionType *inlinableVariadicFunctionType(Module &M, FunctionType *FTy) {
238 return inlinableVariadicFunctionType(M, FTy, FTy->getReturnType());
239 }
240
241 bool expansionApplicableToFunction(Module &M, Function *F) {
242 if (F->isIntrinsic() || !F->isVarArg() ||
243 F->hasFnAttribute(Attribute::Naked))
244 return false;
245
246 if (ABI->ignoreFunction(F))
247 return false;
248
249 if (!isValidCallingConv(F))
250 return false;
251
252 if (rewriteABI())
253 return true;
254
255 if (!F->hasExactDefinition())
256 return false;
257
258 return true;
259 }
260
261 bool expansionApplicableToFunctionCall(CallBase *CB) {
262 if (CallInst *CI = dyn_cast<CallInst>(CB)) {
263 if (CI->isMustTailCall()) {
264 // Cannot expand musttail calls
265 return false;
266 }
267
268 if (!isValidCallingConv(CI))
269 return false;
270
271 return true;
272 }
273
274 if (isa<InvokeInst>(CB)) {
275 // Invoke not implemented in initial implementation of pass
276 return false;
277 }
278
279 // Other unimplemented derivative of CallBase
280 return false;
281 }
282
283 class ExpandedCallFrame {
284 // Helper for constructing an alloca instance containing the arguments bound
285 // to the variadic ... parameter, rearranged to allow indexing through a
286 // va_list iterator
287 enum { N = 4 };
288 SmallVector<Type *, N> FieldTypes;
289 enum Tag { Store, Memcpy, Padding };
291
292 template <Tag tag> void append(Type *FieldType, Value *V, uint64_t Bytes) {
293 FieldTypes.push_back(FieldType);
294 Source.push_back({V, Bytes, tag});
295 }
296
297 public:
298 void store(LLVMContext &Ctx, Type *T, Value *V) { append<Store>(T, V, 0); }
299
300 void memcpy(LLVMContext &Ctx, Type *T, Value *V, uint64_t Bytes) {
301 append<Memcpy>(T, V, Bytes);
302 }
303
304 void padding(LLVMContext &Ctx, uint64_t By) {
305 append<Padding>(ArrayType::get(Type::getInt8Ty(Ctx), By), nullptr, 0);
306 }
307
308 size_t size() const { return FieldTypes.size(); }
309 bool empty() const { return FieldTypes.empty(); }
310
311 StructType *asStruct(LLVMContext &Ctx, StringRef Name) {
312 const bool IsPacked = true;
313 return StructType::create(Ctx, FieldTypes,
314 (Twine(Name) + ".vararg").str(), IsPacked);
315 }
316
317 void initializeStructAlloca(const DataLayout &DL, IRBuilder<> &Builder,
318 AllocaInst *Alloced, StructType *VarargsTy) {
319
320 for (size_t I = 0; I < size(); I++) {
321
322 auto [V, bytes, tag] = Source[I];
323
324 if (tag == Padding) {
325 assert(V == nullptr);
326 continue;
327 }
328
329 auto Dst = Builder.CreateStructGEP(VarargsTy, Alloced, I);
330
331 assert(V != nullptr);
332
333 if (tag == Store)
334 Builder.CreateStore(V, Dst);
335
336 if (tag == Memcpy)
337 Builder.CreateMemCpy(Dst, {}, V, {}, bytes);
338 }
339 }
340 };
341};
342
343bool ExpandVariadics::runOnModule(Module &M) {
344 ExpandVariadicsMode Override = getIPOOptions(M).expand_variadics_override;
345 bool HasOverride = Override != ExpandVariadicsMode::Unspecified;
346 if (HasOverride)
347 Mode = Override;
348
349 bool Changed = false;
351 return Changed;
352
353 Triple TT(M.getTargetTriple());
354 ABI = VariadicABIInfo::create(TT);
355 if (!ABI)
356 return Changed;
357
358 if (!HasOverride && !ABI->enableForTarget())
359 return Changed;
360
361 const DataLayout &DL = M.getDataLayout();
362 IRBuilder<> Builder(M);
363 Builder.disableGEPCanonicalization();
364
365 // Lowering needs to run on all functions exactly once.
366 // Optimize could run on functions containing va_start exactly once.
368 Changed |= runOnFunction(M, Builder, &F);
369
370 // After runOnFunction, all known calls to known variadic functions have been
371 // replaced. va_start intrinsics are presently (and invalidly!) only present
372 // in functions that used to be variadic and have now been replaced to take a
373 // va_list instead. If lowering as opposed to optimising, calls to unknown
374 // variadic functions have also been replaced.
375
376 {
377 unsigned Addrspace = 0;
378 Changed |= expandVAIntrinsicUsersWithAddrspace(M, Builder, Addrspace);
379
380 Addrspace = DL.getAllocaAddrSpace();
381 if (Addrspace != 0)
382 Changed |= expandVAIntrinsicUsersWithAddrspace(M, Builder, Addrspace);
383
384 // Process any addrspaces targets declare to be important.
385 const SmallVector<unsigned> &TargetASVec =
386 ABI->getTargetSpecificVaIntrinAddrSpaces();
387 for (unsigned TargetAS : TargetASVec) {
388 if (TargetAS == 0 || TargetAS == DL.getAllocaAddrSpace())
389 continue;
390 Changed |= expandVAIntrinsicUsersWithAddrspace(M, Builder, TargetAS);
391 }
392 }
393
395 return Changed;
396
397 for (Function &F : make_early_inc_range(M)) {
398 if (F.isDeclaration())
399 continue;
400
401 // Now need to track down indirect calls and va_arg instructions. Can't find
402 // those by walking uses of variadic functions, need to crawl the
403 // instruction stream. Fortunately this is only necessary for the ABI
404 // rewrite case.
405 for (BasicBlock &BB : F) {
406 for (Instruction &I : make_early_inc_range(BB)) {
407 if (auto *VA = dyn_cast<VAArgInst>(&I)) {
408 Changed |= expandVAArgInst(Builder, DL, VA);
409 } else if (CallBase *CB = dyn_cast<CallBase>(&I)) {
410 if (CB->isIndirectCall()) {
411 FunctionType *FTy = CB->getFunctionType();
412 if (FTy->isVarArg())
413 Changed |= expandCall(M, Builder, CB, FTy, /*NF=*/nullptr);
414 }
415 }
416 }
417 }
418 }
419
420 return Changed;
421}
422
423bool ExpandVariadics::runOnFunction(Module &M, IRBuilder<> &Builder,
424 Function *OriginalFunction) {
425 if (!expansionApplicableToFunction(M, OriginalFunction))
426 return false;
427
428 [[maybe_unused]] const bool OriginalFunctionIsDeclaration =
429 OriginalFunction->isDeclaration();
430 assert(rewriteABI() || !OriginalFunctionIsDeclaration);
431
432 // Declare a new function and redirect every use to that new function
433 Function *VariadicWrapper =
434 replaceAllUsesWithNewDeclaration(M, OriginalFunction);
435 assert(VariadicWrapper->isDeclaration());
436 assert(OriginalFunction->use_empty());
437
438 // Create a new function taking va_list containing the implementation of the
439 // original
440 Function *FixedArityReplacement =
441 deriveFixedArityReplacement(M, Builder, OriginalFunction);
442 assert(OriginalFunction->isDeclaration());
443 assert(FixedArityReplacement->isDeclaration() ==
444 OriginalFunctionIsDeclaration);
445 assert(VariadicWrapper->isDeclaration());
446
447 // Create a single block forwarding wrapper that turns a ... into a va_list
448 [[maybe_unused]] Function *VariadicWrapperDefine =
449 defineVariadicWrapper(M, Builder, VariadicWrapper, FixedArityReplacement);
450 assert(VariadicWrapperDefine == VariadicWrapper);
451 assert(!VariadicWrapper->isDeclaration());
452
453 // Add the prof metadata from the original function to the wrapper. Because
454 // FixedArityReplacement is the owner of original function's prof metadata
455 // after the splice, we need to transfer it to VariadicWrapper.
456 VariadicWrapper->setMetadata(
457 LLVMContext::MD_prof,
458 FixedArityReplacement->getMetadata(LLVMContext::MD_prof));
459
460 // We now have:
461 // 1. the original function, now as a declaration with no uses
462 // 2. a variadic function that unconditionally calls a fixed arity replacement
463 // 3. a fixed arity function equivalent to the original function
464
465 // Replace known calls to the variadic with calls to the va_list equivalent
466 for (User *U : make_early_inc_range(VariadicWrapper->users())) {
467 if (CallBase *CB = dyn_cast<CallBase>(U)) {
468 Value *CalledOperand = CB->getCalledOperand();
469 if (VariadicWrapper == CalledOperand)
470 expandCall(M, Builder, CB, VariadicWrapper->getFunctionType(),
471 FixedArityReplacement);
472 }
473 }
474
475 // The original function will be erased.
476 // One of the two new functions will become a replacement for the original.
477 // When preserving the ABI, the other is an internal implementation detail.
478 // When rewriting the ABI, RAUW then the variadic one.
479 Function *const ExternallyAccessible =
480 rewriteABI() ? FixedArityReplacement : VariadicWrapper;
481 Function *const InternalOnly =
482 rewriteABI() ? VariadicWrapper : FixedArityReplacement;
483
484 // The external function is the replacement for the original
485 ExternallyAccessible->setLinkage(OriginalFunction->getLinkage());
486 ExternallyAccessible->setVisibility(OriginalFunction->getVisibility());
487 ExternallyAccessible->setComdat(OriginalFunction->getComdat());
488 ExternallyAccessible->takeName(OriginalFunction);
489
490 // Annotate the internal one as internal
493
494 // The original is unused and obsolete
495 eraseFunction(OriginalFunction);
496
497 InternalOnly->removeDeadConstantUsers();
498
499 if (rewriteABI()) {
500 // All known calls to the function have been removed by expandCall
501 // Resolve everything else by replaceAllUsesWith
502 VariadicWrapper->replaceAllUsesWith(FixedArityReplacement);
503 eraseFunction(VariadicWrapper);
504 }
505
506 return true;
507}
508
509Function *
510ExpandVariadics::replaceAllUsesWithNewDeclaration(Module &M,
511 Function *OriginalFunction) {
512 auto &Ctx = M.getContext();
513 Function &F = *OriginalFunction;
514 FunctionType *FTy = F.getFunctionType();
515 Function *NF = Function::Create(FTy, F.getLinkage(), F.getAddressSpace());
516
517 NF->setName(F.getName() + ".varargs");
518
519 F.getParent()->getFunctionList().insert(F.getIterator(), NF);
520
521 AttrBuilder ParamAttrs(Ctx);
522 AttributeList Attrs = NF->getAttributes();
523 Attrs = Attrs.addParamAttributes(Ctx, FTy->getNumParams(), ParamAttrs);
524 NF->setAttributes(Attrs);
525
526 OriginalFunction->replaceAllUsesWith(NF);
527 return NF;
528}
529
530Function *
531ExpandVariadics::deriveFixedArityReplacement(Module &M, IRBuilder<> &Builder,
532 Function *OriginalFunction) {
533 Function &F = *OriginalFunction;
534 // The purpose here is split the variadic function F into two functions
535 // One is a variadic function that bundles the passed argument into a va_list
536 // and passes it to the second function. The second function does whatever
537 // the original F does, except that it takes a va_list instead of the ...
538
539 assert(expansionApplicableToFunction(M, &F));
540
541 auto &Ctx = M.getContext();
542
543 // Returned value isDeclaration() is equal to F.isDeclaration()
544 // but that property is not invariant throughout this function
545 const bool FunctionIsDefinition = !F.isDeclaration();
546
547 FunctionType *FTy = F.getFunctionType();
548 SmallVector<Type *> ArgTypes(FTy->params());
549 ArgTypes.push_back(ABI->vaListParameterType(M));
550
551 FunctionType *NFTy = inlinableVariadicFunctionType(M, FTy);
552 Function *NF = Function::Create(NFTy, F.getLinkage(), F.getAddressSpace());
553
554 // Note - same attribute handling as DeadArgumentElimination
555 NF->copyAttributesFrom(&F);
556 NF->setComdat(F.getComdat());
557 F.getParent()->getFunctionList().insert(F.getIterator(), NF);
558 NF->setName(F.getName() + ".valist");
559
560 AttrBuilder ParamAttrs(Ctx);
561
562 AttributeList Attrs = NF->getAttributes();
563 Attrs = Attrs.addParamAttributes(Ctx, NFTy->getNumParams() - 1, ParamAttrs);
564 NF->setAttributes(Attrs);
565
566 // Splice the implementation into the new function with minimal changes
567 if (FunctionIsDefinition) {
568 NF->splice(NF->begin(), &F);
569
570 auto NewArg = NF->arg_begin();
571 for (Argument &Arg : F.args()) {
572 Arg.replaceAllUsesWith(NewArg);
573 NewArg->setName(Arg.getName()); // takeName without killing the old one
574 ++NewArg;
575 }
576 NewArg->setName("varargs");
577 }
578
580 F.getAllMetadata(MDs);
581 for (auto [KindID, Node] : MDs)
582 NF->addMetadata(KindID, *Node);
583 F.clearMetadata();
584
585 return NF;
586}
587
588Function *
589ExpandVariadics::defineVariadicWrapper(Module &M, IRBuilder<> &Builder,
590 Function *VariadicWrapper,
591 Function *FixedArityReplacement) {
592 auto &Ctx = Builder.getContext();
593 const DataLayout &DL = M.getDataLayout();
594 assert(VariadicWrapper->isDeclaration());
595 Function &F = *VariadicWrapper;
596
597 assert(F.isDeclaration());
598 Type *VaListTy = ABI->vaListType(Ctx);
599
600 auto *BB = BasicBlock::Create(Ctx, "entry", &F);
601 Builder.SetInsertPoint(BB);
602
603 AllocaInst *VaListInstance =
604 Builder.CreateAlloca(VaListTy, nullptr, "va_start");
605
606 Builder.CreateLifetimeStart(VaListInstance);
607
608 Builder.CreateIntrinsic(Intrinsic::vastart, {DL.getAllocaPtrType(Ctx)},
609 {VaListInstance});
610
612
613 Value *VaListValue = VaListInstance;
614 if (ABI->vaListPassedInSSARegister())
615 VaListValue = Builder.CreateLoad(VaListTy, VaListInstance);
616
617 Type *ParameterType = ABI->vaListParameterType(M);
618 Args.push_back(Builder.CreateAddrSpaceCast(VaListValue, ParameterType));
619
620 CallInst *Result = Builder.CreateCall(FixedArityReplacement, Args);
621
622 Builder.CreateIntrinsic(Intrinsic::vaend, {DL.getAllocaPtrType(Ctx)},
623 {VaListInstance});
624 Builder.CreateLifetimeEnd(VaListInstance);
625
626 if (Result->getType()->isVoidTy())
627 Builder.CreateRetVoid();
628 else
629 Builder.CreateRet(Result);
630
631 return VariadicWrapper;
632}
633
634bool ExpandVariadics::expandCall(Module &M, IRBuilder<> &Builder, CallBase *CB,
635 FunctionType *VarargFunctionType,
636 Function *NF) {
637 bool Changed = false;
638 const DataLayout &DL = M.getDataLayout();
639
640 if (ABI->ignoreFunction(CB->getCalledFunction()))
641 return Changed;
642
643 if (!expansionApplicableToFunctionCall(CB)) {
644 if (rewriteABI())
645 report_fatal_error("Cannot lower callbase instruction");
646 return Changed;
647 }
648
649 // This is tricky. The call instruction's function type might not match
650 // the type of the caller. When optimising, can leave it unchanged.
651 // Webassembly detects that inconsistency and repairs it.
652 if (CB->getFunctionType() != VarargFunctionType)
653 if (!rewriteABI())
654 return Changed;
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 : seq(VarargFunctionType->getNumParams(), CB->arg_size())) {
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->getDebugLoc());
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->getDebugLoc());
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 = VarargFunctionType->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->getDebugLoc());
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 // Use the type of the call site rather than the function type to ensure
814 // RAUW succeeds in the case of a mismatching return type.
815 FunctionType *NFTy =
816 inlinableVariadicFunctionType(M, VarargFunctionType, CB->getType());
817
818 NewCB = CallInst::Create(NFTy, Dst, Args, OpBundles, "", CI->getIterator());
819
820 CallInst::TailCallKind TCK = CI->getTailCallKind();
822
823 // Can't tail call a function that is being passed a pointer to an alloca
824 if (TCK == CallInst::TCK_Tail)
825 TCK = CallInst::TCK_None;
826 CI->setTailCallKind(TCK);
827
828 } else {
829 llvm_unreachable("Unreachable when !expansionApplicableToFunctionCall()");
830 }
831
832 if (VaList)
833 Builder.CreateLifetimeEnd(VaList);
834
835 Builder.CreateLifetimeEnd(Alloced);
836
837 NewCB->setAttributes(PAL);
838 NewCB->takeName(CB);
839 NewCB->setCallingConv(CB->getCallingConv());
840 NewCB->setDebugLoc(DebugLoc());
841
842 // DeadArgElim and ArgPromotion copy exactly this metadata
843 NewCB->copyProfileAndDebugMetadata(*CB);
844
845 CB->replaceAllUsesWith(NewCB);
846 CB->eraseFromParent();
847 return Changed;
848}
849
850bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &Builder,
851 const DataLayout &DL,
852 VAStartInst *Inst) {
853 // Only removing va_start instructions that are not in variadic functions.
854 // Those would be rejected by the IR verifier before this pass.
855 // After splicing basic blocks from a variadic function into a fixed arity
856 // one the va_start that used to refer to the ... parameter still exist.
857 // There are also variadic functions that this pass did not change and
858 // va_start instances in the created single block wrapper functions.
859 // Replace exactly the instances in non-variadic functions as those are
860 // the ones to be fixed up to use the va_list passed as the final argument.
861
862 Function *ContainingFunction = Inst->getFunction();
863 if (ContainingFunction->isVarArg()) {
864 return false;
865 }
866
867 // The last argument is a vaListParameterType, either a va_list
868 // or a pointer to one depending on the target.
869 bool PassedByValue = ABI->vaListPassedInSSARegister();
870 Argument *PassedVaList =
871 ContainingFunction->getArg(ContainingFunction->arg_size() - 1);
872
873 // va_start takes a pointer to a va_list, e.g. one on the stack
874 Value *VaStartArg = Inst->getArgList();
875
876 Builder.SetInsertPoint(Inst);
877
878 if (PassedByValue) {
879 // The general thing to do is create an alloca, store the va_list argument
880 // to it, then create a va_copy. When vaCopyIsMemcpy(), this optimises to a
881 // store to the VaStartArg.
882 assert(ABI->vaCopyIsMemcpy());
883 // The va_list parameter may be passed in a different address space than
884 // the va_list object iterates in (e.g. NVPTX passes a local pointer but
885 // stores a generic cursor). Cast it to the type va_arg expects to load.
886 Value *Cursor = PassedVaList;
887 if (Cursor->getType() != VaStartArg->getType())
888 Cursor = Builder.CreateAddrSpaceCast(Cursor, VaStartArg->getType());
889 Builder.CreateStore(Cursor, VaStartArg);
890 } else {
891
892 // Otherwise emit a vacopy to pick up target-specific handling if any
893 auto &Ctx = Builder.getContext();
894
895 Builder.CreateIntrinsic(Intrinsic::vacopy, {DL.getAllocaPtrType(Ctx)},
896 {VaStartArg, PassedVaList});
897 }
898
899 Inst->eraseFromParent();
900 return true;
901}
902
903bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &, const DataLayout &,
904 VAEndInst *Inst) {
905 assert(ABI->vaEndIsNop());
906 Inst->eraseFromParent();
907 return true;
908}
909
910bool ExpandVariadics::expandVAIntrinsicCall(IRBuilder<> &Builder,
911 const DataLayout &DL,
912 VACopyInst *Inst) {
913 assert(ABI->vaCopyIsMemcpy());
914 Builder.SetInsertPoint(Inst);
915
916 auto &Ctx = Builder.getContext();
917 Type *VaListTy = ABI->vaListType(Ctx);
918 uint64_t Size = DL.getTypeAllocSize(VaListTy).getFixedValue();
919
920 Builder.CreateMemCpy(Inst->getDest(), {}, Inst->getSrc(), {},
921 Builder.getInt32(Size));
922
923 Inst->eraseFromParent();
924 return true;
925}
926
927bool ExpandVariadics::expandVAArgInst(IRBuilder<> &Builder,
928 const DataLayout &DL, VAArgInst *Inst) {
929 Builder.SetInsertPoint(Inst);
930
931 auto &Ctx = Builder.getContext();
932 Type *ValTy = Inst->getType();
933 Value *VaListPtr = Inst->getPointerOperand();
934
935 const VariadicABIInfo::VAArgSlotInfo SlotInfo = ABI->slotInfo(DL, ValTy);
936 Type *FrameFieldType = SlotInfo.Indirect ? DL.getAllocaPtrType(Ctx) : ValTy;
937 const uint64_t SlotSize = DL.getTypeAllocSize(FrameFieldType).getFixedValue();
938 const Align SlotAlign = SlotInfo.DataAlign;
939
940 Type *PtrTy = VaListPtr->getType();
941 Type *IdxTy = DL.getIndexType(PtrTy);
942
943 Value *Cur = Builder.CreateLoad(PtrTy, VaListPtr);
944
945 // Round the cursor up to the slot alignment used by the caller.
946 Value *Aligned = Cur;
947 if (SlotAlign > Align(1)) {
948 Value *RoundUp = Builder.CreateInBoundsPtrAdd(
949 Cur, ConstantInt::get(IdxTy, SlotAlign.value() - 1));
950 Aligned = Builder.CreateIntrinsic(
951 Intrinsic::ptrmask, {PtrTy, IdxTy},
952 {RoundUp, ConstantInt::getSigned(IdxTy, -(int64_t)SlotAlign.value())});
953 }
954
955 // Advance past the slot and write the iterator back.
956 Value *Next =
957 Builder.CreateInBoundsPtrAdd(Aligned, ConstantInt::get(IdxTy, SlotSize));
958 Builder.CreateStore(Next, VaListPtr);
959
960 // Load the slot contents: the value itself for direct arguments, or a
961 // pointer to the value for indirect ones.
962 Value *Result = Builder.CreateAlignedLoad(FrameFieldType, Aligned, SlotAlign);
963
964 if (SlotInfo.Indirect)
965 Result = Builder.CreateLoad(ValTy, Result);
966
967 Result->takeName(Inst);
968 Inst->replaceAllUsesWith(Result);
969 Inst->eraseFromParent();
970 return true;
971}
972
973struct Amdgpu final : public VariadicABIInfo {
974
975 bool enableForTarget() override { return true; }
976
977 bool vaListPassedInSSARegister() override { return true; }
978
979 Type *vaListType(LLVMContext &Ctx) override {
980 return PointerType::getUnqual(Ctx);
981 }
982
983 Type *vaListParameterType(Module &M) override {
984 return PointerType::getUnqual(M.getContext());
985 }
986
987 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
988 AllocaInst * /*va_list*/, Value *Buffer) override {
989 // Given Buffer, which is an AllocInst of vararg_buffer
990 // need to return something usable as parameter type
991 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
992 }
993
994 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
995 return {Align(4), false};
996 }
997};
998
999struct NVPTX final : public VariadicABIInfo {
1000
1001 bool enableForTarget() override { return true; }
1002
1003 bool vaListPassedInSSARegister() override { return true; }
1004
1005 Type *vaListType(LLVMContext &Ctx) override {
1006 return PointerType::getUnqual(Ctx);
1007 }
1008
1009 Type *vaListParameterType(Module &M) override {
1010 return PointerType::get(M.getContext(), NVPTXAS::ADDRESS_SPACE_LOCAL);
1011 }
1012
1013 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
1014 AllocaInst *, Value *Buffer) override {
1015 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
1016 }
1017
1018 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
1019 // NVPTX expects natural alignment in all cases. The variadic call ABI will
1020 // handle promoting types to their appropriate size and alignment.
1021 Align A = DL.getABITypeAlign(Parameter);
1022 return {A, false};
1023 }
1024};
1025
1026struct SPIRV final : public VariadicABIInfo {
1027
1028 bool enableForTarget() override { return true; }
1029
1030 bool vaListPassedInSSARegister() override { return true; }
1031
1032 Type *vaListType(LLVMContext &Ctx) override {
1033 return PointerType::getUnqual(Ctx);
1034 }
1035
1036 Type *vaListParameterType(Module &M) override {
1037 return PointerType::getUnqual(M.getContext());
1038 }
1039
1040 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
1041 AllocaInst *, Value *Buffer) override {
1042 return Builder.CreateAddrSpaceCast(Buffer, vaListParameterType(M));
1043 }
1044
1045 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
1046 // Expects natural alignment in all cases. The variadic call ABI will handle
1047 // promoting types to their appropriate size and alignment.
1048 Align A = DL.getABITypeAlign(Parameter);
1049 return {A, false};
1050 }
1051
1052 // The SPIR-V backend has special handling for builtins.
1053 bool ignoreFunction(const Function *F) override {
1054 if (!F->isDeclaration())
1055 return false;
1056
1057 std::string Demangled = llvm::demangle(F->getName());
1058 StringRef DemangledName(Demangled);
1059
1060 // Skip any SPIR-V builtins.
1061 // Note: an unmangled C `printf` declaration demangles to "printf" with no
1062 // argument list, so the "printf(" prefix check below misses it. Match the
1063 // bare name as well so OpenCL/HIP printf (emitted unmangled) is left as a
1064 // variadic call for the backend's OpenCL.std printf lowering to expand
1065 // inline, rather than being packed into a vararg buffer here.
1066 if (DemangledName.starts_with("__spirv_") ||
1067 DemangledName.starts_with("printf(") || F->getName() == "printf")
1068 return true;
1069
1070 return false;
1071 }
1072
1073 // We will likely see va intrinsics in the generic addrspace (4).
1074 SmallVector<unsigned> getTargetSpecificVaIntrinAddrSpaces() const override {
1075 return {4};
1076 }
1077};
1078
1079struct Wasm final : public VariadicABIInfo {
1080
1081 // Currently wasm is only used for testing, enabled by
1082 // -expand-variadics-override.
1083 bool enableForTarget() override { return false; }
1084
1085 bool vaListPassedInSSARegister() override { return true; }
1086
1087 Type *vaListType(LLVMContext &Ctx) override {
1088 return PointerType::getUnqual(Ctx);
1089 }
1090
1091 Type *vaListParameterType(Module &M) override {
1092 return PointerType::getUnqual(M.getContext());
1093 }
1094
1095 Value *initializeVaList(Module &M, LLVMContext &Ctx, IRBuilder<> &Builder,
1096 AllocaInst * /*va_list*/, Value *Buffer) override {
1097 return Buffer;
1098 }
1099
1100 VAArgSlotInfo slotInfo(const DataLayout &DL, Type *Parameter) override {
1101 LLVMContext &Ctx = Parameter->getContext();
1102 const unsigned MinAlign = 4;
1103 Align A = DL.getABITypeAlign(Parameter);
1104 if (A < MinAlign)
1105 A = Align(MinAlign);
1106
1107 if (auto *S = dyn_cast<StructType>(Parameter)) {
1108 if (S->getNumElements() > 1) {
1109 return {DL.getABITypeAlign(PointerType::getUnqual(Ctx)), true};
1110 }
1111 }
1112
1113 return {A, false};
1114 }
1115};
1116
1117std::unique_ptr<VariadicABIInfo> VariadicABIInfo::create(const Triple &T) {
1118 switch (T.getArch()) {
1119 case Triple::amdgpu:
1120 case Triple::r600: {
1121 return std::make_unique<Amdgpu>();
1122 }
1123
1124 case Triple::wasm32: {
1125 return std::make_unique<Wasm>();
1126 }
1127
1128 case Triple::nvptx:
1129 case Triple::nvptx64: {
1130 return std::make_unique<NVPTX>();
1131 }
1132
1133 case Triple::spirv:
1134 case Triple::spirv32:
1135 case Triple::spirv64: {
1136 return std::make_unique<SPIRV>();
1137 }
1138
1139 default:
1140 return {};
1141 }
1142}
1143
1144} // namespace
1145
1146char ExpandVariadics::ID = 0;
1147
1148INITIALIZE_PASS(ExpandVariadics, DEBUG_TYPE, "Expand variadic functions", false,
1149 false)
1150
1152 return new ExpandVariadics(M);
1153}
1154
1158 MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
1159 ExpandVariadics EV(Mode);
1160 EV.FAM = &FAM;
1161 if (!EV.runOnModule(M))
1162 return PreservedAnalyses::all();
1163
1164 // Preserving the proxy invalidates each function individually, which keeps
1165 // analyses like TargetLibraryInfo.
1168 return PA;
1169}
1170
Ops append({Chain, DAG.getConstant(SVEStores[NumParts - 2], DL, MVT::i32)})
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 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.
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
#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")))
Provides some synthesis utilities to produce sequences of values.
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)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
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
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI 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:169
void splice(Function::iterator ToIt, Function *FromF)
Transfer all blocks from FromF to this function at ToIt.
Definition Function.h:755
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:212
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
iterator begin()
Definition Function.h:847
arg_iterator arg_begin()
Definition Function.h:862
void setAttributes(AttributeList Attrs)
Set the attribute list for this Function.
Definition Function.h:332
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
size_t arg_size() const
Definition Function.h:895
Argument * getArg(unsigned i) const
Definition Function.h:880
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:230
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:846
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
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:408
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:2990
LLVM_ABI void copyProfileAndDebugMetadata(const Instruction &SrcInst)
Copy debug, profile, and memprof metadata from SrcInst to this instruction without copying alias-anal...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
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.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition Pass.h:253
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:133
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:657
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
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:292
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
Value * getPointerOperand()
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: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
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
const ParentTy * getParent() const
Definition ilist_node.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ 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.
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:1685
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Store
The extracted value is stored (ExtractElement only).
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:649
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
ExpandVariadicsMode
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:352
const IPOOptions & getIPOOptions(const LLVMContext &C)
Definition IPOOptions.h:36
LLVM_ABI ModulePass * createExpandVariadicsPass(ExpandVariadicsMode)
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
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
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:82
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111