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/Analysis/OrderedInstructions.h"
23 #include "llvm/IR/AssemblyAnnotationWriter.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/IRBuilder.h"
28 #include "llvm/IR/InstIterator.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/InitializePasses.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.
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.
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 *>
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.
111 static bool valueComesBefore(OrderedInstructions &OI, const Value *A,
112                              const Value *B) {
113   auto *ArgA = dyn_cast_or_null<Argument>(A);
114   auto *ArgB = dyn_cast_or_null<Argument>(B);
115   if (ArgA && !ArgB)
116     return true;
117   if (ArgB && !ArgA)
118     return false;
119   if (ArgA && ArgB)
120     return ArgA->getArgNo() < ArgB->getArgNo();
121   return OI.dfsBefore(cast<Instruction>(A), cast<Instruction>(B));
122 }
123 
124 // This compares ValueDFS structures, creating OrderedBasicBlocks where
125 // necessary to compare uses/defs in the same block.  Doing so allows us to walk
126 // the minimum number of instructions necessary to compute our def/use ordering.
127 struct ValueDFS_Compare {
128   DominatorTree &DT;
129   OrderedInstructions &OI;
130   ValueDFS_Compare(DominatorTree &DT, OrderedInstructions &OI)
131       : DT(DT), OI(OI) {}
132 
133   bool operator()(const ValueDFS &A, const ValueDFS &B) const {
134     if (&A == &B)
135       return false;
136     // The only case we can't directly compare them is when they in the same
137     // block, and both have localnum == middle.  In that case, we have to use
138     // comesbefore to see what the real ordering is, because they are in the
139     // same basic block.
140 
141     assert((A.DFSIn != B.DFSIn || A.DFSOut == B.DFSOut) &&
142            "Equal DFS-in numbers imply equal out numbers");
143     bool SameBlock = A.DFSIn == B.DFSIn;
144 
145     // We want to put the def that will get used for a given set of phi uses,
146     // before those phi uses.
147     // So we sort by edge, then by def.
148     // Note that only phi nodes uses and defs can come last.
149     if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
150       return comparePHIRelated(A, B);
151 
152     bool isADef = A.Def;
153     bool isBDef = B.Def;
154     if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
155       return std::tie(A.DFSIn, A.LocalNum, isADef) <
156              std::tie(B.DFSIn, B.LocalNum, isBDef);
157     return localComesBefore(A, B);
158   }
159 
160   // For a phi use, or a non-materialized def, return the edge it represents.
161   const std::pair<BasicBlock *, BasicBlock *>
162   getBlockEdge(const ValueDFS &VD) const {
163     if (!VD.Def && VD.U) {
164       auto *PHI = cast<PHINode>(VD.U->getUser());
165       return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
166     }
167     // This is really a non-materialized def.
168     return ::getBlockEdge(VD.PInfo);
169   }
170 
171   // For two phi related values, return the ordering.
172   bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
173     BasicBlock *ASrc, *ADest, *BSrc, *BDest;
174     std::tie(ASrc, ADest) = getBlockEdge(A);
175     std::tie(BSrc, BDest) = getBlockEdge(B);
176 
177 #ifndef NDEBUG
178     // This function should only be used for values in the same BB, check that.
179     DomTreeNode *DomASrc = DT.getNode(ASrc);
180     DomTreeNode *DomBSrc = DT.getNode(BSrc);
181     assert(DomASrc->getDFSNumIn() == (unsigned)A.DFSIn &&
182            "DFS numbers for A should match the ones of the source block");
183     assert(DomBSrc->getDFSNumIn() == (unsigned)B.DFSIn &&
184            "DFS numbers for B should match the ones of the source block");
185     assert(A.DFSIn == B.DFSIn && "Values must be in the same block");
186 #endif
187     (void)ASrc;
188     (void)BSrc;
189 
190     // Use DFS numbers to compare destination blocks, to guarantee a
191     // deterministic order.
192     DomTreeNode *DomADest = DT.getNode(ADest);
193     DomTreeNode *DomBDest = DT.getNode(BDest);
194     unsigned AIn = DomADest->getDFSNumIn();
195     unsigned BIn = DomBDest->getDFSNumIn();
196     bool isADef = A.Def;
197     bool isBDef = B.Def;
198     assert((!A.Def || !A.U) && (!B.Def || !B.U) &&
199            "Def and U cannot be set at the same time");
200     // Now sort by edge destination and then defs before uses.
201     return std::tie(AIn, isADef) < std::tie(BIn, isBDef);
202   }
203 
204   // Get the definition of an instruction that occurs in the middle of a block.
205   Value *getMiddleDef(const ValueDFS &VD) const {
206     if (VD.Def)
207       return VD.Def;
208     // It's possible for the defs and uses to be null.  For branches, the local
209     // numbering will say the placed predicaeinfos should go first (IE
210     // LN_beginning), so we won't be in this function. For assumes, we will end
211     // up here, beause we need to order the def we will place relative to the
212     // assume.  So for the purpose of ordering, we pretend the def is the assume
213     // because that is where we will insert the info.
214     if (!VD.U) {
215       assert(VD.PInfo &&
216              "No def, no use, and no predicateinfo should not occur");
217       assert(isa<PredicateAssume>(VD.PInfo) &&
218              "Middle of block should only occur for assumes");
219       return cast<PredicateAssume>(VD.PInfo)->AssumeInst;
220     }
221     return nullptr;
222   }
223 
224   // Return either the Def, if it's not null, or the user of the Use, if the def
225   // is null.
226   const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
227     if (Def)
228       return cast<Instruction>(Def);
229     return cast<Instruction>(U->getUser());
230   }
231 
232   // This performs the necessary local basic block ordering checks to tell
233   // whether A comes before B, where both are in the same basic block.
234   bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
235     auto *ADef = getMiddleDef(A);
236     auto *BDef = getMiddleDef(B);
237 
238     // See if we have real values or uses. If we have real values, we are
239     // guaranteed they are instructions or arguments. No matter what, we are
240     // guaranteed they are in the same block if they are instructions.
241     auto *ArgA = dyn_cast_or_null<Argument>(ADef);
242     auto *ArgB = dyn_cast_or_null<Argument>(BDef);
243 
244     if (ArgA || ArgB)
245       return valueComesBefore(OI, ArgA, ArgB);
246 
247     auto *AInst = getDefOrUser(ADef, A.U);
248     auto *BInst = getDefOrUser(BDef, B.U);
249     return valueComesBefore(OI, AInst, BInst);
250   }
251 };
252 
253 class PredicateInfoBuilder {
254   // Used to store information about each value we might rename.
255   struct ValueInfo {
256     SmallVector<PredicateBase *, 4> Infos;
257   };
258 
259   PredicateInfo &PI;
260   Function &F;
261   DominatorTree &DT;
262   AssumptionCache &AC;
263   OrderedInstructions OI;
264 
265   // This stores info about each operand or comparison result we make copies
266   // of. The real ValueInfos start at index 1, index 0 is unused so that we
267   // can more easily detect invalid indexing.
268   SmallVector<ValueInfo, 32> ValueInfos;
269 
270   // This gives the index into the ValueInfos array for a given Value. Because
271   // 0 is not a valid Value Info index, you can use DenseMap::lookup and tell
272   // whether it returned a valid result.
273   DenseMap<Value *, unsigned int> ValueInfoNums;
274 
275   // The set of edges along which we can only handle phi uses, due to critical
276   // edges.
277   DenseSet<std::pair<BasicBlock *, BasicBlock *>> EdgeUsesOnly;
278 
279   ValueInfo &getOrCreateValueInfo(Value *);
280   const ValueInfo &getValueInfo(Value *) const;
281 
282   void processAssume(IntrinsicInst *, BasicBlock *,
283                      SmallVectorImpl<Value *> &OpsToRename);
284   void processBranch(BranchInst *, BasicBlock *,
285                      SmallVectorImpl<Value *> &OpsToRename);
286   void processSwitch(SwitchInst *, BasicBlock *,
287                      SmallVectorImpl<Value *> &OpsToRename);
288   void renameUses(SmallVectorImpl<Value *> &OpsToRename);
289   void addInfoFor(SmallVectorImpl<Value *> &OpsToRename, Value *Op,
290                   PredicateBase *PB);
291 
292   typedef SmallVectorImpl<ValueDFS> ValueDFSStack;
293   void convertUsesToDFSOrdered(Value *, SmallVectorImpl<ValueDFS> &);
294   Value *materializeStack(unsigned int &, ValueDFSStack &, Value *);
295   bool stackIsInScope(const ValueDFSStack &, const ValueDFS &) const;
296   void popStackUntilDFSScope(ValueDFSStack &, const ValueDFS &);
297 
298 public:
299   PredicateInfoBuilder(PredicateInfo &PI, Function &F, DominatorTree &DT,
300                        AssumptionCache &AC)
301       : PI(PI), F(F), DT(DT), AC(AC), OI(&DT) {
302     // Push an empty operand info so that we can detect 0 as not finding one
303     ValueInfos.resize(1);
304   }
305 
306   void buildPredicateInfo();
307 };
308 
309 bool PredicateInfoBuilder::stackIsInScope(const ValueDFSStack &Stack,
310                                           const ValueDFS &VDUse) const {
311   if (Stack.empty())
312     return false;
313   // If it's a phi only use, make sure it's for this phi node edge, and that the
314   // use is in a phi node.  If it's anything else, and the top of the stack is
315   // EdgeOnly, we need to pop the stack.  We deliberately sort phi uses next to
316   // the defs they must go with so that we can know it's time to pop the stack
317   // when we hit the end of the phi uses for a given def.
318   if (Stack.back().EdgeOnly) {
319     if (!VDUse.U)
320       return false;
321     auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
322     if (!PHI)
323       return false;
324     // Check edge
325     BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
326     if (EdgePred != getBranchBlock(Stack.back().PInfo))
327       return false;
328 
329     // Use dominates, which knows how to handle edge dominance.
330     return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U);
331   }
332 
333   return (VDUse.DFSIn >= Stack.back().DFSIn &&
334           VDUse.DFSOut <= Stack.back().DFSOut);
335 }
336 
337 void PredicateInfoBuilder::popStackUntilDFSScope(ValueDFSStack &Stack,
338                                                  const ValueDFS &VD) {
339   while (!Stack.empty() && !stackIsInScope(Stack, VD))
340     Stack.pop_back();
341 }
342 
343 // Convert the uses of Op into a vector of uses, associating global and local
344 // DFS info with each one.
345 void PredicateInfoBuilder::convertUsesToDFSOrdered(
346     Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
347   for (auto &U : Op->uses()) {
348     if (auto *I = dyn_cast<Instruction>(U.getUser())) {
349       ValueDFS VD;
350       // Put the phi node uses in the incoming block.
351       BasicBlock *IBlock;
352       if (auto *PN = dyn_cast<PHINode>(I)) {
353         IBlock = PN->getIncomingBlock(U);
354         // Make phi node users appear last in the incoming block
355         // they are from.
356         VD.LocalNum = LN_Last;
357       } else {
358         // If it's not a phi node use, it is somewhere in the middle of the
359         // block.
360         IBlock = I->getParent();
361         VD.LocalNum = LN_Middle;
362       }
363       DomTreeNode *DomNode = DT.getNode(IBlock);
364       // It's possible our use is in an unreachable block. Skip it if so.
365       if (!DomNode)
366         continue;
367       VD.DFSIn = DomNode->getDFSNumIn();
368       VD.DFSOut = DomNode->getDFSNumOut();
369       VD.U = &U;
370       DFSOrderedSet.push_back(VD);
371     }
372   }
373 }
374 
375 // Collect relevant operations from Comparison that we may want to insert copies
376 // for.
377 void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
378   auto *Op0 = Comparison->getOperand(0);
379   auto *Op1 = Comparison->getOperand(1);
380   if (Op0 == Op1)
381     return;
382   CmpOperands.push_back(Comparison);
383   // Only want real values, not constants.  Additionally, operands with one use
384   // are only being used in the comparison, which means they will not be useful
385   // for us to consider for predicateinfo.
386   //
387   if ((isa<Instruction>(Op0) || isa<Argument>(Op0)) && !Op0->hasOneUse())
388     CmpOperands.push_back(Op0);
389   if ((isa<Instruction>(Op1) || isa<Argument>(Op1)) && !Op1->hasOneUse())
390     CmpOperands.push_back(Op1);
391 }
392 
393 // Add Op, PB to the list of value infos for Op, and mark Op to be renamed.
394 void PredicateInfoBuilder::addInfoFor(SmallVectorImpl<Value *> &OpsToRename,
395                                       Value *Op, PredicateBase *PB) {
396   auto &OperandInfo = getOrCreateValueInfo(Op);
397   if (OperandInfo.Infos.empty())
398     OpsToRename.push_back(Op);
399   PI.AllInfos.push_back(PB);
400   OperandInfo.Infos.push_back(PB);
401 }
402 
403 // Process an assume instruction and place relevant operations we want to rename
404 // into OpsToRename.
405 void PredicateInfoBuilder::processAssume(
406     IntrinsicInst *II, BasicBlock *AssumeBB,
407     SmallVectorImpl<Value *> &OpsToRename) {
408   // See if we have a comparison we support
409   SmallVector<Value *, 8> CmpOperands;
410   SmallVector<Value *, 2> ConditionsToProcess;
411   CmpInst::Predicate Pred;
412   Value *Operand = II->getOperand(0);
413   if (m_c_And(m_Cmp(Pred, m_Value(), m_Value()),
414               m_Cmp(Pred, m_Value(), m_Value()))
415           .match(II->getOperand(0))) {
416     ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(0));
417     ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(1));
418     ConditionsToProcess.push_back(Operand);
419   } else if (isa<CmpInst>(Operand)) {
420 
421     ConditionsToProcess.push_back(Operand);
422   }
423   for (auto Cond : ConditionsToProcess) {
424     if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
425       collectCmpOps(Cmp, CmpOperands);
426       // Now add our copy infos for our operands
427       for (auto *Op : CmpOperands) {
428         auto *PA = new PredicateAssume(Op, II, Cmp);
429         addInfoFor(OpsToRename, Op, PA);
430       }
431       CmpOperands.clear();
432     } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
433       // Otherwise, it should be an AND.
434       assert(BinOp->getOpcode() == Instruction::And &&
435              "Should have been an AND");
436       auto *PA = new PredicateAssume(BinOp, II, BinOp);
437       addInfoFor(OpsToRename, BinOp, PA);
438     } else {
439       llvm_unreachable("Unknown type of condition");
440     }
441   }
442 }
443 
444 // Process a block terminating branch, and place relevant operations to be
445 // renamed into OpsToRename.
446 void PredicateInfoBuilder::processBranch(
447     BranchInst *BI, BasicBlock *BranchBB,
448     SmallVectorImpl<Value *> &OpsToRename) {
449   BasicBlock *FirstBB = BI->getSuccessor(0);
450   BasicBlock *SecondBB = BI->getSuccessor(1);
451   SmallVector<BasicBlock *, 2> SuccsToProcess;
452   SuccsToProcess.push_back(FirstBB);
453   SuccsToProcess.push_back(SecondBB);
454   SmallVector<Value *, 2> ConditionsToProcess;
455 
456   auto InsertHelper = [&](Value *Op, bool isAnd, bool isOr, Value *Cond) {
457     for (auto *Succ : SuccsToProcess) {
458       // Don't try to insert on a self-edge. This is mainly because we will
459       // eliminate during renaming anyway.
460       if (Succ == BranchBB)
461         continue;
462       bool TakenEdge = (Succ == FirstBB);
463       // For and, only insert on the true edge
464       // For or, only insert on the false edge
465       if ((isAnd && !TakenEdge) || (isOr && TakenEdge))
466         continue;
467       PredicateBase *PB =
468           new PredicateBranch(Op, BranchBB, Succ, Cond, TakenEdge);
469       addInfoFor(OpsToRename, Op, PB);
470       if (!Succ->getSinglePredecessor())
471         EdgeUsesOnly.insert({BranchBB, Succ});
472     }
473   };
474 
475   // Match combinations of conditions.
476   CmpInst::Predicate Pred;
477   bool isAnd = false;
478   bool isOr = false;
479   SmallVector<Value *, 8> CmpOperands;
480   if (match(BI->getCondition(), m_And(m_Cmp(Pred, m_Value(), m_Value()),
481                                       m_Cmp(Pred, m_Value(), m_Value()))) ||
482       match(BI->getCondition(), m_Or(m_Cmp(Pred, m_Value(), m_Value()),
483                                      m_Cmp(Pred, m_Value(), m_Value())))) {
484     auto *BinOp = cast<BinaryOperator>(BI->getCondition());
485     if (BinOp->getOpcode() == Instruction::And)
486       isAnd = true;
487     else if (BinOp->getOpcode() == Instruction::Or)
488       isOr = true;
489     ConditionsToProcess.push_back(BinOp->getOperand(0));
490     ConditionsToProcess.push_back(BinOp->getOperand(1));
491     ConditionsToProcess.push_back(BI->getCondition());
492   } else if (isa<CmpInst>(BI->getCondition())) {
493     ConditionsToProcess.push_back(BI->getCondition());
494   }
495   for (auto Cond : ConditionsToProcess) {
496     if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
497       collectCmpOps(Cmp, CmpOperands);
498       // Now add our copy infos for our operands
499       for (auto *Op : CmpOperands)
500         InsertHelper(Op, isAnd, isOr, Cmp);
501     } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
502       // This must be an AND or an OR.
503       assert((BinOp->getOpcode() == Instruction::And ||
504               BinOp->getOpcode() == Instruction::Or) &&
505              "Should have been an AND or an OR");
506       // The actual value of the binop is not subject to the same restrictions
507       // as the comparison. It's either true or false on the true/false branch.
508       InsertHelper(BinOp, false, false, BinOp);
509     } else {
510       llvm_unreachable("Unknown type of condition");
511     }
512     CmpOperands.clear();
513   }
514 }
515 // Process a block terminating switch, and place relevant operations to be
516 // renamed into OpsToRename.
517 void PredicateInfoBuilder::processSwitch(
518     SwitchInst *SI, BasicBlock *BranchBB,
519     SmallVectorImpl<Value *> &OpsToRename) {
520   Value *Op = SI->getCondition();
521   if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse())
522     return;
523 
524   // Remember how many outgoing edges there are to every successor.
525   SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
526   for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
527     BasicBlock *TargetBlock = SI->getSuccessor(i);
528     ++SwitchEdges[TargetBlock];
529   }
530 
531   // Now propagate info for each case value
532   for (auto C : SI->cases()) {
533     BasicBlock *TargetBlock = C.getCaseSuccessor();
534     if (SwitchEdges.lookup(TargetBlock) == 1) {
535       PredicateSwitch *PS = new PredicateSwitch(
536           Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI);
537       addInfoFor(OpsToRename, Op, PS);
538       if (!TargetBlock->getSinglePredecessor())
539         EdgeUsesOnly.insert({BranchBB, TargetBlock});
540     }
541   }
542 }
543 
544 // Build predicate info for our function
545 void PredicateInfoBuilder::buildPredicateInfo() {
546   DT.updateDFSNumbers();
547   // Collect operands to rename from all conditional branch terminators, as well
548   // as assume statements.
549   SmallVector<Value *, 8> OpsToRename;
550   for (auto DTN : depth_first(DT.getRootNode())) {
551     BasicBlock *BranchBB = DTN->getBlock();
552     if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
553       if (!BI->isConditional())
554         continue;
555       // Can't insert conditional information if they all go to the same place.
556       if (BI->getSuccessor(0) == BI->getSuccessor(1))
557         continue;
558       processBranch(BI, BranchBB, OpsToRename);
559     } else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) {
560       processSwitch(SI, BranchBB, OpsToRename);
561     }
562   }
563   for (auto &Assume : AC.assumptions()) {
564     if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
565       if (DT.isReachableFromEntry(II->getParent()))
566         processAssume(II, II->getParent(), OpsToRename);
567   }
568   // Now rename all our operations.
569   renameUses(OpsToRename);
570 }
571 
572 // Create a ssa_copy declaration with custom mangling, because
573 // Intrinsic::getDeclaration does not handle overloaded unnamed types properly:
574 // all unnamed types get mangled to the same string. We use the pointer
575 // to the type as name here, as it guarantees unique names for different
576 // types and we remove the declarations when destroying PredicateInfo.
577 // It is a workaround for PR38117, because solving it in a fully general way is
578 // tricky (FIXME).
579 static Function *getCopyDeclaration(Module *M, Type *Ty) {
580   std::string Name = "llvm.ssa.copy." + utostr((uintptr_t) Ty);
581   return cast<Function>(
582       M->getOrInsertFunction(Name,
583                              getType(M->getContext(), Intrinsic::ssa_copy, Ty))
584           .getCallee());
585 }
586 
587 // Given the renaming stack, make all the operands currently on the stack real
588 // by inserting them into the IR.  Return the last operation's value.
589 Value *PredicateInfoBuilder::materializeStack(unsigned int &Counter,
590                                              ValueDFSStack &RenameStack,
591                                              Value *OrigOp) {
592   // Find the first thing we have to materialize
593   auto RevIter = RenameStack.rbegin();
594   for (; RevIter != RenameStack.rend(); ++RevIter)
595     if (RevIter->Def)
596       break;
597 
598   size_t Start = RevIter - RenameStack.rbegin();
599   // The maximum number of things we should be trying to materialize at once
600   // right now is 4, depending on if we had an assume, a branch, and both used
601   // and of conditions.
602   for (auto RenameIter = RenameStack.end() - Start;
603        RenameIter != RenameStack.end(); ++RenameIter) {
604     auto *Op =
605         RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
606     ValueDFS &Result = *RenameIter;
607     auto *ValInfo = Result.PInfo;
608     // For edge predicates, we can just place the operand in the block before
609     // the terminator.  For assume, we have to place it right before the assume
610     // to ensure we dominate all of our uses.  Always insert right before the
611     // relevant instruction (terminator, assume), so that we insert in proper
612     // order in the case of multiple predicateinfo in the same block.
613     if (isa<PredicateWithEdge>(ValInfo)) {
614       IRBuilder<> B(getBranchTerminator(ValInfo));
615       Function *IF = getCopyDeclaration(F.getParent(), Op->getType());
616       if (IF->users().empty())
617         PI.CreatedDeclarations.insert(IF);
618       CallInst *PIC =
619           B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
620       PI.PredicateMap.insert({PIC, ValInfo});
621       Result.Def = PIC;
622     } else {
623       auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
624       assert(PAssume &&
625              "Should not have gotten here without it being an assume");
626       IRBuilder<> B(PAssume->AssumeInst);
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.
657 void PredicateInfoBuilder::renameUses(SmallVectorImpl<Value *> &OpsToRename) {
658   ValueDFS_Compare Compare(DT, OI);
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 &
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 &
793 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 
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.
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 
825 void PredicateInfo::verifyPredicateInfo() const {}
826 
827 char PredicateInfoPrinterLegacyPass::ID = 0;
828 
829 PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
830     : FunctionPass(ID) {
831   initializePredicateInfoPrinterLegacyPassPass(
832       *PassRegistry::getPassRegistry());
833 }
834 
835 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.
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 
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 
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:
886   PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
887 
888   virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
889                                         formatted_raw_ostream &OS) {}
890 
891   virtual void emitInstructionAnnot(const Instruction *I,
892                                     formatted_raw_ostream &OS) {
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 << "] }\n";
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 << "] }\n";
909       } else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) {
910         OS << "; assume predicate info {"
911            << " Comparison:" << *PA->Condition << " }\n";
912       }
913     }
914   }
915 };
916 
917 void PredicateInfo::print(raw_ostream &OS) const {
918   PredicateInfoAnnotatedWriter Writer(this);
919   F.print(OS, &Writer);
920 }
921 
922 void PredicateInfo::dump() const {
923   PredicateInfoAnnotatedWriter Writer(this);
924   F.print(dbgs(), &Writer);
925 }
926 
927 PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
928                                                  FunctionAnalysisManager &AM) {
929   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
930   auto &AC = AM.getResult<AssumptionAnalysis>(F);
931   std::make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
932 
933   return PreservedAnalyses::all();
934 }
935 }
936