blob: 3c288bab3779fff8d123165f40621a00bfb9688b [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 {
Florian Hahnc74808b2019-07-25 20:48:13 +0000128 DominatorTree &DT;
Daniel Berlinb7df17e2017-06-29 17:01:14 +0000129 OrderedInstructions &OI;
Florian Hahnc74808b2019-07-25 20:48:13 +0000130 ValueDFS_Compare(DominatorTree &DT, OrderedInstructions &OI)
131 : DT(DT), OI(OI) {}
Daniel Berlinb7df17e2017-06-29 17:01:14 +0000132
Daniel Berlin439042b2017-02-07 21:10:46 +0000133 bool operator()(const ValueDFS &A, const ValueDFS &B) const {
134 if (&A == &B)
135 return false;
136 // The only case we can't directly compare them is when they in the same
137 // block, and both have localnum == middle. In that case, we have to use
138 // comesbefore to see what the real ordering is, because they are in the
139 // same basic block.
140
Florian Hahnc74808b2019-07-25 20:48:13 +0000141 assert((A.DFSIn != B.DFSIn || A.DFSOut == B.DFSOut) &&
142 "Equal DFS-in numbers imply equal out numbers");
143 bool SameBlock = A.DFSIn == B.DFSIn;
Daniel Berlin439042b2017-02-07 21:10:46 +0000144
Daniel Berlindbe82642017-02-12 22:12:20 +0000145 // We want to put the def that will get used for a given set of phi uses,
146 // before those phi uses.
147 // So we sort by edge, then by def.
148 // Note that only phi nodes uses and defs can come last.
149 if (SameBlock && A.LocalNum == LN_Last && B.LocalNum == LN_Last)
150 return comparePHIRelated(A, B);
151
Florian Hahnc74808b2019-07-25 20:48:13 +0000152 bool isADef = A.Def;
153 bool isBDef = B.Def;
Daniel Berlin439042b2017-02-07 21:10:46 +0000154 if (!SameBlock || A.LocalNum != LN_Middle || B.LocalNum != LN_Middle)
Florian Hahnc74808b2019-07-25 20:48:13 +0000155 return std::tie(A.DFSIn, A.LocalNum, isADef) <
156 std::tie(B.DFSIn, B.LocalNum, isBDef);
Daniel Berlin439042b2017-02-07 21:10:46 +0000157 return localComesBefore(A, B);
158 }
159
Daniel Berlindbe82642017-02-12 22:12:20 +0000160 // For a phi use, or a non-materialized def, return the edge it represents.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000161 const std::pair<BasicBlock *, BasicBlock *>
Daniel Berlindbe82642017-02-12 22:12:20 +0000162 getBlockEdge(const ValueDFS &VD) const {
163 if (!VD.Def && VD.U) {
164 auto *PHI = cast<PHINode>(VD.U->getUser());
165 return std::make_pair(PHI->getIncomingBlock(*VD.U), PHI->getParent());
166 }
167 // This is really a non-materialized def.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000168 return ::getBlockEdge(VD.PInfo);
Daniel Berlindbe82642017-02-12 22:12:20 +0000169 }
170
171 // For two phi related values, return the ordering.
172 bool comparePHIRelated(const ValueDFS &A, const ValueDFS &B) const {
Florian Hahnc74808b2019-07-25 20:48:13 +0000173 BasicBlock *ASrc, *ADest, *BSrc, *BDest;
174 std::tie(ASrc, ADest) = getBlockEdge(A);
175 std::tie(BSrc, BDest) = getBlockEdge(B);
176
177#ifndef NDEBUG
178 // This function should only be used for values in the same BB, check that.
179 DomTreeNode *DomASrc = DT.getNode(ASrc);
180 DomTreeNode *DomBSrc = DT.getNode(BSrc);
181 assert(DomASrc->getDFSNumIn() == (unsigned)A.DFSIn &&
182 "DFS numbers for A should match the ones of the source block");
183 assert(DomBSrc->getDFSNumIn() == (unsigned)B.DFSIn &&
184 "DFS numbers for B should match the ones of the source block");
185 assert(A.DFSIn == B.DFSIn && "Values must be in the same block");
186#endif
187 (void)ASrc;
188 (void)BSrc;
189
190 // Use DFS numbers to compare destination blocks, to guarantee a
191 // deterministic order.
192 DomTreeNode *DomADest = DT.getNode(ADest);
193 DomTreeNode *DomBDest = DT.getNode(BDest);
194 unsigned AIn = DomADest->getDFSNumIn();
195 unsigned BIn = DomBDest->getDFSNumIn();
196 bool isADef = A.Def;
197 bool isBDef = B.Def;
198 assert((!A.Def || !A.U) && (!B.Def || !B.U) &&
199 "Def and U cannot be set at the same time");
200 // Now sort by edge destination and then defs before uses.
201 return std::tie(AIn, isADef) < std::tie(BIn, isBDef);
Daniel Berlindbe82642017-02-12 22:12:20 +0000202 }
203
Daniel Berlin439042b2017-02-07 21:10:46 +0000204 // Get the definition of an instruction that occurs in the middle of a block.
205 Value *getMiddleDef(const ValueDFS &VD) const {
206 if (VD.Def)
207 return VD.Def;
208 // It's possible for the defs and uses to be null. For branches, the local
209 // numbering will say the placed predicaeinfos should go first (IE
210 // LN_beginning), so we won't be in this function. For assumes, we will end
211 // up here, beause we need to order the def we will place relative to the
212 // assume. So for the purpose of ordering, we pretend the def is the assume
213 // because that is where we will insert the info.
Daniel Berlinc763fd12017-02-07 22:11:43 +0000214 if (!VD.U) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000215 assert(VD.PInfo &&
216 "No def, no use, and no predicateinfo should not occur");
217 assert(isa<PredicateAssume>(VD.PInfo) &&
218 "Middle of block should only occur for assumes");
219 return cast<PredicateAssume>(VD.PInfo)->AssumeInst;
220 }
221 return nullptr;
222 }
223
224 // Return either the Def, if it's not null, or the user of the Use, if the def
225 // is null.
Daniel Berlinc763fd12017-02-07 22:11:43 +0000226 const Instruction *getDefOrUser(const Value *Def, const Use *U) const {
Daniel Berlin439042b2017-02-07 21:10:46 +0000227 if (Def)
228 return cast<Instruction>(Def);
Daniel Berlinc763fd12017-02-07 22:11:43 +0000229 return cast<Instruction>(U->getUser());
Daniel Berlin439042b2017-02-07 21:10:46 +0000230 }
231
232 // This performs the necessary local basic block ordering checks to tell
233 // whether A comes before B, where both are in the same basic block.
234 bool localComesBefore(const ValueDFS &A, const ValueDFS &B) const {
235 auto *ADef = getMiddleDef(A);
236 auto *BDef = getMiddleDef(B);
237
238 // See if we have real values or uses. If we have real values, we are
239 // guaranteed they are instructions or arguments. No matter what, we are
240 // guaranteed they are in the same block if they are instructions.
241 auto *ArgA = dyn_cast_or_null<Argument>(ADef);
242 auto *ArgB = dyn_cast_or_null<Argument>(BDef);
243
Daniel Berlinb7df17e2017-06-29 17:01:14 +0000244 if (ArgA || ArgB)
245 return valueComesBefore(OI, ArgA, ArgB);
Daniel Berlin439042b2017-02-07 21:10:46 +0000246
Daniel Berlinc763fd12017-02-07 22:11:43 +0000247 auto *AInst = getDefOrUser(ADef, A.U);
248 auto *BInst = getDefOrUser(BDef, B.U);
Daniel Berlinb7df17e2017-06-29 17:01:14 +0000249 return valueComesBefore(OI, AInst, BInst);
Daniel Berlin439042b2017-02-07 21:10:46 +0000250 }
251};
252
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000253} // namespace PredicateInfoClasses
Daniel Berlin439042b2017-02-07 21:10:46 +0000254
Daniel Berlindbe82642017-02-12 22:12:20 +0000255bool PredicateInfo::stackIsInScope(const ValueDFSStack &Stack,
256 const ValueDFS &VDUse) const {
Daniel Berlin439042b2017-02-07 21:10:46 +0000257 if (Stack.empty())
258 return false;
Daniel Berlindbe82642017-02-12 22:12:20 +0000259 // If it's a phi only use, make sure it's for this phi node edge, and that the
260 // 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 +0000261 // EdgeOnly, we need to pop the stack. We deliberately sort phi uses next to
Daniel Berlindbe82642017-02-12 22:12:20 +0000262 // the defs they must go with so that we can know it's time to pop the stack
263 // when we hit the end of the phi uses for a given def.
Daniel Berlin588e0be2017-02-18 23:06:38 +0000264 if (Stack.back().EdgeOnly) {
Daniel Berlindbe82642017-02-12 22:12:20 +0000265 if (!VDUse.U)
266 return false;
267 auto *PHI = dyn_cast<PHINode>(VDUse.U->getUser());
268 if (!PHI)
269 return false;
Daniel Berlinfccbda92017-02-22 22:20:58 +0000270 // Check edge
Daniel Berlindbe82642017-02-12 22:12:20 +0000271 BasicBlock *EdgePred = PHI->getIncomingBlock(*VDUse.U);
Daniel Berlinfccbda92017-02-22 22:20:58 +0000272 if (EdgePred != getBranchBlock(Stack.back().PInfo))
Daniel Berlindbe82642017-02-12 22:12:20 +0000273 return false;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000274
275 // Use dominates, which knows how to handle edge dominance.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000276 return DT.dominates(getBlockEdge(Stack.back().PInfo), *VDUse.U);
Daniel Berlindbe82642017-02-12 22:12:20 +0000277 }
278
279 return (VDUse.DFSIn >= Stack.back().DFSIn &&
280 VDUse.DFSOut <= Stack.back().DFSOut);
Daniel Berlin439042b2017-02-07 21:10:46 +0000281}
282
Daniel Berlindbe82642017-02-12 22:12:20 +0000283void PredicateInfo::popStackUntilDFSScope(ValueDFSStack &Stack,
284 const ValueDFS &VD) {
285 while (!Stack.empty() && !stackIsInScope(Stack, VD))
Daniel Berlin439042b2017-02-07 21:10:46 +0000286 Stack.pop_back();
287}
288
289// Convert the uses of Op into a vector of uses, associating global and local
290// DFS info with each one.
291void PredicateInfo::convertUsesToDFSOrdered(
292 Value *Op, SmallVectorImpl<ValueDFS> &DFSOrderedSet) {
293 for (auto &U : Op->uses()) {
294 if (auto *I = dyn_cast<Instruction>(U.getUser())) {
295 ValueDFS VD;
296 // Put the phi node uses in the incoming block.
297 BasicBlock *IBlock;
298 if (auto *PN = dyn_cast<PHINode>(I)) {
299 IBlock = PN->getIncomingBlock(U);
300 // Make phi node users appear last in the incoming block
301 // they are from.
302 VD.LocalNum = LN_Last;
303 } else {
304 // If it's not a phi node use, it is somewhere in the middle of the
305 // block.
306 IBlock = I->getParent();
307 VD.LocalNum = LN_Middle;
308 }
309 DomTreeNode *DomNode = DT.getNode(IBlock);
310 // It's possible our use is in an unreachable block. Skip it if so.
311 if (!DomNode)
312 continue;
313 VD.DFSIn = DomNode->getDFSNumIn();
314 VD.DFSOut = DomNode->getDFSNumOut();
Daniel Berlinc763fd12017-02-07 22:11:43 +0000315 VD.U = &U;
Daniel Berlin439042b2017-02-07 21:10:46 +0000316 DFSOrderedSet.push_back(VD);
317 }
318 }
319}
320
321// Collect relevant operations from Comparison that we may want to insert copies
322// for.
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000323void collectCmpOps(CmpInst *Comparison, SmallVectorImpl<Value *> &CmpOperands) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000324 auto *Op0 = Comparison->getOperand(0);
325 auto *Op1 = Comparison->getOperand(1);
326 if (Op0 == Op1)
327 return;
328 CmpOperands.push_back(Comparison);
329 // Only want real values, not constants. Additionally, operands with one use
330 // are only being used in the comparison, which means they will not be useful
331 // for us to consider for predicateinfo.
332 //
Daniel Berlin588e0be2017-02-18 23:06:38 +0000333 if ((isa<Instruction>(Op0) || isa<Argument>(Op0)) && !Op0->hasOneUse())
Daniel Berlin439042b2017-02-07 21:10:46 +0000334 CmpOperands.push_back(Op0);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000335 if ((isa<Instruction>(Op1) || isa<Argument>(Op1)) && !Op1->hasOneUse())
Daniel Berlin439042b2017-02-07 21:10:46 +0000336 CmpOperands.push_back(Op1);
337}
338
Daniel Berlin588e0be2017-02-18 23:06:38 +0000339// Add Op, PB to the list of value infos for Op, and mark Op to be renamed.
Florian Hahnc0d0e3b2019-07-25 15:35:10 +0000340void PredicateInfo::addInfoFor(SmallVectorImpl<Value *> &OpsToRename, Value *Op,
Daniel Berlin588e0be2017-02-18 23:06:38 +0000341 PredicateBase *PB) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000342 auto &OperandInfo = getOrCreateValueInfo(Op);
Florian Hahnc0d0e3b2019-07-25 15:35:10 +0000343 if (OperandInfo.Infos.empty())
344 OpsToRename.push_back(Op);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000345 AllInfos.push_back(PB);
346 OperandInfo.Infos.push_back(PB);
347}
348
Daniel Berlin439042b2017-02-07 21:10:46 +0000349// Process an assume instruction and place relevant operations we want to rename
350// into OpsToRename.
351void PredicateInfo::processAssume(IntrinsicInst *II, BasicBlock *AssumeBB,
Florian Hahnc0d0e3b2019-07-25 15:35:10 +0000352 SmallVectorImpl<Value *> &OpsToRename) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000353 // See if we have a comparison we support
Daniel Berlin439042b2017-02-07 21:10:46 +0000354 SmallVector<Value *, 8> CmpOperands;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000355 SmallVector<Value *, 2> ConditionsToProcess;
Daniel Berlin439042b2017-02-07 21:10:46 +0000356 CmpInst::Predicate Pred;
357 Value *Operand = II->getOperand(0);
358 if (m_c_And(m_Cmp(Pred, m_Value(), m_Value()),
359 m_Cmp(Pred, m_Value(), m_Value()))
360 .match(II->getOperand(0))) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000361 ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(0));
362 ConditionsToProcess.push_back(cast<BinaryOperator>(Operand)->getOperand(1));
363 ConditionsToProcess.push_back(Operand);
364 } else if (isa<CmpInst>(Operand)) {
365
366 ConditionsToProcess.push_back(Operand);
Daniel Berlin439042b2017-02-07 21:10:46 +0000367 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000368 for (auto Cond : ConditionsToProcess) {
369 if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000370 collectCmpOps(Cmp, CmpOperands);
371 // Now add our copy infos for our operands
372 for (auto *Op : CmpOperands) {
Daniel Berlin588e0be2017-02-18 23:06:38 +0000373 auto *PA = new PredicateAssume(Op, II, Cmp);
374 addInfoFor(OpsToRename, Op, PA);
Daniel Berlin439042b2017-02-07 21:10:46 +0000375 }
376 CmpOperands.clear();
Daniel Berlin588e0be2017-02-18 23:06:38 +0000377 } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
378 // Otherwise, it should be an AND.
379 assert(BinOp->getOpcode() == Instruction::And &&
Simon Pilgrimdba90112017-02-19 00:33:37 +0000380 "Should have been an AND");
381 auto *PA = new PredicateAssume(BinOp, II, BinOp);
382 addInfoFor(OpsToRename, BinOp, PA);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000383 } else {
384 llvm_unreachable("Unknown type of condition");
Daniel Berlin439042b2017-02-07 21:10:46 +0000385 }
386 }
387}
388
389// Process a block terminating branch, and place relevant operations to be
390// renamed into OpsToRename.
391void PredicateInfo::processBranch(BranchInst *BI, BasicBlock *BranchBB,
Florian Hahnc0d0e3b2019-07-25 15:35:10 +0000392 SmallVectorImpl<Value *> &OpsToRename) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000393 BasicBlock *FirstBB = BI->getSuccessor(0);
394 BasicBlock *SecondBB = BI->getSuccessor(1);
Daniel Berlin439042b2017-02-07 21:10:46 +0000395 SmallVector<BasicBlock *, 2> SuccsToProcess;
Daniel Berlindbe82642017-02-12 22:12:20 +0000396 SuccsToProcess.push_back(FirstBB);
397 SuccsToProcess.push_back(SecondBB);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000398 SmallVector<Value *, 2> ConditionsToProcess;
399
400 auto InsertHelper = [&](Value *Op, bool isAnd, bool isOr, Value *Cond) {
401 for (auto *Succ : SuccsToProcess) {
402 // Don't try to insert on a self-edge. This is mainly because we will
403 // eliminate during renaming anyway.
404 if (Succ == BranchBB)
405 continue;
406 bool TakenEdge = (Succ == FirstBB);
407 // For and, only insert on the true edge
408 // For or, only insert on the false edge
409 if ((isAnd && !TakenEdge) || (isOr && TakenEdge))
410 continue;
411 PredicateBase *PB =
412 new PredicateBranch(Op, BranchBB, Succ, Cond, TakenEdge);
413 addInfoFor(OpsToRename, Op, PB);
414 if (!Succ->getSinglePredecessor())
415 EdgeUsesOnly.insert({BranchBB, Succ});
416 }
417 };
Daniel Berlin439042b2017-02-07 21:10:46 +0000418
419 // Match combinations of conditions.
Daniel Berlin588e0be2017-02-18 23:06:38 +0000420 CmpInst::Predicate Pred;
421 bool isAnd = false;
422 bool isOr = false;
423 SmallVector<Value *, 8> CmpOperands;
Daniel Berlin439042b2017-02-07 21:10:46 +0000424 if (match(BI->getCondition(), m_And(m_Cmp(Pred, m_Value(), m_Value()),
425 m_Cmp(Pred, m_Value(), m_Value()))) ||
426 match(BI->getCondition(), m_Or(m_Cmp(Pred, m_Value(), m_Value()),
427 m_Cmp(Pred, m_Value(), m_Value())))) {
428 auto *BinOp = cast<BinaryOperator>(BI->getCondition());
429 if (BinOp->getOpcode() == Instruction::And)
430 isAnd = true;
431 else if (BinOp->getOpcode() == Instruction::Or)
432 isOr = true;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000433 ConditionsToProcess.push_back(BinOp->getOperand(0));
434 ConditionsToProcess.push_back(BinOp->getOperand(1));
435 ConditionsToProcess.push_back(BI->getCondition());
436 } else if (isa<CmpInst>(BI->getCondition())) {
437 ConditionsToProcess.push_back(BI->getCondition());
Daniel Berlin439042b2017-02-07 21:10:46 +0000438 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000439 for (auto Cond : ConditionsToProcess) {
440 if (auto *Cmp = dyn_cast<CmpInst>(Cond)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000441 collectCmpOps(Cmp, CmpOperands);
442 // Now add our copy infos for our operands
Daniel Berlin588e0be2017-02-18 23:06:38 +0000443 for (auto *Op : CmpOperands)
444 InsertHelper(Op, isAnd, isOr, Cmp);
445 } else if (auto *BinOp = dyn_cast<BinaryOperator>(Cond)) {
446 // This must be an AND or an OR.
447 assert((BinOp->getOpcode() == Instruction::And ||
448 BinOp->getOpcode() == Instruction::Or) &&
449 "Should have been an AND or an OR");
450 // The actual value of the binop is not subject to the same restrictions
451 // as the comparison. It's either true or false on the true/false branch.
Simon Pilgrimdba90112017-02-19 00:33:37 +0000452 InsertHelper(BinOp, false, false, BinOp);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000453 } else {
454 llvm_unreachable("Unknown type of condition");
Daniel Berlin439042b2017-02-07 21:10:46 +0000455 }
Daniel Berlin588e0be2017-02-18 23:06:38 +0000456 CmpOperands.clear();
Daniel Berlin439042b2017-02-07 21:10:46 +0000457 }
458}
Daniel Berlinfccbda92017-02-22 22:20:58 +0000459// Process a block terminating switch, and place relevant operations to be
460// renamed into OpsToRename.
461void PredicateInfo::processSwitch(SwitchInst *SI, BasicBlock *BranchBB,
Florian Hahnc0d0e3b2019-07-25 15:35:10 +0000462 SmallVectorImpl<Value *> &OpsToRename) {
Daniel Berlinfccbda92017-02-22 22:20:58 +0000463 Value *Op = SI->getCondition();
464 if ((!isa<Instruction>(Op) && !isa<Argument>(Op)) || Op->hasOneUse())
465 return;
466
467 // Remember how many outgoing edges there are to every successor.
468 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
469 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
470 BasicBlock *TargetBlock = SI->getSuccessor(i);
471 ++SwitchEdges[TargetBlock];
472 }
473
474 // Now propagate info for each case value
475 for (auto C : SI->cases()) {
476 BasicBlock *TargetBlock = C.getCaseSuccessor();
477 if (SwitchEdges.lookup(TargetBlock) == 1) {
478 PredicateSwitch *PS = new PredicateSwitch(
479 Op, SI->getParent(), TargetBlock, C.getCaseValue(), SI);
480 addInfoFor(OpsToRename, Op, PS);
481 if (!TargetBlock->getSinglePredecessor())
482 EdgeUsesOnly.insert({BranchBB, TargetBlock});
483 }
484 }
485}
Daniel Berlin439042b2017-02-07 21:10:46 +0000486
487// Build predicate info for our function
488void PredicateInfo::buildPredicateInfo() {
489 DT.updateDFSNumbers();
490 // Collect operands to rename from all conditional branch terminators, as well
491 // as assume statements.
Florian Hahnc0d0e3b2019-07-25 15:35:10 +0000492 SmallVector<Value *, 8> OpsToRename;
Daniel Berlin439042b2017-02-07 21:10:46 +0000493 for (auto DTN : depth_first(DT.getRootNode())) {
494 BasicBlock *BranchBB = DTN->getBlock();
495 if (auto *BI = dyn_cast<BranchInst>(BranchBB->getTerminator())) {
496 if (!BI->isConditional())
497 continue;
Daniel Berlin6d2db9e2017-06-14 21:19:52 +0000498 // Can't insert conditional information if they all go to the same place.
499 if (BI->getSuccessor(0) == BI->getSuccessor(1))
500 continue;
Daniel Berlin439042b2017-02-07 21:10:46 +0000501 processBranch(BI, BranchBB, OpsToRename);
Daniel Berlinfccbda92017-02-22 22:20:58 +0000502 } else if (auto *SI = dyn_cast<SwitchInst>(BranchBB->getTerminator())) {
503 processSwitch(SI, BranchBB, OpsToRename);
Daniel Berlin439042b2017-02-07 21:10:46 +0000504 }
505 }
506 for (auto &Assume : AC.assumptions()) {
507 if (auto *II = dyn_cast_or_null<IntrinsicInst>(Assume))
Taewook Oh9d020de2019-05-15 19:35:38 +0000508 if (DT.isReachableFromEntry(II->getParent()))
509 processAssume(II, II->getParent(), OpsToRename);
Daniel Berlin439042b2017-02-07 21:10:46 +0000510 }
511 // Now rename all our operations.
512 renameUses(OpsToRename);
513}
Daniel Berlinfccbda92017-02-22 22:20:58 +0000514
Florian Hahn36d2e252018-07-24 14:49:52 +0000515// Create a ssa_copy declaration with custom mangling, because
516// Intrinsic::getDeclaration does not handle overloaded unnamed types properly:
517// all unnamed types get mangled to the same string. We use the pointer
518// to the type as name here, as it guarantees unique names for different
519// types and we remove the declarations when destroying PredicateInfo.
520// It is a workaround for PR38117, because solving it in a fully general way is
521// tricky (FIXME).
522static Function *getCopyDeclaration(Module *M, Type *Ty) {
523 std::string Name = "llvm.ssa.copy." + utostr((uintptr_t) Ty);
James Y Knight13680222019-02-01 02:28:03 +0000524 return cast<Function>(
525 M->getOrInsertFunction(Name,
526 getType(M->getContext(), Intrinsic::ssa_copy, Ty))
527 .getCallee());
Florian Hahn36d2e252018-07-24 14:49:52 +0000528}
529
Daniel Berlinfccbda92017-02-22 22:20:58 +0000530// Given the renaming stack, make all the operands currently on the stack real
531// by inserting them into the IR. Return the last operation's value.
Daniel Berlin439042b2017-02-07 21:10:46 +0000532Value *PredicateInfo::materializeStack(unsigned int &Counter,
533 ValueDFSStack &RenameStack,
534 Value *OrigOp) {
535 // Find the first thing we have to materialize
536 auto RevIter = RenameStack.rbegin();
537 for (; RevIter != RenameStack.rend(); ++RevIter)
538 if (RevIter->Def)
539 break;
540
541 size_t Start = RevIter - RenameStack.rbegin();
542 // The maximum number of things we should be trying to materialize at once
543 // right now is 4, depending on if we had an assume, a branch, and both used
544 // and of conditions.
545 for (auto RenameIter = RenameStack.end() - Start;
546 RenameIter != RenameStack.end(); ++RenameIter) {
547 auto *Op =
548 RenameIter == RenameStack.begin() ? OrigOp : (RenameIter - 1)->Def;
549 ValueDFS &Result = *RenameIter;
550 auto *ValInfo = Result.PInfo;
Daniel Berlinfccbda92017-02-22 22:20:58 +0000551 // For edge predicates, we can just place the operand in the block before
Daniel Berlindbe82642017-02-12 22:12:20 +0000552 // the terminator. For assume, we have to place it right before the assume
553 // to ensure we dominate all of our uses. Always insert right before the
554 // relevant instruction (terminator, assume), so that we insert in proper
555 // order in the case of multiple predicateinfo in the same block.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000556 if (isa<PredicateWithEdge>(ValInfo)) {
557 IRBuilder<> B(getBranchTerminator(ValInfo));
Florian Hahn36d2e252018-07-24 14:49:52 +0000558 Function *IF = getCopyDeclaration(F.getParent(), Op->getType());
Matthias Braun9fd397b2018-10-31 00:23:23 +0000559 if (empty(IF->users()))
Florian Hahn36d2e252018-07-24 14:49:52 +0000560 CreatedDeclarations.insert(IF);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000561 CallInst *PIC =
562 B.CreateCall(IF, Op, Op->getName() + "." + Twine(Counter++));
Daniel Berlin439042b2017-02-07 21:10:46 +0000563 PredicateMap.insert({PIC, ValInfo});
564 Result.Def = PIC;
565 } else {
566 auto *PAssume = dyn_cast<PredicateAssume>(ValInfo);
567 assert(PAssume &&
568 "Should not have gotten here without it being an assume");
Daniel Berlindbe82642017-02-12 22:12:20 +0000569 IRBuilder<> B(PAssume->AssumeInst);
Florian Hahn36d2e252018-07-24 14:49:52 +0000570 Function *IF = getCopyDeclaration(F.getParent(), Op->getType());
Matthias Braun9fd397b2018-10-31 00:23:23 +0000571 if (empty(IF->users()))
Florian Hahn36d2e252018-07-24 14:49:52 +0000572 CreatedDeclarations.insert(IF);
Daniel Berlin588e0be2017-02-18 23:06:38 +0000573 CallInst *PIC = B.CreateCall(IF, Op);
Daniel Berlin439042b2017-02-07 21:10:46 +0000574 PredicateMap.insert({PIC, ValInfo});
575 Result.Def = PIC;
576 }
577 }
578 return RenameStack.back().Def;
579}
580
581// Instead of the standard SSA renaming algorithm, which is O(Number of
582// instructions), and walks the entire dominator tree, we walk only the defs +
583// uses. The standard SSA renaming algorithm does not really rely on the
584// dominator tree except to order the stack push/pops of the renaming stacks, so
585// that defs end up getting pushed before hitting the correct uses. This does
586// not require the dominator tree, only the *order* of the dominator tree. The
587// complete and correct ordering of the defs and uses, in dominator tree is
588// contained in the DFS numbering of the dominator tree. So we sort the defs and
589// uses into the DFS ordering, and then just use the renaming stack as per
590// normal, pushing when we hit a def (which is a predicateinfo instruction),
591// popping when we are out of the dfs scope for that def, and replacing any uses
592// with top of stack if it exists. In order to handle liveness without
593// propagating liveness info, we don't actually insert the predicateinfo
594// instruction def until we see a use that it would dominate. Once we see such
595// a use, we materialize the predicateinfo instruction in the right place and
596// use it.
597//
598// TODO: Use this algorithm to perform fast single-variable renaming in
599// promotememtoreg and memoryssa.
Florian Hahnc0d0e3b2019-07-25 15:35:10 +0000600void PredicateInfo::renameUses(SmallVectorImpl<Value *> &OpsToRename) {
Florian Hahnc74808b2019-07-25 20:48:13 +0000601 ValueDFS_Compare Compare(DT, OI);
Daniel Berlin439042b2017-02-07 21:10:46 +0000602 // Compute liveness, and rename in O(uses) per Op.
603 for (auto *Op : OpsToRename) {
Florian Hahn5ac26292018-06-20 17:42:01 +0000604 LLVM_DEBUG(dbgs() << "Visiting " << *Op << "\n");
Daniel Berlin439042b2017-02-07 21:10:46 +0000605 unsigned Counter = 0;
606 SmallVector<ValueDFS, 16> OrderedUses;
607 const auto &ValueInfo = getValueInfo(Op);
608 // Insert the possible copies into the def/use list.
609 // They will become real copies if we find a real use for them, and never
610 // created otherwise.
611 for (auto &PossibleCopy : ValueInfo.Infos) {
612 ValueDFS VD;
Daniel Berlin439042b2017-02-07 21:10:46 +0000613 // Determine where we are going to place the copy by the copy type.
614 // The predicate info for branches always come first, they will get
615 // materialized in the split block at the top of the block.
616 // The predicate info for assumes will be somewhere in the middle,
617 // it will get materialized in front of the assume.
Daniel Berlindbe82642017-02-12 22:12:20 +0000618 if (const auto *PAssume = dyn_cast<PredicateAssume>(PossibleCopy)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000619 VD.LocalNum = LN_Middle;
Daniel Berlindbe82642017-02-12 22:12:20 +0000620 DomTreeNode *DomNode = DT.getNode(PAssume->AssumeInst->getParent());
621 if (!DomNode)
622 continue;
623 VD.DFSIn = DomNode->getDFSNumIn();
624 VD.DFSOut = DomNode->getDFSNumOut();
625 VD.PInfo = PossibleCopy;
626 OrderedUses.push_back(VD);
Daniel Berlinfccbda92017-02-22 22:20:58 +0000627 } else if (isa<PredicateWithEdge>(PossibleCopy)) {
Daniel Berlindbe82642017-02-12 22:12:20 +0000628 // If we can only do phi uses, we treat it like it's in the branch
629 // block, and handle it specially. We know that it goes last, and only
630 // dominate phi uses.
Daniel Berlinfccbda92017-02-22 22:20:58 +0000631 auto BlockEdge = getBlockEdge(PossibleCopy);
632 if (EdgeUsesOnly.count(BlockEdge)) {
Daniel Berlindbe82642017-02-12 22:12:20 +0000633 VD.LocalNum = LN_Last;
Daniel Berlinfccbda92017-02-22 22:20:58 +0000634 auto *DomNode = DT.getNode(BlockEdge.first);
Daniel Berlindbe82642017-02-12 22:12:20 +0000635 if (DomNode) {
636 VD.DFSIn = DomNode->getDFSNumIn();
637 VD.DFSOut = DomNode->getDFSNumOut();
638 VD.PInfo = PossibleCopy;
Daniel Berlin588e0be2017-02-18 23:06:38 +0000639 VD.EdgeOnly = true;
Daniel Berlindbe82642017-02-12 22:12:20 +0000640 OrderedUses.push_back(VD);
641 }
642 } else {
643 // Otherwise, we are in the split block (even though we perform
644 // insertion in the branch block).
645 // Insert a possible copy at the split block and before the branch.
646 VD.LocalNum = LN_First;
Daniel Berlinfccbda92017-02-22 22:20:58 +0000647 auto *DomNode = DT.getNode(BlockEdge.second);
Daniel Berlindbe82642017-02-12 22:12:20 +0000648 if (DomNode) {
649 VD.DFSIn = DomNode->getDFSNumIn();
650 VD.DFSOut = DomNode->getDFSNumOut();
651 VD.PInfo = PossibleCopy;
652 OrderedUses.push_back(VD);
653 }
654 }
655 }
Daniel Berlin439042b2017-02-07 21:10:46 +0000656 }
657
658 convertUsesToDFSOrdered(Op, OrderedUses);
Mandeep Singh Grange6bb6632017-11-17 00:43:24 +0000659 // Here we require a stable sort because we do not bother to try to
660 // assign an order to the operands the uses represent. Thus, two
661 // uses in the same instruction do not have a strict sort order
662 // currently and will be considered equal. We could get rid of the
663 // stable sort by creating one if we wanted.
Fangrui Songefd94c52019-04-23 14:51:27 +0000664 llvm::stable_sort(OrderedUses, Compare);
Daniel Berlin439042b2017-02-07 21:10:46 +0000665 SmallVector<ValueDFS, 8> RenameStack;
666 // For each use, sorted into dfs order, push values and replaces uses with
667 // top of stack, which will represent the reaching def.
668 for (auto &VD : OrderedUses) {
669 // We currently do not materialize copy over copy, but we should decide if
670 // we want to.
671 bool PossibleCopy = VD.PInfo != nullptr;
672 if (RenameStack.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000673 LLVM_DEBUG(dbgs() << "Rename Stack is empty\n");
Daniel Berlin439042b2017-02-07 21:10:46 +0000674 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000675 LLVM_DEBUG(dbgs() << "Rename Stack Top DFS numbers are ("
676 << RenameStack.back().DFSIn << ","
677 << RenameStack.back().DFSOut << ")\n");
Daniel Berlin439042b2017-02-07 21:10:46 +0000678 }
679
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000680 LLVM_DEBUG(dbgs() << "Current DFS numbers are (" << VD.DFSIn << ","
681 << VD.DFSOut << ")\n");
Daniel Berlin439042b2017-02-07 21:10:46 +0000682
683 bool ShouldPush = (VD.Def || PossibleCopy);
Daniel Berlindbe82642017-02-12 22:12:20 +0000684 bool OutOfScope = !stackIsInScope(RenameStack, VD);
Daniel Berlin439042b2017-02-07 21:10:46 +0000685 if (OutOfScope || ShouldPush) {
686 // Sync to our current scope.
Daniel Berlindbe82642017-02-12 22:12:20 +0000687 popStackUntilDFSScope(RenameStack, VD);
Daniel Berlin439042b2017-02-07 21:10:46 +0000688 if (ShouldPush) {
689 RenameStack.push_back(VD);
690 }
691 }
692 // If we get to this point, and the stack is empty we must have a use
693 // with no renaming needed, just skip it.
694 if (RenameStack.empty())
695 continue;
696 // Skip values, only want to rename the uses
697 if (VD.Def || PossibleCopy)
698 continue;
Daniel Berlina4b5c012017-02-19 04:29:01 +0000699 if (!DebugCounter::shouldExecute(RenameCounter)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000700 LLVM_DEBUG(dbgs() << "Skipping execution due to debug counter\n");
Daniel Berlina4b5c012017-02-19 04:29:01 +0000701 continue;
702 }
Daniel Berlin439042b2017-02-07 21:10:46 +0000703 ValueDFS &Result = RenameStack.back();
704
705 // If the possible copy dominates something, materialize our stack up to
706 // this point. This ensures every comparison that affects our operation
707 // ends up with predicateinfo.
708 if (!Result.Def)
709 Result.Def = materializeStack(Counter, RenameStack, Op);
710
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000711 LLVM_DEBUG(dbgs() << "Found replacement " << *Result.Def << " for "
712 << *VD.U->get() << " in " << *(VD.U->getUser())
713 << "\n");
Daniel Berlinc763fd12017-02-07 22:11:43 +0000714 assert(DT.dominates(cast<Instruction>(Result.Def), *VD.U) &&
Daniel Berlin439042b2017-02-07 21:10:46 +0000715 "Predicateinfo def should have dominated this use");
Daniel Berlinc763fd12017-02-07 22:11:43 +0000716 VD.U->set(Result.Def);
Daniel Berlin439042b2017-02-07 21:10:46 +0000717 }
718 }
719}
720
721PredicateInfo::ValueInfo &PredicateInfo::getOrCreateValueInfo(Value *Operand) {
722 auto OIN = ValueInfoNums.find(Operand);
723 if (OIN == ValueInfoNums.end()) {
724 // This will grow it
725 ValueInfos.resize(ValueInfos.size() + 1);
726 // This will use the new size and give us a 0 based number of the info
727 auto InsertResult = ValueInfoNums.insert({Operand, ValueInfos.size() - 1});
728 assert(InsertResult.second && "Value info number already existed?");
729 return ValueInfos[InsertResult.first->second];
730 }
731 return ValueInfos[OIN->second];
732}
733
734const PredicateInfo::ValueInfo &
735PredicateInfo::getValueInfo(Value *Operand) const {
736 auto OINI = ValueInfoNums.lookup(Operand);
737 assert(OINI != 0 && "Operand was not really in the Value Info Numbers");
738 assert(OINI < ValueInfos.size() &&
739 "Value Info Number greater than size of Value Info Table");
740 return ValueInfos[OINI];
741}
742
743PredicateInfo::PredicateInfo(Function &F, DominatorTree &DT,
744 AssumptionCache &AC)
Daniel Berlinb7df17e2017-06-29 17:01:14 +0000745 : F(F), DT(DT), AC(AC), OI(&DT) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000746 // Push an empty operand info so that we can detect 0 as not finding one
747 ValueInfos.resize(1);
748 buildPredicateInfo();
749}
750
Florian Hahn36d2e252018-07-24 14:49:52 +0000751// Remove all declarations we created . The PredicateInfo consumers are
752// responsible for remove the ssa_copy calls created.
753PredicateInfo::~PredicateInfo() {
754 // Collect function pointers in set first, as SmallSet uses a SmallVector
755 // internally and we have to remove the asserting value handles first.
756 SmallPtrSet<Function *, 20> FunctionPtrs;
757 for (auto &F : CreatedDeclarations)
758 FunctionPtrs.insert(&*F);
759 CreatedDeclarations.clear();
760
761 for (Function *F : FunctionPtrs) {
762 assert(F->user_begin() == F->user_end() &&
763 "PredicateInfo consumer did not remove all SSA copies.");
764 F->eraseFromParent();
765 }
766}
Daniel Berlin439042b2017-02-07 21:10:46 +0000767
768void PredicateInfo::verifyPredicateInfo() const {}
769
770char PredicateInfoPrinterLegacyPass::ID = 0;
771
772PredicateInfoPrinterLegacyPass::PredicateInfoPrinterLegacyPass()
773 : FunctionPass(ID) {
774 initializePredicateInfoPrinterLegacyPassPass(
775 *PassRegistry::getPassRegistry());
776}
777
778void PredicateInfoPrinterLegacyPass::getAnalysisUsage(AnalysisUsage &AU) const {
779 AU.setPreservesAll();
780 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
781 AU.addRequired<AssumptionCacheTracker>();
782}
783
Florian Hahn36d2e252018-07-24 14:49:52 +0000784// Replace ssa_copy calls created by PredicateInfo with their operand.
785static void replaceCreatedSSACopys(PredicateInfo &PredInfo, Function &F) {
786 for (auto I = inst_begin(F), E = inst_end(F); I != E;) {
787 Instruction *Inst = &*I++;
788 const auto *PI = PredInfo.getPredicateInfoFor(Inst);
789 auto *II = dyn_cast<IntrinsicInst>(Inst);
790 if (!PI || !II || II->getIntrinsicID() != Intrinsic::ssa_copy)
791 continue;
792
793 Inst->replaceAllUsesWith(II->getOperand(0));
794 Inst->eraseFromParent();
795 }
796}
797
Daniel Berlin439042b2017-02-07 21:10:46 +0000798bool PredicateInfoPrinterLegacyPass::runOnFunction(Function &F) {
799 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
800 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000801 auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
Daniel Berlin439042b2017-02-07 21:10:46 +0000802 PredInfo->print(dbgs());
803 if (VerifyPredicateInfo)
804 PredInfo->verifyPredicateInfo();
Florian Hahn36d2e252018-07-24 14:49:52 +0000805
806 replaceCreatedSSACopys(*PredInfo, F);
Daniel Berlin439042b2017-02-07 21:10:46 +0000807 return false;
808}
809
810PreservedAnalyses PredicateInfoPrinterPass::run(Function &F,
811 FunctionAnalysisManager &AM) {
812 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
813 auto &AC = AM.getResult<AssumptionAnalysis>(F);
814 OS << "PredicateInfo for function: " << F.getName() << "\n";
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000815 auto PredInfo = std::make_unique<PredicateInfo>(F, DT, AC);
Florian Hahn36d2e252018-07-24 14:49:52 +0000816 PredInfo->print(OS);
Daniel Berlin439042b2017-02-07 21:10:46 +0000817
Florian Hahn36d2e252018-07-24 14:49:52 +0000818 replaceCreatedSSACopys(*PredInfo, F);
Daniel Berlin439042b2017-02-07 21:10:46 +0000819 return PreservedAnalyses::all();
820}
821
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000822/// An assembly annotator class to print PredicateInfo information in
Daniel Berlin439042b2017-02-07 21:10:46 +0000823/// comments.
824class PredicateInfoAnnotatedWriter : public AssemblyAnnotationWriter {
825 friend class PredicateInfo;
826 const PredicateInfo *PredInfo;
827
828public:
829 PredicateInfoAnnotatedWriter(const PredicateInfo *M) : PredInfo(M) {}
830
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000831 virtual void emitBasicBlockStartAnnot(const BasicBlock *BB,
832 formatted_raw_ostream &OS) {}
Daniel Berlin439042b2017-02-07 21:10:46 +0000833
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000834 virtual void emitInstructionAnnot(const Instruction *I,
835 formatted_raw_ostream &OS) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000836 if (const auto *PI = PredInfo->getPredicateInfoFor(I)) {
837 OS << "; Has predicate info\n";
Daniel Berlinfccbda92017-02-22 22:20:58 +0000838 if (const auto *PB = dyn_cast<PredicateBranch>(PI)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000839 OS << "; branch predicate info { TrueEdge: " << PB->TrueEdge
Daniel Berlinfccbda92017-02-22 22:20:58 +0000840 << " Comparison:" << *PB->Condition << " Edge: [";
841 PB->From->printAsOperand(OS);
842 OS << ",";
843 PB->To->printAsOperand(OS);
844 OS << "] }\n";
845 } else if (const auto *PS = dyn_cast<PredicateSwitch>(PI)) {
846 OS << "; switch predicate info { CaseValue: " << *PS->CaseValue
847 << " Switch:" << *PS->Switch << " Edge: [";
848 PS->From->printAsOperand(OS);
849 OS << ",";
850 PS->To->printAsOperand(OS);
851 OS << "] }\n";
852 } else if (const auto *PA = dyn_cast<PredicateAssume>(PI)) {
Daniel Berlin439042b2017-02-07 21:10:46 +0000853 OS << "; assume predicate info {"
Daniel Berlin588e0be2017-02-18 23:06:38 +0000854 << " Comparison:" << *PA->Condition << " }\n";
Daniel Berlinfccbda92017-02-22 22:20:58 +0000855 }
Daniel Berlin439042b2017-02-07 21:10:46 +0000856 }
857 }
858};
859
860void PredicateInfo::print(raw_ostream &OS) const {
861 PredicateInfoAnnotatedWriter Writer(this);
862 F.print(OS, &Writer);
863}
864
865void PredicateInfo::dump() const {
866 PredicateInfoAnnotatedWriter Writer(this);
867 F.print(dbgs(), &Writer);
868}
869
870PreservedAnalyses PredicateInfoVerifierPass::run(Function &F,
871 FunctionAnalysisManager &AM) {
872 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
873 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Jonas Devlieghere0eaee542019-08-15 15:54:37 +0000874 std::make_unique<PredicateInfo>(F, DT, AC)->verifyPredicateInfo();
Daniel Berlin439042b2017-02-07 21:10:46 +0000875
876 return PreservedAnalyses::all();
877}
Eugene Zelenko6f1ae632017-10-11 21:56:44 +0000878}