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