2001-12-04 01:28:42 +08:00
|
|
|
//===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
|
2005-04-22 07:48:37 +08:00
|
|
|
//
|
2003-10-21 03:43:21 +08:00
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
2007-12-30 04:36:04 +08:00
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
2005-04-22 07:48:37 +08:00
|
|
|
//
|
2003-10-21 03:43:21 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2001-12-04 01:28:42 +08:00
|
|
|
//
|
2004-04-03 04:24:31 +08:00
|
|
|
// This transformation analyzes and transforms the induction variables (and
|
|
|
|
// computations derived from them) into simpler forms suitable for subsequent
|
|
|
|
// analysis and transformation.
|
|
|
|
//
|
|
|
|
// If the trip count of a loop is computable, this pass also makes the following
|
|
|
|
// changes:
|
|
|
|
// 1. The exit condition for the loop is canonicalized to compare the
|
|
|
|
// induction value against the exit value. This turns loops like:
|
|
|
|
// 'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
|
|
|
|
// 2. Any use outside of the loop of an expression derived from the indvar
|
|
|
|
// is changed to compute the derived value outside of the loop, eliminating
|
|
|
|
// the dependence on the exit value of the induction variable. If the only
|
|
|
|
// purpose of the loop is to compute the exit value of some derived
|
|
|
|
// expression, this transformation will make the loop dead.
|
|
|
|
//
|
2001-12-04 01:28:42 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2002-05-08 04:03:00 +08:00
|
|
|
#include "llvm/Transforms/Scalar.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/ADT/DenseMap.h"
|
|
|
|
#include "llvm/ADT/SmallVector.h"
|
|
|
|
#include "llvm/ADT/Statistic.h"
|
2015-09-10 18:22:12 +08:00
|
|
|
#include "llvm/Analysis/GlobalsModRef.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/Analysis/LoopInfo.h"
|
|
|
|
#include "llvm/Analysis/LoopPass.h"
|
|
|
|
#include "llvm/Analysis/ScalarEvolutionExpander.h"
|
[PM/AA] Rebuild LLVM's alias analysis infrastructure in a way compatible
with the new pass manager, and no longer relying on analysis groups.
This builds essentially a ground-up new AA infrastructure stack for
LLVM. The core ideas are the same that are used throughout the new pass
manager: type erased polymorphism and direct composition. The design is
as follows:
- FunctionAAResults is a type-erasing alias analysis results aggregation
interface to walk a single query across a range of results from
different alias analyses. Currently this is function-specific as we
always assume that aliasing queries are *within* a function.
- AAResultBase is a CRTP utility providing stub implementations of
various parts of the alias analysis result concept, notably in several
cases in terms of other more general parts of the interface. This can
be used to implement only a narrow part of the interface rather than
the entire interface. This isn't really ideal, this logic should be
hoisted into FunctionAAResults as currently it will cause
a significant amount of redundant work, but it faithfully models the
behavior of the prior infrastructure.
- All the alias analysis passes are ported to be wrapper passes for the
legacy PM and new-style analysis passes for the new PM with a shared
result object. In some cases (most notably CFL), this is an extremely
naive approach that we should revisit when we can specialize for the
new pass manager.
- BasicAA has been restructured to reflect that it is much more
fundamentally a function analysis because it uses dominator trees and
loop info that need to be constructed for each function.
All of the references to getting alias analysis results have been
updated to use the new aggregation interface. All the preservation and
other pass management code has been updated accordingly.
The way the FunctionAAResultsWrapperPass works is to detect the
available alias analyses when run, and add them to the results object.
This means that we should be able to continue to respect when various
passes are added to the pipeline, for example adding CFL or adding TBAA
passes should just cause their results to be available and to get folded
into this. The exception to this rule is BasicAA which really needs to
be a function pass due to using dominator trees and loop info. As
a consequence, the FunctionAAResultsWrapperPass directly depends on
BasicAA and always includes it in the aggregation.
This has significant implications for preserving analyses. Generally,
most passes shouldn't bother preserving FunctionAAResultsWrapperPass
because rebuilding the results just updates the set of known AA passes.
The exception to this rule are LoopPass instances which need to preserve
all the function analyses that the loop pass manager will end up
needing. This means preserving both BasicAAWrapperPass and the
aggregating FunctionAAResultsWrapperPass.
Now, when preserving an alias analysis, you do so by directly preserving
that analysis. This is only necessary for non-immutable-pass-provided
alias analyses though, and there are only three of interest: BasicAA,
GlobalsAA (formerly GlobalsModRef), and SCEVAA. Usually BasicAA is
preserved when needed because it (like DominatorTree and LoopInfo) is
marked as a CFG-only pass. I've expanded GlobalsAA into the preserved
set everywhere we previously were preserving all of AliasAnalysis, and
I've added SCEVAA in the intersection of that with where we preserve
SCEV itself.
One significant challenge to all of this is that the CGSCC passes were
actually using the alias analysis implementations by taking advantage of
a pretty amazing set of loop holes in the old pass manager's analysis
management code which allowed analysis groups to slide through in many
cases. Moving away from analysis groups makes this problem much more
obvious. To fix it, I've leveraged the flexibility the design of the new
PM components provides to just directly construct the relevant alias
analyses for the relevant functions in the IPO passes that need them.
This is a bit hacky, but should go away with the new pass manager, and
is already in many ways cleaner than the prior state.
Another significant challenge is that various facilities of the old
alias analysis infrastructure just don't fit any more. The most
significant of these is the alias analysis 'counter' pass. That pass
relied on the ability to snoop on AA queries at different points in the
analysis group chain. Instead, I'm planning to build printing
functionality directly into the aggregation layer. I've not included
that in this patch merely to keep it smaller.
Note that all of this needs a nearly complete rewrite of the AA
documentation. I'm planning to do that, but I'd like to make sure the
new design settles, and to flesh out a bit more of what it looks like in
the new pass manager first.
Differential Revision: http://reviews.llvm.org/D12080
llvm-svn: 247167
2015-09-10 01:55:00 +08:00
|
|
|
#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
|
2015-03-24 03:32:43 +08:00
|
|
|
#include "llvm/Analysis/TargetLibraryInfo.h"
|
2014-11-13 02:09:15 +08:00
|
|
|
#include "llvm/Analysis/TargetTransformInfo.h"
|
2013-01-02 19:36:10 +08:00
|
|
|
#include "llvm/IR/BasicBlock.h"
|
2014-03-04 19:45:46 +08:00
|
|
|
#include "llvm/IR/CFG.h"
|
2013-01-02 19:36:10 +08:00
|
|
|
#include "llvm/IR/Constants.h"
|
|
|
|
#include "llvm/IR/DataLayout.h"
|
2014-01-13 17:26:24 +08:00
|
|
|
#include "llvm/IR/Dominators.h"
|
2013-01-02 19:36:10 +08:00
|
|
|
#include "llvm/IR/Instructions.h"
|
|
|
|
#include "llvm/IR/IntrinsicInst.h"
|
|
|
|
#include "llvm/IR/LLVMContext.h"
|
[IndVars] Try to use existing values in RewriteLoopExitValues.
Summary:
In RewriteLoopExitValues, before expanding out an SCEV expression using
SCEVExpander, try to see if an existing LLVM IR expression already
computes the value we're interested in. If so use that existing
expression.
Apart from reducing IndVars' reliance on the rest of the compilation
pipeline, this also prevents IndVars from concluding some expressions as
"high cost" when they're not. For instance,
`InductiveRangeCheckElimination` often emits code of the following form:
```
len = umin(len_A, len_B)
loop:
...
if (i++ < len)
goto loop
outside_loop:
use(i)
```
`SCEVExpander` refuses to rewrite the use of `i` in `outside_loop`,
since it thinks the value of `i` on loop exit, `len`, is a high cost
expansion since it contains an `umax` in it. With this change,
`IndVars` can see that it can re-use `len` instead of creating a new
expression to compute `umin(len_A, len_B)`.
I considered putting this cleverness in `SCEVExpander`, but I was
worried that it may then have a deterimental effect on other passes
that use it. So I decided it was better to just do this in the one
place where it seems like an obviously good idea, with the intent of
generalizing later if needed.
Reviewers: atrick, reames
Subscribers: llvm-commits
Differential Revision: http://reviews.llvm.org/D10782
llvm-svn: 241838
2015-07-10 02:46:12 +08:00
|
|
|
#include "llvm/IR/PatternMatch.h"
|
2013-01-02 19:36:10 +08:00
|
|
|
#include "llvm/IR/Type.h"
|
2011-06-28 11:01:46 +08:00
|
|
|
#include "llvm/Support/CommandLine.h"
|
2007-01-07 09:14:12 +08:00
|
|
|
#include "llvm/Support/Debug.h"
|
2009-08-23 12:37:46 +08:00
|
|
|
#include "llvm/Support/raw_ostream.h"
|
2009-05-12 10:17:14 +08:00
|
|
|
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/Transforms/Utils/Local.h"
|
2011-08-10 11:46:27 +08:00
|
|
|
#include "llvm/Transforms/Utils/SimplifyIndVar.h"
|
2003-12-19 01:19:19 +08:00
|
|
|
using namespace llvm;
|
2003-11-12 06:41:34 +08:00
|
|
|
|
2014-04-22 10:55:47 +08:00
|
|
|
#define DEBUG_TYPE "indvars"
|
|
|
|
|
2011-06-21 11:22:38 +08:00
|
|
|
STATISTIC(NumWidened , "Number of indvars widened");
|
|
|
|
STATISTIC(NumReplaced , "Number of exit values replaced");
|
|
|
|
STATISTIC(NumLFTR , "Number of loop exit tests replaced");
|
|
|
|
STATISTIC(NumElimExt , "Number of IV sign/zero extends eliminated");
|
2011-07-07 04:50:43 +08:00
|
|
|
STATISTIC(NumElimIV , "Number of congruent IVs eliminated");
|
2003-12-22 11:58:44 +08:00
|
|
|
|
2011-11-27 07:01:57 +08:00
|
|
|
// Trip count verification can be enabled by default under NDEBUG if we
|
|
|
|
// implement a strong expression equivalence checker in SCEV. Until then, we
|
|
|
|
// use the verify-indvars flag, which may assert in some cases.
|
|
|
|
static cl::opt<bool> VerifyIndvars(
|
|
|
|
"verify-indvars", cl::Hidden,
|
|
|
|
cl::desc("Verify the ScalarEvolution result after running indvars"));
|
2011-05-04 10:10:13 +08:00
|
|
|
|
2013-12-24 07:31:49 +08:00
|
|
|
static cl::opt<bool> ReduceLiveIVs("liv-reduce", cl::Hidden,
|
|
|
|
cl::desc("Reduce live induction variables."));
|
|
|
|
|
2015-05-29 05:49:07 +08:00
|
|
|
enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl };
|
|
|
|
|
|
|
|
static cl::opt<ReplaceExitVal> ReplaceExitValue(
|
|
|
|
"replexitval", cl::Hidden, cl::init(OnlyCheapRepl),
|
|
|
|
cl::desc("Choose the strategy to replace exit value in IndVarSimplify"),
|
|
|
|
cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"),
|
|
|
|
clEnumValN(OnlyCheapRepl, "cheap",
|
|
|
|
"only replace exit value when the cost is cheap"),
|
|
|
|
clEnumValN(AlwaysRepl, "always",
|
|
|
|
"always replace exit value whenever possible"),
|
|
|
|
clEnumValEnd));
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
struct RewritePhi;
|
|
|
|
}
|
|
|
|
|
2006-12-20 05:40:18 +08:00
|
|
|
namespace {
|
2009-09-02 14:11:42 +08:00
|
|
|
class IndVarSimplify : public LoopPass {
|
2014-11-13 02:09:15 +08:00
|
|
|
LoopInfo *LI;
|
|
|
|
ScalarEvolution *SE;
|
|
|
|
DominatorTree *DT;
|
|
|
|
TargetLibraryInfo *TLI;
|
|
|
|
const TargetTransformInfo *TTI;
|
2011-06-21 11:22:38 +08:00
|
|
|
|
2011-03-18 07:51:11 +08:00
|
|
|
SmallVector<WeakVH, 16> DeadInsts;
|
2003-12-23 15:47:09 +08:00
|
|
|
bool Changed;
|
2003-12-22 11:58:44 +08:00
|
|
|
public:
|
2007-05-02 05:15:47 +08:00
|
|
|
|
2009-07-15 09:26:32 +08:00
|
|
|
static char ID; // Pass identification, replacement for typeid
|
2015-03-10 10:37:25 +08:00
|
|
|
IndVarSimplify()
|
|
|
|
: LoopPass(ID), LI(nullptr), SE(nullptr), DT(nullptr), Changed(false) {
|
2010-10-20 01:21:58 +08:00
|
|
|
initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
|
|
|
|
}
|
2007-05-02 05:15:47 +08:00
|
|
|
|
2014-03-05 17:10:37 +08:00
|
|
|
bool runOnLoop(Loop *L, LPPassManager &LPM) override;
|
2009-02-18 04:49:49 +08:00
|
|
|
|
2014-03-05 17:10:37 +08:00
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override {
|
2014-01-13 21:07:17 +08:00
|
|
|
AU.addRequired<DominatorTreeWrapperPass>();
|
2015-01-17 22:16:18 +08:00
|
|
|
AU.addRequired<LoopInfoWrapperPass>();
|
[PM] Port ScalarEvolution to the new pass manager.
This change makes ScalarEvolution a stand-alone object and just produces
one from a pass as needed. Making this work well requires making the
object movable, using references instead of overwritten pointers in
a number of places, and other refactorings.
I've also wired it up to the new pass manager and added a RUN line to
a test to exercise it under the new pass manager. This includes basic
printing support much like with other analyses.
But there is a big and somewhat scary change here. Prior to this patch
ScalarEvolution was never *actually* invalidated!!! Re-running the pass
just re-wired up the various other analyses and didn't remove any of the
existing entries in the SCEV caches or clear out anything at all. This
might seem OK as everything in SCEV that can uses ValueHandles to track
updates to the values that serve as SCEV keys. However, this still means
that as we ran SCEV over each function in the module, we kept
accumulating more and more SCEVs into the cache. At the end, we would
have a SCEV cache with every value that we ever needed a SCEV for in the
entire module!!! Yowzers. The releaseMemory routine would dump all of
this, but that isn't realy called during normal runs of the pipeline as
far as I can see.
To make matters worse, there *is* actually a key that we don't update
with value handles -- there is a map keyed off of Loop*s. Because
LoopInfo *does* release its memory from run to run, it is entirely
possible to run SCEV over one function, then over another function, and
then lookup a Loop* from the second function but find an entry inserted
for the first function! Ouch.
To make matters still worse, there are plenty of updates that *don't*
trip a value handle. It seems incredibly unlikely that today GVN or
another pass that invalidates SCEV can update values in *just* such
a way that a subsequent run of SCEV will incorrectly find lookups in
a cache, but it is theoretically possible and would be a nightmare to
debug.
With this refactoring, I've fixed all this by actually destroying and
recreating the ScalarEvolution object from run to run. Technically, this
could increase the amount of malloc traffic we see, but then again it is
also technically correct. ;] I don't actually think we're suffering from
tons of malloc traffic from SCEV because if we were, the fact that we
never clear the memory would seem more likely to have come up as an
actual problem before now. So, I've made the simple fix here. If in fact
there are serious issues with too much allocation and deallocation,
I can work on a clever fix that preserves the allocations (while
clearing the data) between each run, but I'd prefer to do that kind of
optimization with a test case / benchmark that shows why we need such
cleverness (and that can test that we actually make it faster). It's
possible that this will make some things faster by making the SCEV
caches have higher locality (due to being significantly smaller) so
until there is a clear benchmark, I think the simple change is best.
Differential Revision: http://reviews.llvm.org/D12063
llvm-svn: 245193
2015-08-17 10:08:17 +08:00
|
|
|
AU.addRequired<ScalarEvolutionWrapperPass>();
|
2009-07-15 09:26:32 +08:00
|
|
|
AU.addRequiredID(LoopSimplifyID);
|
|
|
|
AU.addRequiredID(LCSSAID);
|
2015-09-10 18:22:12 +08:00
|
|
|
AU.addPreserved<GlobalsAAWrapperPass>();
|
[PM] Port ScalarEvolution to the new pass manager.
This change makes ScalarEvolution a stand-alone object and just produces
one from a pass as needed. Making this work well requires making the
object movable, using references instead of overwritten pointers in
a number of places, and other refactorings.
I've also wired it up to the new pass manager and added a RUN line to
a test to exercise it under the new pass manager. This includes basic
printing support much like with other analyses.
But there is a big and somewhat scary change here. Prior to this patch
ScalarEvolution was never *actually* invalidated!!! Re-running the pass
just re-wired up the various other analyses and didn't remove any of the
existing entries in the SCEV caches or clear out anything at all. This
might seem OK as everything in SCEV that can uses ValueHandles to track
updates to the values that serve as SCEV keys. However, this still means
that as we ran SCEV over each function in the module, we kept
accumulating more and more SCEVs into the cache. At the end, we would
have a SCEV cache with every value that we ever needed a SCEV for in the
entire module!!! Yowzers. The releaseMemory routine would dump all of
this, but that isn't realy called during normal runs of the pipeline as
far as I can see.
To make matters worse, there *is* actually a key that we don't update
with value handles -- there is a map keyed off of Loop*s. Because
LoopInfo *does* release its memory from run to run, it is entirely
possible to run SCEV over one function, then over another function, and
then lookup a Loop* from the second function but find an entry inserted
for the first function! Ouch.
To make matters still worse, there are plenty of updates that *don't*
trip a value handle. It seems incredibly unlikely that today GVN or
another pass that invalidates SCEV can update values in *just* such
a way that a subsequent run of SCEV will incorrectly find lookups in
a cache, but it is theoretically possible and would be a nightmare to
debug.
With this refactoring, I've fixed all this by actually destroying and
recreating the ScalarEvolution object from run to run. Technically, this
could increase the amount of malloc traffic we see, but then again it is
also technically correct. ;] I don't actually think we're suffering from
tons of malloc traffic from SCEV because if we were, the fact that we
never clear the memory would seem more likely to have come up as an
actual problem before now. So, I've made the simple fix here. If in fact
there are serious issues with too much allocation and deallocation,
I can work on a clever fix that preserves the allocations (while
clearing the data) between each run, but I'd prefer to do that kind of
optimization with a test case / benchmark that shows why we need such
cleverness (and that can test that we actually make it faster). It's
possible that this will make some things faster by making the SCEV
caches have higher locality (due to being significantly smaller) so
until there is a clear benchmark, I think the simple change is best.
Differential Revision: http://reviews.llvm.org/D12063
llvm-svn: 245193
2015-08-17 10:08:17 +08:00
|
|
|
AU.addPreserved<ScalarEvolutionWrapperPass>();
|
2009-07-15 09:26:32 +08:00
|
|
|
AU.addPreservedID(LoopSimplifyID);
|
|
|
|
AU.addPreservedID(LCSSAID);
|
|
|
|
AU.setPreservesCFG();
|
|
|
|
}
|
2003-12-22 11:58:44 +08:00
|
|
|
|
2004-04-03 04:24:31 +08:00
|
|
|
private:
|
2014-03-05 17:10:37 +08:00
|
|
|
void releaseMemory() override {
|
2011-07-07 04:50:43 +08:00
|
|
|
DeadInsts.clear();
|
|
|
|
}
|
|
|
|
|
2011-03-18 07:51:11 +08:00
|
|
|
bool isValidRewrite(Value *FromVal, Value *ToVal);
|
2007-03-07 14:39:01 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
void HandleFloatingPointIV(Loop *L, PHINode *PH);
|
|
|
|
void RewriteNonIntegerIVs(Loop *L);
|
|
|
|
|
2011-08-10 11:46:27 +08:00
|
|
|
void SimplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LPPassManager &LPM);
|
2011-08-06 15:00:37 +08:00
|
|
|
|
2015-05-29 05:49:07 +08:00
|
|
|
bool CanLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet);
|
2011-08-10 11:46:27 +08:00
|
|
|
void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
|
|
|
|
|
2011-07-19 04:32:31 +08:00
|
|
|
Value *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
|
|
|
|
PHINode *IndVar, SCEVExpander &Rewriter);
|
2009-05-12 10:17:14 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
void SinkUnusedInvariants(Loop *L);
|
[IndVars] Try to use existing values in RewriteLoopExitValues.
Summary:
In RewriteLoopExitValues, before expanding out an SCEV expression using
SCEVExpander, try to see if an existing LLVM IR expression already
computes the value we're interested in. If so use that existing
expression.
Apart from reducing IndVars' reliance on the rest of the compilation
pipeline, this also prevents IndVars from concluding some expressions as
"high cost" when they're not. For instance,
`InductiveRangeCheckElimination` often emits code of the following form:
```
len = umin(len_A, len_B)
loop:
...
if (i++ < len)
goto loop
outside_loop:
use(i)
```
`SCEVExpander` refuses to rewrite the use of `i` in `outside_loop`,
since it thinks the value of `i` on loop exit, `len`, is a high cost
expansion since it contains an `umax` in it. With this change,
`IndVars` can see that it can re-use `len` instead of creating a new
expression to compute `umin(len_A, len_B)`.
I considered putting this cleverness in `SCEVExpander`, but I was
worried that it may then have a deterimental effect on other passes
that use it. So I decided it was better to just do this in the one
place where it seems like an obviously good idea, with the intent of
generalizing later if needed.
Reviewers: atrick, reames
Subscribers: llvm-commits
Differential Revision: http://reviews.llvm.org/D10782
llvm-svn: 241838
2015-07-10 02:46:12 +08:00
|
|
|
|
|
|
|
Value *ExpandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S, Loop *L,
|
2015-08-11 02:23:58 +08:00
|
|
|
Instruction *InsertPt, Type *Ty);
|
2003-12-22 11:58:44 +08:00
|
|
|
};
|
2015-06-23 17:49:53 +08:00
|
|
|
}
|
2001-12-04 12:32:29 +08:00
|
|
|
|
2008-05-13 08:00:25 +08:00
|
|
|
char IndVarSimplify::ID = 0;
|
2010-10-13 03:48:12 +08:00
|
|
|
INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
|
2011-05-04 10:10:13 +08:00
|
|
|
"Induction Variable Simplification", false, false)
|
2014-01-13 21:07:17 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
|
2015-01-17 22:16:18 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
|
[PM] Port ScalarEvolution to the new pass manager.
This change makes ScalarEvolution a stand-alone object and just produces
one from a pass as needed. Making this work well requires making the
object movable, using references instead of overwritten pointers in
a number of places, and other refactorings.
I've also wired it up to the new pass manager and added a RUN line to
a test to exercise it under the new pass manager. This includes basic
printing support much like with other analyses.
But there is a big and somewhat scary change here. Prior to this patch
ScalarEvolution was never *actually* invalidated!!! Re-running the pass
just re-wired up the various other analyses and didn't remove any of the
existing entries in the SCEV caches or clear out anything at all. This
might seem OK as everything in SCEV that can uses ValueHandles to track
updates to the values that serve as SCEV keys. However, this still means
that as we ran SCEV over each function in the module, we kept
accumulating more and more SCEVs into the cache. At the end, we would
have a SCEV cache with every value that we ever needed a SCEV for in the
entire module!!! Yowzers. The releaseMemory routine would dump all of
this, but that isn't realy called during normal runs of the pipeline as
far as I can see.
To make matters worse, there *is* actually a key that we don't update
with value handles -- there is a map keyed off of Loop*s. Because
LoopInfo *does* release its memory from run to run, it is entirely
possible to run SCEV over one function, then over another function, and
then lookup a Loop* from the second function but find an entry inserted
for the first function! Ouch.
To make matters still worse, there are plenty of updates that *don't*
trip a value handle. It seems incredibly unlikely that today GVN or
another pass that invalidates SCEV can update values in *just* such
a way that a subsequent run of SCEV will incorrectly find lookups in
a cache, but it is theoretically possible and would be a nightmare to
debug.
With this refactoring, I've fixed all this by actually destroying and
recreating the ScalarEvolution object from run to run. Technically, this
could increase the amount of malloc traffic we see, but then again it is
also technically correct. ;] I don't actually think we're suffering from
tons of malloc traffic from SCEV because if we were, the fact that we
never clear the memory would seem more likely to have come up as an
actual problem before now. So, I've made the simple fix here. If in fact
there are serious issues with too much allocation and deallocation,
I can work on a clever fix that preserves the allocations (while
clearing the data) between each run, but I'd prefer to do that kind of
optimization with a test case / benchmark that shows why we need such
cleverness (and that can test that we actually make it faster). It's
possible that this will make some things faster by making the SCEV
caches have higher locality (due to being significantly smaller) so
until there is a clear benchmark, I think the simple change is best.
Differential Revision: http://reviews.llvm.org/D12063
llvm-svn: 245193
2015-08-17 10:08:17 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
|
2010-10-13 03:48:12 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(LCSSA)
|
|
|
|
INITIALIZE_PASS_END(IndVarSimplify, "indvars",
|
2011-05-04 10:10:13 +08:00
|
|
|
"Induction Variable Simplification", false, false)
|
2008-05-13 08:00:25 +08:00
|
|
|
|
2008-10-23 07:32:42 +08:00
|
|
|
Pass *llvm::createIndVarSimplifyPass() {
|
2003-12-22 11:58:44 +08:00
|
|
|
return new IndVarSimplify();
|
2001-12-04 12:32:29 +08:00
|
|
|
}
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Return true if the SCEV expansion generated by the rewriter can replace the
|
|
|
|
/// original value. SCEV guarantees that it produces the same value, but the way
|
|
|
|
/// it is produced may be illegal IR. Ideally, this function will only be
|
|
|
|
/// called for verification.
|
2011-03-18 07:51:11 +08:00
|
|
|
bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
|
|
|
|
// If an SCEV expression subsumed multiple pointers, its expansion could
|
|
|
|
// reassociate the GEP changing the base pointer. This is illegal because the
|
|
|
|
// final address produced by a GEP chain must be inbounds relative to its
|
|
|
|
// underlying object. Otherwise basic alias analysis, among other things,
|
|
|
|
// could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
|
|
|
|
// producing an expression involving multiple pointers. Until then, we must
|
|
|
|
// bail out here.
|
|
|
|
//
|
|
|
|
// Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
|
|
|
|
// because it understands lcssa phis while SCEV does not.
|
|
|
|
Value *FromPtr = FromVal;
|
|
|
|
Value *ToPtr = ToVal;
|
|
|
|
if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
|
|
|
|
FromPtr = GEP->getPointerOperand();
|
|
|
|
}
|
|
|
|
if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
|
|
|
|
ToPtr = GEP->getPointerOperand();
|
|
|
|
}
|
|
|
|
if (FromPtr != FromVal || ToPtr != ToVal) {
|
|
|
|
// Quickly check the common case
|
|
|
|
if (FromPtr == ToPtr)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
// SCEV may have rewritten an expression that produces the GEP's pointer
|
|
|
|
// operand. That's ok as long as the pointer operand has the same base
|
|
|
|
// pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
|
|
|
|
// base of a recurrence. This handles the case in which SCEV expansion
|
|
|
|
// converts a pointer type recurrence into a nonrecurrent pointer base
|
|
|
|
// indexed by an integer recurrence.
|
2011-12-05 14:29:09 +08:00
|
|
|
|
|
|
|
// If the GEP base pointer is a vector of pointers, abort.
|
|
|
|
if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
|
|
|
|
return false;
|
|
|
|
|
2011-03-18 07:51:11 +08:00
|
|
|
const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
|
|
|
|
const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
|
|
|
|
if (FromBase == ToBase)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
|
|
|
|
<< *FromBase << " != " << *ToBase << "\n");
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2011-07-20 13:32:06 +08:00
|
|
|
/// Determine the insertion point for this user. By default, insert immediately
|
|
|
|
/// before the user. SCEVExpander or LICM will hoist loop invariants out of the
|
|
|
|
/// loop. For PHI nodes, there may be multiple uses, so compute the nearest
|
|
|
|
/// common dominator for the incoming blocks.
|
|
|
|
static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
|
|
|
|
DominatorTree *DT) {
|
|
|
|
PHINode *PHI = dyn_cast<PHINode>(User);
|
|
|
|
if (!PHI)
|
|
|
|
return User;
|
|
|
|
|
2014-04-25 13:29:35 +08:00
|
|
|
Instruction *InsertPt = nullptr;
|
2011-07-20 13:32:06 +08:00
|
|
|
for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
|
|
|
|
if (PHI->getIncomingValue(i) != Def)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
BasicBlock *InsertBB = PHI->getIncomingBlock(i);
|
|
|
|
if (!InsertPt) {
|
|
|
|
InsertPt = InsertBB->getTerminator();
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
|
|
|
|
InsertPt = InsertBB->getTerminator();
|
|
|
|
}
|
|
|
|
assert(InsertPt && "Missing phi operand");
|
2011-07-20 16:15:21 +08:00
|
|
|
assert((!isa<Instruction>(Def) ||
|
|
|
|
DT->dominates(cast<Instruction>(Def), InsertPt)) &&
|
2011-07-20 13:32:06 +08:00
|
|
|
"def does not dominate all uses");
|
|
|
|
return InsertPt;
|
|
|
|
}
|
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// RewriteNonIntegerIVs and helpers. Prefer integer IVs.
|
|
|
|
//===----------------------------------------------------------------------===//
|
2011-05-04 06:24:10 +08:00
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Convert APF to an integer, if possible.
|
2011-07-12 08:08:50 +08:00
|
|
|
static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
|
|
|
|
bool isExact = false;
|
|
|
|
// See if we can convert this to an int64_t
|
|
|
|
uint64_t UIntVal;
|
|
|
|
if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
|
|
|
|
&isExact) != APFloat::opOK || !isExact)
|
2011-05-04 06:24:10 +08:00
|
|
|
return false;
|
2011-07-12 08:08:50 +08:00
|
|
|
IntVal = UIntVal;
|
2011-05-04 06:24:10 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// If the loop has floating induction variable then insert corresponding
|
|
|
|
/// integer induction variable if possible.
|
2011-07-12 08:08:50 +08:00
|
|
|
/// For example,
|
|
|
|
/// for(double i = 0; i < 10000; ++i)
|
|
|
|
/// bar(i)
|
|
|
|
/// is converted into
|
|
|
|
/// for(int i = 0; i < 10000; ++i)
|
|
|
|
/// bar((double)i);
|
2011-05-25 12:42:22 +08:00
|
|
|
///
|
2011-07-12 08:08:50 +08:00
|
|
|
void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
|
|
|
|
unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
|
|
|
|
unsigned BackEdge = IncomingEdge^1;
|
2011-05-25 12:42:22 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// Check incoming value.
|
|
|
|
ConstantFP *InitValueVal =
|
|
|
|
dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
|
2011-05-25 12:42:22 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
int64_t InitValue;
|
|
|
|
if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
|
|
|
|
return;
|
2011-05-25 12:42:22 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// Check IV increment. Reject this PN if increment operation is not
|
|
|
|
// an add or increment value can not be represented by an integer.
|
|
|
|
BinaryOperator *Incr =
|
|
|
|
dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
|
2014-04-25 13:29:35 +08:00
|
|
|
if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return;
|
2011-05-25 12:42:22 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// If this is not an add of the PHI with a constantfp, or if the constant fp
|
|
|
|
// is not an integer, bail out.
|
|
|
|
ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
|
|
|
|
int64_t IncValue;
|
2014-04-25 13:29:35 +08:00
|
|
|
if (IncValueVal == nullptr || Incr->getOperand(0) != PN ||
|
2011-07-12 08:08:50 +08:00
|
|
|
!ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
|
|
|
|
return;
|
2011-05-25 12:42:22 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// Check Incr uses. One user is PN and the other user is an exit condition
|
|
|
|
// used by the conditional terminator.
|
2014-03-09 11:16:01 +08:00
|
|
|
Value::user_iterator IncrUse = Incr->user_begin();
|
2011-07-12 08:08:50 +08:00
|
|
|
Instruction *U1 = cast<Instruction>(*IncrUse++);
|
2014-03-09 11:16:01 +08:00
|
|
|
if (IncrUse == Incr->user_end()) return;
|
2011-07-12 08:08:50 +08:00
|
|
|
Instruction *U2 = cast<Instruction>(*IncrUse++);
|
2014-03-09 11:16:01 +08:00
|
|
|
if (IncrUse != Incr->user_end()) return;
|
2010-04-13 05:13:43 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// Find exit condition, which is an fcmp. If it doesn't exist, or if it isn't
|
|
|
|
// only used by a branch, we can't transform it.
|
|
|
|
FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
|
|
|
|
if (!Compare)
|
|
|
|
Compare = dyn_cast<FCmpInst>(U2);
|
2014-04-25 13:29:35 +08:00
|
|
|
if (!Compare || !Compare->hasOneUse() ||
|
2014-03-09 11:16:01 +08:00
|
|
|
!isa<BranchInst>(Compare->user_back()))
|
2011-07-12 08:08:50 +08:00
|
|
|
return;
|
2009-02-13 06:19:27 +08:00
|
|
|
|
2014-03-09 11:16:01 +08:00
|
|
|
BranchInst *TheBr = cast<BranchInst>(Compare->user_back());
|
Change the canonical induction variable that we insert.
Instead of producing code like this:
Loop:
X = phi 0, X2
...
X2 = X + 1
if (X != N-1) goto Loop
We now generate code that looks like this:
Loop:
X = phi 0, X2
...
X2 = X + 1
if (X2 != N) goto Loop
This has two big advantages:
1. The trip count of the loop is now explicit in the code, allowing
the direct implementation of Loop::getTripCount()
2. This reduces register pressure in the loop, and allows X and X2 to be
put into the same register.
As a consequence of the second point, the code we generate for loops went
from:
.LBB2: # no_exit.1
...
mov %EDI, %ESI
inc %EDI
cmp %ESI, 2
mov %ESI, %EDI
jne .LBB2 # PC rel: no_exit.1
To:
.LBB2: # no_exit.1
...
inc %ESI
cmp %ESI, 3
jne .LBB2 # PC rel: no_exit.1
... which has two fewer moves, and uses one less register.
llvm-svn: 12961
2004-04-15 23:21:43 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// We need to verify that the branch actually controls the iteration count
|
|
|
|
// of the loop. If not, the new IV can overflow and no one will notice.
|
|
|
|
// The branch block must be in the loop and one of the successors must be out
|
|
|
|
// of the loop.
|
|
|
|
assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
|
|
|
|
if (!L->contains(TheBr->getParent()) ||
|
|
|
|
(L->contains(TheBr->getSuccessor(0)) &&
|
|
|
|
L->contains(TheBr->getSuccessor(1))))
|
|
|
|
return;
|
2004-04-03 04:24:31 +08:00
|
|
|
|
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// If it isn't a comparison with an integer-as-fp (the exit value), we can't
|
|
|
|
// transform it.
|
|
|
|
ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
|
|
|
|
int64_t ExitValue;
|
2014-04-25 13:29:35 +08:00
|
|
|
if (ExitValueVal == nullptr ||
|
2011-07-12 08:08:50 +08:00
|
|
|
!ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
|
|
|
|
return;
|
2009-02-13 06:19:27 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// Find new predicate for integer comparison.
|
|
|
|
CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
|
|
|
|
switch (Compare->getPredicate()) {
|
|
|
|
default: return; // Unknown comparison.
|
|
|
|
case CmpInst::FCMP_OEQ:
|
|
|
|
case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
|
|
|
|
case CmpInst::FCMP_ONE:
|
|
|
|
case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
|
|
|
|
case CmpInst::FCMP_OGT:
|
|
|
|
case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
|
|
|
|
case CmpInst::FCMP_OGE:
|
|
|
|
case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
|
|
|
|
case CmpInst::FCMP_OLT:
|
|
|
|
case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
|
|
|
|
case CmpInst::FCMP_OLE:
|
|
|
|
case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
|
|
|
|
}
|
2009-05-12 10:17:14 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// We convert the floating point induction variable to a signed i32 value if
|
|
|
|
// we can. This is only safe if the comparison will not overflow in a way
|
|
|
|
// that won't be trapped by the integer equivalent operations. Check for this
|
|
|
|
// now.
|
|
|
|
// TODO: We could use i64 if it is native and the range requires it.
|
2003-12-22 11:58:44 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// The start/stride/exit values must all fit in signed i32.
|
|
|
|
if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
|
|
|
|
return;
|
2009-05-12 10:17:14 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// If not actually striding (add x, 0.0), avoid touching the code.
|
|
|
|
if (IncValue == 0)
|
|
|
|
return;
|
|
|
|
|
|
|
|
// Positive and negative strides have different safety conditions.
|
|
|
|
if (IncValue > 0) {
|
|
|
|
// If we have a positive stride, we require the init to be less than the
|
2011-09-13 09:59:32 +08:00
|
|
|
// exit value.
|
|
|
|
if (InitValue >= ExitValue)
|
2011-07-12 08:08:50 +08:00
|
|
|
return;
|
|
|
|
|
|
|
|
uint32_t Range = uint32_t(ExitValue-InitValue);
|
2011-09-13 09:59:32 +08:00
|
|
|
// Check for infinite loop, either:
|
|
|
|
// while (i <= Exit) or until (i > Exit)
|
|
|
|
if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
|
2011-07-12 08:08:50 +08:00
|
|
|
if (++Range == 0) return; // Range overflows.
|
|
|
|
}
|
|
|
|
|
|
|
|
unsigned Leftover = Range % uint32_t(IncValue);
|
|
|
|
|
|
|
|
// If this is an equality comparison, we require that the strided value
|
|
|
|
// exactly land on the exit value, otherwise the IV condition will wrap
|
|
|
|
// around and do things the fp IV wouldn't.
|
|
|
|
if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
|
|
|
|
Leftover != 0)
|
|
|
|
return;
|
|
|
|
|
|
|
|
// If the stride would wrap around the i32 before exiting, we can't
|
|
|
|
// transform the IV.
|
|
|
|
if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
|
|
|
|
return;
|
|
|
|
|
|
|
|
} else {
|
|
|
|
// If we have a negative stride, we require the init to be greater than the
|
2011-09-13 09:59:32 +08:00
|
|
|
// exit value.
|
|
|
|
if (InitValue <= ExitValue)
|
2011-07-12 08:08:50 +08:00
|
|
|
return;
|
|
|
|
|
|
|
|
uint32_t Range = uint32_t(InitValue-ExitValue);
|
2011-09-13 09:59:32 +08:00
|
|
|
// Check for infinite loop, either:
|
|
|
|
// while (i >= Exit) or until (i < Exit)
|
|
|
|
if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
|
2011-07-12 08:08:50 +08:00
|
|
|
if (++Range == 0) return; // Range overflows.
|
|
|
|
}
|
|
|
|
|
|
|
|
unsigned Leftover = Range % uint32_t(-IncValue);
|
|
|
|
|
|
|
|
// If this is an equality comparison, we require that the strided value
|
|
|
|
// exactly land on the exit value, otherwise the IV condition will wrap
|
|
|
|
// around and do things the fp IV wouldn't.
|
|
|
|
if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
|
|
|
|
Leftover != 0)
|
|
|
|
return;
|
|
|
|
|
|
|
|
// If the stride would wrap around the i32 before exiting, we can't
|
|
|
|
// transform the IV.
|
|
|
|
if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2011-07-18 12:54:35 +08:00
|
|
|
IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
|
2011-07-12 08:08:50 +08:00
|
|
|
|
|
|
|
// Insert new integer induction variable.
|
|
|
|
PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
|
|
|
|
NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
|
|
|
|
PN->getIncomingBlock(IncomingEdge));
|
|
|
|
|
|
|
|
Value *NewAdd =
|
|
|
|
BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
|
|
|
|
Incr->getName()+".int", Incr);
|
|
|
|
NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
|
|
|
|
|
|
|
|
ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
|
|
|
|
ConstantInt::get(Int32Ty, ExitValue),
|
|
|
|
Compare->getName());
|
|
|
|
|
|
|
|
// In the following deletions, PN may become dead and may be deleted.
|
|
|
|
// Use a WeakVH to observe whether this happens.
|
|
|
|
WeakVH WeakPH = PN;
|
|
|
|
|
|
|
|
// Delete the old floating point exit comparison. The branch starts using the
|
|
|
|
// new comparison.
|
|
|
|
NewCompare->takeName(Compare);
|
|
|
|
Compare->replaceAllUsesWith(NewCompare);
|
2012-08-29 23:32:21 +08:00
|
|
|
RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI);
|
2011-07-12 08:08:50 +08:00
|
|
|
|
|
|
|
// Delete the old floating point increment.
|
|
|
|
Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
|
2012-08-29 23:32:21 +08:00
|
|
|
RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI);
|
2011-07-12 08:08:50 +08:00
|
|
|
|
|
|
|
// If the FP induction variable still has uses, this is because something else
|
|
|
|
// in the loop uses its value. In order to canonicalize the induction
|
|
|
|
// variable, we chose to eliminate the IV and rewrite it in terms of an
|
|
|
|
// int->fp cast.
|
|
|
|
//
|
|
|
|
// We give preference to sitofp over uitofp because it is faster on most
|
|
|
|
// platforms.
|
|
|
|
if (WeakPH) {
|
|
|
|
Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
|
2011-08-25 04:28:43 +08:00
|
|
|
PN->getParent()->getFirstInsertionPt());
|
2011-07-12 08:08:50 +08:00
|
|
|
PN->replaceAllUsesWith(Conv);
|
2012-08-29 23:32:21 +08:00
|
|
|
RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
|
2011-07-12 08:08:50 +08:00
|
|
|
}
|
2011-08-10 11:46:27 +08:00
|
|
|
Changed = true;
|
2011-07-12 08:08:50 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
|
|
|
|
// First step. Check to see if there are any floating-point recurrences.
|
|
|
|
// If there are, change them into integer recurrences, permitting analysis by
|
|
|
|
// the SCEV routines.
|
|
|
|
//
|
|
|
|
BasicBlock *Header = L->getHeader();
|
|
|
|
|
|
|
|
SmallVector<WeakVH, 8> PHIs;
|
|
|
|
for (BasicBlock::iterator I = Header->begin();
|
|
|
|
PHINode *PN = dyn_cast<PHINode>(I); ++I)
|
|
|
|
PHIs.push_back(PN);
|
|
|
|
|
|
|
|
for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
|
|
|
|
if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
|
|
|
|
HandleFloatingPointIV(L, PN);
|
|
|
|
|
|
|
|
// If the loop previously had floating-point IV, ScalarEvolution
|
|
|
|
// may not have been able to compute a trip count. Now that we've done some
|
|
|
|
// re-writing, the trip count may be computable.
|
|
|
|
if (Changed)
|
|
|
|
SE->forgetLoop(L);
|
|
|
|
}
|
|
|
|
|
2015-05-29 05:49:07 +08:00
|
|
|
namespace {
|
|
|
|
// Collect information about PHI nodes which can be transformed in
|
|
|
|
// RewriteLoopExitValues.
|
|
|
|
struct RewritePhi {
|
|
|
|
PHINode *PN;
|
|
|
|
unsigned Ith; // Ith incoming value.
|
|
|
|
Value *Val; // Exit value after expansion.
|
|
|
|
bool HighCost; // High Cost when expansion.
|
|
|
|
bool SafePhi; // LCSSASafePhiForRAUW.
|
|
|
|
|
|
|
|
RewritePhi(PHINode *P, unsigned I, Value *V, bool H, bool S)
|
|
|
|
: PN(P), Ith(I), Val(V), HighCost(H), SafePhi(S) {}
|
|
|
|
};
|
2015-06-23 17:49:53 +08:00
|
|
|
}
|
2015-05-29 05:49:07 +08:00
|
|
|
|
[IndVars] Try to use existing values in RewriteLoopExitValues.
Summary:
In RewriteLoopExitValues, before expanding out an SCEV expression using
SCEVExpander, try to see if an existing LLVM IR expression already
computes the value we're interested in. If so use that existing
expression.
Apart from reducing IndVars' reliance on the rest of the compilation
pipeline, this also prevents IndVars from concluding some expressions as
"high cost" when they're not. For instance,
`InductiveRangeCheckElimination` often emits code of the following form:
```
len = umin(len_A, len_B)
loop:
...
if (i++ < len)
goto loop
outside_loop:
use(i)
```
`SCEVExpander` refuses to rewrite the use of `i` in `outside_loop`,
since it thinks the value of `i` on loop exit, `len`, is a high cost
expansion since it contains an `umax` in it. With this change,
`IndVars` can see that it can re-use `len` instead of creating a new
expression to compute `umin(len_A, len_B)`.
I considered putting this cleverness in `SCEVExpander`, but I was
worried that it may then have a deterimental effect on other passes
that use it. So I decided it was better to just do this in the one
place where it seems like an obviously good idea, with the intent of
generalizing later if needed.
Reviewers: atrick, reames
Subscribers: llvm-commits
Differential Revision: http://reviews.llvm.org/D10782
llvm-svn: 241838
2015-07-10 02:46:12 +08:00
|
|
|
Value *IndVarSimplify::ExpandSCEVIfNeeded(SCEVExpander &Rewriter, const SCEV *S,
|
|
|
|
Loop *L, Instruction *InsertPt,
|
2015-08-11 02:23:58 +08:00
|
|
|
Type *ResultTy) {
|
[IndVars] Try to use existing values in RewriteLoopExitValues.
Summary:
In RewriteLoopExitValues, before expanding out an SCEV expression using
SCEVExpander, try to see if an existing LLVM IR expression already
computes the value we're interested in. If so use that existing
expression.
Apart from reducing IndVars' reliance on the rest of the compilation
pipeline, this also prevents IndVars from concluding some expressions as
"high cost" when they're not. For instance,
`InductiveRangeCheckElimination` often emits code of the following form:
```
len = umin(len_A, len_B)
loop:
...
if (i++ < len)
goto loop
outside_loop:
use(i)
```
`SCEVExpander` refuses to rewrite the use of `i` in `outside_loop`,
since it thinks the value of `i` on loop exit, `len`, is a high cost
expansion since it contains an `umax` in it. With this change,
`IndVars` can see that it can re-use `len` instead of creating a new
expression to compute `umin(len_A, len_B)`.
I considered putting this cleverness in `SCEVExpander`, but I was
worried that it may then have a deterimental effect on other passes
that use it. So I decided it was better to just do this in the one
place where it seems like an obviously good idea, with the intent of
generalizing later if needed.
Reviewers: atrick, reames
Subscribers: llvm-commits
Differential Revision: http://reviews.llvm.org/D10782
llvm-svn: 241838
2015-07-10 02:46:12 +08:00
|
|
|
// Before expanding S into an expensive LLVM expression, see if we can use an
|
2015-08-11 02:23:58 +08:00
|
|
|
// already existing value as the expansion for S.
|
2015-09-16 07:45:35 +08:00
|
|
|
if (Value *ExistingValue = Rewriter.findExistingExpansion(S, InsertPt, L))
|
2015-09-16 07:45:39 +08:00
|
|
|
if (ExistingValue->getType() == ResultTy)
|
|
|
|
return ExistingValue;
|
[IndVars] Try to use existing values in RewriteLoopExitValues.
Summary:
In RewriteLoopExitValues, before expanding out an SCEV expression using
SCEVExpander, try to see if an existing LLVM IR expression already
computes the value we're interested in. If so use that existing
expression.
Apart from reducing IndVars' reliance on the rest of the compilation
pipeline, this also prevents IndVars from concluding some expressions as
"high cost" when they're not. For instance,
`InductiveRangeCheckElimination` often emits code of the following form:
```
len = umin(len_A, len_B)
loop:
...
if (i++ < len)
goto loop
outside_loop:
use(i)
```
`SCEVExpander` refuses to rewrite the use of `i` in `outside_loop`,
since it thinks the value of `i` on loop exit, `len`, is a high cost
expansion since it contains an `umax` in it. With this change,
`IndVars` can see that it can re-use `len` instead of creating a new
expression to compute `umin(len_A, len_B)`.
I considered putting this cleverness in `SCEVExpander`, but I was
worried that it may then have a deterimental effect on other passes
that use it. So I decided it was better to just do this in the one
place where it seems like an obviously good idea, with the intent of
generalizing later if needed.
Reviewers: atrick, reames
Subscribers: llvm-commits
Differential Revision: http://reviews.llvm.org/D10782
llvm-svn: 241838
2015-07-10 02:46:12 +08:00
|
|
|
|
|
|
|
// We didn't find anything, fall back to using SCEVExpander.
|
|
|
|
return Rewriter.expandCodeFor(S, ResultTy, InsertPt);
|
|
|
|
}
|
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// RewriteLoopExitValues - Optimize IV users outside the loop.
|
|
|
|
// As a side effect, reduces the amount of IV processing within the loop.
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Check to see if this loop has a computable loop-invariant execution count.
|
|
|
|
/// If so, this means that we can compute the final value of any expressions
|
|
|
|
/// that are recurrent in the loop, and substitute the exit values from the loop
|
|
|
|
/// into any instructions outside of the loop that use the final values of the
|
|
|
|
/// current expressions.
|
2011-07-12 08:08:50 +08:00
|
|
|
///
|
|
|
|
/// This is mostly redundant with the regular IndVarSimplify activities that
|
|
|
|
/// happen later, except that it's more powerful in some cases, because it's
|
|
|
|
/// able to brute-force evaluate arbitrary instructions as long as they have
|
|
|
|
/// constant operands at the beginning of the loop.
|
|
|
|
void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
|
|
|
|
// Verify the input to the pass in already in LCSSA form.
|
|
|
|
assert(L->isLCSSAForm(*DT));
|
|
|
|
|
|
|
|
SmallVector<BasicBlock*, 8> ExitBlocks;
|
2007-03-04 11:43:23 +08:00
|
|
|
L->getUniqueExitBlocks(ExitBlocks);
|
|
|
|
|
2015-05-29 05:49:07 +08:00
|
|
|
SmallVector<RewritePhi, 8> RewritePhiSet;
|
2007-03-04 11:43:23 +08:00
|
|
|
// Find all values that are computed inside the loop, but used outside of it.
|
|
|
|
// Because of LCSSA, these values will only occur in LCSSA PHI Nodes. Scan
|
|
|
|
// the exit blocks of the loop to find them.
|
|
|
|
for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
|
|
|
|
BasicBlock *ExitBB = ExitBlocks[i];
|
2009-02-18 03:13:57 +08:00
|
|
|
|
2007-03-04 11:43:23 +08:00
|
|
|
// If there are no PHI nodes in this exit block, then no values defined
|
|
|
|
// inside the loop are used on this path, skip it.
|
|
|
|
PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
|
|
|
|
if (!PN) continue;
|
2009-02-18 03:13:57 +08:00
|
|
|
|
2007-03-04 11:43:23 +08:00
|
|
|
unsigned NumPreds = PN->getNumIncomingValues();
|
2009-02-18 03:13:57 +08:00
|
|
|
|
2014-01-29 12:40:19 +08:00
|
|
|
// We would like to be able to RAUW single-incoming value PHI nodes. We
|
|
|
|
// have to be certain this is safe even when this is an LCSSA PHI node.
|
|
|
|
// While the computed exit value is no longer varying in *this* loop, the
|
|
|
|
// exit block may be an exit block for an outer containing loop as well,
|
|
|
|
// the exit value may be varying in the outer loop, and thus it may still
|
|
|
|
// require an LCSSA PHI node. The safe case is when this is
|
|
|
|
// single-predecessor PHI node (LCSSA) and the exit block containing it is
|
|
|
|
// part of the enclosing loop, or this is the outer most loop of the nest.
|
|
|
|
// In either case the exit value could (at most) be varying in the same
|
|
|
|
// loop body as the phi node itself. Thus if it is in turn used outside of
|
|
|
|
// an enclosing loop it will only be via a separate LCSSA node.
|
|
|
|
bool LCSSASafePhiForRAUW =
|
|
|
|
NumPreds == 1 &&
|
|
|
|
(!L->getParentLoop() || L->getParentLoop() == LI->getLoopFor(ExitBB));
|
|
|
|
|
2007-03-04 11:43:23 +08:00
|
|
|
// Iterate over all of the PHI nodes.
|
|
|
|
BasicBlock::iterator BBI = ExitBB->begin();
|
|
|
|
while ((PN = dyn_cast<PHINode>(BBI++))) {
|
2009-05-25 03:36:09 +08:00
|
|
|
if (PN->use_empty())
|
|
|
|
continue; // dead use, don't replace it
|
2010-02-19 05:34:02 +08:00
|
|
|
|
|
|
|
// SCEV only supports integer expressions for now.
|
|
|
|
if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
|
|
|
|
continue;
|
|
|
|
|
2010-02-19 15:14:22 +08:00
|
|
|
// It's necessary to tell ScalarEvolution about this explicitly so that
|
|
|
|
// it can walk the def-use list and forget all SCEVs, as it may not be
|
|
|
|
// watching the PHI itself. Once the new exit value is in place, there
|
|
|
|
// may not be a def-use connection between the loop and every instruction
|
|
|
|
// which got a SCEVAddRecExpr for that loop.
|
|
|
|
SE->forgetValue(PN);
|
|
|
|
|
2007-03-04 11:43:23 +08:00
|
|
|
// Iterate over all of the values in all the PHI nodes.
|
|
|
|
for (unsigned i = 0; i != NumPreds; ++i) {
|
|
|
|
// If the value being merged in is not integer or is not defined
|
|
|
|
// in the loop, skip it.
|
|
|
|
Value *InVal = PN->getIncomingValue(i);
|
2010-02-19 05:34:02 +08:00
|
|
|
if (!isa<Instruction>(InVal))
|
2007-03-04 11:43:23 +08:00
|
|
|
continue;
|
|
|
|
|
|
|
|
// If this pred is for a subloop, not L itself, skip it.
|
2009-02-18 03:13:57 +08:00
|
|
|
if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
|
2007-03-04 11:43:23 +08:00
|
|
|
continue; // The Block is in a subloop, skip it.
|
|
|
|
|
|
|
|
// Check that InVal is defined in the loop.
|
|
|
|
Instruction *Inst = cast<Instruction>(InVal);
|
2009-12-18 09:24:09 +08:00
|
|
|
if (!L->contains(Inst))
|
2007-03-04 11:43:23 +08:00
|
|
|
continue;
|
2009-02-18 03:13:57 +08:00
|
|
|
|
2007-03-04 11:43:23 +08:00
|
|
|
// Okay, this instruction has a user outside of the current loop
|
|
|
|
// and varies predictably *inside* the loop. Evaluate the value it
|
|
|
|
// contains when the loop exits, if possible.
|
2009-07-08 01:06:11 +08:00
|
|
|
const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
|
2013-10-26 05:35:56 +08:00
|
|
|
if (!SE->isLoopInvariant(ExitValue, L) ||
|
|
|
|
!isSafeToExpand(ExitValue, *SE))
|
2007-03-04 11:43:23 +08:00
|
|
|
continue;
|
|
|
|
|
2013-03-20 04:00:22 +08:00
|
|
|
// Computing the value outside of the loop brings no benefit if :
|
|
|
|
// - it is definitely used inside the loop in a way which can not be
|
|
|
|
// optimized away.
|
|
|
|
// - no use outside of the loop can take advantage of hoisting the
|
|
|
|
// computation out of the loop
|
|
|
|
if (ExitValue->getSCEVType()>=scMulExpr) {
|
|
|
|
unsigned NumHardInternalUses = 0;
|
|
|
|
unsigned NumSoftExternalUses = 0;
|
|
|
|
unsigned NumUses = 0;
|
2014-03-09 11:16:01 +08:00
|
|
|
for (auto IB = Inst->user_begin(), IE = Inst->user_end();
|
|
|
|
IB != IE && NumUses <= 6; ++IB) {
|
2013-03-20 04:00:22 +08:00
|
|
|
Instruction *UseInstr = cast<Instruction>(*IB);
|
|
|
|
unsigned Opc = UseInstr->getOpcode();
|
|
|
|
NumUses++;
|
|
|
|
if (L->contains(UseInstr)) {
|
|
|
|
if (Opc == Instruction::Call || Opc == Instruction::Ret)
|
|
|
|
NumHardInternalUses++;
|
|
|
|
} else {
|
|
|
|
if (Opc == Instruction::PHI) {
|
|
|
|
// Do not count the Phi as a use. LCSSA may have inserted
|
|
|
|
// plenty of trivial ones.
|
|
|
|
NumUses--;
|
2014-03-09 11:16:01 +08:00
|
|
|
for (auto PB = UseInstr->user_begin(),
|
|
|
|
PE = UseInstr->user_end();
|
|
|
|
PB != PE && NumUses <= 6; ++PB, ++NumUses) {
|
2013-03-20 04:00:22 +08:00
|
|
|
unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode();
|
|
|
|
if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret)
|
|
|
|
NumSoftExternalUses++;
|
|
|
|
}
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if (Opc != Instruction::Call && Opc != Instruction::Ret)
|
|
|
|
NumSoftExternalUses++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses)
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2015-08-11 02:23:58 +08:00
|
|
|
bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L, Inst);
|
|
|
|
Value *ExitVal =
|
|
|
|
ExpandSCEVIfNeeded(Rewriter, ExitValue, L, Inst, PN->getType());
|
2009-02-18 03:13:57 +08:00
|
|
|
|
2010-01-05 09:27:06 +08:00
|
|
|
DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
|
2009-08-23 12:37:46 +08:00
|
|
|
<< " LoopVal = " << *Inst << "\n");
|
2007-03-04 09:00:28 +08:00
|
|
|
|
2011-03-18 07:51:11 +08:00
|
|
|
if (!isValidRewrite(Inst, ExitVal)) {
|
|
|
|
DeadInsts.push_back(ExitVal);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2015-05-29 05:49:07 +08:00
|
|
|
// Collect all the candidate PHINodes to be rewritten.
|
|
|
|
RewritePhiSet.push_back(
|
|
|
|
RewritePhi(PN, i, ExitVal, HighCost, LCSSASafePhiForRAUW));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2009-02-18 03:13:57 +08:00
|
|
|
|
2015-05-29 05:49:07 +08:00
|
|
|
bool LoopCanBeDel = CanLoopBeDeleted(L, RewritePhiSet);
|
2009-02-18 03:13:57 +08:00
|
|
|
|
2015-05-29 05:49:07 +08:00
|
|
|
// Transformation.
|
|
|
|
for (const RewritePhi &Phi : RewritePhiSet) {
|
|
|
|
PHINode *PN = Phi.PN;
|
|
|
|
Value *ExitVal = Phi.Val;
|
|
|
|
|
|
|
|
// Only do the rewrite when the ExitValue can be expanded cheaply.
|
|
|
|
// If LoopCanBeDel is true, rewrite exit value aggressively.
|
|
|
|
if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
|
|
|
|
DeadInsts.push_back(ExitVal);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
Changed = true;
|
|
|
|
++NumReplaced;
|
|
|
|
Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
|
|
|
|
PN->setIncomingValue(Phi.Ith, ExitVal);
|
|
|
|
|
|
|
|
// If this instruction is dead now, delete it. Don't do it now to avoid
|
|
|
|
// invalidating iterators.
|
|
|
|
if (isInstructionTriviallyDead(Inst, TLI))
|
|
|
|
DeadInsts.push_back(Inst);
|
|
|
|
|
|
|
|
// If we determined that this PHI is safe to replace even if an LCSSA
|
|
|
|
// PHI, do so.
|
|
|
|
if (Phi.SafePhi) {
|
|
|
|
PN->replaceAllUsesWith(ExitVal);
|
|
|
|
PN->eraseFromParent();
|
2007-03-04 06:48:48 +08:00
|
|
|
}
|
|
|
|
}
|
2010-03-20 11:53:53 +08:00
|
|
|
|
|
|
|
// The insertion point instruction may have been deleted; clear it out
|
|
|
|
// so that the rewriter doesn't trip over it later.
|
|
|
|
Rewriter.clearInsertPoint();
|
2004-04-03 04:24:31 +08:00
|
|
|
}
|
2003-12-23 15:47:09 +08:00
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Check whether it is possible to delete the loop after rewriting exit
|
|
|
|
/// value. If it is possible, ignore ReplaceExitValue and do rewriting
|
|
|
|
/// aggressively.
|
2015-05-29 05:49:07 +08:00
|
|
|
bool IndVarSimplify::CanLoopBeDeleted(
|
|
|
|
Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
|
|
|
|
|
|
|
|
BasicBlock *Preheader = L->getLoopPreheader();
|
|
|
|
// If there is no preheader, the loop will not be deleted.
|
|
|
|
if (!Preheader)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
|
|
|
|
// We obviate multiple ExitingBlocks case for simplicity.
|
|
|
|
// TODO: If we see testcase with multiple ExitingBlocks can be deleted
|
|
|
|
// after exit value rewriting, we can enhance the logic here.
|
|
|
|
SmallVector<BasicBlock *, 4> ExitingBlocks;
|
|
|
|
L->getExitingBlocks(ExitingBlocks);
|
|
|
|
SmallVector<BasicBlock *, 8> ExitBlocks;
|
|
|
|
L->getUniqueExitBlocks(ExitBlocks);
|
|
|
|
if (ExitBlocks.size() > 1 || ExitingBlocks.size() > 1)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
BasicBlock *ExitBlock = ExitBlocks[0];
|
|
|
|
BasicBlock::iterator BI = ExitBlock->begin();
|
|
|
|
while (PHINode *P = dyn_cast<PHINode>(BI)) {
|
|
|
|
Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
|
|
|
|
|
|
|
|
// If the Incoming value of P is found in RewritePhiSet, we know it
|
|
|
|
// could be rewritten to use a loop invariant value in transformation
|
|
|
|
// phase later. Skip it in the loop invariant check below.
|
|
|
|
bool found = false;
|
|
|
|
for (const RewritePhi &Phi : RewritePhiSet) {
|
|
|
|
unsigned i = Phi.Ith;
|
|
|
|
if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
|
|
|
|
found = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Instruction *I;
|
|
|
|
if (!found && (I = dyn_cast<Instruction>(Incoming)))
|
|
|
|
if (!L->hasLoopInvariantOperands(I))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
++BI;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (Loop::block_iterator LI = L->block_begin(), LE = L->block_end();
|
|
|
|
LI != LE; ++LI) {
|
|
|
|
for (BasicBlock::iterator BI = (*LI)->begin(), BE = (*LI)->end(); BI != BE;
|
|
|
|
++BI) {
|
|
|
|
if (BI->mayHaveSideEffects())
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// IV Widening - Extend the width of an IV to cover its widest uses.
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
// Collect information about induction variables that are used by sign/zero
|
|
|
|
// extend operations. This information is recorded by CollectExtend and
|
|
|
|
// provides the input to WidenIV.
|
|
|
|
struct WideIVInfo {
|
2011-10-15 09:38:14 +08:00
|
|
|
PHINode *NarrowIV;
|
2011-07-18 12:54:35 +08:00
|
|
|
Type *WidestNativeType; // Widest integer type created [sz]ext
|
2014-09-27 04:05:35 +08:00
|
|
|
bool IsSigned; // Was a sext user seen before a zext?
|
2011-07-12 08:08:50 +08:00
|
|
|
|
2014-04-25 13:29:35 +08:00
|
|
|
WideIVInfo() : NarrowIV(nullptr), WidestNativeType(nullptr),
|
|
|
|
IsSigned(false) {}
|
2011-07-12 08:08:50 +08:00
|
|
|
};
|
2015-06-23 17:49:53 +08:00
|
|
|
}
|
2011-07-12 08:08:50 +08:00
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Update information about the induction variable that is extended by this
|
|
|
|
/// sign or zero extend operation. This is used to determine the final width of
|
|
|
|
/// the IV before actually widening it.
|
2014-01-03 05:12:11 +08:00
|
|
|
static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE,
|
2015-03-10 10:37:25 +08:00
|
|
|
const TargetTransformInfo *TTI) {
|
2011-08-10 11:46:27 +08:00
|
|
|
bool IsSigned = Cast->getOpcode() == Instruction::SExt;
|
|
|
|
if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
|
|
|
|
return;
|
|
|
|
|
2011-07-18 12:54:35 +08:00
|
|
|
Type *Ty = Cast->getType();
|
2011-07-12 08:08:50 +08:00
|
|
|
uint64_t Width = SE->getTypeSizeInBits(Ty);
|
2015-03-10 10:37:25 +08:00
|
|
|
if (!Cast->getModule()->getDataLayout().isLegalInteger(Width))
|
2011-07-12 08:08:50 +08:00
|
|
|
return;
|
|
|
|
|
2014-11-13 02:09:15 +08:00
|
|
|
// Cast is either an sext or zext up to this point.
|
|
|
|
// We should not widen an indvar if arithmetics on the wider indvar are more
|
|
|
|
// expensive than those on the narrower indvar. We check only the cost of ADD
|
|
|
|
// because at least an ADD is required to increment the induction variable. We
|
|
|
|
// could compute more comprehensively the cost of all instructions on the
|
|
|
|
// induction variable when necessary.
|
|
|
|
if (TTI &&
|
|
|
|
TTI->getArithmeticInstrCost(Instruction::Add, Ty) >
|
|
|
|
TTI->getArithmeticInstrCost(Instruction::Add,
|
|
|
|
Cast->getOperand(0)->getType())) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
if (!WI.WidestNativeType) {
|
|
|
|
WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
|
|
|
|
WI.IsSigned = IsSigned;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// We extend the IV to satisfy the sign of its first user, arbitrarily.
|
|
|
|
if (WI.IsSigned != IsSigned)
|
|
|
|
return;
|
|
|
|
|
|
|
|
if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
|
|
|
|
WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
|
|
|
|
}
|
|
|
|
|
|
|
|
namespace {
|
2011-07-20 12:39:24 +08:00
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Record a link in the Narrow IV def-use chain along with the WideIV that
|
|
|
|
/// computes the same value as the Narrow IV def. This avoids caching Use*
|
|
|
|
/// pointers.
|
2011-07-20 12:39:24 +08:00
|
|
|
struct NarrowIVDefUse {
|
|
|
|
Instruction *NarrowDef;
|
|
|
|
Instruction *NarrowUse;
|
|
|
|
Instruction *WideDef;
|
|
|
|
|
2015-09-20 09:52:18 +08:00
|
|
|
// True if the narrow def is never negative. Tracking this information lets
|
|
|
|
// us use a sign extension instead of a zero extension or vice versa, when
|
|
|
|
// profitable and legal.
|
|
|
|
bool NeverNegative;
|
|
|
|
|
|
|
|
NarrowIVDefUse()
|
|
|
|
: NarrowDef(nullptr), NarrowUse(nullptr), WideDef(nullptr),
|
|
|
|
NeverNegative(false) {}
|
2011-07-20 12:39:24 +08:00
|
|
|
|
2015-09-20 09:52:18 +08:00
|
|
|
NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
|
|
|
|
bool NeverNegative)
|
|
|
|
: NarrowDef(ND), NarrowUse(NU), WideDef(WD),
|
|
|
|
NeverNegative(NeverNegative) {}
|
2011-07-20 12:39:24 +08:00
|
|
|
};
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// The goal of this transform is to remove sign and zero extends without
|
|
|
|
/// creating any new induction variables. To do this, it creates a new phi of
|
|
|
|
/// the wider type and redirects all users, either removing extends or inserting
|
|
|
|
/// truncs whenever we stop propagating the type.
|
2011-07-12 08:08:50 +08:00
|
|
|
///
|
|
|
|
class WidenIV {
|
|
|
|
// Parameters
|
|
|
|
PHINode *OrigPhi;
|
2011-07-18 12:54:35 +08:00
|
|
|
Type *WideType;
|
2011-07-12 08:08:50 +08:00
|
|
|
bool IsSigned;
|
|
|
|
|
|
|
|
// Context
|
|
|
|
LoopInfo *LI;
|
|
|
|
Loop *L;
|
|
|
|
ScalarEvolution *SE;
|
|
|
|
DominatorTree *DT;
|
|
|
|
|
|
|
|
// Result
|
|
|
|
PHINode *WidePhi;
|
|
|
|
Instruction *WideInc;
|
|
|
|
const SCEV *WideIncExpr;
|
2011-06-21 11:22:38 +08:00
|
|
|
SmallVectorImpl<WeakVH> &DeadInsts;
|
2011-05-21 02:25:42 +08:00
|
|
|
|
2011-06-21 11:22:38 +08:00
|
|
|
SmallPtrSet<Instruction*,16> Widened;
|
2011-07-20 12:39:24 +08:00
|
|
|
SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
|
2011-05-21 02:25:42 +08:00
|
|
|
|
|
|
|
public:
|
2011-10-15 09:38:14 +08:00
|
|
|
WidenIV(const WideIVInfo &WI, LoopInfo *LInfo,
|
2011-06-21 11:22:38 +08:00
|
|
|
ScalarEvolution *SEv, DominatorTree *DTree,
|
2011-05-26 08:46:11 +08:00
|
|
|
SmallVectorImpl<WeakVH> &DI) :
|
2011-10-15 09:38:14 +08:00
|
|
|
OrigPhi(WI.NarrowIV),
|
2011-06-21 11:22:38 +08:00
|
|
|
WideType(WI.WidestNativeType),
|
|
|
|
IsSigned(WI.IsSigned),
|
2011-05-21 02:25:42 +08:00
|
|
|
LI(LInfo),
|
|
|
|
L(LI->getLoopFor(OrigPhi->getParent())),
|
|
|
|
SE(SEv),
|
2011-05-26 08:46:11 +08:00
|
|
|
DT(DTree),
|
2014-04-25 13:29:35 +08:00
|
|
|
WidePhi(nullptr),
|
|
|
|
WideInc(nullptr),
|
|
|
|
WideIncExpr(nullptr),
|
2011-06-21 11:22:38 +08:00
|
|
|
DeadInsts(DI) {
|
2011-05-21 02:25:42 +08:00
|
|
|
assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
|
|
|
|
}
|
|
|
|
|
2011-06-21 11:22:38 +08:00
|
|
|
PHINode *CreateWideIV(SCEVExpander &Rewriter);
|
2011-05-21 02:25:42 +08:00
|
|
|
|
|
|
|
protected:
|
2011-09-28 09:35:36 +08:00
|
|
|
Value *getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
|
|
|
|
Instruction *Use);
|
|
|
|
|
2011-07-20 12:39:24 +08:00
|
|
|
Instruction *CloneIVUser(NarrowIVDefUse DU);
|
2011-05-21 02:25:42 +08:00
|
|
|
|
2011-07-06 02:19:39 +08:00
|
|
|
const SCEVAddRecExpr *GetWideRecurrence(Instruction *NarrowUse);
|
|
|
|
|
2011-09-10 09:24:17 +08:00
|
|
|
const SCEVAddRecExpr* GetExtendedOperandRecurrence(NarrowIVDefUse DU);
|
|
|
|
|
2014-08-21 16:25:45 +08:00
|
|
|
const SCEV *GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
|
|
|
|
unsigned OpCode) const;
|
|
|
|
|
2012-01-20 15:41:13 +08:00
|
|
|
Instruction *WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
|
2011-07-02 10:34:25 +08:00
|
|
|
|
2014-09-17 22:10:33 +08:00
|
|
|
bool WidenLoopCompare(NarrowIVDefUse DU);
|
|
|
|
|
2011-07-02 10:34:25 +08:00
|
|
|
void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
|
2011-05-21 02:25:42 +08:00
|
|
|
};
|
|
|
|
} // anonymous namespace
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Perform a quick domtree based check for loop invariance assuming that V is
|
|
|
|
/// used within the loop. LoopInfo::isLoopInvariant() seems gratuitous for this
|
|
|
|
/// purpose.
|
2011-09-28 09:35:36 +08:00
|
|
|
static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
|
|
|
|
Instruction *Inst = dyn_cast<Instruction>(V);
|
|
|
|
if (!Inst)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
return DT->properlyDominates(Inst->getParent(), L->getHeader());
|
|
|
|
}
|
|
|
|
|
|
|
|
Value *WidenIV::getExtend(Value *NarrowOper, Type *WideType, bool IsSigned,
|
|
|
|
Instruction *Use) {
|
|
|
|
// Set the debug location and conservative insertion point.
|
|
|
|
IRBuilder<> Builder(Use);
|
|
|
|
// Hoist the insertion point into loop preheaders as far as possible.
|
|
|
|
for (const Loop *L = LI->getLoopFor(Use->getParent());
|
|
|
|
L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
|
|
|
|
L = L->getParentLoop())
|
|
|
|
Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
|
|
|
|
|
2011-05-25 12:42:22 +08:00
|
|
|
return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
|
|
|
|
Builder.CreateZExt(NarrowOper, WideType);
|
2011-05-21 02:25:42 +08:00
|
|
|
}
|
2010-04-12 10:21:50 +08:00
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Instantiate a wide operation to replace a narrow operation. This only needs
|
|
|
|
/// to handle operations that can evaluation to SCEVAddRec. It can safely return
|
|
|
|
/// 0 for any operation we decide not to clone.
|
2011-07-20 12:39:24 +08:00
|
|
|
Instruction *WidenIV::CloneIVUser(NarrowIVDefUse DU) {
|
|
|
|
unsigned Opcode = DU.NarrowUse->getOpcode();
|
2011-05-21 02:25:42 +08:00
|
|
|
switch (Opcode) {
|
|
|
|
default:
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-05-21 02:25:42 +08:00
|
|
|
case Instruction::Add:
|
|
|
|
case Instruction::Mul:
|
|
|
|
case Instruction::UDiv:
|
|
|
|
case Instruction::Sub:
|
|
|
|
case Instruction::And:
|
|
|
|
case Instruction::Or:
|
|
|
|
case Instruction::Xor:
|
|
|
|
case Instruction::Shl:
|
|
|
|
case Instruction::LShr:
|
|
|
|
case Instruction::AShr:
|
2011-07-20 12:39:24 +08:00
|
|
|
DEBUG(dbgs() << "Cloning IVUser: " << *DU.NarrowUse << "\n");
|
2011-05-21 02:25:42 +08:00
|
|
|
|
2011-05-25 12:42:22 +08:00
|
|
|
// Replace NarrowDef operands with WideDef. Otherwise, we don't know
|
|
|
|
// anything about the narrow operand yet so must insert a [sz]ext. It is
|
|
|
|
// probably loop invariant and will be folded or hoisted. If it actually
|
|
|
|
// comes from a widened IV, it should be removed during a future call to
|
|
|
|
// WidenIVUse.
|
2011-07-20 12:39:24 +08:00
|
|
|
Value *LHS = (DU.NarrowUse->getOperand(0) == DU.NarrowDef) ? DU.WideDef :
|
2011-09-28 09:35:36 +08:00
|
|
|
getExtend(DU.NarrowUse->getOperand(0), WideType, IsSigned, DU.NarrowUse);
|
2011-07-20 12:39:24 +08:00
|
|
|
Value *RHS = (DU.NarrowUse->getOperand(1) == DU.NarrowDef) ? DU.WideDef :
|
2011-09-28 09:35:36 +08:00
|
|
|
getExtend(DU.NarrowUse->getOperand(1), WideType, IsSigned, DU.NarrowUse);
|
2011-05-25 12:42:22 +08:00
|
|
|
|
2011-07-20 12:39:24 +08:00
|
|
|
BinaryOperator *NarrowBO = cast<BinaryOperator>(DU.NarrowUse);
|
2011-05-21 02:25:42 +08:00
|
|
|
BinaryOperator *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(),
|
2011-05-25 12:42:22 +08:00
|
|
|
LHS, RHS,
|
2011-05-21 02:25:42 +08:00
|
|
|
NarrowBO->getName());
|
2011-09-28 09:35:36 +08:00
|
|
|
IRBuilder<> Builder(DU.NarrowUse);
|
2011-05-21 02:25:42 +08:00
|
|
|
Builder.Insert(WideBO);
|
2011-07-01 03:02:17 +08:00
|
|
|
if (const OverflowingBinaryOperator *OBO =
|
|
|
|
dyn_cast<OverflowingBinaryOperator>(NarrowBO)) {
|
|
|
|
if (OBO->hasNoUnsignedWrap()) WideBO->setHasNoUnsignedWrap();
|
|
|
|
if (OBO->hasNoSignedWrap()) WideBO->setHasNoSignedWrap();
|
|
|
|
}
|
2011-05-25 12:42:22 +08:00
|
|
|
return WideBO;
|
2011-05-21 02:25:42 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-08-21 16:25:45 +08:00
|
|
|
const SCEV *WidenIV::GetSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
|
|
|
|
unsigned OpCode) const {
|
|
|
|
if (OpCode == Instruction::Add)
|
|
|
|
return SE->getAddExpr(LHS, RHS);
|
|
|
|
if (OpCode == Instruction::Sub)
|
|
|
|
return SE->getMinusSCEV(LHS, RHS);
|
|
|
|
if (OpCode == Instruction::Mul)
|
|
|
|
return SE->getMulExpr(LHS, RHS);
|
|
|
|
|
|
|
|
llvm_unreachable("Unsupported opcode.");
|
|
|
|
}
|
|
|
|
|
2011-09-10 09:24:17 +08:00
|
|
|
/// No-wrap operations can transfer sign extension of their result to their
|
|
|
|
/// operands. Generate the SCEV value for the widened operation without
|
|
|
|
/// actually modifying the IR yet. If the expression after extending the
|
|
|
|
/// operands is an AddRec for this loop, return it.
|
|
|
|
const SCEVAddRecExpr* WidenIV::GetExtendedOperandRecurrence(NarrowIVDefUse DU) {
|
2014-08-21 16:25:45 +08:00
|
|
|
|
2011-09-10 09:24:17 +08:00
|
|
|
// Handle the common case of add<nsw/nuw>
|
2014-08-21 16:25:45 +08:00
|
|
|
const unsigned OpCode = DU.NarrowUse->getOpcode();
|
|
|
|
// Only Add/Sub/Mul instructions supported yet.
|
|
|
|
if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
|
|
|
|
OpCode != Instruction::Mul)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-09-10 09:24:17 +08:00
|
|
|
|
|
|
|
// One operand (NarrowDef) has already been extended to WideDef. Now determine
|
|
|
|
// if extending the other will lead to a recurrence.
|
2014-10-02 21:01:15 +08:00
|
|
|
const unsigned ExtendOperIdx =
|
|
|
|
DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
|
2011-09-10 09:24:17 +08:00
|
|
|
assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
|
|
|
|
|
2014-04-25 13:29:35 +08:00
|
|
|
const SCEV *ExtendOperExpr = nullptr;
|
2011-09-10 09:24:17 +08:00
|
|
|
const OverflowingBinaryOperator *OBO =
|
|
|
|
cast<OverflowingBinaryOperator>(DU.NarrowUse);
|
|
|
|
if (IsSigned && OBO->hasNoSignedWrap())
|
|
|
|
ExtendOperExpr = SE->getSignExtendExpr(
|
|
|
|
SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
|
|
|
|
else if(!IsSigned && OBO->hasNoUnsignedWrap())
|
|
|
|
ExtendOperExpr = SE->getZeroExtendExpr(
|
|
|
|
SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
|
|
|
|
else
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-09-10 09:24:17 +08:00
|
|
|
|
2014-08-21 16:25:45 +08:00
|
|
|
// When creating this SCEV expr, don't apply the current operations NSW or NUW
|
2011-11-29 10:16:38 +08:00
|
|
|
// flags. This instruction may be guarded by control flow that the no-wrap
|
|
|
|
// behavior depends on. Non-control-equivalent instructions can be mapped to
|
|
|
|
// the same SCEV expression, and it would be incorrect to transfer NSW/NUW
|
|
|
|
// semantics to those operations.
|
2014-10-02 21:01:15 +08:00
|
|
|
const SCEV *lhs = SE->getSCEV(DU.WideDef);
|
|
|
|
const SCEV *rhs = ExtendOperExpr;
|
|
|
|
|
|
|
|
// Let's swap operands to the initial order for the case of non-commutative
|
|
|
|
// operations, like SUB. See PR21014.
|
|
|
|
if (ExtendOperIdx == 0)
|
|
|
|
std::swap(lhs, rhs);
|
|
|
|
const SCEVAddRecExpr *AddRec =
|
|
|
|
dyn_cast<SCEVAddRecExpr>(GetSCEVByOpCode(lhs, rhs, OpCode));
|
|
|
|
|
2011-09-10 09:24:17 +08:00
|
|
|
if (!AddRec || AddRec->getLoop() != L)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-09-10 09:24:17 +08:00
|
|
|
return AddRec;
|
|
|
|
}
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Is this instruction potentially interesting for further simplification after
|
|
|
|
/// widening it's type? In other words, can the extend be safely hoisted out of
|
|
|
|
/// the loop with SCEV reducing the value to a recurrence on the same loop. If
|
|
|
|
/// so, return the sign or zero extended recurrence. Otherwise return NULL.
|
2011-07-06 02:19:39 +08:00
|
|
|
const SCEVAddRecExpr *WidenIV::GetWideRecurrence(Instruction *NarrowUse) {
|
|
|
|
if (!SE->isSCEVable(NarrowUse->getType()))
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-07-06 02:19:39 +08:00
|
|
|
|
|
|
|
const SCEV *NarrowExpr = SE->getSCEV(NarrowUse);
|
|
|
|
if (SE->getTypeSizeInBits(NarrowExpr->getType())
|
|
|
|
>= SE->getTypeSizeInBits(WideType)) {
|
|
|
|
// NarrowUse implicitly widens its operand. e.g. a gep with a narrow
|
|
|
|
// index. So don't follow this use.
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-07-06 02:19:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
const SCEV *WideExpr = IsSigned ?
|
|
|
|
SE->getSignExtendExpr(NarrowExpr, WideType) :
|
|
|
|
SE->getZeroExtendExpr(NarrowExpr, WideType);
|
|
|
|
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
|
|
|
|
if (!AddRec || AddRec->getLoop() != L)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-07-06 02:19:39 +08:00
|
|
|
return AddRec;
|
|
|
|
}
|
|
|
|
|
2014-01-03 03:29:38 +08:00
|
|
|
/// This IV user cannot be widen. Replace this use of the original narrow IV
|
|
|
|
/// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
|
|
|
|
static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT) {
|
2014-01-07 14:59:12 +08:00
|
|
|
DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef
|
|
|
|
<< " for user " << *DU.NarrowUse << "\n");
|
2014-01-03 03:29:38 +08:00
|
|
|
IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
|
|
|
|
Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
|
|
|
|
DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
|
|
|
|
}
|
|
|
|
|
2014-09-17 22:10:33 +08:00
|
|
|
/// If the narrow use is a compare instruction, then widen the compare
|
|
|
|
// (and possibly the other operand). The extend operation is hoisted into the
|
|
|
|
// loop preheader as far as possible.
|
|
|
|
bool WidenIV::WidenLoopCompare(NarrowIVDefUse DU) {
|
|
|
|
ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
|
|
|
|
if (!Cmp)
|
|
|
|
return false;
|
|
|
|
|
2015-09-19 05:21:02 +08:00
|
|
|
// We can legally widen the comparison in the following two cases:
|
|
|
|
//
|
|
|
|
// - The signedness of the IV extension and comparison match
|
|
|
|
//
|
|
|
|
// - The narrow IV is always positive (and thus its sign extension is equal
|
|
|
|
// to its zero extension). For instance, let's say we're zero extending
|
|
|
|
// %narrow for the following use
|
|
|
|
//
|
|
|
|
// icmp slt i32 %narrow, %val ... (A)
|
|
|
|
//
|
|
|
|
// and %narrow is always positive. Then
|
|
|
|
//
|
|
|
|
// (A) == icmp slt i32 sext(%narrow), sext(%val)
|
|
|
|
// == icmp slt i32 zext(%narrow), sext(%val)
|
|
|
|
|
2015-09-20 09:52:18 +08:00
|
|
|
if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
|
2014-09-18 00:35:09 +08:00
|
|
|
return false;
|
|
|
|
|
2014-09-17 22:10:33 +08:00
|
|
|
Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
|
|
|
|
unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
|
|
|
|
unsigned IVWidth = SE->getTypeSizeInBits(WideType);
|
|
|
|
assert (CastWidth <= IVWidth && "Unexpected width while widening compare.");
|
|
|
|
|
|
|
|
// Widen the compare instruction.
|
|
|
|
IRBuilder<> Builder(getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT));
|
|
|
|
DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
|
|
|
|
|
|
|
|
// Widen the other operand of the compare, if necessary.
|
|
|
|
if (CastWidth < IVWidth) {
|
2015-09-19 05:21:02 +08:00
|
|
|
Value *ExtOp = getExtend(Op, WideType, Cmp->isSigned(), Cmp);
|
2014-09-17 22:10:33 +08:00
|
|
|
DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Determine whether an individual user of the narrow IV can be widened. If so,
|
|
|
|
/// return the wide clone of the user.
|
2012-01-20 15:41:13 +08:00
|
|
|
Instruction *WidenIV::WidenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) {
|
2011-06-30 07:03:57 +08:00
|
|
|
|
2011-07-02 10:34:25 +08:00
|
|
|
// Stop traversing the def-use chain at inner-loop phis or post-loop phis.
|
2014-01-07 14:59:12 +08:00
|
|
|
if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
|
|
|
|
if (LI->getLoopFor(UsePhi->getParent()) != L) {
|
|
|
|
// For LCSSA phis, sink the truncate outside the loop.
|
|
|
|
// After SimplifyCFG most loop exit targets have a single predecessor.
|
|
|
|
// Otherwise fall back to a truncate within the loop.
|
|
|
|
if (UsePhi->getNumOperands() != 1)
|
|
|
|
truncateIVUse(DU, DT);
|
|
|
|
else {
|
|
|
|
PHINode *WidePhi =
|
|
|
|
PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
|
|
|
|
UsePhi);
|
|
|
|
WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
|
|
|
|
IRBuilder<> Builder(WidePhi->getParent()->getFirstInsertionPt());
|
|
|
|
Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
|
|
|
|
UsePhi->replaceAllUsesWith(Trunc);
|
2015-05-30 03:43:39 +08:00
|
|
|
DeadInsts.emplace_back(UsePhi);
|
2014-01-07 14:59:12 +08:00
|
|
|
DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi
|
|
|
|
<< " to " << *WidePhi << "\n");
|
|
|
|
}
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2014-01-07 14:59:12 +08:00
|
|
|
}
|
2014-01-03 03:29:38 +08:00
|
|
|
}
|
2011-05-21 02:25:42 +08:00
|
|
|
// Our raison d'etre! Eliminate sign and zero extension.
|
2011-07-20 12:39:24 +08:00
|
|
|
if (IsSigned ? isa<SExtInst>(DU.NarrowUse) : isa<ZExtInst>(DU.NarrowUse)) {
|
|
|
|
Value *NewDef = DU.WideDef;
|
|
|
|
if (DU.NarrowUse->getType() != WideType) {
|
|
|
|
unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
|
2011-05-25 12:42:22 +08:00
|
|
|
unsigned IVWidth = SE->getTypeSizeInBits(WideType);
|
|
|
|
if (CastWidth < IVWidth) {
|
|
|
|
// The cast isn't as wide as the IV, so insert a Trunc.
|
2011-07-20 12:39:24 +08:00
|
|
|
IRBuilder<> Builder(DU.NarrowUse);
|
|
|
|
NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
|
2011-05-25 12:42:22 +08:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
// A wider extend was hidden behind a narrower one. This may induce
|
|
|
|
// another round of IV widening in which the intermediate IV becomes
|
|
|
|
// dead. It should be very rare.
|
|
|
|
DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
|
2011-07-20 12:39:24 +08:00
|
|
|
<< " not wide enough to subsume " << *DU.NarrowUse << "\n");
|
|
|
|
DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
|
|
|
|
NewDef = DU.NarrowUse;
|
2011-05-25 12:42:22 +08:00
|
|
|
}
|
|
|
|
}
|
2011-07-20 12:39:24 +08:00
|
|
|
if (NewDef != DU.NarrowUse) {
|
|
|
|
DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
|
|
|
|
<< " replaced by " << *DU.WideDef << "\n");
|
2011-05-25 12:42:22 +08:00
|
|
|
++NumElimExt;
|
2011-07-20 12:39:24 +08:00
|
|
|
DU.NarrowUse->replaceAllUsesWith(NewDef);
|
2015-05-30 03:43:39 +08:00
|
|
|
DeadInsts.emplace_back(DU.NarrowUse);
|
2011-05-25 12:42:22 +08:00
|
|
|
}
|
2011-06-21 11:22:38 +08:00
|
|
|
// Now that the extend is gone, we want to expose it's uses for potential
|
|
|
|
// further simplification. We don't need to directly inform SimplifyIVUsers
|
|
|
|
// of the new users, because their parent IV will be processed later as a
|
|
|
|
// new loop phi. If we preserved IVUsers analysis, we would also want to
|
|
|
|
// push the uses of WideDef here.
|
2011-05-21 02:25:42 +08:00
|
|
|
|
|
|
|
// No further widening is needed. The deceased [sz]ext had done it for us.
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-05-21 02:25:42 +08:00
|
|
|
}
|
2011-07-02 10:34:25 +08:00
|
|
|
|
|
|
|
// Does this user itself evaluate to a recurrence after widening?
|
2011-07-20 12:39:24 +08:00
|
|
|
const SCEVAddRecExpr *WideAddRec = GetWideRecurrence(DU.NarrowUse);
|
2014-09-17 22:10:33 +08:00
|
|
|
if (!WideAddRec)
|
|
|
|
WideAddRec = GetExtendedOperandRecurrence(DU);
|
|
|
|
|
2011-09-10 09:24:17 +08:00
|
|
|
if (!WideAddRec) {
|
2014-09-17 22:10:33 +08:00
|
|
|
// If use is a loop condition, try to promote the condition instead of
|
|
|
|
// truncating the IV first.
|
|
|
|
if (WidenLoopCompare(DU))
|
|
|
|
return nullptr;
|
|
|
|
|
2011-05-21 02:25:42 +08:00
|
|
|
// This user does not evaluate to a recurence after widening, so don't
|
|
|
|
// follow it. Instead insert a Trunc to kill off the original use,
|
|
|
|
// eventually isolating the original narrow IV so it can be removed.
|
2014-01-03 03:29:38 +08:00
|
|
|
truncateIVUse(DU, DT);
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-05-21 02:25:42 +08:00
|
|
|
}
|
2011-07-19 04:32:31 +08:00
|
|
|
// Assume block terminators cannot evaluate to a recurrence. We can't to
|
2011-07-02 10:34:25 +08:00
|
|
|
// insert a Trunc after a terminator if there happens to be a critical edge.
|
2011-07-20 12:39:24 +08:00
|
|
|
assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
|
2011-07-02 10:34:25 +08:00
|
|
|
"SCEV is not expected to evaluate a block terminator");
|
2011-06-30 07:03:57 +08:00
|
|
|
|
2011-05-26 08:46:11 +08:00
|
|
|
// Reuse the IV increment that SCEVExpander created as long as it dominates
|
|
|
|
// NarrowUse.
|
2014-04-25 13:29:35 +08:00
|
|
|
Instruction *WideUse = nullptr;
|
2011-10-11 10:28:51 +08:00
|
|
|
if (WideAddRec == WideIncExpr
|
2012-01-20 15:41:13 +08:00
|
|
|
&& Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
|
2011-05-21 02:25:42 +08:00
|
|
|
WideUse = WideInc;
|
|
|
|
else {
|
2011-07-20 12:39:24 +08:00
|
|
|
WideUse = CloneIVUser(DU);
|
2011-05-21 02:25:42 +08:00
|
|
|
if (!WideUse)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-05-21 02:25:42 +08:00
|
|
|
}
|
2011-07-02 10:34:25 +08:00
|
|
|
// Evaluation of WideAddRec ensured that the narrow expression could be
|
|
|
|
// extended outside the loop without overflow. This suggests that the wide use
|
2011-05-21 02:25:42 +08:00
|
|
|
// evaluates to the same expression as the extended narrow use, but doesn't
|
|
|
|
// absolutely guarantee it. Hence the following failsafe check. In rare cases
|
2011-06-21 11:22:38 +08:00
|
|
|
// where it fails, we simply throw away the newly created wide use.
|
2011-05-21 02:25:42 +08:00
|
|
|
if (WideAddRec != SE->getSCEV(WideUse)) {
|
|
|
|
DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse
|
|
|
|
<< ": " << *SE->getSCEV(WideUse) << " != " << *WideAddRec << "\n");
|
2015-05-30 03:43:39 +08:00
|
|
|
DeadInsts.emplace_back(WideUse);
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-05-21 02:25:42 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Returning WideUse pushes it on the worklist.
|
|
|
|
return WideUse;
|
|
|
|
}
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Add eligible users of NarrowDef to NarrowIVUsers.
|
2011-07-02 10:34:25 +08:00
|
|
|
///
|
|
|
|
void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
|
2015-09-20 09:52:18 +08:00
|
|
|
const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
|
|
|
|
bool NeverNegative =
|
|
|
|
SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
|
|
|
|
SE->getConstant(NarrowSCEV->getType(), 0));
|
2014-03-09 11:16:01 +08:00
|
|
|
for (User *U : NarrowDef->users()) {
|
|
|
|
Instruction *NarrowUser = cast<Instruction>(U);
|
2011-07-02 10:34:25 +08:00
|
|
|
|
|
|
|
// Handle data flow merges and bizarre phi cycles.
|
2014-11-19 15:49:26 +08:00
|
|
|
if (!Widened.insert(NarrowUser).second)
|
2011-07-02 10:34:25 +08:00
|
|
|
continue;
|
|
|
|
|
2015-09-20 09:52:18 +08:00
|
|
|
NarrowIVUsers.push_back(
|
|
|
|
NarrowIVDefUse(NarrowDef, NarrowUser, WideDef, NeverNegative));
|
2011-07-02 10:34:25 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Process a single induction variable. First use the SCEVExpander to create a
|
|
|
|
/// wide induction variable that evaluates to the same recurrence as the
|
|
|
|
/// original narrow IV. Then use a worklist to forward traverse the narrow IV's
|
|
|
|
/// def-use chain. After WidenIVUse has processed all interesting IV users, the
|
|
|
|
/// narrow IV will be isolated for removal by DeleteDeadPHIs.
|
2011-05-21 02:25:42 +08:00
|
|
|
///
|
|
|
|
/// It would be simpler to delete uses as they are processed, but we must avoid
|
|
|
|
/// invalidating SCEV expressions.
|
|
|
|
///
|
2011-06-21 11:22:38 +08:00
|
|
|
PHINode *WidenIV::CreateWideIV(SCEVExpander &Rewriter) {
|
2011-05-21 02:25:42 +08:00
|
|
|
// Is this phi an induction variable?
|
|
|
|
const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
|
|
|
|
if (!AddRec)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-05-21 02:25:42 +08:00
|
|
|
|
|
|
|
// Widen the induction variable expression.
|
|
|
|
const SCEV *WideIVExpr = IsSigned ?
|
|
|
|
SE->getSignExtendExpr(AddRec, WideType) :
|
|
|
|
SE->getZeroExtendExpr(AddRec, WideType);
|
|
|
|
|
|
|
|
assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
|
|
|
|
"Expect the new IV expression to preserve its type");
|
|
|
|
|
|
|
|
// Can the IV be extended outside the loop without overflow?
|
|
|
|
AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
|
|
|
|
if (!AddRec || AddRec->getLoop() != L)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-05-21 02:25:42 +08:00
|
|
|
|
2011-06-21 11:22:38 +08:00
|
|
|
// An AddRec must have loop-invariant operands. Since this AddRec is
|
2011-05-21 02:25:42 +08:00
|
|
|
// materialized by a loop header phi, the expression cannot have any post-loop
|
|
|
|
// operands, so they must dominate the loop header.
|
|
|
|
assert(SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
|
|
|
|
SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader())
|
|
|
|
&& "Loop header phi recurrence inputs do not dominate the loop");
|
|
|
|
|
|
|
|
// The rewriter provides a value for the desired IV expression. This may
|
|
|
|
// either find an existing phi or materialize a new one. Either way, we
|
|
|
|
// expect a well-formed cyclic phi-with-increments. i.e. any operand not part
|
|
|
|
// of the phi-SCC dominates the loop entry.
|
|
|
|
Instruction *InsertPt = L->getHeader()->begin();
|
|
|
|
WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
|
|
|
|
|
|
|
|
// Remembering the WideIV increment generated by SCEVExpander allows
|
|
|
|
// WidenIVUse to reuse it when widening the narrow IV's increment. We don't
|
|
|
|
// employ a general reuse mechanism because the call above is the only call to
|
|
|
|
// SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
|
2011-05-26 08:46:11 +08:00
|
|
|
if (BasicBlock *LatchBlock = L->getLoopLatch()) {
|
|
|
|
WideInc =
|
|
|
|
cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
|
|
|
|
WideIncExpr = SE->getSCEV(WideInc);
|
|
|
|
}
|
2011-05-21 02:25:42 +08:00
|
|
|
|
|
|
|
DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
|
|
|
|
++NumWidened;
|
|
|
|
|
|
|
|
// Traverse the def-use chain using a worklist starting at the original IV.
|
2011-07-02 10:34:25 +08:00
|
|
|
assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
|
|
|
|
|
|
|
|
Widened.insert(OrigPhi);
|
|
|
|
pushNarrowIVUsers(OrigPhi, WidePhi);
|
2011-05-21 02:25:42 +08:00
|
|
|
|
|
|
|
while (!NarrowIVUsers.empty()) {
|
2011-07-20 12:39:24 +08:00
|
|
|
NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
|
2011-05-26 08:46:11 +08:00
|
|
|
|
|
|
|
// Process a def-use edge. This may replace the use, so don't hold a
|
|
|
|
// use_iterator across it.
|
2012-01-20 15:41:13 +08:00
|
|
|
Instruction *WideUse = WidenIVUse(DU, Rewriter);
|
2011-05-26 08:46:11 +08:00
|
|
|
|
|
|
|
// Follow all def-use edges from the previous narrow use.
|
2011-07-02 10:34:25 +08:00
|
|
|
if (WideUse)
|
2011-07-20 12:39:24 +08:00
|
|
|
pushNarrowIVUsers(DU.NarrowUse, WideUse);
|
2011-07-02 10:34:25 +08:00
|
|
|
|
2011-05-26 08:46:11 +08:00
|
|
|
// WidenIVUse may have removed the def-use edge.
|
2011-07-20 12:39:24 +08:00
|
|
|
if (DU.NarrowDef->use_empty())
|
2015-05-30 03:43:39 +08:00
|
|
|
DeadInsts.emplace_back(DU.NarrowDef);
|
2010-04-12 10:21:50 +08:00
|
|
|
}
|
2011-06-21 11:22:38 +08:00
|
|
|
return WidePhi;
|
2010-04-12 10:21:50 +08:00
|
|
|
}
|
|
|
|
|
2014-01-03 05:12:11 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// Live IV Reduction - Minimize IVs live across the loop.
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// Simplification of IV users based on SCEV evaluation.
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2014-01-03 05:12:11 +08:00
|
|
|
namespace {
|
|
|
|
class IndVarSimplifyVisitor : public IVVisitor {
|
|
|
|
ScalarEvolution *SE;
|
2014-11-13 02:09:15 +08:00
|
|
|
const TargetTransformInfo *TTI;
|
2014-01-03 05:12:11 +08:00
|
|
|
PHINode *IVPhi;
|
|
|
|
|
|
|
|
public:
|
|
|
|
WideIVInfo WI;
|
|
|
|
|
|
|
|
IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
|
2015-03-10 10:37:25 +08:00
|
|
|
const TargetTransformInfo *TTI,
|
2014-11-13 02:09:15 +08:00
|
|
|
const DominatorTree *DTree)
|
2015-03-10 10:37:25 +08:00
|
|
|
: SE(SCEV), TTI(TTI), IVPhi(IV) {
|
2014-01-03 05:12:11 +08:00
|
|
|
DT = DTree;
|
|
|
|
WI.NarrowIV = IVPhi;
|
|
|
|
if (ReduceLiveIVs)
|
|
|
|
setSplitOverflowIntrinsics();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Implement the interface used by simplifyUsersOfIV.
|
2015-03-10 10:37:25 +08:00
|
|
|
void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
|
2014-01-03 05:12:11 +08:00
|
|
|
};
|
2015-06-23 17:49:53 +08:00
|
|
|
}
|
2011-08-06 15:00:37 +08:00
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Iteratively perform simplification on a worklist of IV users. Each
|
|
|
|
/// successive simplification may push more users which may themselves be
|
|
|
|
/// candidates for simplification.
|
2011-06-21 11:22:38 +08:00
|
|
|
///
|
2011-08-10 11:46:27 +08:00
|
|
|
/// Sign/Zero extend elimination is interleaved with IV simplification.
|
2011-06-21 11:22:38 +08:00
|
|
|
///
|
2011-08-10 11:46:27 +08:00
|
|
|
void IndVarSimplify::SimplifyAndExtend(Loop *L,
|
|
|
|
SCEVExpander &Rewriter,
|
|
|
|
LPPassManager &LPM) {
|
2011-10-15 09:38:14 +08:00
|
|
|
SmallVector<WideIVInfo, 8> WideIVs;
|
2011-06-28 10:49:20 +08:00
|
|
|
|
2011-06-21 11:22:38 +08:00
|
|
|
SmallVector<PHINode*, 8> LoopPhis;
|
|
|
|
for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
|
|
|
|
LoopPhis.push_back(cast<PHINode>(I));
|
|
|
|
}
|
2011-06-28 10:49:20 +08:00
|
|
|
// Each round of simplification iterates through the SimplifyIVUsers worklist
|
|
|
|
// for all current phis, then determines whether any IVs can be
|
|
|
|
// widened. Widening adds new phis to LoopPhis, inducing another round of
|
|
|
|
// simplification on the wide IVs.
|
2011-06-21 11:22:38 +08:00
|
|
|
while (!LoopPhis.empty()) {
|
2011-06-28 10:49:20 +08:00
|
|
|
// Evaluate as many IV expressions as possible before widening any IVs. This
|
2011-06-29 00:45:04 +08:00
|
|
|
// forces SCEV to set no-wrap flags before evaluating sign/zero
|
2011-06-28 10:49:20 +08:00
|
|
|
// extension. The first time SCEV attempts to normalize sign/zero extension,
|
|
|
|
// the result becomes final. So for the most predictable results, we delay
|
|
|
|
// evaluation of sign/zero extend evaluation until needed, and avoid running
|
2011-08-10 11:46:27 +08:00
|
|
|
// other SCEV based analysis prior to SimplifyAndExtend.
|
2011-06-28 10:49:20 +08:00
|
|
|
do {
|
|
|
|
PHINode *CurrIV = LoopPhis.pop_back_val();
|
2011-06-21 11:22:38 +08:00
|
|
|
|
2011-06-28 10:49:20 +08:00
|
|
|
// Information about sign/zero extensions of CurrIV.
|
2015-03-10 10:37:25 +08:00
|
|
|
IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
|
2011-06-28 10:49:20 +08:00
|
|
|
|
2014-01-03 05:12:11 +08:00
|
|
|
Changed |= simplifyUsersOfIV(CurrIV, SE, &LPM, DeadInsts, &Visitor);
|
2011-08-06 15:00:37 +08:00
|
|
|
|
2014-01-03 05:12:11 +08:00
|
|
|
if (Visitor.WI.WidestNativeType) {
|
|
|
|
WideIVs.push_back(Visitor.WI);
|
2011-06-21 11:22:38 +08:00
|
|
|
}
|
2011-06-28 10:49:20 +08:00
|
|
|
} while(!LoopPhis.empty());
|
|
|
|
|
2011-10-15 09:38:14 +08:00
|
|
|
for (; !WideIVs.empty(); WideIVs.pop_back()) {
|
|
|
|
WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts);
|
2011-06-21 11:22:38 +08:00
|
|
|
if (PHINode *WidePhi = Widener.CreateWideIV(Rewriter)) {
|
|
|
|
Changed = true;
|
|
|
|
LoopPhis.push_back(WidePhi);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// LinearFunctionTestReplace and its kin. Rewrite the loop exit condition.
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Return true if this loop's backedge taken count expression can be safely and
|
|
|
|
/// cheaply expanded into an instruction sequence that can be used by
|
|
|
|
/// LinearFunctionTestReplace.
|
2011-11-03 01:19:57 +08:00
|
|
|
///
|
|
|
|
/// TODO: This fails for pointer-type loop counters with greater than one byte
|
|
|
|
/// strides, consequently preventing LFTR from running. For the purpose of LFTR
|
|
|
|
/// we could skip this check in the case that the LFTR loop counter (chosen by
|
|
|
|
/// FindLoopCounter) is also pointer type. Instead, we could directly convert
|
|
|
|
/// the loop test to an inequality test by checking the target data's alignment
|
|
|
|
/// of element types (given that the initial pointer value originates from or is
|
|
|
|
/// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
|
|
|
|
/// However, we don't yet have a strong motivation for converting loop tests
|
|
|
|
/// into inequality tests.
|
2015-04-14 11:20:28 +08:00
|
|
|
static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE,
|
|
|
|
SCEVExpander &Rewriter) {
|
2011-07-12 08:08:50 +08:00
|
|
|
const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
|
|
|
|
if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
|
|
|
|
BackedgeTakenCount->isZero())
|
2010-06-18 09:35:11 +08:00
|
|
|
return false;
|
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
if (!L->getExitingBlock())
|
|
|
|
return false;
|
2011-05-04 10:10:13 +08:00
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// Can't rewrite non-branch yet.
|
2015-04-14 11:20:28 +08:00
|
|
|
if (!isa<BranchInst>(L->getExitingBlock()->getTerminator()))
|
2011-07-12 08:08:50 +08:00
|
|
|
return false;
|
2009-02-18 04:49:49 +08:00
|
|
|
|
2015-04-14 11:20:28 +08:00
|
|
|
if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L))
|
2011-07-19 02:21:35 +08:00
|
|
|
return false;
|
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
return true;
|
|
|
|
}
|
2009-02-18 04:49:49 +08:00
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Return the loop header phi IFF IncV adds a loop invariant value to the phi.
|
2011-07-19 04:32:31 +08:00
|
|
|
static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
|
|
|
|
Instruction *IncI = dyn_cast<Instruction>(IncV);
|
|
|
|
if (!IncI)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-07-19 04:32:31 +08:00
|
|
|
|
|
|
|
switch (IncI->getOpcode()) {
|
|
|
|
case Instruction::Add:
|
|
|
|
case Instruction::Sub:
|
|
|
|
break;
|
|
|
|
case Instruction::GetElementPtr:
|
|
|
|
// An IV counter must preserve its type.
|
|
|
|
if (IncI->getNumOperands() == 2)
|
|
|
|
break;
|
|
|
|
default:
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-07-19 04:32:31 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
|
|
|
|
if (Phi && Phi->getParent() == L->getHeader()) {
|
|
|
|
if (isLoopInvariant(IncI->getOperand(1), L, DT))
|
|
|
|
return Phi;
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-07-19 04:32:31 +08:00
|
|
|
}
|
|
|
|
if (IncI->getOpcode() == Instruction::GetElementPtr)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-07-19 04:32:31 +08:00
|
|
|
|
|
|
|
// Allow add/sub to be commuted.
|
|
|
|
Phi = dyn_cast<PHINode>(IncI->getOperand(1));
|
|
|
|
if (Phi && Phi->getParent() == L->getHeader()) {
|
|
|
|
if (isLoopInvariant(IncI->getOperand(0), L, DT))
|
|
|
|
return Phi;
|
|
|
|
}
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-07-19 04:32:31 +08:00
|
|
|
}
|
|
|
|
|
2012-07-18 12:35:10 +08:00
|
|
|
/// Return the compare guarding the loop latch, or NULL for unrecognized tests.
|
|
|
|
static ICmpInst *getLoopTest(Loop *L) {
|
2011-07-19 04:32:31 +08:00
|
|
|
assert(L->getExitingBlock() && "expected loop exit");
|
|
|
|
|
|
|
|
BasicBlock *LatchBlock = L->getLoopLatch();
|
|
|
|
// Don't bother with LFTR if the loop is not properly simplified.
|
|
|
|
if (!LatchBlock)
|
2014-04-25 13:29:35 +08:00
|
|
|
return nullptr;
|
2011-07-19 04:32:31 +08:00
|
|
|
|
|
|
|
BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
|
|
|
|
assert(BI && "expected exit branch");
|
|
|
|
|
2012-07-18 12:35:10 +08:00
|
|
|
return dyn_cast<ICmpInst>(BI->getCondition());
|
|
|
|
}
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// LinearFunctionTestReplace policy. Return true unless we can show that the
|
|
|
|
/// current exit test is already sufficiently canonical.
|
2012-07-18 12:35:10 +08:00
|
|
|
static bool needsLFTR(Loop *L, DominatorTree *DT) {
|
2011-07-19 04:32:31 +08:00
|
|
|
// Do LFTR to simplify the exit condition to an ICMP.
|
2012-07-18 12:35:10 +08:00
|
|
|
ICmpInst *Cond = getLoopTest(L);
|
2011-07-19 04:32:31 +08:00
|
|
|
if (!Cond)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
// Do LFTR to simplify the exit ICMP to EQ/NE
|
|
|
|
ICmpInst::Predicate Pred = Cond->getPredicate();
|
|
|
|
if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
// Look for a loop invariant RHS
|
|
|
|
Value *LHS = Cond->getOperand(0);
|
|
|
|
Value *RHS = Cond->getOperand(1);
|
|
|
|
if (!isLoopInvariant(RHS, L, DT)) {
|
|
|
|
if (!isLoopInvariant(LHS, L, DT))
|
|
|
|
return true;
|
|
|
|
std::swap(LHS, RHS);
|
|
|
|
}
|
|
|
|
// Look for a simple IV counter LHS
|
|
|
|
PHINode *Phi = dyn_cast<PHINode>(LHS);
|
|
|
|
if (!Phi)
|
|
|
|
Phi = getLoopPhiForCounter(LHS, L, DT);
|
|
|
|
|
|
|
|
if (!Phi)
|
|
|
|
return true;
|
|
|
|
|
2012-10-05 03:08:30 +08:00
|
|
|
// Do LFTR if PHI node is defined in the loop, but is *not* a counter.
|
2012-10-04 07:59:47 +08:00
|
|
|
int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
|
|
|
|
if (Idx < 0)
|
|
|
|
return true;
|
2012-10-05 03:08:30 +08:00
|
|
|
|
|
|
|
// Do LFTR if the exit condition's IV is *not* a simple counter.
|
2012-10-04 07:59:47 +08:00
|
|
|
Value *IncV = Phi->getIncomingValue(Idx);
|
2011-07-19 04:32:31 +08:00
|
|
|
return Phi != getLoopPhiForCounter(IncV, L, DT);
|
|
|
|
}
|
|
|
|
|
2012-07-18 12:35:10 +08:00
|
|
|
/// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
|
|
|
|
/// down to checking that all operands are constant and listing instructions
|
|
|
|
/// that may hide undef.
|
2014-08-21 13:55:13 +08:00
|
|
|
static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited,
|
2012-07-18 12:35:10 +08:00
|
|
|
unsigned Depth) {
|
|
|
|
if (isa<Constant>(V))
|
|
|
|
return !isa<UndefValue>(V);
|
|
|
|
|
|
|
|
if (Depth >= 6)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Conservatively handle non-constant non-instructions. For example, Arguments
|
|
|
|
// may be undef.
|
|
|
|
Instruction *I = dyn_cast<Instruction>(V);
|
|
|
|
if (!I)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Load and return values may be undef.
|
|
|
|
if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Optimistically handle other instructions.
|
|
|
|
for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) {
|
2014-11-19 15:49:26 +08:00
|
|
|
if (!Visited.insert(*OI).second)
|
2012-07-18 12:35:10 +08:00
|
|
|
continue;
|
|
|
|
if (!hasConcreteDefImpl(*OI, Visited, Depth+1))
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return true if the given value is concrete. We must prove that undef can
|
|
|
|
/// never reach it.
|
|
|
|
///
|
|
|
|
/// TODO: If we decide that this is a good approach to checking for undef, we
|
|
|
|
/// may factor it into a common location.
|
|
|
|
static bool hasConcreteDef(Value *V) {
|
|
|
|
SmallPtrSet<Value*, 8> Visited;
|
|
|
|
Visited.insert(V);
|
|
|
|
return hasConcreteDefImpl(V, Visited, 0);
|
|
|
|
}
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Return true if this IV has any uses other than the (soon to be rewritten)
|
|
|
|
/// loop exit test.
|
2011-07-19 04:32:31 +08:00
|
|
|
static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
|
|
|
|
int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
|
|
|
|
Value *IncV = Phi->getIncomingValue(LatchIdx);
|
|
|
|
|
2014-03-09 11:16:01 +08:00
|
|
|
for (User *U : Phi->users())
|
|
|
|
if (U != Cond && U != IncV) return false;
|
2011-07-19 04:32:31 +08:00
|
|
|
|
2014-03-09 11:16:01 +08:00
|
|
|
for (User *U : IncV->users())
|
|
|
|
if (U != Cond && U != Phi) return false;
|
2011-07-19 04:32:31 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Find an affine IV in canonical form.
|
2011-07-19 04:32:31 +08:00
|
|
|
///
|
2011-11-03 01:19:57 +08:00
|
|
|
/// BECount may be an i8* pointer type. The pointer difference is already
|
|
|
|
/// valid count without scaling the address stride, so it remains a pointer
|
|
|
|
/// expression as far as SCEV is concerned.
|
|
|
|
///
|
2012-07-18 12:35:10 +08:00
|
|
|
/// Currently only valid for LFTR. See the comments on hasConcreteDef below.
|
|
|
|
///
|
2011-07-19 04:32:31 +08:00
|
|
|
/// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
|
|
|
|
///
|
|
|
|
/// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
|
|
|
|
/// This is difficult in general for SCEV because of potential overflow. But we
|
|
|
|
/// could at least handle constant BECounts.
|
2015-03-10 10:37:25 +08:00
|
|
|
static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount,
|
|
|
|
ScalarEvolution *SE, DominatorTree *DT) {
|
2011-07-19 04:32:31 +08:00
|
|
|
uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
|
|
|
|
|
|
|
|
Value *Cond =
|
|
|
|
cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
|
|
|
|
|
|
|
|
// Loop over all of the PHI nodes, looking for a simple counter.
|
2014-04-25 13:29:35 +08:00
|
|
|
PHINode *BestPhi = nullptr;
|
|
|
|
const SCEV *BestInit = nullptr;
|
2011-07-19 04:32:31 +08:00
|
|
|
BasicBlock *LatchBlock = L->getLoopLatch();
|
|
|
|
assert(LatchBlock && "needsLFTR should guarantee a loop latch");
|
|
|
|
|
|
|
|
for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
|
|
|
|
PHINode *Phi = cast<PHINode>(I);
|
|
|
|
if (!SE->isSCEVable(Phi->getType()))
|
|
|
|
continue;
|
|
|
|
|
2011-11-03 01:19:57 +08:00
|
|
|
// Avoid comparing an integer IV against a pointer Limit.
|
|
|
|
if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
|
|
|
|
continue;
|
|
|
|
|
2011-07-19 04:32:31 +08:00
|
|
|
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
|
|
|
|
if (!AR || AR->getLoop() != L || !AR->isAffine())
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// AR may be a pointer type, while BECount is an integer type.
|
|
|
|
// AR may be wider than BECount. With eq/ne tests overflow is immaterial.
|
|
|
|
// AR may not be a narrower type, or we may never exit.
|
|
|
|
uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
|
2015-03-10 10:37:25 +08:00
|
|
|
if (PhiWidth < BCWidth ||
|
|
|
|
!L->getHeader()->getModule()->getDataLayout().isLegalInteger(PhiWidth))
|
2011-07-19 04:32:31 +08:00
|
|
|
continue;
|
|
|
|
|
|
|
|
const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
|
|
|
|
if (!Step || !Step->isOne())
|
|
|
|
continue;
|
|
|
|
|
|
|
|
int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
|
|
|
|
Value *IncV = Phi->getIncomingValue(LatchIdx);
|
|
|
|
if (getLoopPhiForCounter(IncV, L, DT) != Phi)
|
|
|
|
continue;
|
|
|
|
|
2012-07-18 12:35:10 +08:00
|
|
|
// Avoid reusing a potentially undef value to compute other values that may
|
|
|
|
// have originally had a concrete definition.
|
|
|
|
if (!hasConcreteDef(Phi)) {
|
|
|
|
// We explicitly allow unknown phis as long as they are already used by
|
|
|
|
// the loop test. In this case we assume that performing LFTR could not
|
|
|
|
// increase the number of undef users.
|
|
|
|
if (ICmpInst *Cond = getLoopTest(L)) {
|
|
|
|
if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT)
|
|
|
|
&& Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2011-07-19 04:32:31 +08:00
|
|
|
const SCEV *Init = AR->getStart();
|
|
|
|
|
|
|
|
if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
|
|
|
|
// Don't force a live loop counter if another IV can be used.
|
|
|
|
if (AlmostDeadIV(Phi, LatchBlock, Cond))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// Prefer to count-from-zero. This is a more "canonical" counter form. It
|
|
|
|
// also prefers integer to pointer IVs.
|
|
|
|
if (BestInit->isZero() != Init->isZero()) {
|
|
|
|
if (BestInit->isZero())
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// If two IVs both count from zero or both count from nonzero then the
|
|
|
|
// narrower is likely a dead phi that has been widened. Use the wider phi
|
|
|
|
// to allow the other to be eliminated.
|
2012-07-18 12:35:13 +08:00
|
|
|
else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
|
2011-07-19 04:32:31 +08:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
BestPhi = Phi;
|
|
|
|
BestInit = Init;
|
|
|
|
}
|
|
|
|
return BestPhi;
|
|
|
|
}
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// Help LinearFunctionTestReplace by generating a value that holds the RHS of
|
|
|
|
/// the new loop test.
|
2011-11-03 01:19:57 +08:00
|
|
|
static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
|
2012-11-01 16:07:29 +08:00
|
|
|
SCEVExpander &Rewriter, ScalarEvolution *SE) {
|
2011-11-03 01:19:57 +08:00
|
|
|
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
|
|
|
|
assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
|
|
|
|
const SCEV *IVInit = AR->getStart();
|
|
|
|
|
|
|
|
// IVInit may be a pointer while IVCount is an integer when FindLoopCounter
|
|
|
|
// finds a valid pointer IV. Sign extend BECount in order to materialize a
|
|
|
|
// GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
|
|
|
|
// the existing GEPs whenever possible.
|
|
|
|
if (IndVar->getType()->isPointerTy()
|
|
|
|
&& !IVCount->getType()->isPointerTy()) {
|
|
|
|
|
2013-10-24 13:29:56 +08:00
|
|
|
// IVOffset will be the new GEP offset that is interpreted by GEP as a
|
|
|
|
// signed value. IVCount on the other hand represents the loop trip count,
|
|
|
|
// which is an unsigned value. FindLoopCounter only allows induction
|
|
|
|
// variables that have a positive unit stride of one. This means we don't
|
|
|
|
// have to handle the case of negative offsets (yet) and just need to zero
|
|
|
|
// extend IVCount.
|
2011-11-03 01:19:57 +08:00
|
|
|
Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
|
2013-10-24 13:29:56 +08:00
|
|
|
const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy);
|
2011-11-03 01:19:57 +08:00
|
|
|
|
|
|
|
// Expand the code for the iteration count.
|
|
|
|
assert(SE->isLoopInvariant(IVOffset, L) &&
|
|
|
|
"Computed iteration count is not loop invariant!");
|
|
|
|
BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
|
|
|
|
Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
|
|
|
|
|
|
|
|
Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
|
|
|
|
assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
|
|
|
|
// We could handle pointer IVs other than i8*, but we need to compensate for
|
|
|
|
// gep index scaling. See canExpandBackedgeTakenCount comments.
|
2013-09-11 03:55:24 +08:00
|
|
|
assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()),
|
2012-11-01 16:07:29 +08:00
|
|
|
cast<PointerType>(GEPBase->getType())->getElementType())->isOne()
|
2011-11-03 01:19:57 +08:00
|
|
|
&& "unit stride pointer IV must be i8*");
|
|
|
|
|
|
|
|
IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
|
2015-04-04 03:41:44 +08:00
|
|
|
return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit");
|
2011-11-03 01:19:57 +08:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
// In any other case, convert both IVInit and IVCount to integers before
|
|
|
|
// comparing. This may result in SCEV expension of pointers, but in practice
|
|
|
|
// SCEV will fold the pointer arithmetic away as such:
|
|
|
|
// BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
|
|
|
|
//
|
|
|
|
// Valid Cases: (1) both integers is most common; (2) both may be pointers
|
2013-10-24 08:43:38 +08:00
|
|
|
// for simple memset-style loops.
|
|
|
|
//
|
|
|
|
// IVInit integer and IVCount pointer would only occur if a canonical IV
|
|
|
|
// were generated on top of case #2, which is not expected.
|
2011-11-03 01:19:57 +08:00
|
|
|
|
2014-04-25 13:29:35 +08:00
|
|
|
const SCEV *IVLimit = nullptr;
|
2011-11-03 01:19:57 +08:00
|
|
|
// For unit stride, IVCount = Start + BECount with 2's complement overflow.
|
|
|
|
// For non-zero Start, compute IVCount here.
|
|
|
|
if (AR->getStart()->isZero())
|
|
|
|
IVLimit = IVCount;
|
|
|
|
else {
|
|
|
|
assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
|
|
|
|
const SCEV *IVInit = AR->getStart();
|
|
|
|
|
|
|
|
// For integer IVs, truncate the IV before computing IVInit + BECount.
|
|
|
|
if (SE->getTypeSizeInBits(IVInit->getType())
|
|
|
|
> SE->getTypeSizeInBits(IVCount->getType()))
|
|
|
|
IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
|
|
|
|
|
|
|
|
IVLimit = SE->getAddExpr(IVInit, IVCount);
|
|
|
|
}
|
|
|
|
// Expand the code for the iteration count.
|
|
|
|
BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
|
|
|
|
IRBuilder<> Builder(BI);
|
|
|
|
assert(SE->isLoopInvariant(IVLimit, L) &&
|
|
|
|
"Computed iteration count is not loop invariant!");
|
|
|
|
// Ensure that we generate the same type as IndVar, or a smaller integer
|
|
|
|
// type. In the presence of null pointer values, we have an integer type
|
|
|
|
// SCEV expression (IVInit) for a pointer type IV value (IndVar).
|
|
|
|
Type *LimitTy = IVCount->getType()->isPointerTy() ?
|
|
|
|
IndVar->getType() : IVCount->getType();
|
|
|
|
return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-09-20 14:58:03 +08:00
|
|
|
/// This method rewrites the exit condition of the loop to be a canonical !=
|
|
|
|
/// comparison against the incremented loop induction variable. This pass is
|
|
|
|
/// able to rewrite the exit tests of any loop where the SCEV analysis can
|
|
|
|
/// determine a loop-invariant trip count of the loop, which is actually a much
|
|
|
|
/// broader range than just linear tests.
|
2011-07-19 04:32:31 +08:00
|
|
|
Value *IndVarSimplify::
|
2011-07-12 08:08:50 +08:00
|
|
|
LinearFunctionTestReplace(Loop *L,
|
|
|
|
const SCEV *BackedgeTakenCount,
|
|
|
|
PHINode *IndVar,
|
|
|
|
SCEVExpander &Rewriter) {
|
2015-04-14 11:20:28 +08:00
|
|
|
assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition");
|
2011-07-12 08:08:50 +08:00
|
|
|
|
2013-07-13 06:08:44 +08:00
|
|
|
// Initialize CmpIndVar and IVCount to their preincremented values.
|
|
|
|
Value *CmpIndVar = IndVar;
|
|
|
|
const SCEV *IVCount = BackedgeTakenCount;
|
2011-07-19 04:32:31 +08:00
|
|
|
|
2011-11-03 01:19:57 +08:00
|
|
|
// If the exiting block is the same as the backedge block, we prefer to
|
|
|
|
// compare against the post-incremented value, otherwise we must compare
|
|
|
|
// against the preincremented value.
|
2011-07-12 08:08:50 +08:00
|
|
|
if (L->getExitingBlock() == L->getLoopLatch()) {
|
2015-03-03 05:41:07 +08:00
|
|
|
// Add one to the "backedge-taken" count to get the trip count.
|
|
|
|
// This addition may overflow, which is valid as long as the comparison is
|
|
|
|
// truncated to BackedgeTakenCount->getType().
|
|
|
|
IVCount = SE->getAddExpr(BackedgeTakenCount,
|
|
|
|
SE->getConstant(BackedgeTakenCount->getType(), 1));
|
2011-07-12 08:08:50 +08:00
|
|
|
// The BackedgeTaken expression contains the number of times that the
|
|
|
|
// backedge branches to the loop header. This is one less than the
|
|
|
|
// number of times the loop executes, so use the incremented indvar.
|
2015-03-03 05:41:07 +08:00
|
|
|
CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
|
2011-07-12 08:08:50 +08:00
|
|
|
}
|
|
|
|
|
2012-11-01 16:07:29 +08:00
|
|
|
Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
|
2011-11-03 01:19:57 +08:00
|
|
|
assert(ExitCnt->getType()->isPointerTy() == IndVar->getType()->isPointerTy()
|
|
|
|
&& "genLoopLimit missed a cast");
|
2011-07-12 08:08:50 +08:00
|
|
|
|
|
|
|
// Insert a new icmp_ne or icmp_eq instruction before the branch.
|
2011-11-03 01:19:57 +08:00
|
|
|
BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
|
2011-07-19 04:32:31 +08:00
|
|
|
ICmpInst::Predicate P;
|
2011-07-12 08:08:50 +08:00
|
|
|
if (L->contains(BI->getSuccessor(0)))
|
2011-07-19 04:32:31 +08:00
|
|
|
P = ICmpInst::ICMP_NE;
|
2011-07-12 08:08:50 +08:00
|
|
|
else
|
2011-07-19 04:32:31 +08:00
|
|
|
P = ICmpInst::ICMP_EQ;
|
2011-07-12 08:08:50 +08:00
|
|
|
|
|
|
|
DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
|
|
|
|
<< " LHS:" << *CmpIndVar << '\n'
|
|
|
|
<< " op:\t"
|
2011-07-19 04:32:31 +08:00
|
|
|
<< (P == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
|
|
|
|
<< " RHS:\t" << *ExitCnt << "\n"
|
2011-11-03 01:19:57 +08:00
|
|
|
<< " IVCount:\t" << *IVCount << "\n");
|
2011-07-12 08:08:50 +08:00
|
|
|
|
2013-07-13 06:08:48 +08:00
|
|
|
IRBuilder<> Builder(BI);
|
|
|
|
|
2013-07-13 06:08:44 +08:00
|
|
|
// LFTR can ignore IV overflow and truncate to the width of
|
|
|
|
// BECount. This avoids materializing the add(zext(add)) expression.
|
2013-07-13 06:08:48 +08:00
|
|
|
unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
|
|
|
|
unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
|
|
|
|
if (CmpIndVarSize > ExitCntSize) {
|
|
|
|
const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
|
|
|
|
const SCEV *ARStart = AR->getStart();
|
|
|
|
const SCEV *ARStep = AR->getStepRecurrence(*SE);
|
|
|
|
// For constant IVCount, avoid truncation.
|
|
|
|
if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
|
|
|
|
const APInt &Start = cast<SCEVConstant>(ARStart)->getValue()->getValue();
|
|
|
|
APInt Count = cast<SCEVConstant>(IVCount)->getValue()->getValue();
|
|
|
|
// Note that the post-inc value of BackedgeTakenCount may have overflowed
|
|
|
|
// above such that IVCount is now zero.
|
|
|
|
if (IVCount != BackedgeTakenCount && Count == 0) {
|
|
|
|
Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize);
|
|
|
|
++Count;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
Count = Count.zext(CmpIndVarSize);
|
|
|
|
APInt NewLimit;
|
|
|
|
if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
|
|
|
|
NewLimit = Start - Count;
|
|
|
|
else
|
|
|
|
NewLimit = Start + Count;
|
|
|
|
ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit);
|
|
|
|
|
|
|
|
DEBUG(dbgs() << " Widen RHS:\t" << *ExitCnt << "\n");
|
|
|
|
} else {
|
|
|
|
CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
|
|
|
|
"lftr.wideiv");
|
|
|
|
}
|
2011-07-19 04:32:31 +08:00
|
|
|
}
|
|
|
|
Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
|
2011-07-12 08:08:50 +08:00
|
|
|
Value *OrigCond = BI->getCondition();
|
|
|
|
// It's tempting to use replaceAllUsesWith here to fully replace the old
|
|
|
|
// comparison, but that's not immediately safe, since users of the old
|
|
|
|
// comparison may not be dominated by the new comparison. Instead, just
|
|
|
|
// update the branch to use the new comparison; in the common case this
|
|
|
|
// will make old comparison dead.
|
|
|
|
BI->setCondition(Cond);
|
|
|
|
DeadInsts.push_back(OrigCond);
|
|
|
|
|
|
|
|
++NumLFTR;
|
|
|
|
Changed = true;
|
|
|
|
return Cond;
|
|
|
|
}
|
|
|
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// SinkUnusedInvariants. A late subpass to cleanup loop preheaders.
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
/// If there's a single exit block, sink any loop-invariant values that
|
|
|
|
/// were defined in the preheader but not used inside the loop into the
|
|
|
|
/// exit block to reduce register pressure in the loop.
|
|
|
|
void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
|
|
|
|
BasicBlock *ExitBlock = L->getExitBlock();
|
|
|
|
if (!ExitBlock) return;
|
|
|
|
|
|
|
|
BasicBlock *Preheader = L->getLoopPreheader();
|
|
|
|
if (!Preheader) return;
|
|
|
|
|
2011-08-25 04:28:43 +08:00
|
|
|
Instruction *InsertPt = ExitBlock->getFirstInsertionPt();
|
2011-07-12 08:08:50 +08:00
|
|
|
BasicBlock::iterator I = Preheader->getTerminator();
|
|
|
|
while (I != Preheader->begin()) {
|
|
|
|
--I;
|
|
|
|
// New instructions were inserted at the end of the preheader.
|
|
|
|
if (isa<PHINode>(I))
|
|
|
|
break;
|
|
|
|
|
|
|
|
// Don't move instructions which might have side effects, since the side
|
|
|
|
// effects need to complete before instructions inside the loop. Also don't
|
|
|
|
// move instructions which might read memory, since the loop may modify
|
|
|
|
// memory. Note that it's okay if the instruction might have undefined
|
|
|
|
// behavior: LoopSimplify guarantees that the preheader dominates the exit
|
|
|
|
// block.
|
|
|
|
if (I->mayHaveSideEffects() || I->mayReadFromMemory())
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// Skip debug info intrinsics.
|
|
|
|
if (isa<DbgInfoIntrinsic>(I))
|
|
|
|
continue;
|
|
|
|
|
2015-08-20 03:54:02 +08:00
|
|
|
// Skip eh pad instructions.
|
|
|
|
if (I->isEHPad())
|
2011-08-27 04:40:15 +08:00
|
|
|
continue;
|
|
|
|
|
2011-10-27 09:33:51 +08:00
|
|
|
// Don't sink alloca: we never want to sink static alloca's out of the
|
|
|
|
// entry block, and correctly sinking dynamic alloca's requires
|
|
|
|
// checks for stacksave/stackrestore intrinsics.
|
|
|
|
// FIXME: Refactor this check somehow?
|
|
|
|
if (isa<AllocaInst>(I))
|
|
|
|
continue;
|
2011-07-12 08:08:50 +08:00
|
|
|
|
|
|
|
// Determine if there is a use in or before the loop (direct or
|
|
|
|
// otherwise).
|
|
|
|
bool UsedInLoop = false;
|
2014-03-09 11:16:01 +08:00
|
|
|
for (Use &U : I->uses()) {
|
|
|
|
Instruction *User = cast<Instruction>(U.getUser());
|
|
|
|
BasicBlock *UseBB = User->getParent();
|
|
|
|
if (PHINode *P = dyn_cast<PHINode>(User)) {
|
2011-07-12 08:08:50 +08:00
|
|
|
unsigned i =
|
2014-03-09 11:16:01 +08:00
|
|
|
PHINode::getIncomingValueNumForOperand(U.getOperandNo());
|
2011-07-12 08:08:50 +08:00
|
|
|
UseBB = P->getIncomingBlock(i);
|
|
|
|
}
|
|
|
|
if (UseBB == Preheader || L->contains(UseBB)) {
|
|
|
|
UsedInLoop = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If there is, the def must remain in the preheader.
|
|
|
|
if (UsedInLoop)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// Otherwise, sink it to the exit block.
|
|
|
|
Instruction *ToMove = I;
|
|
|
|
bool Done = false;
|
|
|
|
|
|
|
|
if (I != Preheader->begin()) {
|
|
|
|
// Skip debug info intrinsics.
|
|
|
|
do {
|
|
|
|
--I;
|
|
|
|
} while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
|
|
|
|
|
|
|
|
if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
|
|
|
|
Done = true;
|
|
|
|
} else {
|
|
|
|
Done = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
ToMove->moveBefore(InsertPt);
|
|
|
|
if (Done) break;
|
|
|
|
InsertPt = ToMove;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// IndVarSimplify driver. Manage several subpasses of IV simplification.
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
|
2014-02-06 08:07:05 +08:00
|
|
|
if (skipOptnoneFunction(L))
|
|
|
|
return false;
|
|
|
|
|
2011-07-12 08:08:50 +08:00
|
|
|
// If LoopSimplify form is not available, stay out of trouble. Some notes:
|
|
|
|
// - LSR currently only supports LoopSimplify-form loops. Indvars'
|
|
|
|
// canonicalization can be a pessimization without LSR to "clean up"
|
|
|
|
// afterwards.
|
|
|
|
// - We depend on having a preheader; in particular,
|
|
|
|
// Loop::getCanonicalInductionVariable only supports loops with preheaders,
|
|
|
|
// and we're in trouble if we can't find the induction variable even when
|
|
|
|
// we've manually inserted one.
|
|
|
|
if (!L->isLoopSimplifyForm())
|
|
|
|
return false;
|
|
|
|
|
2015-01-17 22:16:18 +08:00
|
|
|
LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
|
[PM] Port ScalarEvolution to the new pass manager.
This change makes ScalarEvolution a stand-alone object and just produces
one from a pass as needed. Making this work well requires making the
object movable, using references instead of overwritten pointers in
a number of places, and other refactorings.
I've also wired it up to the new pass manager and added a RUN line to
a test to exercise it under the new pass manager. This includes basic
printing support much like with other analyses.
But there is a big and somewhat scary change here. Prior to this patch
ScalarEvolution was never *actually* invalidated!!! Re-running the pass
just re-wired up the various other analyses and didn't remove any of the
existing entries in the SCEV caches or clear out anything at all. This
might seem OK as everything in SCEV that can uses ValueHandles to track
updates to the values that serve as SCEV keys. However, this still means
that as we ran SCEV over each function in the module, we kept
accumulating more and more SCEVs into the cache. At the end, we would
have a SCEV cache with every value that we ever needed a SCEV for in the
entire module!!! Yowzers. The releaseMemory routine would dump all of
this, but that isn't realy called during normal runs of the pipeline as
far as I can see.
To make matters worse, there *is* actually a key that we don't update
with value handles -- there is a map keyed off of Loop*s. Because
LoopInfo *does* release its memory from run to run, it is entirely
possible to run SCEV over one function, then over another function, and
then lookup a Loop* from the second function but find an entry inserted
for the first function! Ouch.
To make matters still worse, there are plenty of updates that *don't*
trip a value handle. It seems incredibly unlikely that today GVN or
another pass that invalidates SCEV can update values in *just* such
a way that a subsequent run of SCEV will incorrectly find lookups in
a cache, but it is theoretically possible and would be a nightmare to
debug.
With this refactoring, I've fixed all this by actually destroying and
recreating the ScalarEvolution object from run to run. Technically, this
could increase the amount of malloc traffic we see, but then again it is
also technically correct. ;] I don't actually think we're suffering from
tons of malloc traffic from SCEV because if we were, the fact that we
never clear the memory would seem more likely to have come up as an
actual problem before now. So, I've made the simple fix here. If in fact
there are serious issues with too much allocation and deallocation,
I can work on a clever fix that preserves the allocations (while
clearing the data) between each run, but I'd prefer to do that kind of
optimization with a test case / benchmark that shows why we need such
cleverness (and that can test that we actually make it faster). It's
possible that this will make some things faster by making the SCEV
caches have higher locality (due to being significantly smaller) so
until there is a clear benchmark, I think the simple change is best.
Differential Revision: http://reviews.llvm.org/D12063
llvm-svn: 245193
2015-08-17 10:08:17 +08:00
|
|
|
SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
|
2014-01-13 21:07:17 +08:00
|
|
|
DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
|
2015-01-15 18:41:28 +08:00
|
|
|
auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
|
|
|
|
TLI = TLIP ? &TLIP->getTLI() : nullptr;
|
[PM] Change the core design of the TTI analysis to use a polymorphic
type erased interface and a single analysis pass rather than an
extremely complex analysis group.
The end result is that the TTI analysis can contain a type erased
implementation that supports the polymorphic TTI interface. We can build
one from a target-specific implementation or from a dummy one in the IR.
I've also factored all of the code into "mix-in"-able base classes,
including CRTP base classes to facilitate calling back up to the most
specialized form when delegating horizontally across the surface. These
aren't as clean as I would like and I'm planning to work on cleaning
some of this up, but I wanted to start by putting into the right form.
There are a number of reasons for this change, and this particular
design. The first and foremost reason is that an analysis group is
complete overkill, and the chaining delegation strategy was so opaque,
confusing, and high overhead that TTI was suffering greatly for it.
Several of the TTI functions had failed to be implemented in all places
because of the chaining-based delegation making there be no checking of
this. A few other functions were implemented with incorrect delegation.
The message to me was very clear working on this -- the delegation and
analysis group structure was too confusing to be useful here.
The other reason of course is that this is *much* more natural fit for
the new pass manager. This will lay the ground work for a type-erased
per-function info object that can look up the correct subtarget and even
cache it.
Yet another benefit is that this will significantly simplify the
interaction of the pass managers and the TargetMachine. See the future
work below.
The downside of this change is that it is very, very verbose. I'm going
to work to improve that, but it is somewhat an implementation necessity
in C++ to do type erasure. =/ I discussed this design really extensively
with Eric and Hal prior to going down this path, and afterward showed
them the result. No one was really thrilled with it, but there doesn't
seem to be a substantially better alternative. Using a base class and
virtual method dispatch would make the code much shorter, but as
discussed in the update to the programmer's manual and elsewhere,
a polymorphic interface feels like the more principled approach even if
this is perhaps the least compelling example of it. ;]
Ultimately, there is still a lot more to be done here, but this was the
huge chunk that I couldn't really split things out of because this was
the interface change to TTI. I've tried to minimize all the other parts
of this. The follow up work should include at least:
1) Improving the TargetMachine interface by having it directly return
a TTI object. Because we have a non-pass object with value semantics
and an internal type erasure mechanism, we can narrow the interface
of the TargetMachine to *just* do what we need: build and return
a TTI object that we can then insert into the pass pipeline.
2) Make the TTI object be fully specialized for a particular function.
This will include splitting off a minimal form of it which is
sufficient for the inliner and the old pass manager.
3) Add a new pass manager analysis which produces TTI objects from the
target machine for each function. This may actually be done as part
of #2 in order to use the new analysis to implement #2.
4) Work on narrowing the API between TTI and the targets so that it is
easier to understand and less verbose to type erase.
5) Work on narrowing the API between TTI and its clients so that it is
easier to understand and less verbose to forward.
6) Try to improve the CRTP-based delegation. I feel like this code is
just a bit messy and exacerbating the complexity of implementing
the TTI in each target.
Many thanks to Eric and Hal for their help here. I ended up blocked on
this somewhat more abruptly than I expected, and so I appreciate getting
it sorted out very quickly.
Differential Revision: http://reviews.llvm.org/D7293
llvm-svn: 227669
2015-01-31 11:43:40 +08:00
|
|
|
auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
|
2015-02-01 20:01:35 +08:00
|
|
|
TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr;
|
2015-03-10 10:37:25 +08:00
|
|
|
const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
|
2011-07-12 08:08:50 +08:00
|
|
|
|
|
|
|
DeadInsts.clear();
|
|
|
|
Changed = false;
|
|
|
|
|
|
|
|
// If there are any floating-point recurrences, attempt to
|
|
|
|
// transform them to use integer recurrences.
|
|
|
|
RewriteNonIntegerIVs(L);
|
|
|
|
|
|
|
|
const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
|
|
|
|
|
|
|
|
// Create a rewriter object which we'll use to transform the code with.
|
2015-03-10 10:37:25 +08:00
|
|
|
SCEVExpander Rewriter(*SE, DL, "indvars");
|
2011-10-11 10:28:51 +08:00
|
|
|
#ifndef NDEBUG
|
|
|
|
Rewriter.setDebugType(DEBUG_TYPE);
|
|
|
|
#endif
|
2011-07-12 08:08:50 +08:00
|
|
|
|
|
|
|
// Eliminate redundant IV users.
|
|
|
|
//
|
|
|
|
// Simplification works best when run before other consumers of SCEV. We
|
|
|
|
// attempt to avoid evaluating SCEVs for sign/zero extend operations until
|
|
|
|
// other expressions involving loop IVs have been evaluated. This helps SCEV
|
|
|
|
// set no-wrap flags before normalizing sign/zero extension.
|
2012-03-23 01:10:11 +08:00
|
|
|
Rewriter.disableCanonicalMode();
|
|
|
|
SimplifyAndExtend(L, Rewriter, LPM);
|
2011-07-12 08:08:50 +08:00
|
|
|
|
|
|
|
// Check to see if this loop has a computable loop-invariant execution count.
|
|
|
|
// If so, this means that we can compute the final value of any expressions
|
|
|
|
// that are recurrent in the loop, and substitute the exit values from the
|
|
|
|
// loop into any instructions outside of the loop that use the final values of
|
|
|
|
// the current expressions.
|
|
|
|
//
|
2015-05-29 05:49:07 +08:00
|
|
|
if (ReplaceExitValue != NeverRepl &&
|
|
|
|
!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
|
2011-07-12 08:08:50 +08:00
|
|
|
RewriteLoopExitValues(L, Rewriter);
|
|
|
|
|
2011-07-16 09:06:48 +08:00
|
|
|
// Eliminate redundant IV cycles.
|
2012-03-23 01:10:11 +08:00
|
|
|
NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
|
2011-07-07 04:50:43 +08:00
|
|
|
|
2009-02-13 06:19:27 +08:00
|
|
|
// If we have a trip count expression, rewrite the loop's exit condition
|
|
|
|
// using it. We can currently only handle loops with a single exit.
|
2015-04-14 11:20:28 +08:00
|
|
|
if (canExpandBackedgeTakenCount(L, SE, Rewriter) && needsLFTR(L, DT)) {
|
2015-03-10 10:37:25 +08:00
|
|
|
PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT);
|
2012-03-24 08:51:17 +08:00
|
|
|
if (IndVar) {
|
|
|
|
// Check preconditions for proper SCEVExpander operation. SCEV does not
|
|
|
|
// express SCEVExpander's dependencies, such as LoopSimplify. Instead any
|
|
|
|
// pass that uses the SCEVExpander must do it. This does not work well for
|
2014-01-07 09:02:52 +08:00
|
|
|
// loop passes because SCEVExpander makes assumptions about all loops,
|
|
|
|
// while LoopPassManager only forces the current loop to be simplified.
|
2012-03-24 08:51:17 +08:00
|
|
|
//
|
|
|
|
// FIXME: SCEV expansion has no way to bail out, so the caller must
|
|
|
|
// explicitly check any assumptions made by SCEV. Brittle.
|
|
|
|
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
|
|
|
|
if (!AR || AR->getLoop()->getLoopPreheader())
|
|
|
|
(void)LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
|
|
|
|
Rewriter);
|
|
|
|
}
|
2009-05-12 10:17:14 +08:00
|
|
|
}
|
2011-03-18 07:51:11 +08:00
|
|
|
// Clear the rewriter cache, because values that are in the rewriter's cache
|
|
|
|
// can be deleted in the loop below, causing the AssertingVH in the cache to
|
|
|
|
// trigger.
|
|
|
|
Rewriter.clear();
|
|
|
|
|
|
|
|
// Now that we're done iterating through lists, clean up any instructions
|
|
|
|
// which are now dead.
|
2015-06-25 06:23:21 +08:00
|
|
|
while (!DeadInsts.empty())
|
|
|
|
if (Instruction *Inst =
|
|
|
|
dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
|
2012-08-29 23:32:21 +08:00
|
|
|
RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
|
2011-03-18 07:51:11 +08:00
|
|
|
|
2009-06-27 06:53:46 +08:00
|
|
|
// The Rewriter may not be used from this point on.
|
2009-05-25 04:08:21 +08:00
|
|
|
|
2009-05-12 10:17:14 +08:00
|
|
|
// Loop-invariant instructions in the preheader that aren't used in the
|
|
|
|
// loop may be sunk below the loop to reduce register pressure.
|
2009-06-27 06:53:46 +08:00
|
|
|
SinkUnusedInvariants(L);
|
2009-05-12 10:17:14 +08:00
|
|
|
|
|
|
|
// Clean up dead instructions.
|
2012-08-29 23:32:21 +08:00
|
|
|
Changed |= DeleteDeadPHIs(L->getHeader(), TLI);
|
2009-05-12 10:17:14 +08:00
|
|
|
// Check a post-condition.
|
2011-07-19 02:44:20 +08:00
|
|
|
assert(L->isLCSSAForm(*DT) &&
|
|
|
|
"Indvars did not leave the loop in lcssa form!");
|
|
|
|
|
|
|
|
// Verify that LFTR, and any other change have not interfered with SCEV's
|
|
|
|
// ability to compute trip count.
|
|
|
|
#ifndef NDEBUG
|
2012-03-23 01:10:11 +08:00
|
|
|
if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
|
2011-07-19 02:44:20 +08:00
|
|
|
SE->forgetLoop(L);
|
|
|
|
const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
|
|
|
|
if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
|
|
|
|
SE->getTypeSizeInBits(NewBECount->getType()))
|
|
|
|
NewBECount = SE->getTruncateOrNoop(NewBECount,
|
|
|
|
BackedgeTakenCount->getType());
|
|
|
|
else
|
|
|
|
BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
|
|
|
|
NewBECount->getType());
|
|
|
|
assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
2009-05-12 10:17:14 +08:00
|
|
|
return Changed;
|
|
|
|
}
|