blob: e71448c4308cc19d80b1648d572814cb8035df2b [file] [log] [blame]
Artur Pilipenko8fb3d572017-01-25 16:00:44 +00001//===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The LoopPredication pass tries to convert loop variant range checks to loop
11// invariant by widening checks across loop iterations. For example, it will
12// convert
13//
14// for (i = 0; i < n; i++) {
15// guard(i < len);
16// ...
17// }
18//
19// to
20//
21// for (i = 0; i < n; i++) {
22// guard(n - 1 < len);
23// ...
24// }
25//
26// After this transformation the condition of the guard is loop invariant, so
27// loop-unswitch can later unswitch the loop by this condition which basically
28// predicates the loop by the widened condition:
29//
30// if (n - 1 < len)
31// for (i = 0; i < n; i++) {
32// ...
33// }
34// else
35// deoptimize
36//
37//===----------------------------------------------------------------------===//
38
39#include "llvm/Transforms/Scalar/LoopPredication.h"
40#include "llvm/Pass.h"
41#include "llvm/Analysis/LoopInfo.h"
42#include "llvm/Analysis/LoopPass.h"
43#include "llvm/Analysis/ScalarEvolution.h"
44#include "llvm/Analysis/ScalarEvolutionExpander.h"
45#include "llvm/Analysis/ScalarEvolutionExpressions.h"
46#include "llvm/IR/Function.h"
47#include "llvm/IR/GlobalValue.h"
48#include "llvm/IR/IntrinsicInst.h"
49#include "llvm/IR/Module.h"
50#include "llvm/IR/PatternMatch.h"
51#include "llvm/Support/Debug.h"
52#include "llvm/Transforms/Scalar.h"
53#include "llvm/Transforms/Utils/LoopUtils.h"
54
55#define DEBUG_TYPE "loop-predication"
56
57using namespace llvm;
58
59namespace {
60class LoopPredication {
61 ScalarEvolution *SE;
62
63 Loop *L;
64 const DataLayout *DL;
65 BasicBlock *Preheader;
66
67 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
68 IRBuilder<> &Builder);
69 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
70
71public:
72 LoopPredication(ScalarEvolution *SE) : SE(SE){};
73 bool runOnLoop(Loop *L);
74};
75
76class LoopPredicationLegacyPass : public LoopPass {
77public:
78 static char ID;
79 LoopPredicationLegacyPass() : LoopPass(ID) {
80 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
81 }
82
83 void getAnalysisUsage(AnalysisUsage &AU) const override {
84 getLoopAnalysisUsage(AU);
85 }
86
87 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
88 if (skipLoop(L))
89 return false;
90 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
91 LoopPredication LP(SE);
92 return LP.runOnLoop(L);
93 }
94};
95
96char LoopPredicationLegacyPass::ID = 0;
97} // end namespace llvm
98
99INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
100 "Loop predication", false, false)
101INITIALIZE_PASS_DEPENDENCY(LoopPass)
102INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
103 "Loop predication", false, false)
104
105Pass *llvm::createLoopPredicationPass() {
106 return new LoopPredicationLegacyPass();
107}
108
109PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
110 LoopStandardAnalysisResults &AR,
111 LPMUpdater &U) {
112 LoopPredication LP(&AR.SE);
113 if (!LP.runOnLoop(&L))
114 return PreservedAnalyses::all();
115
116 return getLoopPassPreservedAnalyses();
117}
118
119/// If ICI can be widened to a loop invariant condition emits the loop
120/// invariant condition in the loop preheader and return it, otherwise
121/// returns None.
122Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
123 SCEVExpander &Expander,
124 IRBuilder<> &Builder) {
125 DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
126 DEBUG(ICI->dump());
127
128 ICmpInst::Predicate Pred = ICI->getPredicate();
129 Value *LHS = ICI->getOperand(0);
130 Value *RHS = ICI->getOperand(1);
131 const SCEV *LHSS = SE->getSCEV(LHS);
132 if (isa<SCEVCouldNotCompute>(LHSS))
133 return None;
134 const SCEV *RHSS = SE->getSCEV(RHS);
135 if (isa<SCEVCouldNotCompute>(RHSS))
136 return None;
137
138 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable index
139 if (SE->isLoopInvariant(LHSS, L)) {
140 std::swap(LHS, RHS);
141 std::swap(LHSS, RHSS);
142 Pred = ICmpInst::getSwappedPredicate(Pred);
143 }
Artur Pilipenko0860bfc2017-02-27 15:44:49 +0000144 if (!SE->isLoopInvariant(RHSS, L) || !isSafeToExpand(RHSS, *SE))
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000145 return None;
146
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000147 const SCEVAddRecExpr *IndexAR = dyn_cast<SCEVAddRecExpr>(LHSS);
148 if (!IndexAR || IndexAR->getLoop() != L)
149 return None;
150
151 DEBUG(dbgs() << "IndexAR: ");
152 DEBUG(IndexAR->dump());
153
154 bool IsIncreasing = false;
155 if (!SE->isMonotonicPredicate(IndexAR, Pred, IsIncreasing))
156 return None;
157
158 // If the predicate is increasing the condition can change from false to true
159 // as the loop progresses, in this case take the value on the first iteration
160 // for the widened check. Otherwise the condition can change from true to
161 // false as the loop progresses, so take the value on the last iteration.
162 const SCEV *NewLHSS = IsIncreasing
163 ? IndexAR->getStart()
164 : SE->getSCEVAtScope(IndexAR, L->getParentLoop());
165 if (NewLHSS == IndexAR) {
Artur Pilipenko2cbaded2017-02-01 12:25:38 +0000166 DEBUG(dbgs() << "Can't compute NewLHSS!\n");
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000167 return None;
168 }
169
170 DEBUG(dbgs() << "NewLHSS: ");
171 DEBUG(NewLHSS->dump());
172
173 if (!SE->isLoopInvariant(NewLHSS, L) || !isSafeToExpand(NewLHSS, *SE))
174 return None;
175
176 DEBUG(dbgs() << "NewLHSS is loop invariant and safe to expand. Expand!\n");
177
Artur Pilipenko0860bfc2017-02-27 15:44:49 +0000178 Type *Ty = LHS->getType();
179 Instruction *InsertAt = Preheader->getTerminator();
180 assert(Ty == RHS->getType() && "icmp operands have different types?");
181 Value *NewLHS = Expander.expandCodeFor(NewLHSS, Ty, InsertAt);
182 Value *NewRHS = Expander.expandCodeFor(RHSS, Ty, InsertAt);
183 return Builder.CreateICmp(Pred, NewLHS, NewRHS);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000184}
185
186bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
187 SCEVExpander &Expander) {
188 DEBUG(dbgs() << "Processing guard:\n");
189 DEBUG(Guard->dump());
190
191 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
192
193 // The guard condition is expected to be in form of:
194 // cond1 && cond2 && cond3 ...
195 // Iterate over subconditions looking for for icmp conditions which can be
196 // widened across loop iterations. Widening these conditions remember the
197 // resulting list of subconditions in Checks vector.
198 SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0));
199 SmallPtrSet<Value *, 4> Visited;
200
201 SmallVector<Value *, 4> Checks;
202
203 unsigned NumWidened = 0;
204 do {
205 Value *Condition = Worklist.pop_back_val();
206 if (!Visited.insert(Condition).second)
207 continue;
208
209 Value *LHS, *RHS;
210 using namespace llvm::PatternMatch;
211 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
212 Worklist.push_back(LHS);
213 Worklist.push_back(RHS);
214 continue;
215 }
216
217 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
218 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) {
219 Checks.push_back(NewRangeCheck.getValue());
220 NumWidened++;
221 continue;
222 }
223 }
224
225 // Save the condition as is if we can't widen it
226 Checks.push_back(Condition);
227 } while (Worklist.size() != 0);
228
229 if (NumWidened == 0)
230 return false;
231
232 // Emit the new guard condition
233 Builder.SetInsertPoint(Guard);
234 Value *LastCheck = nullptr;
235 for (auto *Check : Checks)
236 if (!LastCheck)
237 LastCheck = Check;
238 else
239 LastCheck = Builder.CreateAnd(LastCheck, Check);
240 Guard->setOperand(0, LastCheck);
241
242 DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
243 return true;
244}
245
246bool LoopPredication::runOnLoop(Loop *Loop) {
247 L = Loop;
248
249 DEBUG(dbgs() << "Analyzing ");
250 DEBUG(L->dump());
251
252 Module *M = L->getHeader()->getModule();
253
254 // There is nothing to do if the module doesn't use guards
255 auto *GuardDecl =
256 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
257 if (!GuardDecl || GuardDecl->use_empty())
258 return false;
259
260 DL = &M->getDataLayout();
261
262 Preheader = L->getLoopPreheader();
263 if (!Preheader)
264 return false;
265
266 // Collect all the guards into a vector and process later, so as not
267 // to invalidate the instruction iterator.
268 SmallVector<IntrinsicInst *, 4> Guards;
269 for (const auto BB : L->blocks())
270 for (auto &I : *BB)
271 if (auto *II = dyn_cast<IntrinsicInst>(&I))
272 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
273 Guards.push_back(II);
274
Artur Pilipenko46c4e0a2017-05-19 13:59:34 +0000275 if (Guards.empty())
276 return false;
277
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000278 SCEVExpander Expander(*SE, *DL, "loop-predication");
279
280 bool Changed = false;
281 for (auto *Guard : Guards)
282 Changed |= widenGuardConditions(Guard, Expander);
283
284 return Changed;
285}