blob: cd3974db8c743d2d4e2b7f4aadd71c297139192a [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"
34#include "llvm/Support/FormattedStream.h"
35#include "llvm/Transforms/Scalar.h"
36#include <algorithm>
37#define DEBUG_TYPE "predicateinfo"
38using namespace llvm;
39using namespace PatternMatch;
40using namespace llvm::PredicateInfoClasses;
41
42INITIALIZE_PASS_BEGIN(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
43 "PredicateInfo Printer", false, false)
44INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
45INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
46INITIALIZE_PASS_END(PredicateInfoPrinterLegacyPass, "print-predicateinfo",
47 "PredicateInfo Printer", false, false)
48static cl::opt<bool> VerifyPredicateInfo(
49 "verify-predicateinfo", cl::init(false), cl::Hidden,
50 cl::desc("Verify PredicateInfo in legacy printer pass."));
51namespace llvm {
52namespace PredicateInfoClasses {
53enum LocalNum {
54 // Operations that must appear first in the block.
55 LN_First,
56 // Operations that are somewhere in the middle of the block, and are sorted on
57 // demand.
58 LN_Middle,
59 // Operations that must appear last in a block, like successor phi node uses.
60 LN_Last
61};
62
63// Associate global and local DFS info with defs and uses, so we can sort them
64// into a global domination ordering.
65struct ValueDFS {
66 int DFSIn = 0;
67 int DFSOut = 0;
68 unsigned int LocalNum = LN_Middle;
Daniel Berlin439042b2017-02-07 21:10:46 +000069 // Only one of Def or Use will be set.
70 Value *Def = nullptr;
Daniel Berlinc763fd12017-02-07 22:11:43 +000071 Use *U = nullptr;
Daniel Berlin588e0be2017-02-18 23:06:38 +000072 // Neither PInfo nor EdgeOnly participate in the ordering
Daniel Berlindbe82642017-02-12 22:12:20 +000073 PredicateBase *PInfo = nullptr;
Daniel Berlin588e0be2017-02-18 23:06:38 +000074 bool EdgeOnly = false;
Daniel Berlin439042b2017-02-07 21:10:46 +000075};
76
77// This compares ValueDFS structures, creating OrderedBasicBlocks where
78// necessary to compare uses/defs in the same block. Doing so allows us to walk
79// the minimum number of instructions necessary to compute our def/use ordering.
80struct ValueDFS_Compare {
81 DenseMap<const BasicBlock *, std::unique_ptr<OrderedBasicBlock>> &OBBMap;
82 ValueDFS_Compare(
83 DenseMap<const BasicBlock *, std::unique_ptr<OrderedBasicBlock>> &OBBMap)
84 : OBBMap(OBBMap) {}
85 bool operator()(const ValueDFS &A, const ValueDFS &B) const {
86 if (&A == &B)
87 return false;
88 // The only case we can't directly compare them is when they in the same
89 // block, and both have localnum == middle. In that case, we have to use
90 // comesbefore to see what the real ordering is, because they are in the
91 // same basic block.
92
93 bool SameBlock = std::tie(A.DFSIn, A.DFSOut) == std::tie(B.DFSIn, B.DFSOut);
94
Daniel Berlindbe82642017-02-12 22:12:20 +000095 // We want to put the def that will get used for a given set of phi uses,
96 // before those phi uses.
97 // So we sort by edge, then by def.
98 // Note that only phi nodes uses and defs can come last.
99 if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
100 return comparePHIRelated(A, B);
101
Daniel Berlin439042b2017-02-07 21:10:46 +0000102 if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
Daniel Berlinc763fd12017-02-07 22:11:43 +0000103 return std::tie(A.DFSIn, A.DFSOut, A.LocalNum, A.Def, A.U) <
104 std::tie(B.DFSIn, B.DFSOut, B.LocalNum, B.Def, B.U);
Daniel Berlin439042b2017-02-07 21:10:46 +0000105 return localComesBefore(A, B);
106 }
107
Daniel Berlindbe82642017-02-12 22:12:20 +0000108 // For a phi use, or a non-materialized def, return the edge it represents.
109 const std::pair<const BasicBlock *, const BasicBlock *>
110 getBlockEdge(const ValueDFS &VD) const {
111 if (!VD.Def && VD.U) {
112 auto *PHI = cast<PHINode>(VD.U->getUser());
113 return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
114 }
115 // This is really a non-materialized def.
116 auto *PBranch = cast<PredicateBranch>(VD.PInfo);
117 return std::make_pair(PBranch->BranchBB, PBranch->SplitBB);
118 }
119
120 // For two phi related values, return the ordering.
121 bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
122 auto &ABlockEdge = getBlockEdge(A);
123 auto &BBlockEdge = getBlockEdge(B);
124 // Now sort by block edge and then defs before uses.
125 return std::tie(ABlockEdge, A.Def, A.U) < std::tie(BBlockEdge, B.Def, B.U);
126 }
127
Daniel Berlin439042b2017-02-07 21:10:46 +0000128 // Get the definition of an instruction that occurs in the middle of a block.
129 Value *getMiddleDef(const ValueDFS &VD) const {
130 if (VD.Def)
131 return VD.Def;
132 // It's possible for the defs and uses to be null. For branches, the local
133 // numbering will say the placed predicaeinfos should go first (IE
134 // LN_beginning), so we won't be in this function. For assumes, we will end
135 // up here, beause we need to order the def we will place relative to the
136 // assume. So for the purpose of ordering, we pretend the def is the assume
137 // because that is where we will insert the info.
Daniel Berlinc763fd12017-02-07 22:11:43 +0000138 if (!VD.U) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000139 assert(VD.PInfo &&
140 "No def, no use, and no predicateinfo should not occur");
141 assert(isa<PredicateAssume>(VD.PInfo) &&
142 "Middle of block should only occur for assumes");
143 return cast<PredicateAssume>(VD.PInfo)->AssumeInst;
144 }
145 return nullptr;
146 }
147
148 // Return either the Def, if it's not null, or the user of the Use, if the def
149 // is null.
Daniel Berlinc763fd12017-02-07 22:11:43 +0000150 const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
Daniel Berlin439042b2017-02-07 21:10:46 +0000151 if (Def)
152 return cast<Instruction>(Def);
Daniel Berlinc763fd12017-02-07 22:11:43 +0000153 return cast<Instruction>(U->getUser());
Daniel Berlin439042b2017-02-07 21:10:46 +0000154 }
155
156 // This performs the necessary local basic block ordering checks to tell
157 // whether A comes before B, where both are in the same basic block.
158 bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
159 auto *ADef = getMiddleDef(A);
160 auto *BDef = getMiddleDef(B);
161
162 // See if we have real values or uses. If we have real values, we are
163 // guaranteed they are instructions or arguments. No matter what, we are
164 // guaranteed they are in the same block if they are instructions.
165 auto *ArgA = dyn_cast_or_null<Argument>(ADef);
166 auto *ArgB = dyn_cast_or_null<Argument>(BDef);
167
168 if (ArgA && !ArgB)
169 return true;
170 if (ArgB && !ArgA)
171 return false;
172 if (ArgA && ArgB)
173 return ArgA->getArgNo() < ArgB->getArgNo();
174
Daniel Berlinc763fd12017-02-07 22:11:43 +0000175 auto *AInst = getDefOrUser(ADef, A.U);
176 auto *BInst = getDefOrUser(BDef, B.U);
Daniel Berlin439042b2017-02-07 21:10:46 +0000177
178 auto *BB = AInst->getParent();
179 auto LookupResult = OBBMap.find(BB);
180 if (LookupResult != OBBMap.end())
181 return LookupResult->second->dominates(AInst, BInst);
182 else {
183 auto Result = OBBMap.insert({BB, make_unique<OrderedBasicBlock>(BB)});
184 return Result.first->second->dominates(AInst, BInst);
185 }
Daniel Berlinc763fd12017-02-07 22:11:43 +0000186 return std::tie(ADef, A.U) < std::tie(BDef, B.U);
Daniel Berlin439042b2017-02-07 21:10:46 +0000187 }
188};
189
190} // namespace PredicateInfoClasses
191
Daniel Berlindbe82642017-02-12 22:12:20 +0000192bool PredicateInfo::stackIsInScope(const ValueDFSStack &Stack,
193 const ValueDFS &VDUse) const {
Daniel Berlin439042b2017-02-07 21:10:46 +0000194 if (Stack.empty())
195 return false;
Daniel Berlindbe82642017-02-12 22:12:20 +0000196 // If it's a phi only use, make sure it's for this phi node edge, and that the
197 // 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 +0000198 // EdgeOnly, we need to pop the stack. We deliberately sort phi uses next to
Daniel Berlindbe82642017-02-12 22:12:20 +0000199 // the defs they must go with so that we can know it's time to pop the stack
200 // when we hit the end of the phi uses for a given def.
Daniel Berlin588e0be2017-02-18 23:06:38 +0000201 if (Stack.back().EdgeOnly) {
Daniel Berlindbe82642017-02-12 22:12:20 +0000202 if (!VDUse.U)
203 return false;
204 auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
205 if (!PHI)
206 return false;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000207 // The only EdgeOnly defs should be branch info.
Daniel Berlindbe82642017-02-12 22:12:20 +0000208 auto *PBranch = dyn_cast<PredicateBranch>(Stack.back().PInfo);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000209 assert(PBranch && "Only branches should have EdgeOnly defs");
210 // Check edge matches us.
Daniel Berlindbe82642017-02-12 22:12:20 +0000211 BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
212 if (EdgePred != PBranch->BranchBB)
213 return false;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000214
215 // Use dominates, which knows how to handle edge dominance.
216 return DT.dominates(BasicBlockEdge(PBranch->BranchBB, PBranch->SplitBB),
217 *VDUse.U);
Daniel Berlindbe82642017-02-12 22:12:20 +0000218 }
219
220 return (VDUse.DFSIn >= Stack.back().DFSIn &&
221 VDUse.DFSOut <= Stack.back().DFSOut);
Daniel Berlin439042b2017-02-07 21:10:46 +0000222}
223
Daniel Berlindbe82642017-02-12 22:12:20 +0000224void PredicateInfo::popStackUntilDFSScope(ValueDFSStack &Stack,
225 const ValueDFS &VD) {
226 while (!Stack.empty() && !stackIsInScope(Stack, VD))
Daniel Berlin439042b2017-02-07 21:10:46 +0000227 Stack.pop_back();
228}
229
230// Convert the uses of Op into a vector of uses, associating global and local
231// DFS info with each one.
232void PredicateInfo::convertUsesToDFSOrdered(
233 Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
234 for (auto &U : Op->uses()) {
235 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
236 ValueDFS VD;
237 // Put the phi node uses in the incoming block.
238 BasicBlock *IBlock;
239 if (auto *PN = dyn_cast<PHINode>(I)) {
240 IBlock = PN->getIncomingBlock(U);
241 // Make phi node users appear last in the incoming block
242 // they are from.
243 VD.LocalNum = LN_Last;
244 } else {
245 // If it's not a phi node use, it is somewhere in the middle of the
246 // block.
247 IBlock = I->getParent();
248 VD.LocalNum = LN_Middle;
249 }
250 DomTreeNode *DomNode = DT.getNode(IBlock);
251 // It's possible our use is in an unreachable block. Skip it if so.
252 if (!DomNode)
253 continue;
254 VD.DFSIn = DomNode->getDFSNumIn();
255 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlinc763fd12017-02-07 22:11:43 +0000256 VD.U = &U;
Daniel Berlin439042b2017-02-07 21:10:46 +0000257 DFSOrderedSet.push_back(VD);
258 }
259 }
260}
261
262// Collect relevant operations from Comparison that we may want to insert copies
263// for.
264void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
265 auto *Op0 = Comparison->getOperand(0);
266 auto *Op1 = Comparison->getOperand(1);
267 if (Op0 == Op1)
268 return;
269 CmpOperands.push_back(Comparison);
270 // Only want real values, not constants. Additionally, operands with one use
271 // are only being used in the comparison, which means they will not be useful
272 // for us to consider for predicateinfo.
273 //
Daniel Berlin588e0be2017-02-18 23:06:38 +0000274 if ((isa<Instruction>(Op0) || isa<Argument>(Op0)) && !Op0->hasOneUse())
Daniel Berlin439042b2017-02-07 21:10:46 +0000275 CmpOperands.push_back(Op0);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000276 if ((isa<Instruction>(Op1) || isa<Argument>(Op1)) && !Op1->hasOneUse())
Daniel Berlin439042b2017-02-07 21:10:46 +0000277 CmpOperands.push_back(Op1);
278}
279
Daniel Berlin588e0be2017-02-18 23:06:38 +0000280// Add Op, PB to the list of value infos for Op, and mark Op to be renamed.
281void PredicateInfo::addInfoFor(SmallPtrSetImpl<Value *> &OpsToRename, Value *Op,
282 PredicateBase *PB) {
283 OpsToRename.insert(Op);
284 auto &OperandInfo = getOrCreateValueInfo(Op);
285 AllInfos.push_back(PB);
286 OperandInfo.Infos.push_back(PB);
287}
288
Daniel Berlin439042b2017-02-07 21:10:46 +0000289// Process an assume instruction and place relevant operations we want to rename
290// into OpsToRename.
291void PredicateInfo::processAssume(IntrinsicInst *II, BasicBlock *AssumeBB,
292 SmallPtrSetImpl<Value *> &OpsToRename) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000293 // See if we have a comparison we support
Daniel Berlin439042b2017-02-07 21:10:46 +0000294 SmallVector<Value *, 8> CmpOperands;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000295 SmallVector<Value *, 2> ConditionsToProcess;
Daniel Berlin439042b2017-02-07 21:10:46 +0000296 CmpInst::Predicate Pred;
297 Value *Operand = II->getOperand(0);
298 if (m_c_And(m_Cmp(Pred, m_Value(), m_Value()),
299 m_Cmp(Pred, m_Value(), m_Value()))
300 .match(II->getOperand(0))) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000301 ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(0));
302 ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(1));
303 ConditionsToProcess.push_back(Operand);
304 } else if (isa<CmpInst>(Operand)) {
305
306 ConditionsToProcess.push_back(Operand);
Daniel Berlin439042b2017-02-07 21:10:46 +0000307 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000308 for (auto Cond : ConditionsToProcess) {
309 if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000310 collectCmpOps(Cmp, CmpOperands);
311 // Now add our copy infos for our operands
312 for (auto *Op : CmpOperands) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000313 auto *PA = new PredicateAssume(Op, II, Cmp);
314 addInfoFor(OpsToRename, Op, PA);
Daniel Berlin439042b2017-02-07 21:10:46 +0000315 }
316 CmpOperands.clear();
Daniel Berlin588e0be2017-02-18 23:06:38 +0000317 } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
318 // Otherwise, it should be an AND.
319 assert(BinOp->getOpcode() == Instruction::And &&
320 "Should have been an and");
321 auto *PA = new PredicateAssume(Cond, II, Cond);
322 addInfoFor(OpsToRename, Cond, PA);
323 } else {
324 llvm_unreachable("Unknown type of condition");
Daniel Berlin439042b2017-02-07 21:10:46 +0000325 }
326 }
327}
328
329// Process a block terminating branch, and place relevant operations to be
330// renamed into OpsToRename.
331void PredicateInfo::processBranch(BranchInst *BI, BasicBlock *BranchBB,
332 SmallPtrSetImpl<Value *> &OpsToRename) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000333 BasicBlock *FirstBB = BI->getSuccessor(0);
334 BasicBlock *SecondBB = BI->getSuccessor(1);
Daniel Berlin439042b2017-02-07 21:10:46 +0000335 SmallVector<BasicBlock *, 2> SuccsToProcess;
Daniel Berlindbe82642017-02-12 22:12:20 +0000336 SuccsToProcess.push_back(FirstBB);
337 SuccsToProcess.push_back(SecondBB);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000338 SmallVector<Value *, 2> ConditionsToProcess;
339
340 auto InsertHelper = [&](Value *Op, bool isAnd, bool isOr, Value *Cond) {
341 for (auto *Succ : SuccsToProcess) {
342 // Don't try to insert on a self-edge. This is mainly because we will
343 // eliminate during renaming anyway.
344 if (Succ == BranchBB)
345 continue;
346 bool TakenEdge = (Succ == FirstBB);
347 // For and, only insert on the true edge
348 // For or, only insert on the false edge
349 if ((isAnd && !TakenEdge) || (isOr && TakenEdge))
350 continue;
351 PredicateBase *PB =
352 new PredicateBranch(Op, BranchBB, Succ, Cond, TakenEdge);
353 addInfoFor(OpsToRename, Op, PB);
354 if (!Succ->getSinglePredecessor())
355 EdgeUsesOnly.insert({BranchBB, Succ});
356 }
357 };
Daniel Berlin439042b2017-02-07 21:10:46 +0000358
359 // Match combinations of conditions.
Daniel Berlin588e0be2017-02-18 23:06:38 +0000360 CmpInst::Predicate Pred;
361 bool isAnd = false;
362 bool isOr = false;
363 SmallVector<Value *, 8> CmpOperands;
Daniel Berlin439042b2017-02-07 21:10:46 +0000364 if (match(BI->getCondition(), m_And(m_Cmp(Pred, m_Value(), m_Value()),
365 m_Cmp(Pred, m_Value(), m_Value()))) ||
366 match(BI->getCondition(), m_Or(m_Cmp(Pred, m_Value(), m_Value()),
367 m_Cmp(Pred, m_Value(), m_Value())))) {
368 auto *BinOp = cast<BinaryOperator>(BI->getCondition());
369 if (BinOp->getOpcode() == Instruction::And)
370 isAnd = true;
371 else if (BinOp->getOpcode() == Instruction::Or)
372 isOr = true;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000373 ConditionsToProcess.push_back(BinOp->getOperand(0));
374 ConditionsToProcess.push_back(BinOp->getOperand(1));
375 ConditionsToProcess.push_back(BI->getCondition());
376 } else if (isa<CmpInst>(BI->getCondition())) {
377 ConditionsToProcess.push_back(BI->getCondition());
Daniel Berlin439042b2017-02-07 21:10:46 +0000378 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000379 for (auto Cond : ConditionsToProcess) {
380 if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000381 collectCmpOps(Cmp, CmpOperands);
382 // Now add our copy infos for our operands
Daniel Berlin588e0be2017-02-18 23:06:38 +0000383 for (auto *Op : CmpOperands)
384 InsertHelper(Op, isAnd, isOr, Cmp);
385 } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
386 // This must be an AND or an OR.
387 assert((BinOp->getOpcode() == Instruction::And ||
388 BinOp->getOpcode() == Instruction::Or) &&
389 "Should have been an AND or an OR");
390 // The actual value of the binop is not subject to the same restrictions
391 // as the comparison. It's either true or false on the true/false branch.
392 InsertHelper(Cond, false, false, Cond);
393 } else {
394 llvm_unreachable("Unknown type of condition");
Daniel Berlin439042b2017-02-07 21:10:46 +0000395 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000396 CmpOperands.clear();
Daniel Berlin439042b2017-02-07 21:10:46 +0000397 }
398}
399
400// Build predicate info for our function
401void PredicateInfo::buildPredicateInfo() {
402 DT.updateDFSNumbers();
403 // Collect operands to rename from all conditional branch terminators, as well
404 // as assume statements.
405 SmallPtrSet<Value *, 8> OpsToRename;
406 for (auto DTN : depth_first(DT.getRootNode())) {
407 BasicBlock *BranchBB = DTN->getBlock();
408 if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
409 if (!BI->isConditional())
410 continue;
411 processBranch(BI, BranchBB, OpsToRename);
412 }
413 }
414 for (auto &Assume : AC.assumptions()) {
415 if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
416 processAssume(II, II->getParent(), OpsToRename);
417 }
418 // Now rename all our operations.
419 renameUses(OpsToRename);
420}
421Value *PredicateInfo::materializeStack(unsigned int &Counter,
422 ValueDFSStack &RenameStack,
423 Value *OrigOp) {
424 // Find the first thing we have to materialize
425 auto RevIter = RenameStack.rbegin();
426 for (; RevIter != RenameStack.rend(); ++RevIter)
427 if (RevIter->Def)
428 break;
429
430 size_t Start = RevIter - RenameStack.rbegin();
431 // The maximum number of things we should be trying to materialize at once
432 // right now is 4, depending on if we had an assume, a branch, and both used
433 // and of conditions.
434 for (auto RenameIter = RenameStack.end() - Start;
435 RenameIter != RenameStack.end(); ++RenameIter) {
436 auto *Op =
437 RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
438 ValueDFS &Result = *RenameIter;
439 auto *ValInfo = Result.PInfo;
Daniel Berlindbe82642017-02-12 22:12:20 +0000440 // For branches, we can just place the operand in the branch block before
441 // the terminator. For assume, we have to place it right before the assume
442 // to ensure we dominate all of our uses. Always insert right before the
443 // relevant instruction (terminator, assume), so that we insert in proper
444 // order in the case of multiple predicateinfo in the same block.
Daniel Berlin439042b2017-02-07 21:10:46 +0000445 if (isa<PredicateBranch>(ValInfo)) {
446 auto *PBranch = cast<PredicateBranch>(ValInfo);
Daniel Berlindbe82642017-02-12 22:12:20 +0000447 IRBuilder<> B(PBranch->BranchBB->getTerminator());
Daniel Berlin439042b2017-02-07 21:10:46 +0000448 Function *IF = Intrinsic::getDeclaration(
449 F.getParent(), Intrinsic::ssa_copy, Op->getType());
Daniel Berlin588e0be2017-02-18 23:06:38 +0000450 CallInst *PIC =
451 B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
Daniel Berlin439042b2017-02-07 21:10:46 +0000452 PredicateMap.insert({PIC, ValInfo});
453 Result.Def = PIC;
454 } else {
455 auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
456 assert(PAssume &&
457 "Should not have gotten here without it being an assume");
Daniel Berlindbe82642017-02-12 22:12:20 +0000458 IRBuilder<> B(PAssume->AssumeInst);
Daniel Berlin439042b2017-02-07 21:10:46 +0000459 Function *IF = Intrinsic::getDeclaration(
460 F.getParent(), Intrinsic::ssa_copy, Op->getType());
Daniel Berlin588e0be2017-02-18 23:06:38 +0000461 CallInst *PIC = B.CreateCall(IF, Op);
Daniel Berlin439042b2017-02-07 21:10:46 +0000462 PredicateMap.insert({PIC, ValInfo});
463 Result.Def = PIC;
464 }
465 }
466 return RenameStack.back().Def;
467}
468
469// Instead of the standard SSA renaming algorithm, which is O(Number of
470// instructions), and walks the entire dominator tree, we walk only the defs +
471// uses. The standard SSA renaming algorithm does not really rely on the
472// dominator tree except to order the stack push/pops of the renaming stacks, so
473// that defs end up getting pushed before hitting the correct uses. This does
474// not require the dominator tree, only the *order* of the dominator tree. The
475// complete and correct ordering of the defs and uses, in dominator tree is
476// contained in the DFS numbering of the dominator tree. So we sort the defs and
477// uses into the DFS ordering, and then just use the renaming stack as per
478// normal, pushing when we hit a def (which is a predicateinfo instruction),
479// popping when we are out of the dfs scope for that def, and replacing any uses
480// with top of stack if it exists. In order to handle liveness without
481// propagating liveness info, we don't actually insert the predicateinfo
482// instruction def until we see a use that it would dominate. Once we see such
483// a use, we materialize the predicateinfo instruction in the right place and
484// use it.
485//
486// TODO: Use this algorithm to perform fast single-variable renaming in
487// promotememtoreg and memoryssa.
488void PredicateInfo::renameUses(SmallPtrSetImpl<Value *> &OpsToRename) {
489 ValueDFS_Compare Compare(OBBMap);
490 // Compute liveness, and rename in O(uses) per Op.
491 for (auto *Op : OpsToRename) {
492 unsigned Counter = 0;
493 SmallVector<ValueDFS, 16> OrderedUses;
494 const auto &ValueInfo = getValueInfo(Op);
495 // Insert the possible copies into the def/use list.
496 // They will become real copies if we find a real use for them, and never
497 // created otherwise.
498 for (auto &PossibleCopy : ValueInfo.Infos) {
499 ValueDFS VD;
Daniel Berlin439042b2017-02-07 21:10:46 +0000500 // Determine where we are going to place the copy by the copy type.
501 // The predicate info for branches always come first, they will get
502 // materialized in the split block at the top of the block.
503 // The predicate info for assumes will be somewhere in the middle,
504 // it will get materialized in front of the assume.
Daniel Berlindbe82642017-02-12 22:12:20 +0000505 if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000506 VD.LocalNum = LN_Middle;
Daniel Berlindbe82642017-02-12 22:12:20 +0000507 DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
508 if (!DomNode)
509 continue;
510 VD.DFSIn = DomNode->getDFSNumIn();
511 VD.DFSOut = DomNode->getDFSNumOut();
512 VD.PInfo = PossibleCopy;
513 OrderedUses.push_back(VD);
514 } else if (const auto *PBranch =
515 dyn_cast<PredicateBranch>(PossibleCopy)) {
516 // If we can only do phi uses, we treat it like it's in the branch
517 // block, and handle it specially. We know that it goes last, and only
518 // dominate phi uses.
Daniel Berlin588e0be2017-02-18 23:06:38 +0000519 if (EdgeUsesOnly.count({PBranch->BranchBB, PBranch->SplitBB})) {
Daniel Berlindbe82642017-02-12 22:12:20 +0000520 VD.LocalNum = LN_Last;
521 auto *DomNode = DT.getNode(PBranch->BranchBB);
522 if (DomNode) {
523 VD.DFSIn = DomNode->getDFSNumIn();
524 VD.DFSOut = DomNode->getDFSNumOut();
525 VD.PInfo = PossibleCopy;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000526 VD.EdgeOnly = true;
Daniel Berlindbe82642017-02-12 22:12:20 +0000527 OrderedUses.push_back(VD);
528 }
529 } else {
530 // Otherwise, we are in the split block (even though we perform
531 // insertion in the branch block).
532 // Insert a possible copy at the split block and before the branch.
533 VD.LocalNum = LN_First;
534 auto *DomNode = DT.getNode(PBranch->SplitBB);
535 if (DomNode) {
536 VD.DFSIn = DomNode->getDFSNumIn();
537 VD.DFSOut = DomNode->getDFSNumOut();
538 VD.PInfo = PossibleCopy;
539 OrderedUses.push_back(VD);
540 }
541 }
542 }
Daniel Berlin439042b2017-02-07 21:10:46 +0000543 }
544
545 convertUsesToDFSOrdered(Op, OrderedUses);
546 std::sort(OrderedUses.begin(), OrderedUses.end(), Compare);
547 SmallVector<ValueDFS, 8> RenameStack;
548 // For each use, sorted into dfs order, push values and replaces uses with
549 // top of stack, which will represent the reaching def.
550 for (auto &VD : OrderedUses) {
551 // We currently do not materialize copy over copy, but we should decide if
552 // we want to.
553 bool PossibleCopy = VD.PInfo != nullptr;
554 if (RenameStack.empty()) {
555 DEBUG(dbgs() << "Rename Stack is empty\n");
556 } else {
557 DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
558 << RenameStack.back().DFSIn << ","
559 << RenameStack.back().DFSOut << ")\n");
560 }
561
562 DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
563 << VD.DFSOut << ")\n");
564
565 bool ShouldPush = (VD.Def || PossibleCopy);
Daniel Berlindbe82642017-02-12 22:12:20 +0000566 bool OutOfScope = !stackIsInScope(RenameStack, VD);
Daniel Berlin439042b2017-02-07 21:10:46 +0000567 if (OutOfScope || ShouldPush) {
568 // Sync to our current scope.
Daniel Berlindbe82642017-02-12 22:12:20 +0000569 popStackUntilDFSScope(RenameStack, VD);
Daniel Berlin439042b2017-02-07 21:10:46 +0000570 if (ShouldPush) {
571 RenameStack.push_back(VD);
572 }
573 }
574 // If we get to this point, and the stack is empty we must have a use
575 // with no renaming needed, just skip it.
576 if (RenameStack.empty())
577 continue;
578 // Skip values, only want to rename the uses
579 if (VD.Def || PossibleCopy)
580 continue;
581 ValueDFS &Result = RenameStack.back();
582
583 // If the possible copy dominates something, materialize our stack up to
584 // this point. This ensures every comparison that affects our operation
585 // ends up with predicateinfo.
586 if (!Result.Def)
587 Result.Def = materializeStack(Counter, RenameStack, Op);
588
589 DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
Daniel Berlinc763fd12017-02-07 22:11:43 +0000590 << *VD.U->get() << " in " << *(VD.U->getUser()) << "\n");
591 assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
Daniel Berlin439042b2017-02-07 21:10:46 +0000592 "Predicateinfo def should have dominated this use");
Daniel Berlinc763fd12017-02-07 22:11:43 +0000593 VD.U->set(Result.Def);
Daniel Berlin439042b2017-02-07 21:10:46 +0000594 }
595 }
596}
597
598PredicateInfo::ValueInfo &PredicateInfo::getOrCreateValueInfo(Value *Operand) {
599 auto OIN = ValueInfoNums.find(Operand);
600 if (OIN == ValueInfoNums.end()) {
601 // This will grow it
602 ValueInfos.resize(ValueInfos.size() + 1);
603 // This will use the new size and give us a 0 based number of the info
604 auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
605 assert(InsertResult.second && "Value info number already existed?");
606 return ValueInfos[InsertResult.first->second];
607 }
608 return ValueInfos[OIN->second];
609}
610
611const PredicateInfo::ValueInfo &
612PredicateInfo::getValueInfo(Value *Operand) const {
613 auto OINI = ValueInfoNums.lookup(Operand);
614 assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
615 assert(OINI < ValueInfos.size() &&
616 "Value Info Number greater than size of Value Info Table");
617 return ValueInfos[OINI];
618}
619
620PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
621 AssumptionCache &AC)
622 : F(F), DT(DT), AC(AC) {
623 // Push an empty operand info so that we can detect 0 as not finding one
624 ValueInfos.resize(1);
625 buildPredicateInfo();
626}
627
628PredicateInfo::~PredicateInfo() {}
629
630void PredicateInfo::verifyPredicateInfo() const {}
631
632char PredicateInfoPrinterLegacyPass::ID = 0;
633
634PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
635 : FunctionPass(ID) {
636 initializePredicateInfoPrinterLegacyPassPass(
637 *PassRegistry::getPassRegistry());
638}
639
640void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
641 AU.setPreservesAll();
642 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
643 AU.addRequired<AssumptionCacheTracker>();
644}
645
646bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) {
647 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
648 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
649 auto PredInfo = make_unique<PredicateInfo>(F, DT, AC);
650 PredInfo->print(dbgs());
651 if (VerifyPredicateInfo)
652 PredInfo->verifyPredicateInfo();
653 return false;
654}
655
656PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
657 FunctionAnalysisManager &AM) {
658 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
659 auto &AC = AM.getResult<AssumptionAnalysis>(F);
660 OS << "PredicateInfo for function: " << F.getName() << "\n";
661 make_unique<PredicateInfo>(F, DT, AC)->print(OS);
662
663 return PreservedAnalyses::all();
664}
665
666/// \brief An assembly annotator class to print PredicateInfo information in
667/// comments.
668class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
669 friend class PredicateInfo;
670 const PredicateInfo *PredInfo;
671
672public:
673 PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
674
675 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
676 formatted_raw_ostream &OS) {}
677
678 virtual void emitInstructionAnnot(const Instruction *I,
679 formatted_raw_ostream &OS) {
680 if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
681 OS << "; Has predicate info\n";
682 if (const auto *PB = dyn_cast<PredicateBranch>(PI))
683 OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
Daniel Berlin588e0be2017-02-18 23:06:38 +0000684 << " Comparison:" << *PB->Condition << " }\n";
Daniel Berlin439042b2017-02-07 21:10:46 +0000685 else if (const auto *PA = dyn_cast<PredicateAssume>(PI))
686 OS << "; assume predicate info {"
Daniel Berlin588e0be2017-02-18 23:06:38 +0000687 << " Comparison:" << *PA->Condition << " }\n";
Daniel Berlin439042b2017-02-07 21:10:46 +0000688 }
689 }
690};
691
692void PredicateInfo::print(raw_ostream &OS) const {
693 PredicateInfoAnnotatedWriter Writer(this);
694 F.print(OS, &Writer);
695}
696
697void PredicateInfo::dump() const {
698 PredicateInfoAnnotatedWriter Writer(this);
699 F.print(dbgs(), &Writer);
700}
701
702PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
703 FunctionAnalysisManager &AM) {
704 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
705 auto &AC = AM.getResult<AssumptionAnalysis>(F);
706 make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
707
708 return PreservedAnalyses::all();
709}
710}