blob: 93a7313196dab55edf1ee6d528aceb188ab5e791 [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
Artur Pilipenko6780ba62017-05-19 14:00:58 +000067 Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder,
68 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
69 Instruction *InsertAt);
70
Artur Pilipenko8fb3d572017-01-25 16:00:44 +000071 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
72 IRBuilder<> &Builder);
73 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
74
75public:
76 LoopPredication(ScalarEvolution *SE) : SE(SE){};
77 bool runOnLoop(Loop *L);
78};
79
80class LoopPredicationLegacyPass : public LoopPass {
81public:
82 static char ID;
83 LoopPredicationLegacyPass() : LoopPass(ID) {
84 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
85 }
86
87 void getAnalysisUsage(AnalysisUsage &AU) const override {
88 getLoopAnalysisUsage(AU);
89 }
90
91 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
92 if (skipLoop(L))
93 return false;
94 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
95 LoopPredication LP(SE);
96 return LP.runOnLoop(L);
97 }
98};
99
100char LoopPredicationLegacyPass::ID = 0;
101} // end namespace llvm
102
103INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
104 "Loop predication", false, false)
105INITIALIZE_PASS_DEPENDENCY(LoopPass)
106INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
107 "Loop predication", false, false)
108
109Pass *llvm::createLoopPredicationPass() {
110 return new LoopPredicationLegacyPass();
111}
112
113PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
114 LoopStandardAnalysisResults &AR,
115 LPMUpdater &U) {
116 LoopPredication LP(&AR.SE);
117 if (!LP.runOnLoop(&L))
118 return PreservedAnalyses::all();
119
120 return getLoopPassPreservedAnalyses();
121}
122
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000123Value *LoopPredication::expandCheck(SCEVExpander &Expander,
124 IRBuilder<> &Builder,
125 ICmpInst::Predicate Pred, const SCEV *LHS,
126 const SCEV *RHS, Instruction *InsertAt) {
127 Type *Ty = LHS->getType();
128 assert(Ty == RHS->getType() && "expandCheck operands have different types?");
129 Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt);
130 Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt);
131 return Builder.CreateICmp(Pred, LHSV, RHSV);
132}
133
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000134/// If ICI can be widened to a loop invariant condition emits the loop
135/// invariant condition in the loop preheader and return it, otherwise
136/// returns None.
137Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
138 SCEVExpander &Expander,
139 IRBuilder<> &Builder) {
140 DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
141 DEBUG(ICI->dump());
142
143 ICmpInst::Predicate Pred = ICI->getPredicate();
144 Value *LHS = ICI->getOperand(0);
145 Value *RHS = ICI->getOperand(1);
146 const SCEV *LHSS = SE->getSCEV(LHS);
147 if (isa<SCEVCouldNotCompute>(LHSS))
148 return None;
149 const SCEV *RHSS = SE->getSCEV(RHS);
150 if (isa<SCEVCouldNotCompute>(RHSS))
151 return None;
152
153 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable index
154 if (SE->isLoopInvariant(LHSS, L)) {
155 std::swap(LHS, RHS);
156 std::swap(LHSS, RHSS);
157 Pred = ICmpInst::getSwappedPredicate(Pred);
158 }
Artur Pilipenkoaab28662017-05-19 14:00:04 +0000159
160 auto CanExpand = [this](const SCEV *S) {
161 return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE);
162 };
163 if (!CanExpand(RHSS))
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000164 return None;
165
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000166 const SCEVAddRecExpr *IndexAR = dyn_cast<SCEVAddRecExpr>(LHSS);
167 if (!IndexAR || IndexAR->getLoop() != L)
168 return None;
169
170 DEBUG(dbgs() << "IndexAR: ");
171 DEBUG(IndexAR->dump());
172
173 bool IsIncreasing = false;
174 if (!SE->isMonotonicPredicate(IndexAR, Pred, IsIncreasing))
175 return None;
176
177 // If the predicate is increasing the condition can change from false to true
178 // as the loop progresses, in this case take the value on the first iteration
179 // for the widened check. Otherwise the condition can change from true to
180 // false as the loop progresses, so take the value on the last iteration.
181 const SCEV *NewLHSS = IsIncreasing
182 ? IndexAR->getStart()
183 : SE->getSCEVAtScope(IndexAR, L->getParentLoop());
184 if (NewLHSS == IndexAR) {
Artur Pilipenko2cbaded2017-02-01 12:25:38 +0000185 DEBUG(dbgs() << "Can't compute NewLHSS!\n");
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000186 return None;
187 }
188
189 DEBUG(dbgs() << "NewLHSS: ");
190 DEBUG(NewLHSS->dump());
191
Artur Pilipenkoaab28662017-05-19 14:00:04 +0000192 if (!CanExpand(NewLHSS))
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000193 return None;
194
195 DEBUG(dbgs() << "NewLHSS is loop invariant and safe to expand. Expand!\n");
196
Artur Pilipenko0860bfc2017-02-27 15:44:49 +0000197 Instruction *InsertAt = Preheader->getTerminator();
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000198 return expandCheck(Expander, Builder, Pred, NewLHSS, RHSS, InsertAt);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000199}
200
201bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
202 SCEVExpander &Expander) {
203 DEBUG(dbgs() << "Processing guard:\n");
204 DEBUG(Guard->dump());
205
206 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
207
208 // The guard condition is expected to be in form of:
209 // cond1 && cond2 && cond3 ...
210 // Iterate over subconditions looking for for icmp conditions which can be
211 // widened across loop iterations. Widening these conditions remember the
212 // resulting list of subconditions in Checks vector.
213 SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0));
214 SmallPtrSet<Value *, 4> Visited;
215
216 SmallVector<Value *, 4> Checks;
217
218 unsigned NumWidened = 0;
219 do {
220 Value *Condition = Worklist.pop_back_val();
221 if (!Visited.insert(Condition).second)
222 continue;
223
224 Value *LHS, *RHS;
225 using namespace llvm::PatternMatch;
226 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
227 Worklist.push_back(LHS);
228 Worklist.push_back(RHS);
229 continue;
230 }
231
232 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
233 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) {
234 Checks.push_back(NewRangeCheck.getValue());
235 NumWidened++;
236 continue;
237 }
238 }
239
240 // Save the condition as is if we can't widen it
241 Checks.push_back(Condition);
242 } while (Worklist.size() != 0);
243
244 if (NumWidened == 0)
245 return false;
246
247 // Emit the new guard condition
248 Builder.SetInsertPoint(Guard);
249 Value *LastCheck = nullptr;
250 for (auto *Check : Checks)
251 if (!LastCheck)
252 LastCheck = Check;
253 else
254 LastCheck = Builder.CreateAnd(LastCheck, Check);
255 Guard->setOperand(0, LastCheck);
256
257 DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
258 return true;
259}
260
261bool LoopPredication::runOnLoop(Loop *Loop) {
262 L = Loop;
263
264 DEBUG(dbgs() << "Analyzing ");
265 DEBUG(L->dump());
266
267 Module *M = L->getHeader()->getModule();
268
269 // There is nothing to do if the module doesn't use guards
270 auto *GuardDecl =
271 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
272 if (!GuardDecl || GuardDecl->use_empty())
273 return false;
274
275 DL = &M->getDataLayout();
276
277 Preheader = L->getLoopPreheader();
278 if (!Preheader)
279 return false;
280
281 // Collect all the guards into a vector and process later, so as not
282 // to invalidate the instruction iterator.
283 SmallVector<IntrinsicInst *, 4> Guards;
284 for (const auto BB : L->blocks())
285 for (auto &I : *BB)
286 if (auto *II = dyn_cast<IntrinsicInst>(&I))
287 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
288 Guards.push_back(II);
289
Artur Pilipenko46c4e0a2017-05-19 13:59:34 +0000290 if (Guards.empty())
291 return false;
292
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000293 SCEVExpander Expander(*SE, *DL, "loop-predication");
294
295 bool Changed = false;
296 for (auto *Guard : Guards)
297 Changed |= widenGuardConditions(Guard, Expander);
298
299 return Changed;
300}