LLVM 22.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
15#include "NVPTX.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"
26#include "llvm/Support/MD5.h"
28
29using namespace llvm;
30
31#define DEBUG_TYPE "nvptx-lower-ctor-dtor"
32
34 GlobalStr("nvptx-lower-global-ctor-dtor-id",
35 cl::desc("Override unique ID of ctor/dtor globals."),
36 cl::init(""), cl::Hidden);
37
38static cl::opt<bool>
39 CreateKernels("nvptx-emit-init-fini-kernel",
40 cl::desc("Emit kernels to call ctor/dtor globals."),
41 cl::init(true), cl::Hidden);
42
43namespace {
44
45static std::string getHash(StringRef Str) {
46 llvm::MD5 Hasher;
48 Hasher.update(Str);
49 Hasher.final(Hash);
50 return llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
51}
52
53static void addKernelAttrs(Function *F) {
54 F->addFnAttr("nvvm.maxclusterrank", "1");
55 F->addFnAttr("nvvm.maxntid", "1");
56 F->setCallingConv(CallingConv::PTX_Kernel);
57}
58
59static Function *createInitOrFiniKernelFunction(Module &M, bool IsCtor) {
60 StringRef InitOrFiniKernelName =
61 IsCtor ? "nvptx$device$init" : "nvptx$device$fini";
62 if (M.getFunction(InitOrFiniKernelName))
63 return nullptr;
64
65 Function *InitOrFiniKernel = Function::createWithDefaultAttr(
66 FunctionType::get(Type::getVoidTy(M.getContext()), false),
67 GlobalValue::WeakODRLinkage, 0, InitOrFiniKernelName, &M);
68 addKernelAttrs(InitOrFiniKernel);
69
70 return InitOrFiniKernel;
71}
72
73// We create the IR required to call each callback in this section. This is
74// equivalent to the following code. Normally, the linker would provide us with
75// the definitions of the init and fini array sections. The 'nvlink' linker does
76// not do this so initializing these values is done by the runtime.
77//
78// extern "C" void **__init_array_start = nullptr;
79// extern "C" void **__init_array_end = nullptr;
80// extern "C" void **__fini_array_start = nullptr;
81// extern "C" void **__fini_array_end = nullptr;
82//
83// using InitCallback = void();
84// using FiniCallback = void();
85//
86// void call_init_array_callbacks() {
87// for (auto start = __init_array_start; start != __init_array_end; ++start)
88// reinterpret_cast<InitCallback *>(*start)();
89// }
90//
91// void call_init_array_callbacks() {
92// size_t fini_array_size = __fini_array_end - __fini_array_start;
93// for (size_t i = fini_array_size; i > 0; --i)
94// reinterpret_cast<FiniCallback *>(__fini_array_start[i - 1])();
95// }
96static void createInitOrFiniCalls(Function &F, bool IsCtor) {
97 Module &M = *F.getParent();
98 LLVMContext &C = M.getContext();
99
100 IRBuilder<> IRB(BasicBlock::Create(C, "entry", &F));
101 auto *LoopBB = BasicBlock::Create(C, "while.entry", &F);
102 auto *ExitBB = BasicBlock::Create(C, "while.end", &F);
103 Type *PtrTy = IRB.getPtrTy(llvm::ADDRESS_SPACE_GLOBAL);
104
105 auto *Begin = M.getOrInsertGlobal(
106 IsCtor ? "__init_array_start" : "__fini_array_start",
107 PointerType::get(C, 0), [&]() {
108 auto *GV = new GlobalVariable(
109 M, PointerType::get(C, 0),
110 /*isConstant=*/false, GlobalValue::WeakAnyLinkage,
112 IsCtor ? "__init_array_start" : "__fini_array_start",
113 /*InsertBefore=*/nullptr, GlobalVariable::NotThreadLocal,
114 /*AddressSpace=*/llvm::ADDRESS_SPACE_GLOBAL);
115 GV->setVisibility(GlobalVariable::ProtectedVisibility);
116 return GV;
117 });
118 auto *End = M.getOrInsertGlobal(
119 IsCtor ? "__init_array_end" : "__fini_array_end", PointerType::get(C, 0),
120 [&]() {
121 auto *GV = new GlobalVariable(
122 M, PointerType::get(C, 0),
123 /*isConstant=*/false, GlobalValue::WeakAnyLinkage,
125 IsCtor ? "__init_array_end" : "__fini_array_end",
126 /*InsertBefore=*/nullptr, GlobalVariable::NotThreadLocal,
127 /*AddressSpace=*/llvm::ADDRESS_SPACE_GLOBAL);
128 GV->setVisibility(GlobalVariable::ProtectedVisibility);
129 return GV;
130 });
131
132 // The constructor type is suppoed to allow using the argument vectors, but
133 // for now we just call them with no arguments.
134 auto *CallBackTy = FunctionType::get(IRB.getVoidTy(), {});
135
136 // The destructor array must be called in reverse order. Get an expression to
137 // the end of the array and iterate backwards in that case.
138 Value *BeginVal = IRB.CreateLoad(Begin->getType(), Begin, "begin");
139 Value *EndVal = IRB.CreateLoad(Begin->getType(), End, "stop");
140 if (!IsCtor) {
141 auto *BeginInt = IRB.CreatePtrToInt(BeginVal, IntegerType::getInt64Ty(C));
142 auto *EndInt = IRB.CreatePtrToInt(EndVal, IntegerType::getInt64Ty(C));
143 auto *SubInst = IRB.CreateSub(EndInt, BeginInt);
144 auto *Offset = IRB.CreateAShr(
145 SubInst, ConstantInt::get(IntegerType::getInt64Ty(C), 3), "offset",
146 /*IsExact=*/true);
147 auto *ValuePtr = IRB.CreateGEP(PointerType::get(C, 0), BeginVal,
149 EndVal = BeginVal;
150 BeginVal = IRB.CreateInBoundsGEP(
151 PointerType::get(C, 0), ValuePtr,
152 ArrayRef<Value *>(ConstantInt::get(IntegerType::getInt64Ty(C), -1)),
153 "start");
154 }
155 IRB.CreateCondBr(
156 IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_NE : ICmpInst::ICMP_UGT, BeginVal,
157 EndVal),
158 LoopBB, ExitBB);
159 IRB.SetInsertPoint(LoopBB);
160 auto *CallBackPHI = IRB.CreatePHI(PtrTy, 2, "ptr");
161 auto *CallBack = IRB.CreateLoad(IRB.getPtrTy(F.getAddressSpace()),
162 CallBackPHI, "callback");
163 IRB.CreateCall(CallBackTy, CallBack);
164 auto *NewCallBack =
165 IRB.CreateConstGEP1_64(PtrTy, CallBackPHI, IsCtor ? 1 : -1, "next");
166 auto *EndCmp = IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_ULT,
167 NewCallBack, EndVal, "end");
168 CallBackPHI->addIncoming(BeginVal, &F.getEntryBlock());
169 CallBackPHI->addIncoming(NewCallBack, LoopBB);
170 IRB.CreateCondBr(EndCmp, ExitBB, LoopBB);
171 IRB.SetInsertPoint(ExitBB);
172 IRB.CreateRetVoid();
173}
174
175static bool createInitOrFiniGlobals(Module &M, GlobalVariable *GV,
176 bool IsCtor) {
178 if (!GA || GA->getNumOperands() == 0)
179 return false;
180
181 // NVPTX has no way to emit variables at specific sections or support for
182 // the traditional constructor sections. Instead, we emit mangled global
183 // names so the runtime can build the list manually.
184 for (Value *V : GA->operands()) {
185 auto *CS = cast<ConstantStruct>(V);
186 auto *F = cast<Constant>(CS->getOperand(1));
187 uint64_t Priority = cast<ConstantInt>(CS->getOperand(0))->getSExtValue();
188 std::string PriorityStr = "." + std::to_string(Priority);
189 // We append a semi-unique hash and the priority to the global name.
190 std::string GlobalID =
191 !GlobalStr.empty() ? GlobalStr : getHash(M.getSourceFileName());
192 std::string NameStr =
193 ((IsCtor ? "__init_array_object_" : "__fini_array_object_") +
194 F->getName() + "_" + GlobalID + "_" + std::to_string(Priority))
195 .str();
196 // PTX does not support exported names with '.' in them.
197 llvm::transform(NameStr, NameStr.begin(),
198 [](char c) { return c == '.' ? '_' : c; });
199
200 auto *GV = new GlobalVariable(M, F->getType(), /*IsConstant=*/true,
203 /*AddressSpace=*/4);
204 // This isn't respected by Nvidia, simply put here for clarity.
205 GV->setSection(IsCtor ? ".init_array" + PriorityStr
206 : ".fini_array" + PriorityStr);
208 appendToUsed(M, {GV});
209 }
210
211 return true;
212}
213
214static bool createInitOrFiniKernel(Module &M, StringRef GlobalName,
215 bool IsCtor) {
216 GlobalVariable *GV = M.getGlobalVariable(GlobalName);
217 if (!GV || !GV->hasInitializer())
218 return false;
219
220 if (!createInitOrFiniGlobals(M, GV, IsCtor))
221 return false;
222
223 if (!CreateKernels)
224 return true;
225
226 Function *InitOrFiniKernel = createInitOrFiniKernelFunction(M, IsCtor);
227 if (!InitOrFiniKernel)
228 return false;
229
230 createInitOrFiniCalls(*InitOrFiniKernel, IsCtor);
231
232 GV->eraseFromParent();
233 return true;
234}
235
236static bool lowerCtorsAndDtors(Module &M) {
237 bool Modified = false;
238 Modified |= createInitOrFiniKernel(M, "llvm.global_ctors", /*IsCtor =*/true);
239 Modified |= createInitOrFiniKernel(M, "llvm.global_dtors", /*IsCtor =*/false);
240 return Modified;
241}
242
243class NVPTXCtorDtorLoweringLegacy final : public ModulePass {
244public:
245 static char ID;
246 NVPTXCtorDtorLoweringLegacy() : ModulePass(ID) {}
247 bool runOnModule(Module &M) override { return lowerCtorsAndDtors(M); }
248};
249
250} // End anonymous namespace
251
257
258char NVPTXCtorDtorLoweringLegacy::ID = 0;
259INITIALIZE_PASS(NVPTXCtorDtorLoweringLegacy, DEBUG_TYPE,
260 "Lower ctors and dtors for NVPTX", false, false)
261
263 return new NVPTXCtorDtorLoweringLegacy();
264}
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:55
Machine Check Debug Module
static cl::opt< bool > CreateKernels("nvptx-emit-init-fini-kernel", cl::desc("Emit kernels to call ctor/dtor globals."), cl::init(true), cl::Hidden)
static cl::opt< std::string > GlobalStr("nvptx-lower-global-ctor-dtor-id", cl::desc("Override unique ID of ctor/dtor globals."), cl::init(""), cl::Hidden)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
This file contains some functions that are useful when dealing with strings.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:701
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:703
@ ICMP_NE
not equal
Definition InstrTypes.h:700
ConstantArray - Constant Array Declarations.
Definition Constants.h:433
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:380
LLVM_ABI void setSection(StringRef S)
Change the section for this global.
Definition Globals.cpp:275
@ 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:519
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2780
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
Definition MD5.cpp:189
LLVM_ABI void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
Definition MD5.cpp:234
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
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
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
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:298
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:281
op_range operands()
Definition User.h:292
unsigned getNumOperands() const
Definition User.h:254
LLVM Value Representation.
Definition Value.h:75
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:477
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
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:1948
ModulePass * createNVPTXCtorDtorLoweringLegacyPass()
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
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