LLVM 22.0.0git
AMDGPUUnifyDivergentExitNodes.cpp
Go to the documentation of this file.
1//===- AMDGPUUnifyDivergentExitNodes.cpp ----------------------------------===//
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 is a variant of the UnifyFunctionExitNodes pass. Rather than ensuring
10// there is at most one ret and one unreachable instruction, it ensures there is
11// at most one divergent exiting block.
12//
13// StructurizeCFG can't deal with multi-exit regions formed by branches to
14// multiple return nodes. It is not desirable to structurize regions with
15// uniform branches, so unifying those to the same return block as divergent
16// branches inhibits use of scalar branching. It still can't deal with the case
17// where one branch goes to return, and one unreachable. Replace unreachable in
18// this case with a return.
19//
20//===----------------------------------------------------------------------===//
21
23#include "AMDGPU.h"
24#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/StringRef.h"
32#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/CFG.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/Dominators.h"
36#include "llvm/IR/Function.h"
37#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/InstrTypes.h"
40#include "llvm/IR/Intrinsics.h"
41#include "llvm/IR/IntrinsicsAMDGPU.h"
42#include "llvm/IR/Type.h"
44#include "llvm/Pass.h"
50
51using namespace llvm;
52
53#define DEBUG_TYPE "amdgpu-unify-divergent-exit-nodes"
54
55namespace {
56
57class AMDGPUUnifyDivergentExitNodesImpl {
58private:
59 const TargetTransformInfo *TTI = nullptr;
60
61public:
62 AMDGPUUnifyDivergentExitNodesImpl() = delete;
63 AMDGPUUnifyDivergentExitNodesImpl(const TargetTransformInfo *TTI)
64 : TTI(TTI) {}
65
66 // We can preserve non-critical-edgeness when we unify function exit nodes
67 BasicBlock *unifyReturnBlockSet(Function &F, DomTreeUpdater &DTU,
68 ArrayRef<BasicBlock *> ReturningBlocks,
69 StringRef Name);
70 bool run(Function &F, DominatorTree *DT, const PostDominatorTree &PDT,
71 const UniformityInfo &UA);
72};
73
74class AMDGPUUnifyDivergentExitNodes : public FunctionPass {
75public:
76 static char ID;
77 AMDGPUUnifyDivergentExitNodes() : FunctionPass(ID) {}
78 void getAnalysisUsage(AnalysisUsage &AU) const override;
79 bool runOnFunction(Function &F) override;
80};
81} // end anonymous namespace
82
83char AMDGPUUnifyDivergentExitNodes::ID = 0;
84
85char &llvm::AMDGPUUnifyDivergentExitNodesID = AMDGPUUnifyDivergentExitNodes::ID;
86
87INITIALIZE_PASS_BEGIN(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE,
88 "Unify divergent function exit nodes", false, false)
92INITIALIZE_PASS_END(AMDGPUUnifyDivergentExitNodes, DEBUG_TYPE,
93 "Unify divergent function exit nodes", false, false)
94
95void AMDGPUUnifyDivergentExitNodes::getAnalysisUsage(AnalysisUsage &AU) const {
97 AU.addRequired<DominatorTreeWrapperPass>();
98
99 AU.addRequired<PostDominatorTreeWrapperPass>();
100
101 AU.addRequired<UniformityInfoWrapperPass>();
102
104 AU.addPreserved<DominatorTreeWrapperPass>();
105 // FIXME: preserve PostDominatorTreeWrapperPass
106 }
107
108 // We preserve the non-critical-edgeness property
109 AU.addPreservedID(BreakCriticalEdgesID);
110
112
113 AU.addRequired<TargetTransformInfoWrapperPass>();
114}
115
116/// \returns true if \p BB is reachable through only uniform branches.
117/// XXX - Is there a more efficient way to find this?
118static bool isUniformlyReached(const UniformityInfo &UA, BasicBlock &BB) {
121
122 while (!Stack.empty()) {
123 BasicBlock *Top = Stack.pop_back_val();
124 if (!UA.isUniform(Top->getTerminator()))
125 return false;
126
127 for (BasicBlock *Pred : predecessors(Top)) {
128 if (Visited.insert(Pred).second)
129 Stack.push_back(Pred);
130 }
131 }
132
133 return true;
134}
135
136BasicBlock *AMDGPUUnifyDivergentExitNodesImpl::unifyReturnBlockSet(
137 Function &F, DomTreeUpdater &DTU, ArrayRef<BasicBlock *> ReturningBlocks,
138 StringRef Name) {
139 // Otherwise, we need to insert a new basic block into the function, add a PHI
140 // nodes (if the function returns values), and convert all of the return
141 // instructions into unconditional branches.
142 BasicBlock *NewRetBlock = BasicBlock::Create(F.getContext(), Name, &F);
143 IRBuilder<> B(NewRetBlock);
144
145 PHINode *PN = nullptr;
146 if (F.getReturnType()->isVoidTy()) {
147 B.CreateRetVoid();
148 } else {
149 // If the function doesn't return void... add a PHI node to the block...
150 PN = B.CreatePHI(F.getReturnType(), ReturningBlocks.size(),
151 "UnifiedRetVal");
152 B.CreateRet(PN);
153 }
154
155 // Loop over all of the blocks, replacing the return instruction with an
156 // unconditional branch.
157 std::vector<DominatorTree::UpdateType> Updates;
158 Updates.reserve(ReturningBlocks.size());
159 for (BasicBlock *BB : ReturningBlocks) {
160 // Add an incoming element to the PHI node for every return instruction that
161 // is merging into this new block...
162 if (PN)
163 PN->addIncoming(BB->getTerminator()->getOperand(0), BB);
164
165 // Remove and delete the return inst.
166 BB->getTerminator()->eraseFromParent();
167 BranchInst::Create(NewRetBlock, BB);
168 Updates.emplace_back(DominatorTree::Insert, BB, NewRetBlock);
169 }
170
172 DTU.applyUpdates(Updates);
173 Updates.clear();
174
175 for (BasicBlock *BB : ReturningBlocks) {
176 // Cleanup possible branch to unconditional branch to the return.
177 simplifyCFG(BB, *TTI, RequireAndPreserveDomTree ? &DTU : nullptr,
178 SimplifyCFGOptions().bonusInstThreshold(2));
179 }
180
181 return NewRetBlock;
182}
183
184static BasicBlock *
186 SmallVector<BasicBlock *, 4> &ReturningBlocks) {
187 BasicBlock *DummyReturnBB =
188 BasicBlock::Create(F.getContext(), "DummyReturnBlock", &F);
189 Type *RetTy = F.getReturnType();
190 Value *RetVal = RetTy->isVoidTy() ? nullptr : PoisonValue::get(RetTy);
191 ReturnInst::Create(F.getContext(), RetVal, DummyReturnBB);
192 ReturningBlocks.push_back(DummyReturnBB);
193 return DummyReturnBB;
194}
195
196/// Handle conditional branch instructions (-> 2 targets) and callbr
197/// instructions with N targets.
199 BasicBlock *DummyReturnBB,
200 std::vector<DominatorTree::UpdateType> &Updates) {
202
203 // Create a new transition block to hold the conditional branch.
204 BasicBlock *TransitionBB = BB->splitBasicBlock(BI, "TransitionBlock");
205
206 Updates.reserve(Updates.size() + 2 * Successors.size() + 2);
207
208 // 'Successors' become successors of TransitionBB instead of BB,
209 // and TransitionBB becomes a single successor of BB.
210 Updates.emplace_back(DominatorTree::Insert, BB, TransitionBB);
211 for (BasicBlock *Successor : Successors) {
212 Updates.emplace_back(DominatorTree::Insert, TransitionBB, Successor);
213 Updates.emplace_back(DominatorTree::Delete, BB, Successor);
214 }
215
216 // Create a branch that will always branch to the transition block and
217 // references DummyReturnBB.
219 BranchInst::Create(TransitionBB, DummyReturnBB,
220 ConstantInt::getTrue(F.getContext()), BB);
221 Updates.emplace_back(DominatorTree::Insert, BB, DummyReturnBB);
222}
223
224bool AMDGPUUnifyDivergentExitNodesImpl::run(Function &F, DominatorTree *DT,
225 const PostDominatorTree &PDT,
226 const UniformityInfo &UA) {
227 if (PDT.root_size() == 0 ||
228 (PDT.root_size() == 1 &&
229 !isa<BranchInst, CallBrInst>(PDT.getRoot()->getTerminator())))
230 return false;
231
232 // Loop over all of the blocks in a function, tracking all of the blocks that
233 // return.
234 SmallVector<BasicBlock *, 4> ReturningBlocks;
235 SmallVector<BasicBlock *, 4> UnreachableBlocks;
236
237 // Dummy return block for infinite loop.
238 BasicBlock *DummyReturnBB = nullptr;
239
240 bool Changed = false;
241 std::vector<DominatorTree::UpdateType> Updates;
242
243 // TODO: For now we unify all exit blocks, even though they are uniformly
244 // reachable, if there are any exits not uniformly reached. This is to
245 // workaround the limitation of structurizer, which can not handle multiple
246 // function exits. After structurizer is able to handle multiple function
247 // exits, we should only unify UnreachableBlocks that are not uniformly
248 // reachable.
249 bool HasDivergentExitBlock = llvm::any_of(
250 PDT.roots(), [&](auto BB) { return !isUniformlyReached(UA, *BB); });
251
252 for (BasicBlock *BB : PDT.roots()) {
253 if (auto *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
254 auto *CI = dyn_cast_or_null<CallInst>(RI->getPrevNode());
255 if (CI && CI->isMustTailCall())
256 continue;
257 if (HasDivergentExitBlock)
258 ReturningBlocks.push_back(BB);
259 } else if (isa<UnreachableInst>(BB->getTerminator())) {
260 if (HasDivergentExitBlock)
261 UnreachableBlocks.push_back(BB);
262 } else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
263 if (!DummyReturnBB)
264 DummyReturnBB = createDummyReturnBlock(F, ReturningBlocks);
265
266 if (BI->isUnconditional()) {
267 BasicBlock *LoopHeaderBB = BI->getSuccessor(0);
268 BI->eraseFromParent(); // Delete the unconditional branch.
269 // Add a new conditional branch with a dummy edge to the return block.
270 BranchInst::Create(LoopHeaderBB, DummyReturnBB,
271 ConstantInt::getTrue(F.getContext()), BB);
272 Updates.emplace_back(DominatorTree::Insert, BB, DummyReturnBB);
273 } else {
274 handleNBranch(F, BB, BI, DummyReturnBB, Updates);
275 }
276 Changed = true;
277 } else if (CallBrInst *CBI = dyn_cast<CallBrInst>(BB->getTerminator())) {
278 if (!DummyReturnBB)
279 DummyReturnBB = createDummyReturnBlock(F, ReturningBlocks);
280
281 handleNBranch(F, BB, CBI, DummyReturnBB, Updates);
282 Changed = true;
283 } else {
284 llvm_unreachable("unsupported block terminator");
285 }
286 }
287
288 if (!UnreachableBlocks.empty()) {
289 BasicBlock *UnreachableBlock = nullptr;
290
291 if (UnreachableBlocks.size() == 1) {
292 UnreachableBlock = UnreachableBlocks.front();
293 } else {
294 UnreachableBlock = BasicBlock::Create(F.getContext(),
295 "UnifiedUnreachableBlock", &F);
296 new UnreachableInst(F.getContext(), UnreachableBlock);
297
298 Updates.reserve(Updates.size() + UnreachableBlocks.size());
299 for (BasicBlock *BB : UnreachableBlocks) {
300 // Remove and delete the unreachable inst.
301 BB->getTerminator()->eraseFromParent();
302 BranchInst::Create(UnreachableBlock, BB);
303 Updates.emplace_back(DominatorTree::Insert, BB, UnreachableBlock);
304 }
305 Changed = true;
306 }
307
308 if (!ReturningBlocks.empty()) {
309 // Don't create a new unreachable inst if we have a return. The
310 // structurizer/annotator can't handle the multiple exits
311
312 Type *RetTy = F.getReturnType();
313 Value *RetVal = RetTy->isVoidTy() ? nullptr : PoisonValue::get(RetTy);
314 // Remove and delete the unreachable inst.
315 UnreachableBlock->getTerminator()->eraseFromParent();
316
317 Function *UnreachableIntrin = Intrinsic::getOrInsertDeclaration(
318 F.getParent(), Intrinsic::amdgcn_unreachable);
319
320 // Insert a call to an intrinsic tracking that this is an unreachable
321 // point, in case we want to kill the active lanes or something later.
322 CallInst::Create(UnreachableIntrin, {}, "", UnreachableBlock);
323
324 // Don't create a scalar trap. We would only want to trap if this code was
325 // really reached, but a scalar trap would happen even if no lanes
326 // actually reached here.
327 ReturnInst::Create(F.getContext(), RetVal, UnreachableBlock);
328 ReturningBlocks.push_back(UnreachableBlock);
329 Changed = true;
330 }
331 }
332
333 // FIXME: add PDT here once simplifycfg is ready.
334 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
336 DTU.applyUpdates(Updates);
337 Updates.clear();
338
339 // Now handle return blocks.
340 if (ReturningBlocks.empty())
341 return Changed; // No blocks return
342
343 if (ReturningBlocks.size() == 1)
344 return Changed; // Already has a single return block
345
346 unifyReturnBlockSet(F, DTU, ReturningBlocks, "UnifiedReturnBlock");
347 return true;
348}
349
350bool AMDGPUUnifyDivergentExitNodes::runOnFunction(Function &F) {
351 DominatorTree *DT = nullptr;
353 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
354 const auto &PDT =
355 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
356 const auto &UA = getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
357 const auto *TranformInfo =
358 &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
359 return AMDGPUUnifyDivergentExitNodesImpl(TranformInfo).run(F, DT, PDT, UA);
360}
361
362PreservedAnalyses
365 DominatorTree *DT = nullptr;
368
369 const auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
370 const auto &UA = AM.getResult<UniformityInfoAnalysis>(F);
371 const auto *TransformInfo = &AM.getResult<TargetIRAnalysis>(F);
372 return AMDGPUUnifyDivergentExitNodesImpl(TransformInfo).run(F, DT, PDT, UA)
375}
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)
#define DEBUG_TYPE
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
#define F(x, y, z)
Definition MD5.cpp:55
if(PassOpts->AAPipeline)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This pass exposes codegen information to IR-level passes.
LLVM IR instance of the generic uniformity analysis.
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),...
Definition ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition ArrayRef.h:143
LLVM Basic Block Representation.
Definition BasicBlock.h:62
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="", bool Before=false)
Split the basic block into two basic blocks at the specified instruction.
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:233
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
Analysis pass which computes a DominatorTree.
Definition Dominators.h:284
iterator_range< root_iterator > roots()
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:322
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:165
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
bool isUniform(ConstValueRefT V) const
Whether V is uniform/non-divergent.
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...
Definition Pass.cpp:112
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.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
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.
Definition StringRef.h:55
Analysis pass providing the TargetTransformInfo.
LLVM_ABI Result run(const Function &F, FunctionAnalysisManager &)
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:45
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:139
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
LLVM Value Representation.
Definition Value.h:75
Changed
#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.
Definition CallingConv.h:24
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
char & AMDGPUUnifyDivergentExitNodesID
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1732
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...
Definition Casting.h:547
TargetTransformInfo TTI
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.