LLVM 24.0.0git
NVPTXCtorDtorLowering.cpp
Go to the documentation of this file.
1//===-- NVPTXCtorDtorLowering.cpp - Handle global ctors and dtors --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This pass creates a unified init and fini kernel with the required metadata
11//===----------------------------------------------------------------------===//
12
14#include "NVPTX.h"
15#include "NVPTXSubtarget.h"
17#include "llvm/IR/CallingConv.h"
18#include "llvm/IR/Constants.h"
19#include "llvm/IR/Function.h"
21#include "llvm/IR/IRBuilder.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IR/Value.h"
24#include "llvm/Pass.h"
25#include "llvm/Support/MD5.h"
28
29using namespace llvm;
30
31#define DEBUG_TYPE "nvptx-lower-ctor-dtor"
32
33namespace {
34
35static std::string getHash(StringRef Str) {
36 llvm::MD5 Hasher;
38 Hasher.update(Str);
39 Hasher.final(Hash);
40 return llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
41}
42
43static void addKernelAttrs(Function *F) {
44 F->addFnAttr(NVVMAttr::MaxClusterRank, "1");
45 F->addFnAttr(NVVMAttr::MaxNTID, "1");
46 F->setCallingConv(CallingConv::PTX_Kernel);
47}
48
49static Function *createInitOrFiniKernelFunction(Module &M, bool IsCtor) {
50 StringRef InitOrFiniKernelName =
51 IsCtor ? "nvptx$device$init" : "nvptx$device$fini";
52 if (M.getFunction(InitOrFiniKernelName))
53 return nullptr;
54
55 Function *InitOrFiniKernel = Function::createWithDefaultAttr(
56 FunctionType::get(Type::getVoidTy(M.getContext()), false),
57 GlobalValue::WeakODRLinkage, 0, InitOrFiniKernelName, &M);
58 addKernelAttrs(InitOrFiniKernel);
59
60 return InitOrFiniKernel;
61}
62
63// We create the IR required to call each callback in this section. This is
64// equivalent to the following code. Normally, the linker would provide us with
65// the definitions of the init and fini array sections. The 'nvlink' linker does
66// not do this so initializing these values is done by the runtime.
67//
68// extern "C" void **__init_array_start = nullptr;
69// extern "C" void **__init_array_end = nullptr;
70// extern "C" void **__fini_array_start = nullptr;
71// extern "C" void **__fini_array_end = nullptr;
72//
73// using InitCallback = void();
74// using FiniCallback = void();
75//
76// void call_init_array_callbacks() {
77// for (auto start = __init_array_start; start != __init_array_end; ++start)
78// reinterpret_cast<InitCallback *>(*start)();
79// }
80//
81// void call_fini_array_callbacks() {
82// size_t fini_array_size = __fini_array_end - __fini_array_start;
83// for (size_t i = fini_array_size; i > 0; --i)
84// reinterpret_cast<FiniCallback *>(__fini_array_start[i - 1])();
85// }
86static void createInitOrFiniCalls(Function &F, bool IsCtor) {
87 Module &M = *F.getParent();
88 LLVMContext &C = M.getContext();
89
90 IRBuilder<> IRB(BasicBlock::Create(C, "entry", &F));
91 auto *LoopBB = BasicBlock::Create(C, "while.entry", &F);
92 auto *ExitBB = BasicBlock::Create(C, "while.end", &F);
94
95 auto *Begin = M.getOrInsertGlobal(
96 IsCtor ? "__init_array_start" : "__fini_array_start",
97 PointerType::get(C, 0), [&]() {
98 auto *GV = new GlobalVariable(
99 M, PointerType::get(C, 0),
100 /*isConstant=*/false, GlobalValue::WeakAnyLinkage,
102 IsCtor ? "__init_array_start" : "__fini_array_start",
103 /*InsertBefore=*/nullptr, GlobalVariable::NotThreadLocal,
104 /*AddressSpace=*/llvm::ADDRESS_SPACE_GLOBAL);
105 GV->setVisibility(GlobalVariable::ProtectedVisibility);
106 return GV;
107 });
108 auto *End = M.getOrInsertGlobal(
109 IsCtor ? "__init_array_end" : "__fini_array_end", PointerType::get(C, 0),
110 [&]() {
111 auto *GV = new GlobalVariable(
112 M, PointerType::get(C, 0),
113 /*isConstant=*/false, GlobalValue::WeakAnyLinkage,
115 IsCtor ? "__init_array_end" : "__fini_array_end",
116 /*InsertBefore=*/nullptr, GlobalVariable::NotThreadLocal,
117 /*AddressSpace=*/llvm::ADDRESS_SPACE_GLOBAL);
118 GV->setVisibility(GlobalVariable::ProtectedVisibility);
119 return GV;
120 });
121
122 // The constructor type is suppoed to allow using the argument vectors, but
123 // for now we just call them with no arguments.
124 auto *CallBackTy = FunctionType::get(IRB.getVoidTy(), {});
125
126 // The destructor array must be called in reverse order. Get an expression to
127 // the end of the array and iterate backwards in that case.
128 Value *BeginVal = IRB.CreateLoad(Begin->getType(), Begin, "begin");
129 Value *EndVal = IRB.CreateLoad(Begin->getType(), End, "stop");
130 if (!IsCtor) {
131 Value *OldBeginVal = BeginVal;
132 BeginVal =
133 IRB.CreateInBoundsGEP(PointerType::get(C, 0), EndVal,
136 "start");
137 EndVal = OldBeginVal;
138 }
139 IRB.CreateCondBr(
140 IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_NE : ICmpInst::ICMP_UGE, BeginVal,
141 EndVal),
142 LoopBB, ExitBB);
143 IRB.SetInsertPoint(LoopBB);
144 auto *CallBackPHI = IRB.CreatePHI(PtrTy, 2, "ptr");
145 auto *CallBack = IRB.CreateLoad(IRB.getPtrTy(F.getAddressSpace()),
146 CallBackPHI, "callback");
147 IRB.CreateCall(CallBackTy, CallBack);
148 auto *NewCallBack =
149 IRB.CreateConstGEP1_64(PtrTy, CallBackPHI, IsCtor ? 1 : -1, "next");
150 auto *EndCmp = IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_ULT,
151 NewCallBack, EndVal, "end");
152 CallBackPHI->addIncoming(BeginVal, &F.getEntryBlock());
153 CallBackPHI->addIncoming(NewCallBack, LoopBB);
154 IRB.CreateCondBr(EndCmp, ExitBB, LoopBB);
155 IRB.SetInsertPoint(ExitBB);
156 IRB.CreateRetVoid();
157}
158
159static bool createInitOrFiniGlobals(Module &M, GlobalVariable *GV, bool IsCtor,
160 const NVPTXOptions &CLOpts) {
162 if (!GA || GA->getNumOperands() == 0)
163 return false;
164
165 // NVPTX has no way to emit variables at specific sections or support for
166 // the traditional constructor sections. Instead, we emit mangled global
167 // names so the runtime can build the list manually.
168 for (Value *V : GA->operands()) {
169 auto *CS = cast<ConstantStruct>(V);
170 auto *F = cast<Constant>(CS->getOperand(1));
171 uint64_t Priority = cast<ConstantInt>(CS->getOperand(0))->getSExtValue();
172 std::string PriorityStr = "." + std::to_string(Priority);
173 // We append a semi-unique hash and the priority to the global name.
174 std::string GlobalID = CLOpts.lower_global_ctor_dtor_id.empty()
175 ? getHash(M.getSourceFileName())
176 : CLOpts.lower_global_ctor_dtor_id.str();
177 std::string NameStr =
178 ((IsCtor ? "__init_array_object_" : "__fini_array_object_") +
179 F->getName() + "_" + GlobalID + "_" + std::to_string(Priority))
180 .str();
181 // PTX does not support exported names with '.' in them.
182 llvm::transform(NameStr, NameStr.begin(),
183 [](char c) { return c == '.' ? '_' : c; });
184
185 auto *GV = new GlobalVariable(M, F->getType(), /*IsConstant=*/true,
188 /*AddressSpace=*/4);
189 // This isn't respected by Nvidia, simply put here for clarity.
190 GV->setSection(IsCtor ? ".init_array" + PriorityStr
191 : ".fini_array" + PriorityStr);
193 appendToUsed(M, {GV});
194 }
195
196 return true;
197}
198
199static bool createInitOrFiniKernel(Module &M, StringRef GlobalName, bool IsCtor,
200 const NVPTXOptions &CLOpts) {
201 GlobalVariable *GV = M.getGlobalVariable(GlobalName);
202 if (!GV || !GV->hasInitializer())
203 return false;
204
205 if (!createInitOrFiniGlobals(M, GV, IsCtor, CLOpts))
206 return false;
207
208 if (!CLOpts.emit_init_fini_kernel)
209 return true;
210
211 Function *InitOrFiniKernel = createInitOrFiniKernelFunction(M, IsCtor);
212 if (!InitOrFiniKernel)
213 return false;
214
215 createInitOrFiniCalls(*InitOrFiniKernel, IsCtor);
216
217 GV->eraseFromParent();
218 return true;
219}
220
221static bool lowerCtorsAndDtors(Module &M) {
222 const NVPTXOptions &CLOpts = getNVPTXOptions(M);
223 bool Modified = false;
224 Modified |=
225 createInitOrFiniKernel(M, "llvm.global_ctors", /*IsCtor =*/true, CLOpts);
226 Modified |=
227 createInitOrFiniKernel(M, "llvm.global_dtors", /*IsCtor =*/false, CLOpts);
228 return Modified;
229}
230
231class NVPTXCtorDtorLoweringLegacy final : public ModulePass {
232public:
233 static char ID;
234 NVPTXCtorDtorLoweringLegacy() : ModulePass(ID) {}
235 bool runOnModule(Module &M) override { return lowerCtorsAndDtors(M); }
236};
237
238} // End anonymous namespace
239
245
246char NVPTXCtorDtorLoweringLegacy::ID = 0;
247INITIALIZE_PASS(NVPTXCtorDtorLoweringLegacy, DEBUG_TYPE,
248 "Lower ctors and dtors for NVPTX", false, false)
249
251 return new NVPTXCtorDtorLoweringLegacy();
252}
uint64_t uint64_t
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
ModuleAnalysisManager MAM
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some functions that are useful when dealing with strings.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
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 * createWithDefaultAttr(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Creates a function with some attributes recorded in llvm.module.flags and the LLVMContext applied.
Definition Function.cpp:372
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:348
@ ProtectedVisibility
The GV is protected.
Definition GlobalValue.h:70
void setVisibility(VisibilityTypes V)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
Value * CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, const Twine &Name="")
Definition IRBuilder.h:2055
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1212
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2019
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2556
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2587
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition IRBuilder.h:1907
ReturnInst * CreateRetVoid()
Create a 'ret void' instruction.
Definition IRBuilder.h:1183
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2601
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:565
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:196
Type * getVoidTy()
Fetch the type representing void.
Definition IRBuilder.h:560
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2949
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:188
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:233
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
PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
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:887
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
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
op_range operands()
Definition User.h:267
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
constexpr StringLiteral MaxNTID("nvvm.maxntid")
constexpr StringLiteral MaxClusterRank("nvvm.maxclusterrank")
This is an optimization pass for GlobalISel generic memory operations.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
std::string utohexstr(uint64_t X, bool LowerCase=false, unsigned Width=0)
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition STLExtras.h:2042
ModulePass * createNVPTXCtorDtorLoweringLegacyPass()
const NVPTXOptions & getNVPTXOptions(const LLVMContext &C)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
uint64_t low() const
Definition MD5.h:47