blob: 6f041ace6d1e288c4bed9823465bd4d443a97712 [file] [log] [blame]
Eugene Zelenko6f1ae632017-10-11 21:56:44 +00001//===-- PredicateInfo.cpp - PredicateInfo Builder--------------------===//
Daniel Berlin439042b2017-02-07 21:10:46 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Daniel Berlin439042b2017-02-07 21:10:46 +00006//
Eugene Zelenko6f1ae632017-10-11 21:56:44 +00007//===----------------------------------------------------------------===//
Daniel Berlin439042b2017-02-07 21:10:46 +00008//
9// This file implements the PredicateInfo class.
10//
Eugene Zelenko6f1ae632017-10-11 21:56:44 +000011//===----------------------------------------------------------------===//
Daniel Berlin439042b2017-02-07 21:10:46 +000012
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"
Eugene Zelenko6f1ae632017-10-11 21:56:44 +000018#include "llvm/ADT/Statistic.h"
Florian Hahn36d2e252018-07-24 14:49:52 +000019#include "llvm/ADT/StringExtras.h"
Daniel Berlin439042b2017-02-07 21:10:46 +000020#include "llvm/Analysis/AssumptionCache.h"
Eugene Zelenko6f1ae632017-10-11 21:56:44 +000021#include "llvm/Analysis/CFG.h"
Daniel Berlin439042b2017-02-07 21:10:46 +000022#include "llvm/IR/AssemblyAnnotationWriter.h"
Eugene Zelenko6f1ae632017-10-11 21:56:44 +000023#include "llvm/IR/DataLayout.h"
Daniel Berlin439042b2017-02-07 21:10:46 +000024#include "llvm/IR/Dominators.h"
Eugene Zelenko6f1ae632017-10-11 21:56:44 +000025#include "llvm/IR/GlobalVariable.h"
Daniel Berlin439042b2017-02-07 21:10:46 +000026#include "llvm/IR/IRBuilder.h"
Florian Hahn36d2e252018-07-24 14:49:52 +000027#include "llvm/IR/InstIterator.h"
Daniel Berlin439042b2017-02-07 21:10:46 +000028#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko6f1ae632017-10-11 21:56:44 +000029#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Metadata.h"
31#include "llvm/IR/Module.h"
Daniel Berlin439042b2017-02-07 21:10:46 +000032#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"
David Blaikiea373d182018-03-28 17:44:36 +000036#include "llvm/Transforms/Utils.h"
Daniel Berlin439042b2017-02-07 21:10:46 +000037#include <algorithm>
Eugene Zelenko6f1ae632017-10-11 21:56:44 +000038#define DEBUG_TYPE "predicateinfo"
Daniel Berlin439042b2017-02-07 21:10:46 +000039using 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",
Craig Topper9cd976d2017-08-10 17:48:11 +000053 "Controls which variables are renamed with predicateinfo");
54
Eugene Zelenko6f1ae632017-10-11 21:56:44 +000055namespace {
Daniel Berlinfccbda92017-02-22 22:20:58 +000056// Given a predicate info that is a type of branching terminator, get the
57// branching block.
Eugene Zelenko6f1ae632017-10-11 21:56:44 +000058const BasicBlock *getBranchBlock(const PredicateBase *PB) {
Daniel Berlinfccbda92017-02-22 22:20:58 +000059 assert(isa<PredicateWithEdge>(PB) &&
60 "Only branches and switches should have PHIOnly defs that "
61 "require branch blocks.");
62 return cast<PredicateWithEdge>(PB)->From;
63}
64
65// Given a predicate info that is a type of branching terminator, get the
66// branching terminator.
67static Instruction *getBranchTerminator(const PredicateBase *PB) {
68 assert(isa<PredicateWithEdge>(PB) &&
69 "Not a predicate info type we know how to get a terminator from.");
70 return cast<PredicateWithEdge>(PB)->From->getTerminator();
71}
72
73// Given a predicate info that is a type of branching terminator, get the
74// edge this predicate info represents
Eugene Zelenko6f1ae632017-10-11 21:56:44 +000075const std::pair<BasicBlock *, BasicBlock *>
Daniel Berlinfccbda92017-02-22 22:20:58 +000076getBlockEdge(const PredicateBase *PB) {
77 assert(isa<PredicateWithEdge>(PB) &&
78 "Not a predicate info type we know how to get an edge from.");
79 const auto *PEdge = cast<PredicateWithEdge>(PB);
80 return std::make_pair(PEdge->From, PEdge->To);
81}
82}
Daniel Berlina4b5c012017-02-19 04:29:01 +000083
Daniel Berlin439042b2017-02-07 21:10:46 +000084namespace llvm {
85namespace PredicateInfoClasses {
86enum 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.
98struct ValueDFS {
99 int DFSIn = 0;
100 int DFSOut = 0;
101 unsigned int LocalNum = LN_Middle;
Daniel Berlin439042b2017-02-07 21:10:46 +0000102 // Only one of Def or Use will be set.
103 Value *Def = nullptr;
Daniel Berlinc763fd12017-02-07 22:11:43 +0000104 Use *U = nullptr;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000105 // Neither PInfo nor EdgeOnly participate in the ordering
Daniel Berlindbe82642017-02-12 22:12:20 +0000106 PredicateBase *PInfo = nullptr;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000107 bool EdgeOnly = false;
Daniel Berlin439042b2017-02-07 21:10:46 +0000108};
109
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000110// Perform a strict weak ordering on instructions and arguments.
111static 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();
Florian Hahn5ac26292018-06-20 17:42:01 +0000121 return OI.dfsBefore(cast<Instruction>(A), cast<Instruction>(B));
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000122}
123
Daniel Berlin439042b2017-02-07 21:10:46 +0000124// 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.
127struct ValueDFS_Compare {
Daniel Berlinb7df17e2017-06-29 17:01:14 +0000128 OrderedInstructions &OI;
129 ValueDFS_Compare(OrderedInstructions &OI) : OI(OI) {}
130
Daniel Berlin439042b2017-02-07 21:10:46 +0000131 bool operator()(const ValueDFS &A, const ValueDFS &B) const {
132 if (&A == &B)
133 return false;
134 // The only case we can't directly compare them is when they in the same
135 // block, and both have localnum == middle. In that case, we have to use
136 // comesbefore to see what the real ordering is, because they are in the
137 // same basic block.
138
139 bool SameBlock = std::tie(A.DFSIn, A.DFSOut) == std::tie(B.DFSIn, B.DFSOut);
140
Daniel Berlindbe82642017-02-12 22:12:20 +0000141 // We want to put the def that will get used for a given set of phi uses,
142 // before those phi uses.
143 // So we sort by edge, then by def.
144 // Note that only phi nodes uses and defs can come last.
145 if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
146 return comparePHIRelated(A, B);
147
Daniel Berlin439042b2017-02-07 21:10:46 +0000148 if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
Daniel Berlinc763fd12017-02-07 22:11:43 +0000149 return std::tie(A.DFSIn, A.DFSOut, A.LocalNum, A.Def, A.U) <
150 std::tie(B.DFSIn, B.DFSOut, B.LocalNum, B.Def, B.U);
Daniel Berlin439042b2017-02-07 21:10:46 +0000151 return localComesBefore(A, B);
152 }
153
Daniel Berlindbe82642017-02-12 22:12:20 +0000154 // For a phi use, or a non-materialized def, return the edge it represents.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000155 const std::pair<BasicBlock *, BasicBlock *>
Daniel Berlindbe82642017-02-12 22:12:20 +0000156 getBlockEdge(const ValueDFS &VD) const {
157 if (!VD.Def && VD.U) {
158 auto *PHI = cast<PHINode>(VD.U->getUser());
159 return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
160 }
161 // This is really a non-materialized def.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000162 return ::getBlockEdge(VD.PInfo);
Daniel Berlindbe82642017-02-12 22:12:20 +0000163 }
164
165 // For two phi related values, return the ordering.
166 bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
167 auto &ABlockEdge = getBlockEdge(A);
168 auto &BBlockEdge = getBlockEdge(B);
169 // Now sort by block edge and then defs before uses.
170 return std::tie(ABlockEdge, A.Def, A.U) < std::tie(BBlockEdge, B.Def, B.U);
171 }
172
Daniel Berlin439042b2017-02-07 21:10:46 +0000173 // Get the definition of an instruction that occurs in the middle of a block.
174 Value *getMiddleDef(const ValueDFS &VD) const {
175 if (VD.Def)
176 return VD.Def;
177 // It's possible for the defs and uses to be null. For branches, the local
178 // numbering will say the placed predicaeinfos should go first (IE
179 // LN_beginning), so we won't be in this function. For assumes, we will end
180 // up here, beause we need to order the def we will place relative to the
181 // assume. So for the purpose of ordering, we pretend the def is the assume
182 // because that is where we will insert the info.
Daniel Berlinc763fd12017-02-07 22:11:43 +0000183 if (!VD.U) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000184 assert(VD.PInfo &&
185 "No def, no use, and no predicateinfo should not occur");
186 assert(isa<PredicateAssume>(VD.PInfo) &&
187 "Middle of block should only occur for assumes");
188 return cast<PredicateAssume>(VD.PInfo)->AssumeInst;
189 }
190 return nullptr;
191 }
192
193 // Return either the Def, if it's not null, or the user of the Use, if the def
194 // is null.
Daniel Berlinc763fd12017-02-07 22:11:43 +0000195 const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
Daniel Berlin439042b2017-02-07 21:10:46 +0000196 if (Def)
197 return cast<Instruction>(Def);
Daniel Berlinc763fd12017-02-07 22:11:43 +0000198 return cast<Instruction>(U->getUser());
Daniel Berlin439042b2017-02-07 21:10:46 +0000199 }
200
201 // This performs the necessary local basic block ordering checks to tell
202 // whether A comes before B, where both are in the same basic block.
203 bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
204 auto *ADef = getMiddleDef(A);
205 auto *BDef = getMiddleDef(B);
206
207 // See if we have real values or uses. If we have real values, we are
208 // guaranteed they are instructions or arguments. No matter what, we are
209 // guaranteed they are in the same block if they are instructions.
210 auto *ArgA = dyn_cast_or_null<Argument>(ADef);
211 auto *ArgB = dyn_cast_or_null<Argument>(BDef);
212
Daniel Berlinb7df17e2017-06-29 17:01:14 +0000213 if (ArgA || ArgB)
214 return valueComesBefore(OI, ArgA, ArgB);
Daniel Berlin439042b2017-02-07 21:10:46 +0000215
Daniel Berlinc763fd12017-02-07 22:11:43 +0000216 auto *AInst = getDefOrUser(ADef, A.U);
217 auto *BInst = getDefOrUser(BDef, B.U);
Daniel Berlinb7df17e2017-06-29 17:01:14 +0000218 return valueComesBefore(OI, AInst, BInst);
Daniel Berlin439042b2017-02-07 21:10:46 +0000219 }
220};
221
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000222} // namespace PredicateInfoClasses
Daniel Berlin439042b2017-02-07 21:10:46 +0000223
Daniel Berlindbe82642017-02-12 22:12:20 +0000224bool PredicateInfo::stackIsInScope(const ValueDFSStack &Stack,
225 const ValueDFS &VDUse) const {
Daniel Berlin439042b2017-02-07 21:10:46 +0000226 if (Stack.empty())
227 return false;
Daniel Berlindbe82642017-02-12 22:12:20 +0000228 // If it's a phi only use, make sure it's for this phi node edge, and that the
229 // 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 +0000230 // EdgeOnly, we need to pop the stack. We deliberately sort phi uses next to
Daniel Berlindbe82642017-02-12 22:12:20 +0000231 // the defs they must go with so that we can know it's time to pop the stack
232 // when we hit the end of the phi uses for a given def.
Daniel Berlin588e0be2017-02-18 23:06:38 +0000233 if (Stack.back().EdgeOnly) {
Daniel Berlindbe82642017-02-12 22:12:20 +0000234 if (!VDUse.U)
235 return false;
236 auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
237 if (!PHI)
238 return false;
Daniel Berlinfccbda92017-02-22 22:20:58 +0000239 // Check edge
Daniel Berlindbe82642017-02-12 22:12:20 +0000240 BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
Daniel Berlinfccbda92017-02-22 22:20:58 +0000241 if (EdgePred != getBranchBlock(Stack.back().PInfo))
Daniel Berlindbe82642017-02-12 22:12:20 +0000242 return false;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000243
244 // Use dominates, which knows how to handle edge dominance.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000245 return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U);
Daniel Berlindbe82642017-02-12 22:12:20 +0000246 }
247
248 return (VDUse.DFSIn >= Stack.back().DFSIn &&
249 VDUse.DFSOut <= Stack.back().DFSOut);
Daniel Berlin439042b2017-02-07 21:10:46 +0000250}
251
Daniel Berlindbe82642017-02-12 22:12:20 +0000252void PredicateInfo::popStackUntilDFSScope(ValueDFSStack &Stack,
253 const ValueDFS &VD) {
254 while (!Stack.empty() && !stackIsInScope(Stack, VD))
Daniel Berlin439042b2017-02-07 21:10:46 +0000255 Stack.pop_back();
256}
257
258// Convert the uses of Op into a vector of uses, associating global and local
259// DFS info with each one.
260void PredicateInfo::convertUsesToDFSOrdered(
261 Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
262 for (auto &U : Op->uses()) {
263 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
264 ValueDFS VD;
265 // Put the phi node uses in the incoming block.
266 BasicBlock *IBlock;
267 if (auto *PN = dyn_cast<PHINode>(I)) {
268 IBlock = PN->getIncomingBlock(U);
269 // Make phi node users appear last in the incoming block
270 // they are from.
271 VD.LocalNum = LN_Last;
272 } else {
273 // If it's not a phi node use, it is somewhere in the middle of the
274 // block.
275 IBlock = I->getParent();
276 VD.LocalNum = LN_Middle;
277 }
278 DomTreeNode *DomNode = DT.getNode(IBlock);
279 // It's possible our use is in an unreachable block. Skip it if so.
280 if (!DomNode)
281 continue;
282 VD.DFSIn = DomNode->getDFSNumIn();
283 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlinc763fd12017-02-07 22:11:43 +0000284 VD.U = &U;
Daniel Berlin439042b2017-02-07 21:10:46 +0000285 DFSOrderedSet.push_back(VD);
286 }
287 }
288}
289
290// Collect relevant operations from Comparison that we may want to insert copies
291// for.
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000292void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000293 auto *Op0 = Comparison->getOperand(0);
294 auto *Op1 = Comparison->getOperand(1);
295 if (Op0 == Op1)
296 return;
297 CmpOperands.push_back(Comparison);
298 // Only want real values, not constants. Additionally, operands with one use
299 // are only being used in the comparison, which means they will not be useful
300 // for us to consider for predicateinfo.
301 //
Daniel Berlin588e0be2017-02-18 23:06:38 +0000302 if ((isa<Instruction>(Op0) || isa<Argument>(Op0)) && !Op0->hasOneUse())
Daniel Berlin439042b2017-02-07 21:10:46 +0000303 CmpOperands.push_back(Op0);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000304 if ((isa<Instruction>(Op1) || isa<Argument>(Op1)) && !Op1->hasOneUse())
Daniel Berlin439042b2017-02-07 21:10:46 +0000305 CmpOperands.push_back(Op1);
306}
307
Daniel Berlin588e0be2017-02-18 23:06:38 +0000308// Add Op, PB to the list of value infos for Op, and mark Op to be renamed.
309void PredicateInfo::addInfoFor(SmallPtrSetImpl<Value *> &OpsToRename, Value *Op,
310 PredicateBase *PB) {
311 OpsToRename.insert(Op);
312 auto &OperandInfo = getOrCreateValueInfo(Op);
313 AllInfos.push_back(PB);
314 OperandInfo.Infos.push_back(PB);
315}
316
Daniel Berlin439042b2017-02-07 21:10:46 +0000317// Process an assume instruction and place relevant operations we want to rename
318// into OpsToRename.
319void PredicateInfo::processAssume(IntrinsicInst *II, BasicBlock *AssumeBB,
320 SmallPtrSetImpl<Value *> &OpsToRename) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000321 // See if we have a comparison we support
Daniel Berlin439042b2017-02-07 21:10:46 +0000322 SmallVector<Value *, 8> CmpOperands;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000323 SmallVector<Value *, 2> ConditionsToProcess;
Daniel Berlin439042b2017-02-07 21:10:46 +0000324 CmpInst::Predicate Pred;
325 Value *Operand = II->getOperand(0);
326 if (m_c_And(m_Cmp(Pred, m_Value(), m_Value()),
327 m_Cmp(Pred, m_Value(), m_Value()))
328 .match(II->getOperand(0))) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000329 ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(0));
330 ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(1));
331 ConditionsToProcess.push_back(Operand);
332 } else if (isa<CmpInst>(Operand)) {
333
334 ConditionsToProcess.push_back(Operand);
Daniel Berlin439042b2017-02-07 21:10:46 +0000335 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000336 for (auto Cond : ConditionsToProcess) {
337 if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000338 collectCmpOps(Cmp, CmpOperands);
339 // Now add our copy infos for our operands
340 for (auto *Op : CmpOperands) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000341 auto *PA = new PredicateAssume(Op, II, Cmp);
342 addInfoFor(OpsToRename, Op, PA);
Daniel Berlin439042b2017-02-07 21:10:46 +0000343 }
344 CmpOperands.clear();
Daniel Berlin588e0be2017-02-18 23:06:38 +0000345 } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
346 // Otherwise, it should be an AND.
347 assert(BinOp->getOpcode() == Instruction::And &&
Simon Pilgrimdba90112017-02-19 00:33:37 +0000348 "Should have been an AND");
349 auto *PA = new PredicateAssume(BinOp, II, BinOp);
350 addInfoFor(OpsToRename, BinOp, PA);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000351 } else {
352 llvm_unreachable("Unknown type of condition");
Daniel Berlin439042b2017-02-07 21:10:46 +0000353 }
354 }
355}
356
357// Process a block terminating branch, and place relevant operations to be
358// renamed into OpsToRename.
359void PredicateInfo::processBranch(BranchInst *BI, BasicBlock *BranchBB,
360 SmallPtrSetImpl<Value *> &OpsToRename) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000361 BasicBlock *FirstBB = BI->getSuccessor(0);
362 BasicBlock *SecondBB = BI->getSuccessor(1);
Daniel Berlin439042b2017-02-07 21:10:46 +0000363 SmallVector<BasicBlock *, 2> SuccsToProcess;
Daniel Berlindbe82642017-02-12 22:12:20 +0000364 SuccsToProcess.push_back(FirstBB);
365 SuccsToProcess.push_back(SecondBB);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000366 SmallVector<Value *, 2> ConditionsToProcess;
367
368 auto InsertHelper = [&](Value *Op, bool isAnd, bool isOr, Value *Cond) {
369 for (auto *Succ : SuccsToProcess) {
370 // Don't try to insert on a self-edge. This is mainly because we will
371 // eliminate during renaming anyway.
372 if (Succ == BranchBB)
373 continue;
374 bool TakenEdge = (Succ == FirstBB);
375 // For and, only insert on the true edge
376 // For or, only insert on the false edge
377 if ((isAnd && !TakenEdge) || (isOr && TakenEdge))
378 continue;
379 PredicateBase *PB =
380 new PredicateBranch(Op, BranchBB, Succ, Cond, TakenEdge);
381 addInfoFor(OpsToRename, Op, PB);
382 if (!Succ->getSinglePredecessor())
383 EdgeUsesOnly.insert({BranchBB, Succ});
384 }
385 };
Daniel Berlin439042b2017-02-07 21:10:46 +0000386
387 // Match combinations of conditions.
Daniel Berlin588e0be2017-02-18 23:06:38 +0000388 CmpInst::Predicate Pred;
389 bool isAnd = false;
390 bool isOr = false;
391 SmallVector<Value *, 8> CmpOperands;
Daniel Berlin439042b2017-02-07 21:10:46 +0000392 if (match(BI->getCondition(), m_And(m_Cmp(Pred, m_Value(), m_Value()),
393 m_Cmp(Pred, m_Value(), m_Value()))) ||
394 match(BI->getCondition(), m_Or(m_Cmp(Pred, m_Value(), m_Value()),
395 m_Cmp(Pred, m_Value(), m_Value())))) {
396 auto *BinOp = cast<BinaryOperator>(BI->getCondition());
397 if (BinOp->getOpcode() == Instruction::And)
398 isAnd = true;
399 else if (BinOp->getOpcode() == Instruction::Or)
400 isOr = true;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000401 ConditionsToProcess.push_back(BinOp->getOperand(0));
402 ConditionsToProcess.push_back(BinOp->getOperand(1));
403 ConditionsToProcess.push_back(BI->getCondition());
404 } else if (isa<CmpInst>(BI->getCondition())) {
405 ConditionsToProcess.push_back(BI->getCondition());
Daniel Berlin439042b2017-02-07 21:10:46 +0000406 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000407 for (auto Cond : ConditionsToProcess) {
408 if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000409 collectCmpOps(Cmp, CmpOperands);
410 // Now add our copy infos for our operands
Daniel Berlin588e0be2017-02-18 23:06:38 +0000411 for (auto *Op : CmpOperands)
412 InsertHelper(Op, isAnd, isOr, Cmp);
413 } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
414 // This must be an AND or an OR.
415 assert((BinOp->getOpcode() == Instruction::And ||
416 BinOp->getOpcode() == Instruction::Or) &&
417 "Should have been an AND or an OR");
418 // The actual value of the binop is not subject to the same restrictions
419 // as the comparison. It's either true or false on the true/false branch.
Simon Pilgrimdba90112017-02-19 00:33:37 +0000420 InsertHelper(BinOp, false, false, BinOp);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000421 } else {
422 llvm_unreachable("Unknown type of condition");
Daniel Berlin439042b2017-02-07 21:10:46 +0000423 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000424 CmpOperands.clear();
Daniel Berlin439042b2017-02-07 21:10:46 +0000425 }
426}
Daniel Berlinfccbda92017-02-22 22:20:58 +0000427// Process a block terminating switch, and place relevant operations to be
428// renamed into OpsToRename.
429void PredicateInfo::processSwitch(SwitchInst *SI, BasicBlock *BranchBB,
430 SmallPtrSetImpl<Value *> &OpsToRename) {
431 Value *Op = SI->getCondition();
432 if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse())
433 return;
434
435 // Remember how many outgoing edges there are to every successor.
436 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
437 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
438 BasicBlock *TargetBlock = SI->getSuccessor(i);
439 ++SwitchEdges[TargetBlock];
440 }
441
442 // Now propagate info for each case value
443 for (auto C : SI->cases()) {
444 BasicBlock *TargetBlock = C.getCaseSuccessor();
445 if (SwitchEdges.lookup(TargetBlock) == 1) {
446 PredicateSwitch *PS = new PredicateSwitch(
447 Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI);
448 addInfoFor(OpsToRename, Op, PS);
449 if (!TargetBlock->getSinglePredecessor())
450 EdgeUsesOnly.insert({BranchBB, TargetBlock});
451 }
452 }
453}
Daniel Berlin439042b2017-02-07 21:10:46 +0000454
455// Build predicate info for our function
456void PredicateInfo::buildPredicateInfo() {
457 DT.updateDFSNumbers();
458 // Collect operands to rename from all conditional branch terminators, as well
459 // as assume statements.
460 SmallPtrSet<Value *, 8> OpsToRename;
461 for (auto DTN : depth_first(DT.getRootNode())) {
462 BasicBlock *BranchBB = DTN->getBlock();
463 if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
464 if (!BI->isConditional())
465 continue;
Daniel Berlin6d2db9e2017-06-14 21:19:52 +0000466 // Can't insert conditional information if they all go to the same place.
467 if (BI->getSuccessor(0) == BI->getSuccessor(1))
468 continue;
Daniel Berlin439042b2017-02-07 21:10:46 +0000469 processBranch(BI, BranchBB, OpsToRename);
Daniel Berlinfccbda92017-02-22 22:20:58 +0000470 } else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) {
471 processSwitch(SI, BranchBB, OpsToRename);
Daniel Berlin439042b2017-02-07 21:10:46 +0000472 }
473 }
474 for (auto &Assume : AC.assumptions()) {
475 if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
476 processAssume(II, II->getParent(), OpsToRename);
477 }
478 // Now rename all our operations.
479 renameUses(OpsToRename);
480}
Daniel Berlinfccbda92017-02-22 22:20:58 +0000481
Florian Hahn36d2e252018-07-24 14:49:52 +0000482// Create a ssa_copy declaration with custom mangling, because
483// Intrinsic::getDeclaration does not handle overloaded unnamed types properly:
484// all unnamed types get mangled to the same string. We use the pointer
485// to the type as name here, as it guarantees unique names for different
486// types and we remove the declarations when destroying PredicateInfo.
487// It is a workaround for PR38117, because solving it in a fully general way is
488// tricky (FIXME).
489static Function *getCopyDeclaration(Module *M, Type *Ty) {
490 std::string Name = "llvm.ssa.copy." + utostr((uintptr_t) Ty);
James Y Knight13680222019-02-01 02:28:03 +0000491 return cast<Function>(
492 M->getOrInsertFunction(Name,
493 getType(M->getContext(), Intrinsic::ssa_copy, Ty))
494 .getCallee());
Florian Hahn36d2e252018-07-24 14:49:52 +0000495}
496
Daniel Berlinfccbda92017-02-22 22:20:58 +0000497// Given the renaming stack, make all the operands currently on the stack real
498// by inserting them into the IR. Return the last operation's value.
Daniel Berlin439042b2017-02-07 21:10:46 +0000499Value *PredicateInfo::materializeStack(unsigned int &Counter,
500 ValueDFSStack &RenameStack,
501 Value *OrigOp) {
502 // Find the first thing we have to materialize
503 auto RevIter = RenameStack.rbegin();
504 for (; RevIter != RenameStack.rend(); ++RevIter)
505 if (RevIter->Def)
506 break;
507
508 size_t Start = RevIter - RenameStack.rbegin();
509 // The maximum number of things we should be trying to materialize at once
510 // right now is 4, depending on if we had an assume, a branch, and both used
511 // and of conditions.
512 for (auto RenameIter = RenameStack.end() - Start;
513 RenameIter != RenameStack.end(); ++RenameIter) {
514 auto *Op =
515 RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
516 ValueDFS &Result = *RenameIter;
517 auto *ValInfo = Result.PInfo;
Daniel Berlinfccbda92017-02-22 22:20:58 +0000518 // For edge predicates, we can just place the operand in the block before
Daniel Berlindbe82642017-02-12 22:12:20 +0000519 // the terminator. For assume, we have to place it right before the assume
520 // to ensure we dominate all of our uses. Always insert right before the
521 // relevant instruction (terminator, assume), so that we insert in proper
522 // order in the case of multiple predicateinfo in the same block.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000523 if (isa<PredicateWithEdge>(ValInfo)) {
524 IRBuilder<> B(getBranchTerminator(ValInfo));
Florian Hahn36d2e252018-07-24 14:49:52 +0000525 Function *IF = getCopyDeclaration(F.getParent(), Op->getType());
Matthias Braun9fd397b2018-10-31 00:23:23 +0000526 if (empty(IF->users()))
Florian Hahn36d2e252018-07-24 14:49:52 +0000527 CreatedDeclarations.insert(IF);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000528 CallInst *PIC =
529 B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
Daniel Berlin439042b2017-02-07 21:10:46 +0000530 PredicateMap.insert({PIC, ValInfo});
531 Result.Def = PIC;
532 } else {
533 auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
534 assert(PAssume &&
535 "Should not have gotten here without it being an assume");
Daniel Berlindbe82642017-02-12 22:12:20 +0000536 IRBuilder<> B(PAssume->AssumeInst);
Florian Hahn36d2e252018-07-24 14:49:52 +0000537 Function *IF = getCopyDeclaration(F.getParent(), Op->getType());
Matthias Braun9fd397b2018-10-31 00:23:23 +0000538 if (empty(IF->users()))
Florian Hahn36d2e252018-07-24 14:49:52 +0000539 CreatedDeclarations.insert(IF);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000540 CallInst *PIC = B.CreateCall(IF, Op);
Daniel Berlin439042b2017-02-07 21:10:46 +0000541 PredicateMap.insert({PIC, ValInfo});
542 Result.Def = PIC;
543 }
544 }
545 return RenameStack.back().Def;
546}
547
548// Instead of the standard SSA renaming algorithm, which is O(Number of
549// instructions), and walks the entire dominator tree, we walk only the defs +
550// uses. The standard SSA renaming algorithm does not really rely on the
551// dominator tree except to order the stack push/pops of the renaming stacks, so
552// that defs end up getting pushed before hitting the correct uses. This does
553// not require the dominator tree, only the *order* of the dominator tree. The
554// complete and correct ordering of the defs and uses, in dominator tree is
555// contained in the DFS numbering of the dominator tree. So we sort the defs and
556// uses into the DFS ordering, and then just use the renaming stack as per
557// normal, pushing when we hit a def (which is a predicateinfo instruction),
558// popping when we are out of the dfs scope for that def, and replacing any uses
559// with top of stack if it exists. In order to handle liveness without
560// propagating liveness info, we don't actually insert the predicateinfo
561// instruction def until we see a use that it would dominate. Once we see such
562// a use, we materialize the predicateinfo instruction in the right place and
563// use it.
564//
565// TODO: Use this algorithm to perform fast single-variable renaming in
566// promotememtoreg and memoryssa.
Mandeep Singh Grang33a1b732017-06-01 18:36:24 +0000567void PredicateInfo::renameUses(SmallPtrSetImpl<Value *> &OpSet) {
568 // Sort OpsToRename since we are going to iterate it.
569 SmallVector<Value *, 8> OpsToRename(OpSet.begin(), OpSet.end());
Daniel Berlinb7df17e2017-06-29 17:01:14 +0000570 auto Comparator = [&](const Value *A, const Value *B) {
571 return valueComesBefore(OI, A, B);
572 };
Fangrui Song0cac7262018-09-27 02:13:45 +0000573 llvm::sort(OpsToRename, Comparator);
Daniel Berlinb7df17e2017-06-29 17:01:14 +0000574 ValueDFS_Compare Compare(OI);
Daniel Berlin439042b2017-02-07 21:10:46 +0000575 // Compute liveness, and rename in O(uses) per Op.
576 for (auto *Op : OpsToRename) {
Florian Hahn5ac26292018-06-20 17:42:01 +0000577 LLVM_DEBUG(dbgs() << "Visiting " << *Op << "\n");
Daniel Berlin439042b2017-02-07 21:10:46 +0000578 unsigned Counter = 0;
579 SmallVector<ValueDFS, 16> OrderedUses;
580 const auto &ValueInfo = getValueInfo(Op);
581 // Insert the possible copies into the def/use list.
582 // They will become real copies if we find a real use for them, and never
583 // created otherwise.
584 for (auto &PossibleCopy : ValueInfo.Infos) {
585 ValueDFS VD;
Daniel Berlin439042b2017-02-07 21:10:46 +0000586 // Determine where we are going to place the copy by the copy type.
587 // The predicate info for branches always come first, they will get
588 // materialized in the split block at the top of the block.
589 // The predicate info for assumes will be somewhere in the middle,
590 // it will get materialized in front of the assume.
Daniel Berlindbe82642017-02-12 22:12:20 +0000591 if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000592 VD.LocalNum = LN_Middle;
Daniel Berlindbe82642017-02-12 22:12:20 +0000593 DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
594 if (!DomNode)
595 continue;
596 VD.DFSIn = DomNode->getDFSNumIn();
597 VD.DFSOut = DomNode->getDFSNumOut();
598 VD.PInfo = PossibleCopy;
599 OrderedUses.push_back(VD);
Daniel Berlinfccbda92017-02-22 22:20:58 +0000600 } else if (isa<PredicateWithEdge>(PossibleCopy)) {
Daniel Berlindbe82642017-02-12 22:12:20 +0000601 // If we can only do phi uses, we treat it like it's in the branch
602 // block, and handle it specially. We know that it goes last, and only
603 // dominate phi uses.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000604 auto BlockEdge = getBlockEdge(PossibleCopy);
605 if (EdgeUsesOnly.count(BlockEdge)) {
Daniel Berlindbe82642017-02-12 22:12:20 +0000606 VD.LocalNum = LN_Last;
Daniel Berlinfccbda92017-02-22 22:20:58 +0000607 auto *DomNode = DT.getNode(BlockEdge.first);
Daniel Berlindbe82642017-02-12 22:12:20 +0000608 if (DomNode) {
609 VD.DFSIn = DomNode->getDFSNumIn();
610 VD.DFSOut = DomNode->getDFSNumOut();
611 VD.PInfo = PossibleCopy;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000612 VD.EdgeOnly = true;
Daniel Berlindbe82642017-02-12 22:12:20 +0000613 OrderedUses.push_back(VD);
614 }
615 } else {
616 // Otherwise, we are in the split block (even though we perform
617 // insertion in the branch block).
618 // Insert a possible copy at the split block and before the branch.
619 VD.LocalNum = LN_First;
Daniel Berlinfccbda92017-02-22 22:20:58 +0000620 auto *DomNode = DT.getNode(BlockEdge.second);
Daniel Berlindbe82642017-02-12 22:12:20 +0000621 if (DomNode) {
622 VD.DFSIn = DomNode->getDFSNumIn();
623 VD.DFSOut = DomNode->getDFSNumOut();
624 VD.PInfo = PossibleCopy;
625 OrderedUses.push_back(VD);
626 }
627 }
628 }
Daniel Berlin439042b2017-02-07 21:10:46 +0000629 }
630
631 convertUsesToDFSOrdered(Op, OrderedUses);
Mandeep Singh Grange6bb6632017-11-17 00:43:24 +0000632 // Here we require a stable sort because we do not bother to try to
633 // assign an order to the operands the uses represent. Thus, two
634 // uses in the same instruction do not have a strict sort order
635 // currently and will be considered equal. We could get rid of the
636 // stable sort by creating one if we wanted.
Fangrui Songefd94c52019-04-23 14:51:27 +0000637 llvm::stable_sort(OrderedUses, Compare);
Daniel Berlin439042b2017-02-07 21:10:46 +0000638 SmallVector<ValueDFS, 8> RenameStack;
639 // For each use, sorted into dfs order, push values and replaces uses with
640 // top of stack, which will represent the reaching def.
641 for (auto &VD : OrderedUses) {
642 // We currently do not materialize copy over copy, but we should decide if
643 // we want to.
644 bool PossibleCopy = VD.PInfo != nullptr;
645 if (RenameStack.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000646 LLVM_DEBUG(dbgs() << "Rename Stack is empty\n");
Daniel Berlin439042b2017-02-07 21:10:46 +0000647 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000648 LLVM_DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
649 << RenameStack.back().DFSIn << ","
650 << RenameStack.back().DFSOut << ")\n");
Daniel Berlin439042b2017-02-07 21:10:46 +0000651 }
652
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000653 LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
654 << VD.DFSOut << ")\n");
Daniel Berlin439042b2017-02-07 21:10:46 +0000655
656 bool ShouldPush = (VD.Def || PossibleCopy);
Daniel Berlindbe82642017-02-12 22:12:20 +0000657 bool OutOfScope = !stackIsInScope(RenameStack, VD);
Daniel Berlin439042b2017-02-07 21:10:46 +0000658 if (OutOfScope || ShouldPush) {
659 // Sync to our current scope.
Daniel Berlindbe82642017-02-12 22:12:20 +0000660 popStackUntilDFSScope(RenameStack, VD);
Daniel Berlin439042b2017-02-07 21:10:46 +0000661 if (ShouldPush) {
662 RenameStack.push_back(VD);
663 }
664 }
665 // If we get to this point, and the stack is empty we must have a use
666 // with no renaming needed, just skip it.
667 if (RenameStack.empty())
668 continue;
669 // Skip values, only want to rename the uses
670 if (VD.Def || PossibleCopy)
671 continue;
Daniel Berlina4b5c012017-02-19 04:29:01 +0000672 if (!DebugCounter::shouldExecute(RenameCounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000673 LLVM_DEBUG(dbgs() << "Skipping execution due to debug counter\n");
Daniel Berlina4b5c012017-02-19 04:29:01 +0000674 continue;
675 }
Daniel Berlin439042b2017-02-07 21:10:46 +0000676 ValueDFS &Result = RenameStack.back();
677
678 // If the possible copy dominates something, materialize our stack up to
679 // this point. This ensures every comparison that affects our operation
680 // ends up with predicateinfo.
681 if (!Result.Def)
682 Result.Def = materializeStack(Counter, RenameStack, Op);
683
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000684 LLVM_DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
685 << *VD.U->get() << " in " << *(VD.U->getUser())
686 << "\n");
Daniel Berlinc763fd12017-02-07 22:11:43 +0000687 assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
Daniel Berlin439042b2017-02-07 21:10:46 +0000688 "Predicateinfo def should have dominated this use");
Daniel Berlinc763fd12017-02-07 22:11:43 +0000689 VD.U->set(Result.Def);
Daniel Berlin439042b2017-02-07 21:10:46 +0000690 }
691 }
692}
693
694PredicateInfo::ValueInfo &PredicateInfo::getOrCreateValueInfo(Value *Operand) {
695 auto OIN = ValueInfoNums.find(Operand);
696 if (OIN == ValueInfoNums.end()) {
697 // This will grow it
698 ValueInfos.resize(ValueInfos.size() + 1);
699 // This will use the new size and give us a 0 based number of the info
700 auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
701 assert(InsertResult.second && "Value info number already existed?");
702 return ValueInfos[InsertResult.first->second];
703 }
704 return ValueInfos[OIN->second];
705}
706
707const PredicateInfo::ValueInfo &
708PredicateInfo::getValueInfo(Value *Operand) const {
709 auto OINI = ValueInfoNums.lookup(Operand);
710 assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
711 assert(OINI < ValueInfos.size() &&
712 "Value Info Number greater than size of Value Info Table");
713 return ValueInfos[OINI];
714}
715
716PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
717 AssumptionCache &AC)
Daniel Berlinb7df17e2017-06-29 17:01:14 +0000718 : F(F), DT(DT), AC(AC), OI(&DT) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000719 // Push an empty operand info so that we can detect 0 as not finding one
720 ValueInfos.resize(1);
721 buildPredicateInfo();
722}
723
Florian Hahn36d2e252018-07-24 14:49:52 +0000724// Remove all declarations we created . The PredicateInfo consumers are
725// responsible for remove the ssa_copy calls created.
726PredicateInfo::~PredicateInfo() {
727 // Collect function pointers in set first, as SmallSet uses a SmallVector
728 // internally and we have to remove the asserting value handles first.
729 SmallPtrSet<Function *, 20> FunctionPtrs;
730 for (auto &F : CreatedDeclarations)
731 FunctionPtrs.insert(&*F);
732 CreatedDeclarations.clear();
733
734 for (Function *F : FunctionPtrs) {
735 assert(F->user_begin() == F->user_end() &&
736 "PredicateInfo consumer did not remove all SSA copies.");
737 F->eraseFromParent();
738 }
739}
Daniel Berlin439042b2017-02-07 21:10:46 +0000740
741void PredicateInfo::verifyPredicateInfo() const {}
742
743char PredicateInfoPrinterLegacyPass::ID = 0;
744
745PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
746 : FunctionPass(ID) {
747 initializePredicateInfoPrinterLegacyPassPass(
748 *PassRegistry::getPassRegistry());
749}
750
751void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
752 AU.setPreservesAll();
753 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
754 AU.addRequired<AssumptionCacheTracker>();
755}
756
Florian Hahn36d2e252018-07-24 14:49:52 +0000757// Replace ssa_copy calls created by PredicateInfo with their operand.
758static void replaceCreatedSSACopys(PredicateInfo &PredInfo, Function &F) {
759 for (auto I = inst_begin(F), E = inst_end(F); I != E;) {
760 Instruction *Inst = &*I++;
761 const auto *PI = PredInfo.getPredicateInfoFor(Inst);
762 auto *II = dyn_cast<IntrinsicInst>(Inst);
763 if (!PI || !II || II->getIntrinsicID() != Intrinsic::ssa_copy)
764 continue;
765
766 Inst->replaceAllUsesWith(II->getOperand(0));
767 Inst->eraseFromParent();
768 }
769}
770
Daniel Berlin439042b2017-02-07 21:10:46 +0000771bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) {
772 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
773 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
774 auto PredInfo = make_unique<PredicateInfo>(F, DT, AC);
775 PredInfo->print(dbgs());
776 if (VerifyPredicateInfo)
777 PredInfo->verifyPredicateInfo();
Florian Hahn36d2e252018-07-24 14:49:52 +0000778
779 replaceCreatedSSACopys(*PredInfo, F);
Daniel Berlin439042b2017-02-07 21:10:46 +0000780 return false;
781}
782
783PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
784 FunctionAnalysisManager &AM) {
785 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
786 auto &AC = AM.getResult<AssumptionAnalysis>(F);
787 OS << "PredicateInfo for function: " << F.getName() << "\n";
Florian Hahn36d2e252018-07-24 14:49:52 +0000788 auto PredInfo = make_unique<PredicateInfo>(F, DT, AC);
789 PredInfo->print(OS);
Daniel Berlin439042b2017-02-07 21:10:46 +0000790
Florian Hahn36d2e252018-07-24 14:49:52 +0000791 replaceCreatedSSACopys(*PredInfo, F);
Daniel Berlin439042b2017-02-07 21:10:46 +0000792 return PreservedAnalyses::all();
793}
794
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000795/// An assembly annotator class to print PredicateInfo information in
Daniel Berlin439042b2017-02-07 21:10:46 +0000796/// comments.
797class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
798 friend class PredicateInfo;
799 const PredicateInfo *PredInfo;
800
801public:
802 PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
803
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000804 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
805 formatted_raw_ostream &OS) {}
Daniel Berlin439042b2017-02-07 21:10:46 +0000806
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000807 virtual void emitInstructionAnnot(const Instruction *I,
808 formatted_raw_ostream &OS) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000809 if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
810 OS << "; Has predicate info\n";
Daniel Berlinfccbda92017-02-22 22:20:58 +0000811 if (const auto *PB = dyn_cast<PredicateBranch>(PI)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000812 OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
Daniel Berlinfccbda92017-02-22 22:20:58 +0000813 << " Comparison:" << *PB->Condition << " Edge: [";
814 PB->From->printAsOperand(OS);
815 OS << ",";
816 PB->To->printAsOperand(OS);
817 OS << "] }\n";
818 } else if (const auto *PS = dyn_cast<PredicateSwitch>(PI)) {
819 OS << "; switch predicate info { CaseValue: " << *PS->CaseValue
820 << " Switch:" << *PS->Switch << " Edge: [";
821 PS->From->printAsOperand(OS);
822 OS << ",";
823 PS->To->printAsOperand(OS);
824 OS << "] }\n";
825 } else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000826 OS << "; assume predicate info {"
Daniel Berlin588e0be2017-02-18 23:06:38 +0000827 << " Comparison:" << *PA->Condition << " }\n";
Daniel Berlinfccbda92017-02-22 22:20:58 +0000828 }
Daniel Berlin439042b2017-02-07 21:10:46 +0000829 }
830 }
831};
832
833void PredicateInfo::print(raw_ostream &OS) const {
834 PredicateInfoAnnotatedWriter Writer(this);
835 F.print(OS, &Writer);
836}
837
838void PredicateInfo::dump() const {
839 PredicateInfoAnnotatedWriter Writer(this);
840 F.print(dbgs(), &Writer);
841}
842
843PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
844 FunctionAnalysisManager &AM) {
845 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
846 auto &AC = AM.getResult<AssumptionAnalysis>(F);
847 make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
848
849 return PreservedAnalyses::all();
850}
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000851}