PredicateInfo.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. //===-- PredicateInfo.cpp - PredicateInfo Builder--------------------===//
  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 file implements the PredicateInfo class.
  10. //
  11. //===----------------------------------------------------------------===//
  12. #include "llvm/Transforms/Utils/PredicateInfo.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/DepthFirstIterator.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallPtrSet.h"
  17. #include "llvm/Analysis/AssumptionCache.h"
  18. #include "llvm/IR/AssemblyAnnotationWriter.h"
  19. #include "llvm/IR/Dominators.h"
  20. #include "llvm/IR/IRBuilder.h"
  21. #include "llvm/IR/InstIterator.h"
  22. #include "llvm/IR/IntrinsicInst.h"
  23. #include "llvm/IR/Module.h"
  24. #include "llvm/IR/PatternMatch.h"
  25. #include "llvm/InitializePasses.h"
  26. #include "llvm/Support/CommandLine.h"
  27. #include "llvm/Support/Debug.h"
  28. #include "llvm/Support/DebugCounter.h"
  29. #include "llvm/Support/FormattedStream.h"
  30. #include <algorithm>
  31. #define DEBUG_TYPE "predicateinfo"
  32. using namespace llvm;
  33. using namespace PatternMatch;
  34. INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
  35. "PredicateInfo Printer", false, false)
  36. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  37. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  38. INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
  39. "PredicateInfo Printer", false, false)
  40. static cl::opt<bool> VerifyPredicateInfo(
  41. "verify-predicateinfo", cl::init(false), cl::Hidden,
  42. cl::desc("Verify PredicateInfo in legacy printer pass."));
  43. DEBUG_COUNTER(RenameCounter, "predicateinfo-rename",
  44. "Controls which variables are renamed with predicateinfo");
  45. // Maximum number of conditions considered for renaming for each branch/assume.
  46. // This limits renaming of deep and/or chains.
  47. static const unsigned MaxCondsPerBranch = 8;
  48. namespace {
  49. // Given a predicate info that is a type of branching terminator, get the
  50. // branching block.
  51. const BasicBlock *getBranchBlock(const PredicateBase *PB) {
  52. assert(isa<PredicateWithEdge>(PB) &&
  53. "Only branches and switches should have PHIOnly defs that "
  54. "require branch blocks.");
  55. return cast<PredicateWithEdge>(PB)->From;
  56. }
  57. // Given a predicate info that is a type of branching terminator, get the
  58. // branching terminator.
  59. static Instruction *getBranchTerminator(const PredicateBase *PB) {
  60. assert(isa<PredicateWithEdge>(PB) &&
  61. "Not a predicate info type we know how to get a terminator from.");
  62. return cast<PredicateWithEdge>(PB)->From->getTerminator();
  63. }
  64. // Given a predicate info that is a type of branching terminator, get the
  65. // edge this predicate info represents
  66. std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const PredicateBase *PB) {
  67. assert(isa<PredicateWithEdge>(PB) &&
  68. "Not a predicate info type we know how to get an edge from.");
  69. const auto *PEdge = cast<PredicateWithEdge>(PB);
  70. return std::make_pair(PEdge->From, PEdge->To);
  71. }
  72. }
  73. namespace llvm {
  74. enum LocalNum {
  75. // Operations that must appear first in the block.
  76. LN_First,
  77. // Operations that are somewhere in the middle of the block, and are sorted on
  78. // demand.
  79. LN_Middle,
  80. // Operations that must appear last in a block, like successor phi node uses.
  81. LN_Last
  82. };
  83. // Associate global and local DFS info with defs and uses, so we can sort them
  84. // into a global domination ordering.
  85. struct ValueDFS {
  86. int DFSIn = 0;
  87. int DFSOut = 0;
  88. unsigned int LocalNum = LN_Middle;
  89. // Only one of Def or Use will be set.
  90. Value *Def = nullptr;
  91. Use *U = nullptr;
  92. // Neither PInfo nor EdgeOnly participate in the ordering
  93. PredicateBase *PInfo = nullptr;
  94. bool EdgeOnly = false;
  95. };
  96. // Perform a strict weak ordering on instructions and arguments.
  97. static bool valueComesBefore(const Value *A, const Value *B) {
  98. auto *ArgA = dyn_cast_or_null<Argument>(A);
  99. auto *ArgB = dyn_cast_or_null<Argument>(B);
  100. if (ArgA && !ArgB)
  101. return true;
  102. if (ArgB && !ArgA)
  103. return false;
  104. if (ArgA && ArgB)
  105. return ArgA->getArgNo() < ArgB->getArgNo();
  106. return cast<Instruction>(A)->comesBefore(cast<Instruction>(B));
  107. }
  108. // This compares ValueDFS structures. Doing so allows us to walk the minimum
  109. // number of instructions necessary to compute our def/use ordering.
  110. struct ValueDFS_Compare {
  111. DominatorTree &DT;
  112. ValueDFS_Compare(DominatorTree &DT) : DT(DT) {}
  113. bool operator()(const ValueDFS &A, const ValueDFS &B) const {
  114. if (&A == &B)
  115. return false;
  116. // The only case we can't directly compare them is when they in the same
  117. // block, and both have localnum == middle. In that case, we have to use
  118. // comesbefore to see what the real ordering is, because they are in the
  119. // same basic block.
  120. assert((A.DFSIn != B.DFSIn || A.DFSOut == B.DFSOut) &&
  121. "Equal DFS-in numbers imply equal out numbers");
  122. bool SameBlock = A.DFSIn == B.DFSIn;
  123. // We want to put the def that will get used for a given set of phi uses,
  124. // before those phi uses.
  125. // So we sort by edge, then by def.
  126. // Note that only phi nodes uses and defs can come last.
  127. if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
  128. return comparePHIRelated(A, B);
  129. bool isADef = A.Def;
  130. bool isBDef = B.Def;
  131. if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
  132. return std::tie(A.DFSIn, A.LocalNum, isADef) <
  133. std::tie(B.DFSIn, B.LocalNum, isBDef);
  134. return localComesBefore(A, B);
  135. }
  136. // For a phi use, or a non-materialized def, return the edge it represents.
  137. std::pair<BasicBlock *, BasicBlock *> getBlockEdge(const ValueDFS &VD) const {
  138. if (!VD.Def && VD.U) {
  139. auto *PHI = cast<PHINode>(VD.U->getUser());
  140. return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
  141. }
  142. // This is really a non-materialized def.
  143. return ::getBlockEdge(VD.PInfo);
  144. }
  145. // For two phi related values, return the ordering.
  146. bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
  147. BasicBlock *ASrc, *ADest, *BSrc, *BDest;
  148. std::tie(ASrc, ADest) = getBlockEdge(A);
  149. std::tie(BSrc, BDest) = getBlockEdge(B);
  150. #ifndef NDEBUG
  151. // This function should only be used for values in the same BB, check that.
  152. DomTreeNode *DomASrc = DT.getNode(ASrc);
  153. DomTreeNode *DomBSrc = DT.getNode(BSrc);
  154. assert(DomASrc->getDFSNumIn() == (unsigned)A.DFSIn &&
  155. "DFS numbers for A should match the ones of the source block");
  156. assert(DomBSrc->getDFSNumIn() == (unsigned)B.DFSIn &&
  157. "DFS numbers for B should match the ones of the source block");
  158. assert(A.DFSIn == B.DFSIn && "Values must be in the same block");
  159. #endif
  160. (void)ASrc;
  161. (void)BSrc;
  162. // Use DFS numbers to compare destination blocks, to guarantee a
  163. // deterministic order.
  164. DomTreeNode *DomADest = DT.getNode(ADest);
  165. DomTreeNode *DomBDest = DT.getNode(BDest);
  166. unsigned AIn = DomADest->getDFSNumIn();
  167. unsigned BIn = DomBDest->getDFSNumIn();
  168. bool isADef = A.Def;
  169. bool isBDef = B.Def;
  170. assert((!A.Def || !A.U) && (!B.Def || !B.U) &&
  171. "Def and U cannot be set at the same time");
  172. // Now sort by edge destination and then defs before uses.
  173. return std::tie(AIn, isADef) < std::tie(BIn, isBDef);
  174. }
  175. // Get the definition of an instruction that occurs in the middle of a block.
  176. Value *getMiddleDef(const ValueDFS &VD) const {
  177. if (VD.Def)
  178. return VD.Def;
  179. // It's possible for the defs and uses to be null. For branches, the local
  180. // numbering will say the placed predicaeinfos should go first (IE
  181. // LN_beginning), so we won't be in this function. For assumes, we will end
  182. // up here, beause we need to order the def we will place relative to the
  183. // assume. So for the purpose of ordering, we pretend the def is right
  184. // after the assume, because that is where we will insert the info.
  185. if (!VD.U) {
  186. assert(VD.PInfo &&
  187. "No def, no use, and no predicateinfo should not occur");
  188. assert(isa<PredicateAssume>(VD.PInfo) &&
  189. "Middle of block should only occur for assumes");
  190. return cast<PredicateAssume>(VD.PInfo)->AssumeInst->getNextNode();
  191. }
  192. return nullptr;
  193. }
  194. // Return either the Def, if it's not null, or the user of the Use, if the def
  195. // is null.
  196. const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
  197. if (Def)
  198. return cast<Instruction>(Def);
  199. return cast<Instruction>(U->getUser());
  200. }
  201. // This performs the necessary local basic block ordering checks to tell
  202. // whether A comes before B, where both are in the same basic block.
  203. bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
  204. auto *ADef = getMiddleDef(A);
  205. auto *BDef = getMiddleDef(B);
  206. // See if we have real values or uses. If we have real values, we are
  207. // guaranteed they are instructions or arguments. No matter what, we are
  208. // guaranteed they are in the same block if they are instructions.
  209. auto *ArgA = dyn_cast_or_null<Argument>(ADef);
  210. auto *ArgB = dyn_cast_or_null<Argument>(BDef);
  211. if (ArgA || ArgB)
  212. return valueComesBefore(ArgA, ArgB);
  213. auto *AInst = getDefOrUser(ADef, A.U);
  214. auto *BInst = getDefOrUser(BDef, B.U);
  215. return valueComesBefore(AInst, BInst);
  216. }
  217. };
  218. class PredicateInfoBuilder {
  219. // Used to store information about each value we might rename.
  220. struct ValueInfo {
  221. SmallVector<PredicateBase *, 4> Infos;
  222. };
  223. PredicateInfo &PI;
  224. Function &F;
  225. DominatorTree &DT;
  226. AssumptionCache &AC;
  227. // This stores info about each operand or comparison result we make copies
  228. // of. The real ValueInfos start at index 1, index 0 is unused so that we
  229. // can more easily detect invalid indexing.
  230. SmallVector<ValueInfo, 32> ValueInfos;
  231. // This gives the index into the ValueInfos array for a given Value. Because
  232. // 0 is not a valid Value Info index, you can use DenseMap::lookup and tell
  233. // whether it returned a valid result.
  234. DenseMap<Value *, unsigned int> ValueInfoNums;
  235. // The set of edges along which we can only handle phi uses, due to critical
  236. // edges.
  237. DenseSet<std::pair<BasicBlock *, BasicBlock *>> EdgeUsesOnly;
  238. ValueInfo &getOrCreateValueInfo(Value *);
  239. const ValueInfo &getValueInfo(Value *) const;
  240. void processAssume(IntrinsicInst *, BasicBlock *,
  241. SmallVectorImpl<Value *> &OpsToRename);
  242. void processBranch(BranchInst *, BasicBlock *,
  243. SmallVectorImpl<Value *> &OpsToRename);
  244. void processSwitch(SwitchInst *, BasicBlock *,
  245. SmallVectorImpl<Value *> &OpsToRename);
  246. void renameUses(SmallVectorImpl<Value *> &OpsToRename);
  247. void addInfoFor(SmallVectorImpl<Value *> &OpsToRename, Value *Op,
  248. PredicateBase *PB);
  249. typedef SmallVectorImpl<ValueDFS> ValueDFSStack;
  250. void convertUsesToDFSOrdered(Value *, SmallVectorImpl<ValueDFS> &);
  251. Value *materializeStack(unsigned int &, ValueDFSStack &, Value *);
  252. bool stackIsInScope(const ValueDFSStack &, const ValueDFS &) const;
  253. void popStackUntilDFSScope(ValueDFSStack &, const ValueDFS &);
  254. public:
  255. PredicateInfoBuilder(PredicateInfo &PI, Function &F, DominatorTree &DT,
  256. AssumptionCache &AC)
  257. : PI(PI), F(F), DT(DT), AC(AC) {
  258. // Push an empty operand info so that we can detect 0 as not finding one
  259. ValueInfos.resize(1);
  260. }
  261. void buildPredicateInfo();
  262. };
  263. bool PredicateInfoBuilder::stackIsInScope(const ValueDFSStack &Stack,
  264. const ValueDFS &VDUse) const {
  265. if (Stack.empty())
  266. return false;
  267. // If it's a phi only use, make sure it's for this phi node edge, and that the
  268. // use is in a phi node. If it's anything else, and the top of the stack is
  269. // EdgeOnly, we need to pop the stack. We deliberately sort phi uses next to
  270. // the defs they must go with so that we can know it's time to pop the stack
  271. // when we hit the end of the phi uses for a given def.
  272. if (Stack.back().EdgeOnly) {
  273. if (!VDUse.U)
  274. return false;
  275. auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
  276. if (!PHI)
  277. return false;
  278. // Check edge
  279. BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
  280. if (EdgePred != getBranchBlock(Stack.back().PInfo))
  281. return false;
  282. // Use dominates, which knows how to handle edge dominance.
  283. return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U);
  284. }
  285. return (VDUse.DFSIn >= Stack.back().DFSIn &&
  286. VDUse.DFSOut <= Stack.back().DFSOut);
  287. }
  288. void PredicateInfoBuilder::popStackUntilDFSScope(ValueDFSStack &Stack,
  289. const ValueDFS &VD) {
  290. while (!Stack.empty() && !stackIsInScope(Stack, VD))
  291. Stack.pop_back();
  292. }
  293. // Convert the uses of Op into a vector of uses, associating global and local
  294. // DFS info with each one.
  295. void PredicateInfoBuilder::convertUsesToDFSOrdered(
  296. Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
  297. for (auto &U : Op->uses()) {
  298. if (auto *I = dyn_cast<Instruction>(U.getUser())) {
  299. ValueDFS VD;
  300. // Put the phi node uses in the incoming block.
  301. BasicBlock *IBlock;
  302. if (auto *PN = dyn_cast<PHINode>(I)) {
  303. IBlock = PN->getIncomingBlock(U);
  304. // Make phi node users appear last in the incoming block
  305. // they are from.
  306. VD.LocalNum = LN_Last;
  307. } else {
  308. // If it's not a phi node use, it is somewhere in the middle of the
  309. // block.
  310. IBlock = I->getParent();
  311. VD.LocalNum = LN_Middle;
  312. }
  313. DomTreeNode *DomNode = DT.getNode(IBlock);
  314. // It's possible our use is in an unreachable block. Skip it if so.
  315. if (!DomNode)
  316. continue;
  317. VD.DFSIn = DomNode->getDFSNumIn();
  318. VD.DFSOut = DomNode->getDFSNumOut();
  319. VD.U = &U;
  320. DFSOrderedSet.push_back(VD);
  321. }
  322. }
  323. }
  324. bool shouldRename(Value *V) {
  325. // Only want real values, not constants. Additionally, operands with one use
  326. // are only being used in the comparison, which means they will not be useful
  327. // for us to consider for predicateinfo.
  328. return (isa<Instruction>(V) || isa<Argument>(V)) && !V->hasOneUse();
  329. }
  330. // Collect relevant operations from Comparison that we may want to insert copies
  331. // for.
  332. void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
  333. auto *Op0 = Comparison->getOperand(0);
  334. auto *Op1 = Comparison->getOperand(1);
  335. if (Op0 == Op1)
  336. return;
  337. CmpOperands.push_back(Op0);
  338. CmpOperands.push_back(Op1);
  339. }
  340. // Add Op, PB to the list of value infos for Op, and mark Op to be renamed.
  341. void PredicateInfoBuilder::addInfoFor(SmallVectorImpl<Value *> &OpsToRename,
  342. Value *Op, PredicateBase *PB) {
  343. auto &OperandInfo = getOrCreateValueInfo(Op);
  344. if (OperandInfo.Infos.empty())
  345. OpsToRename.push_back(Op);
  346. PI.AllInfos.push_back(PB);
  347. OperandInfo.Infos.push_back(PB);
  348. }
  349. // Process an assume instruction and place relevant operations we want to rename
  350. // into OpsToRename.
  351. void PredicateInfoBuilder::processAssume(
  352. IntrinsicInst *II, BasicBlock *AssumeBB,
  353. SmallVectorImpl<Value *> &OpsToRename) {
  354. SmallVector<Value *, 4> Worklist;
  355. SmallPtrSet<Value *, 4> Visited;
  356. Worklist.push_back(II->getOperand(0));
  357. while (!Worklist.empty()) {
  358. Value *Cond = Worklist.pop_back_val();
  359. if (!Visited.insert(Cond).second)
  360. continue;
  361. if (Visited.size() > MaxCondsPerBranch)
  362. break;
  363. Value *Op0, *Op1;
  364. if (match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
  365. Worklist.push_back(Op1);
  366. Worklist.push_back(Op0);
  367. }
  368. SmallVector<Value *, 4> Values;
  369. Values.push_back(Cond);
  370. if (auto *Cmp = dyn_cast<CmpInst>(Cond))
  371. collectCmpOps(Cmp, Values);
  372. for (Value *V : Values) {
  373. if (shouldRename(V)) {
  374. auto *PA = new PredicateAssume(V, II, Cond);
  375. addInfoFor(OpsToRename, V, PA);
  376. }
  377. }
  378. }
  379. }
  380. // Process a block terminating branch, and place relevant operations to be
  381. // renamed into OpsToRename.
  382. void PredicateInfoBuilder::processBranch(
  383. BranchInst *BI, BasicBlock *BranchBB,
  384. SmallVectorImpl<Value *> &OpsToRename) {
  385. BasicBlock *FirstBB = BI->getSuccessor(0);
  386. BasicBlock *SecondBB = BI->getSuccessor(1);
  387. for (BasicBlock *Succ : {FirstBB, SecondBB}) {
  388. bool TakenEdge = Succ == FirstBB;
  389. // Don't try to insert on a self-edge. This is mainly because we will
  390. // eliminate during renaming anyway.
  391. if (Succ == BranchBB)
  392. continue;
  393. SmallVector<Value *, 4> Worklist;
  394. SmallPtrSet<Value *, 4> Visited;
  395. Worklist.push_back(BI->getCondition());
  396. while (!Worklist.empty()) {
  397. Value *Cond = Worklist.pop_back_val();
  398. if (!Visited.insert(Cond).second)
  399. continue;
  400. if (Visited.size() > MaxCondsPerBranch)
  401. break;
  402. Value *Op0, *Op1;
  403. if (TakenEdge ? match(Cond, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))
  404. : match(Cond, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
  405. Worklist.push_back(Op1);
  406. Worklist.push_back(Op0);
  407. }
  408. SmallVector<Value *, 4> Values;
  409. Values.push_back(Cond);
  410. if (auto *Cmp = dyn_cast<CmpInst>(Cond))
  411. collectCmpOps(Cmp, Values);
  412. for (Value *V : Values) {
  413. if (shouldRename(V)) {
  414. PredicateBase *PB =
  415. new PredicateBranch(V, BranchBB, Succ, Cond, TakenEdge);
  416. addInfoFor(OpsToRename, V, PB);
  417. if (!Succ->getSinglePredecessor())
  418. EdgeUsesOnly.insert({BranchBB, Succ});
  419. }
  420. }
  421. }
  422. }
  423. }
  424. // Process a block terminating switch, and place relevant operations to be
  425. // renamed into OpsToRename.
  426. void PredicateInfoBuilder::processSwitch(
  427. SwitchInst *SI, BasicBlock *BranchBB,
  428. SmallVectorImpl<Value *> &OpsToRename) {
  429. Value *Op = SI->getCondition();
  430. if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse())
  431. return;
  432. // Remember how many outgoing edges there are to every successor.
  433. SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
  434. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  435. BasicBlock *TargetBlock = SI->getSuccessor(i);
  436. ++SwitchEdges[TargetBlock];
  437. }
  438. // Now propagate info for each case value
  439. for (auto C : SI->cases()) {
  440. BasicBlock *TargetBlock = C.getCaseSuccessor();
  441. if (SwitchEdges.lookup(TargetBlock) == 1) {
  442. PredicateSwitch *PS = new PredicateSwitch(
  443. Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI);
  444. addInfoFor(OpsToRename, Op, PS);
  445. if (!TargetBlock->getSinglePredecessor())
  446. EdgeUsesOnly.insert({BranchBB, TargetBlock});
  447. }
  448. }
  449. }
  450. // Build predicate info for our function
  451. void PredicateInfoBuilder::buildPredicateInfo() {
  452. DT.updateDFSNumbers();
  453. // Collect operands to rename from all conditional branch terminators, as well
  454. // as assume statements.
  455. SmallVector<Value *, 8> OpsToRename;
  456. for (auto *DTN : depth_first(DT.getRootNode())) {
  457. BasicBlock *BranchBB = DTN->getBlock();
  458. if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
  459. if (!BI->isConditional())
  460. continue;
  461. // Can't insert conditional information if they all go to the same place.
  462. if (BI->getSuccessor(0) == BI->getSuccessor(1))
  463. continue;
  464. processBranch(BI, BranchBB, OpsToRename);
  465. } else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) {
  466. processSwitch(SI, BranchBB, OpsToRename);
  467. }
  468. }
  469. for (auto &Assume : AC.assumptions()) {
  470. if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
  471. if (DT.isReachableFromEntry(II->getParent()))
  472. processAssume(II, II->getParent(), OpsToRename);
  473. }
  474. // Now rename all our operations.
  475. renameUses(OpsToRename);
  476. }
  477. // Given the renaming stack, make all the operands currently on the stack real
  478. // by inserting them into the IR. Return the last operation's value.
  479. Value *PredicateInfoBuilder::materializeStack(unsigned int &Counter,
  480. ValueDFSStack &RenameStack,
  481. Value *OrigOp) {
  482. // Find the first thing we have to materialize
  483. auto RevIter = RenameStack.rbegin();
  484. for (; RevIter != RenameStack.rend(); ++RevIter)
  485. if (RevIter->Def)
  486. break;
  487. size_t Start = RevIter - RenameStack.rbegin();
  488. // The maximum number of things we should be trying to materialize at once
  489. // right now is 4, depending on if we had an assume, a branch, and both used
  490. // and of conditions.
  491. for (auto RenameIter = RenameStack.end() - Start;
  492. RenameIter != RenameStack.end(); ++RenameIter) {
  493. auto *Op =
  494. RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
  495. ValueDFS &Result = *RenameIter;
  496. auto *ValInfo = Result.PInfo;
  497. ValInfo->RenamedOp = (RenameStack.end() - Start) == RenameStack.begin()
  498. ? OrigOp
  499. : (RenameStack.end() - Start - 1)->Def;
  500. // For edge predicates, we can just place the operand in the block before
  501. // the terminator. For assume, we have to place it right before the assume
  502. // to ensure we dominate all of our uses. Always insert right before the
  503. // relevant instruction (terminator, assume), so that we insert in proper
  504. // order in the case of multiple predicateinfo in the same block.
  505. // The number of named values is used to detect if a new declaration was
  506. // added. If so, that declaration is tracked so that it can be removed when
  507. // the analysis is done. The corner case were a new declaration results in
  508. // a name clash and the old name being renamed is not considered as that
  509. // represents an invalid module.
  510. if (isa<PredicateWithEdge>(ValInfo)) {
  511. IRBuilder<> B(getBranchTerminator(ValInfo));
  512. auto NumDecls = F.getParent()->getNumNamedValues();
  513. Function *IF = Intrinsic::getDeclaration(
  514. F.getParent(), Intrinsic::ssa_copy, Op->getType());
  515. if (NumDecls != F.getParent()->getNumNamedValues())
  516. PI.CreatedDeclarations.insert(IF);
  517. CallInst *PIC =
  518. B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
  519. PI.PredicateMap.insert({PIC, ValInfo});
  520. Result.Def = PIC;
  521. } else {
  522. auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
  523. assert(PAssume &&
  524. "Should not have gotten here without it being an assume");
  525. // Insert the predicate directly after the assume. While it also holds
  526. // directly before it, assume(i1 true) is not a useful fact.
  527. IRBuilder<> B(PAssume->AssumeInst->getNextNode());
  528. auto NumDecls = F.getParent()->getNumNamedValues();
  529. Function *IF = Intrinsic::getDeclaration(
  530. F.getParent(), Intrinsic::ssa_copy, Op->getType());
  531. if (NumDecls != F.getParent()->getNumNamedValues())
  532. PI.CreatedDeclarations.insert(IF);
  533. CallInst *PIC = B.CreateCall(IF, Op);
  534. PI.PredicateMap.insert({PIC, ValInfo});
  535. Result.Def = PIC;
  536. }
  537. }
  538. return RenameStack.back().Def;
  539. }
  540. // Instead of the standard SSA renaming algorithm, which is O(Number of
  541. // instructions), and walks the entire dominator tree, we walk only the defs +
  542. // uses. The standard SSA renaming algorithm does not really rely on the
  543. // dominator tree except to order the stack push/pops of the renaming stacks, so
  544. // that defs end up getting pushed before hitting the correct uses. This does
  545. // not require the dominator tree, only the *order* of the dominator tree. The
  546. // complete and correct ordering of the defs and uses, in dominator tree is
  547. // contained in the DFS numbering of the dominator tree. So we sort the defs and
  548. // uses into the DFS ordering, and then just use the renaming stack as per
  549. // normal, pushing when we hit a def (which is a predicateinfo instruction),
  550. // popping when we are out of the dfs scope for that def, and replacing any uses
  551. // with top of stack if it exists. In order to handle liveness without
  552. // propagating liveness info, we don't actually insert the predicateinfo
  553. // instruction def until we see a use that it would dominate. Once we see such
  554. // a use, we materialize the predicateinfo instruction in the right place and
  555. // use it.
  556. //
  557. // TODO: Use this algorithm to perform fast single-variable renaming in
  558. // promotememtoreg and memoryssa.
  559. void PredicateInfoBuilder::renameUses(SmallVectorImpl<Value *> &OpsToRename) {
  560. ValueDFS_Compare Compare(DT);
  561. // Compute liveness, and rename in O(uses) per Op.
  562. for (auto *Op : OpsToRename) {
  563. LLVM_DEBUG(dbgs() << "Visiting " << *Op << "\n");
  564. unsigned Counter = 0;
  565. SmallVector<ValueDFS, 16> OrderedUses;
  566. const auto &ValueInfo = getValueInfo(Op);
  567. // Insert the possible copies into the def/use list.
  568. // They will become real copies if we find a real use for them, and never
  569. // created otherwise.
  570. for (const auto &PossibleCopy : ValueInfo.Infos) {
  571. ValueDFS VD;
  572. // Determine where we are going to place the copy by the copy type.
  573. // The predicate info for branches always come first, they will get
  574. // materialized in the split block at the top of the block.
  575. // The predicate info for assumes will be somewhere in the middle,
  576. // it will get materialized in front of the assume.
  577. if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
  578. VD.LocalNum = LN_Middle;
  579. DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
  580. if (!DomNode)
  581. continue;
  582. VD.DFSIn = DomNode->getDFSNumIn();
  583. VD.DFSOut = DomNode->getDFSNumOut();
  584. VD.PInfo = PossibleCopy;
  585. OrderedUses.push_back(VD);
  586. } else if (isa<PredicateWithEdge>(PossibleCopy)) {
  587. // If we can only do phi uses, we treat it like it's in the branch
  588. // block, and handle it specially. We know that it goes last, and only
  589. // dominate phi uses.
  590. auto BlockEdge = getBlockEdge(PossibleCopy);
  591. if (EdgeUsesOnly.count(BlockEdge)) {
  592. VD.LocalNum = LN_Last;
  593. auto *DomNode = DT.getNode(BlockEdge.first);
  594. if (DomNode) {
  595. VD.DFSIn = DomNode->getDFSNumIn();
  596. VD.DFSOut = DomNode->getDFSNumOut();
  597. VD.PInfo = PossibleCopy;
  598. VD.EdgeOnly = true;
  599. OrderedUses.push_back(VD);
  600. }
  601. } else {
  602. // Otherwise, we are in the split block (even though we perform
  603. // insertion in the branch block).
  604. // Insert a possible copy at the split block and before the branch.
  605. VD.LocalNum = LN_First;
  606. auto *DomNode = DT.getNode(BlockEdge.second);
  607. if (DomNode) {
  608. VD.DFSIn = DomNode->getDFSNumIn();
  609. VD.DFSOut = DomNode->getDFSNumOut();
  610. VD.PInfo = PossibleCopy;
  611. OrderedUses.push_back(VD);
  612. }
  613. }
  614. }
  615. }
  616. convertUsesToDFSOrdered(Op, OrderedUses);
  617. // Here we require a stable sort because we do not bother to try to
  618. // assign an order to the operands the uses represent. Thus, two
  619. // uses in the same instruction do not have a strict sort order
  620. // currently and will be considered equal. We could get rid of the
  621. // stable sort by creating one if we wanted.
  622. llvm::stable_sort(OrderedUses, Compare);
  623. SmallVector<ValueDFS, 8> RenameStack;
  624. // For each use, sorted into dfs order, push values and replaces uses with
  625. // top of stack, which will represent the reaching def.
  626. for (auto &VD : OrderedUses) {
  627. // We currently do not materialize copy over copy, but we should decide if
  628. // we want to.
  629. bool PossibleCopy = VD.PInfo != nullptr;
  630. if (RenameStack.empty()) {
  631. LLVM_DEBUG(dbgs() << "Rename Stack is empty\n");
  632. } else {
  633. LLVM_DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
  634. << RenameStack.back().DFSIn << ","
  635. << RenameStack.back().DFSOut << ")\n");
  636. }
  637. LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
  638. << VD.DFSOut << ")\n");
  639. bool ShouldPush = (VD.Def || PossibleCopy);
  640. bool OutOfScope = !stackIsInScope(RenameStack, VD);
  641. if (OutOfScope || ShouldPush) {
  642. // Sync to our current scope.
  643. popStackUntilDFSScope(RenameStack, VD);
  644. if (ShouldPush) {
  645. RenameStack.push_back(VD);
  646. }
  647. }
  648. // If we get to this point, and the stack is empty we must have a use
  649. // with no renaming needed, just skip it.
  650. if (RenameStack.empty())
  651. continue;
  652. // Skip values, only want to rename the uses
  653. if (VD.Def || PossibleCopy)
  654. continue;
  655. if (!DebugCounter::shouldExecute(RenameCounter)) {
  656. LLVM_DEBUG(dbgs() << "Skipping execution due to debug counter\n");
  657. continue;
  658. }
  659. ValueDFS &Result = RenameStack.back();
  660. // If the possible copy dominates something, materialize our stack up to
  661. // this point. This ensures every comparison that affects our operation
  662. // ends up with predicateinfo.
  663. if (!Result.Def)
  664. Result.Def = materializeStack(Counter, RenameStack, Op);
  665. LLVM_DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
  666. << *VD.U->get() << " in " << *(VD.U->getUser())
  667. << "\n");
  668. assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
  669. "Predicateinfo def should have dominated this use");
  670. VD.U->set(Result.Def);
  671. }
  672. }
  673. }
  674. PredicateInfoBuilder::ValueInfo &
  675. PredicateInfoBuilder::getOrCreateValueInfo(Value *Operand) {
  676. auto OIN = ValueInfoNums.find(Operand);
  677. if (OIN == ValueInfoNums.end()) {
  678. // This will grow it
  679. ValueInfos.resize(ValueInfos.size() + 1);
  680. // This will use the new size and give us a 0 based number of the info
  681. auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
  682. assert(InsertResult.second && "Value info number already existed?");
  683. return ValueInfos[InsertResult.first->second];
  684. }
  685. return ValueInfos[OIN->second];
  686. }
  687. const PredicateInfoBuilder::ValueInfo &
  688. PredicateInfoBuilder::getValueInfo(Value *Operand) const {
  689. auto OINI = ValueInfoNums.lookup(Operand);
  690. assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
  691. assert(OINI < ValueInfos.size() &&
  692. "Value Info Number greater than size of Value Info Table");
  693. return ValueInfos[OINI];
  694. }
  695. PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
  696. AssumptionCache &AC)
  697. : F(F) {
  698. PredicateInfoBuilder Builder(*this, F, DT, AC);
  699. Builder.buildPredicateInfo();
  700. }
  701. // Remove all declarations we created . The PredicateInfo consumers are
  702. // responsible for remove the ssa_copy calls created.
  703. PredicateInfo::~PredicateInfo() {
  704. // Collect function pointers in set first, as SmallSet uses a SmallVector
  705. // internally and we have to remove the asserting value handles first.
  706. SmallPtrSet<Function *, 20> FunctionPtrs;
  707. for (const auto &F : CreatedDeclarations)
  708. FunctionPtrs.insert(&*F);
  709. CreatedDeclarations.clear();
  710. for (Function *F : FunctionPtrs) {
  711. assert(F->user_begin() == F->user_end() &&
  712. "PredicateInfo consumer did not remove all SSA copies.");
  713. F->eraseFromParent();
  714. }
  715. }
  716. std::optional<PredicateConstraint> PredicateBase::getConstraint() const {
  717. switch (Type) {
  718. case PT_Assume:
  719. case PT_Branch: {
  720. bool TrueEdge = true;
  721. if (auto *PBranch = dyn_cast<PredicateBranch>(this))
  722. TrueEdge = PBranch->TrueEdge;
  723. if (Condition == RenamedOp) {
  724. return {{CmpInst::ICMP_EQ,
  725. TrueEdge ? ConstantInt::getTrue(Condition->getType())
  726. : ConstantInt::getFalse(Condition->getType())}};
  727. }
  728. CmpInst *Cmp = dyn_cast<CmpInst>(Condition);
  729. if (!Cmp) {
  730. // TODO: Make this an assertion once RenamedOp is fully accurate.
  731. return std::nullopt;
  732. }
  733. CmpInst::Predicate Pred;
  734. Value *OtherOp;
  735. if (Cmp->getOperand(0) == RenamedOp) {
  736. Pred = Cmp->getPredicate();
  737. OtherOp = Cmp->getOperand(1);
  738. } else if (Cmp->getOperand(1) == RenamedOp) {
  739. Pred = Cmp->getSwappedPredicate();
  740. OtherOp = Cmp->getOperand(0);
  741. } else {
  742. // TODO: Make this an assertion once RenamedOp is fully accurate.
  743. return std::nullopt;
  744. }
  745. // Invert predicate along false edge.
  746. if (!TrueEdge)
  747. Pred = CmpInst::getInversePredicate(Pred);
  748. return {{Pred, OtherOp}};
  749. }
  750. case PT_Switch:
  751. if (Condition != RenamedOp) {
  752. // TODO: Make this an assertion once RenamedOp is fully accurate.
  753. return std::nullopt;
  754. }
  755. return {{CmpInst::ICMP_EQ, cast<PredicateSwitch>(this)->CaseValue}};
  756. }
  757. llvm_unreachable("Unknown predicate type");
  758. }
  759. void PredicateInfo::verifyPredicateInfo() const {}
  760. char PredicateInfoPrinterLegacyPass::ID = 0;
  761. PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
  762. : FunctionPass(ID) {
  763. initializePredicateInfoPrinterLegacyPassPass(
  764. *PassRegistry::getPassRegistry());
  765. }
  766. void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
  767. AU.setPreservesAll();
  768. AU.addRequiredTransitive<DominatorTreeWrapperPass>();
  769. AU.addRequired<AssumptionCacheTracker>();
  770. }
  771. // Replace ssa_copy calls created by PredicateInfo with their operand.
  772. static void replaceCreatedSSACopys(PredicateInfo &PredInfo, Function &F) {
  773. for (Instruction &Inst : llvm::make_early_inc_range(instructions(F))) {
  774. const auto *PI = PredInfo.getPredicateInfoFor(&Inst);
  775. auto *II = dyn_cast<IntrinsicInst>(&Inst);
  776. if (!PI || !II || II->getIntrinsicID() != Intrinsic::ssa_copy)
  777. continue;
  778. Inst.replaceAllUsesWith(II->getOperand(0));
  779. Inst.eraseFromParent();
  780. }
  781. }
  782. bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) {
  783. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  784. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  785. auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
  786. PredInfo->print(dbgs());
  787. if (VerifyPredicateInfo)
  788. PredInfo->verifyPredicateInfo();
  789. replaceCreatedSSACopys(*PredInfo, F);
  790. return false;
  791. }
  792. PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
  793. FunctionAnalysisManager &AM) {
  794. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  795. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  796. OS << "PredicateInfo for function: " << F.getName() << "\n";
  797. auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
  798. PredInfo->print(OS);
  799. replaceCreatedSSACopys(*PredInfo, F);
  800. return PreservedAnalyses::all();
  801. }
  802. /// An assembly annotator class to print PredicateInfo information in
  803. /// comments.
  804. class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
  805. friend class PredicateInfo;
  806. const PredicateInfo *PredInfo;
  807. public:
  808. PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
  809. void emitBasicBlockStartAnnot(const BasicBlock *BB,
  810. formatted_raw_ostream &OS) override {}
  811. void emitInstructionAnnot(const Instruction *I,
  812. formatted_raw_ostream &OS) override {
  813. if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
  814. OS << "; Has predicate info\n";
  815. if (const auto *PB = dyn_cast<PredicateBranch>(PI)) {
  816. OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
  817. << " Comparison:" << *PB->Condition << " Edge: [";
  818. PB->From->printAsOperand(OS);
  819. OS << ",";
  820. PB->To->printAsOperand(OS);
  821. OS << "]";
  822. } else if (const auto *PS = dyn_cast<PredicateSwitch>(PI)) {
  823. OS << "; switch predicate info { CaseValue: " << *PS->CaseValue
  824. << " Switch:" << *PS->Switch << " Edge: [";
  825. PS->From->printAsOperand(OS);
  826. OS << ",";
  827. PS->To->printAsOperand(OS);
  828. OS << "]";
  829. } else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) {
  830. OS << "; assume predicate info {"
  831. << " Comparison:" << *PA->Condition;
  832. }
  833. OS << ", RenamedOp: ";
  834. PI->RenamedOp->printAsOperand(OS, false);
  835. OS << " }\n";
  836. }
  837. }
  838. };
  839. void PredicateInfo::print(raw_ostream &OS) const {
  840. PredicateInfoAnnotatedWriter Writer(this);
  841. F.print(OS, &Writer);
  842. }
  843. void PredicateInfo::dump() const {
  844. PredicateInfoAnnotatedWriter Writer(this);
  845. F.print(dbgs(), &Writer);
  846. }
  847. PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
  848. FunctionAnalysisManager &AM) {
  849. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  850. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  851. std::make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
  852. return PreservedAnalyses::all();
  853. }
  854. }