PredicateInfo.cpp 33 KB

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