blob: d0bd614533d7c825a7604c825a846562d2c8d3b2 [file] [log] [blame]
Sanjoy Das083f3892016-05-18 22:55:34 +00001//===- GuardWidening.cpp - ---- Guard widening ----------------------------===//
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// This file implements the guard widening pass. The semantics of the
11// @llvm.experimental.guard intrinsic lets LLVM transform it so that it fails
12// more often that it did before the transform. This optimization is called
13// "widening" and can be used hoist and common runtime checks in situations like
14// these:
15//
16// %cmp0 = 7 u< Length
17// call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
18// call @unknown_side_effects()
19// %cmp1 = 9 u< Length
20// call @llvm.experimental.guard(i1 %cmp1) [ "deopt"(...) ]
21// ...
22//
23// =>
24//
25// %cmp0 = 9 u< Length
26// call @llvm.experimental.guard(i1 %cmp0) [ "deopt"(...) ]
27// call @unknown_side_effects()
28// ...
29//
30// If %cmp0 is false, @llvm.experimental.guard will "deoptimize" back to a
31// generic implementation of the same function, which will have the correct
32// semantics from that point onward. It is always _legal_ to deoptimize (so
33// replacing %cmp0 with false is "correct"), though it may not always be
34// profitable to do so.
35//
36// NB! This pass is a work in progress. It hasn't been tuned to be "production
37// ready" yet. It is known to have quadriatic running time and will not scale
38// to large numbers of guards
39//
40//===----------------------------------------------------------------------===//
41
42#include "llvm/Transforms/Scalar/GuardWidening.h"
43#include "llvm/Pass.h"
44#include "llvm/ADT/DenseMap.h"
45#include "llvm/ADT/DepthFirstIterator.h"
46#include "llvm/Analysis/LoopInfo.h"
47#include "llvm/Analysis/PostDominators.h"
48#include "llvm/Analysis/ValueTracking.h"
49#include "llvm/IR/Dominators.h"
50#include "llvm/IR/IntrinsicInst.h"
51#include "llvm/IR/PatternMatch.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Transforms/Scalar.h"
54
55using namespace llvm;
56
57#define DEBUG_TYPE "guard-widening"
58
59namespace {
60
61class GuardWideningImpl {
62 DominatorTree &DT;
63 PostDominatorTree &PDT;
64 LoopInfo &LI;
65
66 /// The set of guards whose conditions have been widened into dominating
67 /// guards.
68 SmallVector<IntrinsicInst *, 16> EliminatedGuards;
69
70 /// The set of guards which have been widened to include conditions to other
71 /// guards.
72 DenseSet<IntrinsicInst *> WidenedGuards;
73
74 /// Try to eliminate guard \p Guard by widening it into an earlier dominating
75 /// guard. \p DFSI is the DFS iterator on the dominator tree that is
76 /// currently visiting the block containing \p Guard, and \p GuardsPerBlock
77 /// maps BasicBlocks to the set of guards seen in that block.
78 bool eliminateGuardViaWidening(
79 IntrinsicInst *Guard, const df_iterator<DomTreeNode *> &DFSI,
80 const DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> &
81 GuardsPerBlock);
82
83 /// Used to keep track of which widening potential is more effective.
84 enum WideningScore {
85 /// Don't widen.
86 WS_IllegalOrNegative,
87
88 /// Widening is performance neutral as far as the cycles spent in check
89 /// conditions goes (but can still help, e.g., code layout, having less
90 /// deopt state).
91 WS_Neutral,
92
93 /// Widening is profitable.
94 WS_Positive,
95
96 /// Widening is very profitable. Not significantly different from \c
97 /// WS_Positive, except by the order.
98 WS_VeryPositive
99 };
100
101 static StringRef scoreTypeToString(WideningScore WS);
102
103 /// Compute the score for widening the condition in \p DominatedGuard
104 /// (contained in \p DominatedGuardLoop) into \p DominatingGuard (contained in
105 /// \p DominatingGuardLoop).
106 WideningScore computeWideningScore(IntrinsicInst *DominatedGuard,
107 Loop *DominatedGuardLoop,
108 IntrinsicInst *DominatingGuard,
109 Loop *DominatingGuardLoop);
110
111 /// Helper to check if \p V can be hoisted to \p InsertPos.
112 bool isAvailableAt(Value *V, Instruction *InsertPos) {
113 SmallPtrSet<Instruction *, 8> Visited;
114 return isAvailableAt(V, InsertPos, Visited);
115 }
116
117 bool isAvailableAt(Value *V, Instruction *InsertPos,
118 SmallPtrSetImpl<Instruction *> &Visited);
119
120 /// Helper to hoist \p V to \p InsertPos. Guaranteed to succeed if \c
121 /// isAvailableAt returned true.
122 void makeAvailableAt(Value *V, Instruction *InsertPos);
123
124 /// Common helper used by \c widenGuard and \c isWideningCondProfitable. Try
125 /// to generate an expression computing the logical AND of \p Cond0 and \p
126 /// Cond1. Return true if the expression computing the AND is only as
127 /// expensive as computing one of the two. If \p InsertPt is true then
128 /// actually generate the resulting expression, make it available at \p
129 /// InsertPt and return it in \p Result (else no change to the IR is made).
130 bool widenCondCommon(Value *Cond0, Value *Cond1, Instruction *InsertPt,
131 Value *&Result);
132
133 /// Can we compute the logical AND of \p Cond0 and \p Cond1 for the price of
134 /// computing only one of the two expressions?
135 bool isWideningCondProfitable(Value *Cond0, Value *Cond1) {
136 Value *ResultUnused;
137 return widenCondCommon(Cond0, Cond1, /*InsertPt=*/nullptr, ResultUnused);
138 }
139
140 /// Widen \p ToWiden to fail if \p NewCondition is false (in addition to
141 /// whatever it is already checking).
142 void widenGuard(IntrinsicInst *ToWiden, Value *NewCondition) {
143 Value *Result;
144 widenCondCommon(ToWiden->getArgOperand(0), NewCondition, ToWiden, Result);
145 ToWiden->setArgOperand(0, Result);
146 }
147
148public:
149 explicit GuardWideningImpl(DominatorTree &DT, PostDominatorTree &PDT,
150 LoopInfo &LI)
151 : DT(DT), PDT(PDT), LI(LI) {}
152
153 /// The entry point for this pass.
154 bool run();
155};
156
157struct GuardWideningLegacyPass : public FunctionPass {
158 static char ID;
159 GuardWideningPass Impl;
160
161 GuardWideningLegacyPass() : FunctionPass(ID) {
162 initializeGuardWideningLegacyPassPass(*PassRegistry::getPassRegistry());
163 }
164
165 bool runOnFunction(Function &F) override {
166 if (skipFunction(F))
167 return false;
168 return GuardWideningImpl(
169 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
170 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(),
171 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()).run();
172 }
173
174 void getAnalysisUsage(AnalysisUsage &AU) const override {
175 AU.setPreservesCFG();
176 AU.addRequired<DominatorTreeWrapperPass>();
177 AU.addRequired<PostDominatorTreeWrapperPass>();
178 AU.addRequired<LoopInfoWrapperPass>();
179 }
180};
181
182}
183
184bool GuardWideningImpl::run() {
185 using namespace llvm::PatternMatch;
186
187 DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> GuardsInBlock;
188 bool Changed = false;
189
190 for (auto DFI = df_begin(DT.getRootNode()), DFE = df_end(DT.getRootNode());
191 DFI != DFE; ++DFI) {
192 auto *BB = (*DFI)->getBlock();
193 auto &CurrentList = GuardsInBlock[BB];
194
195 for (auto &I : *BB)
196 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>()))
197 CurrentList.push_back(cast<IntrinsicInst>(&I));
198
199 for (auto *II : CurrentList)
200 Changed |= eliminateGuardViaWidening(II, DFI, GuardsInBlock);
201 }
202
203 for (auto *II : EliminatedGuards)
204 if (!WidenedGuards.count(II))
205 II->eraseFromParent();
206
207 return Changed;
208}
209
210bool GuardWideningImpl::eliminateGuardViaWidening(
211 IntrinsicInst *GuardInst, const df_iterator<DomTreeNode *> &DFSI,
212 const DenseMap<BasicBlock *, SmallVector<IntrinsicInst *, 8>> &
213 GuardsInBlock) {
214 IntrinsicInst *BestSoFar = nullptr;
215 auto BestScoreSoFar = WS_IllegalOrNegative;
216 auto *GuardInstLoop = LI.getLoopFor(GuardInst->getParent());
217
218 // In the set of dominating guards, find the one we can merge GuardInst with
219 // for the most profit.
220 for (unsigned i = 0, e = DFSI.getPathLength(); i != e; ++i) {
221 auto *CurBB = DFSI.getPath(i)->getBlock();
222 auto *CurLoop = LI.getLoopFor(CurBB);
223 assert(GuardsInBlock.count(CurBB) && "Must have been populated by now!");
224 const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
225
226 auto I = GuardsInCurBB.begin();
227 auto E = GuardsInCurBB.end();
228
229#ifndef NDEBUG
230 {
231 unsigned Index = 0;
232 for (auto &I : *CurBB) {
233 if (Index == GuardsInCurBB.size())
234 break;
235 if (GuardsInCurBB[Index] == &I)
236 Index++;
237 }
238 assert(Index == GuardsInCurBB.size() &&
239 "Guards expected to be in order!");
240 }
241#endif
242
243 assert((i == (e - 1)) == (GuardInst->getParent() == CurBB) && "Bad DFS?");
244
245 if (i == (e - 1)) {
246 // Corner case: make sure we're only looking at guards strictly dominating
247 // GuardInst when visiting GuardInst->getParent().
248 auto NewEnd = std::find(I, E, GuardInst);
249 assert(NewEnd != E && "GuardInst not in its own block?");
250 E = NewEnd;
251 }
252
253 for (auto *Candidate : make_range(I, E)) {
254 auto Score =
255 computeWideningScore(GuardInst, GuardInstLoop, Candidate, CurLoop);
256 DEBUG(dbgs() << "Score between " << *GuardInst->getArgOperand(0)
257 << " and " << *Candidate->getArgOperand(0) << " is "
258 << scoreTypeToString(Score) << "\n");
259 if (Score > BestScoreSoFar) {
260 BestScoreSoFar = Score;
261 BestSoFar = Candidate;
262 }
263 }
264 }
265
266 if (BestScoreSoFar == WS_IllegalOrNegative) {
267 DEBUG(dbgs() << "Did not eliminate guard " << *GuardInst << "\n");
268 return false;
269 }
270
271 assert(BestSoFar != GuardInst && "Should have never visited same guard!");
272 assert(DT.dominates(BestSoFar, GuardInst) && "Should be!");
273
274 DEBUG(dbgs() << "Widening " << *GuardInst << " into " << *BestSoFar
275 << " with score " << scoreTypeToString(BestScoreSoFar) << "\n");
276 widenGuard(BestSoFar, GuardInst->getArgOperand(0));
277 GuardInst->setArgOperand(0, ConstantInt::getTrue(GuardInst->getContext()));
278 EliminatedGuards.push_back(GuardInst);
279 WidenedGuards.insert(BestSoFar);
280 return true;
281}
282
283GuardWideningImpl::WideningScore GuardWideningImpl::computeWideningScore(
284 IntrinsicInst *DominatedGuard, Loop *DominatedGuardLoop,
285 IntrinsicInst *DominatingGuard, Loop *DominatingGuardLoop) {
286 bool HoistingOutOfLoop = false;
287
288 if (DominatingGuardLoop != DominatedGuardLoop) {
289 if (DominatingGuardLoop &&
290 !DominatingGuardLoop->contains(DominatedGuardLoop))
291 return WS_IllegalOrNegative;
292
293 HoistingOutOfLoop = true;
294 }
295
296 if (!isAvailableAt(DominatedGuard->getArgOperand(0), DominatingGuard))
297 return WS_IllegalOrNegative;
298
299 bool HoistingOutOfIf =
300 !PDT.dominates(DominatedGuard->getParent(), DominatingGuard->getParent());
301
302 if (isWideningCondProfitable(DominatedGuard->getArgOperand(0),
303 DominatingGuard->getArgOperand(0)))
304 return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
305
306 if (HoistingOutOfLoop)
307 return WS_Positive;
308
309 return HoistingOutOfIf ? WS_IllegalOrNegative : WS_Neutral;
310}
311
312bool GuardWideningImpl::isAvailableAt(Value *V, Instruction *Loc,
313 SmallPtrSetImpl<Instruction *> &Visited) {
314 auto *Inst = dyn_cast<Instruction>(V);
315 if (!Inst || DT.dominates(Inst, Loc) || Visited.count(Inst))
316 return true;
317
318 if (!isSafeToSpeculativelyExecute(Inst, Loc, &DT) ||
319 Inst->mayReadFromMemory())
320 return false;
321
322 Visited.insert(Inst);
323
324 // We only want to go _up_ the dominance chain when recursing.
325 assert(!isa<PHINode>(Loc) &&
326 "PHIs should return false for isSafeToSpeculativelyExecute");
327 assert(DT.isReachableFromEntry(Inst->getParent()) &&
328 "We did a DFS from the block entry!");
329 return all_of(Inst->operands(),
330 [&](Value *Op) { return isAvailableAt(Op, Loc, Visited); });
331}
332
333void GuardWideningImpl::makeAvailableAt(Value *V, Instruction *Loc) {
334 auto *Inst = dyn_cast<Instruction>(V);
335 if (!Inst || DT.dominates(Inst, Loc))
336 return;
337
338 assert(isSafeToSpeculativelyExecute(Inst, Loc, &DT) &&
339 !Inst->mayReadFromMemory() && "Should've checked with isAvailableAt!");
340
341 for (Value *Op : Inst->operands())
342 makeAvailableAt(Op, Loc);
343
344 Inst->moveBefore(Loc);
345}
346
347bool GuardWideningImpl::widenCondCommon(Value *Cond0, Value *Cond1,
348 Instruction *InsertPt, Value *&Result) {
349 using namespace llvm::PatternMatch;
350
351 {
352 // L >u C0 && L >u C1 -> L >u max(C0, C1)
353 ConstantInt *RHS0, *RHS1;
354 Value *LHS;
355 ICmpInst::Predicate Pred0, Pred1;
356 if (match(Cond0, m_ICmp(Pred0, m_Value(LHS), m_ConstantInt(RHS0))) &&
357 match(Cond1, m_ICmp(Pred1, m_Specific(LHS), m_ConstantInt(RHS1)))) {
358
359 // TODO: This logic should be generalized and refactored into a new
360 // Constant::getEquivalentICmp helper.
361 if (Pred0 == ICmpInst::ICMP_NE && RHS0->isZero())
362 Pred0 = ICmpInst::ICMP_UGT;
363 if (Pred1 == ICmpInst::ICMP_NE && RHS1->isZero())
364 Pred1 = ICmpInst::ICMP_UGT;
365
366 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_UGT) {
367 if (InsertPt) {
368 ConstantInt *NewRHS =
369 RHS0->getValue().ugt(RHS1->getValue()) ? RHS0 : RHS1;
370 Result = new ICmpInst(InsertPt, ICmpInst::ICMP_UGT, LHS, NewRHS,
371 "wide.chk");
372 }
373
374 return true;
375 }
376 }
377 }
378
379 // Base case -- just logical-and the two conditions together.
380
381 if (InsertPt) {
382 makeAvailableAt(Cond0, InsertPt);
383 makeAvailableAt(Cond1, InsertPt);
384
385 Result = BinaryOperator::CreateAnd(Cond0, Cond1, "wide.chk", InsertPt);
386 }
387
388 // We were not able to compute Cond0 AND Cond1 for the price of one.
389 return false;
390}
391
392PreservedAnalyses GuardWideningPass::run(Function &F,
393 AnalysisManager<Function> &AM) {
394 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
395 auto &LI = AM.getResult<LoopAnalysis>(F);
396 auto &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
397 bool Changed = GuardWideningImpl(DT, PDT, LI).run();
398 return Changed ? PreservedAnalyses::none() : PreservedAnalyses::all();
399}
400
401StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
402 switch (WS) {
403 case WS_IllegalOrNegative:
404 return "IllegalOrNegative";
405 case WS_Neutral:
406 return "Neutral";
407 case WS_Positive:
408 return "Positive";
409 case WS_VeryPositive:
410 return "VeryPositive";
411 }
412
413 llvm_unreachable("Fully covered switch above!");
414}
415
416char GuardWideningLegacyPass::ID = 0;
417
418INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards",
419 false, false)
420INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
421INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
422INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
423INITIALIZE_PASS_END(GuardWideningLegacyPass, "guard-widening", "Widen guards",
424 false, false)
425
426FunctionPass *llvm::createGuardWideningPass() {
427 return new GuardWideningLegacyPass();
428}