blob: ac6843ff04da47a3cb66607baf57012063a6d045 [file] [log] [blame]
Daniel Berlin439042b2017-02-07 21:10:46 +00001//===-- 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
14#include "llvm/Transforms/Utils/PredicateInfo.h"
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/DepthFirstIterator.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/AssumptionCache.h"
21#include "llvm/Analysis/CFG.h"
22#include "llvm/Analysis/OrderedBasicBlock.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/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"
Daniel Berlina4b5c012017-02-19 04:29:01 +000034#include "llvm/Support/DebugCounter.h"
Daniel Berlin439042b2017-02-07 21:10:46 +000035#include "llvm/Support/FormattedStream.h"
36#include "llvm/Transforms/Scalar.h"
37#include <algorithm>
38#define DEBUG_TYPE "predicateinfo"
39using namespace llvm;
40using namespace PatternMatch;
41using namespace llvm::PredicateInfoClasses;
42
43INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
44 "PredicateInfo Printer", false, false)
45INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
46INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
47INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
48 "PredicateInfo Printer", false, false)
49static cl::opt<bool> VerifyPredicateInfo(
50 "verify-predicateinfo", cl::init(false), cl::Hidden,
51 cl::desc("Verify PredicateInfo in legacy printer pass."));
Daniel Berlina4b5c012017-02-19 04:29:01 +000052DEBUG_COUNTER(RenameCounter, "predicateinfo-rename",
53 "Controls which variables are renamed with predicateinfo");
54
Daniel Berlin439042b2017-02-07 21:10:46 +000055namespace llvm {
56namespace PredicateInfoClasses {
57enum LocalNum {
58 // Operations that must appear first in the block.
59 LN_First,
60 // Operations that are somewhere in the middle of the block, and are sorted on
61 // demand.
62 LN_Middle,
63 // Operations that must appear last in a block, like successor phi node uses.
64 LN_Last
65};
66
67// Associate global and local DFS info with defs and uses, so we can sort them
68// into a global domination ordering.
69struct ValueDFS {
70 int DFSIn = 0;
71 int DFSOut = 0;
72 unsigned int LocalNum = LN_Middle;
Daniel Berlin439042b2017-02-07 21:10:46 +000073 // Only one of Def or Use will be set.
74 Value *Def = nullptr;
Daniel Berlinc763fd12017-02-07 22:11:43 +000075 Use *U = nullptr;
Daniel Berlin588e0be2017-02-18 23:06:38 +000076 // Neither PInfo nor EdgeOnly participate in the ordering
Daniel Berlindbe82642017-02-12 22:12:20 +000077 PredicateBase *PInfo = nullptr;
Daniel Berlin588e0be2017-02-18 23:06:38 +000078 bool EdgeOnly = false;
Daniel Berlin439042b2017-02-07 21:10:46 +000079};
80
81// This compares ValueDFS structures, creating OrderedBasicBlocks where
82// necessary to compare uses/defs in the same block. Doing so allows us to walk
83// the minimum number of instructions necessary to compute our def/use ordering.
84struct ValueDFS_Compare {
85 DenseMap<const BasicBlock *, std::unique_ptr<OrderedBasicBlock>> &OBBMap;
86 ValueDFS_Compare(
87 DenseMap<const BasicBlock *, std::unique_ptr<OrderedBasicBlock>> &OBBMap)
88 : OBBMap(OBBMap) {}
89 bool operator()(const ValueDFS &A, const ValueDFS &B) const {
90 if (&A == &B)
91 return false;
92 // The only case we can't directly compare them is when they in the same
93 // block, and both have localnum == middle. In that case, we have to use
94 // comesbefore to see what the real ordering is, because they are in the
95 // same basic block.
96
97 bool SameBlock = std::tie(A.DFSIn, A.DFSOut) == std::tie(B.DFSIn, B.DFSOut);
98
Daniel Berlindbe82642017-02-12 22:12:20 +000099 // We want to put the def that will get used for a given set of phi uses,
100 // before those phi uses.
101 // So we sort by edge, then by def.
102 // Note that only phi nodes uses and defs can come last.
103 if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
104 return comparePHIRelated(A, B);
105
Daniel Berlin439042b2017-02-07 21:10:46 +0000106 if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
Daniel Berlinc763fd12017-02-07 22:11:43 +0000107 return std::tie(A.DFSIn, A.DFSOut, A.LocalNum, A.Def, A.U) <
108 std::tie(B.DFSIn, B.DFSOut, B.LocalNum, B.Def, B.U);
Daniel Berlin439042b2017-02-07 21:10:46 +0000109 return localComesBefore(A, B);
110 }
111
Daniel Berlindbe82642017-02-12 22:12:20 +0000112 // For a phi use, or a non-materialized def, return the edge it represents.
113 const std::pair<const BasicBlock *, const BasicBlock *>
114 getBlockEdge(const ValueDFS &VD) const {
115 if (!VD.Def && VD.U) {
116 auto *PHI = cast<PHINode>(VD.U->getUser());
117 return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
118 }
119 // This is really a non-materialized def.
120 auto *PBranch = cast<PredicateBranch>(VD.PInfo);
121 return std::make_pair(PBranch->BranchBB, PBranch->SplitBB);
122 }
123
124 // For two phi related values, return the ordering.
125 bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
126 auto &ABlockEdge = getBlockEdge(A);
127 auto &BBlockEdge = getBlockEdge(B);
128 // Now sort by block edge and then defs before uses.
129 return std::tie(ABlockEdge, A.Def, A.U) < std::tie(BBlockEdge, B.Def, B.U);
130 }
131
Daniel Berlin439042b2017-02-07 21:10:46 +0000132 // Get the definition of an instruction that occurs in the middle of a block.
133 Value *getMiddleDef(const ValueDFS &VD) const {
134 if (VD.Def)
135 return VD.Def;
136 // It's possible for the defs and uses to be null. For branches, the local
137 // numbering will say the placed predicaeinfos should go first (IE
138 // LN_beginning), so we won't be in this function. For assumes, we will end
139 // up here, beause we need to order the def we will place relative to the
140 // assume. So for the purpose of ordering, we pretend the def is the assume
141 // because that is where we will insert the info.
Daniel Berlinc763fd12017-02-07 22:11:43 +0000142 if (!VD.U) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000143 assert(VD.PInfo &&
144 "No def, no use, and no predicateinfo should not occur");
145 assert(isa<PredicateAssume>(VD.PInfo) &&
146 "Middle of block should only occur for assumes");
147 return cast<PredicateAssume>(VD.PInfo)->AssumeInst;
148 }
149 return nullptr;
150 }
151
152 // Return either the Def, if it's not null, or the user of the Use, if the def
153 // is null.
Daniel Berlinc763fd12017-02-07 22:11:43 +0000154 const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
Daniel Berlin439042b2017-02-07 21:10:46 +0000155 if (Def)
156 return cast<Instruction>(Def);
Daniel Berlinc763fd12017-02-07 22:11:43 +0000157 return cast<Instruction>(U->getUser());
Daniel Berlin439042b2017-02-07 21:10:46 +0000158 }
159
160 // This performs the necessary local basic block ordering checks to tell
161 // whether A comes before B, where both are in the same basic block.
162 bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
163 auto *ADef = getMiddleDef(A);
164 auto *BDef = getMiddleDef(B);
165
166 // See if we have real values or uses. If we have real values, we are
167 // guaranteed they are instructions or arguments. No matter what, we are
168 // guaranteed they are in the same block if they are instructions.
169 auto *ArgA = dyn_cast_or_null<Argument>(ADef);
170 auto *ArgB = dyn_cast_or_null<Argument>(BDef);
171
172 if (ArgA && !ArgB)
173 return true;
174 if (ArgB && !ArgA)
175 return false;
176 if (ArgA && ArgB)
177 return ArgA->getArgNo() < ArgB->getArgNo();
178
Daniel Berlinc763fd12017-02-07 22:11:43 +0000179 auto *AInst = getDefOrUser(ADef, A.U);
180 auto *BInst = getDefOrUser(BDef, B.U);
Daniel Berlin439042b2017-02-07 21:10:46 +0000181
182 auto *BB = AInst->getParent();
183 auto LookupResult = OBBMap.find(BB);
184 if (LookupResult != OBBMap.end())
185 return LookupResult->second->dominates(AInst, BInst);
186 else {
187 auto Result = OBBMap.insert({BB, make_unique<OrderedBasicBlock>(BB)});
188 return Result.first->second->dominates(AInst, BInst);
189 }
Daniel Berlinc763fd12017-02-07 22:11:43 +0000190 return std::tie(ADef, A.U) < std::tie(BDef, B.U);
Daniel Berlin439042b2017-02-07 21:10:46 +0000191 }
192};
193
194} // namespace PredicateInfoClasses
195
Daniel Berlindbe82642017-02-12 22:12:20 +0000196bool PredicateInfo::stackIsInScope(const ValueDFSStack &Stack,
197 const ValueDFS &VDUse) const {
Daniel Berlin439042b2017-02-07 21:10:46 +0000198 if (Stack.empty())
199 return false;
Daniel Berlindbe82642017-02-12 22:12:20 +0000200 // If it's a phi only use, make sure it's for this phi node edge, and that the
201 // use is in a phi node. If it's anything else, and the top of the stack is
Daniel Berlin588e0be2017-02-18 23:06:38 +0000202 // EdgeOnly, we need to pop the stack. We deliberately sort phi uses next to
Daniel Berlindbe82642017-02-12 22:12:20 +0000203 // the defs they must go with so that we can know it's time to pop the stack
204 // when we hit the end of the phi uses for a given def.
Daniel Berlin588e0be2017-02-18 23:06:38 +0000205 if (Stack.back().EdgeOnly) {
Daniel Berlindbe82642017-02-12 22:12:20 +0000206 if (!VDUse.U)
207 return false;
208 auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
209 if (!PHI)
210 return false;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000211 // The only EdgeOnly defs should be branch info.
Daniel Berlindbe82642017-02-12 22:12:20 +0000212 auto *PBranch = dyn_cast<PredicateBranch>(Stack.back().PInfo);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000213 assert(PBranch && "Only branches should have EdgeOnly defs");
214 // Check edge matches us.
Daniel Berlindbe82642017-02-12 22:12:20 +0000215 BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
216 if (EdgePred != PBranch->BranchBB)
217 return false;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000218
219 // Use dominates, which knows how to handle edge dominance.
220 return DT.dominates(BasicBlockEdge(PBranch->BranchBB, PBranch->SplitBB),
221 *VDUse.U);
Daniel Berlindbe82642017-02-12 22:12:20 +0000222 }
223
224 return (VDUse.DFSIn >= Stack.back().DFSIn &&
225 VDUse.DFSOut <= Stack.back().DFSOut);
Daniel Berlin439042b2017-02-07 21:10:46 +0000226}
227
Daniel Berlindbe82642017-02-12 22:12:20 +0000228void PredicateInfo::popStackUntilDFSScope(ValueDFSStack &Stack,
229 const ValueDFS &VD) {
230 while (!Stack.empty() && !stackIsInScope(Stack, VD))
Daniel Berlin439042b2017-02-07 21:10:46 +0000231 Stack.pop_back();
232}
233
234// Convert the uses of Op into a vector of uses, associating global and local
235// DFS info with each one.
236void PredicateInfo::convertUsesToDFSOrdered(
237 Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
238 for (auto &U : Op->uses()) {
239 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
240 ValueDFS VD;
241 // Put the phi node uses in the incoming block.
242 BasicBlock *IBlock;
243 if (auto *PN = dyn_cast<PHINode>(I)) {
244 IBlock = PN->getIncomingBlock(U);
245 // Make phi node users appear last in the incoming block
246 // they are from.
247 VD.LocalNum = LN_Last;
248 } else {
249 // If it's not a phi node use, it is somewhere in the middle of the
250 // block.
251 IBlock = I->getParent();
252 VD.LocalNum = LN_Middle;
253 }
254 DomTreeNode *DomNode = DT.getNode(IBlock);
255 // It's possible our use is in an unreachable block. Skip it if so.
256 if (!DomNode)
257 continue;
258 VD.DFSIn = DomNode->getDFSNumIn();
259 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlinc763fd12017-02-07 22:11:43 +0000260 VD.U = &U;
Daniel Berlin439042b2017-02-07 21:10:46 +0000261 DFSOrderedSet.push_back(VD);
262 }
263 }
264}
265
266// Collect relevant operations from Comparison that we may want to insert copies
267// for.
268void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
269 auto *Op0 = Comparison->getOperand(0);
270 auto *Op1 = Comparison->getOperand(1);
271 if (Op0 == Op1)
272 return;
273 CmpOperands.push_back(Comparison);
274 // Only want real values, not constants. Additionally, operands with one use
275 // are only being used in the comparison, which means they will not be useful
276 // for us to consider for predicateinfo.
277 //
Daniel Berlin588e0be2017-02-18 23:06:38 +0000278 if ((isa<Instruction>(Op0) || isa<Argument>(Op0)) && !Op0->hasOneUse())
Daniel Berlin439042b2017-02-07 21:10:46 +0000279 CmpOperands.push_back(Op0);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000280 if ((isa<Instruction>(Op1) || isa<Argument>(Op1)) && !Op1->hasOneUse())
Daniel Berlin439042b2017-02-07 21:10:46 +0000281 CmpOperands.push_back(Op1);
282}
283
Daniel Berlin588e0be2017-02-18 23:06:38 +0000284// Add Op, PB to the list of value infos for Op, and mark Op to be renamed.
285void PredicateInfo::addInfoFor(SmallPtrSetImpl<Value *> &OpsToRename, Value *Op,
286 PredicateBase *PB) {
287 OpsToRename.insert(Op);
288 auto &OperandInfo = getOrCreateValueInfo(Op);
289 AllInfos.push_back(PB);
290 OperandInfo.Infos.push_back(PB);
291}
292
Daniel Berlin439042b2017-02-07 21:10:46 +0000293// Process an assume instruction and place relevant operations we want to rename
294// into OpsToRename.
295void PredicateInfo::processAssume(IntrinsicInst *II, BasicBlock *AssumeBB,
296 SmallPtrSetImpl<Value *> &OpsToRename) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000297 // See if we have a comparison we support
Daniel Berlin439042b2017-02-07 21:10:46 +0000298 SmallVector<Value *, 8> CmpOperands;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000299 SmallVector<Value *, 2> ConditionsToProcess;
Daniel Berlin439042b2017-02-07 21:10:46 +0000300 CmpInst::Predicate Pred;
301 Value *Operand = II->getOperand(0);
302 if (m_c_And(m_Cmp(Pred, m_Value(), m_Value()),
303 m_Cmp(Pred, m_Value(), m_Value()))
304 .match(II->getOperand(0))) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000305 ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(0));
306 ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(1));
307 ConditionsToProcess.push_back(Operand);
308 } else if (isa<CmpInst>(Operand)) {
309
310 ConditionsToProcess.push_back(Operand);
Daniel Berlin439042b2017-02-07 21:10:46 +0000311 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000312 for (auto Cond : ConditionsToProcess) {
313 if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000314 collectCmpOps(Cmp, CmpOperands);
315 // Now add our copy infos for our operands
316 for (auto *Op : CmpOperands) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000317 auto *PA = new PredicateAssume(Op, II, Cmp);
318 addInfoFor(OpsToRename, Op, PA);
Daniel Berlin439042b2017-02-07 21:10:46 +0000319 }
320 CmpOperands.clear();
Daniel Berlin588e0be2017-02-18 23:06:38 +0000321 } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
322 // Otherwise, it should be an AND.
323 assert(BinOp->getOpcode() == Instruction::And &&
Simon Pilgrimdba90112017-02-19 00:33:37 +0000324 "Should have been an AND");
325 auto *PA = new PredicateAssume(BinOp, II, BinOp);
326 addInfoFor(OpsToRename, BinOp, PA);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000327 } else {
328 llvm_unreachable("Unknown type of condition");
Daniel Berlin439042b2017-02-07 21:10:46 +0000329 }
330 }
331}
332
333// Process a block terminating branch, and place relevant operations to be
334// renamed into OpsToRename.
335void PredicateInfo::processBranch(BranchInst *BI, BasicBlock *BranchBB,
336 SmallPtrSetImpl<Value *> &OpsToRename) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000337 BasicBlock *FirstBB = BI->getSuccessor(0);
338 BasicBlock *SecondBB = BI->getSuccessor(1);
Daniel Berlin439042b2017-02-07 21:10:46 +0000339 SmallVector<BasicBlock *, 2> SuccsToProcess;
Daniel Berlindbe82642017-02-12 22:12:20 +0000340 SuccsToProcess.push_back(FirstBB);
341 SuccsToProcess.push_back(SecondBB);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000342 SmallVector<Value *, 2> ConditionsToProcess;
343
344 auto InsertHelper = [&](Value *Op, bool isAnd, bool isOr, Value *Cond) {
345 for (auto *Succ : SuccsToProcess) {
346 // Don't try to insert on a self-edge. This is mainly because we will
347 // eliminate during renaming anyway.
348 if (Succ == BranchBB)
349 continue;
350 bool TakenEdge = (Succ == FirstBB);
351 // For and, only insert on the true edge
352 // For or, only insert on the false edge
353 if ((isAnd && !TakenEdge) || (isOr && TakenEdge))
354 continue;
355 PredicateBase *PB =
356 new PredicateBranch(Op, BranchBB, Succ, Cond, TakenEdge);
357 addInfoFor(OpsToRename, Op, PB);
358 if (!Succ->getSinglePredecessor())
359 EdgeUsesOnly.insert({BranchBB, Succ});
360 }
361 };
Daniel Berlin439042b2017-02-07 21:10:46 +0000362
363 // Match combinations of conditions.
Daniel Berlin588e0be2017-02-18 23:06:38 +0000364 CmpInst::Predicate Pred;
365 bool isAnd = false;
366 bool isOr = false;
367 SmallVector<Value *, 8> CmpOperands;
Daniel Berlin439042b2017-02-07 21:10:46 +0000368 if (match(BI->getCondition(), m_And(m_Cmp(Pred, m_Value(), m_Value()),
369 m_Cmp(Pred, m_Value(), m_Value()))) ||
370 match(BI->getCondition(), m_Or(m_Cmp(Pred, m_Value(), m_Value()),
371 m_Cmp(Pred, m_Value(), m_Value())))) {
372 auto *BinOp = cast<BinaryOperator>(BI->getCondition());
373 if (BinOp->getOpcode() == Instruction::And)
374 isAnd = true;
375 else if (BinOp->getOpcode() == Instruction::Or)
376 isOr = true;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000377 ConditionsToProcess.push_back(BinOp->getOperand(0));
378 ConditionsToProcess.push_back(BinOp->getOperand(1));
379 ConditionsToProcess.push_back(BI->getCondition());
380 } else if (isa<CmpInst>(BI->getCondition())) {
381 ConditionsToProcess.push_back(BI->getCondition());
Daniel Berlin439042b2017-02-07 21:10:46 +0000382 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000383 for (auto Cond : ConditionsToProcess) {
384 if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000385 collectCmpOps(Cmp, CmpOperands);
386 // Now add our copy infos for our operands
Daniel Berlin588e0be2017-02-18 23:06:38 +0000387 for (auto *Op : CmpOperands)
388 InsertHelper(Op, isAnd, isOr, Cmp);
389 } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
390 // This must be an AND or an OR.
391 assert((BinOp->getOpcode() == Instruction::And ||
392 BinOp->getOpcode() == Instruction::Or) &&
393 "Should have been an AND or an OR");
394 // The actual value of the binop is not subject to the same restrictions
395 // as the comparison. It's either true or false on the true/false branch.
Simon Pilgrimdba90112017-02-19 00:33:37 +0000396 InsertHelper(BinOp, false, false, BinOp);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000397 } else {
398 llvm_unreachable("Unknown type of condition");
Daniel Berlin439042b2017-02-07 21:10:46 +0000399 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000400 CmpOperands.clear();
Daniel Berlin439042b2017-02-07 21:10:46 +0000401 }
402}
403
404// Build predicate info for our function
405void PredicateInfo::buildPredicateInfo() {
406 DT.updateDFSNumbers();
407 // Collect operands to rename from all conditional branch terminators, as well
408 // as assume statements.
409 SmallPtrSet<Value *, 8> OpsToRename;
410 for (auto DTN : depth_first(DT.getRootNode())) {
411 BasicBlock *BranchBB = DTN->getBlock();
412 if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
413 if (!BI->isConditional())
414 continue;
415 processBranch(BI, BranchBB, OpsToRename);
416 }
417 }
418 for (auto &Assume : AC.assumptions()) {
419 if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
420 processAssume(II, II->getParent(), OpsToRename);
421 }
422 // Now rename all our operations.
423 renameUses(OpsToRename);
424}
425Value *PredicateInfo::materializeStack(unsigned int &Counter,
426 ValueDFSStack &RenameStack,
427 Value *OrigOp) {
428 // Find the first thing we have to materialize
429 auto RevIter = RenameStack.rbegin();
430 for (; RevIter != RenameStack.rend(); ++RevIter)
431 if (RevIter->Def)
432 break;
433
434 size_t Start = RevIter - RenameStack.rbegin();
435 // The maximum number of things we should be trying to materialize at once
436 // right now is 4, depending on if we had an assume, a branch, and both used
437 // and of conditions.
438 for (auto RenameIter = RenameStack.end() - Start;
439 RenameIter != RenameStack.end(); ++RenameIter) {
440 auto *Op =
441 RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
442 ValueDFS &Result = *RenameIter;
443 auto *ValInfo = Result.PInfo;
Daniel Berlindbe82642017-02-12 22:12:20 +0000444 // For branches, we can just place the operand in the branch block before
445 // the terminator. For assume, we have to place it right before the assume
446 // to ensure we dominate all of our uses. Always insert right before the
447 // relevant instruction (terminator, assume), so that we insert in proper
448 // order in the case of multiple predicateinfo in the same block.
Daniel Berlin439042b2017-02-07 21:10:46 +0000449 if (isa<PredicateBranch>(ValInfo)) {
450 auto *PBranch = cast<PredicateBranch>(ValInfo);
Daniel Berlindbe82642017-02-12 22:12:20 +0000451 IRBuilder<> B(PBranch->BranchBB->getTerminator());
Daniel Berlin439042b2017-02-07 21:10:46 +0000452 Function *IF = Intrinsic::getDeclaration(
453 F.getParent(), Intrinsic::ssa_copy, Op->getType());
Daniel Berlin588e0be2017-02-18 23:06:38 +0000454 CallInst *PIC =
455 B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
Daniel Berlin439042b2017-02-07 21:10:46 +0000456 PredicateMap.insert({PIC, ValInfo});
457 Result.Def = PIC;
458 } else {
459 auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
460 assert(PAssume &&
461 "Should not have gotten here without it being an assume");
Daniel Berlindbe82642017-02-12 22:12:20 +0000462 IRBuilder<> B(PAssume->AssumeInst);
Daniel Berlin439042b2017-02-07 21:10:46 +0000463 Function *IF = Intrinsic::getDeclaration(
464 F.getParent(), Intrinsic::ssa_copy, Op->getType());
Daniel Berlin588e0be2017-02-18 23:06:38 +0000465 CallInst *PIC = B.CreateCall(IF, Op);
Daniel Berlin439042b2017-02-07 21:10:46 +0000466 PredicateMap.insert({PIC, ValInfo});
467 Result.Def = PIC;
468 }
469 }
470 return RenameStack.back().Def;
471}
472
473// Instead of the standard SSA renaming algorithm, which is O(Number of
474// instructions), and walks the entire dominator tree, we walk only the defs +
475// uses. The standard SSA renaming algorithm does not really rely on the
476// dominator tree except to order the stack push/pops of the renaming stacks, so
477// that defs end up getting pushed before hitting the correct uses. This does
478// not require the dominator tree, only the *order* of the dominator tree. The
479// complete and correct ordering of the defs and uses, in dominator tree is
480// contained in the DFS numbering of the dominator tree. So we sort the defs and
481// uses into the DFS ordering, and then just use the renaming stack as per
482// normal, pushing when we hit a def (which is a predicateinfo instruction),
483// popping when we are out of the dfs scope for that def, and replacing any uses
484// with top of stack if it exists. In order to handle liveness without
485// propagating liveness info, we don't actually insert the predicateinfo
486// instruction def until we see a use that it would dominate. Once we see such
487// a use, we materialize the predicateinfo instruction in the right place and
488// use it.
489//
490// TODO: Use this algorithm to perform fast single-variable renaming in
491// promotememtoreg and memoryssa.
492void PredicateInfo::renameUses(SmallPtrSetImpl<Value *> &OpsToRename) {
493 ValueDFS_Compare Compare(OBBMap);
494 // Compute liveness, and rename in O(uses) per Op.
495 for (auto *Op : OpsToRename) {
496 unsigned Counter = 0;
497 SmallVector<ValueDFS, 16> OrderedUses;
498 const auto &ValueInfo = getValueInfo(Op);
499 // Insert the possible copies into the def/use list.
500 // They will become real copies if we find a real use for them, and never
501 // created otherwise.
502 for (auto &PossibleCopy : ValueInfo.Infos) {
503 ValueDFS VD;
Daniel Berlin439042b2017-02-07 21:10:46 +0000504 // Determine where we are going to place the copy by the copy type.
505 // The predicate info for branches always come first, they will get
506 // materialized in the split block at the top of the block.
507 // The predicate info for assumes will be somewhere in the middle,
508 // it will get materialized in front of the assume.
Daniel Berlindbe82642017-02-12 22:12:20 +0000509 if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000510 VD.LocalNum = LN_Middle;
Daniel Berlindbe82642017-02-12 22:12:20 +0000511 DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
512 if (!DomNode)
513 continue;
514 VD.DFSIn = DomNode->getDFSNumIn();
515 VD.DFSOut = DomNode->getDFSNumOut();
516 VD.PInfo = PossibleCopy;
517 OrderedUses.push_back(VD);
518 } else if (const auto *PBranch =
519 dyn_cast<PredicateBranch>(PossibleCopy)) {
520 // If we can only do phi uses, we treat it like it's in the branch
521 // block, and handle it specially. We know that it goes last, and only
522 // dominate phi uses.
Daniel Berlin588e0be2017-02-18 23:06:38 +0000523 if (EdgeUsesOnly.count({PBranch->BranchBB, PBranch->SplitBB})) {
Daniel Berlindbe82642017-02-12 22:12:20 +0000524 VD.LocalNum = LN_Last;
525 auto *DomNode = DT.getNode(PBranch->BranchBB);
526 if (DomNode) {
527 VD.DFSIn = DomNode->getDFSNumIn();
528 VD.DFSOut = DomNode->getDFSNumOut();
529 VD.PInfo = PossibleCopy;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000530 VD.EdgeOnly = true;
Daniel Berlindbe82642017-02-12 22:12:20 +0000531 OrderedUses.push_back(VD);
532 }
533 } else {
534 // Otherwise, we are in the split block (even though we perform
535 // insertion in the branch block).
536 // Insert a possible copy at the split block and before the branch.
537 VD.LocalNum = LN_First;
538 auto *DomNode = DT.getNode(PBranch->SplitBB);
539 if (DomNode) {
540 VD.DFSIn = DomNode->getDFSNumIn();
541 VD.DFSOut = DomNode->getDFSNumOut();
542 VD.PInfo = PossibleCopy;
543 OrderedUses.push_back(VD);
544 }
545 }
546 }
Daniel Berlin439042b2017-02-07 21:10:46 +0000547 }
548
549 convertUsesToDFSOrdered(Op, OrderedUses);
550 std::sort(OrderedUses.begin(), OrderedUses.end(), Compare);
551 SmallVector<ValueDFS, 8> RenameStack;
552 // For each use, sorted into dfs order, push values and replaces uses with
553 // top of stack, which will represent the reaching def.
554 for (auto &VD : OrderedUses) {
555 // We currently do not materialize copy over copy, but we should decide if
556 // we want to.
557 bool PossibleCopy = VD.PInfo != nullptr;
558 if (RenameStack.empty()) {
559 DEBUG(dbgs() << "Rename Stack is empty\n");
560 } else {
561 DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
562 << RenameStack.back().DFSIn << ","
563 << RenameStack.back().DFSOut << ")\n");
564 }
565
566 DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
567 << VD.DFSOut << ")\n");
568
569 bool ShouldPush = (VD.Def || PossibleCopy);
Daniel Berlindbe82642017-02-12 22:12:20 +0000570 bool OutOfScope = !stackIsInScope(RenameStack, VD);
Daniel Berlin439042b2017-02-07 21:10:46 +0000571 if (OutOfScope || ShouldPush) {
572 // Sync to our current scope.
Daniel Berlindbe82642017-02-12 22:12:20 +0000573 popStackUntilDFSScope(RenameStack, VD);
Daniel Berlin439042b2017-02-07 21:10:46 +0000574 if (ShouldPush) {
575 RenameStack.push_back(VD);
576 }
577 }
578 // If we get to this point, and the stack is empty we must have a use
579 // with no renaming needed, just skip it.
580 if (RenameStack.empty())
581 continue;
582 // Skip values, only want to rename the uses
583 if (VD.Def || PossibleCopy)
584 continue;
Daniel Berlina4b5c012017-02-19 04:29:01 +0000585 if (!DebugCounter::shouldExecute(RenameCounter)) {
586 DEBUG(dbgs() << "Skipping execution due to debug counter\n");
587 continue;
588 }
Daniel Berlin439042b2017-02-07 21:10:46 +0000589 ValueDFS &Result = RenameStack.back();
590
591 // If the possible copy dominates something, materialize our stack up to
592 // this point. This ensures every comparison that affects our operation
593 // ends up with predicateinfo.
594 if (!Result.Def)
595 Result.Def = materializeStack(Counter, RenameStack, Op);
596
597 DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
Daniel Berlinc763fd12017-02-07 22:11:43 +0000598 << *VD.U->get() << " in " << *(VD.U->getUser()) << "\n");
599 assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
Daniel Berlin439042b2017-02-07 21:10:46 +0000600 "Predicateinfo def should have dominated this use");
Daniel Berlinc763fd12017-02-07 22:11:43 +0000601 VD.U->set(Result.Def);
Daniel Berlin439042b2017-02-07 21:10:46 +0000602 }
603 }
604}
605
606PredicateInfo::ValueInfo &PredicateInfo::getOrCreateValueInfo(Value *Operand) {
607 auto OIN = ValueInfoNums.find(Operand);
608 if (OIN == ValueInfoNums.end()) {
609 // This will grow it
610 ValueInfos.resize(ValueInfos.size() + 1);
611 // This will use the new size and give us a 0 based number of the info
612 auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
613 assert(InsertResult.second && "Value info number already existed?");
614 return ValueInfos[InsertResult.first->second];
615 }
616 return ValueInfos[OIN->second];
617}
618
619const PredicateInfo::ValueInfo &
620PredicateInfo::getValueInfo(Value *Operand) const {
621 auto OINI = ValueInfoNums.lookup(Operand);
622 assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
623 assert(OINI < ValueInfos.size() &&
624 "Value Info Number greater than size of Value Info Table");
625 return ValueInfos[OINI];
626}
627
628PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
629 AssumptionCache &AC)
630 : F(F), DT(DT), AC(AC) {
631 // Push an empty operand info so that we can detect 0 as not finding one
632 ValueInfos.resize(1);
633 buildPredicateInfo();
634}
635
636PredicateInfo::~PredicateInfo() {}
637
638void PredicateInfo::verifyPredicateInfo() const {}
639
640char PredicateInfoPrinterLegacyPass::ID = 0;
641
642PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
643 : FunctionPass(ID) {
644 initializePredicateInfoPrinterLegacyPassPass(
645 *PassRegistry::getPassRegistry());
646}
647
648void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
649 AU.setPreservesAll();
650 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
651 AU.addRequired<AssumptionCacheTracker>();
652}
653
654bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) {
655 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
656 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
657 auto PredInfo = make_unique<PredicateInfo>(F, DT, AC);
658 PredInfo->print(dbgs());
659 if (VerifyPredicateInfo)
660 PredInfo->verifyPredicateInfo();
661 return false;
662}
663
664PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
665 FunctionAnalysisManager &AM) {
666 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
667 auto &AC = AM.getResult<AssumptionAnalysis>(F);
668 OS << "PredicateInfo for function: " << F.getName() << "\n";
669 make_unique<PredicateInfo>(F, DT, AC)->print(OS);
670
671 return PreservedAnalyses::all();
672}
673
674/// \brief An assembly annotator class to print PredicateInfo information in
675/// comments.
676class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
677 friend class PredicateInfo;
678 const PredicateInfo *PredInfo;
679
680public:
681 PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
682
683 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
684 formatted_raw_ostream &OS) {}
685
686 virtual void emitInstructionAnnot(const Instruction *I,
687 formatted_raw_ostream &OS) {
688 if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
689 OS << "; Has predicate info\n";
690 if (const auto *PB = dyn_cast<PredicateBranch>(PI))
691 OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
Daniel Berlin588e0be2017-02-18 23:06:38 +0000692 << " Comparison:" << *PB->Condition << " }\n";
Daniel Berlin439042b2017-02-07 21:10:46 +0000693 else if (const auto *PA = dyn_cast<PredicateAssume>(PI))
694 OS << "; assume predicate info {"
Daniel Berlin588e0be2017-02-18 23:06:38 +0000695 << " Comparison:" << *PA->Condition << " }\n";
Daniel Berlin439042b2017-02-07 21:10:46 +0000696 }
697 }
698};
699
700void PredicateInfo::print(raw_ostream &OS) const {
701 PredicateInfoAnnotatedWriter Writer(this);
702 F.print(OS, &Writer);
703}
704
705void PredicateInfo::dump() const {
706 PredicateInfoAnnotatedWriter Writer(this);
707 F.print(dbgs(), &Writer);
708}
709
710PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
711 FunctionAnalysisManager &AM) {
712 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
713 auto &AC = AM.getResult<AssumptionAnalysis>(F);
714 make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
715
716 return PreservedAnalyses::all();
717}
718}