LLVM 24.0.0git
AMDGPURewriteUndefForPHI.cpp
Go to the documentation of this file.
1//===- AMDGPURewriteUndefForPHI.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// This file implements the idea to rewrite undef incoming operand for certain
9// PHIs in structurized CFG. This pass only works on IR that has gone through
10// StructurizedCFG pass, and this pass has some additional limitation that make
11// it can only run after SIAnnotateControlFlow.
12//
13// To achieve optimal code generation for AMDGPU, we assume that uniformity
14// analysis reports the PHI in join block of divergent branch as uniform if
15// it has one unique uniform value plus additional undefined/poisoned incoming
16// value. That is to say the later compiler pipeline will ensure such PHI always
17// return uniform value and ensure it work correctly. Let's take a look at two
18// typical patterns in structured CFG that need to be taken care: (In both
19// patterns, block %if terminate with divergent branch.)
20//
21// Pattern A: Block with undefined incoming value dominates defined predecessor
22// %if
23// | \
24// | %then
25// | /
26// %endif: %phi = phi [%undef, %if], [%uniform, %then]
27//
28// Pattern B: Block with defined incoming value dominates undefined predecessor
29// %if
30// | \
31// | %then
32// | /
33// %endif: %phi = phi [%uniform, %if], [%undef, %then]
34//
35// For pattern A, by reporting %phi as uniform, the later pipeline need to make
36// sure it be handled correctly. The backend usually allocates a scalar register
37// and if any thread in a wave takes %then path, the scalar register will get
38// the %uniform value.
39//
40// For pattern B, we will replace the undef operand with the other defined value
41// in this pass. So the scalar register allocated for such PHI will get correct
42// liveness. Without this transformation, the scalar register may be overwritten
43// in the %then block.
44//
45// Limitation note:
46// If the join block of divergent threads is a loop header, the pass cannot
47// handle it correctly right now. For below case, the undef in %phi should also
48// be rewritten. Currently we depend on SIAnnotateControlFlow to split %header
49// block to get a separate join block, then we can rewrite the undef correctly.
50// %if
51// | \
52// | %then
53// | /
54// -> %header: %phi = phi [%uniform, %if], [%undef, %then], [%uniform2, %header]
55// | |
56// \---
57
58#include "AMDGPU.h"
60#include "llvm/IR/BasicBlock.h"
61#include "llvm/IR/Constants.h"
62#include "llvm/IR/Dominators.h"
65
66using namespace llvm;
67
68#define DEBUG_TYPE "amdgpu-rewrite-undef-for-phi"
69
70namespace {
71
72class AMDGPURewriteUndefForPHILegacy : public FunctionPass {
73public:
74 static char ID;
75 AMDGPURewriteUndefForPHILegacy() : FunctionPass(ID) {}
76 bool runOnFunction(Function &F) override;
77 StringRef getPassName() const override {
78 return "AMDGPU Rewrite Undef for PHI";
79 }
80
81 void getAnalysisUsage(AnalysisUsage &AU) const override {
84
85 AU.setPreservesCFG();
86 }
87};
88
89} // end anonymous namespace
90char AMDGPURewriteUndefForPHILegacy::ID = 0;
91
92INITIALIZE_PASS_BEGIN(AMDGPURewriteUndefForPHILegacy, DEBUG_TYPE,
93 "Rewrite undef for PHI", false, false)
96INITIALIZE_PASS_END(AMDGPURewriteUndefForPHILegacy, DEBUG_TYPE,
97 "Rewrite undef for PHI", false, false)
98
100 bool Changed = false;
101 SmallVector<PHINode *> ToBeDeleted;
102 for (auto &BB : F) {
103 for (auto &PHI : BB.phis()) {
104 if (UA.isDivergentAtDef(&PHI))
105 continue;
106
107 // The unique incoming value except undef/poison for the PHI node.
108 Value *UniqueDefinedIncoming = nullptr;
109 // The divergent block with defined incoming value that dominates all
110 // other block with the same incoming value.
111 BasicBlock *DominateBB = nullptr;
112 // Predecessors with undefined incoming value (excluding loop backedge).
114
115 for (unsigned i = 0; i < PHI.getNumIncomingValues(); i++) {
116 Value *Incoming = PHI.getIncomingValue(i);
117 BasicBlock *IncomingBB = PHI.getIncomingBlock(i);
118
119 if (Incoming == &PHI)
120 continue;
121
122 if (isa<UndefValue>(Incoming)) {
123 // Undef from loop backedge will not be replaced.
124 if (!DT->dominates(&BB, IncomingBB))
125 Undefs.push_back(IncomingBB);
126 continue;
127 }
128
129 if (!UniqueDefinedIncoming) {
130 UniqueDefinedIncoming = Incoming;
131 DominateBB = IncomingBB;
132 } else if (Incoming == UniqueDefinedIncoming) {
133 // Update DominateBB if necessary.
134 if (DT->dominates(IncomingBB, DominateBB))
135 DominateBB = IncomingBB;
136 } else {
137 UniqueDefinedIncoming = nullptr;
138 break;
139 }
140 }
141 // We only need to replace the undef for the PHI which is merging
142 // defined/undefined values from divergent threads.
143 // TODO: We should still be able to replace undef value if the unique
144 // value is a Constant.
145 if (!UniqueDefinedIncoming || Undefs.empty() ||
146 UA.isUniformTerminator(DominateBB->getTerminator()))
147 continue;
148
149 // We only replace the undef when DominateBB truly dominates all the
150 // other predecessors with undefined incoming value. Make sure DominateBB
151 // dominates BB so that UniqueDefinedIncoming is available in BB and
152 // afterwards.
153 if (DT->dominates(DominateBB, &BB) && all_of(Undefs, [&](BasicBlock *UD) {
154 return DT->dominates(DominateBB, UD);
155 })) {
156 PHI.replaceAllUsesWith(UniqueDefinedIncoming);
157 ToBeDeleted.push_back(&PHI);
158 Changed = true;
159 }
160 }
161 }
162
163 for (auto *PHI : ToBeDeleted)
164 PHI->eraseFromParent();
165
166 return Changed;
167}
168
169bool AMDGPURewriteUndefForPHILegacy::runOnFunction(Function &F) {
170 UniformityInfo &UA =
171 getAnalysis<UniformityInfoWrapperPass>().getUniformityInfo();
172 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
173 return rewritePHIs(F, UA, DT);
174}
175
176PreservedAnalyses
189
191 return new AMDGPURewriteUndefForPHILegacy();
192}
Rewrite undef for false bool rewritePHIs(Function &F, UniformityInfo &UA, DominatorTree *DT)
Rewrite undef for PHI
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
#define F(x, y, z)
Definition MD5.cpp:54
#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
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.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass which computes UniformityInfo.
Legacy analysis pass which computes a CycleInfo.
LLVM Value Representation.
Definition Value.h:75
Changed
This is an optimization pass for GlobalISel generic memory operations.
GenericUniformityInfo< SSAContext > UniformityInfo
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
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
FunctionPass * createAMDGPURewriteUndefForPHILegacyPass()
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.