LLVM 17.0.0git
AMDGPUCtorDtorLowering.cpp
Go to the documentation of this file.
1//===-- AMDGPUCtorDtorLowering.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 "AMDGPU.h"
15#include "llvm/IR/Constants.h"
16#include "llvm/IR/Function.h"
18#include "llvm/IR/IRBuilder.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/Value.h"
21#include "llvm/Pass.h"
23
24using namespace llvm;
25
26#define DEBUG_TYPE "amdgpu-lower-ctor-dtor"
27
28namespace {
29
30static Function *createInitOrFiniKernelFunction(Module &M, bool IsCtor) {
31 StringRef InitOrFiniKernelName = "amdgcn.device.init";
32 if (!IsCtor)
33 InitOrFiniKernelName = "amdgcn.device.fini";
34
35 Function *InitOrFiniKernel = Function::createWithDefaultAttr(
36 FunctionType::get(Type::getVoidTy(M.getContext()), false),
37 GlobalValue::ExternalLinkage, 0, InitOrFiniKernelName, &M);
38 BasicBlock *InitOrFiniKernelBB =
39 BasicBlock::Create(M.getContext(), "", InitOrFiniKernel);
40 ReturnInst::Create(M.getContext(), InitOrFiniKernelBB);
41
43 if (IsCtor)
44 InitOrFiniKernel->addFnAttr("device-init");
45 else
46 InitOrFiniKernel->addFnAttr("device-fini");
47 return InitOrFiniKernel;
48}
49
50static bool createInitOrFiniKernel(Module &M, StringRef GlobalName,
51 bool IsCtor) {
52 GlobalVariable *GV = M.getGlobalVariable(GlobalName);
53 if (!GV || !GV->hasInitializer())
54 return false;
55 ConstantArray *GA = dyn_cast<ConstantArray>(GV->getInitializer());
56 if (!GA || GA->getNumOperands() == 0)
57 return false;
58
59 Function *InitOrFiniKernel = createInitOrFiniKernelFunction(M, IsCtor);
60 IRBuilder<> IRB(InitOrFiniKernel->getEntryBlock().getTerminator());
61
62 FunctionType *ConstructorTy = InitOrFiniKernel->getFunctionType();
63
64 for (Value *V : GA->operands()) {
65 auto *CS = cast<ConstantStruct>(V);
66 IRB.CreateCall(ConstructorTy, CS->getOperand(1));
67 }
68
69 appendToUsed(M, {InitOrFiniKernel});
70
71 GV->eraseFromParent();
72 return true;
73}
74
75static bool lowerCtorsAndDtors(Module &M) {
76 bool Modified = false;
77 Modified |= createInitOrFiniKernel(M, "llvm.global_ctors", /*IsCtor =*/true);
78 Modified |= createInitOrFiniKernel(M, "llvm.global_dtors", /*IsCtor =*/false);
79 return Modified;
80}
81
82class AMDGPUCtorDtorLoweringLegacy final : public ModulePass {
83public:
84 static char ID;
85 AMDGPUCtorDtorLoweringLegacy() : ModulePass(ID) {}
86 bool runOnModule(Module &M) override {
87 return lowerCtorsAndDtors(M);
88 }
89};
90
91} // End anonymous namespace
92
95 return lowerCtorsAndDtors(M) ? PreservedAnalyses::none()
97}
98
99char AMDGPUCtorDtorLoweringLegacy::ID = 0;
101 AMDGPUCtorDtorLoweringLegacy::ID;
102INITIALIZE_PASS(AMDGPUCtorDtorLoweringLegacy, DEBUG_TYPE,
103 "Lower ctors and dtors for AMDGPU", false, false)
104
106 return new AMDGPUCtorDtorLoweringLegacy();
107}
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 INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:38
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:105
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:127
ConstantArray - Constant Array Declarations.
Definition: Constants.h:413
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
Definition: Function.cpp:554
const BasicBlock & getEntryBlock() const
Definition: Function.h:740
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:174
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 applied.
Definition: Function.cpp:336
void setCallingConv(CallingConv::ID CC)
Definition: Function.h:241
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:48
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.
Definition: Globals.cpp:468
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args=std::nullopt, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2301
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2558
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:248
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.
Definition: Module.h:65
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:155
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, Instruction *InsertBefore=nullptr)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
static Type * getVoidTy(LLVMContext &C)
op_range operands()
Definition: User.h:242
unsigned getNumOperands() const
Definition: User.h:191
LLVM Value Representation.
Definition: Value.h:74
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
@ AMDGPU_KERNEL
Used for AMDGPU code object kernels.
Definition: CallingConv.h:197
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
char & AMDGPUCtorDtorLoweringLegacyPassID
ModulePass * createAMDGPUCtorDtorLoweringLegacyPass()
void appendToUsed(Module &M, ArrayRef< GlobalValue * > Values)
Adds global values to the llvm.used list.