LLVM 23.0.0git
SPIRVCtorDtorLowering.cpp
Go to the documentation of this file.
1//===-- SPIRVCtorDtorLowering.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// This pass creates a unified init and fini kernel with the required metadata
10// to call global constructors and destructors on SPIR-V targets.
11//
12//===----------------------------------------------------------------------===//
13
16#include "SPIRV.h"
19#include "llvm/IR/CallingConv.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/Function.h"
23#include "llvm/IR/IRBuilder.h"
24#include "llvm/IR/Module.h"
25#include "llvm/IR/Value.h"
26#include "llvm/Pass.h"
28#include "llvm/Support/MD5.h"
31
32using namespace llvm;
33
34#define DEBUG_TYPE "spirv-lower-ctor-dtor"
35
37 GlobalStr("spirv-lower-global-ctor-dtor-id",
38 cl::desc("Override unique ID of ctor/dtor globals."),
39 cl::init(""), cl::Hidden);
40
41static cl::opt<bool>
42 CreateKernels("spirv-emit-init-fini-kernel",
43 cl::desc("Emit kernels to call ctor/dtor globals."),
44 cl::init(true), cl::Hidden);
45
46namespace {
47constexpr int SPIRV_GLOBAL_AS = 1;
48
49std::string getHash(StringRef Str) {
50 llvm::MD5 Hasher;
52 Hasher.update(Str);
53 Hasher.final(Hash);
54 return llvm::utohexstr(Hash.low(), /*LowerCase=*/true);
55}
56
57void addKernelAttrs(Function *F) {
58 F->setCallingConv(CallingConv::SPIR_KERNEL);
59 F->addFnAttr("uniform-work-group-size", "true");
60}
61
62Function *createInitOrFiniKernelFunction(Module &M, bool IsCtor) {
63 StringRef InitOrFiniKernelName =
64 IsCtor ? "spirv$device$init" : "spirv$device$fini";
65 if (M.getFunction(InitOrFiniKernelName))
66 return nullptr;
67
68 Function *InitOrFiniKernel = Function::createWithDefaultAttr(
69 FunctionType::get(Type::getVoidTy(M.getContext()), false),
70 GlobalValue::WeakODRLinkage, 0, InitOrFiniKernelName, &M);
71 addKernelAttrs(InitOrFiniKernel);
72
73 return InitOrFiniKernel;
74}
75
76// We create the IR required to call each callback in this section. This is
77// equivalent to the following code. Normally, the linker would provide us with
78// the definitions of the init and fini array sections. The 'spirv-link' linker
79// does not do this so initializing these values is done by the offload runtime.
80//
81// extern "C" void **__init_array_start = nullptr;
82// extern "C" void **__init_array_end = nullptr;
83// extern "C" void **__fini_array_start = nullptr;
84// extern "C" void **__fini_array_end = nullptr;
85//
86// using InitCallback = void();
87// using FiniCallback = void();
88//
89// void call_init_array_callbacks() {
90// for (auto start = __init_array_start; start != __init_array_end; ++start)
91// reinterpret_cast<InitCallback *>(*start)();
92// }
93//
94// void call_fini_array_callbacks() {
95// size_t fini_array_size = __fini_array_end - __fini_array_start;
96// for (size_t i = fini_array_size; i > 0; --i)
97// reinterpret_cast<FiniCallback *>(__fini_array_start[i - 1])();
98// }
99void createInitOrFiniCalls(Function &F, bool IsCtor) {
100 Module &M = *F.getParent();
101 LLVMContext &C = M.getContext();
102
103 IRBuilder<> IRB(BasicBlock::Create(C, "entry", &F));
104 auto *LoopBB = BasicBlock::Create(C, "while.entry", &F);
105 auto *ExitBB = BasicBlock::Create(C, "while.end", &F);
106 Type *PtrTy = IRB.getPtrTy(SPIRV_GLOBAL_AS);
107
108 auto CreateGlobal = [&](const char *Name) -> GlobalVariable * {
109 auto *GV = new GlobalVariable(
111 /*isConstant=*/false, GlobalValue::WeakAnyLinkage,
113 /*InsertBefore=*/nullptr, GlobalVariable::NotThreadLocal,
114 /*AddressSpace=*/SPIRV_GLOBAL_AS);
115 GV->setVisibility(GlobalVariable::ProtectedVisibility);
116 return GV;
117 };
118
119 auto *Begin = M.getOrInsertGlobal(
120 IsCtor ? "__init_array_start" : "__fini_array_start",
122 return CreateGlobal(IsCtor ? "__init_array_start"
123 : "__fini_array_start");
124 }));
125 auto *End = M.getOrInsertGlobal(
126 IsCtor ? "__init_array_end" : "__fini_array_end",
128 return CreateGlobal(IsCtor ? "__init_array_end" : "__fini_array_end");
129 }));
130 auto *CallBackTy = FunctionType::get(IRB.getVoidTy(), {});
131
132 // The destructor array must be called in reverse order. Get an expression to
133 // the end of the array and iterate backwards in that case.
134 Value *BeginVal = IRB.CreateLoad(Begin->getType(), Begin, "begin");
135 Value *EndVal = IRB.CreateLoad(Begin->getType(), End, "stop");
136 if (!IsCtor) {
137 Value *OldBeginVal = BeginVal;
138 BeginVal =
139 IRB.CreateInBoundsGEP(PointerType::getUnqual(C), EndVal,
142 "start");
143 EndVal = OldBeginVal;
144 }
145 IRB.CreateCondBr(
146 IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_NE : ICmpInst::ICMP_UGE, BeginVal,
147 EndVal),
148 LoopBB, ExitBB);
149 IRB.SetInsertPoint(LoopBB);
150 auto *CallBackPHI = IRB.CreatePHI(PtrTy, 2, "ptr");
151 auto *CallBack = IRB.CreateLoad(IRB.getPtrTy(F.getAddressSpace()),
152 CallBackPHI, "callback");
153 IRB.CreateCall(CallBackTy, CallBack);
154 auto *NewCallBack =
155 IRB.CreateConstGEP1_64(PtrTy, CallBackPHI, IsCtor ? 1 : -1, "next");
156 auto *EndCmp = IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_ULT,
157 NewCallBack, EndVal, "end");
158 CallBackPHI->addIncoming(BeginVal, &F.getEntryBlock());
159 CallBackPHI->addIncoming(NewCallBack, LoopBB);
160 IRB.CreateCondBr(EndCmp, ExitBB, LoopBB);
161 IRB.SetInsertPoint(ExitBB);
162 IRB.CreateRetVoid();
163}
164
165bool createInitOrFiniGlobals(Module &M, GlobalVariable *GV, bool IsCtor) {
167 if (!GA || GA->getNumOperands() == 0)
168 return false;
169
170 // SPIR-V has no way to emit variables at specific sections or support for
171 // the traditional constructor sections. Instead, we emit mangled global
172 // names so the runtime can build the list manually.
173 for (Value *V : GA->operands()) {
174 auto *CS = cast<ConstantStruct>(V);
175 auto *F = cast<Constant>(CS->getOperand(1));
176 uint64_t Priority = cast<ConstantInt>(CS->getOperand(0))->getSExtValue();
177 std::string PriorityStr = "." + std::to_string(Priority);
178 // We append a semi-unique hash and the priority to the global name.
179 std::string GlobalID =
180 !GlobalStr.empty() ? GlobalStr : getHash(M.getSourceFileName());
181 std::string NameStr =
182 ((IsCtor ? "__init_array_object_" : "__fini_array_object_") +
183 F->getName() + "_" + GlobalID + "_" + std::to_string(Priority))
184 .str();
185 llvm::transform(NameStr, NameStr.begin(),
186 [](char c) { return c == '.' ? '_' : c; });
187
188 auto *GV = new GlobalVariable(M, F->getType(), /*IsConstant=*/true,
191 /*AddressSpace=*/SPIRV_GLOBAL_AS);
192 GV->setSection(IsCtor ? ".init_array" + PriorityStr
193 : ".fini_array" + PriorityStr);
195 }
196
197 return true;
198}
199
200bool createInitOrFiniKernel(Module &M, StringRef GlobalName, bool IsCtor) {
201 GlobalVariable *GV = M.getGlobalVariable(GlobalName);
202 if (!GV || !GV->hasInitializer())
203 return false;
204
205 if (!createInitOrFiniGlobals(M, GV, IsCtor))
206 return false;
207
208 if (!CreateKernels)
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
221bool lowerCtorsAndDtors(Module &M) {
222 // Only run this pass for OpenMP offload compilation
224 return false;
225
226 bool Modified = false;
227 Modified |= createInitOrFiniKernel(M, "llvm.global_ctors", /*IsCtor =*/true);
228 Modified |= createInitOrFiniKernel(M, "llvm.global_dtors", /*IsCtor =*/false);
229 return Modified;
230}
231
232class SPIRVCtorDtorLoweringLegacy final : public ModulePass {
233public:
234 static char ID;
235 SPIRVCtorDtorLoweringLegacy() : ModulePass(ID) {}
236 bool runOnModule(Module &M) override { return lowerCtorsAndDtors(M); }
237};
238
239} // End anonymous namespace
240
246
247char SPIRVCtorDtorLoweringLegacy::ID = 0;
248INITIALIZE_PASS(SPIRVCtorDtorLoweringLegacy, DEBUG_TYPE,
249 "SPIRV lower ctors and dtors", false, false)
250
252 return new SPIRVCtorDtorLoweringLegacy();
253}
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
static cl::opt< std::string > GlobalStr("spirv-lower-global-ctor-dtor-id", cl::desc("Override unique ID of ctor/dtor globals."), cl::init(""), cl::Hidden)
static cl::opt< bool > CreateKernels("spirv-emit-init-fini-kernel", cl::desc("Emit kernels to call ctor/dtor globals."), cl::init(true), cl::Hidden)
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
static PointerType * getUnqual(Type *ElementType)
This constructs a pointer to an object of the specified type in the default address space (address sp...
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
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
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
An efficient, type-erasing, non-owning reference to a callable.
@ SPIR_KERNEL
Used for SPIR kernel functions.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
initializer< Ty > init(const Ty &Val)
bool isOpenMPDevice(Module &M)
Helper to determine if M is a OpenMP target offloading device module.
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
ModulePass * createSPIRVCtorDtorLoweringLegacyPass()
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
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
uint64_t low() const
Definition MD5.h:47