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