2014-01-25 10:02:55 +08:00
|
|
|
//===- ConstantHoisting.cpp - Prepare code for expensive constants --------===//
|
|
|
|
//
|
2019-01-19 16:50:56 +08:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2014-01-25 10:02:55 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This pass identifies expensive constants to hoist and coalesces them to
|
|
|
|
// better prepare it for SelectionDAG-based code generation. This works around
|
|
|
|
// the limitations of the basic-block-at-a-time approach.
|
|
|
|
//
|
|
|
|
// First it scans all instructions for integer constants and calculates its
|
|
|
|
// cost. If the constant can be folded into the instruction (the cost is
|
|
|
|
// TCC_Free) or the cost is just a simple operation (TCC_BASIC), then we don't
|
|
|
|
// consider it expensive and leave it alone. This is the default behavior and
|
2019-12-12 03:54:58 +08:00
|
|
|
// the default implementation of getIntImmCostInst will always return TCC_Free.
|
2014-01-25 10:02:55 +08:00
|
|
|
//
|
|
|
|
// If the cost is more than TCC_BASIC, then the integer constant can't be folded
|
|
|
|
// into the instruction and it might be beneficial to hoist the constant.
|
|
|
|
// Similar constants are coalesced to reduce register pressure and
|
|
|
|
// materialization code.
|
|
|
|
//
|
|
|
|
// When a constant is hoisted, it is also hidden behind a bitcast to force it to
|
|
|
|
// be live-out of the basic block. Otherwise the constant would be just
|
|
|
|
// duplicated and each basic block would have its own copy in the SelectionDAG.
|
|
|
|
// The SelectionDAG recognizes such constants as opaque and doesn't perform
|
|
|
|
// certain transformations on them, which would create a new expensive constant.
|
|
|
|
//
|
|
|
|
// This optimization is only applied to integer constants in instructions and
|
2014-03-21 14:04:45 +08:00
|
|
|
// simple (this means not nested) constant cast expressions. For example:
|
2014-01-25 10:02:55 +08:00
|
|
|
// %0 = load i64* inttoptr (i64 big_constant to i64*)
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2016-07-02 08:16:47 +08:00
|
|
|
#include "llvm/Transforms/Scalar/ConstantHoisting.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/ADT/APInt.h"
|
|
|
|
#include "llvm/ADT/DenseMap.h"
|
|
|
|
#include "llvm/ADT/None.h"
|
|
|
|
#include "llvm/ADT/Optional.h"
|
|
|
|
#include "llvm/ADT/SmallPtrSet.h"
|
2014-03-21 14:04:30 +08:00
|
|
|
#include "llvm/ADT/SmallVector.h"
|
2014-01-25 10:02:55 +08:00
|
|
|
#include "llvm/ADT/Statistic.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/Analysis/BlockFrequencyInfo.h"
|
2019-04-16 00:49:00 +08:00
|
|
|
#include "llvm/Analysis/ProfileSummaryInfo.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/Analysis/TargetTransformInfo.h"
|
|
|
|
#include "llvm/IR/BasicBlock.h"
|
2014-01-25 10:02:55 +08:00
|
|
|
#include "llvm/IR/Constants.h"
|
2018-03-22 06:34:23 +08:00
|
|
|
#include "llvm/IR/DebugInfoMetadata.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/IR/Dominators.h"
|
|
|
|
#include "llvm/IR/Function.h"
|
|
|
|
#include "llvm/IR/InstrTypes.h"
|
|
|
|
#include "llvm/IR/Instruction.h"
|
|
|
|
#include "llvm/IR/Instructions.h"
|
2014-01-25 10:02:55 +08:00
|
|
|
#include "llvm/IR/IntrinsicInst.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/IR/Value.h"
|
Sink all InitializePasses.h includes
This file lists every pass in LLVM, and is included by Pass.h, which is
very popular. Every time we add, remove, or rename a pass in LLVM, it
caused lots of recompilation.
I found this fact by looking at this table, which is sorted by the
number of times a file was changed over the last 100,000 git commits
multiplied by the number of object files that depend on it in the
current checkout:
recompiles touches affected_files header
342380 95 3604 llvm/include/llvm/ADT/STLExtras.h
314730 234 1345 llvm/include/llvm/InitializePasses.h
307036 118 2602 llvm/include/llvm/ADT/APInt.h
213049 59 3611 llvm/include/llvm/Support/MathExtras.h
170422 47 3626 llvm/include/llvm/Support/Compiler.h
162225 45 3605 llvm/include/llvm/ADT/Optional.h
158319 63 2513 llvm/include/llvm/ADT/Triple.h
140322 39 3598 llvm/include/llvm/ADT/StringRef.h
137647 59 2333 llvm/include/llvm/Support/Error.h
131619 73 1803 llvm/include/llvm/Support/FileSystem.h
Before this change, touching InitializePasses.h would cause 1345 files
to recompile. After this change, touching it only causes 550 compiles in
an incremental rebuild.
Reviewers: bkramer, asbirlea, bollu, jdoerfert
Differential Revision: https://reviews.llvm.org/D70211
2019-11-14 05:15:01 +08:00
|
|
|
#include "llvm/InitializePasses.h"
|
2014-01-25 10:02:55 +08:00
|
|
|
#include "llvm/Pass.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/Support/BlockFrequency.h"
|
|
|
|
#include "llvm/Support/Casting.h"
|
|
|
|
#include "llvm/Support/CommandLine.h"
|
2014-01-25 10:02:55 +08:00
|
|
|
#include "llvm/Support/Debug.h"
|
2015-03-24 03:32:43 +08:00
|
|
|
#include "llvm/Support/raw_ostream.h"
|
2016-07-02 08:16:47 +08:00
|
|
|
#include "llvm/Transforms/Scalar.h"
|
Sink all InitializePasses.h includes
This file lists every pass in LLVM, and is included by Pass.h, which is
very popular. Every time we add, remove, or rename a pass in LLVM, it
caused lots of recompilation.
I found this fact by looking at this table, which is sorted by the
number of times a file was changed over the last 100,000 git commits
multiplied by the number of object files that depend on it in the
current checkout:
recompiles touches affected_files header
342380 95 3604 llvm/include/llvm/ADT/STLExtras.h
314730 234 1345 llvm/include/llvm/InitializePasses.h
307036 118 2602 llvm/include/llvm/ADT/APInt.h
213049 59 3611 llvm/include/llvm/Support/MathExtras.h
170422 47 3626 llvm/include/llvm/Support/Compiler.h
162225 45 3605 llvm/include/llvm/ADT/Optional.h
158319 63 2513 llvm/include/llvm/ADT/Triple.h
140322 39 3598 llvm/include/llvm/ADT/StringRef.h
137647 59 2333 llvm/include/llvm/Support/Error.h
131619 73 1803 llvm/include/llvm/Support/FileSystem.h
Before this change, touching InitializePasses.h would cause 1345 files
to recompile. After this change, touching it only causes 550 compiles in
an incremental rebuild.
Reviewers: bkramer, asbirlea, bollu, jdoerfert
Differential Revision: https://reviews.llvm.org/D70211
2019-11-14 05:15:01 +08:00
|
|
|
#include "llvm/Transforms/Utils/Local.h"
|
2019-04-16 00:49:00 +08:00
|
|
|
#include "llvm/Transforms/Utils/SizeOpts.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include <algorithm>
|
|
|
|
#include <cassert>
|
|
|
|
#include <cstdint>
|
|
|
|
#include <iterator>
|
2014-04-30 14:44:50 +08:00
|
|
|
#include <tuple>
|
2017-09-14 05:43:53 +08:00
|
|
|
#include <utility>
|
2014-01-25 10:02:55 +08:00
|
|
|
|
|
|
|
using namespace llvm;
|
2016-07-02 08:16:47 +08:00
|
|
|
using namespace consthoist;
|
2014-01-25 10:02:55 +08:00
|
|
|
|
2014-04-22 10:55:47 +08:00
|
|
|
#define DEBUG_TYPE "consthoist"
|
|
|
|
|
2014-01-25 10:02:55 +08:00
|
|
|
STATISTIC(NumConstantsHoisted, "Number of constants hoisted");
|
|
|
|
STATISTIC(NumConstantsRebased, "Number of constants rebased");
|
|
|
|
|
2017-04-21 23:50:16 +08:00
|
|
|
static cl::opt<bool> ConstHoistWithBlockFrequency(
|
2017-07-07 08:11:05 +08:00
|
|
|
"consthoist-with-block-frequency", cl::init(true), cl::Hidden,
|
2017-04-21 23:50:16 +08:00
|
|
|
cl::desc("Enable the use of the block frequency analysis to reduce the "
|
|
|
|
"chance to execute const materialization more frequently than "
|
|
|
|
"without hoisting."));
|
|
|
|
|
2018-09-05 06:17:03 +08:00
|
|
|
static cl::opt<bool> ConstHoistGEP(
|
|
|
|
"consthoist-gep", cl::init(false), cl::Hidden,
|
|
|
|
cl::desc("Try hoisting constant gep expressions"));
|
|
|
|
|
2018-09-26 08:59:09 +08:00
|
|
|
static cl::opt<unsigned>
|
|
|
|
MinNumOfDependentToRebase("consthoist-min-num-to-rebase",
|
|
|
|
cl::desc("Do not rebase if number of dependent constants of a Base is less "
|
|
|
|
"than this number."),
|
|
|
|
cl::init(0), cl::Hidden);
|
|
|
|
|
2014-03-21 04:17:13 +08:00
|
|
|
namespace {
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// The constant hoisting pass.
|
2016-07-02 08:16:47 +08:00
|
|
|
class ConstantHoistingLegacyPass : public FunctionPass {
|
2014-01-25 10:02:55 +08:00
|
|
|
public:
|
|
|
|
static char ID; // Pass identification, replacement for typeid
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2016-07-02 08:16:47 +08:00
|
|
|
ConstantHoistingLegacyPass() : FunctionPass(ID) {
|
|
|
|
initializeConstantHoistingLegacyPassPass(*PassRegistry::getPassRegistry());
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
|
|
|
|
2014-03-21 14:04:36 +08:00
|
|
|
bool runOnFunction(Function &Fn) override;
|
2014-01-25 10:02:55 +08:00
|
|
|
|
2016-10-01 10:56:57 +08:00
|
|
|
StringRef getPassName() const override { return "Constant Hoisting"; }
|
2014-01-25 10:02:55 +08:00
|
|
|
|
2014-03-05 17:10:37 +08:00
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override {
|
2014-01-25 10:02:55 +08:00
|
|
|
AU.setPreservesCFG();
|
2017-04-21 23:50:16 +08:00
|
|
|
if (ConstHoistWithBlockFrequency)
|
|
|
|
AU.addRequired<BlockFrequencyInfoWrapperPass>();
|
2014-01-25 10:02:55 +08:00
|
|
|
AU.addRequired<DominatorTreeWrapperPass>();
|
2019-04-16 00:49:00 +08:00
|
|
|
AU.addRequired<ProfileSummaryInfoWrapperPass>();
|
[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
|
|
|
AU.addRequired<TargetTransformInfoWrapperPass>();
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
|
|
|
|
2016-07-02 08:16:47 +08:00
|
|
|
private:
|
|
|
|
ConstantHoistingPass Impl;
|
2014-01-25 10:02:55 +08:00
|
|
|
};
|
2017-09-14 05:43:53 +08:00
|
|
|
|
|
|
|
} // end anonymous namespace
|
2014-01-25 10:02:55 +08:00
|
|
|
|
2016-07-02 08:16:47 +08:00
|
|
|
char ConstantHoistingLegacyPass::ID = 0;
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2016-07-02 08:16:47 +08:00
|
|
|
INITIALIZE_PASS_BEGIN(ConstantHoistingLegacyPass, "consthoist",
|
|
|
|
"Constant Hoisting", false, false)
|
2017-04-21 23:50:16 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
|
2014-01-25 10:02:55 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
|
2019-04-16 00:49:00 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
|
[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
|
|
|
INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
|
2016-07-02 08:16:47 +08:00
|
|
|
INITIALIZE_PASS_END(ConstantHoistingLegacyPass, "consthoist",
|
|
|
|
"Constant Hoisting", false, false)
|
2014-01-25 10:02:55 +08:00
|
|
|
|
|
|
|
FunctionPass *llvm::createConstantHoistingPass() {
|
2016-07-02 08:16:47 +08:00
|
|
|
return new ConstantHoistingLegacyPass();
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Perform the constant hoisting optimization for the given function.
|
2016-07-02 08:16:47 +08:00
|
|
|
bool ConstantHoistingLegacyPass::runOnFunction(Function &Fn) {
|
2016-04-23 06:06:11 +08:00
|
|
|
if (skipFunction(Fn))
|
2015-02-14 23:11:48 +08:00
|
|
|
return false;
|
|
|
|
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "********** Begin Constant Hoisting **********\n");
|
|
|
|
LLVM_DEBUG(dbgs() << "********** Function: " << Fn.getName() << '\n');
|
2014-03-21 14:04:36 +08:00
|
|
|
|
2017-04-21 23:50:16 +08:00
|
|
|
bool MadeChange =
|
|
|
|
Impl.runImpl(Fn, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(Fn),
|
|
|
|
getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
|
|
|
|
ConstHoistWithBlockFrequency
|
|
|
|
? &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI()
|
|
|
|
: nullptr,
|
2019-04-16 00:49:00 +08:00
|
|
|
Fn.getEntryBlock(),
|
|
|
|
&getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI());
|
2014-03-21 14:04:36 +08:00
|
|
|
|
|
|
|
if (MadeChange) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "********** Function after Constant Hoisting: "
|
|
|
|
<< Fn.getName() << '\n');
|
|
|
|
LLVM_DEBUG(dbgs() << Fn);
|
2014-03-21 14:04:36 +08:00
|
|
|
}
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "********** End Constant Hoisting **********\n");
|
2014-03-21 14:04:36 +08:00
|
|
|
|
|
|
|
return MadeChange;
|
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Find the constant materialization insertion point.
|
2016-07-02 08:16:47 +08:00
|
|
|
Instruction *ConstantHoistingPass::findMatInsertPt(Instruction *Inst,
|
|
|
|
unsigned Idx) const {
|
2014-04-23 02:06:58 +08:00
|
|
|
// If the operand is a cast instruction, then we have to materialize the
|
|
|
|
// constant before the cast instruction.
|
|
|
|
if (Idx != ~0U) {
|
|
|
|
Value *Opnd = Inst->getOperand(Idx);
|
|
|
|
if (auto CastInst = dyn_cast<Instruction>(Opnd))
|
|
|
|
if (CastInst->isCast())
|
|
|
|
return CastInst;
|
|
|
|
}
|
|
|
|
|
|
|
|
// The simple and common case. This also includes constant expressions.
|
2015-08-20 03:54:02 +08:00
|
|
|
if (!isa<PHINode>(Inst) && !Inst->isEHPad())
|
2014-03-21 14:04:36 +08:00
|
|
|
return Inst;
|
|
|
|
|
2015-08-20 03:54:02 +08:00
|
|
|
// We can't insert directly before a phi node or an eh pad. Insert before
|
2014-03-21 14:04:36 +08:00
|
|
|
// the terminator of the incoming or dominating block.
|
|
|
|
assert(Entry != Inst->getParent() && "PHI or landing pad in entry block!");
|
2021-02-02 02:51:29 +08:00
|
|
|
BasicBlock *InsertionBlock = nullptr;
|
|
|
|
if (Idx != ~0U && isa<PHINode>(Inst)) {
|
|
|
|
InsertionBlock = cast<PHINode>(Inst)->getIncomingBlock(Idx);
|
|
|
|
if (!InsertionBlock->isEHPad()) {
|
|
|
|
return InsertionBlock->getTerminator();
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
InsertionBlock = Inst->getParent();
|
|
|
|
}
|
2014-03-21 14:04:36 +08:00
|
|
|
|
2017-03-02 06:41:12 +08:00
|
|
|
// This must be an EH pad. Iterate over immediate dominators until we find a
|
|
|
|
// non-EH pad. We need to skip over catchswitch blocks, which are both EH pads
|
|
|
|
// and terminators.
|
2021-02-02 02:51:29 +08:00
|
|
|
auto *IDom = DT->getNode(InsertionBlock)->getIDom();
|
2017-03-02 06:41:12 +08:00
|
|
|
while (IDom->getBlock()->isEHPad()) {
|
|
|
|
assert(Entry != IDom->getBlock() && "eh pad in entry block");
|
|
|
|
IDom = IDom->getIDom();
|
|
|
|
}
|
|
|
|
|
|
|
|
return IDom->getBlock()->getTerminator();
|
2014-03-21 14:04:36 +08:00
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Given \p BBs as input, find another set of BBs which collectively
|
2017-04-21 23:50:16 +08:00
|
|
|
/// dominates \p BBs and have the minimal sum of frequencies. Return the BB
|
|
|
|
/// set found in \p BBs.
|
2017-05-27 04:09:00 +08:00
|
|
|
static void findBestInsertionSet(DominatorTree &DT, BlockFrequencyInfo &BFI,
|
|
|
|
BasicBlock *Entry,
|
2019-09-12 02:55:00 +08:00
|
|
|
SetVector<BasicBlock *> &BBs) {
|
2017-04-21 23:50:16 +08:00
|
|
|
assert(!BBs.count(Entry) && "Assume Entry is not in BBs");
|
|
|
|
// Nodes on the current path to the root.
|
|
|
|
SmallPtrSet<BasicBlock *, 8> Path;
|
|
|
|
// Candidates includes any block 'BB' in set 'BBs' that is not strictly
|
|
|
|
// dominated by any other blocks in set 'BBs', and all nodes in the path
|
|
|
|
// in the dominator tree from Entry to 'BB'.
|
|
|
|
SmallPtrSet<BasicBlock *, 16> Candidates;
|
|
|
|
for (auto BB : BBs) {
|
2019-03-05 04:57:14 +08:00
|
|
|
// Ignore unreachable basic blocks.
|
|
|
|
if (!DT.isReachableFromEntry(BB))
|
|
|
|
continue;
|
2017-04-21 23:50:16 +08:00
|
|
|
Path.clear();
|
|
|
|
// Walk up the dominator tree until Entry or another BB in BBs
|
|
|
|
// is reached. Insert the nodes on the way to the Path.
|
|
|
|
BasicBlock *Node = BB;
|
|
|
|
// The "Path" is a candidate path to be added into Candidates set.
|
|
|
|
bool isCandidate = false;
|
|
|
|
do {
|
|
|
|
Path.insert(Node);
|
|
|
|
if (Node == Entry || Candidates.count(Node)) {
|
|
|
|
isCandidate = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
assert(DT.getNode(Node)->getIDom() &&
|
|
|
|
"Entry doens't dominate current Node");
|
|
|
|
Node = DT.getNode(Node)->getIDom()->getBlock();
|
|
|
|
} while (!BBs.count(Node));
|
|
|
|
|
|
|
|
// If isCandidate is false, Node is another Block in BBs dominating
|
|
|
|
// current 'BB'. Drop the nodes on the Path.
|
|
|
|
if (!isCandidate)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// Add nodes on the Path into Candidates.
|
|
|
|
Candidates.insert(Path.begin(), Path.end());
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sort the nodes in Candidates in top-down order and save the nodes
|
|
|
|
// in Orders.
|
|
|
|
unsigned Idx = 0;
|
|
|
|
SmallVector<BasicBlock *, 16> Orders;
|
|
|
|
Orders.push_back(Entry);
|
|
|
|
while (Idx != Orders.size()) {
|
|
|
|
BasicBlock *Node = Orders[Idx++];
|
DomTree: Remove getChildren() accessor
Summary:
Avoid exposing details about how children are stored. This will enable
subsequent type-erasure changes.
New methods are introduced to cover common access patterns.
Change-Id: Idb5f4b1b9c84e4cc71ddb39bb52a388682f5674f
Reviewers: arsenm, RKSimon, mehdi_amini, courbet
Subscribers: qcolombet, sdardis, wdng, hiraditya, jrtc27, zzheng, atanasyan, asbirlea, llvm-commits
Tags: #llvm
Differential Revision: https://reviews.llvm.org/D83083
2020-05-18 22:28:24 +08:00
|
|
|
for (auto ChildDomNode : DT.getNode(Node)->children()) {
|
2017-04-21 23:50:16 +08:00
|
|
|
if (Candidates.count(ChildDomNode->getBlock()))
|
|
|
|
Orders.push_back(ChildDomNode->getBlock());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Visit Orders in bottom-up order.
|
2017-09-14 05:43:53 +08:00
|
|
|
using InsertPtsCostPair =
|
2019-09-12 02:55:00 +08:00
|
|
|
std::pair<SetVector<BasicBlock *>, BlockFrequency>;
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2017-04-21 23:50:16 +08:00
|
|
|
// InsertPtsMap is a map from a BB to the best insertion points for the
|
|
|
|
// subtree of BB (subtree not including the BB itself).
|
|
|
|
DenseMap<BasicBlock *, InsertPtsCostPair> InsertPtsMap;
|
|
|
|
InsertPtsMap.reserve(Orders.size() + 1);
|
|
|
|
for (auto RIt = Orders.rbegin(); RIt != Orders.rend(); RIt++) {
|
|
|
|
BasicBlock *Node = *RIt;
|
|
|
|
bool NodeInBBs = BBs.count(Node);
|
2019-09-12 02:55:00 +08:00
|
|
|
auto &InsertPts = InsertPtsMap[Node].first;
|
2017-04-21 23:50:16 +08:00
|
|
|
BlockFrequency &InsertPtsFreq = InsertPtsMap[Node].second;
|
|
|
|
|
|
|
|
// Return the optimal insert points in BBs.
|
|
|
|
if (Node == Entry) {
|
|
|
|
BBs.clear();
|
2017-07-07 06:32:27 +08:00
|
|
|
if (InsertPtsFreq > BFI.getBlockFreq(Node) ||
|
|
|
|
(InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1))
|
2017-04-21 23:50:16 +08:00
|
|
|
BBs.insert(Entry);
|
|
|
|
else
|
|
|
|
BBs.insert(InsertPts.begin(), InsertPts.end());
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
BasicBlock *Parent = DT.getNode(Node)->getIDom()->getBlock();
|
|
|
|
// Initially, ParentInsertPts is empty and ParentPtsFreq is 0. Every child
|
|
|
|
// will update its parent's ParentInsertPts and ParentPtsFreq.
|
2019-09-12 02:55:00 +08:00
|
|
|
auto &ParentInsertPts = InsertPtsMap[Parent].first;
|
2017-04-21 23:50:16 +08:00
|
|
|
BlockFrequency &ParentPtsFreq = InsertPtsMap[Parent].second;
|
|
|
|
// Choose to insert in Node or in subtree of Node.
|
2017-07-07 06:32:27 +08:00
|
|
|
// Don't hoist to EHPad because we may not find a proper place to insert
|
|
|
|
// in EHPad.
|
|
|
|
// If the total frequency of InsertPts is the same as the frequency of the
|
|
|
|
// target Node, and InsertPts contains more than one nodes, choose hoisting
|
|
|
|
// to reduce code size.
|
|
|
|
if (NodeInBBs ||
|
|
|
|
(!Node->isEHPad() &&
|
|
|
|
(InsertPtsFreq > BFI.getBlockFreq(Node) ||
|
|
|
|
(InsertPtsFreq == BFI.getBlockFreq(Node) && InsertPts.size() > 1)))) {
|
2017-04-21 23:50:16 +08:00
|
|
|
ParentInsertPts.insert(Node);
|
|
|
|
ParentPtsFreq += BFI.getBlockFreq(Node);
|
|
|
|
} else {
|
|
|
|
ParentInsertPts.insert(InsertPts.begin(), InsertPts.end());
|
|
|
|
ParentPtsFreq += InsertPtsFreq;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Find an insertion point that dominates all uses.
|
2019-09-12 02:55:00 +08:00
|
|
|
SetVector<Instruction *> ConstantHoistingPass::findConstantInsertionPoint(
|
2016-07-02 08:16:47 +08:00
|
|
|
const ConstantInfo &ConstInfo) const {
|
2014-03-21 14:04:36 +08:00
|
|
|
assert(!ConstInfo.RebasedConstants.empty() && "Invalid constant info entry.");
|
2014-04-03 09:38:47 +08:00
|
|
|
// Collect all basic blocks.
|
2019-09-12 02:55:00 +08:00
|
|
|
SetVector<BasicBlock *> BBs;
|
|
|
|
SetVector<Instruction *> InsertPts;
|
2014-03-21 14:04:36 +08:00
|
|
|
for (auto const &RCI : ConstInfo.RebasedConstants)
|
2014-04-03 09:38:47 +08:00
|
|
|
for (auto const &U : RCI.Uses)
|
2014-04-23 02:06:58 +08:00
|
|
|
BBs.insert(findMatInsertPt(U.Inst, U.OpndIdx)->getParent());
|
2014-01-25 10:02:55 +08:00
|
|
|
|
2017-04-21 23:50:16 +08:00
|
|
|
if (BBs.count(Entry)) {
|
|
|
|
InsertPts.insert(&Entry->front());
|
|
|
|
return InsertPts;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (BFI) {
|
|
|
|
findBestInsertionSet(*DT, *BFI, Entry, BBs);
|
|
|
|
for (auto BB : BBs) {
|
|
|
|
BasicBlock::iterator InsertPt = BB->begin();
|
|
|
|
for (; isa<PHINode>(InsertPt) || InsertPt->isEHPad(); ++InsertPt)
|
|
|
|
;
|
|
|
|
InsertPts.insert(&*InsertPt);
|
|
|
|
}
|
|
|
|
return InsertPts;
|
|
|
|
}
|
2014-01-25 10:02:55 +08:00
|
|
|
|
2014-03-21 14:04:36 +08:00
|
|
|
while (BBs.size() >= 2) {
|
|
|
|
BasicBlock *BB, *BB1, *BB2;
|
2019-09-12 02:55:00 +08:00
|
|
|
BB1 = BBs.pop_back_val();
|
|
|
|
BB2 = BBs.pop_back_val();
|
2014-03-21 14:04:36 +08:00
|
|
|
BB = DT->findNearestCommonDominator(BB1, BB2);
|
2017-04-21 23:50:16 +08:00
|
|
|
if (BB == Entry) {
|
|
|
|
InsertPts.insert(&Entry->front());
|
|
|
|
return InsertPts;
|
|
|
|
}
|
2014-03-21 14:04:36 +08:00
|
|
|
BBs.insert(BB);
|
|
|
|
}
|
|
|
|
assert((BBs.size() == 1) && "Expected only one element.");
|
|
|
|
Instruction &FirstInst = (*BBs.begin())->front();
|
2017-04-21 23:50:16 +08:00
|
|
|
InsertPts.insert(findMatInsertPt(&FirstInst));
|
|
|
|
return InsertPts;
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Record constant integer ConstInt for instruction Inst at operand
|
2014-03-21 14:04:36 +08:00
|
|
|
/// index Idx.
|
|
|
|
///
|
2014-03-21 14:04:45 +08:00
|
|
|
/// The operand at index Idx is not necessarily the constant integer itself. It
|
2014-03-21 14:04:36 +08:00
|
|
|
/// could also be a cast instruction or a constant expression that uses the
|
2018-09-05 06:17:03 +08:00
|
|
|
/// constant integer.
|
2016-07-02 08:16:47 +08:00
|
|
|
void ConstantHoistingPass::collectConstantCandidates(
|
|
|
|
ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
|
|
|
|
ConstantInt *ConstInt) {
|
2021-01-27 23:01:16 +08:00
|
|
|
InstructionCost Cost;
|
2014-03-21 14:04:36 +08:00
|
|
|
// Ask the target about the cost of materializing the constant for the given
|
2014-03-21 14:04:45 +08:00
|
|
|
// instruction and operand index.
|
2014-03-21 14:04:36 +08:00
|
|
|
if (auto IntrInst = dyn_cast<IntrinsicInst>(Inst))
|
2019-12-12 03:54:58 +08:00
|
|
|
Cost = TTI->getIntImmCostIntrin(IntrInst->getIntrinsicID(), Idx,
|
2020-04-28 21:11:27 +08:00
|
|
|
ConstInt->getValue(), ConstInt->getType(),
|
|
|
|
TargetTransformInfo::TCK_SizeAndLatency);
|
2014-01-25 10:02:55 +08:00
|
|
|
else
|
2020-09-22 19:54:10 +08:00
|
|
|
Cost = TTI->getIntImmCostInst(
|
|
|
|
Inst->getOpcode(), Idx, ConstInt->getValue(), ConstInt->getType(),
|
|
|
|
TargetTransformInfo::TCK_SizeAndLatency, Inst);
|
2014-01-25 10:02:55 +08:00
|
|
|
|
2014-03-21 14:04:30 +08:00
|
|
|
// Ignore cheap integer constants.
|
2014-01-25 10:02:55 +08:00
|
|
|
if (Cost > TargetTransformInfo::TCC_Basic) {
|
2014-03-21 14:04:30 +08:00
|
|
|
ConstCandMapType::iterator Itr;
|
|
|
|
bool Inserted;
|
2018-09-05 06:17:03 +08:00
|
|
|
ConstPtrUnionType Cand = ConstInt;
|
|
|
|
std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
|
2014-03-21 14:04:30 +08:00
|
|
|
if (Inserted) {
|
2018-09-05 06:17:03 +08:00
|
|
|
ConstIntCandVec.push_back(ConstantCandidate(ConstInt));
|
|
|
|
Itr->second = ConstIntCandVec.size() - 1;
|
2014-03-21 14:04:30 +08:00
|
|
|
}
|
2021-01-27 23:01:16 +08:00
|
|
|
ConstIntCandVec[Itr->second].addUser(Inst, Idx, *Cost.getValue());
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(if (isa<ConstantInt>(Inst->getOperand(Idx))) dbgs()
|
|
|
|
<< "Collect constant " << *ConstInt << " from " << *Inst
|
2014-03-21 14:04:36 +08:00
|
|
|
<< " with cost " << Cost << '\n';
|
2018-05-14 20:53:11 +08:00
|
|
|
else dbgs() << "Collect constant " << *ConstInt
|
|
|
|
<< " indirectly from " << *Inst << " via "
|
|
|
|
<< *Inst->getOperand(Idx) << " with cost " << Cost
|
|
|
|
<< '\n';);
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-05 06:17:03 +08:00
|
|
|
/// Record constant GEP expression for instruction Inst at operand index Idx.
|
|
|
|
void ConstantHoistingPass::collectConstantCandidates(
|
|
|
|
ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx,
|
|
|
|
ConstantExpr *ConstExpr) {
|
|
|
|
// TODO: Handle vector GEPs
|
|
|
|
if (ConstExpr->getType()->isVectorTy())
|
|
|
|
return;
|
|
|
|
|
|
|
|
GlobalVariable *BaseGV = dyn_cast<GlobalVariable>(ConstExpr->getOperand(0));
|
|
|
|
if (!BaseGV)
|
|
|
|
return;
|
|
|
|
|
|
|
|
// Get offset from the base GV.
|
2019-09-23 01:45:05 +08:00
|
|
|
PointerType *GVPtrTy = cast<PointerType>(BaseGV->getType());
|
2018-09-05 06:17:03 +08:00
|
|
|
IntegerType *PtrIntTy = DL->getIntPtrType(*Ctx, GVPtrTy->getAddressSpace());
|
|
|
|
APInt Offset(DL->getTypeSizeInBits(PtrIntTy), /*val*/0, /*isSigned*/true);
|
|
|
|
auto *GEPO = cast<GEPOperator>(ConstExpr);
|
|
|
|
if (!GEPO->accumulateConstantOffset(*DL, Offset))
|
|
|
|
return;
|
|
|
|
|
|
|
|
if (!Offset.isIntN(32))
|
|
|
|
return;
|
|
|
|
|
|
|
|
// A constant GEP expression that has a GlobalVariable as base pointer is
|
|
|
|
// usually lowered to a load from constant pool. Such operation is unlikely
|
|
|
|
// to be cheaper than compute it by <Base + Offset>, which can be lowered to
|
|
|
|
// an ADD instruction or folded into Load/Store instruction.
|
2021-01-27 23:01:16 +08:00
|
|
|
InstructionCost Cost =
|
2020-09-22 19:54:10 +08:00
|
|
|
TTI->getIntImmCostInst(Instruction::Add, 1, Offset, PtrIntTy,
|
|
|
|
TargetTransformInfo::TCK_SizeAndLatency, Inst);
|
2018-09-05 06:17:03 +08:00
|
|
|
ConstCandVecType &ExprCandVec = ConstGEPCandMap[BaseGV];
|
|
|
|
ConstCandMapType::iterator Itr;
|
|
|
|
bool Inserted;
|
|
|
|
ConstPtrUnionType Cand = ConstExpr;
|
|
|
|
std::tie(Itr, Inserted) = ConstCandMap.insert(std::make_pair(Cand, 0));
|
|
|
|
if (Inserted) {
|
|
|
|
ExprCandVec.push_back(ConstantCandidate(
|
|
|
|
ConstantInt::get(Type::getInt32Ty(*Ctx), Offset.getLimitedValue()),
|
|
|
|
ConstExpr));
|
|
|
|
Itr->second = ExprCandVec.size() - 1;
|
|
|
|
}
|
2021-01-27 23:01:16 +08:00
|
|
|
ExprCandVec[Itr->second].addUser(Inst, Idx, *Cost.getValue());
|
2018-09-05 06:17:03 +08:00
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Check the operand for instruction Inst at index Idx.
|
2017-06-30 01:03:34 +08:00
|
|
|
void ConstantHoistingPass::collectConstantCandidates(
|
|
|
|
ConstCandMapType &ConstCandMap, Instruction *Inst, unsigned Idx) {
|
|
|
|
Value *Opnd = Inst->getOperand(Idx);
|
|
|
|
|
|
|
|
// Visit constant integers.
|
|
|
|
if (auto ConstInt = dyn_cast<ConstantInt>(Opnd)) {
|
|
|
|
collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Visit cast instructions that have constant integers.
|
|
|
|
if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
|
|
|
|
// Only visit cast instructions, which have been skipped. All other
|
|
|
|
// instructions should have already been visited.
|
|
|
|
if (!CastInst->isCast())
|
|
|
|
return;
|
|
|
|
|
|
|
|
if (auto *ConstInt = dyn_cast<ConstantInt>(CastInst->getOperand(0))) {
|
|
|
|
// Pretend the constant is directly used by the instruction and ignore
|
|
|
|
// the cast instruction.
|
|
|
|
collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Visit constant expressions that have constant integers.
|
|
|
|
if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
|
2018-09-05 06:17:03 +08:00
|
|
|
// Handle constant gep expressions.
|
|
|
|
if (ConstHoistGEP && ConstExpr->isGEPWithNoNotionalOverIndexing())
|
|
|
|
collectConstantCandidates(ConstCandMap, Inst, Idx, ConstExpr);
|
|
|
|
|
2017-06-30 01:03:34 +08:00
|
|
|
// Only visit constant cast expressions.
|
|
|
|
if (!ConstExpr->isCast())
|
|
|
|
return;
|
|
|
|
|
|
|
|
if (auto ConstInt = dyn_cast<ConstantInt>(ConstExpr->getOperand(0))) {
|
|
|
|
// Pretend the constant is directly used by the instruction and ignore
|
|
|
|
// the constant expression.
|
|
|
|
collectConstantCandidates(ConstCandMap, Inst, Idx, ConstInt);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Scan the instruction for expensive integer constants and record them
|
2014-03-21 14:04:36 +08:00
|
|
|
/// in the constant candidate vector.
|
2016-07-02 08:16:47 +08:00
|
|
|
void ConstantHoistingPass::collectConstantCandidates(
|
|
|
|
ConstCandMapType &ConstCandMap, Instruction *Inst) {
|
2014-03-21 14:04:36 +08:00
|
|
|
// Skip all cast instructions. They are visited indirectly later on.
|
|
|
|
if (Inst->isCast())
|
|
|
|
return;
|
|
|
|
|
2017-06-30 01:03:34 +08:00
|
|
|
// Scan all operands.
|
|
|
|
for (unsigned Idx = 0, E = Inst->getNumOperands(); Idx != E; ++Idx) {
|
2017-07-11 04:45:34 +08:00
|
|
|
// The cost of materializing the constants (defined in
|
2019-12-12 03:54:58 +08:00
|
|
|
// `TargetTransformInfo::getIntImmCostInst`) for instructions which only
|
|
|
|
// take constant variables is lower than `TargetTransformInfo::TCC_Basic`.
|
|
|
|
// So it's safe for us to collect constant candidates from all
|
|
|
|
// IntrinsicInsts.
|
2019-02-14 07:28:16 +08:00
|
|
|
if (canReplaceOperandWithVariable(Inst, Idx)) {
|
2017-07-11 04:45:34 +08:00
|
|
|
collectConstantCandidates(ConstCandMap, Inst, Idx);
|
|
|
|
}
|
2014-03-21 14:04:36 +08:00
|
|
|
} // end of for all operands
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Collect all integer constants in the function that cannot be folded
|
2014-01-25 10:02:55 +08:00
|
|
|
/// into an instruction itself.
|
2016-07-02 08:16:47 +08:00
|
|
|
void ConstantHoistingPass::collectConstantCandidates(Function &Fn) {
|
2014-03-26 05:21:10 +08:00
|
|
|
ConstCandMapType ConstCandMap;
|
2019-12-18 20:30:47 +08:00
|
|
|
for (BasicBlock &BB : Fn) {
|
|
|
|
// Ignore unreachable basic blocks.
|
|
|
|
if (!DT->isReachableFromEntry(&BB))
|
|
|
|
continue;
|
2015-10-14 02:26:00 +08:00
|
|
|
for (Instruction &Inst : BB)
|
|
|
|
collectConstantCandidates(ConstCandMap, &Inst);
|
2019-12-18 20:30:47 +08:00
|
|
|
}
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
|
|
|
|
2016-07-14 15:44:20 +08:00
|
|
|
// This helper function is necessary to deal with values that have different
|
|
|
|
// bit widths (APInt Operator- does not like that). If the value cannot be
|
|
|
|
// represented in uint64 we return an "empty" APInt. This is then interpreted
|
|
|
|
// as the value is not in range.
|
2017-09-14 05:43:53 +08:00
|
|
|
static Optional<APInt> calculateOffsetDiff(const APInt &V1, const APInt &V2) {
|
|
|
|
Optional<APInt> Res = None;
|
2016-07-14 15:44:20 +08:00
|
|
|
unsigned BW = V1.getBitWidth() > V2.getBitWidth() ?
|
|
|
|
V1.getBitWidth() : V2.getBitWidth();
|
|
|
|
uint64_t LimVal1 = V1.getLimitedValue();
|
|
|
|
uint64_t LimVal2 = V2.getLimitedValue();
|
|
|
|
|
|
|
|
if (LimVal1 == ~0ULL || LimVal2 == ~0ULL)
|
|
|
|
return Res;
|
|
|
|
|
|
|
|
uint64_t Diff = LimVal1 - LimVal2;
|
|
|
|
return APInt(BW, Diff, true);
|
|
|
|
}
|
|
|
|
|
|
|
|
// From a list of constants, one needs to picked as the base and the other
|
|
|
|
// constants will be transformed into an offset from that base constant. The
|
|
|
|
// question is which we can pick best? For example, consider these constants
|
|
|
|
// and their number of uses:
|
|
|
|
//
|
|
|
|
// Constants| 2 | 4 | 12 | 42 |
|
|
|
|
// NumUses | 3 | 2 | 8 | 7 |
|
|
|
|
//
|
|
|
|
// Selecting constant 12 because it has the most uses will generate negative
|
|
|
|
// offsets for constants 2 and 4 (i.e. -10 and -8 respectively). If negative
|
|
|
|
// offsets lead to less optimal code generation, then there might be better
|
|
|
|
// solutions. Suppose immediates in the range of 0..35 are most optimally
|
|
|
|
// supported by the architecture, then selecting constant 2 is most optimal
|
|
|
|
// because this will generate offsets: 0, 2, 10, 40. Offsets 0, 2 and 10 are in
|
|
|
|
// range 0..35, and thus 3 + 2 + 8 = 13 uses are in range. Selecting 12 would
|
|
|
|
// have only 8 uses in range, so choosing 2 as a base is more optimal. Thus, in
|
|
|
|
// selecting the base constant the range of the offsets is a very important
|
|
|
|
// factor too that we take into account here. This algorithm calculates a total
|
|
|
|
// costs for selecting a constant as the base and substract the costs if
|
|
|
|
// immediates are out of range. It has quadratic complexity, so we call this
|
|
|
|
// function only when we're optimising for size and there are less than 100
|
|
|
|
// constants, we fall back to the straightforward algorithm otherwise
|
|
|
|
// which does not do all the offset calculations.
|
|
|
|
unsigned
|
|
|
|
ConstantHoistingPass::maximizeConstantsInRange(ConstCandVecType::iterator S,
|
|
|
|
ConstCandVecType::iterator E,
|
|
|
|
ConstCandVecType::iterator &MaxCostItr) {
|
2014-01-25 10:02:55 +08:00
|
|
|
unsigned NumUses = 0;
|
2016-07-14 15:44:20 +08:00
|
|
|
|
2019-04-16 00:49:00 +08:00
|
|
|
bool OptForSize = Entry->getParent()->hasOptSize() ||
|
2019-11-21 05:08:07 +08:00
|
|
|
llvm::shouldOptimizeForSize(Entry->getParent(), PSI, BFI,
|
|
|
|
PGSOQueryType::IRPass);
|
2019-04-16 00:49:00 +08:00
|
|
|
if (!OptForSize || std::distance(S,E) > 100) {
|
2016-07-14 15:44:20 +08:00
|
|
|
for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
|
|
|
|
NumUses += ConstCand->Uses.size();
|
|
|
|
if (ConstCand->CumulativeCost > MaxCostItr->CumulativeCost)
|
|
|
|
MaxCostItr = ConstCand;
|
|
|
|
}
|
|
|
|
return NumUses;
|
|
|
|
}
|
|
|
|
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "== Maximize constants in range ==\n");
|
2021-01-27 23:01:16 +08:00
|
|
|
InstructionCost MaxCost = -1;
|
2014-03-21 14:04:36 +08:00
|
|
|
for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
|
2016-07-14 15:44:20 +08:00
|
|
|
auto Value = ConstCand->ConstInt->getValue();
|
|
|
|
Type *Ty = ConstCand->ConstInt->getType();
|
2021-01-27 23:01:16 +08:00
|
|
|
InstructionCost Cost = 0;
|
2014-03-21 14:04:36 +08:00
|
|
|
NumUses += ConstCand->Uses.size();
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "= Constant: " << ConstCand->ConstInt->getValue()
|
|
|
|
<< "\n");
|
2016-07-14 15:44:20 +08:00
|
|
|
|
|
|
|
for (auto User : ConstCand->Uses) {
|
|
|
|
unsigned Opcode = User.Inst->getOpcode();
|
|
|
|
unsigned OpndIdx = User.OpndIdx;
|
2020-04-28 21:11:27 +08:00
|
|
|
Cost += TTI->getIntImmCostInst(Opcode, OpndIdx, Value, Ty,
|
|
|
|
TargetTransformInfo::TCK_SizeAndLatency);
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "Cost: " << Cost << "\n");
|
2016-07-14 15:44:20 +08:00
|
|
|
|
|
|
|
for (auto C2 = S; C2 != E; ++C2) {
|
2017-09-14 05:43:53 +08:00
|
|
|
Optional<APInt> Diff = calculateOffsetDiff(
|
|
|
|
C2->ConstInt->getValue(),
|
|
|
|
ConstCand->ConstInt->getValue());
|
2016-07-14 15:44:20 +08:00
|
|
|
if (Diff) {
|
2021-01-27 23:01:16 +08:00
|
|
|
const InstructionCost ImmCosts =
|
|
|
|
TTI->getIntImmCodeSizeCost(Opcode, OpndIdx, Diff.getValue(), Ty);
|
2016-07-14 15:44:20 +08:00
|
|
|
Cost -= ImmCosts;
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "Offset " << Diff.getValue() << " "
|
|
|
|
<< "has penalty: " << ImmCosts << "\n"
|
|
|
|
<< "Adjusted cost: " << Cost << "\n");
|
2016-07-14 15:44:20 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "Cumulative cost: " << Cost << "\n");
|
2016-07-14 15:44:20 +08:00
|
|
|
if (Cost > MaxCost) {
|
|
|
|
MaxCost = Cost;
|
2014-03-21 14:04:36 +08:00
|
|
|
MaxCostItr = ConstCand;
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "New candidate: " << MaxCostItr->ConstInt->getValue()
|
|
|
|
<< "\n");
|
2016-07-14 15:44:20 +08:00
|
|
|
}
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
2016-07-14 15:44:20 +08:00
|
|
|
return NumUses;
|
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Find the base constant within the given range and rebase all other
|
2016-07-14 15:44:20 +08:00
|
|
|
/// constants with respect to the base constant.
|
|
|
|
void ConstantHoistingPass::findAndMakeBaseConstant(
|
2018-09-05 06:17:03 +08:00
|
|
|
ConstCandVecType::iterator S, ConstCandVecType::iterator E,
|
|
|
|
SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec) {
|
2016-07-14 15:44:20 +08:00
|
|
|
auto MaxCostItr = S;
|
|
|
|
unsigned NumUses = maximizeConstantsInRange(S, E, MaxCostItr);
|
2014-01-25 10:02:55 +08:00
|
|
|
|
|
|
|
// Don't hoist constants that have only one use.
|
|
|
|
if (NumUses <= 1)
|
|
|
|
return;
|
|
|
|
|
2018-09-05 06:17:03 +08:00
|
|
|
ConstantInt *ConstInt = MaxCostItr->ConstInt;
|
|
|
|
ConstantExpr *ConstExpr = MaxCostItr->ConstExpr;
|
2014-03-21 14:04:36 +08:00
|
|
|
ConstantInfo ConstInfo;
|
2018-09-05 06:17:03 +08:00
|
|
|
ConstInfo.BaseInt = ConstInt;
|
|
|
|
ConstInfo.BaseExpr = ConstExpr;
|
|
|
|
Type *Ty = ConstInt->getType();
|
2014-03-21 14:04:36 +08:00
|
|
|
|
2014-01-25 10:02:55 +08:00
|
|
|
// Rebase the constants with respect to the base constant.
|
2014-03-21 14:04:36 +08:00
|
|
|
for (auto ConstCand = S; ConstCand != E; ++ConstCand) {
|
2018-09-05 06:17:03 +08:00
|
|
|
APInt Diff = ConstCand->ConstInt->getValue() - ConstInt->getValue();
|
2014-03-21 14:04:36 +08:00
|
|
|
Constant *Offset = Diff == 0 ? nullptr : ConstantInt::get(Ty, Diff);
|
2018-09-05 06:17:03 +08:00
|
|
|
Type *ConstTy =
|
|
|
|
ConstCand->ConstExpr ? ConstCand->ConstExpr->getType() : nullptr;
|
2014-03-21 14:04:36 +08:00
|
|
|
ConstInfo.RebasedConstants.push_back(
|
2018-09-05 06:17:03 +08:00
|
|
|
RebasedConstantInfo(std::move(ConstCand->Uses), Offset, ConstTy));
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
2018-09-05 06:17:03 +08:00
|
|
|
ConstInfoVec.push_back(std::move(ConstInfo));
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Finds and combines constant candidates that can be easily
|
2014-03-21 14:04:36 +08:00
|
|
|
/// rematerialized with an add from a common base constant.
|
2018-09-05 06:17:03 +08:00
|
|
|
void ConstantHoistingPass::findBaseConstants(GlobalVariable *BaseGV) {
|
|
|
|
// If BaseGV is nullptr, find base among candidate constant integers;
|
|
|
|
// Otherwise find base among constant GEPs that share the same BaseGV.
|
|
|
|
ConstCandVecType &ConstCandVec = BaseGV ?
|
|
|
|
ConstGEPCandMap[BaseGV] : ConstIntCandVec;
|
|
|
|
ConstInfoVecType &ConstInfoVec = BaseGV ?
|
|
|
|
ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
|
|
|
|
|
2014-03-21 14:04:36 +08:00
|
|
|
// Sort the constants by value and type. This invalidates the mapping!
|
2019-04-23 22:51:27 +08:00
|
|
|
llvm::stable_sort(ConstCandVec, [](const ConstantCandidate &LHS,
|
|
|
|
const ConstantCandidate &RHS) {
|
2014-03-21 14:04:30 +08:00
|
|
|
if (LHS.ConstInt->getType() != RHS.ConstInt->getType())
|
|
|
|
return LHS.ConstInt->getType()->getBitWidth() <
|
|
|
|
RHS.ConstInt->getType()->getBitWidth();
|
|
|
|
return LHS.ConstInt->getValue().ult(RHS.ConstInt->getValue());
|
2014-03-21 04:17:13 +08:00
|
|
|
});
|
|
|
|
|
2014-03-21 14:04:36 +08:00
|
|
|
// Simple linear scan through the sorted constant candidate vector for viable
|
|
|
|
// merge candidates.
|
|
|
|
auto MinValItr = ConstCandVec.begin();
|
|
|
|
for (auto CC = std::next(ConstCandVec.begin()), E = ConstCandVec.end();
|
|
|
|
CC != E; ++CC) {
|
|
|
|
if (MinValItr->ConstInt->getType() == CC->ConstInt->getType()) {
|
2018-08-29 07:00:59 +08:00
|
|
|
Type *MemUseValTy = nullptr;
|
|
|
|
for (auto &U : CC->Uses) {
|
|
|
|
auto *UI = U.Inst;
|
|
|
|
if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
|
|
|
|
MemUseValTy = LI->getType();
|
|
|
|
break;
|
|
|
|
} else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
|
|
|
|
// Make sure the constant is used as pointer operand of the StoreInst.
|
|
|
|
if (SI->getPointerOperand() == SI->getOperand(U.OpndIdx)) {
|
|
|
|
MemUseValTy = SI->getValueOperand()->getType();
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-01-25 10:02:55 +08:00
|
|
|
// Check if the constant is in range of an add with immediate.
|
2014-03-21 14:04:36 +08:00
|
|
|
APInt Diff = CC->ConstInt->getValue() - MinValItr->ConstInt->getValue();
|
2014-01-25 10:02:55 +08:00
|
|
|
if ((Diff.getBitWidth() <= 64) &&
|
2018-08-29 07:00:59 +08:00
|
|
|
TTI->isLegalAddImmediate(Diff.getSExtValue()) &&
|
|
|
|
// Check if Diff can be used as offset in addressing mode of the user
|
|
|
|
// memory instruction.
|
|
|
|
(!MemUseValTy || TTI->isLegalAddressingMode(MemUseValTy,
|
|
|
|
/*BaseGV*/nullptr, /*BaseOffset*/Diff.getSExtValue(),
|
|
|
|
/*HasBaseReg*/true, /*Scale*/0)))
|
2014-01-25 10:02:55 +08:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
// We either have now a different constant type or the constant is not in
|
|
|
|
// range of an add with immediate anymore.
|
2018-09-05 06:17:03 +08:00
|
|
|
findAndMakeBaseConstant(MinValItr, CC, ConstInfoVec);
|
2014-01-25 10:02:55 +08:00
|
|
|
// Start a new base constant search.
|
2014-03-21 14:04:36 +08:00
|
|
|
MinValItr = CC;
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
|
|
|
// Finalize the last base constant search.
|
2018-09-05 06:17:03 +08:00
|
|
|
findAndMakeBaseConstant(MinValItr, ConstCandVec.end(), ConstInfoVec);
|
2014-01-27 21:11:43 +08:00
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Updates the operand at Idx in instruction Inst with the result of
|
2014-03-22 09:49:27 +08:00
|
|
|
/// instruction Mat. If the instruction is a PHI node then special
|
2016-11-20 21:19:49 +08:00
|
|
|
/// handling for duplicate values form the same incoming basic block is
|
2014-03-22 09:49:27 +08:00
|
|
|
/// required.
|
|
|
|
/// \return The update will always succeed, but the return value indicated if
|
|
|
|
/// Mat was used for the update or not.
|
|
|
|
static bool updateOperand(Instruction *Inst, unsigned Idx, Instruction *Mat) {
|
|
|
|
if (auto PHI = dyn_cast<PHINode>(Inst)) {
|
|
|
|
// Check if any previous operand of the PHI node has the same incoming basic
|
|
|
|
// block. This is a very odd case that happens when the incoming basic block
|
|
|
|
// has a switch statement. In this case use the same value as the previous
|
|
|
|
// operand(s), otherwise we will fail verification due to different values.
|
|
|
|
// The values are actually the same, but the variable names are different
|
|
|
|
// and the verifier doesn't like that.
|
|
|
|
BasicBlock *IncomingBB = PHI->getIncomingBlock(Idx);
|
|
|
|
for (unsigned i = 0; i < Idx; ++i) {
|
|
|
|
if (PHI->getIncomingBlock(i) == IncomingBB) {
|
|
|
|
Value *IncomingVal = PHI->getIncomingValue(i);
|
|
|
|
Inst->setOperand(Idx, IncomingVal);
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
Inst->setOperand(Idx, Mat);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Emit materialization code for all rebased constants and update their
|
2014-03-21 04:17:13 +08:00
|
|
|
/// users.
|
2016-07-02 08:16:47 +08:00
|
|
|
void ConstantHoistingPass::emitBaseConstants(Instruction *Base,
|
|
|
|
Constant *Offset,
|
2018-09-05 06:17:03 +08:00
|
|
|
Type *Ty,
|
2016-07-02 08:16:47 +08:00
|
|
|
const ConstantUser &ConstUser) {
|
2014-03-21 14:04:36 +08:00
|
|
|
Instruction *Mat = Base;
|
2018-09-05 06:17:03 +08:00
|
|
|
|
|
|
|
// The same offset can be dereferenced to different types in nested struct.
|
|
|
|
if (!Offset && Ty && Ty != Base->getType())
|
|
|
|
Offset = ConstantInt::get(Type::getInt32Ty(*Ctx), 0);
|
|
|
|
|
2014-03-21 14:04:36 +08:00
|
|
|
if (Offset) {
|
|
|
|
Instruction *InsertionPt = findMatInsertPt(ConstUser.Inst,
|
|
|
|
ConstUser.OpndIdx);
|
2018-09-05 06:17:03 +08:00
|
|
|
if (Ty) {
|
|
|
|
// Constant being rebased is a ConstantExpr.
|
|
|
|
PointerType *Int8PtrTy = Type::getInt8PtrTy(*Ctx,
|
|
|
|
cast<PointerType>(Ty)->getAddressSpace());
|
|
|
|
Base = new BitCastInst(Base, Int8PtrTy, "base_bitcast", InsertionPt);
|
|
|
|
Mat = GetElementPtrInst::Create(Int8PtrTy->getElementType(), Base,
|
|
|
|
Offset, "mat_gep", InsertionPt);
|
|
|
|
Mat = new BitCastInst(Mat, Ty, "mat_bitcast", InsertionPt);
|
|
|
|
} else
|
|
|
|
// Constant being rebased is a ConstantInt.
|
|
|
|
Mat = BinaryOperator::Create(Instruction::Add, Base, Offset,
|
2014-03-21 14:04:36 +08:00
|
|
|
"const_mat", InsertionPt);
|
|
|
|
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "Materialize constant (" << *Base->getOperand(0)
|
|
|
|
<< " + " << *Offset << ") in BB "
|
|
|
|
<< Mat->getParent()->getName() << '\n'
|
|
|
|
<< *Mat << '\n');
|
2014-03-21 14:04:36 +08:00
|
|
|
Mat->setDebugLoc(ConstUser.Inst->getDebugLoc());
|
2014-03-21 03:55:52 +08:00
|
|
|
}
|
2014-03-21 14:04:36 +08:00
|
|
|
Value *Opnd = ConstUser.Inst->getOperand(ConstUser.OpndIdx);
|
2014-01-25 10:02:55 +08:00
|
|
|
|
2014-03-21 14:04:36 +08:00
|
|
|
// Visit constant integer.
|
|
|
|
if (isa<ConstantInt>(Opnd)) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
|
2014-03-22 09:49:27 +08:00
|
|
|
if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat) && Offset)
|
|
|
|
Mat->eraseFromParent();
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
|
2014-03-21 14:04:36 +08:00
|
|
|
return;
|
|
|
|
}
|
2014-03-21 04:17:13 +08:00
|
|
|
|
2014-03-21 14:04:36 +08:00
|
|
|
// Visit cast instruction.
|
|
|
|
if (auto CastInst = dyn_cast<Instruction>(Opnd)) {
|
|
|
|
assert(CastInst->isCast() && "Expected an cast instruction!");
|
|
|
|
// Check if we already have visited this cast instruction before to avoid
|
|
|
|
// unnecessary cloning.
|
|
|
|
Instruction *&ClonedCastInst = ClonedCastMap[CastInst];
|
|
|
|
if (!ClonedCastInst) {
|
|
|
|
ClonedCastInst = CastInst->clone();
|
|
|
|
ClonedCastInst->setOperand(0, Mat);
|
|
|
|
ClonedCastInst->insertAfter(CastInst);
|
|
|
|
// Use the same debug location as the original cast instruction.
|
|
|
|
ClonedCastInst->setDebugLoc(CastInst->getDebugLoc());
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "Clone instruction: " << *CastInst << '\n'
|
|
|
|
<< "To : " << *ClonedCastInst << '\n');
|
2014-03-21 04:17:13 +08:00
|
|
|
}
|
2014-03-21 14:04:36 +08:00
|
|
|
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
|
2014-03-22 09:49:27 +08:00
|
|
|
updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ClonedCastInst);
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
|
2014-03-21 14:04:36 +08:00
|
|
|
return;
|
2014-03-21 04:17:13 +08:00
|
|
|
}
|
2014-03-21 14:04:36 +08:00
|
|
|
|
|
|
|
// Visit constant expression.
|
|
|
|
if (auto ConstExpr = dyn_cast<ConstantExpr>(Opnd)) {
|
2018-09-05 06:17:03 +08:00
|
|
|
if (ConstExpr->isGEPWithNoNotionalOverIndexing()) {
|
|
|
|
// Operand is a ConstantGEP, replace it.
|
|
|
|
updateOperand(ConstUser.Inst, ConstUser.OpndIdx, Mat);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Aside from constant GEPs, only constant cast expressions are collected.
|
|
|
|
assert(ConstExpr->isCast() && "ConstExpr should be a cast");
|
2014-03-21 14:04:36 +08:00
|
|
|
Instruction *ConstExprInst = ConstExpr->getAsInstruction();
|
|
|
|
ConstExprInst->setOperand(0, Mat);
|
|
|
|
ConstExprInst->insertBefore(findMatInsertPt(ConstUser.Inst,
|
|
|
|
ConstUser.OpndIdx));
|
|
|
|
|
|
|
|
// Use the same debug location as the instruction we are about to update.
|
|
|
|
ConstExprInst->setDebugLoc(ConstUser.Inst->getDebugLoc());
|
|
|
|
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "Create instruction: " << *ConstExprInst << '\n'
|
|
|
|
<< "From : " << *ConstExpr << '\n');
|
|
|
|
LLVM_DEBUG(dbgs() << "Update: " << *ConstUser.Inst << '\n');
|
2014-03-22 09:49:27 +08:00
|
|
|
if (!updateOperand(ConstUser.Inst, ConstUser.OpndIdx, ConstExprInst)) {
|
|
|
|
ConstExprInst->eraseFromParent();
|
|
|
|
if (Offset)
|
|
|
|
Mat->eraseFromParent();
|
|
|
|
}
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "To : " << *ConstUser.Inst << '\n');
|
2014-03-21 14:04:36 +08:00
|
|
|
return;
|
2014-02-08 08:20:45 +08:00
|
|
|
}
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Hoist and hide the base constant behind a bitcast and emit
|
2014-01-25 10:02:55 +08:00
|
|
|
/// materialization code for derived constants.
|
2018-09-05 06:17:03 +08:00
|
|
|
bool ConstantHoistingPass::emitBaseConstants(GlobalVariable *BaseGV) {
|
2014-01-25 10:02:55 +08:00
|
|
|
bool MadeChange = false;
|
2018-09-05 06:17:03 +08:00
|
|
|
SmallVectorImpl<consthoist::ConstantInfo> &ConstInfoVec =
|
|
|
|
BaseGV ? ConstGEPInfoMap[BaseGV] : ConstIntInfoVec;
|
|
|
|
for (auto const &ConstInfo : ConstInfoVec) {
|
2019-09-12 02:55:00 +08:00
|
|
|
SetVector<Instruction *> IPSet = findConstantInsertionPoint(ConstInfo);
|
2019-03-05 04:57:14 +08:00
|
|
|
// We can have an empty set if the function contains unreachable blocks.
|
|
|
|
if (IPSet.empty())
|
|
|
|
continue;
|
2017-04-21 23:50:16 +08:00
|
|
|
|
|
|
|
unsigned UsesNum = 0;
|
|
|
|
unsigned ReBasesNum = 0;
|
2018-09-26 08:59:09 +08:00
|
|
|
unsigned NotRebasedNum = 0;
|
2017-04-21 23:50:16 +08:00
|
|
|
for (Instruction *IP : IPSet) {
|
2018-09-26 08:59:09 +08:00
|
|
|
// First, collect constants depending on this IP of the base.
|
|
|
|
unsigned Uses = 0;
|
|
|
|
using RebasedUse = std::tuple<Constant *, Type *, ConstantUser>;
|
|
|
|
SmallVector<RebasedUse, 4> ToBeRebased;
|
|
|
|
for (auto const &RCI : ConstInfo.RebasedConstants) {
|
|
|
|
for (auto const &U : RCI.Uses) {
|
|
|
|
Uses++;
|
|
|
|
BasicBlock *OrigMatInsertBB =
|
|
|
|
findMatInsertPt(U.Inst, U.OpndIdx)->getParent();
|
|
|
|
// If Base constant is to be inserted in multiple places,
|
|
|
|
// generate rebase for U using the Base dominating U.
|
|
|
|
if (IPSet.size() == 1 ||
|
|
|
|
DT->dominates(IP->getParent(), OrigMatInsertBB))
|
|
|
|
ToBeRebased.push_back(RebasedUse(RCI.Offset, RCI.Ty, U));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
UsesNum = Uses;
|
|
|
|
|
|
|
|
// If only few constants depend on this IP of base, skip rebasing,
|
|
|
|
// assuming the base and the rebased have the same materialization cost.
|
|
|
|
if (ToBeRebased.size() < MinNumOfDependentToRebase) {
|
|
|
|
NotRebasedNum += ToBeRebased.size();
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Emit an instance of the base at this IP.
|
2018-09-05 06:17:03 +08:00
|
|
|
Instruction *Base = nullptr;
|
|
|
|
// Hoist and hide the base constant behind a bitcast.
|
|
|
|
if (ConstInfo.BaseExpr) {
|
|
|
|
assert(BaseGV && "A base constant expression must have an base GV");
|
|
|
|
Type *Ty = ConstInfo.BaseExpr->getType();
|
|
|
|
Base = new BitCastInst(ConstInfo.BaseExpr, Ty, "const", IP);
|
|
|
|
} else {
|
|
|
|
IntegerType *Ty = ConstInfo.BaseInt->getType();
|
|
|
|
Base = new BitCastInst(ConstInfo.BaseInt, Ty, "const", IP);
|
|
|
|
}
|
2017-11-10 04:01:31 +08:00
|
|
|
|
|
|
|
Base->setDebugLoc(IP->getDebugLoc());
|
|
|
|
|
2018-09-05 06:17:03 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "Hoist constant (" << *ConstInfo.BaseInt
|
2018-05-14 20:53:11 +08:00
|
|
|
<< ") to BB " << IP->getParent()->getName() << '\n'
|
|
|
|
<< *Base << '\n');
|
2017-04-21 23:50:16 +08:00
|
|
|
|
2018-09-26 08:59:09 +08:00
|
|
|
// Emit materialization code for rebased constants depending on this IP.
|
|
|
|
for (auto const &R : ToBeRebased) {
|
|
|
|
Constant *Off = std::get<0>(R);
|
|
|
|
Type *Ty = std::get<1>(R);
|
|
|
|
ConstantUser U = std::get<2>(R);
|
|
|
|
emitBaseConstants(Base, Off, Ty, U);
|
|
|
|
ReBasesNum++;
|
|
|
|
// Use the same debug location as the last user of the constant.
|
|
|
|
Base->setDebugLoc(DILocation::getMergedLocation(
|
|
|
|
Base->getDebugLoc(), U.Inst->getDebugLoc()));
|
2017-04-21 23:50:16 +08:00
|
|
|
}
|
|
|
|
assert(!Base->use_empty() && "The use list is empty!?");
|
|
|
|
assert(isa<Instruction>(Base->user_back()) &&
|
|
|
|
"All uses should be instructions.");
|
2014-01-25 10:02:55 +08:00
|
|
|
}
|
2017-04-21 23:50:16 +08:00
|
|
|
(void)UsesNum;
|
|
|
|
(void)ReBasesNum;
|
2018-09-26 08:59:09 +08:00
|
|
|
(void)NotRebasedNum;
|
2017-04-21 23:50:16 +08:00
|
|
|
// Expect all uses are rebased after rebase is done.
|
2018-09-26 08:59:09 +08:00
|
|
|
assert(UsesNum == (ReBasesNum + NotRebasedNum) &&
|
|
|
|
"Not all uses are rebased");
|
2017-04-21 23:50:16 +08:00
|
|
|
|
|
|
|
NumConstantsHoisted++;
|
2014-01-25 10:02:55 +08:00
|
|
|
|
2017-04-21 23:50:16 +08:00
|
|
|
// Base constant is also included in ConstInfo.RebasedConstants, so
|
|
|
|
// deduct 1 from ConstInfo.RebasedConstants.size().
|
2018-09-05 06:17:03 +08:00
|
|
|
NumConstantsRebased += ConstInfo.RebasedConstants.size() - 1;
|
2014-01-25 10:02:55 +08:00
|
|
|
|
|
|
|
MadeChange = true;
|
|
|
|
}
|
|
|
|
return MadeChange;
|
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Check all cast instructions we made a copy of and remove them if they
|
2014-03-21 14:04:36 +08:00
|
|
|
/// have no more users.
|
2016-07-02 08:16:47 +08:00
|
|
|
void ConstantHoistingPass::deleteDeadCastInst() const {
|
2014-03-21 14:04:36 +08:00
|
|
|
for (auto const &I : ClonedCastMap)
|
|
|
|
if (I.first->use_empty())
|
2014-03-22 09:49:30 +08:00
|
|
|
I.first->eraseFromParent();
|
2014-03-21 14:04:36 +08:00
|
|
|
}
|
2014-03-21 04:17:13 +08:00
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Optimize expensive integer constants in the given function.
|
2016-07-02 08:16:47 +08:00
|
|
|
bool ConstantHoistingPass::runImpl(Function &Fn, TargetTransformInfo &TTI,
|
2017-04-21 23:50:16 +08:00
|
|
|
DominatorTree &DT, BlockFrequencyInfo *BFI,
|
2019-04-16 00:49:00 +08:00
|
|
|
BasicBlock &Entry, ProfileSummaryInfo *PSI) {
|
2016-07-02 08:16:47 +08:00
|
|
|
this->TTI = &TTI;
|
|
|
|
this->DT = &DT;
|
2017-04-21 23:50:16 +08:00
|
|
|
this->BFI = BFI;
|
2018-09-05 06:17:03 +08:00
|
|
|
this->DL = &Fn.getParent()->getDataLayout();
|
|
|
|
this->Ctx = &Fn.getContext();
|
2018-07-31 03:41:25 +08:00
|
|
|
this->Entry = &Entry;
|
2019-04-16 00:49:00 +08:00
|
|
|
this->PSI = PSI;
|
2014-01-25 10:02:55 +08:00
|
|
|
// Collect all constant candidates.
|
2014-03-21 14:04:36 +08:00
|
|
|
collectConstantCandidates(Fn);
|
2014-01-25 10:02:55 +08:00
|
|
|
|
|
|
|
// Combine constants that can be easily materialized with an add from a common
|
|
|
|
// base constant.
|
2018-09-05 06:17:03 +08:00
|
|
|
if (!ConstIntCandVec.empty())
|
|
|
|
findBaseConstants(nullptr);
|
2020-09-25 01:28:21 +08:00
|
|
|
for (const auto &MapEntry : ConstGEPCandMap)
|
2018-09-05 06:17:03 +08:00
|
|
|
if (!MapEntry.second.empty())
|
|
|
|
findBaseConstants(MapEntry.first);
|
2014-03-21 14:04:36 +08:00
|
|
|
|
2014-03-21 14:04:45 +08:00
|
|
|
// Finally hoist the base constant and emit materialization code for dependent
|
2014-01-25 10:02:55 +08:00
|
|
|
// constants.
|
2018-09-05 06:17:03 +08:00
|
|
|
bool MadeChange = false;
|
|
|
|
if (!ConstIntInfoVec.empty())
|
|
|
|
MadeChange = emitBaseConstants(nullptr);
|
2020-09-25 01:28:21 +08:00
|
|
|
for (const auto &MapEntry : ConstGEPInfoMap)
|
2018-09-05 06:17:03 +08:00
|
|
|
if (!MapEntry.second.empty())
|
|
|
|
MadeChange |= emitBaseConstants(MapEntry.first);
|
|
|
|
|
2014-01-25 10:02:55 +08:00
|
|
|
|
2014-03-21 14:04:36 +08:00
|
|
|
// Cleanup dead instructions.
|
|
|
|
deleteDeadCastInst();
|
2014-01-25 10:02:55 +08:00
|
|
|
|
2019-03-01 13:27:01 +08:00
|
|
|
cleanup();
|
|
|
|
|
2014-01-25 10:02:55 +08:00
|
|
|
return MadeChange;
|
|
|
|
}
|
2016-07-02 08:16:47 +08:00
|
|
|
|
|
|
|
PreservedAnalyses ConstantHoistingPass::run(Function &F,
|
|
|
|
FunctionAnalysisManager &AM) {
|
|
|
|
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
|
|
|
|
auto &TTI = AM.getResult<TargetIRAnalysis>(F);
|
2017-04-21 23:50:16 +08:00
|
|
|
auto BFI = ConstHoistWithBlockFrequency
|
|
|
|
? &AM.getResult<BlockFrequencyAnalysis>(F)
|
|
|
|
: nullptr;
|
2020-01-15 02:27:20 +08:00
|
|
|
auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
|
|
|
|
auto *PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
|
2019-04-16 00:49:00 +08:00
|
|
|
if (!runImpl(F, TTI, DT, BFI, F.getEntryBlock(), PSI))
|
2016-07-02 08:16:47 +08:00
|
|
|
return PreservedAnalyses::all();
|
|
|
|
|
2017-01-15 14:32:49 +08:00
|
|
|
PreservedAnalyses PA;
|
|
|
|
PA.preserveSet<CFGAnalyses>();
|
|
|
|
return PA;
|
2016-07-02 08:16:47 +08:00
|
|
|
}
|