LegacyDivergenceAnalysis.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
  67. #include "llvm/ADT/PostOrderIterator.h"
  68. #include "llvm/Analysis/CFG.h"
  69. #include "llvm/Analysis/DivergenceAnalysis.h"
  70. #include "llvm/Analysis/LoopInfo.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/CommandLine.h"
  80. #include "llvm/Support/Debug.h"
  81. #include "llvm/Support/raw_ostream.h"
  82. #include <vector>
  83. using namespace llvm;
  84. #define DEBUG_TYPE "divergence"
  85. // transparently use the GPUDivergenceAnalysis
  86. static cl::opt<bool> UseGPUDA("use-gpu-divergence-analysis", cl::init(false),
  87. cl::Hidden,
  88. cl::desc("turn the LegacyDivergenceAnalysis into "
  89. "a wrapper for GPUDivergenceAnalysis"));
  90. namespace {
  91. class DivergencePropagator {
  92. public:
  93. DivergencePropagator(Function &F, TargetTransformInfo &TTI, DominatorTree &DT,
  94. PostDominatorTree &PDT, DenseSet<const Value *> &DV,
  95. DenseSet<const Use *> &DU)
  96. : F(F), TTI(TTI), DT(DT), PDT(PDT), DV(DV), DU(DU) {}
  97. void populateWithSourcesOfDivergence();
  98. void propagate();
  99. private:
  100. // A helper function that explores data dependents of V.
  101. void exploreDataDependency(Value *V);
  102. // A helper function that explores sync dependents of TI.
  103. void exploreSyncDependency(Instruction *TI);
  104. // Computes the influence region from Start to End. This region includes all
  105. // basic blocks on any simple path from Start to End.
  106. void computeInfluenceRegion(BasicBlock *Start, BasicBlock *End,
  107. DenseSet<BasicBlock *> &InfluenceRegion);
  108. // Finds all users of I that are outside the influence region, and add these
  109. // users to Worklist.
  110. void findUsersOutsideInfluenceRegion(
  111. Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion);
  112. Function &F;
  113. TargetTransformInfo &TTI;
  114. DominatorTree &DT;
  115. PostDominatorTree &PDT;
  116. std::vector<Value *> Worklist; // Stack for DFS.
  117. DenseSet<const Value *> &DV; // Stores all divergent values.
  118. DenseSet<const Use *> &DU; // Stores divergent uses of possibly uniform
  119. // values.
  120. };
  121. void DivergencePropagator::populateWithSourcesOfDivergence() {
  122. Worklist.clear();
  123. DV.clear();
  124. DU.clear();
  125. for (auto &I : instructions(F)) {
  126. if (TTI.isSourceOfDivergence(&I)) {
  127. Worklist.push_back(&I);
  128. DV.insert(&I);
  129. }
  130. }
  131. for (auto &Arg : F.args()) {
  132. if (TTI.isSourceOfDivergence(&Arg)) {
  133. Worklist.push_back(&Arg);
  134. DV.insert(&Arg);
  135. }
  136. }
  137. }
  138. void DivergencePropagator::exploreSyncDependency(Instruction *TI) {
  139. // Propagation rule 1: if branch TI is divergent, all PHINodes in TI's
  140. // immediate post dominator are divergent. This rule handles if-then-else
  141. // patterns. For example,
  142. //
  143. // if (tid < 5)
  144. // a1 = 1;
  145. // else
  146. // a2 = 2;
  147. // a = phi(a1, a2); // sync dependent on (tid < 5)
  148. BasicBlock *ThisBB = TI->getParent();
  149. // Unreachable blocks may not be in the dominator tree.
  150. if (!DT.isReachableFromEntry(ThisBB))
  151. return;
  152. // If the function has no exit blocks or doesn't reach any exit blocks, the
  153. // post dominator may be null.
  154. DomTreeNode *ThisNode = PDT.getNode(ThisBB);
  155. if (!ThisNode)
  156. return;
  157. BasicBlock *IPostDom = ThisNode->getIDom()->getBlock();
  158. if (IPostDom == nullptr)
  159. return;
  160. for (auto I = IPostDom->begin(); isa<PHINode>(I); ++I) {
  161. // A PHINode is uniform if it returns the same value no matter which path is
  162. // taken.
  163. if (!cast<PHINode>(I)->hasConstantOrUndefValue() && DV.insert(&*I).second)
  164. Worklist.push_back(&*I);
  165. }
  166. // Propagation rule 2: if a value defined in a loop is used outside, the user
  167. // is sync dependent on the condition of the loop exits that dominate the
  168. // user. For example,
  169. //
  170. // int i = 0;
  171. // do {
  172. // i++;
  173. // if (foo(i)) ... // uniform
  174. // } while (i < tid);
  175. // if (bar(i)) ... // divergent
  176. //
  177. // A program may contain unstructured loops. Therefore, we cannot leverage
  178. // LoopInfo, which only recognizes natural loops.
  179. //
  180. // The algorithm used here handles both natural and unstructured loops. Given
  181. // a branch TI, we first compute its influence region, the union of all simple
  182. // paths from TI to its immediate post dominator (IPostDom). Then, we search
  183. // for all the values defined in the influence region but used outside. All
  184. // these users are sync dependent on TI.
  185. DenseSet<BasicBlock *> InfluenceRegion;
  186. computeInfluenceRegion(ThisBB, IPostDom, InfluenceRegion);
  187. // An insight that can speed up the search process is that all the in-region
  188. // values that are used outside must dominate TI. Therefore, instead of
  189. // searching every basic blocks in the influence region, we search all the
  190. // dominators of TI until it is outside the influence region.
  191. BasicBlock *InfluencedBB = ThisBB;
  192. while (InfluenceRegion.count(InfluencedBB)) {
  193. for (auto &I : *InfluencedBB) {
  194. if (!DV.count(&I))
  195. findUsersOutsideInfluenceRegion(I, InfluenceRegion);
  196. }
  197. DomTreeNode *IDomNode = DT.getNode(InfluencedBB)->getIDom();
  198. if (IDomNode == nullptr)
  199. break;
  200. InfluencedBB = IDomNode->getBlock();
  201. }
  202. }
  203. void DivergencePropagator::findUsersOutsideInfluenceRegion(
  204. Instruction &I, const DenseSet<BasicBlock *> &InfluenceRegion) {
  205. for (Use &Use : I.uses()) {
  206. Instruction *UserInst = cast<Instruction>(Use.getUser());
  207. if (!InfluenceRegion.count(UserInst->getParent())) {
  208. DU.insert(&Use);
  209. if (DV.insert(UserInst).second)
  210. Worklist.push_back(UserInst);
  211. }
  212. }
  213. }
  214. // A helper function for computeInfluenceRegion that adds successors of "ThisBB"
  215. // to the influence region.
  216. static void
  217. addSuccessorsToInfluenceRegion(BasicBlock *ThisBB, BasicBlock *End,
  218. DenseSet<BasicBlock *> &InfluenceRegion,
  219. std::vector<BasicBlock *> &InfluenceStack) {
  220. for (BasicBlock *Succ : successors(ThisBB)) {
  221. if (Succ != End && InfluenceRegion.insert(Succ).second)
  222. InfluenceStack.push_back(Succ);
  223. }
  224. }
  225. void DivergencePropagator::computeInfluenceRegion(
  226. BasicBlock *Start, BasicBlock *End,
  227. DenseSet<BasicBlock *> &InfluenceRegion) {
  228. assert(PDT.properlyDominates(End, Start) &&
  229. "End does not properly dominate Start");
  230. // The influence region starts from the end of "Start" to the beginning of
  231. // "End". Therefore, "Start" should not be in the region unless "Start" is in
  232. // a loop that doesn't contain "End".
  233. std::vector<BasicBlock *> InfluenceStack;
  234. addSuccessorsToInfluenceRegion(Start, End, InfluenceRegion, InfluenceStack);
  235. while (!InfluenceStack.empty()) {
  236. BasicBlock *BB = InfluenceStack.back();
  237. InfluenceStack.pop_back();
  238. addSuccessorsToInfluenceRegion(BB, End, InfluenceRegion, InfluenceStack);
  239. }
  240. }
  241. void DivergencePropagator::exploreDataDependency(Value *V) {
  242. // Follow def-use chains of V.
  243. for (User *U : V->users()) {
  244. if (!TTI.isAlwaysUniform(U) && DV.insert(U).second)
  245. Worklist.push_back(U);
  246. }
  247. }
  248. void DivergencePropagator::propagate() {
  249. // Traverse the dependency graph using DFS.
  250. while (!Worklist.empty()) {
  251. Value *V = Worklist.back();
  252. Worklist.pop_back();
  253. if (Instruction *I = dyn_cast<Instruction>(V)) {
  254. // Terminators with less than two successors won't introduce sync
  255. // dependency. Ignore them.
  256. if (I->isTerminator() && I->getNumSuccessors() > 1)
  257. exploreSyncDependency(I);
  258. }
  259. exploreDataDependency(V);
  260. }
  261. }
  262. } // namespace
  263. // Register this pass.
  264. char LegacyDivergenceAnalysis::ID = 0;
  265. LegacyDivergenceAnalysis::LegacyDivergenceAnalysis() : FunctionPass(ID) {
  266. initializeLegacyDivergenceAnalysisPass(*PassRegistry::getPassRegistry());
  267. }
  268. INITIALIZE_PASS_BEGIN(LegacyDivergenceAnalysis, "divergence",
  269. "Legacy Divergence Analysis", false, true)
  270. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  271. INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
  272. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  273. INITIALIZE_PASS_END(LegacyDivergenceAnalysis, "divergence",
  274. "Legacy Divergence Analysis", false, true)
  275. FunctionPass *llvm::createLegacyDivergenceAnalysisPass() {
  276. return new LegacyDivergenceAnalysis();
  277. }
  278. bool LegacyDivergenceAnalysisImpl::shouldUseGPUDivergenceAnalysis(
  279. const Function &F, const TargetTransformInfo &TTI, const LoopInfo &LI) {
  280. if (!(UseGPUDA || TTI.useGPUDivergenceAnalysis()))
  281. return false;
  282. // GPUDivergenceAnalysis requires a reducible CFG.
  283. using RPOTraversal = ReversePostOrderTraversal<const Function *>;
  284. RPOTraversal FuncRPOT(&F);
  285. return !containsIrreducibleCFG<const BasicBlock *, const RPOTraversal,
  286. const LoopInfo>(FuncRPOT, LI);
  287. }
  288. void LegacyDivergenceAnalysisImpl::run(Function &F,
  289. llvm::TargetTransformInfo &TTI,
  290. llvm::DominatorTree &DT,
  291. llvm::PostDominatorTree &PDT,
  292. const llvm::LoopInfo &LI) {
  293. if (shouldUseGPUDivergenceAnalysis(F, TTI, LI)) {
  294. // run the new GPU divergence analysis
  295. gpuDA = std::make_unique<DivergenceInfo>(F, DT, PDT, LI, TTI,
  296. /* KnownReducible = */ true);
  297. } else {
  298. // run LLVM's existing DivergenceAnalysis
  299. DivergencePropagator DP(F, TTI, DT, PDT, DivergentValues, DivergentUses);
  300. DP.populateWithSourcesOfDivergence();
  301. DP.propagate();
  302. }
  303. }
  304. bool LegacyDivergenceAnalysisImpl::isDivergent(const Value *V) const {
  305. if (gpuDA) {
  306. return gpuDA->isDivergent(*V);
  307. }
  308. return DivergentValues.count(V);
  309. }
  310. bool LegacyDivergenceAnalysisImpl::isDivergentUse(const Use *U) const {
  311. if (gpuDA) {
  312. return gpuDA->isDivergentUse(*U);
  313. }
  314. return DivergentValues.count(U->get()) || DivergentUses.count(U);
  315. }
  316. void LegacyDivergenceAnalysisImpl::print(raw_ostream &OS,
  317. const Module *) const {
  318. if ((!gpuDA || !gpuDA->hasDivergence()) && DivergentValues.empty())
  319. return;
  320. const Function *F = nullptr;
  321. if (!DivergentValues.empty()) {
  322. const Value *FirstDivergentValue = *DivergentValues.begin();
  323. if (const Argument *Arg = dyn_cast<Argument>(FirstDivergentValue)) {
  324. F = Arg->getParent();
  325. } else if (const Instruction *I =
  326. dyn_cast<Instruction>(FirstDivergentValue)) {
  327. F = I->getParent()->getParent();
  328. } else {
  329. llvm_unreachable("Only arguments and instructions can be divergent");
  330. }
  331. } else if (gpuDA) {
  332. F = &gpuDA->getFunction();
  333. }
  334. if (!F)
  335. return;
  336. // Dumps all divergent values in F, arguments and then instructions.
  337. for (const auto &Arg : F->args()) {
  338. OS << (isDivergent(&Arg) ? "DIVERGENT: " : " ");
  339. OS << Arg << "\n";
  340. }
  341. // Iterate instructions using instructions() to ensure a deterministic order.
  342. for (const BasicBlock &BB : *F) {
  343. OS << "\n " << BB.getName() << ":\n";
  344. for (const auto &I : BB.instructionsWithoutDebug()) {
  345. OS << (isDivergent(&I) ? "DIVERGENT: " : " ");
  346. OS << I << "\n";
  347. }
  348. }
  349. OS << "\n";
  350. }
  351. void LegacyDivergenceAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  352. AU.addRequiredTransitive<DominatorTreeWrapperPass>();
  353. AU.addRequiredTransitive<PostDominatorTreeWrapperPass>();
  354. AU.addRequiredTransitive<LoopInfoWrapperPass>();
  355. AU.setPreservesAll();
  356. }
  357. bool LegacyDivergenceAnalysis::runOnFunction(Function &F) {
  358. auto *TTIWP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
  359. if (TTIWP == nullptr)
  360. return false;
  361. TargetTransformInfo &TTI = TTIWP->getTTI(F);
  362. // Fast path: if the target does not have branch divergence, we do not mark
  363. // any branch as divergent.
  364. if (!TTI.hasBranchDivergence())
  365. return false;
  366. DivergentValues.clear();
  367. DivergentUses.clear();
  368. gpuDA = nullptr;
  369. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  370. auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
  371. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  372. LegacyDivergenceAnalysisImpl::run(F, TTI, DT, PDT, LI);
  373. LLVM_DEBUG(dbgs() << "\nAfter divergence analysis on " << F.getName()
  374. << ":\n";
  375. LegacyDivergenceAnalysisImpl::print(dbgs(), F.getParent()));
  376. return false;
  377. }
  378. PreservedAnalyses
  379. LegacyDivergenceAnalysisPass::run(Function &F, FunctionAnalysisManager &AM) {
  380. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  381. if (!TTI.hasBranchDivergence())
  382. return PreservedAnalyses::all();
  383. DivergentValues.clear();
  384. DivergentUses.clear();
  385. gpuDA = nullptr;
  386. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  387. auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
  388. auto &LI = AM.getResult<LoopAnalysis>(F);
  389. LegacyDivergenceAnalysisImpl::run(F, TTI, DT, PDT, LI);
  390. LLVM_DEBUG(dbgs() << "\nAfter divergence analysis on " << F.getName()
  391. << ":\n";
  392. LegacyDivergenceAnalysisImpl::print(dbgs(), F.getParent()));
  393. return PreservedAnalyses::all();
  394. }