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