llvm.org GIT mirror llvm / 16a143e
[MustExecute] Move isGuaranteedToExecute and related rourtines to Analysis Next step is to actually merge the implementations and get both implementations tested through the new printer. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@328055 91177308-0d34-0410-b5e6-96231b3b80d8 Philip Reames 2 years ago
4 changed file(s) with 195 addition(s) and 156 deletion(s). Raw diff Collapse all Expand all
0 //===- MustExecute.h - Is an instruction known to execute--------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// Contains a collection of routines for determining if a given instruction is
10 /// guaranteed to execute if a given point in control flow is reached. The most
11 /// common example is an instruction within a loop being provably executed if we
12 /// branch to the header of it's containing loop.
13 ///
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_ANALYSIS_MUSTEXECUTE_H
17 #define LLVM_ANALYSIS_MUSTEXECUTE_H
18
19 namespace llvm {
20
21 class Instruction;
22 class DominatorTree;
23 class Loop;
24
25 /// \brief Captures loop safety information.
26 /// It keep information for loop & its header may throw exception or otherwise
27 /// exit abnormaly on any iteration of the loop which might actually execute
28 /// at runtime. The primary way to consume this infromation is via
29 /// isGuaranteedToExecute below, but some callers bailout or fallback to
30 /// alternate reasoning if a loop contains any implicit control flow.
31 struct LoopSafetyInfo {
32 bool MayThrow = false; // The current loop contains an instruction which
33 // may throw.
34 bool HeaderMayThrow = false; // Same as previous, but specific to loop header
35 // Used to update funclet bundle operands.
36 DenseMap BlockColors;
37
38 LoopSafetyInfo() = default;
39 };
40
41 /// \brief Computes safety information for a loop checks loop body & header for
42 /// the possibility of may throw exception, it takes LoopSafetyInfo and loop as
43 /// argument. Updates safety information in LoopSafetyInfo argument.
44 /// Note: This is defined to clear and reinitialize an already initialized
45 /// LoopSafetyInfo. Some callers rely on this fact.
46 void computeLoopSafetyInfo(LoopSafetyInfo *, Loop *);
47
48 /// Returns true if the instruction in a loop is guaranteed to execute at least
49 /// once (under the assumption that the loop is entered).
50 bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT,
51 const Loop *CurLoop,
52 const LoopSafetyInfo *SafetyInfo);
53
54 }
55
56 #endif
2222 #include "llvm/Analysis/AliasAnalysis.h"
2323 #include "llvm/Analysis/DemandedBits.h"
2424 #include "llvm/Analysis/EHPersonalities.h"
25 #include "llvm/Analysis/MustExecute.h"
2526 #include "llvm/Analysis/TargetTransformInfo.h"
2627 #include "llvm/IR/Dominators.h"
2728 #include "llvm/IR/IRBuilder.h"
3839 class DataLayout;
3940 class Loop;
4041 class LoopInfo;
42 class LoopSafetyInfo;
4143 class OptimizationRemarkEmitter;
4244 class PredicatedScalarEvolution;
4345 class PredIteratorCache;
4648 class TargetLibraryInfo;
4749 class TargetTransformInfo;
4850
49 /// \brief Captures loop safety information.
50 /// It keep information for loop & its header may throw exception.
51 struct LoopSafetyInfo {
52 bool MayThrow = false; // The current loop contains an instruction which
53 // may throw.
54 bool HeaderMayThrow = false; // Same as previous, but specific to loop header
55 // Used to update funclet bundle operands.
56 DenseMap BlockColors;
57
58 LoopSafetyInfo() = default;
59 };
6051
6152 /// The RecurrenceDescriptor is used to identify recurrences variables in a
6253 /// loop. Reduction is a special case of recurrence that has uses of the
479470 SmallVector collectChildrenInLoop(DomTreeNode *N,
480471 const Loop *CurLoop);
481472
482 /// \brief Computes safety information for a loop
483 /// checks loop body & header for the possibility of may throw
484 /// exception, it takes LoopSafetyInfo and loop as argument.
485 /// Updates safety information in LoopSafetyInfo argument.
486 void computeLoopSafetyInfo(LoopSafetyInfo *, Loop *);
487
488 /// Returns true if the instruction in a loop is guaranteed to execute at least
489 /// once.
490 bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT,
491 const Loop *CurLoop,
492 const LoopSafetyInfo *SafetyInfo);
493
494473 /// \brief Returns the instructions that use values defined in the loop.
495474 SmallVector findDefsUsedOutsideOfLoop(Loop *L);
496475
66 //
77 //===----------------------------------------------------------------------===//
88
9 #include "llvm/Analysis/InstructionSimplify.h"
910 #include "llvm/Analysis/LoopInfo.h"
1011 #include "llvm/Analysis/Passes.h"
1112 #include "llvm/Analysis/ValueTracking.h"
2021 #include "llvm/Transforms/Utils/LoopUtils.h"
2122 using namespace llvm;
2223
24 /// Computes loop safety information, checks loop body & header
25 /// for the possibility of may throw exception.
26 ///
27 void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
28 assert(CurLoop != nullptr && "CurLoop cant be null");
29 BasicBlock *Header = CurLoop->getHeader();
30 // Setting default safety values.
31 SafetyInfo->MayThrow = false;
32 SafetyInfo->HeaderMayThrow = false;
33 // Iterate over header and compute safety info.
34 SafetyInfo->HeaderMayThrow =
35 !isGuaranteedToTransferExecutionToSuccessor(Header);
36
37 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
38 // Iterate over loop instructions and compute safety info.
39 // Skip header as it has been computed and stored in HeaderMayThrow.
40 // The first block in loopinfo.Blocks is guaranteed to be the header.
41 assert(Header == *CurLoop->getBlocks().begin() &&
42 "First block must be header");
43 for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
44 BBE = CurLoop->block_end();
45 (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
46 SafetyInfo->MayThrow |=
47 !isGuaranteedToTransferExecutionToSuccessor(*BB);
48
49 // Compute funclet colors if we might sink/hoist in a function with a funclet
50 // personality routine.
51 Function *Fn = CurLoop->getHeader()->getParent();
52 if (Fn->hasPersonalityFn())
53 if (Constant *PersonalityFn = Fn->getPersonalityFn())
54 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
55 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
56 }
57
58 /// Return true if we can prove that the given ExitBlock is not reached on the
59 /// first iteration of the given loop. That is, the backedge of the loop must
60 /// be executed before the ExitBlock is executed in any dynamic execution trace.
61 static bool CanProveNotTakenFirstIteration(BasicBlock *ExitBlock,
62 const DominatorTree *DT,
63 const Loop *CurLoop) {
64 auto *CondExitBlock = ExitBlock->getSinglePredecessor();
65 if (!CondExitBlock)
66 // expect unique exits
67 return false;
68 assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
69 auto *BI = dyn_cast(CondExitBlock->getTerminator());
70 if (!BI || !BI->isConditional())
71 return false;
72 auto *Cond = dyn_cast(BI->getCondition());
73 if (!Cond)
74 return false;
75 // todo: this would be a lot more powerful if we used scev, but all the
76 // plumbing is currently missing to pass a pointer in from the pass
77 // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
78 auto *LHS = dyn_cast(Cond->getOperand(0));
79 auto *RHS = Cond->getOperand(1);
80 if (!LHS || LHS->getParent() != CurLoop->getHeader())
81 return false;
82 auto DL = ExitBlock->getModule()->getDataLayout();
83 auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
84 auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
85 IVStart, RHS,
86 {DL, /*TLI*/ nullptr,
87 DT, /*AC*/ nullptr, BI});
88 auto *SimpleCst = dyn_cast_or_null(SimpleValOrNull);
89 if (!SimpleCst)
90 return false;
91 if (ExitBlock == BI->getSuccessor(0))
92 return SimpleCst->isZeroValue();
93 assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
94 return SimpleCst->isAllOnesValue();
95 }
96
97 /// Returns true if the instruction in a loop is guaranteed to execute at least
98 /// once.
99 bool llvm::isGuaranteedToExecute(const Instruction &Inst,
100 const DominatorTree *DT, const Loop *CurLoop,
101 const LoopSafetyInfo *SafetyInfo) {
102 // We have to check to make sure that the instruction dominates all
103 // of the exit blocks. If it doesn't, then there is a path out of the loop
104 // which does not execute this instruction, so we can't hoist it.
105
106 // If the instruction is in the header block for the loop (which is very
107 // common), it is always guaranteed to dominate the exit blocks. Since this
108 // is a common case, and can save some work, check it now.
109 if (Inst.getParent() == CurLoop->getHeader())
110 // If there's a throw in the header block, we can't guarantee we'll reach
111 // Inst.
112 return !SafetyInfo->HeaderMayThrow;
113
114 // Somewhere in this loop there is an instruction which may throw and make us
115 // exit the loop.
116 if (SafetyInfo->MayThrow)
117 return false;
118
119 // Note: There are two styles of reasoning intermixed below for
120 // implementation efficiency reasons. They are:
121 // 1) If we can prove that the instruction dominates all exit blocks, then we
122 // know the instruction must have executed on *some* iteration before we
123 // exit. We do not prove *which* iteration the instruction must execute on.
124 // 2) If we can prove that the instruction dominates the latch and all exits
125 // which might be taken on the first iteration, we know the instruction must
126 // execute on the first iteration. This second style allows a conditional
127 // exit before the instruction of interest which is provably not taken on the
128 // first iteration. This is a quite common case for range check like
129 // patterns. TODO: support loops with multiple latches.
130
131 const bool InstDominatesLatch =
132 CurLoop->getLoopLatch() != nullptr &&
133 DT->dominates(Inst.getParent(), CurLoop->getLoopLatch());
134
135 // Get the exit blocks for the current loop.
136 SmallVector ExitBlocks;
137 CurLoop->getExitBlocks(ExitBlocks);
138
139 // Verify that the block dominates each of the exit blocks of the loop.
140 for (BasicBlock *ExitBlock : ExitBlocks)
141 if (!DT->dominates(Inst.getParent(), ExitBlock))
142 if (!InstDominatesLatch ||
143 !CanProveNotTakenFirstIteration(ExitBlock, DT, CurLoop))
144 return false;
145
146 // As a degenerate case, if the loop is statically infinite then we haven't
147 // proven anything since there are no exit blocks.
148 if (ExitBlocks.empty())
149 return false;
150
151 // FIXME: In general, we have to prove that the loop isn't an infinite loop.
152 // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
153 // just a special case of this.)
154 return true;
155 }
156
157
23158 namespace {
24159 struct MustExecutePrinter : public FunctionPass {
25160
1818 #include "llvm/Analysis/InstructionSimplify.h"
1919 #include "llvm/Analysis/LoopInfo.h"
2020 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/MustExecute.h"
2122 #include "llvm/Analysis/ScalarEvolution.h"
2223 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
2324 #include "llvm/Analysis/ScalarEvolutionExpander.h"
14791480 // The last step is to update LoopInfo now that we've eliminated this loop.
14801481 LI->erase(L);
14811482 }
1482 }
1483
1484 /// Computes loop safety information, checks loop body & header
1485 /// for the possibility of may throw exception.
1486 ///
1487 void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
1488 assert(CurLoop != nullptr && "CurLoop cant be null");
1489 BasicBlock *Header = CurLoop->getHeader();
1490 // Setting default safety values.
1491 SafetyInfo->MayThrow = false;
1492 SafetyInfo->HeaderMayThrow = false;
1493 // Iterate over header and compute safety info.
1494 SafetyInfo->HeaderMayThrow =
1495 !isGuaranteedToTransferExecutionToSuccessor(Header);
1496
1497 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
1498 // Iterate over loop instructions and compute safety info.
1499 // Skip header as it has been computed and stored in HeaderMayThrow.
1500 // The first block in loopinfo.Blocks is guaranteed to be the header.
1501 assert(Header == *CurLoop->getBlocks().begin() &&
1502 "First block must be header");
1503 for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
1504 BBE = CurLoop->block_end();
1505 (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
1506 SafetyInfo->MayThrow |=
1507 !isGuaranteedToTransferExecutionToSuccessor(*BB);
1508
1509 // Compute funclet colors if we might sink/hoist in a function with a funclet
1510 // personality routine.
1511 Function *Fn = CurLoop->getHeader()->getParent();
1512 if (Fn->hasPersonalityFn())
1513 if (Constant *PersonalityFn = Fn->getPersonalityFn())
1514 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
1515 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
1516 }
1517
1518 /// Return true if we can prove that the given ExitBlock is not reached on the
1519 /// first iteration of the given loop. That is, the backedge of the loop must
1520 /// be executed before the ExitBlock is executed in any dynamic execution trace.
1521 static bool CanProveNotTakenFirstIteration(BasicBlock *ExitBlock,
1522 const DominatorTree *DT,
1523 const Loop *CurLoop) {
1524 auto *CondExitBlock = ExitBlock->getSinglePredecessor();
1525 if (!CondExitBlock)
1526 // expect unique exits
1527 return false;
1528 assert(CurLoop->contains(CondExitBlock) && "meaning of exit block");
1529 auto *BI = dyn_cast(CondExitBlock->getTerminator());
1530 if (!BI || !BI->isConditional())
1531 return false;
1532 auto *Cond = dyn_cast(BI->getCondition());
1533 if (!Cond)
1534 return false;
1535 // todo: this would be a lot more powerful if we used scev, but all the
1536 // plumbing is currently missing to pass a pointer in from the pass
1537 // Check for cmp (phi [x, preheader] ...), y where (pred x, y is known
1538 auto *LHS = dyn_cast(Cond->getOperand(0));
1539 auto *RHS = Cond->getOperand(1);
1540 if (!LHS || LHS->getParent() != CurLoop->getHeader())
1541 return false;
1542 auto DL = ExitBlock->getModule()->getDataLayout();
1543 auto *IVStart = LHS->getIncomingValueForBlock(CurLoop->getLoopPreheader());
1544 auto *SimpleValOrNull = SimplifyCmpInst(Cond->getPredicate(),
1545 IVStart, RHS,
1546 {DL, /*TLI*/ nullptr,
1547 DT, /*AC*/ nullptr, BI});
1548 auto *SimpleCst = dyn_cast_or_null(SimpleValOrNull);
1549 if (!SimpleCst)
1550 return false;
1551 if (ExitBlock == BI->getSuccessor(0))
1552 return SimpleCst->isZeroValue();
1553 assert(ExitBlock == BI->getSuccessor(1) && "implied by above");
1554 return SimpleCst->isAllOnesValue();
1555 }
1556
1557 /// Returns true if the instruction in a loop is guaranteed to execute at least
1558 /// once.
1559 bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1560 const DominatorTree *DT, const Loop *CurLoop,
1561 const LoopSafetyInfo *SafetyInfo) {
1562 // We have to check to make sure that the instruction dominates all
1563 // of the exit blocks. If it doesn't, then there is a path out of the loop
1564 // which does not execute this instruction, so we can't hoist it.
1565
1566 // If the instruction is in the header block for the loop (which is very
1567 // common), it is always guaranteed to dominate the exit blocks. Since this
1568 // is a common case, and can save some work, check it now.
1569 if (Inst.getParent() == CurLoop->getHeader())
1570 // If there's a throw in the header block, we can't guarantee we'll reach
1571 // Inst.
1572 return !SafetyInfo->HeaderMayThrow;
1573
1574 // Somewhere in this loop there is an instruction which may throw and make us
1575 // exit the loop.
1576 if (SafetyInfo->MayThrow)
1577 return false;
1578
1579 // Note: There are two styles of reasoning intermixed below for
1580 // implementation efficiency reasons. They are:
1581 // 1) If we can prove that the instruction dominates all exit blocks, then we
1582 // know the instruction must have executed on *some* iteration before we
1583 // exit. We do not prove *which* iteration the instruction must execute on.
1584 // 2) If we can prove that the instruction dominates the latch and all exits
1585 // which might be taken on the first iteration, we know the instruction must
1586 // execute on the first iteration. This second style allows a conditional
1587 // exit before the instruction of interest which is provably not taken on the
1588 // first iteration. This is a quite common case for range check like
1589 // patterns. TODO: support loops with multiple latches.
1590
1591 const bool InstDominatesLatch =
1592 CurLoop->getLoopLatch() != nullptr &&
1593 DT->dominates(Inst.getParent(), CurLoop->getLoopLatch());
1594
1595 // Get the exit blocks for the current loop.
1596 SmallVector ExitBlocks;
1597 CurLoop->getExitBlocks(ExitBlocks);
1598
1599 // Verify that the block dominates each of the exit blocks of the loop.
1600 for (BasicBlock *ExitBlock : ExitBlocks)
1601 if (!DT->dominates(Inst.getParent(), ExitBlock))
1602 if (!InstDominatesLatch ||
1603 !CanProveNotTakenFirstIteration(ExitBlock, DT, CurLoop))
1604 return false;
1605
1606 // As a degenerate case, if the loop is statically infinite then we haven't
1607 // proven anything since there are no exit blocks.
1608 if (ExitBlocks.empty())
1609 return false;
1610
1611 // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1612 // See http::llvm.org/PR24078 . (The "ExitBlocks.empty()" check above is
1613 // just a special case of this.)
1614 return true;
16151483 }
16161484
16171485 Optional llvm::getLoopEstimatedTripCount(Loop *L) {