2008-12-05 15:49:08 +08:00
|
|
|
//===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
|
2007-07-25 01:55:58 +08:00
|
|
|
//
|
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
|
2007-07-25 01:55:58 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This pass performs global value numbering to eliminate fully redundant
|
|
|
|
// instructions. It also performs simple dead load elimination.
|
|
|
|
//
|
2009-03-10 23:04:53 +08:00
|
|
|
// Note that this pass does the value numbering itself; it does not use the
|
2008-06-05 15:55:49 +08:00
|
|
|
// ValueNumbering analysis passes.
|
|
|
|
//
|
2007-07-25 01:55:58 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2016-03-11 16:50:55 +08:00
|
|
|
#include "llvm/Transforms/Scalar/GVN.h"
|
2012-06-29 20:38:19 +08:00
|
|
|
#include "llvm/ADT/DenseMap.h"
|
|
|
|
#include "llvm/ADT/DepthFirstIterator.h"
|
|
|
|
#include "llvm/ADT/Hashing.h"
|
2014-05-14 05:06:40 +08:00
|
|
|
#include "llvm/ADT/MapVector.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/ADT/PointerIntPair.h"
|
2015-01-10 03:19:56 +08:00
|
|
|
#include "llvm/ADT/PostOrderIterator.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/ADT/STLExtras.h"
|
2013-11-12 06:00:23 +08:00
|
|
|
#include "llvm/ADT/SetVector.h"
|
2014-01-07 19:48:04 +08:00
|
|
|
#include "llvm/ADT/SmallPtrSet.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/ADT/SmallVector.h"
|
2012-06-29 20:38:19 +08:00
|
|
|
#include "llvm/ADT/Statistic.h"
|
2007-10-19 03:39:33 +08:00
|
|
|
#include "llvm/Analysis/AliasAnalysis.h"
|
2016-12-19 16:22:17 +08:00
|
|
|
#include "llvm/Analysis/AssumptionCache.h"
|
2013-07-27 09:24:00 +08:00
|
|
|
#include "llvm/Analysis/CFG.h"
|
2019-02-06 10:52:52 +08:00
|
|
|
#include "llvm/Analysis/DomTreeUpdater.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"
|
2010-11-13 05:10:24 +08:00
|
|
|
#include "llvm/Analysis/InstructionSimplify.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/Analysis/LoopInfo.h"
|
2009-10-28 04:05:49 +08:00
|
|
|
#include "llvm/Analysis/MemoryBuiltins.h"
|
2007-07-25 01:55:58 +08:00
|
|
|
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
|
2017-10-10 07:19:02 +08:00
|
|
|
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
|
2009-12-09 09:59:31 +08:00
|
|
|
#include "llvm/Analysis/PHITransAddr.h"
|
2015-03-24 03:32:43 +08:00
|
|
|
#include "llvm/Analysis/TargetLibraryInfo.h"
|
2017-10-31 13:07:56 +08:00
|
|
|
#include "llvm/Analysis/ValueTracking.h"
|
2018-04-30 22:59:11 +08:00
|
|
|
#include "llvm/Config/llvm-config.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/IR/Attributes.h"
|
|
|
|
#include "llvm/IR/BasicBlock.h"
|
|
|
|
#include "llvm/IR/CallSite.h"
|
|
|
|
#include "llvm/IR/Constant.h"
|
|
|
|
#include "llvm/IR/Constants.h"
|
2013-01-02 19:36:10 +08:00
|
|
|
#include "llvm/IR/DataLayout.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/IR/DebugLoc.h"
|
2014-01-13 17:26:24 +08:00
|
|
|
#include "llvm/IR/Dominators.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/IR/Function.h"
|
|
|
|
#include "llvm/IR/InstrTypes.h"
|
|
|
|
#include "llvm/IR/Instruction.h"
|
|
|
|
#include "llvm/IR/Instructions.h"
|
2013-01-02 19:36:10 +08:00
|
|
|
#include "llvm/IR/IntrinsicInst.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/IR/Intrinsics.h"
|
2013-01-02 19:36:10 +08:00
|
|
|
#include "llvm/IR/LLVMContext.h"
|
|
|
|
#include "llvm/IR/Metadata.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/IR/Module.h"
|
|
|
|
#include "llvm/IR/Operator.h"
|
|
|
|
#include "llvm/IR/PassManager.h"
|
2014-03-04 19:08:18 +08:00
|
|
|
#include "llvm/IR/PatternMatch.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/IR/Type.h"
|
|
|
|
#include "llvm/IR/Use.h"
|
|
|
|
#include "llvm/IR/Value.h"
|
|
|
|
#include "llvm/Pass.h"
|
|
|
|
#include "llvm/Support/Casting.h"
|
2008-06-20 03:57:25 +08:00
|
|
|
#include "llvm/Support/CommandLine.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include "llvm/Support/Compiler.h"
|
2008-03-29 12:36:18 +08:00
|
|
|
#include "llvm/Support/Debug.h"
|
2015-03-24 03:32:43 +08:00
|
|
|
#include "llvm/Support/raw_ostream.h"
|
2012-06-29 20:38:19 +08:00
|
|
|
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
|
2018-08-03 13:08:17 +08:00
|
|
|
#include "llvm/Transforms/Utils/Local.h"
|
2012-06-29 20:38:19 +08:00
|
|
|
#include "llvm/Transforms/Utils/SSAUpdater.h"
|
2017-03-10 12:54:10 +08:00
|
|
|
#include "llvm/Transforms/Utils/VNCoercion.h"
|
2017-09-14 05:43:53 +08:00
|
|
|
#include <algorithm>
|
|
|
|
#include <cassert>
|
|
|
|
#include <cstdint>
|
|
|
|
#include <utility>
|
2013-05-10 02:34:27 +08:00
|
|
|
#include <vector>
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2007-07-25 01:55:58 +08:00
|
|
|
using namespace llvm;
|
2016-03-11 16:50:55 +08:00
|
|
|
using namespace llvm::gvn;
|
2017-03-10 12:54:10 +08:00
|
|
|
using namespace llvm::VNCoercion;
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
using namespace PatternMatch;
|
2007-07-25 01:55:58 +08:00
|
|
|
|
2014-04-22 10:55:47 +08:00
|
|
|
#define DEBUG_TYPE "gvn"
|
|
|
|
|
2008-12-23 06:14:07 +08:00
|
|
|
STATISTIC(NumGVNInstr, "Number of instructions deleted");
|
|
|
|
STATISTIC(NumGVNLoad, "Number of loads deleted");
|
|
|
|
STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
|
2008-07-16 00:28:06 +08:00
|
|
|
STATISTIC(NumGVNBlocks, "Number of blocks merged");
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
STATISTIC(NumGVNSimpl, "Number of instructions simplified");
|
|
|
|
STATISTIC(NumGVNEqProp, "Number of equalities propagated");
|
2008-12-23 06:14:07 +08:00
|
|
|
STATISTIC(NumPRELoad, "Number of loads PRE'd");
|
2008-03-22 12:13:49 +08:00
|
|
|
|
2008-06-20 09:01:07 +08:00
|
|
|
static cl::opt<bool> EnablePRE("enable-pre",
|
2008-07-18 03:41:00 +08:00
|
|
|
cl::init(true), cl::Hidden);
|
2009-06-16 02:30:15 +08:00
|
|
|
static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
|
2018-08-22 03:11:27 +08:00
|
|
|
static cl::opt<bool> EnableMemDep("enable-gvn-memdep", cl::init(true));
|
2008-06-20 03:57:25 +08:00
|
|
|
|
2012-04-28 02:09:28 +08:00
|
|
|
// Maximum allowed recursion depth.
|
2012-04-28 03:30:32 +08:00
|
|
|
static cl::opt<uint32_t>
|
2018-09-10 23:07:56 +08:00
|
|
|
MaxRecurseDepth("gvn-max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
|
|
|
|
cl::desc("Max recurse depth in GVN (default = 1000)"));
|
2012-04-28 02:09:28 +08:00
|
|
|
|
2018-09-10 23:07:59 +08:00
|
|
|
static cl::opt<uint32_t> MaxNumDeps(
|
|
|
|
"gvn-max-num-deps", cl::Hidden, cl::init(100), cl::ZeroOrMore,
|
|
|
|
cl::desc("Max number of dependences to attempt Load PRE (default = 100)"));
|
|
|
|
|
2016-03-12 00:25:19 +08:00
|
|
|
struct llvm::GVN::Expression {
|
2016-03-10 08:58:20 +08:00
|
|
|
uint32_t opcode;
|
|
|
|
Type *type;
|
2017-09-14 05:43:53 +08:00
|
|
|
bool commutative = false;
|
2016-03-10 08:58:20 +08:00
|
|
|
SmallVector<uint32_t, 4> varargs;
|
|
|
|
|
2017-09-14 05:43:53 +08:00
|
|
|
Expression(uint32_t o = ~2U) : opcode(o) {}
|
2016-03-10 08:58:20 +08:00
|
|
|
|
|
|
|
bool operator==(const Expression &other) const {
|
|
|
|
if (opcode != other.opcode)
|
|
|
|
return false;
|
|
|
|
if (opcode == ~0U || opcode == ~1U)
|
|
|
|
return true;
|
|
|
|
if (type != other.type)
|
|
|
|
return false;
|
|
|
|
if (varargs != other.varargs)
|
|
|
|
return false;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
friend hash_code hash_value(const Expression &Value) {
|
|
|
|
return hash_combine(
|
|
|
|
Value.opcode, Value.type,
|
|
|
|
hash_combine_range(Value.varargs.begin(), Value.varargs.end()));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2007-07-25 01:55:58 +08:00
|
|
|
namespace llvm {
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2016-03-12 00:25:19 +08:00
|
|
|
template <> struct DenseMapInfo<GVN::Expression> {
|
|
|
|
static inline GVN::Expression getEmptyKey() { return ~0U; }
|
|
|
|
static inline GVN::Expression getTombstoneKey() { return ~1U; }
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2016-06-18 04:41:14 +08:00
|
|
|
static unsigned getHashValue(const GVN::Expression &e) {
|
2012-03-05 19:29:54 +08:00
|
|
|
using llvm::hash_value;
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2012-03-05 19:29:54 +08:00
|
|
|
return static_cast<unsigned>(hash_value(e));
|
2007-07-25 01:55:58 +08:00
|
|
|
}
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2016-03-12 00:25:19 +08:00
|
|
|
static bool isEqual(const GVN::Expression &LHS, const GVN::Expression &RHS) {
|
2007-09-18 02:34:04 +08:00
|
|
|
return LHS == RHS;
|
|
|
|
}
|
2007-07-25 01:55:58 +08:00
|
|
|
};
|
2017-09-14 05:43:53 +08:00
|
|
|
|
|
|
|
} // end namespace llvm
|
2007-07-25 01:55:58 +08:00
|
|
|
|
2016-03-11 16:50:55 +08:00
|
|
|
/// Represents a particular available value that we know how to materialize.
|
|
|
|
/// Materialization of an AvailableValue never fails. An AvailableValue is
|
|
|
|
/// implicitly associated with a rematerialization point which is the
|
|
|
|
/// location of the instruction from which it was formed.
|
|
|
|
struct llvm::gvn::AvailableValue {
|
|
|
|
enum ValType {
|
2016-10-21 09:37:02 +08:00
|
|
|
SimpleVal, // A simple offsetted value that is accessed.
|
|
|
|
LoadVal, // A value produced by a load.
|
|
|
|
MemIntrin, // A memory intrinsic which is loaded from.
|
|
|
|
UndefVal // A UndefValue representing a value from dead block (which
|
|
|
|
// is not yet physically removed from the CFG).
|
2016-03-11 16:50:55 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
/// V - The value that is live out of the block.
|
2016-10-21 09:37:02 +08:00
|
|
|
PointerIntPair<Value *, 2, ValType> Val;
|
2016-03-11 16:50:55 +08:00
|
|
|
|
|
|
|
/// Offset - The byte offset in Val that is interesting for the load query.
|
|
|
|
unsigned Offset;
|
|
|
|
|
|
|
|
static AvailableValue get(Value *V, unsigned Offset = 0) {
|
|
|
|
AvailableValue Res;
|
2016-10-21 09:37:02 +08:00
|
|
|
Res.Val.setPointer(V);
|
|
|
|
Res.Val.setInt(SimpleVal);
|
2016-03-11 16:50:55 +08:00
|
|
|
Res.Offset = Offset;
|
|
|
|
return Res;
|
|
|
|
}
|
|
|
|
|
|
|
|
static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset = 0) {
|
|
|
|
AvailableValue Res;
|
2016-10-21 09:37:02 +08:00
|
|
|
Res.Val.setPointer(MI);
|
|
|
|
Res.Val.setInt(MemIntrin);
|
2016-03-11 16:50:55 +08:00
|
|
|
Res.Offset = Offset;
|
|
|
|
return Res;
|
|
|
|
}
|
|
|
|
|
|
|
|
static AvailableValue getLoad(LoadInst *LI, unsigned Offset = 0) {
|
|
|
|
AvailableValue Res;
|
2016-10-21 09:37:02 +08:00
|
|
|
Res.Val.setPointer(LI);
|
|
|
|
Res.Val.setInt(LoadVal);
|
2016-03-11 16:50:55 +08:00
|
|
|
Res.Offset = Offset;
|
|
|
|
return Res;
|
|
|
|
}
|
|
|
|
|
|
|
|
static AvailableValue getUndef() {
|
|
|
|
AvailableValue Res;
|
2016-10-21 09:37:02 +08:00
|
|
|
Res.Val.setPointer(nullptr);
|
|
|
|
Res.Val.setInt(UndefVal);
|
2016-03-11 16:50:55 +08:00
|
|
|
Res.Offset = 0;
|
|
|
|
return Res;
|
|
|
|
}
|
|
|
|
|
2016-10-21 09:37:02 +08:00
|
|
|
bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
|
|
|
|
bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
|
|
|
|
bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
|
|
|
|
bool isUndefValue() const { return Val.getInt() == UndefVal; }
|
2016-03-11 16:50:55 +08:00
|
|
|
|
|
|
|
Value *getSimpleValue() const {
|
|
|
|
assert(isSimpleValue() && "Wrong accessor");
|
2016-10-21 09:37:02 +08:00
|
|
|
return Val.getPointer();
|
2016-03-11 16:50:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
LoadInst *getCoercedLoadValue() const {
|
|
|
|
assert(isCoercedLoadValue() && "Wrong accessor");
|
2016-10-21 09:37:02 +08:00
|
|
|
return cast<LoadInst>(Val.getPointer());
|
2016-03-11 16:50:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
MemIntrinsic *getMemIntrinValue() const {
|
|
|
|
assert(isMemIntrinValue() && "Wrong accessor");
|
2016-10-21 09:37:02 +08:00
|
|
|
return cast<MemIntrinsic>(Val.getPointer());
|
2016-03-11 16:50:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Emit code at the specified insertion point to adjust the value defined
|
|
|
|
/// here to the specified type. This handles various coercion cases.
|
|
|
|
Value *MaterializeAdjustedValue(LoadInst *LI, Instruction *InsertPt,
|
|
|
|
GVN &gvn) const;
|
|
|
|
};
|
|
|
|
|
|
|
|
/// Represents an AvailableValue which can be rematerialized at the end of
|
|
|
|
/// the associated BasicBlock.
|
|
|
|
struct llvm::gvn::AvailableValueInBlock {
|
|
|
|
/// BB - The basic block in question.
|
|
|
|
BasicBlock *BB;
|
|
|
|
|
|
|
|
/// AV - The actual available value
|
|
|
|
AvailableValue AV;
|
|
|
|
|
|
|
|
static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV) {
|
|
|
|
AvailableValueInBlock Res;
|
|
|
|
Res.BB = BB;
|
|
|
|
Res.AV = std::move(AV);
|
|
|
|
return Res;
|
|
|
|
}
|
|
|
|
|
|
|
|
static AvailableValueInBlock get(BasicBlock *BB, Value *V,
|
|
|
|
unsigned Offset = 0) {
|
|
|
|
return get(BB, AvailableValue::get(V, Offset));
|
|
|
|
}
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2016-03-11 16:50:55 +08:00
|
|
|
static AvailableValueInBlock getUndef(BasicBlock *BB) {
|
|
|
|
return get(BB, AvailableValue::getUndef());
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Emit code at the end of this block to adjust the value defined here to
|
|
|
|
/// the specified type. This handles various coercion cases.
|
|
|
|
Value *MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const {
|
|
|
|
return AV.MaterializeAdjustedValue(LI, BB->getTerminator(), gvn);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2007-07-25 01:55:58 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// ValueTable Internal Functions
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2016-04-29 00:00:15 +08:00
|
|
|
GVN::Expression GVN::ValueTable::createExpr(Instruction *I) {
|
2007-07-25 01:55:58 +08:00
|
|
|
Expression e;
|
|
|
|
e.type = I->getType();
|
2011-01-04 03:00:11 +08:00
|
|
|
e.opcode = I->getOpcode();
|
|
|
|
for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
|
|
|
|
OI != OE; ++OI)
|
2016-04-29 00:00:15 +08:00
|
|
|
e.varargs.push_back(lookupOrAdd(*OI));
|
2012-02-24 23:16:31 +08:00
|
|
|
if (I->isCommutative()) {
|
|
|
|
// Ensure that commutative instructions that only differ by a permutation
|
|
|
|
// of their operands get the same value number by sorting the operand value
|
|
|
|
// numbers. Since all commutative instructions have two operands it is more
|
|
|
|
// efficient to sort by hand rather than using, say, std::sort.
|
|
|
|
assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
|
|
|
|
if (e.varargs[0] > e.varargs[1])
|
|
|
|
std::swap(e.varargs[0], e.varargs[1]);
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
e.commutative = true;
|
2012-02-24 23:16:31 +08:00
|
|
|
}
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2011-07-08 09:50:54 +08:00
|
|
|
if (CmpInst *C = dyn_cast<CmpInst>(I)) {
|
2012-02-24 23:16:31 +08:00
|
|
|
// Sort the operand value numbers so x<y and y>x get the same value number.
|
|
|
|
CmpInst::Predicate Predicate = C->getPredicate();
|
|
|
|
if (e.varargs[0] > e.varargs[1]) {
|
|
|
|
std::swap(e.varargs[0], e.varargs[1]);
|
|
|
|
Predicate = CmpInst::getSwappedPredicate(Predicate);
|
|
|
|
}
|
|
|
|
e.opcode = (C->getOpcode() << 8) | Predicate;
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
e.commutative = true;
|
2011-01-04 03:00:11 +08:00
|
|
|
} else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
|
|
|
|
for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
|
|
|
|
II != IE; ++II)
|
|
|
|
e.varargs.push_back(*II);
|
2014-03-11 17:36:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return e;
|
|
|
|
}
|
|
|
|
|
2016-04-29 00:00:15 +08:00
|
|
|
GVN::Expression GVN::ValueTable::createCmpExpr(unsigned Opcode,
|
|
|
|
CmpInst::Predicate Predicate,
|
|
|
|
Value *LHS, Value *RHS) {
|
2012-02-27 16:14:30 +08:00
|
|
|
assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
|
|
|
|
"Not a comparison!");
|
|
|
|
Expression e;
|
|
|
|
e.type = CmpInst::makeCmpResultType(LHS->getType());
|
2016-04-29 00:00:15 +08:00
|
|
|
e.varargs.push_back(lookupOrAdd(LHS));
|
|
|
|
e.varargs.push_back(lookupOrAdd(RHS));
|
2012-02-27 16:14:30 +08:00
|
|
|
|
|
|
|
// Sort the operand value numbers so x<y and y>x get the same value number.
|
|
|
|
if (e.varargs[0] > e.varargs[1]) {
|
|
|
|
std::swap(e.varargs[0], e.varargs[1]);
|
|
|
|
Predicate = CmpInst::getSwappedPredicate(Predicate);
|
|
|
|
}
|
|
|
|
e.opcode = (Opcode << 8) | Predicate;
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
e.commutative = true;
|
2012-02-27 16:14:30 +08:00
|
|
|
return e;
|
|
|
|
}
|
|
|
|
|
2016-04-29 00:00:15 +08:00
|
|
|
GVN::Expression GVN::ValueTable::createExtractvalueExpr(ExtractValueInst *EI) {
|
2014-04-28 12:05:08 +08:00
|
|
|
assert(EI && "Not an ExtractValueInst?");
|
2014-03-28 22:42:34 +08:00
|
|
|
Expression e;
|
|
|
|
e.type = EI->getType();
|
|
|
|
e.opcode = 0;
|
|
|
|
|
|
|
|
IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
|
2014-04-25 13:29:35 +08:00
|
|
|
if (I != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
|
2014-03-28 22:42:34 +08:00
|
|
|
// EI might be an extract from one of our recognised intrinsics. If it
|
|
|
|
// is we'll synthesize a semantically equivalent expression instead on
|
|
|
|
// an extract value expression.
|
|
|
|
switch (I->getIntrinsicID()) {
|
|
|
|
case Intrinsic::sadd_with_overflow:
|
|
|
|
case Intrinsic::uadd_with_overflow:
|
|
|
|
e.opcode = Instruction::Add;
|
|
|
|
break;
|
|
|
|
case Intrinsic::ssub_with_overflow:
|
|
|
|
case Intrinsic::usub_with_overflow:
|
|
|
|
e.opcode = Instruction::Sub;
|
|
|
|
break;
|
|
|
|
case Intrinsic::smul_with_overflow:
|
|
|
|
case Intrinsic::umul_with_overflow:
|
|
|
|
e.opcode = Instruction::Mul;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (e.opcode != 0) {
|
|
|
|
// Intrinsic recognized. Grab its args to finish building the expression.
|
|
|
|
assert(I->getNumArgOperands() == 2 &&
|
|
|
|
"Expect two args for recognised intrinsics.");
|
2016-04-29 00:00:15 +08:00
|
|
|
e.varargs.push_back(lookupOrAdd(I->getArgOperand(0)));
|
|
|
|
e.varargs.push_back(lookupOrAdd(I->getArgOperand(1)));
|
2014-03-28 22:42:34 +08:00
|
|
|
return e;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Not a recognised intrinsic. Fall back to producing an extract value
|
|
|
|
// expression.
|
|
|
|
e.opcode = EI->getOpcode();
|
|
|
|
for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
|
|
|
|
OI != OE; ++OI)
|
2016-04-29 00:00:15 +08:00
|
|
|
e.varargs.push_back(lookupOrAdd(*OI));
|
2014-03-28 22:42:34 +08:00
|
|
|
|
|
|
|
for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
|
|
|
|
II != IE; ++II)
|
|
|
|
e.varargs.push_back(*II);
|
|
|
|
|
|
|
|
return e;
|
|
|
|
}
|
|
|
|
|
2007-07-25 01:55:58 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
// ValueTable External Functions
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2017-09-14 05:43:53 +08:00
|
|
|
GVN::ValueTable::ValueTable() = default;
|
2016-10-20 21:09:12 +08:00
|
|
|
GVN::ValueTable::ValueTable(const ValueTable &) = default;
|
|
|
|
GVN::ValueTable::ValueTable(ValueTable &&) = default;
|
|
|
|
GVN::ValueTable::~ValueTable() = default;
|
2016-03-11 16:50:55 +08:00
|
|
|
|
2008-06-19 05:41:49 +08:00
|
|
|
/// add - Insert a value into the table with a specified value number.
|
2016-03-11 16:50:55 +08:00
|
|
|
void GVN::ValueTable::add(Value *V, uint32_t num) {
|
2008-06-19 05:41:49 +08:00
|
|
|
valueNumbering.insert(std::make_pair(V, num));
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
if (PHINode *PN = dyn_cast<PHINode>(V))
|
|
|
|
NumberingPhi[num] = PN;
|
2008-06-19 05:41:49 +08:00
|
|
|
}
|
|
|
|
|
2016-04-29 00:00:15 +08:00
|
|
|
uint32_t GVN::ValueTable::lookupOrAddCall(CallInst *C) {
|
2009-10-20 06:14:22 +08:00
|
|
|
if (AA->doesNotAccessMemory(C)) {
|
2016-04-29 00:00:15 +08:00
|
|
|
Expression exp = createExpr(C);
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
uint32_t e = assignExpNewValueNum(exp).first;
|
2009-10-20 06:14:22 +08:00
|
|
|
valueNumbering[C] = e;
|
|
|
|
return e;
|
2018-08-22 03:11:27 +08:00
|
|
|
} else if (MD && AA->onlyReadsMemory(C)) {
|
2016-04-29 00:00:15 +08:00
|
|
|
Expression exp = createExpr(C);
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
auto ValNum = assignExpNewValueNum(exp);
|
|
|
|
if (ValNum.second) {
|
|
|
|
valueNumbering[C] = ValNum.first;
|
|
|
|
return ValNum.first;
|
2009-10-20 06:14:22 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
MemDepResult local_dep = MD->getDependency(C);
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2009-10-20 06:14:22 +08:00
|
|
|
if (!local_dep.isDef() && !local_dep.isNonLocal()) {
|
|
|
|
valueNumbering[C] = nextValueNumber;
|
|
|
|
return nextValueNumber++;
|
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2009-10-20 06:14:22 +08:00
|
|
|
if (local_dep.isDef()) {
|
|
|
|
CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
|
|
|
|
|
2010-06-30 17:17:53 +08:00
|
|
|
if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
|
2009-10-20 06:14:22 +08:00
|
|
|
valueNumbering[C] = nextValueNumber;
|
2008-05-14 07:18:30 +08:00
|
|
|
return nextValueNumber++;
|
2008-12-01 07:39:23 +08:00
|
|
|
}
|
2008-12-06 05:04:20 +08:00
|
|
|
|
2010-06-24 18:17:17 +08:00
|
|
|
for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
|
2016-04-29 00:00:15 +08:00
|
|
|
uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
|
|
|
|
uint32_t cd_vn = lookupOrAdd(local_cdep->getArgOperand(i));
|
2009-10-20 06:14:22 +08:00
|
|
|
if (c_vn != cd_vn) {
|
|
|
|
valueNumbering[C] = nextValueNumber;
|
2008-05-14 07:18:30 +08:00
|
|
|
return nextValueNumber++;
|
2008-12-01 07:39:23 +08:00
|
|
|
}
|
2008-05-14 07:18:30 +08:00
|
|
|
}
|
2008-12-01 09:15:42 +08:00
|
|
|
|
2016-04-29 00:00:15 +08:00
|
|
|
uint32_t v = lookupOrAdd(local_cdep);
|
2009-10-20 06:14:22 +08:00
|
|
|
valueNumbering[C] = v;
|
|
|
|
return v;
|
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2009-10-20 06:14:22 +08:00
|
|
|
// Non-local case.
|
2016-03-10 08:55:30 +08:00
|
|
|
const MemoryDependenceResults::NonLocalDepInfo &deps =
|
2019-01-07 13:42:51 +08:00
|
|
|
MD->getNonLocalCallDependency(C);
|
2011-06-15 08:47:34 +08:00
|
|
|
// FIXME: Move the checking logic to MemDep!
|
2014-04-25 13:29:35 +08:00
|
|
|
CallInst* cdep = nullptr;
|
2009-10-20 06:14:22 +08:00
|
|
|
|
|
|
|
// Check to see if we have a single dominating call instruction that is
|
|
|
|
// identical to C.
|
|
|
|
for (unsigned i = 0, e = deps.size(); i != e; ++i) {
|
2009-12-09 15:08:01 +08:00
|
|
|
const NonLocalDepEntry *I = &deps[i];
|
|
|
|
if (I->getResult().isNonLocal())
|
2009-10-20 06:14:22 +08:00
|
|
|
continue;
|
|
|
|
|
2011-06-15 08:47:34 +08:00
|
|
|
// We don't handle non-definitions. If we already have a call, reject
|
2009-10-20 06:14:22 +08:00
|
|
|
// instruction dependencies.
|
2014-04-25 13:29:35 +08:00
|
|
|
if (!I->getResult().isDef() || cdep != nullptr) {
|
|
|
|
cdep = nullptr;
|
2008-12-01 07:39:23 +08:00
|
|
|
break;
|
2008-05-13 16:17:22 +08:00
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2009-12-09 15:08:01 +08:00
|
|
|
CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
|
2009-10-20 06:14:22 +08:00
|
|
|
// FIXME: All duplicated with non-local case.
|
2009-12-09 15:08:01 +08:00
|
|
|
if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
|
2009-10-20 06:14:22 +08:00
|
|
|
cdep = NonLocalDepCall;
|
|
|
|
continue;
|
2008-04-17 13:36:50 +08:00
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2014-04-25 13:29:35 +08:00
|
|
|
cdep = nullptr;
|
2009-10-20 06:14:22 +08:00
|
|
|
break;
|
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2009-10-20 06:14:22 +08:00
|
|
|
if (!cdep) {
|
|
|
|
valueNumbering[C] = nextValueNumber;
|
|
|
|
return nextValueNumber++;
|
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2010-06-30 17:17:53 +08:00
|
|
|
if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
|
2009-10-20 06:14:22 +08:00
|
|
|
valueNumbering[C] = nextValueNumber;
|
2007-10-19 03:39:33 +08:00
|
|
|
return nextValueNumber++;
|
|
|
|
}
|
2010-06-24 18:17:17 +08:00
|
|
|
for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
|
2016-04-29 00:00:15 +08:00
|
|
|
uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
|
|
|
|
uint32_t cd_vn = lookupOrAdd(cdep->getArgOperand(i));
|
2009-10-20 06:14:22 +08:00
|
|
|
if (c_vn != cd_vn) {
|
|
|
|
valueNumbering[C] = nextValueNumber;
|
|
|
|
return nextValueNumber++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-29 00:00:15 +08:00
|
|
|
uint32_t v = lookupOrAdd(cdep);
|
2009-10-20 06:14:22 +08:00
|
|
|
valueNumbering[C] = v;
|
|
|
|
return v;
|
2007-07-25 01:55:58 +08:00
|
|
|
} else {
|
2009-10-20 06:14:22 +08:00
|
|
|
valueNumbering[C] = nextValueNumber;
|
|
|
|
return nextValueNumber++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-19 10:45:18 +08:00
|
|
|
/// Returns true if a value number exists for the specified value.
|
2016-03-11 16:50:55 +08:00
|
|
|
bool GVN::ValueTable::exists(Value *V) const { return valueNumbering.count(V) != 0; }
|
2015-11-19 10:45:18 +08:00
|
|
|
|
2009-10-20 06:14:22 +08:00
|
|
|
/// lookup_or_add - Returns the value number for the specified value, assigning
|
|
|
|
/// it a new number if it did not have one before.
|
2016-04-29 00:00:15 +08:00
|
|
|
uint32_t GVN::ValueTable::lookupOrAdd(Value *V) {
|
2009-10-20 06:14:22 +08:00
|
|
|
DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
|
|
|
|
if (VI != valueNumbering.end())
|
|
|
|
return VI->second;
|
|
|
|
|
|
|
|
if (!isa<Instruction>(V)) {
|
2009-10-20 05:14:57 +08:00
|
|
|
valueNumbering[V] = nextValueNumber;
|
2007-07-25 01:55:58 +08:00
|
|
|
return nextValueNumber++;
|
|
|
|
}
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2009-10-20 06:14:22 +08:00
|
|
|
Instruction* I = cast<Instruction>(V);
|
|
|
|
Expression exp;
|
|
|
|
switch (I->getOpcode()) {
|
2014-03-28 22:42:34 +08:00
|
|
|
case Instruction::Call:
|
2016-04-29 00:00:15 +08:00
|
|
|
return lookupOrAddCall(cast<CallInst>(I));
|
2009-10-20 06:14:22 +08:00
|
|
|
case Instruction::Add:
|
|
|
|
case Instruction::FAdd:
|
|
|
|
case Instruction::Sub:
|
|
|
|
case Instruction::FSub:
|
|
|
|
case Instruction::Mul:
|
|
|
|
case Instruction::FMul:
|
|
|
|
case Instruction::UDiv:
|
|
|
|
case Instruction::SDiv:
|
|
|
|
case Instruction::FDiv:
|
|
|
|
case Instruction::URem:
|
|
|
|
case Instruction::SRem:
|
|
|
|
case Instruction::FRem:
|
|
|
|
case Instruction::Shl:
|
|
|
|
case Instruction::LShr:
|
|
|
|
case Instruction::AShr:
|
|
|
|
case Instruction::And:
|
2012-09-10 07:41:11 +08:00
|
|
|
case Instruction::Or:
|
2009-10-20 06:14:22 +08:00
|
|
|
case Instruction::Xor:
|
|
|
|
case Instruction::ICmp:
|
|
|
|
case Instruction::FCmp:
|
|
|
|
case Instruction::Trunc:
|
|
|
|
case Instruction::ZExt:
|
|
|
|
case Instruction::SExt:
|
|
|
|
case Instruction::FPToUI:
|
|
|
|
case Instruction::FPToSI:
|
|
|
|
case Instruction::UIToFP:
|
|
|
|
case Instruction::SIToFP:
|
|
|
|
case Instruction::FPTrunc:
|
|
|
|
case Instruction::FPExt:
|
|
|
|
case Instruction::PtrToInt:
|
|
|
|
case Instruction::IntToPtr:
|
|
|
|
case Instruction::BitCast:
|
|
|
|
case Instruction::Select:
|
|
|
|
case Instruction::ExtractElement:
|
|
|
|
case Instruction::InsertElement:
|
|
|
|
case Instruction::ShuffleVector:
|
|
|
|
case Instruction::InsertValue:
|
|
|
|
case Instruction::GetElementPtr:
|
2016-04-29 00:00:15 +08:00
|
|
|
exp = createExpr(I);
|
2011-07-08 09:50:54 +08:00
|
|
|
break;
|
2014-03-28 22:42:34 +08:00
|
|
|
case Instruction::ExtractValue:
|
2016-04-29 00:00:15 +08:00
|
|
|
exp = createExtractvalueExpr(cast<ExtractValueInst>(I));
|
2014-03-28 22:42:34 +08:00
|
|
|
break;
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
case Instruction::PHI:
|
|
|
|
valueNumbering[V] = nextValueNumber;
|
|
|
|
NumberingPhi[nextValueNumber] = cast<PHINode>(V);
|
|
|
|
return nextValueNumber++;
|
2009-10-20 06:14:22 +08:00
|
|
|
default:
|
|
|
|
valueNumbering[V] = nextValueNumber;
|
|
|
|
return nextValueNumber++;
|
|
|
|
}
|
|
|
|
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
uint32_t e = assignExpNewValueNum(exp).first;
|
2009-10-20 06:14:22 +08:00
|
|
|
valueNumbering[V] = e;
|
|
|
|
return e;
|
2007-07-25 01:55:58 +08:00
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Returns the value number of the specified value. Fails if
|
2007-07-25 01:55:58 +08:00
|
|
|
/// the value has not yet been numbered.
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
uint32_t GVN::ValueTable::lookup(Value *V, bool Verify) const {
|
2009-11-10 09:02:17 +08:00
|
|
|
DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
if (Verify) {
|
|
|
|
assert(VI != valueNumbering.end() && "Value not numbered?");
|
|
|
|
return VI->second;
|
|
|
|
}
|
|
|
|
return (VI != valueNumbering.end()) ? VI->second : 0;
|
2007-07-25 01:55:58 +08:00
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Returns the value number of the given comparison,
|
2012-02-27 16:14:30 +08:00
|
|
|
/// assigning it a new number if it did not have one before. Useful when
|
|
|
|
/// we deduced the result of a comparison, but don't immediately have an
|
|
|
|
/// instruction realizing that comparison to hand.
|
2016-04-29 00:00:15 +08:00
|
|
|
uint32_t GVN::ValueTable::lookupOrAddCmp(unsigned Opcode,
|
|
|
|
CmpInst::Predicate Predicate,
|
|
|
|
Value *LHS, Value *RHS) {
|
|
|
|
Expression exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
return assignExpNewValueNum(exp).first;
|
2012-02-27 16:14:30 +08:00
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Remove all entries from the ValueTable.
|
2016-03-11 16:50:55 +08:00
|
|
|
void GVN::ValueTable::clear() {
|
2007-07-25 01:55:58 +08:00
|
|
|
valueNumbering.clear();
|
|
|
|
expressionNumbering.clear();
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
NumberingPhi.clear();
|
|
|
|
PhiTranslateTable.clear();
|
2007-07-25 01:55:58 +08:00
|
|
|
nextValueNumber = 1;
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
Expressions.clear();
|
|
|
|
ExprIdx.clear();
|
|
|
|
nextExprNumber = 0;
|
2007-07-25 01:55:58 +08:00
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Remove a value from the value numbering.
|
2016-03-11 16:50:55 +08:00
|
|
|
void GVN::ValueTable::erase(Value *V) {
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
uint32_t Num = valueNumbering.lookup(V);
|
2007-08-01 07:27:13 +08:00
|
|
|
valueNumbering.erase(V);
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
// If V is PHINode, V <--> value number is an one-to-one mapping.
|
|
|
|
if (isa<PHINode>(V))
|
|
|
|
NumberingPhi.erase(Num);
|
2007-08-01 07:27:13 +08:00
|
|
|
}
|
|
|
|
|
2008-12-23 05:36:08 +08:00
|
|
|
/// verifyRemoved - Verify that the value is removed from all internal data
|
|
|
|
/// structures.
|
2016-03-11 16:50:55 +08:00
|
|
|
void GVN::ValueTable::verifyRemoved(const Value *V) const {
|
2009-11-10 09:02:17 +08:00
|
|
|
for (DenseMap<Value*, uint32_t>::const_iterator
|
2008-12-23 05:36:08 +08:00
|
|
|
I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
|
|
|
|
assert(I->first != V && "Inst still occurs in value numbering map!");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2007-07-25 01:55:58 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2008-12-23 06:32:22 +08:00
|
|
|
// GVN Pass
|
2007-07-25 01:55:58 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
2008-06-13 03:25:32 +08:00
|
|
|
|
2016-08-09 08:28:15 +08:00
|
|
|
PreservedAnalyses GVN::run(Function &F, FunctionAnalysisManager &AM) {
|
2016-03-11 21:26:47 +08:00
|
|
|
// FIXME: The order of evaluation of these 'getResult' calls is very
|
|
|
|
// significant! Re-ordering these variables will cause GVN when run alone to
|
|
|
|
// be less effective! We should fix memdep and basic-aa to not exhibit this
|
|
|
|
// behavior, but until then don't change the order here.
|
2016-12-19 16:22:17 +08:00
|
|
|
auto &AC = AM.getResult<AssumptionAnalysis>(F);
|
2016-03-11 21:26:47 +08:00
|
|
|
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
|
|
|
|
auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
|
|
|
|
auto &AA = AM.getResult<AAManager>(F);
|
|
|
|
auto &MemDep = AM.getResult<MemoryDependenceAnalysis>(F);
|
2016-12-01 11:56:43 +08:00
|
|
|
auto *LI = AM.getCachedResult<LoopAnalysis>(F);
|
2016-12-02 00:40:32 +08:00
|
|
|
auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
|
2016-12-19 16:22:17 +08:00
|
|
|
bool Changed = runImpl(F, AC, DT, TLI, AA, &MemDep, LI, &ORE);
|
2016-06-07 04:01:50 +08:00
|
|
|
if (!Changed)
|
|
|
|
return PreservedAnalyses::all();
|
|
|
|
PreservedAnalyses PA;
|
|
|
|
PA.preserve<DominatorTreeAnalysis>();
|
|
|
|
PA.preserve<GlobalsAA>();
|
2017-02-01 05:53:18 +08:00
|
|
|
PA.preserve<TargetLibraryAnalysis>();
|
2016-06-07 04:01:50 +08:00
|
|
|
return PA;
|
2009-11-14 10:27:51 +08:00
|
|
|
}
|
2007-07-25 01:55:58 +08:00
|
|
|
|
2017-10-15 22:32:27 +08:00
|
|
|
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
|
2017-06-22 06:19:17 +08:00
|
|
|
LLVM_DUMP_METHOD void GVN::dump(DenseMap<uint32_t, Value*>& d) const {
|
2009-12-18 11:25:51 +08:00
|
|
|
errs() << "{\n";
|
2008-06-19 05:41:49 +08:00
|
|
|
for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
|
2007-07-26 03:57:03 +08:00
|
|
|
E = d.end(); I != E; ++I) {
|
2009-12-18 11:25:51 +08:00
|
|
|
errs() << I->first << "\n";
|
2007-07-26 03:57:03 +08:00
|
|
|
I->second->dump();
|
|
|
|
}
|
2009-12-18 11:25:51 +08:00
|
|
|
errs() << "}\n";
|
2007-07-26 03:57:03 +08:00
|
|
|
}
|
2017-01-28 10:02:38 +08:00
|
|
|
#endif
|
2007-07-26 03:57:03 +08:00
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Return true if we can prove that the value
|
2008-12-02 16:16:11 +08:00
|
|
|
/// we're analyzing is fully available in the specified block. As we go, keep
|
2008-12-05 15:49:08 +08:00
|
|
|
/// track of which blocks we know are fully alive in FullyAvailableBlocks. This
|
|
|
|
/// map is actually a tri-state map with the following values:
|
|
|
|
/// 0) we know the block *is not* fully available.
|
|
|
|
/// 1) we know the block *is* fully available.
|
|
|
|
/// 2) we do not know whether the block is fully available or not, but we are
|
|
|
|
/// currently speculating that it will be.
|
|
|
|
/// 3) we are speculating for this block and have used that to speculate for
|
|
|
|
/// other blocks.
|
2009-09-20 10:20:51 +08:00
|
|
|
static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
|
2012-04-28 02:09:28 +08:00
|
|
|
DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
|
|
|
|
uint32_t RecurseDepth) {
|
|
|
|
if (RecurseDepth > MaxRecurseDepth)
|
|
|
|
return false;
|
|
|
|
|
2008-12-02 16:16:11 +08:00
|
|
|
// Optimistically assume that the block is fully available and check to see
|
|
|
|
// if we already know about this block in one lookup.
|
2018-08-15 23:06:53 +08:00
|
|
|
std::pair<DenseMap<BasicBlock*, char>::iterator, bool> IV =
|
2008-12-05 15:49:08 +08:00
|
|
|
FullyAvailableBlocks.insert(std::make_pair(BB, 2));
|
2008-12-02 16:16:11 +08:00
|
|
|
|
|
|
|
// If the entry already existed for this block, return the precomputed value.
|
2008-12-05 15:49:08 +08:00
|
|
|
if (!IV.second) {
|
|
|
|
// If this is a speculative "available" value, mark it as being used for
|
|
|
|
// speculation of other blocks.
|
|
|
|
if (IV.first->second == 2)
|
|
|
|
IV.first->second = 3;
|
|
|
|
return IV.first->second != 0;
|
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-12-02 16:16:11 +08:00
|
|
|
// Otherwise, see if it is fully available in all predecessors.
|
|
|
|
pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-12-02 16:16:11 +08:00
|
|
|
// If this block has no predecessors, it isn't live-in here.
|
|
|
|
if (PI == PE)
|
2008-12-05 15:49:08 +08:00
|
|
|
goto SpeculationFailure;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-12-02 16:16:11 +08:00
|
|
|
for (; PI != PE; ++PI)
|
|
|
|
// If the value isn't fully available in one of our predecessors, then it
|
|
|
|
// isn't fully available in this block either. Undo our previous
|
|
|
|
// optimistic assumption and bail out.
|
2012-04-28 02:09:28 +08:00
|
|
|
if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
|
2008-12-05 15:49:08 +08:00
|
|
|
goto SpeculationFailure;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-12-02 16:16:11 +08:00
|
|
|
return true;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
// If we get here, we found out that this is not, after
|
2008-12-05 15:49:08 +08:00
|
|
|
// all, a fully-available block. We have a problem if we speculated on this and
|
|
|
|
// used the speculation to mark other blocks as available.
|
|
|
|
SpeculationFailure:
|
|
|
|
char &BBVal = FullyAvailableBlocks[BB];
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-12-05 15:49:08 +08:00
|
|
|
// If we didn't speculate on this, just return with it set to false.
|
|
|
|
if (BBVal == 2) {
|
|
|
|
BBVal = 0;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we did speculate on this value, we could have blocks set to 1 that are
|
|
|
|
// incorrect. Walk the (transitive) successors of this block and mark them as
|
|
|
|
// 0 if set to one.
|
|
|
|
SmallVector<BasicBlock*, 32> BBWorklist;
|
|
|
|
BBWorklist.push_back(BB);
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2010-01-06 00:27:25 +08:00
|
|
|
do {
|
2008-12-05 15:49:08 +08:00
|
|
|
BasicBlock *Entry = BBWorklist.pop_back_val();
|
|
|
|
// Note that this sets blocks to 0 (unavailable) if they happen to not
|
|
|
|
// already be in FullyAvailableBlocks. This is safe.
|
|
|
|
char &EntryVal = FullyAvailableBlocks[Entry];
|
|
|
|
if (EntryVal == 0) continue; // Already unavailable.
|
|
|
|
|
|
|
|
// Mark as unavailable.
|
|
|
|
EntryVal = 0;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2014-02-10 22:17:42 +08:00
|
|
|
BBWorklist.append(succ_begin(Entry), succ_end(Entry));
|
2010-01-06 00:27:25 +08:00
|
|
|
} while (!BBWorklist.empty());
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-12-05 15:49:08 +08:00
|
|
|
return false;
|
2008-12-02 16:16:11 +08:00
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Given a set of loads specified by ValuesPerBlock,
|
2009-10-11 07:50:30 +08:00
|
|
|
/// construct SSA form, allowing us to eliminate LI. This returns the value
|
|
|
|
/// that should be used at LI's definition site.
|
2012-07-24 18:51:42 +08:00
|
|
|
static Value *ConstructSSAForLoadSet(LoadInst *LI,
|
2009-10-11 07:50:30 +08:00
|
|
|
SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
|
2011-04-29 00:36:48 +08:00
|
|
|
GVN &gvn) {
|
2009-12-22 07:15:48 +08:00
|
|
|
// Check for the fully redundant, dominating load case. In this case, we can
|
|
|
|
// just use the dominating value directly.
|
2012-07-24 18:51:42 +08:00
|
|
|
if (ValuesPerBlock.size() == 1 &&
|
2011-04-29 00:36:48 +08:00
|
|
|
gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
|
2013-11-12 06:00:23 +08:00
|
|
|
LI->getParent())) {
|
2016-01-27 07:43:16 +08:00
|
|
|
assert(!ValuesPerBlock[0].AV.isUndefValue() &&
|
|
|
|
"Dead BB dominate this block");
|
2015-03-10 10:37:25 +08:00
|
|
|
return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn);
|
2013-11-12 06:00:23 +08:00
|
|
|
}
|
2009-12-22 07:15:48 +08:00
|
|
|
|
|
|
|
// Otherwise, we have to construct SSA form.
|
2009-10-11 07:50:30 +08:00
|
|
|
SmallVector<PHINode*, 8> NewPHIs;
|
|
|
|
SSAUpdater SSAUpdate(&NewPHIs);
|
2010-09-02 16:14:03 +08:00
|
|
|
SSAUpdate.Initialize(LI->getType(), LI->getName());
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2015-11-28 16:23:04 +08:00
|
|
|
for (const AvailableValueInBlock &AV : ValuesPerBlock) {
|
2009-12-06 12:54:31 +08:00
|
|
|
BasicBlock *BB = AV.BB;
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2009-10-11 07:50:30 +08:00
|
|
|
if (SSAUpdate.HasValueForBlock(BB))
|
|
|
|
continue;
|
2009-12-06 12:54:31 +08:00
|
|
|
|
2018-07-23 20:14:45 +08:00
|
|
|
// If the value is the load that we will be eliminating, and the block it's
|
|
|
|
// available in is the block that the load is in, then don't add it as
|
|
|
|
// SSAUpdater will resolve the value to the relevant phi which may let it
|
|
|
|
// avoid phi construction entirely if there's actually only one value.
|
|
|
|
if (BB == LI->getParent() &&
|
|
|
|
((AV.AV.isSimpleValue() && AV.AV.getSimpleValue() == LI) ||
|
|
|
|
(AV.AV.isCoercedLoadValue() && AV.AV.getCoercedLoadValue() == LI)))
|
|
|
|
continue;
|
|
|
|
|
2015-03-10 10:37:25 +08:00
|
|
|
SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LI, gvn));
|
2009-09-21 04:09:34 +08:00
|
|
|
}
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2009-10-11 07:50:30 +08:00
|
|
|
// Perform PHI construction.
|
[PM/AA] Remove the addEscapingUse update API that won't be easy to
directly model in the new PM.
This also was an incredibly brittle and expensive update API that was
never fully utilized by all the passes that claimed to preserve AA, nor
could it reasonably have been extended to all of them. Any number of
places add uses of values. If we ever wanted to reliably instrument
this, we would want a callback hook much like we have with ValueHandles,
but doing this for every use addition seems *extremely* expensive in
terms of compile time.
The only user of this update mechanism is GlobalsModRef. The idea of
using this to keep it up to date doesn't really work anyways as its
analysis requires a symmetric analysis of two different memory
locations. It would be very hard to make updates be sufficiently
rigorous to *guarantee* symmetric analysis in this way, and it pretty
certainly isn't true today.
However, folks have been using GMR with this update for a long time and
seem to not be hitting the issues. The reported issue that the update
hook fixes isn't even a problem any more as other changes to
GetUnderlyingObject worked around it, and that issue stemmed from *many*
years ago. As a consequence, a prior patch provided a flag to control
the unsafe behavior of GMR, and this patch removes the update mechanism
that has questionable compile-time tradeoffs and is causing problems
with moving to the new pass manager. Note the lack of test updates --
not one test in tree actually requires this update, even for a contrived
case.
All of this was extensively discussed on the dev list, this patch will
just enact what that discussion decides on. I'm sending it for review in
part to show what I'm planning, and in part to show the *amazing* amount
of work this avoids. Every call to the AA here is something like three
to six indirect function calls, which in the non-LTO pipeline never do
any work! =[
Differential Revision: http://reviews.llvm.org/D11214
llvm-svn: 242605
2015-07-18 11:26:46 +08:00
|
|
|
return SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
|
2009-09-21 04:09:34 +08:00
|
|
|
}
|
|
|
|
|
2016-01-27 07:43:16 +08:00
|
|
|
Value *AvailableValue::MaterializeAdjustedValue(LoadInst *LI,
|
|
|
|
Instruction *InsertPt,
|
|
|
|
GVN &gvn) const {
|
2013-05-04 03:17:26 +08:00
|
|
|
Value *Res;
|
2015-03-10 10:37:25 +08:00
|
|
|
Type *LoadTy = LI->getType();
|
|
|
|
const DataLayout &DL = LI->getModule()->getDataLayout();
|
2016-10-21 09:37:02 +08:00
|
|
|
if (isSimpleValue()) {
|
2013-05-04 03:17:26 +08:00
|
|
|
Res = getSimpleValue();
|
|
|
|
if (Res->getType() != LoadTy) {
|
2017-03-10 12:54:10 +08:00
|
|
|
Res = getStoreValueForLoad(Res, Offset, LoadTy, InsertPt, DL);
|
2015-03-10 10:37:25 +08:00
|
|
|
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset
|
|
|
|
<< " " << *getSimpleValue() << '\n'
|
|
|
|
<< *Res << '\n'
|
|
|
|
<< "\n\n\n");
|
2013-05-04 03:17:26 +08:00
|
|
|
}
|
|
|
|
} else if (isCoercedLoadValue()) {
|
|
|
|
LoadInst *Load = getCoercedLoadValue();
|
|
|
|
if (Load->getType() == LoadTy && Offset == 0) {
|
|
|
|
Res = Load;
|
|
|
|
} else {
|
2017-03-21 00:08:29 +08:00
|
|
|
Res = getLoadValueForLoad(Load, Offset, LoadTy, InsertPt, DL);
|
2017-03-10 12:54:10 +08:00
|
|
|
// We would like to use gvn.markInstructionForDeletion here, but we can't
|
|
|
|
// because the load is already memoized into the leader map table that GVN
|
|
|
|
// tracks. It is potentially possible to remove the load from the table,
|
|
|
|
// but then there all of the operations based on it would need to be
|
|
|
|
// rehashed. Just leave the dead load around.
|
|
|
|
gvn.getMemDep().removeInstruction(Load);
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset
|
|
|
|
<< " " << *getCoercedLoadValue() << '\n'
|
|
|
|
<< *Res << '\n'
|
|
|
|
<< "\n\n\n");
|
2013-05-04 03:17:26 +08:00
|
|
|
}
|
2013-11-12 06:00:23 +08:00
|
|
|
} else if (isMemIntrinValue()) {
|
2017-03-10 12:54:10 +08:00
|
|
|
Res = getMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy,
|
2016-01-27 07:43:16 +08:00
|
|
|
InsertPt, DL);
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
|
|
|
|
<< " " << *getMemIntrinValue() << '\n'
|
|
|
|
<< *Res << '\n'
|
|
|
|
<< "\n\n\n");
|
2013-11-12 06:00:23 +08:00
|
|
|
} else {
|
|
|
|
assert(isUndefValue() && "Should be UndefVal");
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
|
2013-11-12 06:00:23 +08:00
|
|
|
return UndefValue::get(LoadTy);
|
2013-05-04 03:17:26 +08:00
|
|
|
}
|
2016-01-27 07:43:16 +08:00
|
|
|
assert(Res && "failed to materialize?");
|
2013-05-04 03:17:26 +08:00
|
|
|
return Res;
|
|
|
|
}
|
|
|
|
|
2010-04-09 18:57:00 +08:00
|
|
|
static bool isLifetimeStart(const Instruction *Inst) {
|
|
|
|
if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
|
2009-12-02 15:35:19 +08:00
|
|
|
return II->getIntrinsicID() == Intrinsic::lifetime_start;
|
2009-12-02 14:44:58 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2018-05-01 23:54:18 +08:00
|
|
|
/// Try to locate the three instruction involved in a missed
|
2016-12-02 01:34:50 +08:00
|
|
|
/// load-elimination case that is due to an intervening store.
|
|
|
|
static void reportMayClobberedLoad(LoadInst *LI, MemDepResult DepInfo,
|
|
|
|
DominatorTree *DT,
|
|
|
|
OptimizationRemarkEmitter *ORE) {
|
|
|
|
using namespace ore;
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2016-12-02 01:34:50 +08:00
|
|
|
User *OtherAccess = nullptr;
|
|
|
|
|
|
|
|
OptimizationRemarkMissed R(DEBUG_TYPE, "LoadClobbered", LI);
|
|
|
|
R << "load of type " << NV("Type", LI->getType()) << " not eliminated"
|
|
|
|
<< setExtraArgs();
|
|
|
|
|
|
|
|
for (auto *U : LI->getPointerOperand()->users())
|
|
|
|
if (U != LI && (isa<LoadInst>(U) || isa<StoreInst>(U)) &&
|
|
|
|
DT->dominates(cast<Instruction>(U), LI)) {
|
|
|
|
// FIXME: for now give up if there are multiple memory accesses that
|
|
|
|
// dominate the load. We need further analysis to decide which one is
|
|
|
|
// that we're forwarding from.
|
|
|
|
if (OtherAccess)
|
|
|
|
OtherAccess = nullptr;
|
|
|
|
else
|
|
|
|
OtherAccess = U;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (OtherAccess)
|
|
|
|
R << " in favor of " << NV("OtherAccess", OtherAccess);
|
|
|
|
|
|
|
|
R << " because it is clobbered by " << NV("ClobberedBy", DepInfo.getInst());
|
|
|
|
|
|
|
|
ORE->emit(R);
|
|
|
|
}
|
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
bool GVN::AnalyzeLoadAvailability(LoadInst *LI, MemDepResult DepInfo,
|
|
|
|
Value *Address, AvailableValue &Res) {
|
|
|
|
assert((DepInfo.isDef() || DepInfo.isClobber()) &&
|
|
|
|
"expected a local dependence");
|
2016-05-07 02:17:13 +08:00
|
|
|
assert(LI->isUnordered() && "rules below are incorrect for ordered access");
|
2016-02-13 03:24:57 +08:00
|
|
|
|
|
|
|
const DataLayout &DL = LI->getModule()->getDataLayout();
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
if (DepInfo.isClobber()) {
|
|
|
|
// If the dependence is to a store that writes to a superset of the bits
|
|
|
|
// read by the load, we can extract the bits we need for the load from the
|
|
|
|
// stored value.
|
|
|
|
if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
|
2016-05-07 02:17:13 +08:00
|
|
|
// Can't forward from non-atomic to atomic without violating memory model.
|
|
|
|
if (Address && LI->isAtomic() <= DepSI->isAtomic()) {
|
2016-02-13 03:24:57 +08:00
|
|
|
int Offset =
|
2017-03-11 08:51:01 +08:00
|
|
|
analyzeLoadFromClobberingStore(LI->getType(), Address, DepSI, DL);
|
2016-02-13 03:24:57 +08:00
|
|
|
if (Offset != -1) {
|
|
|
|
Res = AvailableValue::get(DepSI->getValueOperand(), Offset);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check to see if we have something like this:
|
|
|
|
// load i32* P
|
|
|
|
// load i8* (P+1)
|
|
|
|
// if we have this, replace the later with an extraction from the former.
|
|
|
|
if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
|
|
|
|
// If this is a clobber and L is the first instruction in its block, then
|
|
|
|
// we have the first instruction in the entry block.
|
2016-05-07 02:17:13 +08:00
|
|
|
// Can't forward from non-atomic to atomic without violating memory model.
|
|
|
|
if (DepLI != LI && Address && LI->isAtomic() <= DepLI->isAtomic()) {
|
2016-02-13 03:24:57 +08:00
|
|
|
int Offset =
|
2017-03-10 12:54:10 +08:00
|
|
|
analyzeLoadFromClobberingLoad(LI->getType(), Address, DepLI, DL);
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
if (Offset != -1) {
|
|
|
|
Res = AvailableValue::getLoad(DepLI, Offset);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the clobbering value is a memset/memcpy/memmove, see if we can
|
|
|
|
// forward a value on from it.
|
|
|
|
if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
|
2016-05-07 02:17:13 +08:00
|
|
|
if (Address && !LI->isAtomic()) {
|
2017-03-10 12:54:10 +08:00
|
|
|
int Offset = analyzeLoadFromClobberingMemInst(LI->getType(), Address,
|
2016-02-13 03:24:57 +08:00
|
|
|
DepMI, DL);
|
|
|
|
if (Offset != -1) {
|
|
|
|
Res = AvailableValue::getMI(DepMI, Offset);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Nothing known about this clobber, have to be conservative
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(
|
|
|
|
// fast print dep, using operator<< on instruction is too slow.
|
|
|
|
dbgs() << "GVN: load "; LI->printAsOperand(dbgs());
|
|
|
|
Instruction *I = DepInfo.getInst();
|
|
|
|
dbgs() << " is clobbered by " << *I << '\n';);
|
2017-09-16 04:10:09 +08:00
|
|
|
if (ORE->allowExtraAnalysis(DEBUG_TYPE))
|
2016-12-02 01:34:50 +08:00
|
|
|
reportMayClobberedLoad(LI, DepInfo, DT, ORE);
|
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
assert(DepInfo.isDef() && "follows from above");
|
|
|
|
|
|
|
|
Instruction *DepInst = DepInfo.getInst();
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
// Loading the allocation -> undef.
|
|
|
|
if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
|
|
|
|
// Loading immediately after lifetime begin -> undef.
|
|
|
|
isLifetimeStart(DepInst)) {
|
|
|
|
Res = AvailableValue::get(UndefValue::get(LI->getType()));
|
|
|
|
return true;
|
|
|
|
}
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
// Loading from calloc (which zero initializes memory) -> zero
|
|
|
|
if (isCallocLikeFn(DepInst, TLI)) {
|
|
|
|
Res = AvailableValue::get(Constant::getNullValue(LI->getType()));
|
|
|
|
return true;
|
|
|
|
}
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
|
|
|
|
// Reject loads and stores that are to the same address but are of
|
|
|
|
// different types if we have to. If the stored value is larger or equal to
|
|
|
|
// the loaded value, we can reuse it.
|
|
|
|
if (S->getValueOperand()->getType() != LI->getType() &&
|
2017-03-10 12:54:10 +08:00
|
|
|
!canCoerceMustAliasedValueToLoad(S->getValueOperand(),
|
2016-02-13 03:24:57 +08:00
|
|
|
LI->getType(), DL))
|
|
|
|
return false;
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2016-05-07 02:17:13 +08:00
|
|
|
// Can't forward from non-atomic to atomic without violating memory model.
|
|
|
|
if (S->isAtomic() < LI->isAtomic())
|
|
|
|
return false;
|
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
Res = AvailableValue::get(S->getValueOperand());
|
|
|
|
return true;
|
|
|
|
}
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
|
|
|
|
// If the types mismatch and we can't handle it, reject reuse of the load.
|
|
|
|
// If the stored value is larger or equal to the loaded value, we can reuse
|
2016-04-29 00:00:15 +08:00
|
|
|
// it.
|
2016-02-13 03:24:57 +08:00
|
|
|
if (LD->getType() != LI->getType() &&
|
2017-03-10 12:54:10 +08:00
|
|
|
!canCoerceMustAliasedValueToLoad(LD, LI->getType(), DL))
|
2016-02-13 03:24:57 +08:00
|
|
|
return false;
|
|
|
|
|
2016-05-07 02:17:13 +08:00
|
|
|
// Can't forward from non-atomic to atomic without violating memory model.
|
|
|
|
if (LD->isAtomic() < LI->isAtomic())
|
|
|
|
return false;
|
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
Res = AvailableValue::getLoad(LD);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unknown def - must be conservative
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(
|
|
|
|
// fast print dep, using operator<< on instruction is too slow.
|
|
|
|
dbgs() << "GVN: load "; LI->printAsOperand(dbgs());
|
|
|
|
dbgs() << " has unknown def " << *DepInst << '\n';);
|
2016-02-13 03:24:57 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2016-04-29 00:00:15 +08:00
|
|
|
void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
|
2013-05-04 03:17:26 +08:00
|
|
|
AvailValInBlkVect &ValuesPerBlock,
|
|
|
|
UnavailBlkVect &UnavailableBlocks) {
|
2008-12-02 16:16:11 +08:00
|
|
|
// Filter out useless results (non-locals, etc). Keep track of the blocks
|
|
|
|
// where we have a value available in repl, also keep track of whether we see
|
|
|
|
// dependencies that produce an unknown value for the load (such as a call
|
|
|
|
// that could potentially clobber the load).
|
2013-05-04 03:17:26 +08:00
|
|
|
unsigned NumDeps = Deps.size();
|
2012-01-31 14:57:53 +08:00
|
|
|
for (unsigned i = 0, e = NumDeps; i != e; ++i) {
|
2009-12-09 15:08:01 +08:00
|
|
|
BasicBlock *DepBB = Deps[i].getBB();
|
|
|
|
MemDepResult DepInfo = Deps[i].getResult();
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2013-11-12 06:00:23 +08:00
|
|
|
if (DeadBlocks.count(DepBB)) {
|
|
|
|
// Dead dependent mem-op disguise as a load evaluating the same value
|
|
|
|
// as the load in question.
|
|
|
|
ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2016-10-21 09:37:02 +08:00
|
|
|
if (!DepInfo.isDef() && !DepInfo.isClobber()) {
|
2011-06-15 08:47:34 +08:00
|
|
|
UnavailableBlocks.push_back(DepBB);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
// The address being loaded in this non-local block may not be the same as
|
|
|
|
// the pointer operand of the load if PHI translation occurs. Make sure
|
|
|
|
// to consider the right address.
|
|
|
|
Value *Address = Deps[i].getAddress();
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
AvailableValue AV;
|
2016-10-21 09:37:02 +08:00
|
|
|
if (AnalyzeLoadAvailability(LI, DepInfo, Address, AV)) {
|
2016-02-13 03:24:57 +08:00
|
|
|
// subtlety: because we know this was a non-local dependency, we know
|
|
|
|
// it's safe to materialize anywhere between the instruction within
|
|
|
|
// DepInfo and the end of it's block.
|
2016-10-21 09:37:02 +08:00
|
|
|
ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
|
|
|
|
std::move(AV)));
|
2016-02-13 03:24:57 +08:00
|
|
|
} else {
|
|
|
|
UnavailableBlocks.push_back(DepBB);
|
2007-07-26 03:57:03 +08:00
|
|
|
}
|
2007-08-08 07:12:31 +08:00
|
|
|
}
|
2016-02-13 03:24:57 +08:00
|
|
|
|
|
|
|
assert(NumDeps == ValuesPerBlock.size() + UnavailableBlocks.size() &&
|
|
|
|
"post condition violation");
|
2013-05-04 03:17:26 +08:00
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2016-04-29 00:00:15 +08:00
|
|
|
bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
|
2013-05-04 03:17:26 +08:00
|
|
|
UnavailBlkVect &UnavailableBlocks) {
|
2008-12-02 16:16:11 +08:00
|
|
|
// Okay, we have *some* definitions of the value. This means that the value
|
|
|
|
// is available in some of our (transitive) predecessors. Lets think about
|
|
|
|
// doing PRE of this load. This will involve inserting a new load into the
|
|
|
|
// predecessor when it's not available. We could do this in general, but
|
|
|
|
// prefer to not increase code size. As such, we only do this when we know
|
|
|
|
// that we only have to insert *one* load (which means we're basically moving
|
|
|
|
// the load, not inserting a new one).
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2015-11-28 16:23:04 +08:00
|
|
|
SmallPtrSet<BasicBlock *, 4> Blockers(UnavailableBlocks.begin(),
|
|
|
|
UnavailableBlocks.end());
|
2009-05-31 17:03:40 +08:00
|
|
|
|
2011-08-18 05:32:02 +08:00
|
|
|
// Let's find the first basic block with more than one predecessor. Walk
|
|
|
|
// backwards through predecessors if needed.
|
2008-12-02 16:16:11 +08:00
|
|
|
BasicBlock *LoadBB = LI->getParent();
|
2009-05-31 17:03:40 +08:00
|
|
|
BasicBlock *TmpBB = LoadBB;
|
2017-10-31 13:07:56 +08:00
|
|
|
bool IsSafeToSpeculativelyExecute = isSafeToSpeculativelyExecute(LI);
|
2009-05-31 17:03:40 +08:00
|
|
|
|
2017-10-31 13:07:56 +08:00
|
|
|
// Check that there is no implicit control flow instructions above our load in
|
|
|
|
// its block. If there is an instruction that doesn't always pass the
|
|
|
|
// execution to the following instruction, then moving through it may become
|
|
|
|
// invalid. For example:
|
|
|
|
//
|
|
|
|
// int arr[LEN];
|
|
|
|
// int index = ???;
|
|
|
|
// ...
|
|
|
|
// guard(0 <= index && index < LEN);
|
|
|
|
// use(arr[index]);
|
|
|
|
//
|
|
|
|
// It is illegal to move the array access to any point above the guard,
|
|
|
|
// because if the index is out of bounds we should deoptimize rather than
|
|
|
|
// access the array.
|
2018-06-14 13:41:49 +08:00
|
|
|
// Check that there is no guard in this block above our instruction.
|
2018-08-07 09:47:20 +08:00
|
|
|
if (!IsSafeToSpeculativelyExecute && ICF->isDominatedByICFIFromSameBlock(LI))
|
|
|
|
return false;
|
2009-05-31 17:03:40 +08:00
|
|
|
while (TmpBB->getSinglePredecessor()) {
|
|
|
|
TmpBB = TmpBB->getSinglePredecessor();
|
|
|
|
if (TmpBB == LoadBB) // Infinite (unreachable) loop.
|
|
|
|
return false;
|
|
|
|
if (Blockers.count(TmpBB))
|
|
|
|
return false;
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2010-09-25 13:26:18 +08:00
|
|
|
// If any of these blocks has more than one successor (i.e. if the edge we
|
2012-07-24 18:51:42 +08:00
|
|
|
// just traversed was critical), then there are other paths through this
|
|
|
|
// block along which the load may not be anticipated. Hoisting the load
|
2010-09-25 13:26:18 +08:00
|
|
|
// above this block would be adding the load to execution paths along
|
|
|
|
// which it was not previously executed.
|
2009-06-18 04:48:23 +08:00
|
|
|
if (TmpBB->getTerminator()->getNumSuccessors() != 1)
|
2010-09-25 13:26:18 +08:00
|
|
|
return false;
|
2017-10-31 13:07:56 +08:00
|
|
|
|
|
|
|
// Check that there is no implicit control flow in a block above.
|
2018-08-07 09:47:20 +08:00
|
|
|
if (!IsSafeToSpeculativelyExecute && ICF->hasICF(TmpBB))
|
2017-10-31 13:07:56 +08:00
|
|
|
return false;
|
2009-05-31 17:03:40 +08:00
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2009-05-31 17:03:40 +08:00
|
|
|
assert(TmpBB);
|
|
|
|
LoadBB = TmpBB;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2010-02-02 05:17:14 +08:00
|
|
|
// Check to see how many predecessors have the loaded value fully
|
|
|
|
// available.
|
2014-05-14 05:06:40 +08:00
|
|
|
MapVector<BasicBlock *, Value *> PredLoads;
|
2008-12-05 15:49:08 +08:00
|
|
|
DenseMap<BasicBlock*, char> FullyAvailableBlocks;
|
2015-11-28 16:23:04 +08:00
|
|
|
for (const AvailableValueInBlock &AV : ValuesPerBlock)
|
|
|
|
FullyAvailableBlocks[AV.BB] = true;
|
|
|
|
for (BasicBlock *UnavailableBB : UnavailableBlocks)
|
|
|
|
FullyAvailableBlocks[UnavailableBB] = false;
|
2008-12-01 08:40:32 +08:00
|
|
|
|
2013-05-10 02:34:27 +08:00
|
|
|
SmallVector<BasicBlock *, 4> CriticalEdgePred;
|
2015-11-28 16:23:04 +08:00
|
|
|
for (BasicBlock *Pred : predecessors(LoadBB)) {
|
2015-11-24 03:51:41 +08:00
|
|
|
// If any predecessor block is an EH pad that does not allow non-PHI
|
|
|
|
// instructions before the terminator, we can't PRE the load.
|
|
|
|
if (Pred->getTerminator()->isEHPad()) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(
|
|
|
|
dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '"
|
|
|
|
<< Pred->getName() << "': " << *LI << '\n');
|
2015-11-24 03:51:41 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2012-04-28 02:09:28 +08:00
|
|
|
if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
|
2008-12-02 16:16:11 +08:00
|
|
|
continue;
|
2010-02-02 05:17:14 +08:00
|
|
|
}
|
2010-02-17 03:51:59 +08:00
|
|
|
|
2010-02-02 05:17:14 +08:00
|
|
|
if (Pred->getTerminator()->getNumSuccessors() != 1) {
|
2010-02-17 03:51:59 +08:00
|
|
|
if (isa<IndirectBrInst>(Pred->getTerminator())) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(
|
|
|
|
dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
|
|
|
|
<< Pred->getName() << "': " << *LI << '\n');
|
2010-02-17 03:51:59 +08:00
|
|
|
return false;
|
|
|
|
}
|
2011-08-18 05:32:02 +08:00
|
|
|
|
2019-02-09 04:48:56 +08:00
|
|
|
// FIXME: Can we support the fallthrough edge?
|
|
|
|
if (isa<CallBrInst>(Pred->getTerminator())) {
|
|
|
|
LLVM_DEBUG(
|
|
|
|
dbgs() << "COULD NOT PRE LOAD BECAUSE OF CALLBR CRITICAL EDGE '"
|
|
|
|
<< Pred->getName() << "': " << *LI << '\n');
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2015-08-04 16:21:40 +08:00
|
|
|
if (LoadBB->isEHPad()) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(
|
|
|
|
dbgs() << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '"
|
|
|
|
<< Pred->getName() << "': " << *LI << '\n');
|
2011-08-18 05:32:02 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2013-05-10 02:34:27 +08:00
|
|
|
CriticalEdgePred.push_back(Pred);
|
2014-05-14 05:06:40 +08:00
|
|
|
} else {
|
|
|
|
// Only add the predecessors that will not be split for now.
|
|
|
|
PredLoads[Pred] = nullptr;
|
2010-02-02 05:17:14 +08:00
|
|
|
}
|
2008-12-02 16:16:11 +08:00
|
|
|
}
|
2011-08-18 05:32:02 +08:00
|
|
|
|
2010-02-02 05:17:14 +08:00
|
|
|
// Decide whether PRE is profitable for this load.
|
2014-05-14 05:06:40 +08:00
|
|
|
unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size();
|
2010-02-02 05:17:14 +08:00
|
|
|
assert(NumUnavailablePreds != 0 &&
|
2013-05-10 02:34:27 +08:00
|
|
|
"Fully available value should already be eliminated!");
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2010-10-02 04:02:55 +08:00
|
|
|
// If this load is unavailable in multiple predecessors, reject it.
|
|
|
|
// FIXME: If we could restructure the CFG, we could make a common pred with
|
|
|
|
// all the preds that don't have an available LI and insert a new load into
|
|
|
|
// that one block.
|
|
|
|
if (NumUnavailablePreds != 1)
|
2010-02-02 05:17:14 +08:00
|
|
|
return false;
|
|
|
|
|
2013-05-10 02:34:27 +08:00
|
|
|
// Split critical edges, and update the unavailable predecessors accordingly.
|
2014-05-14 05:06:36 +08:00
|
|
|
for (BasicBlock *OrigPred : CriticalEdgePred) {
|
2013-05-10 02:34:27 +08:00
|
|
|
BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
|
2014-05-14 05:06:40 +08:00
|
|
|
assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
|
2014-04-25 13:29:35 +08:00
|
|
|
PredLoads[NewPred] = nullptr;
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
|
|
|
|
<< LoadBB->getName() << '\n');
|
2013-05-10 02:34:27 +08:00
|
|
|
}
|
|
|
|
|
2010-02-02 05:17:14 +08:00
|
|
|
// Check if the load can safely be moved to all the unavailable predecessors.
|
|
|
|
bool CanDoPRE = true;
|
2015-03-10 10:37:25 +08:00
|
|
|
const DataLayout &DL = LI->getModule()->getDataLayout();
|
2009-11-28 23:39:14 +08:00
|
|
|
SmallVector<Instruction*, 8> NewInsts;
|
2014-05-14 05:06:36 +08:00
|
|
|
for (auto &PredLoad : PredLoads) {
|
|
|
|
BasicBlock *UnavailablePred = PredLoad.first;
|
2010-02-02 05:17:14 +08:00
|
|
|
|
|
|
|
// Do PHI translation to get its value in the predecessor if necessary. The
|
|
|
|
// returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
|
|
|
|
|
|
|
|
// If all preds have a single successor, then we know it is safe to insert
|
|
|
|
// the load on the pred (?!?), so we can insert code to materialize the
|
|
|
|
// pointer if it is not available.
|
2016-12-19 16:22:17 +08:00
|
|
|
PHITransAddr Address(LI->getPointerOperand(), DL, AC);
|
2014-04-25 13:29:35 +08:00
|
|
|
Value *LoadPtr = nullptr;
|
2013-05-03 05:14:31 +08:00
|
|
|
LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
|
|
|
|
*DT, NewInsts);
|
2009-12-03 11:43:29 +08:00
|
|
|
|
2010-02-02 05:17:14 +08:00
|
|
|
// If we couldn't find or insert a computation of this phi translated value,
|
|
|
|
// we fail PRE.
|
2014-04-25 13:29:35 +08:00
|
|
|
if (!LoadPtr) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
|
|
|
|
<< *LI->getPointerOperand() << "\n");
|
2010-02-02 05:17:14 +08:00
|
|
|
CanDoPRE = false;
|
|
|
|
break;
|
|
|
|
}
|
2009-12-09 09:59:31 +08:00
|
|
|
|
2014-05-14 05:06:36 +08:00
|
|
|
PredLoad.second = LoadPtr;
|
2009-12-09 09:59:31 +08:00
|
|
|
}
|
2010-02-02 05:17:14 +08:00
|
|
|
|
|
|
|
if (!CanDoPRE) {
|
2011-01-11 16:19:16 +08:00
|
|
|
while (!NewInsts.empty()) {
|
|
|
|
Instruction *I = NewInsts.pop_back_val();
|
2017-10-30 12:48:34 +08:00
|
|
|
markInstructionForDeletion(I);
|
2011-01-11 16:19:16 +08:00
|
|
|
}
|
2014-05-14 05:06:36 +08:00
|
|
|
// HINT: Don't revert the edge-splitting as following transformation may
|
|
|
|
// also need to split these critical edges.
|
2013-05-10 02:34:27 +08:00
|
|
|
return !CriticalEdgePred.empty();
|
2009-11-29 00:08:18 +08:00
|
|
|
}
|
2009-06-18 04:48:23 +08:00
|
|
|
|
2008-12-02 16:16:11 +08:00
|
|
|
// Okay, we can eliminate this load by inserting a reload in the predecessor
|
|
|
|
// and using PHI construction to get the value in the other predecessors, do
|
|
|
|
// it.
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
|
|
|
|
LLVM_DEBUG(if (!NewInsts.empty()) dbgs()
|
|
|
|
<< "INSERTED " << NewInsts.size() << " INSTS: " << *NewInsts.back()
|
|
|
|
<< '\n');
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2010-02-02 05:17:14 +08:00
|
|
|
// Assign value numbers to the new instructions.
|
2015-11-28 16:23:04 +08:00
|
|
|
for (Instruction *I : NewInsts) {
|
2017-01-05 07:58:26 +08:00
|
|
|
// Instructions that have been inserted in predecessor(s) to materialize
|
|
|
|
// the load address do not retain their original debug locations. Doing
|
|
|
|
// so could lead to confusing (but correct) source attributions.
|
|
|
|
// FIXME: How do we retain source locations without causing poor debugging
|
|
|
|
// behavior?
|
|
|
|
I->setDebugLoc(DebugLoc());
|
|
|
|
|
2012-07-24 18:51:42 +08:00
|
|
|
// FIXME: We really _ought_ to insert these value numbers into their
|
2010-02-02 05:17:14 +08:00
|
|
|
// parent's availability map. However, in doing so, we risk getting into
|
|
|
|
// ordering issues. If a block hasn't been processed yet, we would be
|
|
|
|
// marking a value as AVAIL-IN, which isn't what we intend.
|
2016-04-29 00:00:15 +08:00
|
|
|
VN.lookupOrAdd(I);
|
2010-02-02 05:17:14 +08:00
|
|
|
}
|
|
|
|
|
2014-05-14 05:06:36 +08:00
|
|
|
for (const auto &PredLoad : PredLoads) {
|
|
|
|
BasicBlock *UnavailablePred = PredLoad.first;
|
|
|
|
Value *LoadPtr = PredLoad.second;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2019-02-02 04:44:24 +08:00
|
|
|
auto *NewLoad =
|
|
|
|
new LoadInst(LI->getType(), LoadPtr, LI->getName() + ".pre",
|
|
|
|
LI->isVolatile(), LI->getAlignment(), LI->getOrdering(),
|
|
|
|
LI->getSyncScopeID(), UnavailablePred->getTerminator());
|
2017-07-19 09:27:24 +08:00
|
|
|
NewLoad->setDebugLoc(LI->getDebugLoc());
|
2010-12-16 07:53:55 +08:00
|
|
|
|
2014-07-24 20:16:19 +08:00
|
|
|
// Transfer the old load's AA tags to the new load.
|
|
|
|
AAMDNodes Tags;
|
|
|
|
LI->getAAMetadata(Tags);
|
|
|
|
if (Tags)
|
|
|
|
NewLoad->setAAMetadata(Tags);
|
2010-02-02 05:17:14 +08:00
|
|
|
|
2015-11-17 08:15:09 +08:00
|
|
|
if (auto *MD = LI->getMetadata(LLVMContext::MD_invariant_load))
|
|
|
|
NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
|
2015-10-03 06:12:22 +08:00
|
|
|
if (auto *InvGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group))
|
|
|
|
NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
|
2016-05-28 03:03:10 +08:00
|
|
|
if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range))
|
|
|
|
NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
|
2015-10-03 06:12:22 +08:00
|
|
|
|
2017-01-05 07:58:26 +08:00
|
|
|
// We do not propagate the old load's debug location, because the new
|
|
|
|
// load now lives in a different BB, and we want to avoid a jumpy line
|
|
|
|
// table.
|
|
|
|
// FIXME: How do we retain source locations without causing poor debugging
|
|
|
|
// behavior?
|
2011-05-18 03:43:38 +08:00
|
|
|
|
2010-02-02 05:17:14 +08:00
|
|
|
// Add the newly created load.
|
|
|
|
ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
|
|
|
|
NewLoad));
|
2010-02-23 13:55:00 +08:00
|
|
|
MD->invalidateCachedPointerInfo(LoadPtr);
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
|
2010-02-02 05:17:14 +08:00
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-12-02 16:16:11 +08:00
|
|
|
// Perform PHI construction.
|
2011-04-29 00:36:48 +08:00
|
|
|
Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
|
2009-09-21 04:09:34 +08:00
|
|
|
LI->replaceAllUsesWith(V);
|
|
|
|
if (isa<PHINode>(V))
|
|
|
|
V->takeName(LI);
|
2015-06-11 01:37:38 +08:00
|
|
|
if (Instruction *I = dyn_cast<Instruction>(V))
|
|
|
|
I->setDebugLoc(LI->getDebugLoc());
|
2017-07-09 15:04:00 +08:00
|
|
|
if (V->getType()->isPtrOrPtrVectorTy())
|
2009-09-21 04:09:34 +08:00
|
|
|
MD->invalidateCachedPointerInfo(V);
|
2011-04-29 00:36:48 +08:00
|
|
|
markInstructionForDeletion(LI);
|
2017-10-12 01:12:59 +08:00
|
|
|
ORE->emit([&]() {
|
|
|
|
return OptimizationRemark(DEBUG_TYPE, "LoadPRE", LI)
|
|
|
|
<< "load eliminated by PRE";
|
|
|
|
});
|
2010-06-22 23:08:57 +08:00
|
|
|
++NumPRELoad;
|
2007-07-26 03:57:03 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2016-12-02 01:34:44 +08:00
|
|
|
static void reportLoadElim(LoadInst *LI, Value *AvailableValue,
|
|
|
|
OptimizationRemarkEmitter *ORE) {
|
|
|
|
using namespace ore;
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2017-10-12 01:12:59 +08:00
|
|
|
ORE->emit([&]() {
|
|
|
|
return OptimizationRemark(DEBUG_TYPE, "LoadElim", LI)
|
|
|
|
<< "load of type " << NV("Type", LI->getType()) << " eliminated"
|
|
|
|
<< setExtraArgs() << " in favor of "
|
|
|
|
<< NV("InfavorOfValue", AvailableValue);
|
|
|
|
});
|
2016-12-02 00:40:32 +08:00
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Attempt to eliminate a load whose dependencies are
|
2013-05-04 03:17:26 +08:00
|
|
|
/// non-local by performing PHI construction.
|
|
|
|
bool GVN::processNonLocalLoad(LoadInst *LI) {
|
2015-11-19 04:43:00 +08:00
|
|
|
// non-local speculations are not allowed under asan.
|
2017-12-09 08:21:41 +08:00
|
|
|
if (LI->getParent()->getParent()->hasFnAttribute(
|
|
|
|
Attribute::SanitizeAddress) ||
|
|
|
|
LI->getParent()->getParent()->hasFnAttribute(
|
|
|
|
Attribute::SanitizeHWAddress))
|
2015-11-19 04:43:00 +08:00
|
|
|
return false;
|
|
|
|
|
2013-05-04 03:17:26 +08:00
|
|
|
// Step 1: Find the non-local dependencies of the load.
|
|
|
|
LoadDepVect Deps;
|
2015-01-09 08:04:22 +08:00
|
|
|
MD->getNonLocalPointerDependency(LI, Deps);
|
2013-05-04 03:17:26 +08:00
|
|
|
|
|
|
|
// If we had to process more than one hundred blocks to find the
|
|
|
|
// dependencies, this load isn't worth worrying about. Optimizing
|
|
|
|
// it will be too expensive.
|
|
|
|
unsigned NumDeps = Deps.size();
|
2018-09-10 23:07:59 +08:00
|
|
|
if (NumDeps > MaxNumDeps)
|
2013-05-04 03:17:26 +08:00
|
|
|
return false;
|
|
|
|
|
|
|
|
// If we had a phi translation failure, we'll have a single entry which is a
|
|
|
|
// clobber in the current block. Reject this early.
|
|
|
|
if (NumDeps == 1 &&
|
|
|
|
!Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN: non-local load "; LI->printAsOperand(dbgs());
|
|
|
|
dbgs() << " has unknown dependencies\n";);
|
2013-05-04 03:17:26 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2015-01-10 03:19:56 +08:00
|
|
|
// If this load follows a GEP, see if we can PRE the indices before analyzing.
|
|
|
|
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) {
|
|
|
|
for (GetElementPtrInst::op_iterator OI = GEP->idx_begin(),
|
|
|
|
OE = GEP->idx_end();
|
|
|
|
OI != OE; ++OI)
|
|
|
|
if (Instruction *I = dyn_cast<Instruction>(OI->get()))
|
|
|
|
performScalarPRE(I);
|
|
|
|
}
|
|
|
|
|
2013-05-04 03:17:26 +08:00
|
|
|
// Step 2: Analyze the availability of the load
|
|
|
|
AvailValInBlkVect ValuesPerBlock;
|
|
|
|
UnavailBlkVect UnavailableBlocks;
|
|
|
|
AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
|
|
|
|
|
|
|
|
// If we have no predecessors that produce a known value for this load, exit
|
|
|
|
// early.
|
|
|
|
if (ValuesPerBlock.empty())
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Step 3: Eliminate fully redundancy.
|
|
|
|
//
|
|
|
|
// If all of the instructions we depend on produce a known value for this
|
|
|
|
// load, then it is fully redundant and we can use PHI insertion to compute
|
|
|
|
// its value. Insert PHIs and remove the fully redundant value now.
|
|
|
|
if (UnavailableBlocks.empty()) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
|
2013-05-04 03:17:26 +08:00
|
|
|
|
|
|
|
// Perform PHI construction.
|
|
|
|
Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
|
|
|
|
LI->replaceAllUsesWith(V);
|
|
|
|
|
|
|
|
if (isa<PHINode>(V))
|
|
|
|
V->takeName(LI);
|
2015-06-11 01:37:38 +08:00
|
|
|
if (Instruction *I = dyn_cast<Instruction>(V))
|
2016-12-07 20:31:36 +08:00
|
|
|
// If instruction I has debug info, then we should not update it.
|
|
|
|
// Also, if I has a null DebugLoc, then it is still potentially incorrect
|
|
|
|
// to propagate LI's DebugLoc because LI may not post-dominate I.
|
Do not propagate DebugLoc across basic blocks
Summary:
DebugLoc shouldn't be propagated across basic blocks to prevent incorrect stepping and imprecise sample profile result. rL288903 addressed the wrong DebugLoc propagation issue by limiting the copy of DebugLoc when GVN removes a fully redundant load that is dominated by some other load. However, DebugLoc is still incorrectly propagated in the following example:
```
1: extern int g;
2:
3: void foo(int x, int y, int z) {
4: if (x)
5: g = 0;
6: else
7: g = 1;
8:
9: int i = 0;
10: for ( ; i < y ; i++)
11: if (i > z)
12: g++;
13: }
```
Below is LLVM IR representation of the program before GVN:
```
@g = external local_unnamed_addr global i32, align 4
; Function Attrs: nounwind uwtable
define void @foo(i32 %x, i32 %y, i32 %z) local_unnamed_addr #0 !dbg !4 {
entry:
%not.tobool = icmp eq i32 %x, 0, !dbg !8
%.sink = zext i1 %not.tobool to i32, !dbg !8
store i32 %.sink, i32* @g, align 4, !tbaa !9
%cmp8 = icmp sgt i32 %y, 0, !dbg !13
br i1 %cmp8, label %for.body.preheader, label %for.end, !dbg !17
for.body.preheader: ; preds = %entry
br label %for.body, !dbg !19
for.body: ; preds = %for.body.preheader, %for.inc
%i.09 = phi i32 [ %inc4, %for.inc ], [ 0, %for.body.preheader ]
%cmp1 = icmp sgt i32 %i.09, %z, !dbg !19
br i1 %cmp1, label %if.then2, label %for.inc, !dbg !21
if.then2: ; preds = %for.body
%0 = load i32, i32* @g, align 4, !dbg !22, !tbaa !9
%inc = add nsw i32 %0, 1, !dbg !22
store i32 %inc, i32* @g, align 4, !dbg !22, !tbaa !9
br label %for.inc, !dbg !23
for.inc: ; preds = %for.body, %if.then2
%inc4 = add nuw nsw i32 %i.09, 1, !dbg !24
%exitcond = icmp ne i32 %inc4, %y, !dbg !13
br i1 %exitcond, label %for.body, label %for.end.loopexit, !dbg !17
for.end.loopexit: ; preds = %for.inc
br label %for.end, !dbg !26
for.end: ; preds = %for.end.loopexit, %entry
ret void, !dbg !26
}
```
where
```
!21 = !DILocation(line: 11, column: 9, scope: !15)
!22 = !DILocation(line: 12, column: 8, scope: !20)
!23 = !DILocation(line: 12, column: 7, scope: !20)
!24 = !DILocation(line: 10, column: 20, scope: !25)
```
And below is after GVN:
```
@g = external local_unnamed_addr global i32, align 4
define void @foo(i32 %x, i32 %y, i32 %z) local_unnamed_addr !dbg !4 {
entry:
%not.tobool = icmp eq i32 %x, 0, !dbg !8
%.sink = zext i1 %not.tobool to i32, !dbg !8
store i32 %.sink, i32* @g, align 4, !tbaa !9
%cmp8 = icmp sgt i32 %y, 0, !dbg !13
br i1 %cmp8, label %for.body.preheader, label %for.end, !dbg !17
for.body.preheader: ; preds = %entry
br label %for.body, !dbg !19
for.body: ; preds = %for.inc, %for.body.preheader
%0 = phi i32 [ %1, %for.inc ], [ %.sink, %for.body.preheader ], !dbg !21
%i.09 = phi i32 [ %inc4, %for.inc ], [ 0, %for.body.preheader ]
%cmp1 = icmp sgt i32 %i.09, %z, !dbg !19
br i1 %cmp1, label %if.then2, label %for.inc, !dbg !22
if.then2: ; preds = %for.body
%inc = add nsw i32 %0, 1, !dbg !21
store i32 %inc, i32* @g, align 4, !dbg !21, !tbaa !9
br label %for.inc, !dbg !23
for.inc: ; preds = %if.then2, %for.body
%1 = phi i32 [ %inc, %if.then2 ], [ %0, %for.body ]
%inc4 = add nuw nsw i32 %i.09, 1, !dbg !24
%exitcond = icmp ne i32 %inc4, %y, !dbg !13
br i1 %exitcond, label %for.body, label %for.end.loopexit, !dbg !17
for.end.loopexit: ; preds = %for.inc
br label %for.end, !dbg !26
for.end: ; preds = %for.end.loopexit, %entry
ret void, !dbg !26
}
```
As you see, GVN removes the load in if.then2 block and creates a phi instruction in for.body for it. The problem is that DebugLoc of remove load instruction is propagated to the newly created phi instruction, which is wrong. rL288903 cannot handle this case because ValuesPerBlock.size() is not 1 in this example when the load is removed.
Reviewers: aprantl, andreadb, wolfgangp
Reviewed By: andreadb
Subscribers: davide, llvm-commits
Differential Revision: https://reviews.llvm.org/D29254
llvm-svn: 293688
2017-02-01 04:57:13 +08:00
|
|
|
if (LI->getDebugLoc() && LI->getParent() == I->getParent())
|
2015-08-21 02:23:56 +08:00
|
|
|
I->setDebugLoc(LI->getDebugLoc());
|
2017-07-09 15:04:00 +08:00
|
|
|
if (V->getType()->isPtrOrPtrVectorTy())
|
2013-05-04 03:17:26 +08:00
|
|
|
MD->invalidateCachedPointerInfo(V);
|
|
|
|
markInstructionForDeletion(LI);
|
|
|
|
++NumGVNLoad;
|
2016-12-02 01:34:44 +08:00
|
|
|
reportLoadElim(LI, V, ORE);
|
2013-05-04 03:17:26 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Step 4: Eliminate partial redundancy.
|
|
|
|
if (!EnablePRE || !EnableLoadPRE)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
|
|
|
|
}
|
|
|
|
|
2015-09-03 03:59:53 +08:00
|
|
|
bool GVN::processAssumeIntrinsic(IntrinsicInst *IntrinsicI) {
|
|
|
|
assert(IntrinsicI->getIntrinsicID() == Intrinsic::assume &&
|
|
|
|
"This function can only be called with llvm.assume intrinsic");
|
|
|
|
Value *V = IntrinsicI->getArgOperand(0);
|
2015-09-03 04:00:03 +08:00
|
|
|
|
|
|
|
if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
|
|
|
|
if (Cond->isZero()) {
|
|
|
|
Type *Int8Ty = Type::getInt8Ty(V->getContext());
|
|
|
|
// Insert a new store to null instruction before the load to indicate that
|
|
|
|
// this code is not reachable. FIXME: We could insert unreachable
|
|
|
|
// instruction directly because we can modify the CFG.
|
|
|
|
new StoreInst(UndefValue::get(Int8Ty),
|
|
|
|
Constant::getNullValue(Int8Ty->getPointerTo()),
|
|
|
|
IntrinsicI);
|
|
|
|
}
|
|
|
|
markInstructionForDeletion(IntrinsicI);
|
|
|
|
return false;
|
2017-10-11 12:21:51 +08:00
|
|
|
} else if (isa<Constant>(V)) {
|
|
|
|
// If it's not false, and constant, it must evaluate to true. This means our
|
|
|
|
// assume is assume(true), and thus, pointless, and we don't want to do
|
|
|
|
// anything more here.
|
|
|
|
return false;
|
2015-09-03 04:00:03 +08:00
|
|
|
}
|
|
|
|
|
2015-09-03 03:59:53 +08:00
|
|
|
Constant *True = ConstantInt::getTrue(V->getContext());
|
|
|
|
bool Changed = false;
|
2015-09-03 04:00:03 +08:00
|
|
|
|
2015-09-03 03:59:53 +08:00
|
|
|
for (BasicBlock *Successor : successors(IntrinsicI->getParent())) {
|
|
|
|
BasicBlockEdge Edge(IntrinsicI->getParent(), Successor);
|
|
|
|
|
|
|
|
// This property is only true in dominated successors, propagateEquality
|
|
|
|
// will check dominance for us.
|
2015-09-03 03:59:59 +08:00
|
|
|
Changed |= propagateEquality(V, True, Edge, false);
|
2015-09-03 03:59:53 +08:00
|
|
|
}
|
2015-09-03 04:00:03 +08:00
|
|
|
|
2015-09-03 03:59:59 +08:00
|
|
|
// We can replace assume value with true, which covers cases like this:
|
|
|
|
// call void @llvm.assume(i1 %cmp)
|
|
|
|
// br i1 %cmp, label %bb1, label %bb2 ; will change %cmp to true
|
|
|
|
ReplaceWithConstMap[V] = True;
|
|
|
|
|
|
|
|
// If one of *cmp *eq operand is const, adding it to map will cover this:
|
|
|
|
// %cmp = fcmp oeq float 3.000000e+00, %0 ; const on lhs could happen
|
|
|
|
// call void @llvm.assume(i1 %cmp)
|
|
|
|
// ret float %0 ; will change it to ret float 3.000000e+00
|
2015-09-03 03:59:53 +08:00
|
|
|
if (auto *CmpI = dyn_cast<CmpInst>(V)) {
|
|
|
|
if (CmpI->getPredicate() == CmpInst::Predicate::ICMP_EQ ||
|
|
|
|
CmpI->getPredicate() == CmpInst::Predicate::FCMP_OEQ ||
|
|
|
|
(CmpI->getPredicate() == CmpInst::Predicate::FCMP_UEQ &&
|
|
|
|
CmpI->getFastMathFlags().noNaNs())) {
|
|
|
|
Value *CmpLHS = CmpI->getOperand(0);
|
|
|
|
Value *CmpRHS = CmpI->getOperand(1);
|
|
|
|
if (isa<Constant>(CmpLHS))
|
|
|
|
std::swap(CmpLHS, CmpRHS);
|
|
|
|
auto *RHSConst = dyn_cast<Constant>(CmpRHS);
|
|
|
|
|
|
|
|
// If only one operand is constant.
|
|
|
|
if (RHSConst != nullptr && !isa<Constant>(CmpLHS))
|
|
|
|
ReplaceWithConstMap[CmpLHS] = RHSConst;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return Changed;
|
|
|
|
}
|
2013-05-04 03:17:26 +08:00
|
|
|
|
2013-03-13 00:22:56 +08:00
|
|
|
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
|
|
|
|
patchReplacementInstruction(I, Repl);
|
2012-06-05 06:44:21 +08:00
|
|
|
I->replaceAllUsesWith(Repl);
|
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Attempt to eliminate a load, first by eliminating it
|
2007-08-17 06:02:55 +08:00
|
|
|
/// locally, and then attempting non-local elimination if that fails.
|
2011-04-29 00:18:52 +08:00
|
|
|
bool GVN::processLoad(LoadInst *L) {
|
2009-11-14 10:27:51 +08:00
|
|
|
if (!MD)
|
|
|
|
return false;
|
|
|
|
|
2016-05-07 02:17:13 +08:00
|
|
|
// This code hasn't been audited for ordered or volatile memory access
|
|
|
|
if (!L->isUnordered())
|
2007-07-25 01:55:58 +08:00
|
|
|
return false;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2011-05-22 15:03:34 +08:00
|
|
|
if (L->use_empty()) {
|
|
|
|
markInstructionForDeletion(L);
|
|
|
|
return true;
|
|
|
|
}
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2007-07-25 01:55:58 +08:00
|
|
|
// ... to a pointer that has been loaded from before...
|
2009-09-21 10:42:51 +08:00
|
|
|
MemDepResult Dep = MD->getDependency(L);
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2016-01-26 07:37:53 +08:00
|
|
|
// If it is defined in another block, try harder.
|
|
|
|
if (Dep.isNonLocal())
|
|
|
|
return processNonLocalLoad(L);
|
|
|
|
|
|
|
|
// Only handle the local case below
|
|
|
|
if (!Dep.isDef() && !Dep.isClobber()) {
|
|
|
|
// This might be a NonFuncLocal or an Unknown
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(
|
|
|
|
// fast print dep, using operator<< on instruction is too slow.
|
|
|
|
dbgs() << "GVN: load "; L->printAsOperand(dbgs());
|
|
|
|
dbgs() << " has unknown dependence\n";);
|
2016-01-26 07:37:53 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
AvailableValue AV;
|
|
|
|
if (AnalyzeLoadAvailability(L, Dep, L->getPointerOperand(), AV)) {
|
|
|
|
Value *AvailableValue = AV.MaterializeAdjustedValue(L, L, *this);
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2016-02-13 03:24:57 +08:00
|
|
|
// Replace the load!
|
2016-01-26 07:19:12 +08:00
|
|
|
patchAndReplaceAllUsesWith(L, AvailableValue);
|
2014-06-13 05:16:19 +08:00
|
|
|
markInstructionForDeletion(L);
|
|
|
|
++NumGVNLoad;
|
2016-12-02 01:34:44 +08:00
|
|
|
reportLoadElim(L, AvailableValue, ORE);
|
2016-01-26 07:19:12 +08:00
|
|
|
// Tell MDA to rexamine the reused pointer since we might have more
|
|
|
|
// information after forwarding it.
|
2017-07-09 15:04:00 +08:00
|
|
|
if (MD && AvailableValue->getType()->isPtrOrPtrVectorTy())
|
2016-01-26 07:19:12 +08:00
|
|
|
MD->invalidateCachedPointerInfo(AvailableValue);
|
2014-06-13 05:16:19 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2008-12-06 05:04:20 +08:00
|
|
|
return false;
|
2007-07-25 01:55:58 +08:00
|
|
|
}
|
|
|
|
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
/// Return a pair the first field showing the value number of \p Exp and the
|
|
|
|
/// second field showing whether it is a value number newly created.
|
|
|
|
std::pair<uint32_t, bool>
|
|
|
|
GVN::ValueTable::assignExpNewValueNum(Expression &Exp) {
|
|
|
|
uint32_t &e = expressionNumbering[Exp];
|
|
|
|
bool CreateNewValNum = !e;
|
|
|
|
if (CreateNewValNum) {
|
|
|
|
Expressions.push_back(Exp);
|
|
|
|
if (ExprIdx.size() < nextValueNumber + 1)
|
|
|
|
ExprIdx.resize(nextValueNumber * 2);
|
|
|
|
e = nextValueNumber;
|
|
|
|
ExprIdx[nextValueNumber++] = nextExprNumber++;
|
|
|
|
}
|
|
|
|
return {e, CreateNewValNum};
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Return whether all the values related with the same \p num are
|
|
|
|
/// defined in \p BB.
|
|
|
|
bool GVN::ValueTable::areAllValsInBB(uint32_t Num, const BasicBlock *BB,
|
|
|
|
GVN &Gvn) {
|
|
|
|
LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
|
|
|
|
while (Vals && Vals->BB == BB)
|
|
|
|
Vals = Vals->Next;
|
|
|
|
return !Vals;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Wrap phiTranslateImpl to provide caching functionality.
|
|
|
|
uint32_t GVN::ValueTable::phiTranslate(const BasicBlock *Pred,
|
|
|
|
const BasicBlock *PhiBlock, uint32_t Num,
|
|
|
|
GVN &Gvn) {
|
|
|
|
auto FindRes = PhiTranslateTable.find({Num, Pred});
|
|
|
|
if (FindRes != PhiTranslateTable.end())
|
|
|
|
return FindRes->second;
|
|
|
|
uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, Gvn);
|
|
|
|
PhiTranslateTable.insert({{Num, Pred}, NewNum});
|
|
|
|
return NewNum;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Translate value number \p Num using phis, so that it has the values of
|
|
|
|
/// the phis in BB.
|
|
|
|
uint32_t GVN::ValueTable::phiTranslateImpl(const BasicBlock *Pred,
|
|
|
|
const BasicBlock *PhiBlock,
|
|
|
|
uint32_t Num, GVN &Gvn) {
|
|
|
|
if (PHINode *PN = NumberingPhi[Num]) {
|
|
|
|
for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
|
|
|
|
if (PN->getParent() == PhiBlock && PN->getIncomingBlock(i) == Pred)
|
|
|
|
if (uint32_t TransVal = lookup(PN->getIncomingValue(i), false))
|
|
|
|
return TransVal;
|
|
|
|
}
|
|
|
|
return Num;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If there is any value related with Num is defined in a BB other than
|
|
|
|
// PhiBlock, it cannot depend on a phi in PhiBlock without going through
|
|
|
|
// a backedge. We can do an early exit in that case to save compile time.
|
|
|
|
if (!areAllValsInBB(Num, PhiBlock, Gvn))
|
|
|
|
return Num;
|
|
|
|
|
|
|
|
if (Num >= ExprIdx.size() || ExprIdx[Num] == 0)
|
|
|
|
return Num;
|
|
|
|
Expression Exp = Expressions[ExprIdx[Num]];
|
|
|
|
|
|
|
|
for (unsigned i = 0; i < Exp.varargs.size(); i++) {
|
|
|
|
// For InsertValue and ExtractValue, some varargs are index numbers
|
|
|
|
// instead of value numbers. Those index numbers should not be
|
|
|
|
// translated.
|
|
|
|
if ((i > 1 && Exp.opcode == Instruction::InsertValue) ||
|
|
|
|
(i > 0 && Exp.opcode == Instruction::ExtractValue))
|
|
|
|
continue;
|
|
|
|
Exp.varargs[i] = phiTranslate(Pred, PhiBlock, Exp.varargs[i], Gvn);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Exp.commutative) {
|
|
|
|
assert(Exp.varargs.size() == 2 && "Unsupported commutative expression!");
|
|
|
|
if (Exp.varargs[0] > Exp.varargs[1]) {
|
|
|
|
std::swap(Exp.varargs[0], Exp.varargs[1]);
|
|
|
|
uint32_t Opcode = Exp.opcode >> 8;
|
|
|
|
if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)
|
|
|
|
Exp.opcode = (Opcode << 8) |
|
|
|
|
CmpInst::getSwappedPredicate(
|
|
|
|
static_cast<CmpInst::Predicate>(Exp.opcode & 255));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (uint32_t NewNum = expressionNumbering[Exp])
|
|
|
|
return NewNum;
|
|
|
|
return Num;
|
|
|
|
}
|
|
|
|
|
2017-08-09 05:40:14 +08:00
|
|
|
/// Erase stale entry from phiTranslate cache so phiTranslate can be computed
|
|
|
|
/// again.
|
|
|
|
void GVN::ValueTable::eraseTranslateCacheEntry(uint32_t Num,
|
|
|
|
const BasicBlock &CurrBlock) {
|
|
|
|
for (const BasicBlock *Pred : predecessors(&CurrBlock)) {
|
|
|
|
auto FindRes = PhiTranslateTable.find({Num, Pred});
|
|
|
|
if (FindRes != PhiTranslateTable.end())
|
|
|
|
PhiTranslateTable.erase(FindRes);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
// In order to find a leader for a given value number at a
|
2010-11-20 06:48:40 +08:00
|
|
|
// specific basic block, we first obtain the list of all Values for that number,
|
2012-07-24 18:51:42 +08:00
|
|
|
// and then scan the list to find one whose block dominates the block in
|
2010-11-20 06:48:40 +08:00
|
|
|
// question. This is fast because dominator tree queries consist of only
|
|
|
|
// a few comparisons of DFS numbers.
|
2012-08-10 23:55:25 +08:00
|
|
|
Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
|
2011-01-05 03:29:46 +08:00
|
|
|
LeaderTableEntry Vals = LeaderTable[num];
|
2014-04-25 13:29:35 +08:00
|
|
|
if (!Vals.Val) return nullptr;
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2014-04-25 13:29:35 +08:00
|
|
|
Value *Val = nullptr;
|
2010-12-22 07:54:34 +08:00
|
|
|
if (DT->dominates(Vals.BB, BB)) {
|
|
|
|
Val = Vals.Val;
|
|
|
|
if (isa<Constant>(Val)) return Val;
|
|
|
|
}
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2011-01-05 03:13:25 +08:00
|
|
|
LeaderTableEntry* Next = Vals.Next;
|
2010-11-19 02:32:40 +08:00
|
|
|
while (Next) {
|
2010-12-22 07:54:34 +08:00
|
|
|
if (DT->dominates(Next->BB, BB)) {
|
|
|
|
if (isa<Constant>(Next->Val)) return Next->Val;
|
|
|
|
if (!Val) Val = Next->Val;
|
|
|
|
}
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2010-12-22 07:54:34 +08:00
|
|
|
Next = Next->Next;
|
2008-06-20 09:15:47 +08:00
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2010-12-22 07:54:34 +08:00
|
|
|
return Val;
|
2008-06-20 09:15:47 +08:00
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// There is an edge from 'Src' to 'Dst'. Return
|
2012-08-16 23:09:43 +08:00
|
|
|
/// true if every path from the entry block to 'Dst' passes via this edge. In
|
|
|
|
/// particular 'Dst' must not be reachable via another edge from 'Src'.
|
|
|
|
static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
|
|
|
|
DominatorTree *DT) {
|
|
|
|
// While in theory it is interesting to consider the case in which Dst has
|
|
|
|
// more than one predecessor, because Dst might be part of a loop which is
|
|
|
|
// only reachable from Src, in practice it is pointless since at the time
|
|
|
|
// GVN runs all such loops have preheaders, which means that Dst will have
|
|
|
|
// been changed to have only one predecessor, namely Src.
|
|
|
|
const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
|
2016-04-29 00:00:15 +08:00
|
|
|
assert((!Pred || Pred == E.getStart()) &&
|
|
|
|
"No edge between these basic blocks!");
|
2014-04-25 13:29:35 +08:00
|
|
|
return Pred != nullptr;
|
2012-08-16 23:09:43 +08:00
|
|
|
}
|
|
|
|
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
void GVN::assignBlockRPONumber(Function &F) {
|
[GVN] Update BlockRPONumber prior to use.
Summary:
The original patch addressed the use of BlockRPONumber by forcing a sequence point when accessing that map in a conditional. In short we found cases where that map was being accessed with blocks that had not yet been added to that structure. For context, I've kept the wall of text below, to what we are trying to fix, by always ensuring a updated BlockRPONumber.
== Backstory ==
I was investigating an ICE (segfault accessing a DenseMap item). This failure happened non-deterministically, with no apparent reason and only on a Windows build of LLVM (from October 2018).
After looking into the crashes (multiple core files) and running DynamoRio, the cores and DynamoRio (DR) log pointed to the same code in `GVN::performScalarPRE()`. The values in the map are unsigned integers, the keys are `llvm::BasicBlock*`. Our test case that triggered this warning and periodic crash is rather involved. But the problematic line looks to be:
GVN.cpp: Line 2197
```
if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
```
To test things out, I cooked up a patch that accessed the items in the map outside of the condition, by forcing a sequence point between accesses. DynamoRio stopped warning of the issue, and the test didn't seem to crash after 1000+ runs.
My investigation was on an older version of LLVM, (source from October this year). What it looks like was occurring is the following, and the assembly from the latest pull of llvm in December seems to confirm this might still be an issue; however, I have not witnessed the crash on more recent builds. Of course the asm in question is generated from the host compiler on that Windows box (not clang), but it hints that we might want to consider how we access the BlockRPONumber map in this conditional (line 2197, listed above). In any case, I don't think the host compiler is wrong, rather I think it is pointing out a possibly latent bug in llvm.
1) There is no sequence point for the `>=` operation.
2) A call to a `DenseMapBase::operator[]` can have the side effect of the map reallocating a larger store (more Buckets, via a call to `DenseMap::grow`).
3) It seems perfectly legal for a host compiler to generate assembly that stores the result of a call to `operator[]` on the stack (that's what my host compile of GVN.cpp is doing) . A second call to `operator[]` //might// encourage the map to 'grow' thus making any pointers to the map's store invalid. The `>=` compares the first and second values. If the first happens to be a pointer produced from operator[], it could be invalid when dereferenced at the time of comparison.
The assembly generated from the Window's host compiler does show the result of the first access to the map via `operator[]` produces a pointer to an unsigned int. And that pointer is being stored on the stack. If a second call to the map (which does occur) causes the map to grow, that address (on the stack) is now invalid.
Reviewers: t.p.northover, efriedma
Reviewed By: efriedma
Subscribers: efriedma, llvm-commits
Differential Revision: https://reviews.llvm.org/D55974
llvm-svn: 350880
2019-01-11 03:56:03 +08:00
|
|
|
BlockRPONumber.clear();
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
uint32_t NextBlockNumber = 1;
|
|
|
|
ReversePostOrderTraversal<Function *> RPOT(&F);
|
|
|
|
for (BasicBlock *BB : RPOT)
|
|
|
|
BlockRPONumber[BB] = NextBlockNumber++;
|
[GVN] Update BlockRPONumber prior to use.
Summary:
The original patch addressed the use of BlockRPONumber by forcing a sequence point when accessing that map in a conditional. In short we found cases where that map was being accessed with blocks that had not yet been added to that structure. For context, I've kept the wall of text below, to what we are trying to fix, by always ensuring a updated BlockRPONumber.
== Backstory ==
I was investigating an ICE (segfault accessing a DenseMap item). This failure happened non-deterministically, with no apparent reason and only on a Windows build of LLVM (from October 2018).
After looking into the crashes (multiple core files) and running DynamoRio, the cores and DynamoRio (DR) log pointed to the same code in `GVN::performScalarPRE()`. The values in the map are unsigned integers, the keys are `llvm::BasicBlock*`. Our test case that triggered this warning and periodic crash is rather involved. But the problematic line looks to be:
GVN.cpp: Line 2197
```
if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
```
To test things out, I cooked up a patch that accessed the items in the map outside of the condition, by forcing a sequence point between accesses. DynamoRio stopped warning of the issue, and the test didn't seem to crash after 1000+ runs.
My investigation was on an older version of LLVM, (source from October this year). What it looks like was occurring is the following, and the assembly from the latest pull of llvm in December seems to confirm this might still be an issue; however, I have not witnessed the crash on more recent builds. Of course the asm in question is generated from the host compiler on that Windows box (not clang), but it hints that we might want to consider how we access the BlockRPONumber map in this conditional (line 2197, listed above). In any case, I don't think the host compiler is wrong, rather I think it is pointing out a possibly latent bug in llvm.
1) There is no sequence point for the `>=` operation.
2) A call to a `DenseMapBase::operator[]` can have the side effect of the map reallocating a larger store (more Buckets, via a call to `DenseMap::grow`).
3) It seems perfectly legal for a host compiler to generate assembly that stores the result of a call to `operator[]` on the stack (that's what my host compile of GVN.cpp is doing) . A second call to `operator[]` //might// encourage the map to 'grow' thus making any pointers to the map's store invalid. The `>=` compares the first and second values. If the first happens to be a pointer produced from operator[], it could be invalid when dereferenced at the time of comparison.
The assembly generated from the Window's host compiler does show the result of the first access to the map via `operator[]` produces a pointer to an unsigned int. And that pointer is being stored on the stack. If a second call to the map (which does occur) causes the map to grow, that address (on the stack) is now invalid.
Reviewers: t.p.northover, efriedma
Reviewed By: efriedma
Subscribers: efriedma, llvm-commits
Differential Revision: https://reviews.llvm.org/D55974
llvm-svn: 350880
2019-01-11 03:56:03 +08:00
|
|
|
InvalidBlockRPONumbers = false;
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
}
|
|
|
|
|
2015-09-03 03:59:53 +08:00
|
|
|
// Tries to replace instruction with const, using information from
|
|
|
|
// ReplaceWithConstMap.
|
|
|
|
bool GVN::replaceOperandsWithConsts(Instruction *Instr) const {
|
|
|
|
bool Changed = false;
|
|
|
|
for (unsigned OpNum = 0; OpNum < Instr->getNumOperands(); ++OpNum) {
|
|
|
|
Value *Operand = Instr->getOperand(OpNum);
|
|
|
|
auto it = ReplaceWithConstMap.find(Operand);
|
|
|
|
if (it != ReplaceWithConstMap.end()) {
|
2015-09-03 04:00:03 +08:00
|
|
|
assert(!isa<Constant>(Operand) &&
|
|
|
|
"Replacing constants with constants is invalid");
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN replacing: " << *Operand << " with "
|
|
|
|
<< *it->second << " in instruction " << *Instr << '\n');
|
2015-09-03 03:59:53 +08:00
|
|
|
Instr->setOperand(OpNum, it->second);
|
|
|
|
Changed = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return Changed;
|
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// The given values are known to be equal in every block
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
/// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
|
|
|
|
/// 'RHS' everywhere in the scope. Returns whether a change was made.
|
2016-01-22 05:32:35 +08:00
|
|
|
/// If DominatesByEdge is false, then it means that we will propagate the RHS
|
|
|
|
/// value starting from the end of Root.Start.
|
2015-09-03 03:59:59 +08:00
|
|
|
bool GVN::propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root,
|
|
|
|
bool DominatesByEdge) {
|
2012-04-06 23:31:09 +08:00
|
|
|
SmallVector<std::pair<Value*, Value*>, 4> Worklist;
|
|
|
|
Worklist.push_back(std::make_pair(LHS, RHS));
|
|
|
|
bool Changed = false;
|
2012-08-16 23:09:43 +08:00
|
|
|
// For speed, compute a conservative fast approximation to
|
|
|
|
// DT->dominates(Root, Root.getEnd());
|
2016-04-29 00:00:15 +08:00
|
|
|
const bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
|
2012-04-06 23:31:09 +08:00
|
|
|
while (!Worklist.empty()) {
|
|
|
|
std::pair<Value*, Value*> Item = Worklist.pop_back_val();
|
|
|
|
LHS = Item.first; RHS = Item.second;
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
|
2015-09-03 03:59:53 +08:00
|
|
|
if (LHS == RHS)
|
|
|
|
continue;
|
2012-04-06 23:31:09 +08:00
|
|
|
assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
|
2012-04-06 23:31:09 +08:00
|
|
|
// Don't try to propagate equalities between constants.
|
2015-09-03 03:59:53 +08:00
|
|
|
if (isa<Constant>(LHS) && isa<Constant>(RHS))
|
|
|
|
continue;
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
|
2012-04-06 23:31:09 +08:00
|
|
|
// Prefer a constant on the right-hand side, or an Argument if no constants.
|
|
|
|
if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
|
|
|
|
std::swap(LHS, RHS);
|
|
|
|
assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
|
|
|
|
|
2015-01-13 05:21:28 +08:00
|
|
|
// If there is no obvious reason to prefer the left-hand side over the
|
|
|
|
// right-hand side, ensure the longest lived term is on the right-hand side,
|
|
|
|
// so the shortest lived term will be replaced by the longest lived.
|
|
|
|
// This tends to expose more simplifications.
|
2016-04-29 00:00:15 +08:00
|
|
|
uint32_t LVN = VN.lookupOrAdd(LHS);
|
2012-04-06 23:31:09 +08:00
|
|
|
if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
|
|
|
|
(isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
|
2015-01-13 05:21:28 +08:00
|
|
|
// Move the 'oldest' value to the right-hand side, using the value number
|
|
|
|
// as a proxy for age.
|
2016-04-29 00:00:15 +08:00
|
|
|
uint32_t RVN = VN.lookupOrAdd(RHS);
|
2012-04-06 23:31:09 +08:00
|
|
|
if (LVN < RVN) {
|
|
|
|
std::swap(LHS, RHS);
|
|
|
|
LVN = RVN;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-05-22 22:17:53 +08:00
|
|
|
// If value numbering later sees that an instruction in the scope is equal
|
|
|
|
// to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve
|
|
|
|
// the invariant that instructions only occur in the leader table for their
|
|
|
|
// own value number (this is used by removeFromLeaderTable), do not do this
|
|
|
|
// if RHS is an instruction (if an instruction in the scope is morphed into
|
|
|
|
// LHS then it will be turned into RHS by the next GVN iteration anyway, so
|
|
|
|
// using the leader table is about compiling faster, not optimizing better).
|
2012-08-16 23:09:43 +08:00
|
|
|
// The leader table only tracks basic blocks, not edges. Only add to if we
|
|
|
|
// have the simple case where the edge dominates the end.
|
|
|
|
if (RootDominatesEnd && !isa<Instruction>(RHS))
|
|
|
|
addToLeaderTable(LVN, RHS, Root.getEnd());
|
2012-04-06 23:31:09 +08:00
|
|
|
|
|
|
|
// Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
|
|
|
|
// LHS always has at least one use that is not dominated by Root, this will
|
|
|
|
// never do anything if LHS has only one use.
|
|
|
|
if (!LHS->hasOneUse()) {
|
2015-09-03 03:59:59 +08:00
|
|
|
unsigned NumReplacements =
|
|
|
|
DominatesByEdge
|
|
|
|
? replaceDominatedUsesWith(LHS, RHS, *DT, Root)
|
2016-09-08 23:25:12 +08:00
|
|
|
: replaceDominatedUsesWith(LHS, RHS, *DT, Root.getStart());
|
2015-09-03 03:59:59 +08:00
|
|
|
|
2012-04-06 23:31:09 +08:00
|
|
|
Changed |= NumReplacements > 0;
|
|
|
|
NumGVNEqProp += NumReplacements;
|
2018-09-10 20:23:05 +08:00
|
|
|
// Cached information for anything that uses LHS will be invalid.
|
|
|
|
if (MD)
|
|
|
|
MD->invalidateCachedPointerInfo(LHS);
|
2012-04-06 23:31:09 +08:00
|
|
|
}
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
|
2015-01-13 05:21:28 +08:00
|
|
|
// Now try to deduce additional equalities from this one. For example, if
|
|
|
|
// the known equality was "(A != B)" == "false" then it follows that A and B
|
|
|
|
// are equal in the scope. Only boolean equalities with an explicit true or
|
|
|
|
// false RHS are currently supported.
|
2012-04-06 23:31:09 +08:00
|
|
|
if (!RHS->getType()->isIntegerTy(1))
|
|
|
|
// Not a boolean equality - bail out.
|
|
|
|
continue;
|
|
|
|
ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
|
|
|
|
if (!CI)
|
|
|
|
// RHS neither 'true' nor 'false' - bail out.
|
|
|
|
continue;
|
|
|
|
// Whether RHS equals 'true'. Otherwise it equals 'false'.
|
2017-07-07 02:39:47 +08:00
|
|
|
bool isKnownTrue = CI->isMinusOne();
|
2012-04-06 23:31:09 +08:00
|
|
|
bool isKnownFalse = !isKnownTrue;
|
|
|
|
|
|
|
|
// If "A && B" is known true then both A and B are known true. If "A || B"
|
|
|
|
// is known false then both A and B are known false.
|
|
|
|
Value *A, *B;
|
|
|
|
if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
|
|
|
|
(isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
|
|
|
|
Worklist.push_back(std::make_pair(A, RHS));
|
|
|
|
Worklist.push_back(std::make_pair(B, RHS));
|
|
|
|
continue;
|
|
|
|
}
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
|
2012-04-06 23:31:09 +08:00
|
|
|
// If we are propagating an equality like "(A == B)" == "true" then also
|
|
|
|
// propagate the equality A == B. When propagating a comparison such as
|
|
|
|
// "(A >= B)" == "true", replace all instances of "A < B" with "false".
|
2015-01-13 03:29:48 +08:00
|
|
|
if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
|
2012-04-06 23:31:09 +08:00
|
|
|
Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
|
|
|
|
|
|
|
|
// If "A == B" is known true, or "A != B" is known false, then replace
|
|
|
|
// A with B everywhere in the scope.
|
|
|
|
if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
|
|
|
|
(isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
|
|
|
|
Worklist.push_back(std::make_pair(Op0, Op1));
|
|
|
|
|
2015-01-13 03:29:48 +08:00
|
|
|
// Handle the floating point versions of equality comparisons too.
|
|
|
|
if ((isKnownTrue && Cmp->getPredicate() == CmpInst::FCMP_OEQ) ||
|
2015-01-30 04:51:49 +08:00
|
|
|
(isKnownFalse && Cmp->getPredicate() == CmpInst::FCMP_UNE)) {
|
2015-02-26 06:46:08 +08:00
|
|
|
|
|
|
|
// Floating point -0.0 and 0.0 compare equal, so we can only
|
|
|
|
// propagate values if we know that we have a constant and that
|
|
|
|
// its value is non-zero.
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2015-01-30 04:51:49 +08:00
|
|
|
// FIXME: We should do this optimization if 'no signed zeros' is
|
|
|
|
// applicable via an instruction-level fast-math-flag or some other
|
|
|
|
// indicator that relaxed FP semantics are being used.
|
2015-02-26 06:46:08 +08:00
|
|
|
|
|
|
|
if (isa<ConstantFP>(Op1) && !cast<ConstantFP>(Op1)->isZero())
|
2015-01-30 04:51:49 +08:00
|
|
|
Worklist.push_back(std::make_pair(Op0, Op1));
|
|
|
|
}
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2012-04-06 23:31:09 +08:00
|
|
|
// If "A >= B" is known true, replace "A < B" with false everywhere.
|
|
|
|
CmpInst::Predicate NotPred = Cmp->getInversePredicate();
|
|
|
|
Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
|
2015-01-13 05:21:28 +08:00
|
|
|
// Since we don't have the instruction "A < B" immediately to hand, work
|
|
|
|
// out the value number that it would have and use that to find an
|
|
|
|
// appropriate instruction (if any).
|
2012-04-06 23:31:09 +08:00
|
|
|
uint32_t NextNum = VN.getNextUnusedValueNumber();
|
2016-04-29 00:00:15 +08:00
|
|
|
uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1);
|
2012-04-06 23:31:09 +08:00
|
|
|
// If the number we were assigned was brand new then there is no point in
|
|
|
|
// looking for an instruction realizing it: there cannot be one!
|
|
|
|
if (Num < NextNum) {
|
2012-08-16 23:09:43 +08:00
|
|
|
Value *NotCmp = findLeader(Root.getEnd(), Num);
|
2012-04-06 23:31:09 +08:00
|
|
|
if (NotCmp && isa<Instruction>(NotCmp)) {
|
|
|
|
unsigned NumReplacements =
|
2015-09-03 03:59:59 +08:00
|
|
|
DominatesByEdge
|
|
|
|
? replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root)
|
|
|
|
: replaceDominatedUsesWith(NotCmp, NotVal, *DT,
|
2016-09-08 23:25:12 +08:00
|
|
|
Root.getStart());
|
2012-04-06 23:31:09 +08:00
|
|
|
Changed |= NumReplacements > 0;
|
|
|
|
NumGVNEqProp += NumReplacements;
|
2018-09-10 20:23:05 +08:00
|
|
|
// Cached information for anything that uses NotCmp will be invalid.
|
|
|
|
if (MD)
|
|
|
|
MD->invalidateCachedPointerInfo(NotCmp);
|
2012-04-06 23:31:09 +08:00
|
|
|
}
|
2012-02-27 20:11:41 +08:00
|
|
|
}
|
2012-04-06 23:31:09 +08:00
|
|
|
// Ensure that any instruction in scope that gets the "A < B" value number
|
|
|
|
// is replaced with false.
|
2012-08-16 23:09:43 +08:00
|
|
|
// The leader table only tracks basic blocks, not edges. Only add to if we
|
|
|
|
// have the simple case where the edge dominates the end.
|
|
|
|
if (RootDominatesEnd)
|
|
|
|
addToLeaderTable(Num, NotVal, Root.getEnd());
|
2012-02-27 16:14:30 +08:00
|
|
|
|
2012-04-06 23:31:09 +08:00
|
|
|
continue;
|
|
|
|
}
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return Changed;
|
|
|
|
}
|
2008-12-15 10:03:00 +08:00
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// When calculating availability, handle an instruction
|
2007-07-25 01:55:58 +08:00
|
|
|
/// by inserting it into the appropriate sets
|
2011-04-29 00:18:52 +08:00
|
|
|
bool GVN::processInstruction(Instruction *I) {
|
2010-02-11 08:20:49 +08:00
|
|
|
// Ignore dbg info intrinsics.
|
|
|
|
if (isa<DbgInfoIntrinsic>(I))
|
|
|
|
return false;
|
|
|
|
|
2010-11-13 05:10:24 +08:00
|
|
|
// If the instruction can be easily simplified then do so now in preference
|
|
|
|
// to value numbering it. Value numbering often exposes redundancies, for
|
|
|
|
// example if it determines that %y is equal to %x then the instruction
|
|
|
|
// "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
|
2015-03-10 10:37:25 +08:00
|
|
|
const DataLayout &DL = I->getModule()->getDataLayout();
|
2017-04-29 03:55:38 +08:00
|
|
|
if (Value *V = SimplifyInstruction(I, {DL, TLI, DT, AC})) {
|
2016-06-25 08:04:10 +08:00
|
|
|
bool Changed = false;
|
|
|
|
if (!I->use_empty()) {
|
|
|
|
I->replaceAllUsesWith(V);
|
|
|
|
Changed = true;
|
|
|
|
}
|
|
|
|
if (isInstructionTriviallyDead(I, TLI)) {
|
|
|
|
markInstructionForDeletion(I);
|
|
|
|
Changed = true;
|
|
|
|
}
|
|
|
|
if (Changed) {
|
2017-07-09 15:04:00 +08:00
|
|
|
if (MD && V->getType()->isPtrOrPtrVectorTy())
|
2016-06-25 08:04:10 +08:00
|
|
|
MD->invalidateCachedPointerInfo(V);
|
|
|
|
++NumGVNSimpl;
|
|
|
|
return true;
|
|
|
|
}
|
2010-11-13 05:10:24 +08:00
|
|
|
}
|
|
|
|
|
2015-09-03 03:59:53 +08:00
|
|
|
if (IntrinsicInst *IntrinsicI = dyn_cast<IntrinsicInst>(I))
|
|
|
|
if (IntrinsicI->getIntrinsicID() == Intrinsic::assume)
|
|
|
|
return processAssumeIntrinsic(IntrinsicI);
|
|
|
|
|
2009-09-21 10:42:51 +08:00
|
|
|
if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
|
2011-04-29 00:18:52 +08:00
|
|
|
if (processLoad(LI))
|
|
|
|
return true;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2016-04-29 00:00:15 +08:00
|
|
|
unsigned Num = VN.lookupOrAdd(LI);
|
2011-04-29 00:18:52 +08:00
|
|
|
addToLeaderTable(Num, LI, LI->getParent());
|
|
|
|
return false;
|
2008-06-19 05:41:49 +08:00
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
// For conditional branches, we can perform simple conditional propagation on
|
2010-12-22 07:54:34 +08:00
|
|
|
// the condition value itself.
|
|
|
|
if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
|
2013-11-12 06:00:23 +08:00
|
|
|
if (!BI->isConditional())
|
2010-12-22 07:54:34 +08:00
|
|
|
return false;
|
GVN does simple propagation of conditions: when it sees a conditional
branch "br i1 %x, label %if_true, label %if_false" then it replaces
"%x" with "true" in places only reachable via the %if_true arm, and
with "false" in places only reachable via the %if_false arm. Except
that actually it doesn't: if value numbering shows that %y is equal
to %x then, yes, %y will be turned into true/false in this way, but
any occurrences of %x itself are not transformed. Fix this. What's
more, it's often the case that %x is an equality comparison such as
"%x = icmp eq %A, 0", in which case every occurrence of %A that is
only reachable via the %if_true arm can be replaced with 0. Implement
this and a few other variations on this theme. This reduces the number
of lines of LLVM IR in "GCC as one big file" by 0.2%. It has a bigger
impact on Ada code, typically reducing the number of lines of bitcode
by around 0.4% by removing repeated compiler generated checks. Passes
the LLVM nightly testsuite and the Ada ACATS testsuite.
llvm-svn: 141177
2011-10-05 22:28:49 +08:00
|
|
|
|
2013-11-12 06:00:23 +08:00
|
|
|
if (isa<Constant>(BI->getCondition()))
|
|
|
|
return processFoldableCondBr(BI);
|
2013-11-10 15:34:34 +08:00
|
|
|
|
2013-11-12 06:00:23 +08:00
|
|
|
Value *BranchCond = BI->getCondition();
|
2010-12-22 07:54:34 +08:00
|
|
|
BasicBlock *TrueSucc = BI->getSuccessor(0);
|
|
|
|
BasicBlock *FalseSucc = BI->getSuccessor(1);
|
2012-08-16 23:09:43 +08:00
|
|
|
// Avoid multiple edges early.
|
|
|
|
if (TrueSucc == FalseSucc)
|
|
|
|
return false;
|
|
|
|
|
2011-10-05 22:17:01 +08:00
|
|
|
BasicBlock *Parent = BI->getParent();
|
2011-10-07 16:29:06 +08:00
|
|
|
bool Changed = false;
|
2011-10-05 22:17:01 +08:00
|
|
|
|
2012-08-16 23:09:43 +08:00
|
|
|
Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
|
|
|
|
BasicBlockEdge TrueE(Parent, TrueSucc);
|
2015-09-03 03:59:59 +08:00
|
|
|
Changed |= propagateEquality(BranchCond, TrueVal, TrueE, true);
|
2011-10-05 22:17:01 +08:00
|
|
|
|
2012-08-16 23:09:43 +08:00
|
|
|
Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
|
|
|
|
BasicBlockEdge FalseE(Parent, FalseSucc);
|
2015-09-03 03:59:59 +08:00
|
|
|
Changed |= propagateEquality(BranchCond, FalseVal, FalseE, true);
|
2011-10-05 22:17:01 +08:00
|
|
|
|
2011-10-07 16:29:06 +08:00
|
|
|
return Changed;
|
|
|
|
}
|
2011-10-05 22:17:01 +08:00
|
|
|
|
2011-10-07 16:29:06 +08:00
|
|
|
// For switches, propagate the case values into the case destinations.
|
|
|
|
if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
|
|
|
|
Value *SwitchCond = SI->getCondition();
|
|
|
|
BasicBlock *Parent = SI->getParent();
|
|
|
|
bool Changed = false;
|
2012-08-24 23:06:28 +08:00
|
|
|
|
|
|
|
// Remember how many outgoing edges there are to every successor.
|
|
|
|
SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
|
|
|
|
for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
|
|
|
|
++SwitchEdges[SI->getSuccessor(i)];
|
|
|
|
|
2012-03-11 14:09:17 +08:00
|
|
|
for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
|
2012-03-08 15:06:20 +08:00
|
|
|
i != e; ++i) {
|
2017-04-12 15:27:28 +08:00
|
|
|
BasicBlock *Dst = i->getCaseSuccessor();
|
2012-08-24 23:06:28 +08:00
|
|
|
// If there is only a single edge, propagate the case value into it.
|
|
|
|
if (SwitchEdges.lookup(Dst) == 1) {
|
|
|
|
BasicBlockEdge E(Parent, Dst);
|
2017-04-12 15:27:28 +08:00
|
|
|
Changed |= propagateEquality(SwitchCond, i->getCaseValue(), E, true);
|
2012-08-24 23:06:28 +08:00
|
|
|
}
|
2011-10-07 16:29:06 +08:00
|
|
|
}
|
|
|
|
return Changed;
|
2010-12-22 07:54:34 +08:00
|
|
|
}
|
2011-10-07 16:29:06 +08:00
|
|
|
|
2011-01-05 06:15:21 +08:00
|
|
|
// Instructions with void type don't return a value, so there's
|
2012-02-27 17:54:35 +08:00
|
|
|
// no point in trying to find redundancies in them.
|
2015-09-03 03:59:53 +08:00
|
|
|
if (I->getType()->isVoidTy())
|
|
|
|
return false;
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2011-01-05 02:54:18 +08:00
|
|
|
uint32_t NextNum = VN.getNextUnusedValueNumber();
|
2016-04-29 00:00:15 +08:00
|
|
|
unsigned Num = VN.lookupOrAdd(I);
|
2011-01-05 02:54:18 +08:00
|
|
|
|
2008-04-07 17:59:07 +08:00
|
|
|
// Allocations are always uniquely numbered, so we can save time and memory
|
2009-09-20 10:20:51 +08:00
|
|
|
// by fast failing them.
|
2018-08-26 17:51:22 +08:00
|
|
|
if (isa<AllocaInst>(I) || I->isTerminator() || isa<PHINode>(I)) {
|
2011-01-05 03:13:25 +08:00
|
|
|
addToLeaderTable(Num, I, I->getParent());
|
2008-04-07 17:59:07 +08:00
|
|
|
return false;
|
2008-06-19 05:41:49 +08:00
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-07-04 01:44:33 +08:00
|
|
|
// If the number we were assigned was a brand new VN, then we don't
|
|
|
|
// need to do a lookup to see if the number already exists
|
|
|
|
// somewhere in the domtree: it can't!
|
2012-02-27 17:54:35 +08:00
|
|
|
if (Num >= NextNum) {
|
2011-01-05 03:13:25 +08:00
|
|
|
addToLeaderTable(Num, I, I->getParent());
|
2010-12-20 04:24:28 +08:00
|
|
|
return false;
|
|
|
|
}
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2008-12-15 10:03:00 +08:00
|
|
|
// Perform fast-path value-number based elimination of values inherited from
|
|
|
|
// dominators.
|
2015-10-24 04:30:02 +08:00
|
|
|
Value *Repl = findLeader(I->getParent(), Num);
|
|
|
|
if (!Repl) {
|
2010-12-20 04:24:28 +08:00
|
|
|
// Failure, just remember this instance for future use.
|
2011-01-05 03:13:25 +08:00
|
|
|
addToLeaderTable(Num, I, I->getParent());
|
2010-12-20 04:24:28 +08:00
|
|
|
return false;
|
2015-10-24 04:30:02 +08:00
|
|
|
} else if (Repl == I) {
|
|
|
|
// If I was the result of a shortcut PRE, it might already be in the table
|
|
|
|
// and the best replacement for itself. Nothing to do.
|
|
|
|
return false;
|
2007-07-25 01:55:58 +08:00
|
|
|
}
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2010-12-20 04:24:28 +08:00
|
|
|
// Remove it!
|
2015-10-24 04:30:02 +08:00
|
|
|
patchAndReplaceAllUsesWith(I, Repl);
|
2017-07-09 15:04:00 +08:00
|
|
|
if (MD && Repl->getType()->isPtrOrPtrVectorTy())
|
2015-10-24 04:30:02 +08:00
|
|
|
MD->invalidateCachedPointerInfo(Repl);
|
2011-04-29 00:36:48 +08:00
|
|
|
markInstructionForDeletion(I);
|
2010-12-20 04:24:28 +08:00
|
|
|
return true;
|
2007-07-25 01:55:58 +08:00
|
|
|
}
|
|
|
|
|
2008-12-23 06:32:22 +08:00
|
|
|
/// runOnFunction - This is the main transformation entry point for a function.
|
2016-12-19 16:22:17 +08:00
|
|
|
bool GVN::runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
|
2016-03-11 16:50:55 +08:00
|
|
|
const TargetLibraryInfo &RunTLI, AAResults &RunAA,
|
2016-12-02 00:40:32 +08:00
|
|
|
MemoryDependenceResults *RunMD, LoopInfo *LI,
|
|
|
|
OptimizationRemarkEmitter *RunORE) {
|
2016-12-19 16:22:17 +08:00
|
|
|
AC = &RunAC;
|
2016-03-11 16:50:55 +08:00
|
|
|
DT = &RunDT;
|
2008-12-01 08:40:32 +08:00
|
|
|
VN.setDomTree(DT);
|
2016-03-11 16:50:55 +08:00
|
|
|
TLI = &RunTLI;
|
|
|
|
VN.setAliasAnalysis(&RunAA);
|
|
|
|
MD = RunMD;
|
2018-08-07 09:47:20 +08:00
|
|
|
ImplicitControlFlowTracking ImplicitCFT(DT);
|
|
|
|
ICF = &ImplicitCFT;
|
2016-03-11 16:50:55 +08:00
|
|
|
VN.setMemDep(MD);
|
2016-12-02 00:40:32 +08:00
|
|
|
ORE = RunORE;
|
[GVN] Update BlockRPONumber prior to use.
Summary:
The original patch addressed the use of BlockRPONumber by forcing a sequence point when accessing that map in a conditional. In short we found cases where that map was being accessed with blocks that had not yet been added to that structure. For context, I've kept the wall of text below, to what we are trying to fix, by always ensuring a updated BlockRPONumber.
== Backstory ==
I was investigating an ICE (segfault accessing a DenseMap item). This failure happened non-deterministically, with no apparent reason and only on a Windows build of LLVM (from October 2018).
After looking into the crashes (multiple core files) and running DynamoRio, the cores and DynamoRio (DR) log pointed to the same code in `GVN::performScalarPRE()`. The values in the map are unsigned integers, the keys are `llvm::BasicBlock*`. Our test case that triggered this warning and periodic crash is rather involved. But the problematic line looks to be:
GVN.cpp: Line 2197
```
if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
```
To test things out, I cooked up a patch that accessed the items in the map outside of the condition, by forcing a sequence point between accesses. DynamoRio stopped warning of the issue, and the test didn't seem to crash after 1000+ runs.
My investigation was on an older version of LLVM, (source from October this year). What it looks like was occurring is the following, and the assembly from the latest pull of llvm in December seems to confirm this might still be an issue; however, I have not witnessed the crash on more recent builds. Of course the asm in question is generated from the host compiler on that Windows box (not clang), but it hints that we might want to consider how we access the BlockRPONumber map in this conditional (line 2197, listed above). In any case, I don't think the host compiler is wrong, rather I think it is pointing out a possibly latent bug in llvm.
1) There is no sequence point for the `>=` operation.
2) A call to a `DenseMapBase::operator[]` can have the side effect of the map reallocating a larger store (more Buckets, via a call to `DenseMap::grow`).
3) It seems perfectly legal for a host compiler to generate assembly that stores the result of a call to `operator[]` on the stack (that's what my host compile of GVN.cpp is doing) . A second call to `operator[]` //might// encourage the map to 'grow' thus making any pointers to the map's store invalid. The `>=` compares the first and second values. If the first happens to be a pointer produced from operator[], it could be invalid when dereferenced at the time of comparison.
The assembly generated from the Window's host compiler does show the result of the first access to the map via `operator[]` produces a pointer to an unsigned int. And that pointer is being stored on the stack. If a second call to the map (which does occur) causes the map to grow, that address (on the stack) is now invalid.
Reviewers: t.p.northover, efriedma
Reviewed By: efriedma
Subscribers: efriedma, llvm-commits
Differential Revision: https://reviews.llvm.org/D55974
llvm-svn: 350880
2019-01-11 03:56:03 +08:00
|
|
|
InvalidBlockRPONumbers = true;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2009-09-21 10:42:51 +08:00
|
|
|
bool Changed = false;
|
|
|
|
bool ShouldContinue = true;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2018-08-03 13:08:17 +08:00
|
|
|
DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
|
2008-07-17 01:52:31 +08:00
|
|
|
// Merge unconditional branches, allowing PRE to catch more
|
|
|
|
// optimization opportunities.
|
|
|
|
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
|
2015-10-14 02:26:00 +08:00
|
|
|
BasicBlock *BB = &*FI++;
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2018-08-22 07:32:03 +08:00
|
|
|
bool removedBlock = MergeBlockIntoPredecessor(BB, &DTU, LI, nullptr, MD);
|
2016-12-01 11:56:43 +08:00
|
|
|
if (removedBlock)
|
|
|
|
++NumGVNBlocks;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2009-09-21 10:42:51 +08:00
|
|
|
Changed |= removedBlock;
|
2008-07-17 01:52:31 +08:00
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-12-10 03:21:47 +08:00
|
|
|
unsigned Iteration = 0;
|
2009-09-21 10:42:51 +08:00
|
|
|
while (ShouldContinue) {
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
|
2009-09-21 10:42:51 +08:00
|
|
|
ShouldContinue = iterateOnFunction(F);
|
|
|
|
Changed |= ShouldContinue;
|
2008-12-10 03:21:47 +08:00
|
|
|
++Iteration;
|
2007-08-15 02:04:11 +08:00
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-07-19 02:03:38 +08:00
|
|
|
if (EnablePRE) {
|
2013-11-12 06:00:23 +08:00
|
|
|
// Fabricate val-num for dead-code in order to suppress assertion in
|
|
|
|
// performPRE().
|
|
|
|
assignValNumForDeadCode();
|
2008-09-04 07:06:07 +08:00
|
|
|
bool PREChanged = true;
|
|
|
|
while (PREChanged) {
|
|
|
|
PREChanged = performPRE(F);
|
2009-09-21 10:42:51 +08:00
|
|
|
Changed |= PREChanged;
|
2008-09-04 07:06:07 +08:00
|
|
|
}
|
2008-07-19 02:03:38 +08:00
|
|
|
}
|
2013-05-10 02:34:27 +08:00
|
|
|
|
2008-12-10 03:21:47 +08:00
|
|
|
// FIXME: Should perform GVN again after PRE does something. PRE can move
|
|
|
|
// computations into blocks where they become fully redundant. Note that
|
|
|
|
// we can't do this until PRE's critical edge splitting updates memdep.
|
|
|
|
// Actually, when this happens, we should just fully integrate PRE into GVN.
|
2008-10-11 00:25:50 +08:00
|
|
|
|
|
|
|
cleanupGlobalSets();
|
2013-11-12 06:00:23 +08:00
|
|
|
// Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
|
2016-04-29 00:00:15 +08:00
|
|
|
// iteration.
|
2013-11-12 06:00:23 +08:00
|
|
|
DeadBlocks.clear();
|
2008-10-11 00:25:50 +08:00
|
|
|
|
2009-09-21 10:42:51 +08:00
|
|
|
return Changed;
|
2007-08-15 02:04:11 +08:00
|
|
|
}
|
|
|
|
|
2009-09-21 10:42:51 +08:00
|
|
|
bool GVN::processBlock(BasicBlock *BB) {
|
2011-04-29 00:18:52 +08:00
|
|
|
// FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
|
|
|
|
// (and incrementing BI before processing an instruction).
|
|
|
|
assert(InstrsToErase.empty() &&
|
|
|
|
"We expect InstrsToErase to be empty across iterations");
|
2013-11-12 06:00:23 +08:00
|
|
|
if (DeadBlocks.count(BB))
|
|
|
|
return false;
|
|
|
|
|
2015-09-03 03:59:53 +08:00
|
|
|
// Clearing map before every BB because it can be used only for single BB.
|
|
|
|
ReplaceWithConstMap.clear();
|
2009-09-21 10:42:51 +08:00
|
|
|
bool ChangedFunction = false;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-06-13 03:25:32 +08:00
|
|
|
for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
|
|
|
|
BI != BE;) {
|
2015-09-03 03:59:53 +08:00
|
|
|
if (!ReplaceWithConstMap.empty())
|
2015-10-14 02:26:00 +08:00
|
|
|
ChangedFunction |= replaceOperandsWithConsts(&*BI);
|
|
|
|
ChangedFunction |= processInstruction(&*BI);
|
2015-09-03 04:00:03 +08:00
|
|
|
|
2011-04-29 00:18:52 +08:00
|
|
|
if (InstrsToErase.empty()) {
|
2008-06-13 03:25:32 +08:00
|
|
|
++BI;
|
|
|
|
continue;
|
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-06-13 03:25:32 +08:00
|
|
|
// If we need some instructions deleted, do it now.
|
2011-04-29 00:18:52 +08:00
|
|
|
NumGVNInstr += InstrsToErase.size();
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2008-06-13 03:25:32 +08:00
|
|
|
// Avoid iterator invalidation.
|
|
|
|
bool AtStart = BI == BB->begin();
|
|
|
|
if (!AtStart)
|
|
|
|
--BI;
|
|
|
|
|
2017-10-27 16:19:35 +08:00
|
|
|
for (auto *I : InstrsToErase) {
|
|
|
|
assert(I->getParent() == BB && "Removing instruction from wrong block?");
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN removed: " << *I << '\n');
|
2018-02-14 06:27:17 +08:00
|
|
|
salvageDebugInfo(*I);
|
2017-10-27 16:19:35 +08:00
|
|
|
if (MD) MD->removeInstruction(I);
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(verifyRemoved(I));
|
2019-01-09 15:28:13 +08:00
|
|
|
ICF->removeInstruction(I);
|
2017-10-27 16:19:35 +08:00
|
|
|
I->eraseFromParent();
|
2008-12-01 08:40:32 +08:00
|
|
|
}
|
2011-04-29 00:18:52 +08:00
|
|
|
InstrsToErase.clear();
|
2008-06-13 03:25:32 +08:00
|
|
|
|
|
|
|
if (AtStart)
|
|
|
|
BI = BB->begin();
|
|
|
|
else
|
|
|
|
++BI;
|
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2009-09-21 10:42:51 +08:00
|
|
|
return ChangedFunction;
|
2008-06-13 03:25:32 +08:00
|
|
|
}
|
|
|
|
|
2015-02-04 04:37:08 +08:00
|
|
|
// Instantiate an expression in a predecessor that lacked it.
|
|
|
|
bool GVN::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
BasicBlock *Curr, unsigned int ValNo) {
|
2015-02-04 04:37:08 +08:00
|
|
|
// Because we are going top-down through the block, all value numbers
|
|
|
|
// will be available in the predecessor by the time we need them. Any
|
|
|
|
// that weren't originally present will have been instantiated earlier
|
|
|
|
// in this loop.
|
|
|
|
bool success = true;
|
|
|
|
for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) {
|
|
|
|
Value *Op = Instr->getOperand(i);
|
|
|
|
if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
|
|
|
|
continue;
|
2015-11-19 10:45:18 +08:00
|
|
|
// This could be a newly inserted instruction, in which case, we won't
|
|
|
|
// find a value number, and should give up before we hurt ourselves.
|
|
|
|
// FIXME: Rewrite the infrastructure to let it easier to value number
|
|
|
|
// and process newly inserted instructions.
|
|
|
|
if (!VN.exists(Op)) {
|
|
|
|
success = false;
|
|
|
|
break;
|
|
|
|
}
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
uint32_t TValNo =
|
|
|
|
VN.phiTranslate(Pred, Curr, VN.lookup(Op), *this);
|
|
|
|
if (Value *V = findLeader(Pred, TValNo)) {
|
2015-02-04 04:37:08 +08:00
|
|
|
Instr->setOperand(i, V);
|
|
|
|
} else {
|
|
|
|
success = false;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Fail out if we encounter an operand that is not available in
|
|
|
|
// the PRE predecessor. This is typically because of loads which
|
|
|
|
// are not value numbered precisely.
|
|
|
|
if (!success)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
Instr->insertBefore(Pred->getTerminator());
|
|
|
|
Instr->setName(Instr->getName() + ".pre");
|
|
|
|
Instr->setDebugLoc(Instr->getDebugLoc());
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
|
|
|
|
unsigned Num = VN.lookupOrAdd(Instr);
|
|
|
|
VN.add(Instr, Num);
|
2015-02-04 04:37:08 +08:00
|
|
|
|
|
|
|
// Update the availability map to include the new instruction.
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
addToLeaderTable(Num, Instr, Pred);
|
2015-02-04 04:37:08 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-01-10 03:19:56 +08:00
|
|
|
bool GVN::performScalarPRE(Instruction *CurInst) {
|
2018-08-26 17:51:22 +08:00
|
|
|
if (isa<AllocaInst>(CurInst) || CurInst->isTerminator() ||
|
2015-01-10 03:19:56 +08:00
|
|
|
isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
|
|
|
|
CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
|
|
|
|
isa<DbgInfoIntrinsic>(CurInst))
|
|
|
|
return false;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2015-01-10 03:19:56 +08:00
|
|
|
// Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
|
|
|
|
// sinking the compare again, and it would force the code generator to
|
|
|
|
// move the i1 from processor flags or predicate registers into a general
|
|
|
|
// purpose register.
|
|
|
|
if (isa<CmpInst>(CurInst))
|
|
|
|
return false;
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2018-12-07 00:11:58 +08:00
|
|
|
// Don't do PRE on GEPs. The inserted PHI would prevent CodeGenPrepare from
|
|
|
|
// sinking the addressing mode computation back to its uses. Extending the
|
|
|
|
// GEP's live range increases the register pressure, and therefore it can
|
|
|
|
// introduce unnecessary spills.
|
|
|
|
//
|
|
|
|
// This doesn't prevent Load PRE. PHI translation will make the GEP available
|
|
|
|
// to the load by moving it to the predecessor block if necessary.
|
|
|
|
if (isa<GetElementPtrInst>(CurInst))
|
|
|
|
return false;
|
|
|
|
|
2015-01-10 03:19:56 +08:00
|
|
|
// We don't currently value number ANY inline asm calls.
|
2019-02-09 04:48:56 +08:00
|
|
|
if (auto *CallB = dyn_cast<CallBase>(CurInst))
|
|
|
|
if (CallB->isInlineAsm())
|
2015-01-10 03:19:56 +08:00
|
|
|
return false;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2015-01-10 03:19:56 +08:00
|
|
|
uint32_t ValNo = VN.lookup(CurInst);
|
|
|
|
|
|
|
|
// Look for the predecessors for PRE opportunities. We're
|
|
|
|
// only trying to solve the basic diamond case, where
|
|
|
|
// a value is computed in the successor and one predecessor,
|
|
|
|
// but not the other. We also explicitly disallow cases
|
|
|
|
// where the successor is its own predecessor, because they're
|
|
|
|
// more complicated to get right.
|
|
|
|
unsigned NumWith = 0;
|
|
|
|
unsigned NumWithout = 0;
|
|
|
|
BasicBlock *PREPred = nullptr;
|
|
|
|
BasicBlock *CurrentBlock = CurInst->getParent();
|
|
|
|
|
[GVN] Update BlockRPONumber prior to use.
Summary:
The original patch addressed the use of BlockRPONumber by forcing a sequence point when accessing that map in a conditional. In short we found cases where that map was being accessed with blocks that had not yet been added to that structure. For context, I've kept the wall of text below, to what we are trying to fix, by always ensuring a updated BlockRPONumber.
== Backstory ==
I was investigating an ICE (segfault accessing a DenseMap item). This failure happened non-deterministically, with no apparent reason and only on a Windows build of LLVM (from October 2018).
After looking into the crashes (multiple core files) and running DynamoRio, the cores and DynamoRio (DR) log pointed to the same code in `GVN::performScalarPRE()`. The values in the map are unsigned integers, the keys are `llvm::BasicBlock*`. Our test case that triggered this warning and periodic crash is rather involved. But the problematic line looks to be:
GVN.cpp: Line 2197
```
if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
```
To test things out, I cooked up a patch that accessed the items in the map outside of the condition, by forcing a sequence point between accesses. DynamoRio stopped warning of the issue, and the test didn't seem to crash after 1000+ runs.
My investigation was on an older version of LLVM, (source from October this year). What it looks like was occurring is the following, and the assembly from the latest pull of llvm in December seems to confirm this might still be an issue; however, I have not witnessed the crash on more recent builds. Of course the asm in question is generated from the host compiler on that Windows box (not clang), but it hints that we might want to consider how we access the BlockRPONumber map in this conditional (line 2197, listed above). In any case, I don't think the host compiler is wrong, rather I think it is pointing out a possibly latent bug in llvm.
1) There is no sequence point for the `>=` operation.
2) A call to a `DenseMapBase::operator[]` can have the side effect of the map reallocating a larger store (more Buckets, via a call to `DenseMap::grow`).
3) It seems perfectly legal for a host compiler to generate assembly that stores the result of a call to `operator[]` on the stack (that's what my host compile of GVN.cpp is doing) . A second call to `operator[]` //might// encourage the map to 'grow' thus making any pointers to the map's store invalid. The `>=` compares the first and second values. If the first happens to be a pointer produced from operator[], it could be invalid when dereferenced at the time of comparison.
The assembly generated from the Window's host compiler does show the result of the first access to the map via `operator[]` produces a pointer to an unsigned int. And that pointer is being stored on the stack. If a second call to the map (which does occur) causes the map to grow, that address (on the stack) is now invalid.
Reviewers: t.p.northover, efriedma
Reviewed By: efriedma
Subscribers: efriedma, llvm-commits
Differential Revision: https://reviews.llvm.org/D55974
llvm-svn: 350880
2019-01-11 03:56:03 +08:00
|
|
|
// Update the RPO numbers for this function.
|
|
|
|
if (InvalidBlockRPONumbers)
|
|
|
|
assignBlockRPONumber(*CurrentBlock->getParent());
|
|
|
|
|
2016-04-29 00:00:15 +08:00
|
|
|
SmallVector<std::pair<Value *, BasicBlock *>, 8> predMap;
|
2015-11-28 16:23:04 +08:00
|
|
|
for (BasicBlock *P : predecessors(CurrentBlock)) {
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
// We're not interested in PRE where blocks with predecessors that are
|
|
|
|
// not reachable.
|
|
|
|
if (!DT->isReachableFromEntry(P)) {
|
2015-01-10 03:19:56 +08:00
|
|
|
NumWithout = 2;
|
|
|
|
break;
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
}
|
|
|
|
// It is not safe to do PRE when P->CurrentBlock is a loop backedge, and
|
|
|
|
// when CurInst has operand defined in CurrentBlock (so it may be defined
|
|
|
|
// by phi in the loop header).
|
[GVN] Update BlockRPONumber prior to use.
Summary:
The original patch addressed the use of BlockRPONumber by forcing a sequence point when accessing that map in a conditional. In short we found cases where that map was being accessed with blocks that had not yet been added to that structure. For context, I've kept the wall of text below, to what we are trying to fix, by always ensuring a updated BlockRPONumber.
== Backstory ==
I was investigating an ICE (segfault accessing a DenseMap item). This failure happened non-deterministically, with no apparent reason and only on a Windows build of LLVM (from October 2018).
After looking into the crashes (multiple core files) and running DynamoRio, the cores and DynamoRio (DR) log pointed to the same code in `GVN::performScalarPRE()`. The values in the map are unsigned integers, the keys are `llvm::BasicBlock*`. Our test case that triggered this warning and periodic crash is rather involved. But the problematic line looks to be:
GVN.cpp: Line 2197
```
if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
```
To test things out, I cooked up a patch that accessed the items in the map outside of the condition, by forcing a sequence point between accesses. DynamoRio stopped warning of the issue, and the test didn't seem to crash after 1000+ runs.
My investigation was on an older version of LLVM, (source from October this year). What it looks like was occurring is the following, and the assembly from the latest pull of llvm in December seems to confirm this might still be an issue; however, I have not witnessed the crash on more recent builds. Of course the asm in question is generated from the host compiler on that Windows box (not clang), but it hints that we might want to consider how we access the BlockRPONumber map in this conditional (line 2197, listed above). In any case, I don't think the host compiler is wrong, rather I think it is pointing out a possibly latent bug in llvm.
1) There is no sequence point for the `>=` operation.
2) A call to a `DenseMapBase::operator[]` can have the side effect of the map reallocating a larger store (more Buckets, via a call to `DenseMap::grow`).
3) It seems perfectly legal for a host compiler to generate assembly that stores the result of a call to `operator[]` on the stack (that's what my host compile of GVN.cpp is doing) . A second call to `operator[]` //might// encourage the map to 'grow' thus making any pointers to the map's store invalid. The `>=` compares the first and second values. If the first happens to be a pointer produced from operator[], it could be invalid when dereferenced at the time of comparison.
The assembly generated from the Window's host compiler does show the result of the first access to the map via `operator[]` produces a pointer to an unsigned int. And that pointer is being stored on the stack. If a second call to the map (which does occur) causes the map to grow, that address (on the stack) is now invalid.
Reviewers: t.p.northover, efriedma
Reviewed By: efriedma
Subscribers: efriedma, llvm-commits
Differential Revision: https://reviews.llvm.org/D55974
llvm-svn: 350880
2019-01-11 03:56:03 +08:00
|
|
|
assert(BlockRPONumber.count(P) && BlockRPONumber.count(CurrentBlock) &&
|
|
|
|
"Invalid BlockRPONumber map.");
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
|
2017-09-14 05:43:53 +08:00
|
|
|
llvm::any_of(CurInst->operands(), [&](const Use &U) {
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
if (auto *Inst = dyn_cast<Instruction>(U.get()))
|
|
|
|
return Inst->getParent() == CurrentBlock;
|
|
|
|
return false;
|
|
|
|
})) {
|
2015-01-10 03:19:56 +08:00
|
|
|
NumWithout = 2;
|
|
|
|
break;
|
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
uint32_t TValNo = VN.phiTranslate(P, CurrentBlock, ValNo, *this);
|
|
|
|
Value *predV = findLeader(P, TValNo);
|
2015-01-10 03:19:56 +08:00
|
|
|
if (!predV) {
|
|
|
|
predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
|
|
|
|
PREPred = P;
|
|
|
|
++NumWithout;
|
|
|
|
} else if (predV == CurInst) {
|
|
|
|
/* CurInst dominates this predecessor. */
|
|
|
|
NumWithout = 2;
|
|
|
|
break;
|
|
|
|
} else {
|
|
|
|
predMap.push_back(std::make_pair(predV, P));
|
|
|
|
++NumWith;
|
|
|
|
}
|
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2015-01-10 03:19:56 +08:00
|
|
|
// Don't do PRE when it might increase code size, i.e. when
|
|
|
|
// we would need to insert instructions in more than one pred.
|
2015-02-04 04:37:08 +08:00
|
|
|
if (NumWithout > 1 || NumWith == 0)
|
2015-01-10 03:19:56 +08:00
|
|
|
return false;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2015-02-04 04:37:08 +08:00
|
|
|
// We may have a case where all predecessors have the instruction,
|
|
|
|
// and we just need to insert a phi node. Otherwise, perform
|
|
|
|
// insertion.
|
|
|
|
Instruction *PREInstr = nullptr;
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2015-02-04 04:37:08 +08:00
|
|
|
if (NumWithout != 0) {
|
2017-11-28 15:07:55 +08:00
|
|
|
if (!isSafeToSpeculativelyExecute(CurInst)) {
|
|
|
|
// It is only valid to insert a new instruction if the current instruction
|
|
|
|
// is always executed. An instruction with implicit control flow could
|
|
|
|
// prevent us from doing it. If we cannot speculate the execution, then
|
|
|
|
// PRE should be prohibited.
|
2018-08-07 09:47:20 +08:00
|
|
|
if (ICF->isDominatedByICFIFromSameBlock(CurInst))
|
|
|
|
return false;
|
2017-11-28 15:07:55 +08:00
|
|
|
}
|
|
|
|
|
2015-02-04 04:37:08 +08:00
|
|
|
// Don't do PRE across indirect branch.
|
|
|
|
if (isa<IndirectBrInst>(PREPred->getTerminator()))
|
|
|
|
return false;
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2019-02-09 04:48:56 +08:00
|
|
|
// Don't do PRE across callbr.
|
|
|
|
// FIXME: Can we do this across the fallthrough edge?
|
|
|
|
if (isa<CallBrInst>(PREPred->getTerminator()))
|
|
|
|
return false;
|
|
|
|
|
2015-02-04 04:37:08 +08:00
|
|
|
// We can't do PRE safely on a critical edge, so instead we schedule
|
|
|
|
// the edge to be split and perform the PRE the next time we iterate
|
|
|
|
// on the function.
|
|
|
|
unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
|
|
|
|
if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
|
|
|
|
toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
// We need to insert somewhere, so let's give it a shot
|
|
|
|
PREInstr = CurInst->clone();
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) {
|
2015-02-04 04:37:08 +08:00
|
|
|
// If we failed insertion, make sure we remove the instruction.
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(verifyRemoved(PREInstr));
|
[IR] De-virtualize ~Value to save a vptr
Summary:
Implements PR889
Removing the virtual table pointer from Value saves 1% of RSS when doing
LTO of llc on Linux. The impact on time was positive, but too noisy to
conclusively say that performance improved. Here is a link to the
spreadsheet with the original data:
https://docs.google.com/spreadsheets/d/1F4FHir0qYnV0MEp2sYYp_BuvnJgWlWPhWOwZ6LbW7W4/edit?usp=sharing
This change makes it invalid to directly delete a Value, User, or
Instruction pointer. Instead, such code can be rewritten to a null check
and a call Value::deleteValue(). Value objects tend to have their
lifetimes managed through iplist, so for the most part, this isn't a big
deal. However, there are some places where LLVM deletes values, and
those places had to be migrated to deleteValue. I have also created
llvm::unique_value, which has a custom deleter, so it can be used in
place of std::unique_ptr<Value>.
I had to add the "DerivedUser" Deleter escape hatch for MemorySSA, which
derives from User outside of lib/IR. Code in IR cannot include MemorySSA
headers or call the MemoryAccess object destructors without introducing
a circular dependency, so we need some level of indirection.
Unfortunately, no class derived from User may have any virtual methods,
because adding a virtual method would break User::getHungOffOperands(),
which assumes that it can find the use list immediately prior to the
User object. I've added a static_assert to the appropriate OperandTraits
templates to help people avoid this trap.
Reviewers: chandlerc, mehdi_amini, pete, dberlin, george.burgess.iv
Reviewed By: chandlerc
Subscribers: krytarowski, eraman, george.burgess.iv, mzolotukhin, Prazek, nlewycky, hans, inglorion, pcc, tejohnson, dberlin, llvm-commits
Differential Revision: https://reviews.llvm.org/D31261
llvm-svn: 303362
2017-05-19 01:24:10 +08:00
|
|
|
PREInstr->deleteValue();
|
2015-02-04 04:37:08 +08:00
|
|
|
return false;
|
2015-01-10 03:19:56 +08:00
|
|
|
}
|
|
|
|
}
|
2014-11-14 05:17:58 +08:00
|
|
|
|
2015-02-04 04:37:08 +08:00
|
|
|
// Either we should have filled in the PRE instruction, or we should
|
|
|
|
// not have needed insertions.
|
2017-09-14 05:43:53 +08:00
|
|
|
assert(PREInstr != nullptr || NumWithout == 0);
|
2014-11-14 05:17:58 +08:00
|
|
|
|
2015-01-10 03:19:56 +08:00
|
|
|
++NumGVNPRE;
|
2014-11-14 05:17:58 +08:00
|
|
|
|
2015-01-10 03:19:56 +08:00
|
|
|
// Create a PHI to make the value available in this block.
|
|
|
|
PHINode *Phi =
|
|
|
|
PHINode::Create(CurInst->getType(), predMap.size(),
|
2015-10-14 02:26:00 +08:00
|
|
|
CurInst->getName() + ".pre-phi", &CurrentBlock->front());
|
2015-01-10 03:19:56 +08:00
|
|
|
for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
|
2017-11-09 14:02:18 +08:00
|
|
|
if (Value *V = predMap[i].first) {
|
|
|
|
// If we use an existing value in this phi, we have to patch the original
|
|
|
|
// value because the phi will be used to replace a later value.
|
|
|
|
patchReplacementInstruction(CurInst, V);
|
2015-01-10 03:19:56 +08:00
|
|
|
Phi->addIncoming(V, predMap[i].second);
|
2017-11-09 14:02:18 +08:00
|
|
|
} else
|
2015-01-10 03:19:56 +08:00
|
|
|
Phi->addIncoming(PREInstr, PREPred);
|
|
|
|
}
|
|
|
|
|
|
|
|
VN.add(Phi, ValNo);
|
2017-08-09 05:40:14 +08:00
|
|
|
// After creating a new PHI for ValNo, the phi translate result for ValNo will
|
|
|
|
// be changed, so erase the related stale entries in phi translate cache.
|
|
|
|
VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock);
|
2015-01-10 03:19:56 +08:00
|
|
|
addToLeaderTable(ValNo, Phi, CurrentBlock);
|
|
|
|
Phi->setDebugLoc(CurInst->getDebugLoc());
|
|
|
|
CurInst->replaceAllUsesWith(Phi);
|
2017-07-09 15:04:00 +08:00
|
|
|
if (MD && Phi->getType()->isPtrOrPtrVectorTy())
|
[PM/AA] Remove the addEscapingUse update API that won't be easy to
directly model in the new PM.
This also was an incredibly brittle and expensive update API that was
never fully utilized by all the passes that claimed to preserve AA, nor
could it reasonably have been extended to all of them. Any number of
places add uses of values. If we ever wanted to reliably instrument
this, we would want a callback hook much like we have with ValueHandles,
but doing this for every use addition seems *extremely* expensive in
terms of compile time.
The only user of this update mechanism is GlobalsModRef. The idea of
using this to keep it up to date doesn't really work anyways as its
analysis requires a symmetric analysis of two different memory
locations. It would be very hard to make updates be sufficiently
rigorous to *guarantee* symmetric analysis in this way, and it pretty
certainly isn't true today.
However, folks have been using GMR with this update for a long time and
seem to not be hitting the issues. The reported issue that the update
hook fixes isn't even a problem any more as other changes to
GetUnderlyingObject worked around it, and that issue stemmed from *many*
years ago. As a consequence, a prior patch provided a flag to control
the unsafe behavior of GMR, and this patch removes the update mechanism
that has questionable compile-time tradeoffs and is causing problems
with moving to the new pass manager. Note the lack of test updates --
not one test in tree actually requires this update, even for a contrived
case.
All of this was extensively discussed on the dev list, this patch will
just enact what that discussion decides on. I'm sending it for review in
part to show what I'm planning, and in part to show the *amazing* amount
of work this avoids. Every call to the AA here is something like three
to six indirect function calls, which in the non-LTO pipeline never do
any work! =[
Differential Revision: http://reviews.llvm.org/D11214
llvm-svn: 242605
2015-07-18 11:26:46 +08:00
|
|
|
MD->invalidateCachedPointerInfo(Phi);
|
2015-01-10 03:19:56 +08:00
|
|
|
VN.erase(CurInst);
|
|
|
|
removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
|
2014-11-15 05:09:13 +08:00
|
|
|
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
|
2015-01-10 03:19:56 +08:00
|
|
|
if (MD)
|
|
|
|
MD->removeInstruction(CurInst);
|
2018-05-14 20:53:11 +08:00
|
|
|
LLVM_DEBUG(verifyRemoved(CurInst));
|
2017-10-31 13:07:56 +08:00
|
|
|
// FIXME: Intended to be markInstructionForDeletion(CurInst), but it causes
|
|
|
|
// some assertion failures.
|
2019-01-09 15:28:13 +08:00
|
|
|
ICF->removeInstruction(CurInst);
|
2015-01-10 03:19:56 +08:00
|
|
|
CurInst->eraseFromParent();
|
2015-02-04 04:37:08 +08:00
|
|
|
++NumGVNInstr;
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2015-01-10 03:19:56 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Perform a purely local form of PRE that looks for diamond
|
2015-01-10 03:19:56 +08:00
|
|
|
/// control flow patterns and attempts to perform simple PRE at the join point.
|
|
|
|
bool GVN::performPRE(Function &F) {
|
|
|
|
bool Changed = false;
|
|
|
|
for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
|
|
|
|
// Nothing to PRE in the entry block.
|
|
|
|
if (CurrentBlock == &F.getEntryBlock())
|
|
|
|
continue;
|
|
|
|
|
2015-08-04 16:21:40 +08:00
|
|
|
// Don't perform PRE on an EH pad.
|
|
|
|
if (CurrentBlock->isEHPad())
|
2015-01-10 03:19:56 +08:00
|
|
|
continue;
|
|
|
|
|
|
|
|
for (BasicBlock::iterator BI = CurrentBlock->begin(),
|
|
|
|
BE = CurrentBlock->end();
|
|
|
|
BI != BE;) {
|
2015-10-14 02:26:00 +08:00
|
|
|
Instruction *CurInst = &*BI++;
|
2015-11-19 06:49:49 +08:00
|
|
|
Changed |= performScalarPRE(CurInst);
|
2008-06-19 05:41:49 +08:00
|
|
|
}
|
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2010-02-17 03:51:59 +08:00
|
|
|
if (splitCriticalEdges())
|
|
|
|
Changed = true;
|
|
|
|
|
|
|
|
return Changed;
|
|
|
|
}
|
2009-09-20 10:20:51 +08:00
|
|
|
|
2013-05-10 02:34:27 +08:00
|
|
|
/// Split the critical edge connecting the given two blocks, and return
|
|
|
|
/// the block inserted to the critical edge.
|
|
|
|
BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
|
2015-07-22 17:52:54 +08:00
|
|
|
BasicBlock *BB =
|
|
|
|
SplitCriticalEdge(Pred, Succ, CriticalEdgeSplittingOptions(DT));
|
2013-05-10 02:34:27 +08:00
|
|
|
if (MD)
|
|
|
|
MD->invalidateCachedPredecessors();
|
[GVN] Update BlockRPONumber prior to use.
Summary:
The original patch addressed the use of BlockRPONumber by forcing a sequence point when accessing that map in a conditional. In short we found cases where that map was being accessed with blocks that had not yet been added to that structure. For context, I've kept the wall of text below, to what we are trying to fix, by always ensuring a updated BlockRPONumber.
== Backstory ==
I was investigating an ICE (segfault accessing a DenseMap item). This failure happened non-deterministically, with no apparent reason and only on a Windows build of LLVM (from October 2018).
After looking into the crashes (multiple core files) and running DynamoRio, the cores and DynamoRio (DR) log pointed to the same code in `GVN::performScalarPRE()`. The values in the map are unsigned integers, the keys are `llvm::BasicBlock*`. Our test case that triggered this warning and periodic crash is rather involved. But the problematic line looks to be:
GVN.cpp: Line 2197
```
if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
```
To test things out, I cooked up a patch that accessed the items in the map outside of the condition, by forcing a sequence point between accesses. DynamoRio stopped warning of the issue, and the test didn't seem to crash after 1000+ runs.
My investigation was on an older version of LLVM, (source from October this year). What it looks like was occurring is the following, and the assembly from the latest pull of llvm in December seems to confirm this might still be an issue; however, I have not witnessed the crash on more recent builds. Of course the asm in question is generated from the host compiler on that Windows box (not clang), but it hints that we might want to consider how we access the BlockRPONumber map in this conditional (line 2197, listed above). In any case, I don't think the host compiler is wrong, rather I think it is pointing out a possibly latent bug in llvm.
1) There is no sequence point for the `>=` operation.
2) A call to a `DenseMapBase::operator[]` can have the side effect of the map reallocating a larger store (more Buckets, via a call to `DenseMap::grow`).
3) It seems perfectly legal for a host compiler to generate assembly that stores the result of a call to `operator[]` on the stack (that's what my host compile of GVN.cpp is doing) . A second call to `operator[]` //might// encourage the map to 'grow' thus making any pointers to the map's store invalid. The `>=` compares the first and second values. If the first happens to be a pointer produced from operator[], it could be invalid when dereferenced at the time of comparison.
The assembly generated from the Window's host compiler does show the result of the first access to the map via `operator[]` produces a pointer to an unsigned int. And that pointer is being stored on the stack. If a second call to the map (which does occur) causes the map to grow, that address (on the stack) is now invalid.
Reviewers: t.p.northover, efriedma
Reviewed By: efriedma
Subscribers: efriedma, llvm-commits
Differential Revision: https://reviews.llvm.org/D55974
llvm-svn: 350880
2019-01-11 03:56:03 +08:00
|
|
|
InvalidBlockRPONumbers = true;
|
2013-05-10 02:34:27 +08:00
|
|
|
return BB;
|
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Split critical edges found during the previous
|
2010-02-17 03:51:59 +08:00
|
|
|
/// iteration that may enable further optimization.
|
|
|
|
bool GVN::splitCriticalEdges() {
|
|
|
|
if (toSplit.empty())
|
|
|
|
return false;
|
|
|
|
do {
|
2018-10-15 18:00:15 +08:00
|
|
|
std::pair<Instruction *, unsigned> Edge = toSplit.pop_back_val();
|
2015-01-19 20:09:11 +08:00
|
|
|
SplitCriticalEdge(Edge.first, Edge.second,
|
2015-07-22 17:52:54 +08:00
|
|
|
CriticalEdgeSplittingOptions(DT));
|
2010-02-17 03:51:59 +08:00
|
|
|
} while (!toSplit.empty());
|
2010-03-02 06:23:12 +08:00
|
|
|
if (MD) MD->invalidateCachedPredecessors();
|
[GVN] Update BlockRPONumber prior to use.
Summary:
The original patch addressed the use of BlockRPONumber by forcing a sequence point when accessing that map in a conditional. In short we found cases where that map was being accessed with blocks that had not yet been added to that structure. For context, I've kept the wall of text below, to what we are trying to fix, by always ensuring a updated BlockRPONumber.
== Backstory ==
I was investigating an ICE (segfault accessing a DenseMap item). This failure happened non-deterministically, with no apparent reason and only on a Windows build of LLVM (from October 2018).
After looking into the crashes (multiple core files) and running DynamoRio, the cores and DynamoRio (DR) log pointed to the same code in `GVN::performScalarPRE()`. The values in the map are unsigned integers, the keys are `llvm::BasicBlock*`. Our test case that triggered this warning and periodic crash is rather involved. But the problematic line looks to be:
GVN.cpp: Line 2197
```
if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
```
To test things out, I cooked up a patch that accessed the items in the map outside of the condition, by forcing a sequence point between accesses. DynamoRio stopped warning of the issue, and the test didn't seem to crash after 1000+ runs.
My investigation was on an older version of LLVM, (source from October this year). What it looks like was occurring is the following, and the assembly from the latest pull of llvm in December seems to confirm this might still be an issue; however, I have not witnessed the crash on more recent builds. Of course the asm in question is generated from the host compiler on that Windows box (not clang), but it hints that we might want to consider how we access the BlockRPONumber map in this conditional (line 2197, listed above). In any case, I don't think the host compiler is wrong, rather I think it is pointing out a possibly latent bug in llvm.
1) There is no sequence point for the `>=` operation.
2) A call to a `DenseMapBase::operator[]` can have the side effect of the map reallocating a larger store (more Buckets, via a call to `DenseMap::grow`).
3) It seems perfectly legal for a host compiler to generate assembly that stores the result of a call to `operator[]` on the stack (that's what my host compile of GVN.cpp is doing) . A second call to `operator[]` //might// encourage the map to 'grow' thus making any pointers to the map's store invalid. The `>=` compares the first and second values. If the first happens to be a pointer produced from operator[], it could be invalid when dereferenced at the time of comparison.
The assembly generated from the Window's host compiler does show the result of the first access to the map via `operator[]` produces a pointer to an unsigned int. And that pointer is being stored on the stack. If a second call to the map (which does occur) causes the map to grow, that address (on the stack) is now invalid.
Reviewers: t.p.northover, efriedma
Reviewed By: efriedma
Subscribers: efriedma, llvm-commits
Differential Revision: https://reviews.llvm.org/D55974
llvm-svn: 350880
2019-01-11 03:56:03 +08:00
|
|
|
InvalidBlockRPONumbers = true;
|
2010-02-17 03:51:59 +08:00
|
|
|
return true;
|
2008-06-19 05:41:49 +08:00
|
|
|
}
|
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Executes one iteration of GVN
|
2007-08-15 02:04:11 +08:00
|
|
|
bool GVN::iterateOnFunction(Function &F) {
|
2008-10-11 00:25:50 +08:00
|
|
|
cleanupGlobalSets();
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2007-07-25 01:55:58 +08:00
|
|
|
// Top-down walk of the dominator tree
|
2009-09-21 10:42:51 +08:00
|
|
|
bool Changed = false;
|
2015-01-10 03:19:56 +08:00
|
|
|
// Needed for value numbering with phi construction to work.
|
2017-03-19 02:24:41 +08:00
|
|
|
// RPOT walks the graph in its constructor and will not be invalidated during
|
|
|
|
// processBlock.
|
2015-01-10 03:19:56 +08:00
|
|
|
ReversePostOrderTraversal<Function *> RPOT(&F);
|
2017-10-31 13:07:56 +08:00
|
|
|
|
2017-03-19 02:24:41 +08:00
|
|
|
for (BasicBlock *BB : RPOT)
|
|
|
|
Changed |= processBlock(BB);
|
2014-11-14 06:54:59 +08:00
|
|
|
|
2009-09-21 10:42:51 +08:00
|
|
|
return Changed;
|
2007-07-25 01:55:58 +08:00
|
|
|
}
|
2008-10-11 00:25:50 +08:00
|
|
|
|
|
|
|
void GVN::cleanupGlobalSets() {
|
|
|
|
VN.clear();
|
2011-01-05 03:29:46 +08:00
|
|
|
LeaderTable.clear();
|
[GVN] Recommit the patch "Add phi-translate support in scalarpre"
Recommit after workaround the bug PR31652.
Three bugs fixed in previous recommits: The first one is to use CurrentBlock
instead of PREInstr's Parent as param of performScalarPREInsertion because
the Parent of a clone instruction may be uninitialized. The second one is stop
PRE when CurrentBlock to its predecessor is a backedge and an operand of CurInst
is defined inside of CurrentBlock. The same value defined inside of loop in last
iteration can not be regarded as available. The third one is an out-of-bound
array access in a flipped if guard.
Right now scalarpre doesn't have phi-translate support, so it will miss some
simple pre opportunities. Like the following testcase, current scalarpre cannot
recognize the last "a * b" is fully redundent because a and b used by the last
"a * b" expr are both defined by phis.
long a[100], b[100], g1, g2, g3;
__attribute__((pure)) long goo();
void foo(long a, long b, long c, long d) {
g1 = a * b;
if (__builtin_expect(g2 > 3, 0)) {
a = c;
b = d;
g2 = a * b;
}
g3 = a * b; // fully redundant.
}
The patch adds phi-translate support in scalarpre. This is only a temporary
solution before the newpre based on newgvn is available.
Differential Revision: https://reviews.llvm.org/D32252
llvm-svn: 309397
2017-07-28 23:47:25 +08:00
|
|
|
BlockRPONumber.clear();
|
2010-11-19 02:32:40 +08:00
|
|
|
TableAllocator.Reset();
|
2018-08-07 09:47:20 +08:00
|
|
|
ICF->clear();
|
[GVN] Update BlockRPONumber prior to use.
Summary:
The original patch addressed the use of BlockRPONumber by forcing a sequence point when accessing that map in a conditional. In short we found cases where that map was being accessed with blocks that had not yet been added to that structure. For context, I've kept the wall of text below, to what we are trying to fix, by always ensuring a updated BlockRPONumber.
== Backstory ==
I was investigating an ICE (segfault accessing a DenseMap item). This failure happened non-deterministically, with no apparent reason and only on a Windows build of LLVM (from October 2018).
After looking into the crashes (multiple core files) and running DynamoRio, the cores and DynamoRio (DR) log pointed to the same code in `GVN::performScalarPRE()`. The values in the map are unsigned integers, the keys are `llvm::BasicBlock*`. Our test case that triggered this warning and periodic crash is rather involved. But the problematic line looks to be:
GVN.cpp: Line 2197
```
if (BlockRPONumber[P] >= BlockRPONumber[CurrentBlock] &&
```
To test things out, I cooked up a patch that accessed the items in the map outside of the condition, by forcing a sequence point between accesses. DynamoRio stopped warning of the issue, and the test didn't seem to crash after 1000+ runs.
My investigation was on an older version of LLVM, (source from October this year). What it looks like was occurring is the following, and the assembly from the latest pull of llvm in December seems to confirm this might still be an issue; however, I have not witnessed the crash on more recent builds. Of course the asm in question is generated from the host compiler on that Windows box (not clang), but it hints that we might want to consider how we access the BlockRPONumber map in this conditional (line 2197, listed above). In any case, I don't think the host compiler is wrong, rather I think it is pointing out a possibly latent bug in llvm.
1) There is no sequence point for the `>=` operation.
2) A call to a `DenseMapBase::operator[]` can have the side effect of the map reallocating a larger store (more Buckets, via a call to `DenseMap::grow`).
3) It seems perfectly legal for a host compiler to generate assembly that stores the result of a call to `operator[]` on the stack (that's what my host compile of GVN.cpp is doing) . A second call to `operator[]` //might// encourage the map to 'grow' thus making any pointers to the map's store invalid. The `>=` compares the first and second values. If the first happens to be a pointer produced from operator[], it could be invalid when dereferenced at the time of comparison.
The assembly generated from the Window's host compiler does show the result of the first access to the map via `operator[]` produces a pointer to an unsigned int. And that pointer is being stored on the stack. If a second call to the map (which does occur) causes the map to grow, that address (on the stack) is now invalid.
Reviewers: t.p.northover, efriedma
Reviewed By: efriedma
Subscribers: efriedma, llvm-commits
Differential Revision: https://reviews.llvm.org/D55974
llvm-svn: 350880
2019-01-11 03:56:03 +08:00
|
|
|
InvalidBlockRPONumbers = true;
|
2008-10-11 00:25:50 +08:00
|
|
|
}
|
2008-12-23 05:36:08 +08:00
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// Verify that the specified instruction does not occur in our
|
2008-12-23 05:36:08 +08:00
|
|
|
/// internal data structures.
|
2008-12-23 06:28:56 +08:00
|
|
|
void GVN::verifyRemoved(const Instruction *Inst) const {
|
|
|
|
VN.verifyRemoved(Inst);
|
2008-12-23 06:14:07 +08:00
|
|
|
|
2008-12-23 06:28:56 +08:00
|
|
|
// Walk through the value number scope to make sure the instruction isn't
|
|
|
|
// ferreted away in it.
|
2011-01-05 03:13:25 +08:00
|
|
|
for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
|
2011-01-05 03:29:46 +08:00
|
|
|
I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
|
2011-01-05 03:13:25 +08:00
|
|
|
const LeaderTableEntry *Node = &I->second;
|
2010-12-22 07:54:34 +08:00
|
|
|
assert(Node->Val != Inst && "Inst still in value numbering scope!");
|
2012-07-24 18:51:42 +08:00
|
|
|
|
2010-12-22 07:54:34 +08:00
|
|
|
while (Node->Next) {
|
|
|
|
Node = Node->Next;
|
|
|
|
assert(Node->Val != Inst && "Inst still in value numbering scope!");
|
2008-12-23 06:14:07 +08:00
|
|
|
}
|
|
|
|
}
|
2008-12-23 05:36:08 +08:00
|
|
|
}
|
2013-11-12 06:00:23 +08:00
|
|
|
|
2015-02-25 06:43:06 +08:00
|
|
|
/// BB is declared dead, which implied other blocks become dead as well. This
|
|
|
|
/// function is to add all these blocks to "DeadBlocks". For the dead blocks'
|
|
|
|
/// live successors, update their phi nodes by replacing the operands
|
|
|
|
/// corresponding to dead blocks with UndefVal.
|
2013-11-12 06:00:23 +08:00
|
|
|
void GVN::addDeadBlock(BasicBlock *BB) {
|
|
|
|
SmallVector<BasicBlock *, 4> NewDead;
|
|
|
|
SmallSetVector<BasicBlock *, 4> DF;
|
|
|
|
|
|
|
|
NewDead.push_back(BB);
|
|
|
|
while (!NewDead.empty()) {
|
|
|
|
BasicBlock *D = NewDead.pop_back_val();
|
|
|
|
if (DeadBlocks.count(D))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// All blocks dominated by D are dead.
|
|
|
|
SmallVector<BasicBlock *, 8> Dom;
|
|
|
|
DT->getDescendants(D, Dom);
|
|
|
|
DeadBlocks.insert(Dom.begin(), Dom.end());
|
2016-04-29 00:00:15 +08:00
|
|
|
|
2013-11-12 06:00:23 +08:00
|
|
|
// Figure out the dominance-frontier(D).
|
2015-11-28 16:23:04 +08:00
|
|
|
for (BasicBlock *B : Dom) {
|
|
|
|
for (BasicBlock *S : successors(B)) {
|
2013-11-12 06:00:23 +08:00
|
|
|
if (DeadBlocks.count(S))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
bool AllPredDead = true;
|
2015-11-28 16:23:04 +08:00
|
|
|
for (BasicBlock *P : predecessors(S))
|
|
|
|
if (!DeadBlocks.count(P)) {
|
2013-11-12 06:00:23 +08:00
|
|
|
AllPredDead = false;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!AllPredDead) {
|
|
|
|
// S could be proved dead later on. That is why we don't update phi
|
|
|
|
// operands at this moment.
|
|
|
|
DF.insert(S);
|
|
|
|
} else {
|
|
|
|
// While S is not dominated by D, it is dead by now. This could take
|
|
|
|
// place if S already have a dead predecessor before D is declared
|
|
|
|
// dead.
|
|
|
|
NewDead.push_back(S);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// For the dead blocks' live successors, update their phi nodes by replacing
|
|
|
|
// the operands corresponding to dead blocks with UndefVal.
|
|
|
|
for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
|
|
|
|
I != E; I++) {
|
|
|
|
BasicBlock *B = *I;
|
|
|
|
if (DeadBlocks.count(B))
|
|
|
|
continue;
|
|
|
|
|
2013-11-12 16:33:03 +08:00
|
|
|
SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
|
2015-11-28 16:23:04 +08:00
|
|
|
for (BasicBlock *P : Preds) {
|
2013-11-12 06:00:23 +08:00
|
|
|
if (!DeadBlocks.count(P))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
|
|
|
|
if (BasicBlock *S = splitCriticalEdges(P, B))
|
|
|
|
DeadBlocks.insert(P = S);
|
|
|
|
}
|
|
|
|
|
|
|
|
for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); ++II) {
|
|
|
|
PHINode &Phi = cast<PHINode>(*II);
|
|
|
|
Phi.setIncomingValue(Phi.getBasicBlockIndex(P),
|
|
|
|
UndefValue::get(Phi.getType()));
|
2018-08-23 20:48:17 +08:00
|
|
|
if (MD)
|
|
|
|
MD->invalidateCachedPointerInfo(&Phi);
|
2013-11-12 06:00:23 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the given branch is recognized as a foldable branch (i.e. conditional
|
|
|
|
// branch with constant condition), it will perform following analyses and
|
|
|
|
// transformation.
|
2016-04-29 00:00:15 +08:00
|
|
|
// 1) If the dead out-coming edge is a critical-edge, split it. Let
|
2013-11-12 06:00:23 +08:00
|
|
|
// R be the target of the dead out-coming edge.
|
|
|
|
// 1) Identify the set of dead blocks implied by the branch's dead outcoming
|
|
|
|
// edge. The result of this step will be {X| X is dominated by R}
|
2015-08-09 02:27:36 +08:00
|
|
|
// 2) Identify those blocks which haves at least one dead predecessor. The
|
2013-11-12 06:00:23 +08:00
|
|
|
// result of this step will be dominance-frontier(R).
|
2016-04-29 00:00:15 +08:00
|
|
|
// 3) Update the PHIs in DF(R) by replacing the operands corresponding to
|
2013-11-12 06:00:23 +08:00
|
|
|
// dead blocks with "UndefVal" in an hope these PHIs will optimized away.
|
|
|
|
//
|
|
|
|
// Return true iff *NEW* dead code are found.
|
|
|
|
bool GVN::processFoldableCondBr(BranchInst *BI) {
|
|
|
|
if (!BI || BI->isUnconditional())
|
|
|
|
return false;
|
|
|
|
|
2015-06-26 02:32:02 +08:00
|
|
|
// If a branch has two identical successors, we cannot declare either dead.
|
|
|
|
if (BI->getSuccessor(0) == BI->getSuccessor(1))
|
|
|
|
return false;
|
|
|
|
|
2013-11-12 06:00:23 +08:00
|
|
|
ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
|
|
|
|
if (!Cond)
|
|
|
|
return false;
|
|
|
|
|
2016-04-29 00:00:15 +08:00
|
|
|
BasicBlock *DeadRoot =
|
|
|
|
Cond->getZExtValue() ? BI->getSuccessor(1) : BI->getSuccessor(0);
|
2013-11-12 06:00:23 +08:00
|
|
|
if (DeadBlocks.count(DeadRoot))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
if (!DeadRoot->getSinglePredecessor())
|
|
|
|
DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
|
|
|
|
|
|
|
|
addDeadBlock(DeadRoot);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2014-08-06 07:27:34 +08:00
|
|
|
// performPRE() will trigger assert if it comes across an instruction without
|
2013-11-12 06:00:23 +08:00
|
|
|
// associated val-num. As it normally has far more live instructions than dead
|
|
|
|
// instructions, it makes more sense just to "fabricate" a val-number for the
|
|
|
|
// dead code than checking if instruction involved is dead or not.
|
|
|
|
void GVN::assignValNumForDeadCode() {
|
2015-11-28 16:23:04 +08:00
|
|
|
for (BasicBlock *BB : DeadBlocks) {
|
|
|
|
for (Instruction &Inst : *BB) {
|
2016-04-29 00:00:15 +08:00
|
|
|
unsigned ValNum = VN.lookupOrAdd(&Inst);
|
2015-11-28 16:23:04 +08:00
|
|
|
addToLeaderTable(ValNum, &Inst, BB);
|
2013-11-12 06:00:23 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-03-11 16:50:55 +08:00
|
|
|
|
|
|
|
class llvm::gvn::GVNLegacyPass : public FunctionPass {
|
|
|
|
public:
|
|
|
|
static char ID; // Pass identification, replacement for typeid
|
2017-09-14 05:43:53 +08:00
|
|
|
|
2018-08-22 03:11:27 +08:00
|
|
|
explicit GVNLegacyPass(bool NoMemDepAnalysis = !EnableMemDep)
|
|
|
|
: FunctionPass(ID), NoMemDepAnalysis(NoMemDepAnalysis) {
|
2016-03-11 16:50:55 +08:00
|
|
|
initializeGVNLegacyPassPass(*PassRegistry::getPassRegistry());
|
|
|
|
}
|
|
|
|
|
|
|
|
bool runOnFunction(Function &F) override {
|
2016-04-23 06:06:11 +08:00
|
|
|
if (skipFunction(F))
|
2016-03-11 16:50:55 +08:00
|
|
|
return false;
|
|
|
|
|
2016-12-01 11:56:43 +08:00
|
|
|
auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
|
|
|
|
|
2016-03-11 16:50:55 +08:00
|
|
|
return Impl.runImpl(
|
2016-12-19 16:22:17 +08:00
|
|
|
F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
|
|
|
|
getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
|
2016-03-11 16:50:55 +08:00
|
|
|
getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
|
|
|
|
getAnalysis<AAResultsWrapperPass>().getAAResults(),
|
2018-08-22 03:11:27 +08:00
|
|
|
NoMemDepAnalysis ? nullptr
|
2016-12-01 11:56:43 +08:00
|
|
|
: &getAnalysis<MemoryDependenceWrapperPass>().getMemDep(),
|
2016-12-02 00:40:32 +08:00
|
|
|
LIWP ? &LIWP->getLoopInfo() : nullptr,
|
|
|
|
&getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE());
|
2016-03-11 16:50:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override {
|
2016-12-19 16:22:17 +08:00
|
|
|
AU.addRequired<AssumptionCacheTracker>();
|
2016-03-11 16:50:55 +08:00
|
|
|
AU.addRequired<DominatorTreeWrapperPass>();
|
|
|
|
AU.addRequired<TargetLibraryInfoWrapperPass>();
|
2018-08-22 03:11:27 +08:00
|
|
|
if (!NoMemDepAnalysis)
|
2016-03-11 16:50:55 +08:00
|
|
|
AU.addRequired<MemoryDependenceWrapperPass>();
|
|
|
|
AU.addRequired<AAResultsWrapperPass>();
|
|
|
|
|
|
|
|
AU.addPreserved<DominatorTreeWrapperPass>();
|
|
|
|
AU.addPreserved<GlobalsAAWrapperPass>();
|
2017-02-01 05:53:18 +08:00
|
|
|
AU.addPreserved<TargetLibraryInfoWrapperPass>();
|
2016-12-02 00:40:32 +08:00
|
|
|
AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
|
2016-03-11 16:50:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2018-08-22 03:11:27 +08:00
|
|
|
bool NoMemDepAnalysis;
|
2016-03-11 16:50:55 +08:00
|
|
|
GVN Impl;
|
|
|
|
};
|
|
|
|
|
|
|
|
char GVNLegacyPass::ID = 0;
|
|
|
|
|
|
|
|
INITIALIZE_PASS_BEGIN(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
|
2016-12-19 16:22:17 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
|
2016-03-11 16:50:55 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
|
2016-12-02 00:40:32 +08:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
|
2016-03-11 16:50:55 +08:00
|
|
|
INITIALIZE_PASS_END(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
|
2017-09-14 05:43:53 +08:00
|
|
|
|
|
|
|
// The public interface to this file...
|
2018-08-22 03:11:27 +08:00
|
|
|
FunctionPass *llvm::createGVNPass(bool NoMemDepAnalysis) {
|
|
|
|
return new GVNLegacyPass(NoMemDepAnalysis);
|
2017-09-14 05:43:53 +08:00
|
|
|
}
|