2002-05-11 06:44:58 +08:00
|
|
|
//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
|
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
|
|
|
//===----------------------------------------------------------------------===//
|
2002-05-11 06:44:58 +08:00
|
|
|
//
|
2003-12-10 01:18:00 +08:00
|
|
|
// This pass performs loop invariant code motion, attempting to remove as much
|
|
|
|
// code from the body of a loop as possible. It does this by either hoisting
|
|
|
|
// code into the preheader block, or by sinking code to the exit blocks if it is
|
|
|
|
// safe. This pass also promotes must-aliased memory locations in the loop to
|
2003-12-19 15:22:45 +08:00
|
|
|
// live in registers, thus hoisting and sinking "invariant" loads and stores.
|
2003-12-10 01:18:00 +08:00
|
|
|
//
|
|
|
|
// This pass uses alias analysis for two purposes:
|
2003-02-24 11:52:32 +08:00
|
|
|
//
|
2004-05-24 05:20:19 +08:00
|
|
|
// 1. Moving loop invariant loads and calls out of loops. If we can determine
|
|
|
|
// that a load or call inside of a loop never aliases anything stored to,
|
|
|
|
// we can hoist it or sink it like any other instruction.
|
2003-02-24 11:52:32 +08:00
|
|
|
// 2. Scalar Promotion of Memory - If there is a store instruction inside of
|
|
|
|
// the loop, we try to move the store to happen AFTER the loop instead of
|
|
|
|
// inside of the loop. This can only happen if a few conditions are true:
|
|
|
|
// A. The pointer stored through is loop invariant
|
|
|
|
// B. There are no stores or loads in the loop which _may_ alias the
|
|
|
|
// pointer. There are no calls in the loop which mod/ref the pointer.
|
|
|
|
// If these conditions are true, we can promote the loads and stores in the
|
|
|
|
// loop of the pointer to use a temporary alloca'd variable. We then use
|
2010-08-29 14:43:52 +08:00
|
|
|
// the SSAUpdater to construct the appropriate SSA form for the value.
|
2002-05-11 06:44:58 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2016-07-13 06:37:48 +08:00
|
|
|
#include "llvm/Transforms/Scalar/LICM.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/ADT/Statistic.h"
|
2002-08-23 05:39:55 +08:00
|
|
|
#include "llvm/Analysis/AliasAnalysis.h"
|
2003-03-04 07:32:45 +08:00
|
|
|
#include "llvm/Analysis/AliasSetTracker.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/BasicAliasAnalysis.h"
|
2016-03-10 06:59:30 +08:00
|
|
|
#include "llvm/Analysis/CaptureTracking.h"
|
2010-09-01 07:00:16 +08:00
|
|
|
#include "llvm/Analysis/ConstantFolding.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/GlobalsModRef.h"
|
2016-03-10 07:07:53 +08:00
|
|
|
#include "llvm/Analysis/Loads.h"
|
2010-09-01 07:00:16 +08:00
|
|
|
#include "llvm/Analysis/LoopInfo.h"
|
|
|
|
#include "llvm/Analysis/LoopPass.h"
|
2016-07-13 06:37:48 +08:00
|
|
|
#include "llvm/Analysis/LoopPassManager.h"
|
2016-03-10 06:59:30 +08:00
|
|
|
#include "llvm/Analysis/MemoryBuiltins.h"
|
2014-01-24 09:59:49 +08:00
|
|
|
#include "llvm/Analysis/ScalarEvolution.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"
|
2011-12-15 07:49:11 +08:00
|
|
|
#include "llvm/Analysis/ValueTracking.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"
|
|
|
|
#include "llvm/IR/DerivedTypes.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"
|
2013-01-06 00:44:07 +08:00
|
|
|
#include "llvm/IR/Metadata.h"
|
2014-03-04 20:09:19 +08:00
|
|
|
#include "llvm/IR/PredIteratorCache.h"
|
2004-09-02 06:55:40 +08:00
|
|
|
#include "llvm/Support/CommandLine.h"
|
|
|
|
#include "llvm/Support/Debug.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/Support/raw_ostream.h"
|
2016-05-05 08:54:54 +08:00
|
|
|
#include "llvm/Transforms/Scalar.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/Transforms/Utils/Local.h"
|
2014-01-25 12:07:24 +08:00
|
|
|
#include "llvm/Transforms/Utils/LoopUtils.h"
|
2012-12-04 00:50:05 +08:00
|
|
|
#include "llvm/Transforms/Utils/SSAUpdater.h"
|
2002-05-11 06:44:58 +08:00
|
|
|
#include <algorithm>
|
2016-05-27 22:27:24 +08:00
|
|
|
#include <utility>
|
2003-12-10 01:18:00 +08:00
|
|
|
using namespace llvm;
|
2003-11-12 06:41:34 +08:00
|
|
|
|
2014-04-22 10:55:47 +08:00
|
|
|
#define DEBUG_TYPE "licm"
|
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
STATISTIC(NumSunk, "Number of instructions sunk out of loop");
|
|
|
|
STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
|
2006-12-20 05:40:18 +08:00
|
|
|
STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
|
|
|
|
STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
|
2016-05-05 08:54:54 +08:00
|
|
|
STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
|
2006-12-20 05:40:18 +08:00
|
|
|
|
2008-05-13 08:00:25 +08:00
|
|
|
static cl::opt<bool>
|
2016-05-05 08:54:54 +08:00
|
|
|
DisablePromotion("disable-licm-promotion", cl::Hidden,
|
|
|
|
cl::desc("Disable memory promotion in LICM pass"));
|
2003-02-24 11:52:32 +08:00
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
|
2016-01-04 11:37:39 +08:00
|
|
|
static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
|
2016-06-11 04:03:17 +08:00
|
|
|
const LoopSafetyInfo *SafetyInfo);
|
2016-01-28 23:51:58 +08:00
|
|
|
static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
|
2016-06-11 04:03:17 +08:00
|
|
|
const LoopSafetyInfo *SafetyInfo);
|
2015-05-13 09:12:18 +08:00
|
|
|
static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
|
2016-01-04 11:37:39 +08:00
|
|
|
const Loop *CurLoop, AliasSetTracker *CurAST,
|
2016-06-11 04:03:17 +08:00
|
|
|
const LoopSafetyInfo *SafetyInfo);
|
2015-05-13 09:12:18 +08:00
|
|
|
static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
|
|
|
|
const DominatorTree *DT,
|
|
|
|
const Loop *CurLoop,
|
2016-06-11 04:03:17 +08:00
|
|
|
const LoopSafetyInfo *SafetyInfo,
|
2015-05-22 10:14:05 +08:00
|
|
|
const Instruction *CtxI = nullptr);
|
2015-02-23 02:35:32 +08:00
|
|
|
static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
|
2016-05-05 08:54:54 +08:00
|
|
|
const AAMDNodes &AAInfo,
|
2015-02-23 02:35:32 +08:00
|
|
|
AliasSetTracker *CurAST);
|
2016-01-04 11:37:39 +08:00
|
|
|
static Instruction *
|
|
|
|
CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
|
|
|
|
const LoopInfo *LI,
|
2016-06-11 04:03:17 +08:00
|
|
|
const LoopSafetyInfo *SafetyInfo);
|
2015-03-10 10:37:25 +08:00
|
|
|
static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
|
2015-05-19 02:07:00 +08:00
|
|
|
DominatorTree *DT, TargetLibraryInfo *TLI,
|
|
|
|
Loop *CurLoop, AliasSetTracker *CurAST,
|
2016-06-11 04:03:17 +08:00
|
|
|
LoopSafetyInfo *SafetyInfo);
|
2015-02-23 02:35:32 +08:00
|
|
|
|
2008-05-13 08:00:25 +08:00
|
|
|
namespace {
|
2016-07-13 06:37:48 +08:00
|
|
|
struct LoopInvariantCodeMotion {
|
|
|
|
bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
|
|
|
|
TargetLibraryInfo *TLI, ScalarEvolution *SE, bool DeleteAST);
|
|
|
|
|
|
|
|
DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
|
|
|
|
return LoopToAliasSetMap;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
|
|
|
|
|
|
|
|
AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
|
|
|
|
AliasAnalysis *AA);
|
|
|
|
};
|
|
|
|
|
|
|
|
struct LegacyLICMPass : public LoopPass {
|
2016-05-05 08:54:54 +08:00
|
|
|
static char ID; // Pass identification, replacement for typeid
|
2016-07-13 06:37:48 +08:00
|
|
|
LegacyLICMPass() : LoopPass(ID) {
|
|
|
|
initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
|
2016-05-05 08:54:54 +08:00
|
|
|
}
|
2007-05-02 05:15:47 +08:00
|
|
|
|
2016-07-13 06:37:48 +08:00
|
|
|
bool runOnLoop(Loop *L, LPPassManager &LPM) override {
|
|
|
|
if (skipLoop(L))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
|
|
|
|
return LICM.runOnLoop(L,
|
|
|
|
&getAnalysis<AAResultsWrapperPass>().getAAResults(),
|
|
|
|
&getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
|
|
|
|
&getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
|
|
|
|
&getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
|
|
|
|
SE ? &SE->getSE() : nullptr, false);
|
|
|
|
}
|
2002-05-11 06:44:58 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
/// This transformation requires natural loop information & requires that
|
|
|
|
/// loop preheaders be inserted into the CFG...
|
|
|
|
///
|
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override {
|
|
|
|
AU.setPreservesCFG();
|
|
|
|
AU.addRequired<TargetLibraryInfoWrapperPass>();
|
|
|
|
getLoopAnalysisUsage(AU);
|
|
|
|
}
|
2002-05-11 06:44:58 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
using llvm::Pass::doFinalization;
|
2012-12-04 13:41:27 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
bool doFinalization() override {
|
2016-07-13 06:37:48 +08:00
|
|
|
assert(LICM.getLoopToAliasSetMap().empty() &&
|
|
|
|
"Didn't free loop alias sets");
|
2016-05-05 08:54:54 +08:00
|
|
|
return false;
|
|
|
|
}
|
2007-03-07 12:41:30 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
private:
|
2016-07-13 06:37:48 +08:00
|
|
|
LoopInvariantCodeMotion LICM;
|
2002-05-11 06:44:58 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
|
|
|
|
void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
|
|
|
|
Loop *L) override;
|
2007-07-31 16:01:41 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
|
|
|
|
/// set.
|
|
|
|
void deleteAnalysisValue(Value *V, Loop *L) override;
|
2007-07-31 16:01:41 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
/// Simple Analysis hook. Delete loop L from alias set map.
|
|
|
|
void deleteAnalysisLoop(Loop *L) override;
|
2016-07-12 14:25:32 +08:00
|
|
|
};
|
2016-07-12 06:45:24 +08:00
|
|
|
}
|
|
|
|
|
2016-07-13 06:37:48 +08:00
|
|
|
PreservedAnalyses LICMPass::run(Loop &L, AnalysisManager<Loop> &AM) {
|
|
|
|
const auto &FAM =
|
|
|
|
AM.getResult<FunctionAnalysisManagerLoopProxy>(L).getManager();
|
|
|
|
Function *F = L.getHeader()->getParent();
|
|
|
|
|
|
|
|
auto *AA = FAM.getCachedResult<AAManager>(*F);
|
|
|
|
auto *LI = FAM.getCachedResult<LoopAnalysis>(*F);
|
|
|
|
auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(*F);
|
|
|
|
auto *TLI = FAM.getCachedResult<TargetLibraryAnalysis>(*F);
|
|
|
|
auto *SE = FAM.getCachedResult<ScalarEvolutionAnalysis>(*F);
|
|
|
|
assert((AA && LI && DT && TLI && SE) && "Analyses for LICM not available");
|
|
|
|
|
|
|
|
LoopInvariantCodeMotion LICM;
|
|
|
|
|
|
|
|
if (!LICM.runOnLoop(&L, AA, LI, DT, TLI, SE, true))
|
|
|
|
return PreservedAnalyses::all();
|
|
|
|
|
|
|
|
// FIXME: There is no setPreservesCFG in the new PM. When that becomes
|
|
|
|
// available, it should be used here.
|
|
|
|
return getLoopPassPreservedAnalyses();
|
|
|
|
}
|
|
|
|
|
|
|
|
char LegacyLICMPass::ID = 0;
|
|
|
|
INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
|
|
|
|
false, false)
|
[LPM] Factor all of the loop analysis usage updates into a common helper
routine.
We were getting this wrong in small ways and generally being very
inconsistent about it across loop passes. Instead, let's have a common
place where we do this. One minor downside is that this will require
some analyses like SCEV in more places than they are strictly needed.
However, this seems benign as these analyses are complete no-ops, and
without this consistency we can in many cases end up with the legacy
pass manager scheduling deciding to split up a loop pass pipeline in
order to run the function analysis half-way through. It is very, very
annoying to fix these without just being very pedantic across the board.
The only loop passes I've not updated here are ones that use
AU.setPreservesAll() such as IVUsers (an analysis) and the pass printer.
They seemed less relevant.
With this patch, almost all of the problems in PR24804 around loop pass
pipelines are fixed. The one remaining issue is that we run simplify-cfg
and instcombine in the middle of the loop pass pipeline. We've recently
added some loop variants of these passes that would seem substantially
cleaner to use, but this at least gets us much closer to the previous
state. Notably, the seven loop pass managers is down to three.
I've not updated the loop passes using LoopAccessAnalysis because that
analysis hasn't been fully wired into LoopSimplify/LCSSA, and it isn't
clear that those transforms want to support those forms anyways. They
all run late anyways, so this is harmless. Similarly, LSR is left alone
because it already carefully manages its forms and doesn't need to get
fused into a single loop pass manager with a bunch of other loop passes.
LoopReroll didn't use loop simplified form previously, and I've updated
the test case to match the trivially different output.
Finally, I've also factored all the pass initialization for the passes
that use this technique as well, so that should be done regularly and
reliably.
Thanks to James for the help reviewing and thinking about this stuff,
and Ben for help thinking about it as well!
Differential Revision: http://reviews.llvm.org/D17435
llvm-svn: 261316
2016-02-19 18:45:18 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(LoopPass)
|
2015-01-15 18:41:28 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
|
2016-07-13 06:37:48 +08:00
|
|
|
INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
|
|
|
|
false)
|
2008-05-13 08:00:25 +08:00
|
|
|
|
2016-07-13 06:37:48 +08:00
|
|
|
Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
|
2002-05-11 06:44:58 +08:00
|
|
|
|
2007-08-01 00:52:25 +08:00
|
|
|
/// Hoist expressions out of the specified loop. Note, alias info for inner
|
2011-07-07 03:20:02 +08:00
|
|
|
/// loop is not preserved so it is not a good idea to run LICM multiple
|
2007-08-01 00:52:25 +08:00
|
|
|
/// times on one loop.
|
2016-07-13 06:37:48 +08:00
|
|
|
/// We should delete AST for inner loops in the new pass manager to avoid
|
|
|
|
/// memory leak.
|
2002-09-27 00:52:07 +08:00
|
|
|
///
|
2016-07-13 06:37:48 +08:00
|
|
|
bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AliasAnalysis *AA,
|
|
|
|
LoopInfo *LI, DominatorTree *DT,
|
|
|
|
TargetLibraryInfo *TLI,
|
|
|
|
ScalarEvolution *SE, bool DeleteAST) {
|
|
|
|
bool Changed = false;
|
2011-12-02 09:26:24 +08:00
|
|
|
|
2014-02-11 20:52:27 +08:00
|
|
|
assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
|
|
|
|
|
2016-07-13 06:37:48 +08:00
|
|
|
AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
|
2002-05-11 06:44:58 +08:00
|
|
|
|
2002-09-27 03:40:25 +08:00
|
|
|
// Get the preheader block to move instructions into...
|
2016-07-13 06:37:48 +08:00
|
|
|
BasicBlock *Preheader = L->getLoopPreheader();
|
2002-09-27 03:40:25 +08:00
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
// Compute loop safety information.
|
2016-06-11 04:03:17 +08:00
|
|
|
LoopSafetyInfo SafetyInfo;
|
2016-07-13 06:37:48 +08:00
|
|
|
computeLoopSafetyInfo(&SafetyInfo, L);
|
2012-09-04 18:25:04 +08:00
|
|
|
|
2002-05-11 06:44:58 +08:00
|
|
|
// We want to visit all of the instructions in this loop... that are not parts
|
|
|
|
// of our subloops (they have already had their invariants hoisted out of
|
|
|
|
// their loop, into this loop, so there is no need to process the BODIES of
|
|
|
|
// the subloops).
|
|
|
|
//
|
2002-09-30 05:46:09 +08:00
|
|
|
// Traverse the body of the loop in depth first order on the dominator tree so
|
|
|
|
// that we are guaranteed to see definitions before we see uses. This allows
|
2007-08-18 23:08:56 +08:00
|
|
|
// us to sink instructions in one pass, without iteration. After sinking
|
2003-12-19 15:22:45 +08:00
|
|
|
// instructions, we perform another pass to hoist them out of the loop.
|
2002-09-30 05:46:09 +08:00
|
|
|
//
|
2009-11-06 05:11:53 +08:00
|
|
|
if (L->hasDedicatedExits())
|
2016-07-13 06:37:48 +08:00
|
|
|
Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
|
2015-03-10 10:37:25 +08:00
|
|
|
CurAST, &SafetyInfo);
|
2009-11-06 05:11:53 +08:00
|
|
|
if (Preheader)
|
2016-07-13 06:37:48 +08:00
|
|
|
Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
|
|
|
|
CurAST, &SafetyInfo);
|
2002-05-11 06:44:58 +08:00
|
|
|
|
2003-02-24 11:52:32 +08:00
|
|
|
// Now that all loop invariants have been removed from the loop, promote any
|
2010-08-29 14:43:52 +08:00
|
|
|
// memory references to scalars that we can.
|
2014-01-24 10:24:47 +08:00
|
|
|
if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
|
2012-08-08 08:00:26 +08:00
|
|
|
SmallVector<BasicBlock *, 8> ExitBlocks;
|
|
|
|
SmallVector<Instruction *, 8> InsertPts;
|
2014-02-11 20:52:27 +08:00
|
|
|
PredIteratorCache PIC;
|
2012-08-08 08:00:26 +08:00
|
|
|
|
2010-08-29 14:43:52 +08:00
|
|
|
// Loop over all of the alias sets in the tracker object.
|
2016-01-09 06:59:42 +08:00
|
|
|
for (AliasSet &AS : *CurAST)
|
2016-07-13 06:37:48 +08:00
|
|
|
Changed |= promoteLoopAccessesToScalars(
|
|
|
|
AS, ExitBlocks, InsertPts, PIC, LI, DT, TLI, L, CurAST, &SafetyInfo);
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2014-02-01 21:35:14 +08:00
|
|
|
// Once we have promoted values across the loop body we have to recursively
|
|
|
|
// reform LCSSA as any nested loop may now have values defined within the
|
|
|
|
// loop used in the outer loop.
|
|
|
|
// FIXME: This is really heavy handed. It would be a bit better to use an
|
|
|
|
// SSAUpdater strategy during promotion that was LCSSA aware and reformed
|
|
|
|
// it as it went.
|
[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
|
|
|
if (Changed) {
|
2016-07-13 06:37:48 +08:00
|
|
|
formLCSSARecursively(*L, *DT, LI, SE);
|
[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
|
|
|
}
|
2014-02-01 21:35:14 +08:00
|
|
|
}
|
|
|
|
|
2014-02-11 20:52:27 +08:00
|
|
|
// Check that neither this loop nor its parent have had LCSSA broken. LICM is
|
|
|
|
// specifically moving instructions across the loop boundary and so it is
|
|
|
|
// especially in need of sanity checking here.
|
|
|
|
assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
|
|
|
|
assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
|
|
|
|
"Parent loop not left in LCSSA form after LICM!");
|
2014-01-25 12:07:24 +08:00
|
|
|
|
2010-08-30 01:46:00 +08:00
|
|
|
// If this loop is nested inside of another one, save the alias information
|
|
|
|
// for when we process the outer loop.
|
2016-07-13 06:37:48 +08:00
|
|
|
if (L->getParentLoop() && !DeleteAST)
|
2010-08-30 01:46:00 +08:00
|
|
|
LoopToAliasSetMap[L] = CurAST;
|
|
|
|
else
|
|
|
|
delete CurAST;
|
2016-05-04 01:50:11 +08:00
|
|
|
|
2016-07-13 06:37:48 +08:00
|
|
|
if (Changed && SE)
|
|
|
|
SE->forgetLoopDispositions(L);
|
2007-03-07 12:41:30 +08:00
|
|
|
return Changed;
|
2002-05-11 06:44:58 +08:00
|
|
|
}
|
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
/// Walk the specified region of the CFG (defined by all blocks dominated by
|
2016-05-05 08:54:54 +08:00
|
|
|
/// the specified block, and that are in the current loop) in reverse depth
|
2015-02-23 02:35:32 +08:00
|
|
|
/// first order w.r.t the DominatorTree. This allows us to visit uses before
|
|
|
|
/// definitions, allowing us to sink a loop body in one pass without iteration.
|
2003-12-19 15:22:45 +08:00
|
|
|
///
|
2015-03-10 10:37:25 +08:00
|
|
|
bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
|
|
|
|
DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
|
2016-06-11 04:03:17 +08:00
|
|
|
AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
|
2015-02-23 02:35:32 +08:00
|
|
|
|
|
|
|
// Verify inputs.
|
2016-05-05 08:54:54 +08:00
|
|
|
assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
|
|
|
|
CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
|
|
|
|
"Unexpected input to sinkRegion");
|
2015-02-23 02:35:32 +08:00
|
|
|
|
2007-04-24 14:40:39 +08:00
|
|
|
BasicBlock *BB = N->getBlock();
|
2003-12-19 15:22:45 +08:00
|
|
|
// If this subregion is not in the top level loop at all, exit.
|
2016-05-05 08:54:54 +08:00
|
|
|
if (!CurLoop->contains(BB))
|
|
|
|
return false;
|
2003-12-19 15:22:45 +08:00
|
|
|
|
2010-08-30 02:22:25 +08:00
|
|
|
// We are processing blocks in reverse dfo, so process children first.
|
2016-01-14 07:01:57 +08:00
|
|
|
bool Changed = false;
|
2016-05-05 08:54:54 +08:00
|
|
|
const std::vector<DomTreeNode *> &Children = N->getChildren();
|
2016-01-09 06:59:42 +08:00
|
|
|
for (DomTreeNode *Child : Children)
|
|
|
|
Changed |= sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
|
|
|
|
|
2003-12-19 15:22:45 +08:00
|
|
|
// Only need to process the contents of this block if it is not part of a
|
|
|
|
// subloop (which would already have been processed).
|
2016-05-05 08:54:54 +08:00
|
|
|
if (inSubLoop(BB, CurLoop, LI))
|
|
|
|
return Changed;
|
2003-12-19 15:22:45 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
|
2003-12-19 16:18:16 +08:00
|
|
|
Instruction &I = *--II;
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2010-08-30 02:22:25 +08:00
|
|
|
// If the instruction is dead, we would try to sink it because it isn't used
|
|
|
|
// in the loop, instead, just delete it.
|
2012-08-29 23:32:21 +08:00
|
|
|
if (isInstructionTriviallyDead(&I, TLI)) {
|
2010-08-30 02:42:23 +08:00
|
|
|
DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
|
2010-08-30 02:22:25 +08:00
|
|
|
++II;
|
|
|
|
CurAST->deleteValue(&I);
|
|
|
|
I.eraseFromParent();
|
|
|
|
Changed = true;
|
|
|
|
continue;
|
|
|
|
}
|
2005-04-22 07:48:37 +08:00
|
|
|
|
2003-12-19 15:22:45 +08:00
|
|
|
// Check to see if we can sink this instruction to the exit blocks
|
|
|
|
// of the loop. We can do this if the all users of the instruction are
|
|
|
|
// outside of the loop. In this case, it doesn't even matter if the
|
|
|
|
// operands of the instruction are loop invariant.
|
|
|
|
//
|
2016-01-04 11:37:39 +08:00
|
|
|
if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
|
2015-05-19 02:07:00 +08:00
|
|
|
canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) {
|
2003-12-19 16:18:16 +08:00
|
|
|
++II;
|
2016-01-04 11:37:39 +08:00
|
|
|
Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo);
|
2003-12-19 16:18:16 +08:00
|
|
|
}
|
2003-12-19 15:22:45 +08:00
|
|
|
}
|
2015-02-23 02:35:32 +08:00
|
|
|
return Changed;
|
2003-12-19 15:22:45 +08:00
|
|
|
}
|
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
/// Walk the specified region of the CFG (defined by all blocks dominated by
|
|
|
|
/// the specified block, and that are in the current loop) in depth first
|
|
|
|
/// order w.r.t the DominatorTree. This allows us to visit definitions before
|
|
|
|
/// uses, allowing us to hoist a loop body in one pass without iteration.
|
2002-09-30 05:46:09 +08:00
|
|
|
///
|
2015-03-10 10:37:25 +08:00
|
|
|
bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
|
|
|
|
DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
|
2016-06-11 04:03:17 +08:00
|
|
|
AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
|
2015-02-23 02:35:32 +08:00
|
|
|
// Verify inputs.
|
2016-05-05 08:54:54 +08:00
|
|
|
assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
|
|
|
|
CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
|
|
|
|
"Unexpected input to hoistRegion");
|
2016-01-14 07:01:57 +08:00
|
|
|
|
2007-04-24 14:40:39 +08:00
|
|
|
BasicBlock *BB = N->getBlock();
|
2016-01-14 07:01:57 +08:00
|
|
|
|
2002-09-30 06:26:07 +08:00
|
|
|
// If this subregion is not in the top level loop at all, exit.
|
2016-05-05 08:54:54 +08:00
|
|
|
if (!CurLoop->contains(BB))
|
|
|
|
return false;
|
2016-01-14 07:01:57 +08:00
|
|
|
|
2003-12-10 14:41:05 +08:00
|
|
|
// Only need to process the contents of this block if it is not part of a
|
|
|
|
// subloop (which would already have been processed).
|
2016-01-14 07:01:57 +08:00
|
|
|
bool Changed = false;
|
2015-02-23 02:35:32 +08:00
|
|
|
if (!inSubLoop(BB, CurLoop, LI))
|
2016-05-05 08:54:54 +08:00
|
|
|
for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
|
2003-12-10 14:41:05 +08:00
|
|
|
Instruction &I = *II++;
|
2010-09-01 07:00:16 +08:00
|
|
|
// Try constant folding this instruction. If all the operands are
|
|
|
|
// constants, it is technically hoistable, but it would be better to just
|
|
|
|
// fold it.
|
2015-03-10 10:37:25 +08:00
|
|
|
if (Constant *C = ConstantFoldInstruction(
|
|
|
|
&I, I.getModule()->getDataLayout(), TLI)) {
|
2010-09-01 07:00:16 +08:00
|
|
|
DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
|
|
|
|
CurAST->copyValue(&I, C);
|
|
|
|
I.replaceAllUsesWith(C);
|
2016-07-22 12:54:44 +08:00
|
|
|
if (isInstructionTriviallyDead(&I, TLI)) {
|
|
|
|
CurAST->deleteValue(&I);
|
|
|
|
I.eraseFromParent();
|
|
|
|
}
|
2010-09-01 07:00:16 +08:00
|
|
|
continue;
|
|
|
|
}
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2003-12-19 15:22:45 +08:00
|
|
|
// Try hoisting the instruction out to the preheader. We can only do this
|
|
|
|
// if all of the operands of the instruction are loop invariant and if it
|
|
|
|
// is safe to hoist the instruction.
|
|
|
|
//
|
2015-03-10 10:37:25 +08:00
|
|
|
if (CurLoop->hasLoopInvariantOperands(&I) &&
|
2015-05-19 02:07:00 +08:00
|
|
|
canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) &&
|
2016-05-05 08:54:54 +08:00
|
|
|
isSafeToExecuteUnconditionally(
|
2016-07-03 07:47:27 +08:00
|
|
|
I, DT, CurLoop, SafetyInfo,
|
2016-05-05 08:54:54 +08:00
|
|
|
CurLoop->getLoopPreheader()->getTerminator()))
|
2016-01-28 23:51:58 +08:00
|
|
|
Changed |= hoist(I, DT, CurLoop, SafetyInfo);
|
2010-09-01 07:00:16 +08:00
|
|
|
}
|
2002-09-30 05:46:09 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
const std::vector<DomTreeNode *> &Children = N->getChildren();
|
2016-01-09 06:59:42 +08:00
|
|
|
for (DomTreeNode *Child : Children)
|
|
|
|
Changed |= hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
|
2015-02-23 02:35:32 +08:00
|
|
|
return Changed;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Computes loop safety information, checks loop body & header
|
2015-08-09 02:27:36 +08:00
|
|
|
/// for the possibility of may throw exception.
|
2015-02-23 02:35:32 +08:00
|
|
|
///
|
2016-06-11 04:03:17 +08:00
|
|
|
void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
|
2015-02-23 02:35:32 +08:00
|
|
|
assert(CurLoop != nullptr && "CurLoop cant be null");
|
|
|
|
BasicBlock *Header = CurLoop->getHeader();
|
|
|
|
// Setting default safety values.
|
|
|
|
SafetyInfo->MayThrow = false;
|
|
|
|
SafetyInfo->HeaderMayThrow = false;
|
2015-08-09 02:27:36 +08:00
|
|
|
// Iterate over header and compute safety info.
|
2015-02-23 02:35:32 +08:00
|
|
|
for (BasicBlock::iterator I = Header->begin(), E = Header->end();
|
|
|
|
(I != E) && !SafetyInfo->HeaderMayThrow; ++I)
|
2016-07-13 06:37:48 +08:00
|
|
|
SafetyInfo->HeaderMayThrow |=
|
|
|
|
!isGuaranteedToTransferExecutionToSuccessor(&*I);
|
2016-05-05 08:54:54 +08:00
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
|
2016-05-05 08:54:54 +08:00
|
|
|
// Iterate over loop instructions and compute safety info.
|
|
|
|
for (Loop::block_iterator BB = CurLoop->block_begin(),
|
|
|
|
BBE = CurLoop->block_end();
|
|
|
|
(BB != BBE) && !SafetyInfo->MayThrow; ++BB)
|
2015-02-23 02:35:32 +08:00
|
|
|
for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
|
|
|
|
(I != E) && !SafetyInfo->MayThrow; ++I)
|
[LICM] Make isGuaranteedToExecute more accurate.
Summary:
Make isGuaranteedToExecute use the
isGuaranteedToTransferExecutionToSuccessor helper, and make that helper
a bit more accurate.
There's a potential performance impact here from assuming that arbitrary
calls might not return. This probably has little impact on loads and
stores to a pointer because most things alias analysis can reason about
are dereferenceable anyway. The other impacts, like less aggressive
hoisting of sdiv by a variable and less aggressive hoisting around
volatile memory operations, are unlikely to matter for real code.
This also impacts SCEV, which uses the same helper. It's a minor
improvement there because we can tell that, for example, memcpy always
returns normally. Strictly speaking, it's also introducing
a bug, but it's not any worse than everywhere else we assume readonly
functions terminate.
Fixes http://llvm.org/PR27857.
Reviewers: hfinkel, reames, chandlerc, sanjoy
Subscribers: broune, llvm-commits
Differential Revision: http://reviews.llvm.org/D21167
llvm-svn: 272489
2016-06-12 05:48:25 +08:00
|
|
|
SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I);
|
2016-01-04 11:37:39 +08:00
|
|
|
|
|
|
|
// Compute funclet colors if we might sink/hoist in a function with a funclet
|
|
|
|
// personality routine.
|
|
|
|
Function *Fn = CurLoop->getHeader()->getParent();
|
|
|
|
if (Fn->hasPersonalityFn())
|
|
|
|
if (Constant *PersonalityFn = Fn->getPersonalityFn())
|
|
|
|
if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
|
|
|
|
SafetyInfo->BlockColors = colorEHFunclets(*Fn);
|
2002-09-30 05:46:09 +08:00
|
|
|
}
|
|
|
|
|
2003-12-10 14:41:05 +08:00
|
|
|
/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
|
|
|
|
/// instruction.
|
|
|
|
///
|
2015-03-10 10:37:25 +08:00
|
|
|
bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT,
|
2015-05-19 02:07:00 +08:00
|
|
|
TargetLibraryInfo *TLI, Loop *CurLoop,
|
2016-06-11 04:03:17 +08:00
|
|
|
AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
|
2003-12-10 03:32:44 +08:00
|
|
|
// Loads have extra constraints we have to verify before we can hoist them.
|
|
|
|
if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
|
2011-08-16 04:52:09 +08:00
|
|
|
if (!LI->isUnordered())
|
2016-05-05 08:54:54 +08:00
|
|
|
return false; // Don't hoist volatile/atomic loads!
|
2003-12-10 03:32:44 +08:00
|
|
|
|
2008-07-23 13:06:28 +08:00
|
|
|
// Loads from constant memory are always safe to move, even if they end up
|
|
|
|
// in the same alias set as something that ends up being modified.
|
2009-11-20 03:00:10 +08:00
|
|
|
if (AA->pointsToConstantMemory(LI->getOperand(0)))
|
2008-07-23 13:06:28 +08:00
|
|
|
return true;
|
2014-10-21 08:13:20 +08:00
|
|
|
if (LI->getMetadata(LLVMContext::MD_invariant_load))
|
2011-11-09 03:30:00 +08:00
|
|
|
return true;
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2003-12-10 03:32:44 +08:00
|
|
|
// Don't hoist loads which have may-aliased stores in loop.
|
2010-10-20 06:54:46 +08:00
|
|
|
uint64_t Size = 0;
|
2004-11-27 05:20:09 +08:00
|
|
|
if (LI->getType()->isSized())
|
2015-08-06 10:05:46 +08:00
|
|
|
Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
|
2014-07-24 20:16:19 +08:00
|
|
|
|
|
|
|
AAMDNodes AAInfo;
|
|
|
|
LI->getAAMetadata(AAInfo);
|
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
|
2004-03-15 12:11:30 +08:00
|
|
|
} else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
|
2011-05-28 02:37:52 +08:00
|
|
|
// Don't sink or hoist dbg info; it's legal, but not useful.
|
|
|
|
if (isa<DbgInfoIntrinsic>(I))
|
|
|
|
return false;
|
|
|
|
|
2016-01-04 11:37:39 +08:00
|
|
|
// Don't sink calls which can throw.
|
|
|
|
if (CI->mayThrow())
|
|
|
|
return false;
|
|
|
|
|
2011-05-28 02:37:52 +08:00
|
|
|
// Handle simple cases by querying alias analysis.
|
2015-07-23 07:15:57 +08:00
|
|
|
FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
|
|
|
|
if (Behavior == FMRB_DoesNotAccessMemory)
|
2007-12-01 15:51:45 +08:00
|
|
|
return true;
|
2010-11-10 03:58:21 +08:00
|
|
|
if (AliasAnalysis::onlyReadsMemory(Behavior)) {
|
2015-09-22 06:27:59 +08:00
|
|
|
// A readonly argmemonly function only reads from memory pointed to by
|
|
|
|
// it's arguments with arbitrary offsets. If we can prove there are no
|
|
|
|
// writes to this memory in the loop, we can hoist or sink.
|
|
|
|
if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
|
|
|
|
for (Value *Op : CI->arg_operands())
|
|
|
|
if (Op->getType()->isPointerTy() &&
|
|
|
|
pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
|
|
|
|
AAMDNodes(), CurAST))
|
|
|
|
return false;
|
|
|
|
return true;
|
|
|
|
}
|
2007-12-01 15:51:45 +08:00
|
|
|
// If this call only reads from memory and there are no writes to memory
|
|
|
|
// in the loop, we can hoist or sink the call as appropriate.
|
|
|
|
bool FoundMod = false;
|
2016-01-09 06:59:42 +08:00
|
|
|
for (AliasSet &AS : *CurAST) {
|
2007-12-01 15:51:45 +08:00
|
|
|
if (!AS.isForwardingAliasSet() && AS.isMod()) {
|
|
|
|
FoundMod = true;
|
|
|
|
break;
|
2004-03-15 12:11:30 +08:00
|
|
|
}
|
|
|
|
}
|
2016-05-05 08:54:54 +08:00
|
|
|
if (!FoundMod)
|
|
|
|
return true;
|
2004-03-15 12:11:30 +08:00
|
|
|
}
|
|
|
|
|
2012-09-04 18:25:04 +08:00
|
|
|
// FIXME: This should use mod/ref information to see if we can hoist or
|
|
|
|
// sink the call.
|
2005-04-22 07:48:37 +08:00
|
|
|
|
2004-03-15 12:11:30 +08:00
|
|
|
return false;
|
2003-12-10 03:32:44 +08:00
|
|
|
}
|
|
|
|
|
2012-09-04 18:25:04 +08:00
|
|
|
// Only these instructions are hoistable/sinkable.
|
2013-01-10 02:12:03 +08:00
|
|
|
if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
|
|
|
|
!isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
|
|
|
|
!isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
|
|
|
|
!isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
|
|
|
|
!isa<InsertValueInst>(I))
|
|
|
|
return false;
|
2012-09-04 18:25:04 +08:00
|
|
|
|
2015-05-22 10:14:05 +08:00
|
|
|
// TODO: Plumb the context instruction through to make hoisting and sinking
|
|
|
|
// more powerful. Hoisting of loads already works due to the special casing
|
2016-05-05 08:54:54 +08:00
|
|
|
// above.
|
2016-07-03 07:47:27 +08:00
|
|
|
return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
|
2003-12-10 14:41:05 +08:00
|
|
|
}
|
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
/// Returns true if a PHINode is a trivially replaceable with an
|
2014-01-25 12:07:24 +08:00
|
|
|
/// Instruction.
|
2015-02-23 02:35:32 +08:00
|
|
|
/// This is true when all incoming values are that instruction.
|
|
|
|
/// This pattern occurs most often with LCSSA PHI nodes.
|
2014-01-25 12:07:24 +08:00
|
|
|
///
|
2015-05-13 04:05:20 +08:00
|
|
|
static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
|
2015-05-13 04:05:31 +08:00
|
|
|
for (const Value *IncValue : PN.incoming_values())
|
|
|
|
if (IncValue != &I)
|
2014-01-25 12:07:24 +08:00
|
|
|
return false;
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
/// Return true if the only users of this instruction are outside of
|
|
|
|
/// the loop. If this is true, we can sink the instruction to the exit
|
|
|
|
/// blocks of the loop.
|
2003-12-10 14:41:05 +08:00
|
|
|
///
|
2016-01-04 11:37:39 +08:00
|
|
|
static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
|
2016-06-11 04:03:17 +08:00
|
|
|
const LoopSafetyInfo *SafetyInfo) {
|
2016-01-04 11:37:39 +08:00
|
|
|
const auto &BlockColors = SafetyInfo->BlockColors;
|
2015-05-13 09:12:18 +08:00
|
|
|
for (const User *U : I.users()) {
|
|
|
|
const Instruction *UI = cast<Instruction>(U);
|
|
|
|
if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
|
2016-01-04 11:37:39 +08:00
|
|
|
const BasicBlock *BB = PN->getParent();
|
|
|
|
// We cannot sink uses in catchswitches.
|
|
|
|
if (isa<CatchSwitchInst>(BB->getTerminator()))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// We need to sink a callsite to a unique funclet. Avoid sinking if the
|
|
|
|
// phi use is too muddled.
|
|
|
|
if (isa<CallInst>(I))
|
|
|
|
if (!BlockColors.empty() &&
|
|
|
|
BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
|
|
|
|
return false;
|
|
|
|
|
2014-01-25 12:07:24 +08:00
|
|
|
// A PHI node where all of the incoming values are this instruction are
|
|
|
|
// special -- they can just be RAUW'ed with the instruction and thus
|
|
|
|
// don't require a use in the predecessor. This is a particular important
|
|
|
|
// special case because it is the pattern found in LCSSA form.
|
|
|
|
if (isTriviallyReplacablePHI(*PN, I)) {
|
|
|
|
if (CurLoop->contains(PN))
|
|
|
|
return false;
|
|
|
|
else
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise, PHI node uses occur in predecessor blocks if the incoming
|
|
|
|
// values. Check for such a use being inside the loop.
|
2003-12-12 06:23:32 +08:00
|
|
|
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
|
|
|
|
if (PN->getIncomingValue(i) == &I)
|
|
|
|
if (CurLoop->contains(PN->getIncomingBlock(i)))
|
|
|
|
return false;
|
2014-01-25 12:07:24 +08:00
|
|
|
|
|
|
|
continue;
|
2003-12-12 06:23:32 +08:00
|
|
|
}
|
2014-01-25 12:07:24 +08:00
|
|
|
|
2014-03-09 11:16:01 +08:00
|
|
|
if (CurLoop->contains(UI))
|
2014-01-25 12:07:24 +08:00
|
|
|
return false;
|
2003-12-12 06:23:32 +08:00
|
|
|
}
|
2003-12-10 14:41:05 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2016-01-04 11:37:39 +08:00
|
|
|
static Instruction *
|
|
|
|
CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
|
|
|
|
const LoopInfo *LI,
|
2016-06-11 04:03:17 +08:00
|
|
|
const LoopSafetyInfo *SafetyInfo) {
|
2016-01-04 11:37:39 +08:00
|
|
|
Instruction *New;
|
|
|
|
if (auto *CI = dyn_cast<CallInst>(&I)) {
|
|
|
|
const auto &BlockColors = SafetyInfo->BlockColors;
|
|
|
|
|
|
|
|
// Sinking call-sites need to be handled differently from other
|
|
|
|
// instructions. The cloned call-site needs a funclet bundle operand
|
|
|
|
// appropriate for it's location in the CFG.
|
|
|
|
SmallVector<OperandBundleDef, 1> OpBundles;
|
|
|
|
for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
|
|
|
|
BundleIdx != BundleEnd; ++BundleIdx) {
|
|
|
|
OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
|
|
|
|
if (Bundle.getTagID() == LLVMContext::OB_funclet)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
OpBundles.emplace_back(Bundle);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!BlockColors.empty()) {
|
|
|
|
const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
|
|
|
|
assert(CV.size() == 1 && "non-unique color for exit block!");
|
|
|
|
BasicBlock *BBColor = CV.front();
|
|
|
|
Instruction *EHPad = BBColor->getFirstNonPHI();
|
|
|
|
if (EHPad->isEHPad())
|
|
|
|
OpBundles.emplace_back("funclet", EHPad);
|
|
|
|
}
|
|
|
|
|
|
|
|
New = CallInst::Create(CI, OpBundles);
|
|
|
|
} else {
|
|
|
|
New = I.clone();
|
|
|
|
}
|
|
|
|
|
2014-06-25 17:17:21 +08:00
|
|
|
ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
|
2016-05-05 08:54:54 +08:00
|
|
|
if (!I.getName().empty())
|
|
|
|
New->setName(I.getName() + ".le");
|
2014-06-25 17:17:21 +08:00
|
|
|
|
|
|
|
// Build LCSSA PHI nodes for any in-loop operands. Note that this is
|
|
|
|
// particularly cheap because we can rip off the PHI node that we're
|
|
|
|
// replacing for the number and blocks of the predecessors.
|
|
|
|
// OPT: If this shows up in a profile, we can instead finish sinking all
|
|
|
|
// invariant instructions, and then walk their operands to re-establish
|
|
|
|
// LCSSA. That will eliminate creating PHI nodes just to nuke them when
|
|
|
|
// sinking bottom-up.
|
|
|
|
for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
|
|
|
|
++OI)
|
|
|
|
if (Instruction *OInst = dyn_cast<Instruction>(*OI))
|
|
|
|
if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
|
|
|
|
if (!OLoop->contains(&PN)) {
|
|
|
|
PHINode *OpPN =
|
|
|
|
PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
|
2015-10-14 03:26:58 +08:00
|
|
|
OInst->getName() + ".lcssa", &ExitBlock.front());
|
2014-06-25 17:17:21 +08:00
|
|
|
for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
|
|
|
|
OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
|
|
|
|
*OI = OpPN;
|
|
|
|
}
|
|
|
|
return New;
|
|
|
|
}
|
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
/// When an instruction is found to only be used outside of the loop, this
|
|
|
|
/// function moves it to the exit blocks and patches up SSA form as needed.
|
2003-12-19 16:18:16 +08:00
|
|
|
/// This method is guaranteed to remove the original instruction from its
|
|
|
|
/// position, and may either delete it or move it to outside of the loop.
|
2003-12-10 14:41:05 +08:00
|
|
|
///
|
2015-05-13 09:12:18 +08:00
|
|
|
static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
|
2016-01-04 11:37:39 +08:00
|
|
|
const Loop *CurLoop, AliasSetTracker *CurAST,
|
2016-06-11 04:03:17 +08:00
|
|
|
const LoopSafetyInfo *SafetyInfo) {
|
2010-07-31 04:27:01 +08:00
|
|
|
DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
|
2015-02-23 02:35:32 +08:00
|
|
|
bool Changed = false;
|
2016-05-05 08:54:54 +08:00
|
|
|
if (isa<LoadInst>(I))
|
|
|
|
++NumMovedLoads;
|
|
|
|
else if (isa<CallInst>(I))
|
|
|
|
++NumMovedCalls;
|
2003-12-11 04:43:29 +08:00
|
|
|
++NumSunk;
|
|
|
|
Changed = true;
|
|
|
|
|
2014-02-11 20:52:27 +08:00
|
|
|
#ifndef NDEBUG
|
|
|
|
SmallVector<BasicBlock *, 32> ExitBlocks;
|
|
|
|
CurLoop->getUniqueExitBlocks(ExitBlocks);
|
2016-05-05 08:54:54 +08:00
|
|
|
SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
|
2015-02-23 02:35:32 +08:00
|
|
|
ExitBlocks.end());
|
2014-02-11 20:52:27 +08:00
|
|
|
#endif
|
|
|
|
|
2014-06-25 15:54:58 +08:00
|
|
|
// Clones of this instruction. Don't create more than one per exit block!
|
|
|
|
SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
|
|
|
|
|
2014-02-11 20:52:27 +08:00
|
|
|
// If this instruction is only used outside of the loop, then all users are
|
|
|
|
// PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
|
|
|
|
// the instruction.
|
|
|
|
while (!I.use_empty()) {
|
2015-07-12 11:53:05 +08:00
|
|
|
Value::user_iterator UI = I.user_begin();
|
|
|
|
auto *User = cast<Instruction>(*UI);
|
2014-09-03 00:22:00 +08:00
|
|
|
if (!DT->isReachableFromEntry(User->getParent())) {
|
|
|
|
User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
|
|
|
|
continue;
|
|
|
|
}
|
2014-02-11 20:52:27 +08:00
|
|
|
// The user must be a PHI node.
|
2014-09-03 00:22:00 +08:00
|
|
|
PHINode *PN = cast<PHINode>(User);
|
2014-02-11 20:52:27 +08:00
|
|
|
|
2015-07-12 11:53:05 +08:00
|
|
|
// Surprisingly, instructions can be used outside of loops without any
|
|
|
|
// exits. This can only happen in PHI nodes if the incoming block is
|
|
|
|
// unreachable.
|
|
|
|
Use &U = UI.getUse();
|
|
|
|
BasicBlock *BB = PN->getIncomingBlock(U);
|
|
|
|
if (!DT->isReachableFromEntry(BB)) {
|
|
|
|
U = UndefValue::get(I.getType());
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2014-02-11 20:52:27 +08:00
|
|
|
BasicBlock *ExitBlock = PN->getParent();
|
|
|
|
assert(ExitBlockSet.count(ExitBlock) &&
|
|
|
|
"The LCSSA PHI is not in an exit block!");
|
|
|
|
|
2014-06-25 15:54:58 +08:00
|
|
|
Instruction *New;
|
|
|
|
auto It = SunkCopies.find(ExitBlock);
|
2014-06-25 17:17:21 +08:00
|
|
|
if (It != SunkCopies.end())
|
2014-06-25 15:54:58 +08:00
|
|
|
New = It->second;
|
2014-06-25 17:17:21 +08:00
|
|
|
else
|
|
|
|
New = SunkCopies[ExitBlock] =
|
2016-01-04 11:37:39 +08:00
|
|
|
CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo);
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2014-02-11 20:52:27 +08:00
|
|
|
PN->replaceAllUsesWith(New);
|
|
|
|
PN->eraseFromParent();
|
2003-12-10 14:41:05 +08:00
|
|
|
}
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2010-08-30 02:00:00 +08:00
|
|
|
CurAST->deleteValue(&I);
|
2014-02-11 20:52:27 +08:00
|
|
|
I.eraseFromParent();
|
2015-02-23 02:35:32 +08:00
|
|
|
return Changed;
|
2003-12-10 14:41:05 +08:00
|
|
|
}
|
2002-09-30 05:46:09 +08:00
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
/// When an instruction is found to only use loop invariant operands that
|
|
|
|
/// is safe to hoist, this instruction is called to do the dirty work.
|
2002-09-27 00:52:07 +08:00
|
|
|
///
|
2016-01-28 23:51:58 +08:00
|
|
|
static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
|
2016-06-11 04:03:17 +08:00
|
|
|
const LoopSafetyInfo *SafetyInfo) {
|
2016-01-28 23:51:58 +08:00
|
|
|
auto *Preheader = CurLoop->getLoopPreheader();
|
2016-05-05 08:54:54 +08:00
|
|
|
DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
|
|
|
|
<< "\n");
|
2016-01-28 23:51:58 +08:00
|
|
|
|
|
|
|
// Metadata can be dependent on conditions we are hoisting above.
|
|
|
|
// Conservatively strip all metadata on the instruction unless we were
|
|
|
|
// guaranteed to execute I if we entered the loop, in which case the metadata
|
|
|
|
// is valid in the loop preheader.
|
|
|
|
if (I.hasMetadataOtherThanDebugLoc() &&
|
|
|
|
// The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
|
|
|
|
// time in isGuaranteedToExecute if we don't actually have anything to
|
|
|
|
// drop. It is a compile time optimization, not required for correctness.
|
|
|
|
!isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
|
|
|
|
I.dropUnknownNonDebugMetadata();
|
|
|
|
|
2010-08-30 02:18:40 +08:00
|
|
|
// Move the new node to the Preheader, before its terminator.
|
|
|
|
I.moveBefore(Preheader->getTerminator());
|
2005-04-22 07:48:37 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
if (isa<LoadInst>(I))
|
|
|
|
++NumMovedLoads;
|
|
|
|
else if (isa<CallInst>(I))
|
|
|
|
++NumMovedCalls;
|
2002-09-27 00:38:03 +08:00
|
|
|
++NumHoisted;
|
2015-02-23 02:35:32 +08:00
|
|
|
return true;
|
2002-05-11 06:44:58 +08:00
|
|
|
}
|
|
|
|
|
2015-05-19 02:07:00 +08:00
|
|
|
/// Only sink or hoist an instruction if it is not a trapping instruction,
|
|
|
|
/// or if the instruction is known not to trap when moved to the preheader.
|
2015-02-23 02:35:32 +08:00
|
|
|
/// or if it is a trapping instruction and is guaranteed to execute.
|
2016-05-05 08:54:54 +08:00
|
|
|
static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
|
2015-05-13 09:12:18 +08:00
|
|
|
const DominatorTree *DT,
|
|
|
|
const Loop *CurLoop,
|
2016-06-11 04:03:17 +08:00
|
|
|
const LoopSafetyInfo *SafetyInfo,
|
2015-05-22 10:14:05 +08:00
|
|
|
const Instruction *CtxI) {
|
2016-07-03 07:47:27 +08:00
|
|
|
if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
|
2009-07-17 12:28:42 +08:00
|
|
|
return true;
|
2005-04-22 07:48:37 +08:00
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
|
2011-07-21 05:37:47 +08:00
|
|
|
}
|
|
|
|
|
2011-01-15 08:12:35 +08:00
|
|
|
namespace {
|
2016-05-05 08:54:54 +08:00
|
|
|
class LoopPromoter : public LoadAndStorePromoter {
|
|
|
|
Value *SomePtr; // Designated pointer to store to.
|
|
|
|
SmallPtrSetImpl<Value *> &PointerMustAliases;
|
|
|
|
SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
|
|
|
|
SmallVectorImpl<Instruction *> &LoopInsertPts;
|
|
|
|
PredIteratorCache &PredCache;
|
|
|
|
AliasSetTracker &AST;
|
|
|
|
LoopInfo &LI;
|
|
|
|
DebugLoc DL;
|
|
|
|
int Alignment;
|
|
|
|
AAMDNodes AATags;
|
2014-02-11 20:52:27 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
|
|
|
|
if (Instruction *I = dyn_cast<Instruction>(V))
|
|
|
|
if (Loop *L = LI.getLoopFor(I->getParent()))
|
|
|
|
if (!L->contains(BB)) {
|
|
|
|
// We need to create an LCSSA PHI node for the incoming value and
|
|
|
|
// store that.
|
|
|
|
PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
|
|
|
|
I->getName() + ".lcssa", &BB->front());
|
|
|
|
for (BasicBlock *Pred : PredCache.get(BB))
|
|
|
|
PN->addIncoming(I, Pred);
|
|
|
|
return PN;
|
|
|
|
}
|
|
|
|
return V;
|
|
|
|
}
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
public:
|
|
|
|
LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
|
|
|
|
SmallPtrSetImpl<Value *> &PMA,
|
|
|
|
SmallVectorImpl<BasicBlock *> &LEB,
|
|
|
|
SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
|
|
|
|
AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
|
|
|
|
const AAMDNodes &AATags)
|
|
|
|
: LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
|
|
|
|
LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
|
2016-05-27 22:27:24 +08:00
|
|
|
LI(li), DL(std::move(dl)), Alignment(alignment), AATags(AATags) {}
|
2016-05-05 08:54:54 +08:00
|
|
|
|
|
|
|
bool isInstInList(Instruction *I,
|
|
|
|
const SmallVectorImpl<Instruction *> &) const override {
|
|
|
|
Value *Ptr;
|
|
|
|
if (LoadInst *LI = dyn_cast<LoadInst>(I))
|
|
|
|
Ptr = LI->getOperand(0);
|
|
|
|
else
|
|
|
|
Ptr = cast<StoreInst>(I)->getPointerOperand();
|
|
|
|
return PointerMustAliases.count(Ptr);
|
|
|
|
}
|
2011-01-15 08:12:35 +08:00
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
void doExtraRewritesBeforeFinalDeletion() const override {
|
|
|
|
// Insert stores after in the loop exit blocks. Each exit block gets a
|
|
|
|
// store of the live-out values that feed them. Since we've already told
|
|
|
|
// the SSA updater about the defs in the loop and the preheader
|
|
|
|
// definition, it is all set and we can start using it.
|
|
|
|
for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
|
|
|
|
BasicBlock *ExitBlock = LoopExitBlocks[i];
|
|
|
|
Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
|
|
|
|
LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
|
|
|
|
Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
|
|
|
|
Instruction *InsertPos = LoopInsertPts[i];
|
|
|
|
StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
|
|
|
|
NewSI->setAlignment(Alignment);
|
|
|
|
NewSI->setDebugLoc(DL);
|
|
|
|
if (AATags)
|
|
|
|
NewSI->setAAMetadata(AATags);
|
2011-01-15 08:12:35 +08:00
|
|
|
}
|
2016-05-05 08:54:54 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
|
|
|
|
// Update alias analysis.
|
|
|
|
AST.copyValue(LI, V);
|
|
|
|
}
|
|
|
|
void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
|
|
|
|
};
|
2015-06-23 17:49:53 +08:00
|
|
|
} // end anon namespace
|
2011-01-15 08:12:35 +08:00
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
/// Try to promote memory values to scalars by sinking stores out of the
|
|
|
|
/// loop and moving loads to before the loop. We do this by looping over
|
|
|
|
/// the stores in the loop, looking for stores to Must pointers which are
|
|
|
|
/// loop invariant.
|
2003-02-24 11:52:32 +08:00
|
|
|
///
|
2016-05-05 08:54:54 +08:00
|
|
|
bool llvm::promoteLoopAccessesToScalars(
|
|
|
|
AliasSet &AS, SmallVectorImpl<BasicBlock *> &ExitBlocks,
|
|
|
|
SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
|
|
|
|
LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
|
2016-06-11 04:03:17 +08:00
|
|
|
Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) {
|
2015-02-23 02:35:32 +08:00
|
|
|
// Verify inputs.
|
2016-05-05 08:54:54 +08:00
|
|
|
assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
|
|
|
|
CurAST != nullptr && SafetyInfo != nullptr &&
|
2015-02-23 02:35:32 +08:00
|
|
|
"Unexpected Input to promoteLoopAccessesToScalars");
|
2016-01-14 07:01:57 +08:00
|
|
|
|
2010-08-29 14:43:52 +08:00
|
|
|
// We can promote this alias set if it has a store, if it is a "Must" alias
|
|
|
|
// set, if the pointer is loop invariant, and if we are not eliminating any
|
|
|
|
// volatile loads or stores.
|
|
|
|
if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
|
|
|
|
AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
|
2016-01-14 07:01:57 +08:00
|
|
|
return false;
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2010-08-29 14:43:52 +08:00
|
|
|
assert(!AS.empty() &&
|
|
|
|
"Must alias set should have at least one pointer element in it!");
|
2015-02-23 02:35:32 +08:00
|
|
|
|
2010-08-29 14:43:52 +08:00
|
|
|
Value *SomePtr = AS.begin()->getValue();
|
2016-05-05 08:54:54 +08:00
|
|
|
BasicBlock *Preheader = CurLoop->getLoopPreheader();
|
2005-04-22 07:48:37 +08:00
|
|
|
|
2010-08-29 14:43:52 +08:00
|
|
|
// It isn't safe to promote a load/store from the loop if the load/store is
|
|
|
|
// conditional. For example, turning:
|
2003-02-24 11:52:32 +08:00
|
|
|
//
|
2010-08-29 14:43:52 +08:00
|
|
|
// for () { if (c) *P += 1; }
|
2003-02-24 11:52:32 +08:00
|
|
|
//
|
2010-08-29 14:43:52 +08:00
|
|
|
// into:
|
|
|
|
//
|
|
|
|
// tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
|
|
|
|
//
|
|
|
|
// is not safe, because *P may only be valid to access if 'c' is true.
|
2011-07-07 03:20:02 +08:00
|
|
|
//
|
2016-03-10 06:59:30 +08:00
|
|
|
// The safety property divides into two parts:
|
|
|
|
// 1) The memory may not be dereferenceable on entry to the loop. In this
|
|
|
|
// case, we can't insert the required load in the preheader.
|
|
|
|
// 2) The memory model does not allow us to insert a store along any dynamic
|
|
|
|
// path which did not originally have one.
|
|
|
|
//
|
2010-08-29 14:43:52 +08:00
|
|
|
// It is safe to promote P if all uses are direct load/stores and if at
|
|
|
|
// least one is guaranteed to be executed.
|
|
|
|
bool GuaranteedToExecute = false;
|
2011-07-07 03:19:55 +08:00
|
|
|
|
2016-03-10 06:59:30 +08:00
|
|
|
// It is also safe to promote P if we can prove that speculating a load into
|
|
|
|
// the preheader is safe (i.e. proving dereferenceability on all
|
|
|
|
// paths through the loop), and that the memory can be proven thread local
|
|
|
|
// (so that the memory model requirement doesn't apply.) We first establish
|
|
|
|
// the former, and then run a capture analysis below to establish the later.
|
|
|
|
// We can use any access within the alias set to prove dereferenceability
|
|
|
|
// since they're all must alias.
|
|
|
|
bool CanSpeculateLoad = false;
|
|
|
|
|
2016-05-05 08:54:54 +08:00
|
|
|
SmallVector<Instruction *, 64> LoopUses;
|
|
|
|
SmallPtrSet<Value *, 4> PointerMustAliases;
|
2010-08-29 14:43:52 +08:00
|
|
|
|
2011-07-07 03:19:55 +08:00
|
|
|
// We start with an alignment of one and try to find instructions that allow
|
|
|
|
// us to prove better alignment.
|
|
|
|
unsigned Alignment = 1;
|
2014-07-24 20:16:19 +08:00
|
|
|
AAMDNodes AATags;
|
2014-11-29 03:47:46 +08:00
|
|
|
bool HasDedicatedExits = CurLoop->hasDedicatedExits();
|
2011-07-07 03:19:55 +08:00
|
|
|
|
2016-03-10 06:59:30 +08:00
|
|
|
// Don't sink stores from loops without dedicated block exits. Exits
|
|
|
|
// containing indirect branches are not transformed by loop simplify,
|
|
|
|
// make sure we catch that. An additional load may be generated in the
|
|
|
|
// preheader for SSA updater, so also avoid sinking when no preheader
|
|
|
|
// is available.
|
|
|
|
if (!HasDedicatedExits || !Preheader)
|
|
|
|
return false;
|
2016-05-05 08:54:54 +08:00
|
|
|
|
2016-03-10 06:59:30 +08:00
|
|
|
const DataLayout &MDL = Preheader->getModule()->getDataLayout();
|
|
|
|
|
2016-06-06 06:13:52 +08:00
|
|
|
if (SafetyInfo->MayThrow) {
|
|
|
|
// If a loop can throw, we have to insert a store along each unwind edge.
|
|
|
|
// That said, we can't actually make the unwind edge explicit. Therefore,
|
|
|
|
// we have to prove that the store is dead along the unwind edge.
|
|
|
|
//
|
|
|
|
// Currently, this code just special-cases alloca instructions.
|
|
|
|
if (!isa<AllocaInst>(GetUnderlyingObject(SomePtr, MDL)))
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2010-08-29 14:43:52 +08:00
|
|
|
// Check that all of the pointers in the alias set have the same type. We
|
|
|
|
// cannot (yet) promote a memory location that is loaded and stored in
|
2014-07-24 20:16:19 +08:00
|
|
|
// different sizes. While we are at it, collect alignment and AA info.
|
2016-01-14 07:01:57 +08:00
|
|
|
bool Changed = false;
|
2016-06-26 20:28:59 +08:00
|
|
|
for (const auto &ASI : AS) {
|
|
|
|
Value *ASIV = ASI.getValue();
|
2010-08-29 14:43:52 +08:00
|
|
|
PointerMustAliases.insert(ASIV);
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2008-05-22 08:53:38 +08:00
|
|
|
// Check that all of the pointers in the alias set have the same type. We
|
|
|
|
// cannot (yet) promote a memory location that is loaded and stored in
|
|
|
|
// different sizes.
|
2010-08-29 14:43:52 +08:00
|
|
|
if (SomePtr->getType() != ASIV->getType())
|
2015-02-23 02:35:32 +08:00
|
|
|
return Changed;
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2014-03-09 11:16:01 +08:00
|
|
|
for (User *U : ASIV->users()) {
|
2010-08-29 14:43:52 +08:00
|
|
|
// Ignore instructions that are outside the loop.
|
2014-03-09 11:16:01 +08:00
|
|
|
Instruction *UI = dyn_cast<Instruction>(U);
|
|
|
|
if (!UI || !CurLoop->contains(UI))
|
2008-05-22 08:53:38 +08:00
|
|
|
continue;
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2010-08-29 14:43:52 +08:00
|
|
|
// If there is an non-load/store instruction in the loop, we can't promote
|
|
|
|
// it.
|
2016-01-09 06:05:03 +08:00
|
|
|
if (const LoadInst *Load = dyn_cast<LoadInst>(UI)) {
|
|
|
|
assert(!Load->isVolatile() && "AST broken");
|
|
|
|
if (!Load->isSimple())
|
2015-02-23 02:35:32 +08:00
|
|
|
return Changed;
|
2016-03-10 06:59:30 +08:00
|
|
|
|
|
|
|
if (!GuaranteedToExecute && !CanSpeculateLoad)
|
2016-05-05 08:54:54 +08:00
|
|
|
CanSpeculateLoad = isSafeToExecuteUnconditionally(
|
2016-07-03 07:47:27 +08:00
|
|
|
*Load, DT, CurLoop, SafetyInfo, Preheader->getTerminator());
|
2016-01-09 06:05:03 +08:00
|
|
|
} else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
|
2010-12-19 13:57:25 +08:00
|
|
|
// Stores *of* the pointer are not interesting, only stores *to* the
|
|
|
|
// pointer.
|
2014-03-09 11:16:01 +08:00
|
|
|
if (UI->getOperand(1) != ASIV)
|
2010-12-19 13:57:25 +08:00
|
|
|
continue;
|
2016-01-09 06:05:03 +08:00
|
|
|
assert(!Store->isVolatile() && "AST broken");
|
|
|
|
if (!Store->isSimple())
|
2015-02-23 02:35:32 +08:00
|
|
|
return Changed;
|
2011-07-07 03:19:55 +08:00
|
|
|
|
2011-07-21 05:37:47 +08:00
|
|
|
// Note that we only check GuaranteedToExecute inside the store case
|
|
|
|
// so that we do not introduce stores where they did not exist before
|
|
|
|
// (which would break the LLVM concurrency model).
|
|
|
|
|
|
|
|
// If the alignment of this instruction allows us to specify a more
|
|
|
|
// restrictive (and performant) alignment and if we are sure this
|
|
|
|
// instruction will be executed, update the alignment.
|
|
|
|
// Larger is better, with the exception of 0 being the best alignment.
|
2016-01-09 06:05:03 +08:00
|
|
|
unsigned InstAlignment = Store->getAlignment();
|
2016-06-24 20:38:45 +08:00
|
|
|
if ((InstAlignment > Alignment || InstAlignment == 0) &&
|
|
|
|
Alignment != 0) {
|
2015-02-23 02:35:32 +08:00
|
|
|
if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
|
2011-07-21 05:37:47 +08:00
|
|
|
GuaranteedToExecute = true;
|
|
|
|
Alignment = InstAlignment;
|
|
|
|
}
|
2016-06-24 20:38:45 +08:00
|
|
|
} else if (!GuaranteedToExecute) {
|
2016-05-05 08:54:54 +08:00
|
|
|
GuaranteedToExecute =
|
|
|
|
isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo);
|
2016-06-24 20:38:45 +08:00
|
|
|
}
|
2016-03-10 06:59:30 +08:00
|
|
|
|
|
|
|
if (!GuaranteedToExecute && !CanSpeculateLoad) {
|
2016-05-05 08:54:54 +08:00
|
|
|
CanSpeculateLoad = isDereferenceableAndAlignedPointer(
|
|
|
|
Store->getPointerOperand(), Store->getAlignment(), MDL,
|
2016-07-03 07:47:27 +08:00
|
|
|
Preheader->getTerminator(), DT);
|
2016-03-10 06:59:30 +08:00
|
|
|
}
|
2011-07-21 05:37:47 +08:00
|
|
|
} else
|
2015-02-23 02:35:32 +08:00
|
|
|
return Changed; // Not a load or store.
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2014-07-24 20:16:19 +08:00
|
|
|
// Merge the AA tags.
|
2012-12-31 16:37:17 +08:00
|
|
|
if (LoopUses.empty()) {
|
2014-07-24 20:16:19 +08:00
|
|
|
// On the first load/store, just take its AA tags.
|
|
|
|
UI->getAAMetadata(AATags);
|
|
|
|
} else if (AATags) {
|
|
|
|
UI->getAAMetadata(AATags, /* Merge = */ true);
|
2012-12-31 16:37:17 +08:00
|
|
|
}
|
2014-03-09 11:16:01 +08:00
|
|
|
|
|
|
|
LoopUses.push_back(UI);
|
2008-05-22 08:53:38 +08:00
|
|
|
}
|
2010-08-29 14:43:52 +08:00
|
|
|
}
|
2011-07-07 03:19:55 +08:00
|
|
|
|
2016-03-10 06:59:30 +08:00
|
|
|
// Check legality per comment above. Otherwise, we can't promote.
|
|
|
|
bool PromotionIsLegal = GuaranteedToExecute;
|
|
|
|
if (!PromotionIsLegal && CanSpeculateLoad) {
|
|
|
|
// If this is a thread local location, then we can insert stores along
|
|
|
|
// paths which originally didn't have them without violating the memory
|
2016-05-05 08:54:54 +08:00
|
|
|
// model.
|
2016-03-10 06:59:30 +08:00
|
|
|
Value *Object = GetUnderlyingObject(SomePtr, MDL);
|
2016-05-05 08:54:54 +08:00
|
|
|
PromotionIsLegal =
|
|
|
|
isAllocLikeFn(Object, TLI) && !PointerMayBeCaptured(Object, true, true);
|
2016-03-10 06:59:30 +08:00
|
|
|
}
|
|
|
|
if (!PromotionIsLegal)
|
2015-02-23 02:35:32 +08:00
|
|
|
return Changed;
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2016-01-05 01:42:19 +08:00
|
|
|
// Figure out the loop exits and their insertion points, if this is the
|
|
|
|
// first promotion.
|
|
|
|
if (ExitBlocks.empty()) {
|
|
|
|
CurLoop->getUniqueExitBlocks(ExitBlocks);
|
|
|
|
InsertPts.clear();
|
|
|
|
InsertPts.reserve(ExitBlocks.size());
|
2016-01-05 07:16:22 +08:00
|
|
|
for (BasicBlock *ExitBlock : ExitBlocks)
|
2016-01-05 01:42:19 +08:00
|
|
|
InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
|
|
|
|
}
|
|
|
|
|
2016-01-05 07:16:22 +08:00
|
|
|
// Can't insert into a catchswitch.
|
|
|
|
for (BasicBlock *ExitBlock : ExitBlocks)
|
|
|
|
if (isa<CatchSwitchInst>(ExitBlock->getTerminator()))
|
|
|
|
return Changed;
|
|
|
|
|
2010-08-29 14:43:52 +08:00
|
|
|
// Otherwise, this is safe to promote, lets do it!
|
2016-05-05 08:54:54 +08:00
|
|
|
DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
|
|
|
|
<< '\n');
|
2010-08-29 14:43:52 +08:00
|
|
|
Changed = true;
|
|
|
|
++NumPromoted;
|
2007-10-02 02:12:58 +08:00
|
|
|
|
2011-05-28 04:31:51 +08:00
|
|
|
// Grab a debug location for the inserted loads/stores; given that the
|
|
|
|
// inserted loads/stores have little relation to the original loads/stores,
|
|
|
|
// this code just arbitrarily picks a location from one, since any debug
|
|
|
|
// location is better than none.
|
|
|
|
DebugLoc DL = LoopUses[0]->getDebugLoc();
|
|
|
|
|
2010-08-29 14:43:52 +08:00
|
|
|
// We use the SSAUpdater interface to insert phi nodes as required.
|
2016-05-05 08:54:54 +08:00
|
|
|
SmallVector<PHINode *, 16> NewPHIs;
|
2010-08-29 14:43:52 +08:00
|
|
|
SSAUpdater SSA(&NewPHIs);
|
2016-05-05 08:54:54 +08:00
|
|
|
LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
|
2014-07-24 20:16:19 +08:00
|
|
|
InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
|
2011-07-07 03:20:02 +08:00
|
|
|
|
2011-01-15 08:12:35 +08:00
|
|
|
// Set up the preheader to have a definition of the value. It is the live-out
|
|
|
|
// value from the preheader that uses in the loop will use.
|
2016-05-05 08:54:54 +08:00
|
|
|
LoadInst *PreheaderLoad = new LoadInst(
|
|
|
|
SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
|
2011-07-07 03:19:55 +08:00
|
|
|
PreheaderLoad->setAlignment(Alignment);
|
2011-05-28 04:31:51 +08:00
|
|
|
PreheaderLoad->setDebugLoc(DL);
|
2016-05-05 08:54:54 +08:00
|
|
|
if (AATags)
|
|
|
|
PreheaderLoad->setAAMetadata(AATags);
|
2010-08-29 14:43:52 +08:00
|
|
|
SSA.AddAvailableValue(Preheader, PreheaderLoad);
|
|
|
|
|
2011-01-15 08:12:35 +08:00
|
|
|
// Rewrite all the loads in the loop and remember all the definitions from
|
|
|
|
// stores in the loop.
|
|
|
|
Promoter.run(LoopUses);
|
2011-04-07 09:35:06 +08:00
|
|
|
|
|
|
|
// If the SSAUpdater didn't use the load in the preheader, just zap it now.
|
|
|
|
if (PreheaderLoad->use_empty())
|
|
|
|
PreheaderLoad->eraseFromParent();
|
2007-07-31 16:01:41 +08:00
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
return Changed;
|
|
|
|
}
|
2010-08-29 14:43:52 +08:00
|
|
|
|
2016-02-15 22:48:50 +08:00
|
|
|
/// Returns an owning pointer to an alias set which incorporates aliasing info
|
2016-02-27 12:34:07 +08:00
|
|
|
/// from L and all subloops of L.
|
2016-07-13 06:37:48 +08:00
|
|
|
/// FIXME: In new pass manager, there is no helper functions to handle loop
|
|
|
|
/// analysis such as cloneBasicBlockAnalysis. So the AST needs to be recompute
|
|
|
|
/// from scratch for every loop. Hook up with the helper functions when
|
|
|
|
/// available in the new pass manager to avoid redundant computation.
|
|
|
|
AliasSetTracker *
|
|
|
|
LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
|
|
|
|
AliasAnalysis *AA) {
|
2016-02-15 22:48:50 +08:00
|
|
|
AliasSetTracker *CurAST = nullptr;
|
2016-02-27 12:34:07 +08:00
|
|
|
SmallVector<Loop *, 4> RecomputeLoops;
|
2016-02-15 22:48:50 +08:00
|
|
|
for (Loop *InnerL : L->getSubLoops()) {
|
2016-02-27 12:34:07 +08:00
|
|
|
auto MapI = LoopToAliasSetMap.find(InnerL);
|
|
|
|
// If the AST for this inner loop is missing it may have been merged into
|
|
|
|
// some other loop's AST and then that loop unrolled, and so we need to
|
|
|
|
// recompute it.
|
|
|
|
if (MapI == LoopToAliasSetMap.end()) {
|
|
|
|
RecomputeLoops.push_back(InnerL);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
AliasSetTracker *InnerAST = MapI->second;
|
2016-02-15 22:48:50 +08:00
|
|
|
|
|
|
|
if (CurAST != nullptr) {
|
|
|
|
// What if InnerLoop was modified by other passes ?
|
|
|
|
CurAST->add(*InnerAST);
|
|
|
|
|
|
|
|
// Once we've incorporated the inner loop's AST into ours, we don't need
|
|
|
|
// the subloop's anymore.
|
|
|
|
delete InnerAST;
|
|
|
|
} else {
|
|
|
|
CurAST = InnerAST;
|
|
|
|
}
|
2016-02-27 12:34:07 +08:00
|
|
|
LoopToAliasSetMap.erase(MapI);
|
2016-02-15 22:48:50 +08:00
|
|
|
}
|
|
|
|
if (CurAST == nullptr)
|
|
|
|
CurAST = new AliasSetTracker(*AA);
|
2016-02-27 12:34:07 +08:00
|
|
|
|
|
|
|
auto mergeLoop = [&](Loop *L) {
|
|
|
|
// Loop over the body of this loop, looking for calls, invokes, and stores.
|
|
|
|
// Because subloops have already been incorporated into AST, we skip blocks
|
|
|
|
// in subloops.
|
|
|
|
for (BasicBlock *BB : L->blocks())
|
|
|
|
if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
|
|
|
|
CurAST->add(*BB); // Incorporate the specified basic block
|
|
|
|
};
|
|
|
|
|
|
|
|
// Add everything from the sub loops that are no longer directly available.
|
|
|
|
for (Loop *InnerL : RecomputeLoops)
|
|
|
|
mergeLoop(InnerL);
|
|
|
|
|
|
|
|
// And merge in this loop.
|
|
|
|
mergeLoop(L);
|
|
|
|
|
2016-02-15 22:48:50 +08:00
|
|
|
return CurAST;
|
|
|
|
}
|
|
|
|
|
2015-08-13 19:18:35 +08:00
|
|
|
/// Simple analysis hook. Clone alias set info.
|
2015-02-23 02:35:32 +08:00
|
|
|
///
|
2016-07-13 06:37:48 +08:00
|
|
|
void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
|
|
|
|
Loop *L) {
|
|
|
|
AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
|
2007-07-31 16:01:41 +08:00
|
|
|
if (!AST)
|
|
|
|
return;
|
|
|
|
|
|
|
|
AST->copyValue(From, To);
|
|
|
|
}
|
|
|
|
|
2015-02-23 02:35:32 +08:00
|
|
|
/// Simple Analysis hook. Delete value V from alias set
|
|
|
|
///
|
2016-07-13 06:37:48 +08:00
|
|
|
void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
|
|
|
|
AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
|
2007-07-31 16:01:41 +08:00
|
|
|
if (!AST)
|
|
|
|
return;
|
|
|
|
|
|
|
|
AST->deleteValue(V);
|
|
|
|
}
|
2014-09-25 00:48:31 +08:00
|
|
|
|
|
|
|
/// Simple Analysis hook. Delete value L from alias set map.
|
2015-02-23 02:35:32 +08:00
|
|
|
///
|
2016-07-13 06:37:48 +08:00
|
|
|
void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
|
|
|
|
AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
|
2014-09-25 00:48:31 +08:00
|
|
|
if (!AST)
|
|
|
|
return;
|
|
|
|
|
|
|
|
delete AST;
|
2016-07-13 06:37:48 +08:00
|
|
|
LICM.getLoopToAliasSetMap().erase(L);
|
2014-09-25 00:48:31 +08:00
|
|
|
}
|
2015-02-23 02:35:32 +08:00
|
|
|
|
|
|
|
/// Return true if the body of this loop may store into the memory
|
|
|
|
/// location pointed to by V.
|
|
|
|
///
|
|
|
|
static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
|
2016-05-05 08:54:54 +08:00
|
|
|
const AAMDNodes &AAInfo,
|
2015-02-23 02:35:32 +08:00
|
|
|
AliasSetTracker *CurAST) {
|
|
|
|
// Check to see if any of the basic blocks in CurLoop invalidate *V.
|
|
|
|
return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Little predicate that returns true if the specified basic block is in
|
|
|
|
/// a subloop of the current one, not the current one itself.
|
|
|
|
///
|
|
|
|
static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
|
|
|
|
assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
|
|
|
|
return LI->getLoopFor(BB) != CurLoop;
|
|
|
|
}
|