31#define DEBUG_TYPE "nvptx-lower-ctor-dtor"
35 cl::desc(
"Override unique ID of ctor/dtor globals."),
40 cl::desc(
"Emit kernels to call ctor/dtor globals."),
45static std::string getHash(
StringRef Str) {
50 return llvm::utohexstr(Hash.
low(),
true);
87static Function *createInitOrFiniKernelFunction(
Module &M,
bool IsCtor) {
89 IsCtor ?
"nvptx$device$init" :
"nvptx$device$fini";
90 if (
M.getFunction(InitOrFiniKernelName))
96 addKernelMetadata(M, InitOrFiniKernel);
98 return InitOrFiniKernel;
124static void createInitOrFiniCalls(
Function &
F,
bool IsCtor) {
133 auto *Begin =
M.getOrInsertGlobal(
134 IsCtor ?
"__init_array_start" :
"__fini_array_start",
135 PointerType::get(
C, 0), [&]() {
137 M, PointerType::get(
C, 0),
140 IsCtor ?
"__init_array_start" :
"__fini_array_start",
141 nullptr, GlobalVariable::NotThreadLocal,
143 GV->setVisibility(GlobalVariable::ProtectedVisibility);
146 auto *
End =
M.getOrInsertGlobal(
147 IsCtor ?
"__init_array_end" :
"__fini_array_end", PointerType::get(
C, 0),
150 M, PointerType::get(
C, 0),
153 IsCtor ?
"__init_array_end" :
"__fini_array_end",
154 nullptr, GlobalVariable::NotThreadLocal,
156 GV->setVisibility(GlobalVariable::ProtectedVisibility);
162 auto *CallBackTy = FunctionType::get(IRB.getVoidTy(), {});
166 Value *BeginVal = IRB.CreateLoad(Begin->getType(), Begin,
"begin");
167 Value *EndVal = IRB.CreateLoad(Begin->getType(),
End,
"stop");
169 auto *BeginInt = IRB.CreatePtrToInt(BeginVal, IntegerType::getInt64Ty(
C));
170 auto *EndInt = IRB.CreatePtrToInt(EndVal, IntegerType::getInt64Ty(
C));
171 auto *SubInst = IRB.CreateSub(EndInt, BeginInt);
172 auto *
Offset = IRB.CreateAShr(
173 SubInst, ConstantInt::get(IntegerType::getInt64Ty(
C), 3),
"offset",
175 auto *ValuePtr = IRB.CreateGEP(PointerType::get(
C, 0), BeginVal,
178 BeginVal = IRB.CreateInBoundsGEP(
179 PointerType::get(
C, 0), ValuePtr,
184 IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_NE : ICmpInst::ICMP_UGT, BeginVal,
187 IRB.SetInsertPoint(LoopBB);
188 auto *CallBackPHI = IRB.CreatePHI(PtrTy, 2,
"ptr");
189 auto *CallBack = IRB.CreateLoad(IRB.getPtrTy(
F.getAddressSpace()),
190 CallBackPHI,
"callback");
191 IRB.CreateCall(CallBackTy, CallBack);
193 IRB.CreateConstGEP1_64(PtrTy, CallBackPHI, IsCtor ? 1 : -1,
"next");
194 auto *EndCmp = IRB.CreateCmp(IsCtor ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_ULT,
195 NewCallBack, EndVal,
"end");
196 CallBackPHI->addIncoming(BeginVal, &
F.getEntryBlock());
197 CallBackPHI->addIncoming(NewCallBack, LoopBB);
198 IRB.CreateCondBr(EndCmp, ExitBB, LoopBB);
199 IRB.SetInsertPoint(ExitBB);
213 auto *CS = cast<ConstantStruct>(V);
214 auto *
F = cast<Constant>(CS->getOperand(1));
215 uint64_t Priority = cast<ConstantInt>(CS->getOperand(0))->getSExtValue();
216 std::string PriorityStr =
"." + std::to_string(Priority);
220 std::string NameStr =
221 ((IsCtor ?
"__init_array_object_" :
"__fini_array_object_") +
222 F->getName() +
"_" +
GlobalID +
"_" + std::to_string(Priority))
226 [](
char c) { return c ==
'.' ?
'_' : c; });
233 GV->
setSection(IsCtor ?
".init_array" + PriorityStr
234 :
".fini_array" + PriorityStr);
248 if (!createInitOrFiniGlobals(M, GV, IsCtor))
254 Function *InitOrFiniKernel = createInitOrFiniKernelFunction(M, IsCtor);
255 if (!InitOrFiniKernel)
258 createInitOrFiniCalls(*InitOrFiniKernel, IsCtor);
264static bool lowerCtorsAndDtors(
Module &M) {
266 Modified |= createInitOrFiniKernel(M,
"llvm.global_ctors",
true);
267 Modified |= createInitOrFiniKernel(M,
"llvm.global_dtors",
false);
271class NVPTXCtorDtorLoweringLegacy final :
public ModulePass {
286char NVPTXCtorDtorLoweringLegacy::ID = 0;
289 "Lower ctors and dtors for NVPTX",
false,
false)
292 return new NVPTXCtorDtorLoweringLegacy();
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Module.h This file contains the declarations for the Module class.
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)
A container for analyses that lazily runs them and caches their results.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
ConstantArray - Constant Array Declarations.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
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.
void setSection(StringRef S)
Change the section for this global.
void setVisibility(VisibilityTypes V)
@ WeakODRLinkage
Same, but only replaced by something equivalent.
@ ExternalLinkage
Externally visible function.
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool hasInitializer() const
Definitions have initializers, declarations don't.
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This is an important class for using LLVM in a threaded context.
void update(ArrayRef< uint8_t > Data)
Updates the hash for the byte stream provided.
void final(MD5Result &Result)
Finishes off the hash and puts the result in result.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static MDString * get(LLVMContext &Context, StringRef Str)
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
virtual bool runOnModule(Module &M)=0
runOnModule - Virtual method overriden by subclasses to process the module being operated on.
A Module instance is used to store all the information related to an LLVM module.
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void addOperand(MDNode *M)
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
StringRef - Represent a constant reference to a string, i.e.
The instances of the Type class are immutable: once they are created, they are never changed.
static Type * getVoidTy(LLVMContext &C)
static IntegerType * getInt32Ty(LLVMContext &C)
unsigned getNumOperands() const
LLVM Value Representation.
@ PTX_Kernel
Call to a PTX kernel. Passes all arguments in parameter space.
@ C
The default llvm calling convention, compatible with C.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
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.
char & NVPTXCtorDtorLoweringLegacyPassID
ModulePass * createNVPTXCtorDtorLoweringLegacyPass()
void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.