41#include "llvm/IR/IntrinsicsAMDGPU.h"
53#define DEBUG_TYPE "amdgpu-unify-divergent-exit-nodes"
57class AMDGPUUnifyDivergentExitNodesImpl {
62 AMDGPUUnifyDivergentExitNodesImpl() =
delete;
74class AMDGPUUnifyDivergentExitNodesLegacy :
public FunctionPass {
83char AMDGPUUnifyDivergentExitNodesLegacy::ID = 0;
86 AMDGPUUnifyDivergentExitNodesLegacy::ID;
89 "Unify divergent function exit nodes",
false,
false)
96void AMDGPUUnifyDivergentExitNodesLegacy::getAnalysisUsage(
124 while (!Stack.empty()) {
130 if (Visited.
insert(Pred).second)
131 Stack.push_back(Pred);
138BasicBlock *AMDGPUUnifyDivergentExitNodesImpl::unifyReturnBlockSet(
147 PHINode *PN =
nullptr;
148 if (
F.getReturnType()->isVoidTy()) {
152 PN =
B.CreatePHI(
F.getReturnType(), ReturningBlocks.
size(),
159 std::vector<DominatorTree::UpdateType> Updates;
160 Updates.reserve(ReturningBlocks.
size());
161 for (BasicBlock *BB : ReturningBlocks) {
165 PN->
addIncoming(BB->getTerminator()->getOperand(0), BB);
168 BB->getTerminator()->eraseFromParent();
170 Updates.emplace_back(DominatorTree::Insert, BB, NewRetBlock);
177 for (BasicBlock *BB : ReturningBlocks) {
180 SimplifyCFGOptions().bonusInstThreshold(2));
191 Type *RetTy =
F.getReturnType();
194 ReturningBlocks.
push_back(DummyReturnBB);
195 return DummyReturnBB;
202 std::vector<DominatorTree::UpdateType> &Updates) {
208 Updates.reserve(Updates.size() + 2 * Successors.
size() + 2);
226bool AMDGPUUnifyDivergentExitNodesImpl::run(Function &
F, DominatorTree *DT,
227 const PostDominatorTree &PDT,
231 PDT.
getRoot()->getTerminator())))
243 std::vector<DominatorTree::UpdateType> Updates;
252 PDT.
roots(), [&](
auto BB) { return !isUniformlyReached(UA, *BB); });
254 for (BasicBlock *BB : PDT.
roots()) {
258 if (CI && CI->isMustTailCall())
260 if (HasDivergentExitBlock)
263 if (HasDivergentExitBlock)
269 BasicBlock *LoopHeaderBB = BI->getSuccessor();
270 BI->eraseFromParent();
274 Updates.emplace_back(DominatorTree::Insert, BB, DummyReturnBB);
287 if (!UnreachableBlocks.
empty()) {
290 if (UnreachableBlocks.
size() == 1) {
291 UnreachableBlock = UnreachableBlocks.
front();
294 "UnifiedUnreachableBlock", &
F);
295 new UnreachableInst(
F.getContext(), UnreachableBlock);
297 Updates.reserve(Updates.size() + UnreachableBlocks.
size());
298 for (BasicBlock *BB : UnreachableBlocks) {
300 BB->getTerminator()->eraseFromParent();
302 Updates.emplace_back(DominatorTree::Insert, BB, UnreachableBlock);
307 if (!ReturningBlocks.
empty()) {
311 Type *RetTy =
F.getReturnType();
317 F.getParent(), Intrinsic::amdgcn_unreachable);
327 ReturningBlocks.
push_back(UnreachableBlock);
333 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
339 if (ReturningBlocks.
empty())
342 if (ReturningBlocks.
size() == 1)
345 unifyReturnBlockSet(
F, DTU, ReturningBlocks,
"UnifiedReturnBlock");
349bool AMDGPUUnifyDivergentExitNodesLegacy::runOnFunction(Function &
F) {
350 DominatorTree *DT =
nullptr;
352 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
354 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
355 const auto &UA = getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
356 const auto *TranformInfo =
357 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
F);
358 return AMDGPUUnifyDivergentExitNodesImpl(TranformInfo).run(
F, DT, PDT, UA);
371 return AMDGPUUnifyDivergentExitNodesImpl(TransformInfo).
run(
F, DT, PDT, UA)
static BasicBlock * createDummyReturnBlock(Function &F, SmallVector< BasicBlock *, 4 > &ReturningBlocks)
static bool isUniformlyReached(const UniformityInfo &UA, BasicBlock &BB)
static void handleNBranch(Function &F, BasicBlock *BB, Instruction *BI, BasicBlock *DummyReturnBB, std::vector< DominatorTree::UpdateType > &Updates)
Handle conditional branch instructions (-> 2 targets) and callbr instructions with N targets.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool runOnFunction(Function &F, bool PostInlining)
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
LLVM Basic Block Representation.
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
Analysis pass which computes a DominatorTree.
iterator_range< root_iterator > roots()
static constexpr UpdateKind Delete
static constexpr UpdateKind Insert
Legacy analysis pass which computes a DominatorTree.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
FunctionPass class - This class is used to implement most global optimizations.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static ReturnInst * Create(LLVMContext &C, Value *retVal=nullptr, InsertPosition InsertBefore=nullptr)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Analysis pass providing the TargetTransformInfo.
LLVM_ABI Result run(const Function &F, FunctionAnalysisManager &)
The instances of the Type class are immutable: once they are created, they are never changed.
bool isVoidTy() const
Return true if this is 'void'.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
LLVM Value Representation.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ BasicBlock
Various leaf nodes.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
FunctionAddr VTableAddr Value
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto successors(const MachineBasicBlock *BB)
char & AMDGPUUnifyDivergentExitNodesID
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI char & BreakCriticalEdgesID
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
LLVM_ABI cl::opt< bool > RequireAndPreserveDomTree
This function is used to do simplification of a CFG.
LLVM_ABI bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, DomTreeUpdater *DTU=nullptr, const SimplifyCFGOptions &Options={}, ArrayRef< WeakVH > LoopHeaders={})
auto predecessors(const MachineBasicBlock *BB)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.