1 //===- LegacyDivergenceAnalysis.cpp --------- Legacy Divergence Analysis
2 //Implementation -==//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements divergence analysis which determines whether a branch
11 // in a GPU program is divergent.It can help branch optimizations such as jump
12 // threading and loop unswitching to make better decisions.
13 //
14 // GPU programs typically use the SIMD execution model, where multiple threads
15 // in the same execution group have to execute in lock-step. Therefore, if the
16 // code contains divergent branches (i.e., threads in a group do not agree on
17 // which path of the branch to take), the group of threads has to execute all
18 // the paths from that branch with different subsets of threads enabled until
19 // they converge at the immediately post-dominating BB of the paths.
20 //
21 // Due to this execution model, some optimizations such as jump
22 // threading and loop unswitching can be unfortunately harmful when performed on
23 // divergent branches. Therefore, an analysis that computes which branches in a
24 // GPU program are divergent can help the compiler to selectively run these
25 // optimizations.
26 //
27 // This file defines divergence analysis which computes a conservative but
28 // non-trivial approximation of all divergent branches in a GPU program. It
29 // partially implements the approach described in
30 //
31 //   Divergence Analysis
32 //   Sampaio, Souza, Collange, Pereira
33 //   TOPLAS '13
34 //
35 // The divergence analysis identifies the sources of divergence (e.g., special
36 // variables that hold the thread ID), and recursively marks variables that are
37 // data or sync dependent on a source of divergence as divergent.
38 //
39 // While data dependency is a well-known concept, the notion of sync dependency
40 // is worth more explanation. Sync dependence characterizes the control flow
41 // aspect of the propagation of branch divergence. For example,
42 //
43 //   %cond = icmp slt i32 %tid, 10
44 //   br i1 %cond, label %then, label %else
45 // then:
46 //   br label %merge
47 // else:
48 //   br label %merge
49 // merge:
50 //   %a = phi i32 [ 0, %then ], [ 1, %else ]
51 //
52 // Suppose %tid holds the thread ID. Although %a is not data dependent on %tid
53 // because %tid is not on its use-def chains, %a is sync dependent on %tid
54 // because the branch "br i1 %cond" depends on %tid and affects which value %a
55 // is assigned to.
56 //
57 // The current implementation has the following limitations:
58 // 1. intra-procedural. It conservatively considers the arguments of a
59 //    non-kernel-entry function and the return value of a function call as
60 //    divergent.
61 // 2. memory as black box. It conservatively considers values loaded from
62 //    generic or local address as divergent. This can be improved by leveraging
63 //    pointer analysis.
64 //
65 //===----------------------------------------------------------------------===//
66 
67 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
68 #include "llvm/ADT/PostOrderIterator.h"
69 #include "llvm/Analysis/CFG.h"
70 #include "llvm/Analysis/DivergenceAnalysis.h"
71 #include "llvm/Analysis/Passes.h"
72 #include "llvm/Analysis/PostDominators.h"
73 #include "llvm/Analysis/TargetTransformInfo.h"
74 #include "llvm/IR/Dominators.h"
75 #include "llvm/IR/InstIterator.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/Value.h"
78 #include "llvm/InitializePasses.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/raw_ostream.h"
81 #include <vector>
82 using namespace llvm;
83 
84 #define DEBUG_TYPE "divergence"
85 
86 // transparently use the GPUDivergenceAnalysis
87 static cl::opt<bool> UseGPUDA("use-gpu-divergence-analysis", cl::init(false),
88                               cl::Hidden,
89                               cl::desc("turn the LegacyDivergenceAnalysis into "
90                                        "a wrapper for GPUDivergenceAnalysis"));
91 
92 namespace {
93 
94 class DivergencePropagator {
95 public:
96   DivergencePropagator(Function &F, TargetTransformInfo &TTI, DominatorTree &DT,
97                        PostDominatorTree &PDT, DenseSet<const Value *> &DV,
98                        DenseSet<const Use *> &DU)
99       : F(F), TTI(TTI), DT(DT), PDT(PDT), DV(DV), DU(DU) {}
100   void populateWithSourcesOfDivergence();
101   void propagate();
102 
103 private:
104   // A helper function that explores data dependents of V.
105   void exploreDataDependency(Value *V);
106   // A helper function that explores sync dependents of TI.
107   void exploreSyncDependency(Instruction *TI);
108   // Computes the influence region from Start to End. This region includes all
109   // basic blocks on any simple path from Start to End.
110   void computeInfluenceRegion(BasicBlock *Start, BasicBlock *End,
111                               DenseSet<BasicBlock *> &InfluenceRegion);
112   // Finds all users of I that are outside the influence region, and add these
113   // users to Worklist.
114   void findUsersOutsideInfluenceRegion(
115       Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion);
116 
117   Function &F;
118   TargetTransformInfo &TTI;
119   DominatorTree &DT;
120   PostDominatorTree &PDT;
121   std::vector<Value *> Worklist; // Stack for DFS.
122   DenseSet<const Value *> &DV;   // Stores all divergent values.
123   DenseSet<const Use *> &DU;   // Stores divergent uses of possibly uniform
124                                // values.
125 };
126 
127 void DivergencePropagator::populateWithSourcesOfDivergence() {
128   Worklist.clear();
129   DV.clear();
130   DU.clear();
131   for (auto &I : instructions(F)) {
132     if (TTI.isSourceOfDivergence(&I)) {
133       Worklist.push_back(&I);
134       DV.insert(&I);
135     }
136   }
137   for (auto &Arg : F.args()) {
138     if (TTI.isSourceOfDivergence(&Arg)) {
139       Worklist.push_back(&Arg);
140       DV.insert(&Arg);
141     }
142   }
143 }
144 
145 void DivergencePropagator::exploreSyncDependency(Instruction *TI) {
146   // Propagation rule 1: if branch TI is divergent, all PHINodes in TI's
147   // immediate post dominator are divergent. This rule handles if-then-else
148   // patterns. For example,
149   //
150   // if (tid < 5)
151   //   a1 = 1;
152   // else
153   //   a2 = 2;
154   // a = phi(a1, a2); // sync dependent on (tid < 5)
155   BasicBlock *ThisBB = TI->getParent();
156 
157   // Unreachable blocks may not be in the dominator tree.
158   if (!DT.isReachableFromEntry(ThisBB))
159     return;
160 
161   // If the function has no exit blocks or doesn't reach any exit blocks, the
162   // post dominator may be null.
163   DomTreeNode *ThisNode = PDT.getNode(ThisBB);
164   if (!ThisNode)
165     return;
166 
167   BasicBlock *IPostDom = ThisNode->getIDom()->getBlock();
168   if (IPostDom == nullptr)
169     return;
170 
171   for (auto I = IPostDom->begin(); isa<PHINode>(I); ++I) {
172     // A PHINode is uniform if it returns the same value no matter which path is
173     // taken.
174     if (!cast<PHINode>(I)->hasConstantOrUndefValue() && DV.insert(&*I).second)
175       Worklist.push_back(&*I);
176   }
177 
178   // Propagation rule 2: if a value defined in a loop is used outside, the user
179   // is sync dependent on the condition of the loop exits that dominate the
180   // user. For example,
181   //
182   // int i = 0;
183   // do {
184   //   i++;
185   //   if (foo(i)) ... // uniform
186   // } while (i < tid);
187   // if (bar(i)) ...   // divergent
188   //
189   // A program may contain unstructured loops. Therefore, we cannot leverage
190   // LoopInfo, which only recognizes natural loops.
191   //
192   // The algorithm used here handles both natural and unstructured loops.  Given
193   // a branch TI, we first compute its influence region, the union of all simple
194   // paths from TI to its immediate post dominator (IPostDom). Then, we search
195   // for all the values defined in the influence region but used outside. All
196   // these users are sync dependent on TI.
197   DenseSet<BasicBlock *> InfluenceRegion;
198   computeInfluenceRegion(ThisBB, IPostDom, InfluenceRegion);
199   // An insight that can speed up the search process is that all the in-region
200   // values that are used outside must dominate TI. Therefore, instead of
201   // searching every basic blocks in the influence region, we search all the
202   // dominators of TI until it is outside the influence region.
203   BasicBlock *InfluencedBB = ThisBB;
204   while (InfluenceRegion.count(InfluencedBB)) {
205     for (auto &I : *InfluencedBB) {
206       if (!DV.count(&I))
207         findUsersOutsideInfluenceRegion(I, InfluenceRegion);
208     }
209     DomTreeNode *IDomNode = DT.getNode(InfluencedBB)->getIDom();
210     if (IDomNode == nullptr)
211       break;
212     InfluencedBB = IDomNode->getBlock();
213   }
214 }
215 
216 void DivergencePropagator::findUsersOutsideInfluenceRegion(
217     Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion) {
218   for (Use &Use : I.uses()) {
219     Instruction *UserInst = cast<Instruction>(Use.getUser());
220     if (!InfluenceRegion.count(UserInst->getParent())) {
221       DU.insert(&Use);
222       if (DV.insert(UserInst).second)
223         Worklist.push_back(UserInst);
224     }
225   }
226 }
227 
228 // A helper function for computeInfluenceRegion that adds successors of "ThisBB"
229 // to the influence region.
230 static void
231 addSuccessorsToInfluenceRegion(BasicBlock *ThisBB, BasicBlock *End,
232                                DenseSet<BasicBlock *> &InfluenceRegion,
233                                std::vector<BasicBlock *> &InfluenceStack) {
234   for (BasicBlock *Succ : successors(ThisBB)) {
235     if (Succ != End && InfluenceRegion.insert(Succ).second)
236       InfluenceStack.push_back(Succ);
237   }
238 }
239 
240 void DivergencePropagator::computeInfluenceRegion(
241     BasicBlock *Start, BasicBlock *End,
242     DenseSet<BasicBlock *> &InfluenceRegion) {
243   assert(PDT.properlyDominates(End, Start) &&
244          "End does not properly dominate Start");
245 
246   // The influence region starts from the end of "Start" to the beginning of
247   // "End". Therefore, "Start" should not be in the region unless "Start" is in
248   // a loop that doesn't contain "End".
249   std::vector<BasicBlock *> InfluenceStack;
250   addSuccessorsToInfluenceRegion(Start, End, InfluenceRegion, InfluenceStack);
251   while (!InfluenceStack.empty()) {
252     BasicBlock *BB = InfluenceStack.back();
253     InfluenceStack.pop_back();
254     addSuccessorsToInfluenceRegion(BB, End, InfluenceRegion, InfluenceStack);
255   }
256 }
257 
258 void DivergencePropagator::exploreDataDependency(Value *V) {
259   // Follow def-use chains of V.
260   for (User *U : V->users()) {
261     if (!TTI.isAlwaysUniform(U) && DV.insert(U).second)
262       Worklist.push_back(U);
263   }
264 }
265 
266 void DivergencePropagator::propagate() {
267   // Traverse the dependency graph using DFS.
268   while (!Worklist.empty()) {
269     Value *V = Worklist.back();
270     Worklist.pop_back();
271     if (Instruction *I = dyn_cast<Instruction>(V)) {
272       // Terminators with less than two successors won't introduce sync
273       // dependency. Ignore them.
274       if (I->isTerminator() && I->getNumSuccessors() > 1)
275         exploreSyncDependency(I);
276     }
277     exploreDataDependency(V);
278   }
279 }
280 
281 } // namespace
282 
283 // Register this pass.
284 char LegacyDivergenceAnalysis::ID = 0;
285 LegacyDivergenceAnalysis::LegacyDivergenceAnalysis() : FunctionPass(ID) {
286   initializeLegacyDivergenceAnalysisPass(*PassRegistry::getPassRegistry());
287 }
288 INITIALIZE_PASS_BEGIN(LegacyDivergenceAnalysis, "divergence",
289                       "Legacy Divergence Analysis", false, true)
290 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
291 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
292 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
293 INITIALIZE_PASS_END(LegacyDivergenceAnalysis, "divergence",
294                     "Legacy Divergence Analysis", false, true)
295 
296 FunctionPass *llvm::createLegacyDivergenceAnalysisPass() {
297   return new LegacyDivergenceAnalysis();
298 }
299 
300 void LegacyDivergenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
301   AU.addRequired<DominatorTreeWrapperPass>();
302   AU.addRequired<PostDominatorTreeWrapperPass>();
303   if (UseGPUDA)
304     AU.addRequired<LoopInfoWrapperPass>();
305   AU.setPreservesAll();
306 }
307 
308 bool LegacyDivergenceAnalysis::shouldUseGPUDivergenceAnalysis(
309     const Function &F) const {
310   if (!UseGPUDA)
311     return false;
312 
313   // GPUDivergenceAnalysis requires a reducible CFG.
314   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
315   using RPOTraversal = ReversePostOrderTraversal<const Function *>;
316   RPOTraversal FuncRPOT(&F);
317   return !containsIrreducibleCFG<const BasicBlock *, const RPOTraversal,
318                                  const LoopInfo>(FuncRPOT, LI);
319 }
320 
321 bool LegacyDivergenceAnalysis::runOnFunction(Function &F) {
322   auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
323   if (TTIWP == nullptr)
324     return false;
325 
326   TargetTransformInfo &TTI = TTIWP->getTTI(F);
327   // Fast path: if the target does not have branch divergence, we do not mark
328   // any branch as divergent.
329   if (!TTI.hasBranchDivergence())
330     return false;
331 
332   DivergentValues.clear();
333   DivergentUses.clear();
334   gpuDA = nullptr;
335 
336   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
337   auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
338 
339   if (shouldUseGPUDivergenceAnalysis(F)) {
340     // run the new GPU divergence analysis
341     auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
342     gpuDA = std::make_unique<GPUDivergenceAnalysis>(F, DT, PDT, LI, TTI);
343 
344   } else {
345     // run LLVM's existing DivergenceAnalysis
346     DivergencePropagator DP(F, TTI, DT, PDT, DivergentValues, DivergentUses);
347     DP.populateWithSourcesOfDivergence();
348     DP.propagate();
349   }
350 
351   LLVM_DEBUG(dbgs() << "\nAfter divergence analysis on " << F.getName()
352                     << ":\n";
353              print(dbgs(), F.getParent()));
354 
355   return false;
356 }
357 
358 bool LegacyDivergenceAnalysis::isDivergent(const Value *V) const {
359   if (gpuDA) {
360     return gpuDA->isDivergent(*V);
361   }
362   return DivergentValues.count(V);
363 }
364 
365 bool LegacyDivergenceAnalysis::isDivergentUse(const Use *U) const {
366   if (gpuDA) {
367     return gpuDA->isDivergentUse(*U);
368   }
369   return DivergentValues.count(U->get()) || DivergentUses.count(U);
370 }
371 
372 void LegacyDivergenceAnalysis::print(raw_ostream &OS, const Module *) const {
373   if ((!gpuDA || !gpuDA->hasDivergence()) && DivergentValues.empty())
374     return;
375 
376   const Function *F = nullptr;
377   if (!DivergentValues.empty()) {
378     const Value *FirstDivergentValue = *DivergentValues.begin();
379     if (const Argument *Arg = dyn_cast<Argument>(FirstDivergentValue)) {
380       F = Arg->getParent();
381     } else if (const Instruction *I =
382                    dyn_cast<Instruction>(FirstDivergentValue)) {
383       F = I->getParent()->getParent();
384     } else {
385       llvm_unreachable("Only arguments and instructions can be divergent");
386     }
387   } else if (gpuDA) {
388     F = &gpuDA->getFunction();
389   }
390   if (!F)
391     return;
392 
393   // Dumps all divergent values in F, arguments and then instructions.
394   for (auto &Arg : F->args()) {
395     OS << (isDivergent(&Arg) ? "DIVERGENT: " : "           ");
396     OS << Arg << "\n";
397   }
398   // Iterate instructions using instructions() to ensure a deterministic order.
399   for (auto BI = F->begin(), BE = F->end(); BI != BE; ++BI) {
400     auto &BB = *BI;
401     OS << "\n           " << BB.getName() << ":\n";
402     for (auto &I : BB.instructionsWithoutDebug()) {
403       OS << (isDivergent(&I) ? "DIVERGENT:     " : "               ");
404       OS << I << "\n";
405     }
406   }
407   OS << "\n";
408 }
409