blob: cb0ee7b741a9b08902f0734554c5aaaf927ad5c8 [file] [log] [blame]
Sanjoy Das083f3892016-05-18 22:55:34 +00001//===- GuardWidening.cpp - ---- Guard widening ----------------------------===//
2//
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
Sanjoy Das083f3892016-05-18 22:55:34 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the guard widening pass. The semantics of the
10// @llvm.experimental.guard intrinsic lets LLVM transform it so that it fails
11// more often that it did before the transform. This optimization is called
12// "widening" and can be used hoist and common runtime checks in situations like
13// these:
14//
15// %cmp0 = 7 u< Length
16// call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
17// call @unknown_side_effects()
18// %cmp1 = 9 u< Length
19// call @llvm.experimental.guard(i1 %cmp1) [ "deopt"(...) ]
20// ...
21//
22// =>
23//
24// %cmp0 = 9 u< Length
25// call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
26// call @unknown_side_effects()
27// ...
28//
29// If %cmp0 is false, @llvm.experimental.guard will "deoptimize" back to a
30// generic implementation of the same function, which will have the correct
31// semantics from that point onward. It is always _legal_ to deoptimize (so
32// replacing %cmp0 with false is "correct"), though it may not always be
33// profitable to do so.
34//
35// NB! This pass is a work in progress. It hasn't been tuned to be "production
36// ready" yet. It is known to have quadriatic running time and will not scale
37// to large numbers of guards
38//
39//===----------------------------------------------------------------------===//
40
41#include "llvm/Transforms/Scalar/GuardWidening.h"
Philip Reames9258e9d2018-04-27 17:29:10 +000042#include <functional>
Sanjoy Das083f3892016-05-18 22:55:34 +000043#include "llvm/ADT/DenseMap.h"
44#include "llvm/ADT/DepthFirstIterator.h"
Max Kazantseveb8e9c02018-07-31 04:37:11 +000045#include "llvm/ADT/Statistic.h"
Max Kazantseveded4ab2018-08-06 05:49:19 +000046#include "llvm/Analysis/BranchProbabilityInfo.h"
Max Kazantsev3c284bd2018-08-30 03:39:16 +000047#include "llvm/Analysis/GuardUtils.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000048#include "llvm/Analysis/LoopInfo.h"
Philip Reames9258e9d2018-04-27 17:29:10 +000049#include "llvm/Analysis/LoopPass.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000050#include "llvm/Analysis/PostDominators.h"
51#include "llvm/Analysis/ValueTracking.h"
Peter Collingbourneecdd58f2016-10-21 19:59:26 +000052#include "llvm/IR/ConstantRange.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000053#include "llvm/IR/Dominators.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/PatternMatch.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000056#include "llvm/Pass.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000057#include "llvm/Support/Debug.h"
Craig Topperb45eabc2017-04-26 16:39:58 +000058#include "llvm/Support/KnownBits.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000059#include "llvm/Transforms/Scalar.h"
Philip Reames9258e9d2018-04-27 17:29:10 +000060#include "llvm/Transforms/Utils/LoopUtils.h"
Sanjoy Das083f3892016-05-18 22:55:34 +000061
62using namespace llvm;
63
64#define DEBUG_TYPE "guard-widening"
65
Max Kazantseveb8e9c02018-07-31 04:37:11 +000066STATISTIC(GuardsEliminated, "Number of eliminated guards");
Max Kazantseveded4ab2018-08-06 05:49:19 +000067STATISTIC(CondBranchEliminated, "Number of eliminated conditional branches");
68
69static cl::opt<bool> WidenFrequentBranches(
70 "guard-widening-widen-frequent-branches", cl::Hidden,
71 cl::desc("Widen conditions of explicit branches into dominating guards in "
72 "case if their taken frequency exceeds threshold set by "
73 "guard-widening-frequent-branch-threshold option"),
74 cl::init(false));
75
76static cl::opt<unsigned> FrequentBranchThreshold(
77 "guard-widening-frequent-branch-threshold", cl::Hidden,
78 cl::desc("When WidenFrequentBranches is set to true, this option is used "
79 "to determine which branches are frequently taken. The criteria "
80 "that a branch is taken more often than "
81 "((FrequentBranchThreshold - 1) / FrequentBranchThreshold), then "
82 "it is considered frequently taken"),
83 cl::init(1000));
84
Max Kazantseveb8e9c02018-07-31 04:37:11 +000085
Sanjoy Das083f3892016-05-18 22:55:34 +000086namespace {
87
Max Kazantseveded4ab2018-08-06 05:49:19 +000088// Get the condition of \p I. It can either be a guard or a conditional branch.
89static Value *getCondition(Instruction *I) {
90 if (IntrinsicInst *GI = dyn_cast<IntrinsicInst>(I)) {
91 assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
92 "Bad guard intrinsic?");
93 return GI->getArgOperand(0);
94 }
95 return cast<BranchInst>(I)->getCondition();
Max Kazantsev65cd4832018-08-03 10:16:40 +000096}
97
Max Kazantseveded4ab2018-08-06 05:49:19 +000098// Set the condition for \p I to \p NewCond. \p I can either be a guard or a
99// conditional branch.
100static void setCondition(Instruction *I, Value *NewCond) {
101 if (IntrinsicInst *GI = dyn_cast<IntrinsicInst>(I)) {
102 assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
103 "Bad guard intrinsic?");
104 GI->setArgOperand(0, NewCond);
105 return;
106 }
107 cast<BranchInst>(I)->setCondition(NewCond);
Max Kazantsev65cd4832018-08-03 10:16:40 +0000108}
109
Max Kazantsev65cd4832018-08-03 10:16:40 +0000110// Eliminates the guard instruction properly.
111static void eliminateGuard(Instruction *GuardInst) {
112 GuardInst->eraseFromParent();
113 ++GuardsEliminated;
114}
115
Sanjoy Das083f3892016-05-18 22:55:34 +0000116class GuardWideningImpl {
117 DominatorTree &DT;
Philip Reames502d44812018-04-27 23:15:56 +0000118 PostDominatorTree *PDT;
Sanjoy Das083f3892016-05-18 22:55:34 +0000119 LoopInfo &LI;
Max Kazantseveded4ab2018-08-06 05:49:19 +0000120 BranchProbabilityInfo *BPI;
Sanjoy Das083f3892016-05-18 22:55:34 +0000121
Philip Reames9258e9d2018-04-27 17:29:10 +0000122 /// Together, these describe the region of interest. This might be all of
123 /// the blocks within a function, or only a given loop's blocks and preheader.
124 DomTreeNode *Root;
125 std::function<bool(BasicBlock*)> BlockFilter;
126
Max Kazantseveded4ab2018-08-06 05:49:19 +0000127 /// The set of guards and conditional branches whose conditions have been
128 /// widened into dominating guards.
129 SmallVector<Instruction *, 16> EliminatedGuardsAndBranches;
Sanjoy Das083f3892016-05-18 22:55:34 +0000130
131 /// The set of guards which have been widened to include conditions to other
132 /// guards.
Max Kazantsev3327bca2018-07-30 07:07:32 +0000133 DenseSet<Instruction *> WidenedGuards;
Sanjoy Das083f3892016-05-18 22:55:34 +0000134
135 /// Try to eliminate guard \p Guard by widening it into an earlier dominating
136 /// guard. \p DFSI is the DFS iterator on the dominator tree that is
137 /// currently visiting the block containing \p Guard, and \p GuardsPerBlock
138 /// maps BasicBlocks to the set of guards seen in that block.
139 bool eliminateGuardViaWidening(
Max Kazantsev3327bca2018-07-30 07:07:32 +0000140 Instruction *Guard, const df_iterator<DomTreeNode *> &DFSI,
141 const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> &
Max Kazantsev5c490b42018-08-13 07:58:19 +0000142 GuardsPerBlock, bool InvertCondition = false);
Sanjoy Das083f3892016-05-18 22:55:34 +0000143
144 /// Used to keep track of which widening potential is more effective.
145 enum WideningScore {
146 /// Don't widen.
147 WS_IllegalOrNegative,
148
149 /// Widening is performance neutral as far as the cycles spent in check
150 /// conditions goes (but can still help, e.g., code layout, having less
151 /// deopt state).
152 WS_Neutral,
153
154 /// Widening is profitable.
155 WS_Positive,
156
157 /// Widening is very profitable. Not significantly different from \c
158 /// WS_Positive, except by the order.
159 WS_VeryPositive
160 };
161
162 static StringRef scoreTypeToString(WideningScore WS);
163
164 /// Compute the score for widening the condition in \p DominatedGuard
165 /// (contained in \p DominatedGuardLoop) into \p DominatingGuard (contained in
Max Kazantsev5c490b42018-08-13 07:58:19 +0000166 /// \p DominatingGuardLoop). If \p InvertCond is set, then we widen the
167 /// inverted condition of the dominating guard.
Max Kazantsev3327bca2018-07-30 07:07:32 +0000168 WideningScore computeWideningScore(Instruction *DominatedGuard,
Sanjoy Das083f3892016-05-18 22:55:34 +0000169 Loop *DominatedGuardLoop,
Max Kazantsev3327bca2018-07-30 07:07:32 +0000170 Instruction *DominatingGuard,
Max Kazantsev5c490b42018-08-13 07:58:19 +0000171 Loop *DominatingGuardLoop,
172 bool InvertCond);
Sanjoy Das083f3892016-05-18 22:55:34 +0000173
174 /// Helper to check if \p V can be hoisted to \p InsertPos.
175 bool isAvailableAt(Value *V, Instruction *InsertPos) {
176 SmallPtrSet<Instruction *, 8> Visited;
177 return isAvailableAt(V, InsertPos, Visited);
178 }
179
180 bool isAvailableAt(Value *V, Instruction *InsertPos,
181 SmallPtrSetImpl<Instruction *> &Visited);
182
183 /// Helper to hoist \p V to \p InsertPos. Guaranteed to succeed if \c
184 /// isAvailableAt returned true.
185 void makeAvailableAt(Value *V, Instruction *InsertPos);
186
187 /// Common helper used by \c widenGuard and \c isWideningCondProfitable. Try
Max Kazantsev5c490b42018-08-13 07:58:19 +0000188 /// to generate an expression computing the logical AND of \p Cond0 and (\p
189 /// Cond1 XOR \p InvertCondition).
190 /// Return true if the expression computing the AND is only as
Sanjoy Das083f3892016-05-18 22:55:34 +0000191 /// expensive as computing one of the two. If \p InsertPt is true then
192 /// actually generate the resulting expression, make it available at \p
193 /// InsertPt and return it in \p Result (else no change to the IR is made).
194 bool widenCondCommon(Value *Cond0, Value *Cond1, Instruction *InsertPt,
Max Kazantsev5c490b42018-08-13 07:58:19 +0000195 Value *&Result, bool InvertCondition);
Sanjoy Das083f3892016-05-18 22:55:34 +0000196
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000197 /// Represents a range check of the form \c Base + \c Offset u< \c Length,
198 /// with the constraint that \c Length is not negative. \c CheckInst is the
199 /// pre-existing instruction in the IR that computes the result of this range
200 /// check.
Sanjoy Dasbe991532016-05-24 20:54:45 +0000201 class RangeCheck {
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000202 Value *Base;
203 ConstantInt *Offset;
204 Value *Length;
205 ICmpInst *CheckInst;
206
Sanjoy Dasbe991532016-05-24 20:54:45 +0000207 public:
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000208 explicit RangeCheck(Value *Base, ConstantInt *Offset, Value *Length,
209 ICmpInst *CheckInst)
210 : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
211
Sanjoy Dasbe991532016-05-24 20:54:45 +0000212 void setBase(Value *NewBase) { Base = NewBase; }
213 void setOffset(ConstantInt *NewOffset) { Offset = NewOffset; }
214
215 Value *getBase() const { return Base; }
216 ConstantInt *getOffset() const { return Offset; }
217 const APInt &getOffsetValue() const { return getOffset()->getValue(); }
218 Value *getLength() const { return Length; };
219 ICmpInst *getCheckInst() const { return CheckInst; }
220
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000221 void print(raw_ostream &OS, bool PrintTypes = false) {
222 OS << "Base: ";
223 Base->printAsOperand(OS, PrintTypes);
224 OS << " Offset: ";
225 Offset->printAsOperand(OS, PrintTypes);
226 OS << " Length: ";
227 Length->printAsOperand(OS, PrintTypes);
228 }
229
230 LLVM_DUMP_METHOD void dump() {
231 print(dbgs());
232 dbgs() << "\n";
233 }
234 };
235
236 /// Parse \p CheckCond into a conjunction (logical-and) of range checks; and
237 /// append them to \p Checks. Returns true on success, may clobber \c Checks
238 /// on failure.
239 bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks) {
240 SmallPtrSet<Value *, 8> Visited;
241 return parseRangeChecks(CheckCond, Checks, Visited);
242 }
243
244 bool parseRangeChecks(Value *CheckCond, SmallVectorImpl<RangeCheck> &Checks,
245 SmallPtrSetImpl<Value *> &Visited);
246
247 /// Combine the checks in \p Checks into a smaller set of checks and append
248 /// them into \p CombinedChecks. Return true on success (i.e. all of checks
249 /// in \p Checks were combined into \p CombinedChecks). Clobbers \p Checks
250 /// and \p CombinedChecks on success and on failure.
251 bool combineRangeChecks(SmallVectorImpl<RangeCheck> &Checks,
252 SmallVectorImpl<RangeCheck> &CombinedChecks);
253
Sanjoy Das083f3892016-05-18 22:55:34 +0000254 /// Can we compute the logical AND of \p Cond0 and \p Cond1 for the price of
255 /// computing only one of the two expressions?
Max Kazantsev5c490b42018-08-13 07:58:19 +0000256 bool isWideningCondProfitable(Value *Cond0, Value *Cond1, bool InvertCond) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000257 Value *ResultUnused;
Max Kazantsev5c490b42018-08-13 07:58:19 +0000258 return widenCondCommon(Cond0, Cond1, /*InsertPt=*/nullptr, ResultUnused,
259 InvertCond);
Sanjoy Das083f3892016-05-18 22:55:34 +0000260 }
261
Max Kazantsev5c490b42018-08-13 07:58:19 +0000262 /// If \p InvertCondition is false, Widen \p ToWiden to fail if
263 /// \p NewCondition is false, otherwise make it fail if \p NewCondition is
264 /// true (in addition to whatever it is already checking).
265 void widenGuard(Instruction *ToWiden, Value *NewCondition,
266 bool InvertCondition) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000267 Value *Result;
Max Kazantsev5c490b42018-08-13 07:58:19 +0000268 widenCondCommon(ToWiden->getOperand(0), NewCondition, ToWiden, Result,
269 InvertCondition);
Max Kazantseveded4ab2018-08-06 05:49:19 +0000270 setCondition(ToWiden, Result);
Sanjoy Das083f3892016-05-18 22:55:34 +0000271 }
272
273public:
Philip Reames9258e9d2018-04-27 17:29:10 +0000274
Philip Reames502d44812018-04-27 23:15:56 +0000275 explicit GuardWideningImpl(DominatorTree &DT, PostDominatorTree *PDT,
Max Kazantseveded4ab2018-08-06 05:49:19 +0000276 LoopInfo &LI, BranchProbabilityInfo *BPI,
277 DomTreeNode *Root,
Philip Reames9258e9d2018-04-27 17:29:10 +0000278 std::function<bool(BasicBlock*)> BlockFilter)
Max Kazantseveded4ab2018-08-06 05:49:19 +0000279 : DT(DT), PDT(PDT), LI(LI), BPI(BPI), Root(Root), BlockFilter(BlockFilter)
280 {}
Sanjoy Das083f3892016-05-18 22:55:34 +0000281
282 /// The entry point for this pass.
283 bool run();
284};
Sanjoy Das083f3892016-05-18 22:55:34 +0000285}
286
287bool GuardWideningImpl::run() {
Max Kazantsev3327bca2018-07-30 07:07:32 +0000288 DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> GuardsInBlock;
Sanjoy Das083f3892016-05-18 22:55:34 +0000289 bool Changed = false;
Max Kazantseveded4ab2018-08-06 05:49:19 +0000290 Optional<BranchProbability> LikelyTaken = None;
291 if (WidenFrequentBranches && BPI) {
292 unsigned Threshold = FrequentBranchThreshold;
293 assert(Threshold > 0 && "Zero threshold makes no sense!");
Max Kazantsev778f62b2018-08-06 06:35:21 +0000294 LikelyTaken = BranchProbability(Threshold - 1, Threshold);
Max Kazantseveded4ab2018-08-06 05:49:19 +0000295 }
Sanjoy Das083f3892016-05-18 22:55:34 +0000296
Philip Reames9258e9d2018-04-27 17:29:10 +0000297 for (auto DFI = df_begin(Root), DFE = df_end(Root);
Sanjoy Das083f3892016-05-18 22:55:34 +0000298 DFI != DFE; ++DFI) {
299 auto *BB = (*DFI)->getBlock();
Philip Reames9258e9d2018-04-27 17:29:10 +0000300 if (!BlockFilter(BB))
301 continue;
302
Sanjoy Das083f3892016-05-18 22:55:34 +0000303 auto &CurrentList = GuardsInBlock[BB];
304
305 for (auto &I : *BB)
Max Kazantsev3327bca2018-07-30 07:07:32 +0000306 if (isGuard(&I))
307 CurrentList.push_back(cast<Instruction>(&I));
Sanjoy Das083f3892016-05-18 22:55:34 +0000308
309 for (auto *II : CurrentList)
310 Changed |= eliminateGuardViaWidening(II, DFI, GuardsInBlock);
Max Kazantseveded4ab2018-08-06 05:49:19 +0000311 if (WidenFrequentBranches && BPI)
312 if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator()))
Max Kazantsev5c490b42018-08-13 07:58:19 +0000313 if (BI->isConditional()) {
314 // If one of branches of a conditional is likely taken, try to
315 // eliminate it.
316 if (BPI->getEdgeProbability(BB, 0U) >= *LikelyTaken)
317 Changed |= eliminateGuardViaWidening(BI, DFI, GuardsInBlock);
318 else if (BPI->getEdgeProbability(BB, 1U) >= *LikelyTaken)
319 Changed |= eliminateGuardViaWidening(BI, DFI, GuardsInBlock,
320 /*InvertCondition*/true);
321 }
Sanjoy Das083f3892016-05-18 22:55:34 +0000322 }
323
Max Kazantseveded4ab2018-08-06 05:49:19 +0000324 assert(EliminatedGuardsAndBranches.empty() || Changed);
325 for (auto *I : EliminatedGuardsAndBranches)
326 if (!WidenedGuards.count(I)) {
327 assert(isa<ConstantInt>(getCondition(I)) && "Should be!");
328 if (isGuard(I))
329 eliminateGuard(I);
330 else {
331 assert(isa<BranchInst>(I) &&
332 "Eliminated something other than guard or branch?");
333 ++CondBranchEliminated;
334 }
335 }
Sanjoy Das083f3892016-05-18 22:55:34 +0000336
337 return Changed;
338}
339
340bool GuardWideningImpl::eliminateGuardViaWidening(
Max Kazantsev3327bca2018-07-30 07:07:32 +0000341 Instruction *GuardInst, const df_iterator<DomTreeNode *> &DFSI,
342 const DenseMap<BasicBlock *, SmallVector<Instruction *, 8>> &
Max Kazantsev5c490b42018-08-13 07:58:19 +0000343 GuardsInBlock, bool InvertCondition) {
Max Kazantsev611d6452018-08-22 02:40:49 +0000344 // Ignore trivial true or false conditions. These instructions will be
345 // trivially eliminated by any cleanup pass. Do not erase them because other
346 // guards can possibly be widened into them.
347 if (isa<ConstantInt>(getCondition(GuardInst)))
348 return false;
349
Max Kazantsev3327bca2018-07-30 07:07:32 +0000350 Instruction *BestSoFar = nullptr;
Sanjoy Das083f3892016-05-18 22:55:34 +0000351 auto BestScoreSoFar = WS_IllegalOrNegative;
352 auto *GuardInstLoop = LI.getLoopFor(GuardInst->getParent());
353
354 // In the set of dominating guards, find the one we can merge GuardInst with
355 // for the most profit.
356 for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) {
357 auto *CurBB = DFSI.getPath(i)->getBlock();
Philip Reames9258e9d2018-04-27 17:29:10 +0000358 if (!BlockFilter(CurBB))
359 break;
Sanjoy Das083f3892016-05-18 22:55:34 +0000360 auto *CurLoop = LI.getLoopFor(CurBB);
361 assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!");
362 const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
363
364 auto I = GuardsInCurBB.begin();
365 auto E = GuardsInCurBB.end();
366
367#ifndef NDEBUG
368 {
369 unsigned Index = 0;
370 for (auto &I : *CurBB) {
371 if (Index == GuardsInCurBB.size())
372 break;
373 if (GuardsInCurBB[Index] == &I)
374 Index++;
375 }
376 assert(Index == GuardsInCurBB.size() &&
377 "Guards expected to be in order!");
378 }
379#endif
380
381 assert((i == (e - 1)) == (GuardInst->getParent() == CurBB) && "Bad DFS?");
382
Max Kazantseveded4ab2018-08-06 05:49:19 +0000383 if (i == (e - 1) && CurBB->getTerminator() != GuardInst) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000384 // Corner case: make sure we're only looking at guards strictly dominating
385 // GuardInst when visiting GuardInst->getParent().
386 auto NewEnd = std::find(I, E, GuardInst);
387 assert(NewEnd != E && "GuardInst not in its own block?");
388 E = NewEnd;
389 }
390
391 for (auto *Candidate : make_range(I, E)) {
392 auto Score =
Max Kazantsev5c490b42018-08-13 07:58:19 +0000393 computeWideningScore(GuardInst, GuardInstLoop, Candidate, CurLoop,
394 InvertCondition);
Max Kazantseveded4ab2018-08-06 05:49:19 +0000395 LLVM_DEBUG(dbgs() << "Score between " << *getCondition(GuardInst)
396 << " and " << *getCondition(Candidate) << " is "
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000397 << scoreTypeToString(Score) << "\n");
Sanjoy Das083f3892016-05-18 22:55:34 +0000398 if (Score > BestScoreSoFar) {
399 BestScoreSoFar = Score;
400 BestSoFar = Candidate;
401 }
402 }
403 }
404
405 if (BestScoreSoFar == WS_IllegalOrNegative) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000406 LLVM_DEBUG(dbgs() << "Did not eliminate guard " << *GuardInst << "\n");
Sanjoy Das083f3892016-05-18 22:55:34 +0000407 return false;
408 }
409
410 assert(BestSoFar != GuardInst && "Should have never visited same guard!");
411 assert(DT.dominates(BestSoFar, GuardInst) && "Should be!");
412
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000413 LLVM_DEBUG(dbgs() << "Widening " << *GuardInst << " into " << *BestSoFar
414 << " with score " << scoreTypeToString(BestScoreSoFar)
415 << "\n");
Max Kazantsev5c490b42018-08-13 07:58:19 +0000416 widenGuard(BestSoFar, getCondition(GuardInst), InvertCondition);
417 auto NewGuardCondition = InvertCondition
418 ? ConstantInt::getFalse(GuardInst->getContext())
419 : ConstantInt::getTrue(GuardInst->getContext());
420 setCondition(GuardInst, NewGuardCondition);
Max Kazantseveded4ab2018-08-06 05:49:19 +0000421 EliminatedGuardsAndBranches.push_back(GuardInst);
Sanjoy Das083f3892016-05-18 22:55:34 +0000422 WidenedGuards.insert(BestSoFar);
423 return true;
424}
425
426GuardWideningImpl::WideningScore GuardWideningImpl::computeWideningScore(
Max Kazantsev3327bca2018-07-30 07:07:32 +0000427 Instruction *DominatedGuard, Loop *DominatedGuardLoop,
Max Kazantsev5c490b42018-08-13 07:58:19 +0000428 Instruction *DominatingGuard, Loop *DominatingGuardLoop, bool InvertCond) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000429 bool HoistingOutOfLoop = false;
430
431 if (DominatingGuardLoop != DominatedGuardLoop) {
Philip Reamesde5a1da2018-04-27 17:41:37 +0000432 // Be conservative and don't widen into a sibling loop. TODO: If the
433 // sibling is colder, we should consider allowing this.
Sanjoy Das083f3892016-05-18 22:55:34 +0000434 if (DominatingGuardLoop &&
435 !DominatingGuardLoop->contains(DominatedGuardLoop))
436 return WS_IllegalOrNegative;
437
438 HoistingOutOfLoop = true;
439 }
440
Max Kazantseveded4ab2018-08-06 05:49:19 +0000441 if (!isAvailableAt(getCondition(DominatedGuard), DominatingGuard))
Sanjoy Das083f3892016-05-18 22:55:34 +0000442 return WS_IllegalOrNegative;
443
Philip Reamesde5a1da2018-04-27 17:41:37 +0000444 // If the guard was conditional executed, it may never be reached
445 // dynamically. There are two potential downsides to hoisting it out of the
446 // conditionally executed region: 1) we may spuriously deopt without need and
447 // 2) we have the extra cost of computing the guard condition in the common
448 // case. At the moment, we really only consider the second in our heuristic
449 // here. TODO: evaluate cost model for spurious deopt
Philip Reames502d44812018-04-27 23:15:56 +0000450 // NOTE: As written, this also lets us hoist right over another guard which
Fangrui Songf78650a2018-07-30 19:41:25 +0000451 // is essentially just another spelling for control flow.
Max Kazantseveded4ab2018-08-06 05:49:19 +0000452 if (isWideningCondProfitable(getCondition(DominatedGuard),
Max Kazantsev5c490b42018-08-13 07:58:19 +0000453 getCondition(DominatingGuard), InvertCond))
Sanjoy Das083f3892016-05-18 22:55:34 +0000454 return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
455
456 if (HoistingOutOfLoop)
457 return WS_Positive;
458
Philip Reames502d44812018-04-27 23:15:56 +0000459 // Returns true if we might be hoisting above explicit control flow. Note
460 // that this completely ignores implicit control flow (guards, calls which
461 // throw, etc...). That choice appears arbitrary.
462 auto MaybeHoistingOutOfIf = [&]() {
463 auto *DominatingBlock = DominatingGuard->getParent();
464 auto *DominatedBlock = DominatedGuard->getParent();
Fangrui Songf78650a2018-07-30 19:41:25 +0000465
Philip Reames502d44812018-04-27 23:15:56 +0000466 // Same Block?
467 if (DominatedBlock == DominatingBlock)
468 return false;
469 // Obvious successor (common loop header/preheader case)
470 if (DominatedBlock == DominatingBlock->getUniqueSuccessor())
471 return false;
472 // TODO: diamond, triangle cases
473 if (!PDT) return true;
Max Kazantsev9b25bf32018-12-25 07:20:06 +0000474 return !PDT->dominates(DominatedBlock, DominatingBlock);
Philip Reames502d44812018-04-27 23:15:56 +0000475 };
476
477 return MaybeHoistingOutOfIf() ? WS_IllegalOrNegative : WS_Neutral;
Sanjoy Das083f3892016-05-18 22:55:34 +0000478}
479
480bool GuardWideningImpl::isAvailableAt(Value *V, Instruction *Loc,
481 SmallPtrSetImpl<Instruction *> &Visited) {
482 auto *Inst = dyn_cast<Instruction>(V);
483 if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst))
484 return true;
485
486 if (!isSafeToSpeculativelyExecute(Inst, Loc, &DT) ||
487 Inst->mayReadFromMemory())
488 return false;
489
490 Visited.insert(Inst);
491
492 // We only want to go _up_ the dominance chain when recursing.
493 assert(!isa<PHINode>(Loc) &&
494 "PHIs should return false for isSafeToSpeculativelyExecute");
495 assert(DT.isReachableFromEntry(Inst->getParent()) &&
496 "We did a DFS from the block entry!");
497 return all_of(Inst->operands(),
498 [&](Value *Op) { return isAvailableAt(Op, Loc, Visited); });
499}
500
501void GuardWideningImpl::makeAvailableAt(Value *V, Instruction *Loc) {
502 auto *Inst = dyn_cast<Instruction>(V);
503 if (!Inst || DT.dominates(Inst, Loc))
504 return;
505
506 assert(isSafeToSpeculativelyExecute(Inst, Loc, &DT) &&
507 !Inst->mayReadFromMemory() && "Should've checked with isAvailableAt!");
508
509 for (Value *Op : Inst->operands())
510 makeAvailableAt(Op, Loc);
511
512 Inst->moveBefore(Loc);
513}
514
515bool GuardWideningImpl::widenCondCommon(Value *Cond0, Value *Cond1,
Max Kazantsev5c490b42018-08-13 07:58:19 +0000516 Instruction *InsertPt, Value *&Result,
517 bool InvertCondition) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000518 using namespace llvm::PatternMatch;
519
520 {
521 // L >u C0 && L >u C1 -> L >u max(C0, C1)
522 ConstantInt *RHS0, *RHS1;
523 Value *LHS;
524 ICmpInst::Predicate Pred0, Pred1;
525 if (match(Cond0, m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) &&
526 match(Cond1, m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) {
Max Kazantsev5c490b42018-08-13 07:58:19 +0000527 if (InvertCondition)
528 Pred1 = ICmpInst::getInversePredicate(Pred1);
Sanjoy Das083f3892016-05-18 22:55:34 +0000529
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000530 ConstantRange CR0 =
531 ConstantRange::makeExactICmpRegion(Pred0, RHS0->getValue());
532 ConstantRange CR1 =
533 ConstantRange::makeExactICmpRegion(Pred1, RHS1->getValue());
Sanjoy Das083f3892016-05-18 22:55:34 +0000534
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000535 // SubsetIntersect is a subset of the actual mathematical intersection of
Sanjay Patelf8ee0e02016-06-19 17:20:27 +0000536 // CR0 and CR1, while SupersetIntersect is a superset of the actual
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000537 // mathematical intersection. If these two ConstantRanges are equal, then
538 // we know we were able to represent the actual mathematical intersection
539 // of CR0 and CR1, and can use the same to generate an icmp instruction.
540 //
541 // Given what we're doing here and the semantics of guards, it would
542 // actually be correct to just use SubsetIntersect, but that may be too
543 // aggressive in cases we care about.
544 auto SubsetIntersect = CR0.inverse().unionWith(CR1.inverse()).inverse();
545 auto SupersetIntersect = CR0.intersectWith(CR1);
546
547 APInt NewRHSAP;
548 CmpInst::Predicate Pred;
549 if (SubsetIntersect == SupersetIntersect &&
550 SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) {
Sanjoy Das083f3892016-05-18 22:55:34 +0000551 if (InsertPt) {
Sanjoy Dasb784ed32016-05-19 03:53:17 +0000552 ConstantInt *NewRHS = ConstantInt::get(Cond0->getContext(), NewRHSAP);
553 Result = new ICmpInst(InsertPt, Pred, LHS, NewRHS, "wide.chk");
Sanjoy Das083f3892016-05-18 22:55:34 +0000554 }
Sanjoy Das083f3892016-05-18 22:55:34 +0000555 return true;
556 }
557 }
558 }
559
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000560 {
561 SmallVector<GuardWideningImpl::RangeCheck, 4> Checks, CombinedChecks;
Max Kazantsev5c490b42018-08-13 07:58:19 +0000562 // TODO: Support InvertCondition case?
563 if (!InvertCondition &&
564 parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000565 combineRangeChecks(Checks, CombinedChecks)) {
566 if (InsertPt) {
567 Result = nullptr;
568 for (auto &RC : CombinedChecks) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000569 makeAvailableAt(RC.getCheckInst(), InsertPt);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000570 if (Result)
Sanjoy Dasbe991532016-05-24 20:54:45 +0000571 Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result, "",
572 InsertPt);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000573 else
Sanjoy Dasbe991532016-05-24 20:54:45 +0000574 Result = RC.getCheckInst();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000575 }
576
577 Result->setName("wide.chk");
578 }
579 return true;
580 }
581 }
582
Sanjoy Das083f3892016-05-18 22:55:34 +0000583 // Base case -- just logical-and the two conditions together.
584
585 if (InsertPt) {
586 makeAvailableAt(Cond0, InsertPt);
587 makeAvailableAt(Cond1, InsertPt);
Max Kazantsev5c490b42018-08-13 07:58:19 +0000588 if (InvertCondition)
589 Cond1 = BinaryOperator::CreateNot(Cond1, "inverted", InsertPt);
Sanjoy Das083f3892016-05-18 22:55:34 +0000590 Result = BinaryOperator::CreateAnd(Cond0, Cond1, "wide.chk", InsertPt);
591 }
592
593 // We were not able to compute Cond0 AND Cond1 for the price of one.
594 return false;
595}
596
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000597bool GuardWideningImpl::parseRangeChecks(
598 Value *CheckCond, SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
599 SmallPtrSetImpl<Value *> &Visited) {
600 if (!Visited.insert(CheckCond).second)
601 return true;
602
603 using namespace llvm::PatternMatch;
604
605 {
606 Value *AndLHS, *AndRHS;
607 if (match(CheckCond, m_And(m_Value(AndLHS), m_Value(AndRHS))))
608 return parseRangeChecks(AndLHS, Checks) &&
609 parseRangeChecks(AndRHS, Checks);
610 }
611
612 auto *IC = dyn_cast<ICmpInst>(CheckCond);
613 if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
614 (IC->getPredicate() != ICmpInst::ICMP_ULT &&
615 IC->getPredicate() != ICmpInst::ICMP_UGT))
616 return false;
617
618 Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
619 if (IC->getPredicate() == ICmpInst::ICMP_UGT)
620 std::swap(CmpLHS, CmpRHS);
621
622 auto &DL = IC->getModule()->getDataLayout();
623
Sanjoy Dasbe991532016-05-24 20:54:45 +0000624 GuardWideningImpl::RangeCheck Check(
625 CmpLHS, cast<ConstantInt>(ConstantInt::getNullValue(CmpRHS->getType())),
626 CmpRHS, IC);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000627
Sanjoy Dasbe991532016-05-24 20:54:45 +0000628 if (!isKnownNonNegative(Check.getLength(), DL))
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000629 return false;
630
631 // What we have in \c Check now is a correct interpretation of \p CheckCond.
632 // Try to see if we can move some constant offsets into the \c Offset field.
633
634 bool Changed;
Sanjoy Dasbe991532016-05-24 20:54:45 +0000635 auto &Ctx = CheckCond->getContext();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000636
637 do {
638 Value *OpLHS;
639 ConstantInt *OpRHS;
640 Changed = false;
641
642#ifndef NDEBUG
Sanjoy Dasbe991532016-05-24 20:54:45 +0000643 auto *BaseInst = dyn_cast<Instruction>(Check.getBase());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000644 assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) &&
645 "Unreachable instruction?");
646#endif
647
Sanjoy Dasbe991532016-05-24 20:54:45 +0000648 if (match(Check.getBase(), m_Add(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
649 Check.setBase(OpLHS);
650 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
651 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000652 Changed = true;
Sanjoy Dasbe991532016-05-24 20:54:45 +0000653 } else if (match(Check.getBase(),
654 m_Or(m_Value(OpLHS), m_ConstantInt(OpRHS)))) {
Craig Topper8205a1a2017-05-24 16:53:07 +0000655 KnownBits Known = computeKnownBits(OpLHS, DL);
Craig Topperb45eabc2017-04-26 16:39:58 +0000656 if ((OpRHS->getValue() & Known.Zero) == OpRHS->getValue()) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000657 Check.setBase(OpLHS);
658 APInt NewOffset = Check.getOffsetValue() + OpRHS->getValue();
659 Check.setOffset(ConstantInt::get(Ctx, NewOffset));
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000660 Changed = true;
661 }
662 }
663 } while (Changed);
664
665 Checks.push_back(Check);
666 return true;
667}
668
669bool GuardWideningImpl::combineRangeChecks(
670 SmallVectorImpl<GuardWideningImpl::RangeCheck> &Checks,
671 SmallVectorImpl<GuardWideningImpl::RangeCheck> &RangeChecksOut) {
672 unsigned OldCount = Checks.size();
673 while (!Checks.empty()) {
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000674 // Pick all of the range checks with a specific base and length, and try to
675 // merge them.
Sanjoy Dasbe991532016-05-24 20:54:45 +0000676 Value *CurrentBase = Checks.front().getBase();
677 Value *CurrentLength = Checks.front().getLength();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000678
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000679 SmallVector<GuardWideningImpl::RangeCheck, 3> CurrentChecks;
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000680
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000681 auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000682 return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000683 };
684
Sanjoy Das90208722017-02-21 00:38:44 +0000685 copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck);
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000686 Checks.erase(remove_if(Checks, IsCurrentCheck), Checks.end());
687
688 assert(CurrentChecks.size() != 0 && "We know we have at least one!");
689
690 if (CurrentChecks.size() < 3) {
691 RangeChecksOut.insert(RangeChecksOut.end(), CurrentChecks.begin(),
692 CurrentChecks.end());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000693 continue;
694 }
695
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000696 // CurrentChecks.size() will typically be 3 here, but so far there has been
697 // no need to hard-code that fact.
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000698
Fangrui Song0cac7262018-09-27 02:13:45 +0000699 llvm::sort(CurrentChecks, [&](const GuardWideningImpl::RangeCheck &LHS,
700 const GuardWideningImpl::RangeCheck &RHS) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000701 return LHS.getOffsetValue().slt(RHS.getOffsetValue());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000702 });
703
704 // Note: std::sort should not invalidate the ChecksStart iterator.
705
Sanjoy Dasbe991532016-05-24 20:54:45 +0000706 ConstantInt *MinOffset = CurrentChecks.front().getOffset(),
707 *MaxOffset = CurrentChecks.back().getOffset();
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000708
709 unsigned BitWidth = MaxOffset->getValue().getBitWidth();
710 if ((MaxOffset->getValue() - MinOffset->getValue())
711 .ugt(APInt::getSignedMinValue(BitWidth)))
712 return false;
713
714 APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000715 const APInt &HighOffset = MaxOffset->getValue();
Sanjoy Das23519752016-05-19 23:15:59 +0000716 auto OffsetOK = [&](const GuardWideningImpl::RangeCheck &RC) {
Sanjoy Dasbe991532016-05-24 20:54:45 +0000717 return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000718 };
719
720 if (MaxDiff.isMinValue() ||
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000721 !std::all_of(std::next(CurrentChecks.begin()), CurrentChecks.end(),
722 OffsetOK))
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000723 return false;
724
725 // We have a series of f+1 checks as:
726 //
727 // I+k_0 u< L ... Chk_0
Sanjoy Das23f314d2017-05-03 18:29:34 +0000728 // I+k_1 u< L ... Chk_1
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000729 // ...
Sanjoy Das23f314d2017-05-03 18:29:34 +0000730 // I+k_f u< L ... Chk_f
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000731 //
Sanjoy Das23f314d2017-05-03 18:29:34 +0000732 // with forall i in [0,f]: k_f-k_i u< k_f-k_0 ... Precond_0
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000733 // k_f-k_0 u< INT_MIN+k_f ... Precond_1
734 // k_f != k_0 ... Precond_2
735 //
736 // Claim:
Sanjoy Das23f314d2017-05-03 18:29:34 +0000737 // Chk_0 AND Chk_f implies all the other checks
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000738 //
739 // Informal proof sketch:
740 //
741 // We will show that the integer range [I+k_0,I+k_f] does not unsigned-wrap
742 // (i.e. going from I+k_0 to I+k_f does not cross the -1,0 boundary) and
743 // thus I+k_f is the greatest unsigned value in that range.
744 //
745 // This combined with Ckh_(f+1) shows that everything in that range is u< L.
746 // Via Precond_0 we know that all of the indices in Chk_0 through Chk_(f+1)
747 // lie in [I+k_0,I+k_f], this proving our claim.
748 //
749 // To see that [I+k_0,I+k_f] is not a wrapping range, note that there are
750 // two possibilities: I+k_0 u< I+k_f or I+k_0 >u I+k_f (they can't be equal
751 // since k_0 != k_f). In the former case, [I+k_0,I+k_f] is not a wrapping
752 // range by definition, and the latter case is impossible:
753 //
754 // 0-----I+k_f---I+k_0----L---INT_MAX,INT_MIN------------------(-1)
755 // xxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
756 //
757 // For Chk_0 to succeed, we'd have to have k_f-k_0 (the range highlighted
758 // with 'x' above) to be at least >u INT_MIN.
759
Sanjoy Dasbe6c7a12016-05-21 02:24:44 +0000760 RangeChecksOut.emplace_back(CurrentChecks.front());
761 RangeChecksOut.emplace_back(CurrentChecks.back());
Sanjoy Dasf5f03312016-05-19 22:55:46 +0000762 }
763
764 assert(RangeChecksOut.size() <= OldCount && "We pessimized!");
765 return RangeChecksOut.size() != OldCount;
766}
767
Florian Hahn6b3216a2017-07-31 10:07:49 +0000768#ifndef NDEBUG
Sanjoy Das083f3892016-05-18 22:55:34 +0000769StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
770 switch (WS) {
771 case WS_IllegalOrNegative:
772 return "IllegalOrNegative";
773 case WS_Neutral:
774 return "Neutral";
775 case WS_Positive:
776 return "Positive";
777 case WS_VeryPositive:
778 return "VeryPositive";
779 }
780
781 llvm_unreachable("Fully covered switch above!");
782}
Florian Hahn6b3216a2017-07-31 10:07:49 +0000783#endif
Sanjoy Das083f3892016-05-18 22:55:34 +0000784
Philip Reames6a1f3442018-03-23 23:41:47 +0000785PreservedAnalyses GuardWideningPass::run(Function &F,
786 FunctionAnalysisManager &AM) {
787 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
788 auto &LI = AM.getResult<LoopAnalysis>(F);
789 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
Max Kazantseveded4ab2018-08-06 05:49:19 +0000790 BranchProbabilityInfo *BPI = nullptr;
791 if (WidenFrequentBranches)
792 BPI = AM.getCachedResult<BranchProbabilityAnalysis>(F);
793 if (!GuardWideningImpl(DT, &PDT, LI, BPI, DT.getRootNode(),
Philip Reames9258e9d2018-04-27 17:29:10 +0000794 [](BasicBlock*) { return true; } ).run())
Philip Reames6a1f3442018-03-23 23:41:47 +0000795 return PreservedAnalyses::all();
796
797 PreservedAnalyses PA;
798 PA.preserveSet<CFGAnalyses>();
799 return PA;
800}
801
802namespace {
803struct GuardWideningLegacyPass : public FunctionPass {
804 static char ID;
Philip Reames6a1f3442018-03-23 23:41:47 +0000805
806 GuardWideningLegacyPass() : FunctionPass(ID) {
807 initializeGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
808 }
809
810 bool runOnFunction(Function &F) override {
811 if (skipFunction(F))
812 return false;
Philip Reames9258e9d2018-04-27 17:29:10 +0000813 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
814 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
815 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
Max Kazantseveded4ab2018-08-06 05:49:19 +0000816 BranchProbabilityInfo *BPI = nullptr;
817 if (WidenFrequentBranches)
818 BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
819 return GuardWideningImpl(DT, &PDT, LI, BPI, DT.getRootNode(),
Philip Reames9258e9d2018-04-27 17:29:10 +0000820 [](BasicBlock*) { return true; } ).run();
Philip Reames6a1f3442018-03-23 23:41:47 +0000821 }
822
823 void getAnalysisUsage(AnalysisUsage &AU) const override {
824 AU.setPreservesCFG();
825 AU.addRequired<DominatorTreeWrapperPass>();
826 AU.addRequired<PostDominatorTreeWrapperPass>();
827 AU.addRequired<LoopInfoWrapperPass>();
Max Kazantseveded4ab2018-08-06 05:49:19 +0000828 if (WidenFrequentBranches)
829 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Philip Reames6a1f3442018-03-23 23:41:47 +0000830 }
831};
Philip Reames9258e9d2018-04-27 17:29:10 +0000832
833/// Same as above, but restricted to a single loop at a time. Can be
834/// scheduled with other loop passes w/o breaking out of LPM
835struct LoopGuardWideningLegacyPass : public LoopPass {
836 static char ID;
837
838 LoopGuardWideningLegacyPass() : LoopPass(ID) {
839 initializeLoopGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
840 }
841
842 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
843 if (skipLoop(L))
844 return false;
845 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
846 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Philip Reames502d44812018-04-27 23:15:56 +0000847 auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
848 auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
Philip Reames9258e9d2018-04-27 17:29:10 +0000849 BasicBlock *RootBB = L->getLoopPredecessor();
850 if (!RootBB)
851 RootBB = L->getHeader();
852 auto BlockFilter = [&](BasicBlock *BB) {
853 return BB == RootBB || L->contains(BB);
854 };
Max Kazantseveded4ab2018-08-06 05:49:19 +0000855 BranchProbabilityInfo *BPI = nullptr;
856 if (WidenFrequentBranches)
857 BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
858 return GuardWideningImpl(DT, PDT, LI, BPI,
Philip Reames9258e9d2018-04-27 17:29:10 +0000859 DT.getNode(RootBB), BlockFilter).run();
860 }
861
862 void getAnalysisUsage(AnalysisUsage &AU) const override {
Max Kazantseveded4ab2018-08-06 05:49:19 +0000863 if (WidenFrequentBranches)
864 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Philip Reames9258e9d2018-04-27 17:29:10 +0000865 AU.setPreservesCFG();
866 getLoopAnalysisUsage(AU);
Philip Reames9258e9d2018-04-27 17:29:10 +0000867 AU.addPreserved<PostDominatorTreeWrapperPass>();
868 }
869};
Philip Reames6a1f3442018-03-23 23:41:47 +0000870}
871
Sanjoy Das083f3892016-05-18 22:55:34 +0000872char GuardWideningLegacyPass::ID = 0;
Philip Reames9258e9d2018-04-27 17:29:10 +0000873char LoopGuardWideningLegacyPass::ID = 0;
Sanjoy Das083f3892016-05-18 22:55:34 +0000874
875INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards",
876 false, false)
877INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
878INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
879INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Max Kazantseveded4ab2018-08-06 05:49:19 +0000880if (WidenFrequentBranches)
881 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Sanjoy Das083f3892016-05-18 22:55:34 +0000882INITIALIZE_PASS_END(GuardWideningLegacyPass, "guard-widening", "Widen guards",
883 false, false)
884
Philip Reames9258e9d2018-04-27 17:29:10 +0000885INITIALIZE_PASS_BEGIN(LoopGuardWideningLegacyPass, "loop-guard-widening",
886 "Widen guards (within a single loop, as a loop pass)",
887 false, false)
888INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
889INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
890INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Max Kazantseveded4ab2018-08-06 05:49:19 +0000891if (WidenFrequentBranches)
892 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Philip Reames9258e9d2018-04-27 17:29:10 +0000893INITIALIZE_PASS_END(LoopGuardWideningLegacyPass, "loop-guard-widening",
894 "Widen guards (within a single loop, as a loop pass)",
895 false, false)
896
Sanjoy Das083f3892016-05-18 22:55:34 +0000897FunctionPass *llvm::createGuardWideningPass() {
898 return new GuardWideningLegacyPass();
899}
Philip Reames9258e9d2018-04-27 17:29:10 +0000900
901Pass *llvm::createLoopGuardWideningPass() {
902 return new LoopGuardWideningLegacyPass();
903}