1*9880d681SAndroid Build Coastguard Worker //===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
2*9880d681SAndroid Build Coastguard Worker //
3*9880d681SAndroid Build Coastguard Worker // The LLVM Compiler Infrastructure
4*9880d681SAndroid Build Coastguard Worker //
5*9880d681SAndroid Build Coastguard Worker // This file is distributed under the University of Illinois Open Source
6*9880d681SAndroid Build Coastguard Worker // License. See LICENSE.TXT for details.
7*9880d681SAndroid Build Coastguard Worker //
8*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
9*9880d681SAndroid Build Coastguard Worker //
10*9880d681SAndroid Build Coastguard Worker // This pass performs global value numbering to eliminate fully redundant
11*9880d681SAndroid Build Coastguard Worker // instructions. It also performs simple dead load elimination.
12*9880d681SAndroid Build Coastguard Worker //
13*9880d681SAndroid Build Coastguard Worker // Note that this pass does the value numbering itself; it does not use the
14*9880d681SAndroid Build Coastguard Worker // ValueNumbering analysis passes.
15*9880d681SAndroid Build Coastguard Worker //
16*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
17*9880d681SAndroid Build Coastguard Worker
18*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Scalar/GVN.h"
19*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DenseMap.h"
20*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/DepthFirstIterator.h"
21*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Hashing.h"
22*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/MapVector.h"
23*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/PostOrderIterator.h"
24*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SetVector.h"
25*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/SmallPtrSet.h"
26*9880d681SAndroid Build Coastguard Worker #include "llvm/ADT/Statistic.h"
27*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AliasAnalysis.h"
28*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/AssumptionCache.h"
29*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/CFG.h"
30*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ConstantFolding.h"
31*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/GlobalsModRef.h"
32*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/InstructionSimplify.h"
33*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/Loads.h"
34*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/MemoryBuiltins.h"
35*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/MemoryDependenceAnalysis.h"
36*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/PHITransAddr.h"
37*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/TargetLibraryInfo.h"
38*9880d681SAndroid Build Coastguard Worker #include "llvm/Analysis/ValueTracking.h"
39*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/DataLayout.h"
40*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Dominators.h"
41*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/GlobalVariable.h"
42*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IRBuilder.h"
43*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/IntrinsicInst.h"
44*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/LLVMContext.h"
45*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/Metadata.h"
46*9880d681SAndroid Build Coastguard Worker #include "llvm/IR/PatternMatch.h"
47*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/CommandLine.h"
48*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/Debug.h"
49*9880d681SAndroid Build Coastguard Worker #include "llvm/Support/raw_ostream.h"
50*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/BasicBlockUtils.h"
51*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/Local.h"
52*9880d681SAndroid Build Coastguard Worker #include "llvm/Transforms/Utils/SSAUpdater.h"
53*9880d681SAndroid Build Coastguard Worker #include <vector>
54*9880d681SAndroid Build Coastguard Worker using namespace llvm;
55*9880d681SAndroid Build Coastguard Worker using namespace llvm::gvn;
56*9880d681SAndroid Build Coastguard Worker using namespace PatternMatch;
57*9880d681SAndroid Build Coastguard Worker
58*9880d681SAndroid Build Coastguard Worker #define DEBUG_TYPE "gvn"
59*9880d681SAndroid Build Coastguard Worker
60*9880d681SAndroid Build Coastguard Worker STATISTIC(NumGVNInstr, "Number of instructions deleted");
61*9880d681SAndroid Build Coastguard Worker STATISTIC(NumGVNLoad, "Number of loads deleted");
62*9880d681SAndroid Build Coastguard Worker STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
63*9880d681SAndroid Build Coastguard Worker STATISTIC(NumGVNBlocks, "Number of blocks merged");
64*9880d681SAndroid Build Coastguard Worker STATISTIC(NumGVNSimpl, "Number of instructions simplified");
65*9880d681SAndroid Build Coastguard Worker STATISTIC(NumGVNEqProp, "Number of equalities propagated");
66*9880d681SAndroid Build Coastguard Worker STATISTIC(NumPRELoad, "Number of loads PRE'd");
67*9880d681SAndroid Build Coastguard Worker
68*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> EnablePRE("enable-pre",
69*9880d681SAndroid Build Coastguard Worker cl::init(true), cl::Hidden);
70*9880d681SAndroid Build Coastguard Worker static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
71*9880d681SAndroid Build Coastguard Worker
72*9880d681SAndroid Build Coastguard Worker // Maximum allowed recursion depth.
73*9880d681SAndroid Build Coastguard Worker static cl::opt<uint32_t>
74*9880d681SAndroid Build Coastguard Worker MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
75*9880d681SAndroid Build Coastguard Worker cl::desc("Max recurse depth (default = 1000)"));
76*9880d681SAndroid Build Coastguard Worker
77*9880d681SAndroid Build Coastguard Worker struct llvm::GVN::Expression {
78*9880d681SAndroid Build Coastguard Worker uint32_t opcode;
79*9880d681SAndroid Build Coastguard Worker Type *type;
80*9880d681SAndroid Build Coastguard Worker SmallVector<uint32_t, 4> varargs;
81*9880d681SAndroid Build Coastguard Worker
Expressionllvm::GVN::Expression82*9880d681SAndroid Build Coastguard Worker Expression(uint32_t o = ~2U) : opcode(o) {}
83*9880d681SAndroid Build Coastguard Worker
operator ==llvm::GVN::Expression84*9880d681SAndroid Build Coastguard Worker bool operator==(const Expression &other) const {
85*9880d681SAndroid Build Coastguard Worker if (opcode != other.opcode)
86*9880d681SAndroid Build Coastguard Worker return false;
87*9880d681SAndroid Build Coastguard Worker if (opcode == ~0U || opcode == ~1U)
88*9880d681SAndroid Build Coastguard Worker return true;
89*9880d681SAndroid Build Coastguard Worker if (type != other.type)
90*9880d681SAndroid Build Coastguard Worker return false;
91*9880d681SAndroid Build Coastguard Worker if (varargs != other.varargs)
92*9880d681SAndroid Build Coastguard Worker return false;
93*9880d681SAndroid Build Coastguard Worker return true;
94*9880d681SAndroid Build Coastguard Worker }
95*9880d681SAndroid Build Coastguard Worker
hash_value(const Expression & Value)96*9880d681SAndroid Build Coastguard Worker friend hash_code hash_value(const Expression &Value) {
97*9880d681SAndroid Build Coastguard Worker return hash_combine(
98*9880d681SAndroid Build Coastguard Worker Value.opcode, Value.type,
99*9880d681SAndroid Build Coastguard Worker hash_combine_range(Value.varargs.begin(), Value.varargs.end()));
100*9880d681SAndroid Build Coastguard Worker }
101*9880d681SAndroid Build Coastguard Worker };
102*9880d681SAndroid Build Coastguard Worker
103*9880d681SAndroid Build Coastguard Worker namespace llvm {
104*9880d681SAndroid Build Coastguard Worker template <> struct DenseMapInfo<GVN::Expression> {
getEmptyKeyllvm::DenseMapInfo105*9880d681SAndroid Build Coastguard Worker static inline GVN::Expression getEmptyKey() { return ~0U; }
106*9880d681SAndroid Build Coastguard Worker
getTombstoneKeyllvm::DenseMapInfo107*9880d681SAndroid Build Coastguard Worker static inline GVN::Expression getTombstoneKey() { return ~1U; }
108*9880d681SAndroid Build Coastguard Worker
getHashValuellvm::DenseMapInfo109*9880d681SAndroid Build Coastguard Worker static unsigned getHashValue(const GVN::Expression &e) {
110*9880d681SAndroid Build Coastguard Worker using llvm::hash_value;
111*9880d681SAndroid Build Coastguard Worker return static_cast<unsigned>(hash_value(e));
112*9880d681SAndroid Build Coastguard Worker }
isEqualllvm::DenseMapInfo113*9880d681SAndroid Build Coastguard Worker static bool isEqual(const GVN::Expression &LHS, const GVN::Expression &RHS) {
114*9880d681SAndroid Build Coastguard Worker return LHS == RHS;
115*9880d681SAndroid Build Coastguard Worker }
116*9880d681SAndroid Build Coastguard Worker };
117*9880d681SAndroid Build Coastguard Worker } // End llvm namespace.
118*9880d681SAndroid Build Coastguard Worker
119*9880d681SAndroid Build Coastguard Worker /// Represents a particular available value that we know how to materialize.
120*9880d681SAndroid Build Coastguard Worker /// Materialization of an AvailableValue never fails. An AvailableValue is
121*9880d681SAndroid Build Coastguard Worker /// implicitly associated with a rematerialization point which is the
122*9880d681SAndroid Build Coastguard Worker /// location of the instruction from which it was formed.
123*9880d681SAndroid Build Coastguard Worker struct llvm::gvn::AvailableValue {
124*9880d681SAndroid Build Coastguard Worker enum ValType {
125*9880d681SAndroid Build Coastguard Worker SimpleVal, // A simple offsetted value that is accessed.
126*9880d681SAndroid Build Coastguard Worker LoadVal, // A value produced by a load.
127*9880d681SAndroid Build Coastguard Worker MemIntrin, // A memory intrinsic which is loaded from.
128*9880d681SAndroid Build Coastguard Worker UndefVal // A UndefValue representing a value from dead block (which
129*9880d681SAndroid Build Coastguard Worker // is not yet physically removed from the CFG).
130*9880d681SAndroid Build Coastguard Worker };
131*9880d681SAndroid Build Coastguard Worker
132*9880d681SAndroid Build Coastguard Worker /// V - The value that is live out of the block.
133*9880d681SAndroid Build Coastguard Worker PointerIntPair<Value *, 2, ValType> Val;
134*9880d681SAndroid Build Coastguard Worker
135*9880d681SAndroid Build Coastguard Worker /// Offset - The byte offset in Val that is interesting for the load query.
136*9880d681SAndroid Build Coastguard Worker unsigned Offset;
137*9880d681SAndroid Build Coastguard Worker
getllvm::gvn::AvailableValue138*9880d681SAndroid Build Coastguard Worker static AvailableValue get(Value *V, unsigned Offset = 0) {
139*9880d681SAndroid Build Coastguard Worker AvailableValue Res;
140*9880d681SAndroid Build Coastguard Worker Res.Val.setPointer(V);
141*9880d681SAndroid Build Coastguard Worker Res.Val.setInt(SimpleVal);
142*9880d681SAndroid Build Coastguard Worker Res.Offset = Offset;
143*9880d681SAndroid Build Coastguard Worker return Res;
144*9880d681SAndroid Build Coastguard Worker }
145*9880d681SAndroid Build Coastguard Worker
getMIllvm::gvn::AvailableValue146*9880d681SAndroid Build Coastguard Worker static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset = 0) {
147*9880d681SAndroid Build Coastguard Worker AvailableValue Res;
148*9880d681SAndroid Build Coastguard Worker Res.Val.setPointer(MI);
149*9880d681SAndroid Build Coastguard Worker Res.Val.setInt(MemIntrin);
150*9880d681SAndroid Build Coastguard Worker Res.Offset = Offset;
151*9880d681SAndroid Build Coastguard Worker return Res;
152*9880d681SAndroid Build Coastguard Worker }
153*9880d681SAndroid Build Coastguard Worker
getLoadllvm::gvn::AvailableValue154*9880d681SAndroid Build Coastguard Worker static AvailableValue getLoad(LoadInst *LI, unsigned Offset = 0) {
155*9880d681SAndroid Build Coastguard Worker AvailableValue Res;
156*9880d681SAndroid Build Coastguard Worker Res.Val.setPointer(LI);
157*9880d681SAndroid Build Coastguard Worker Res.Val.setInt(LoadVal);
158*9880d681SAndroid Build Coastguard Worker Res.Offset = Offset;
159*9880d681SAndroid Build Coastguard Worker return Res;
160*9880d681SAndroid Build Coastguard Worker }
161*9880d681SAndroid Build Coastguard Worker
getUndefllvm::gvn::AvailableValue162*9880d681SAndroid Build Coastguard Worker static AvailableValue getUndef() {
163*9880d681SAndroid Build Coastguard Worker AvailableValue Res;
164*9880d681SAndroid Build Coastguard Worker Res.Val.setPointer(nullptr);
165*9880d681SAndroid Build Coastguard Worker Res.Val.setInt(UndefVal);
166*9880d681SAndroid Build Coastguard Worker Res.Offset = 0;
167*9880d681SAndroid Build Coastguard Worker return Res;
168*9880d681SAndroid Build Coastguard Worker }
169*9880d681SAndroid Build Coastguard Worker
isSimpleValuellvm::gvn::AvailableValue170*9880d681SAndroid Build Coastguard Worker bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
isCoercedLoadValuellvm::gvn::AvailableValue171*9880d681SAndroid Build Coastguard Worker bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
isMemIntrinValuellvm::gvn::AvailableValue172*9880d681SAndroid Build Coastguard Worker bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
isUndefValuellvm::gvn::AvailableValue173*9880d681SAndroid Build Coastguard Worker bool isUndefValue() const { return Val.getInt() == UndefVal; }
174*9880d681SAndroid Build Coastguard Worker
getSimpleValuellvm::gvn::AvailableValue175*9880d681SAndroid Build Coastguard Worker Value *getSimpleValue() const {
176*9880d681SAndroid Build Coastguard Worker assert(isSimpleValue() && "Wrong accessor");
177*9880d681SAndroid Build Coastguard Worker return Val.getPointer();
178*9880d681SAndroid Build Coastguard Worker }
179*9880d681SAndroid Build Coastguard Worker
getCoercedLoadValuellvm::gvn::AvailableValue180*9880d681SAndroid Build Coastguard Worker LoadInst *getCoercedLoadValue() const {
181*9880d681SAndroid Build Coastguard Worker assert(isCoercedLoadValue() && "Wrong accessor");
182*9880d681SAndroid Build Coastguard Worker return cast<LoadInst>(Val.getPointer());
183*9880d681SAndroid Build Coastguard Worker }
184*9880d681SAndroid Build Coastguard Worker
getMemIntrinValuellvm::gvn::AvailableValue185*9880d681SAndroid Build Coastguard Worker MemIntrinsic *getMemIntrinValue() const {
186*9880d681SAndroid Build Coastguard Worker assert(isMemIntrinValue() && "Wrong accessor");
187*9880d681SAndroid Build Coastguard Worker return cast<MemIntrinsic>(Val.getPointer());
188*9880d681SAndroid Build Coastguard Worker }
189*9880d681SAndroid Build Coastguard Worker
190*9880d681SAndroid Build Coastguard Worker /// Emit code at the specified insertion point to adjust the value defined
191*9880d681SAndroid Build Coastguard Worker /// here to the specified type. This handles various coercion cases.
192*9880d681SAndroid Build Coastguard Worker Value *MaterializeAdjustedValue(LoadInst *LI, Instruction *InsertPt,
193*9880d681SAndroid Build Coastguard Worker GVN &gvn) const;
194*9880d681SAndroid Build Coastguard Worker };
195*9880d681SAndroid Build Coastguard Worker
196*9880d681SAndroid Build Coastguard Worker /// Represents an AvailableValue which can be rematerialized at the end of
197*9880d681SAndroid Build Coastguard Worker /// the associated BasicBlock.
198*9880d681SAndroid Build Coastguard Worker struct llvm::gvn::AvailableValueInBlock {
199*9880d681SAndroid Build Coastguard Worker /// BB - The basic block in question.
200*9880d681SAndroid Build Coastguard Worker BasicBlock *BB;
201*9880d681SAndroid Build Coastguard Worker
202*9880d681SAndroid Build Coastguard Worker /// AV - The actual available value
203*9880d681SAndroid Build Coastguard Worker AvailableValue AV;
204*9880d681SAndroid Build Coastguard Worker
getllvm::gvn::AvailableValueInBlock205*9880d681SAndroid Build Coastguard Worker static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV) {
206*9880d681SAndroid Build Coastguard Worker AvailableValueInBlock Res;
207*9880d681SAndroid Build Coastguard Worker Res.BB = BB;
208*9880d681SAndroid Build Coastguard Worker Res.AV = std::move(AV);
209*9880d681SAndroid Build Coastguard Worker return Res;
210*9880d681SAndroid Build Coastguard Worker }
211*9880d681SAndroid Build Coastguard Worker
getllvm::gvn::AvailableValueInBlock212*9880d681SAndroid Build Coastguard Worker static AvailableValueInBlock get(BasicBlock *BB, Value *V,
213*9880d681SAndroid Build Coastguard Worker unsigned Offset = 0) {
214*9880d681SAndroid Build Coastguard Worker return get(BB, AvailableValue::get(V, Offset));
215*9880d681SAndroid Build Coastguard Worker }
getUndefllvm::gvn::AvailableValueInBlock216*9880d681SAndroid Build Coastguard Worker static AvailableValueInBlock getUndef(BasicBlock *BB) {
217*9880d681SAndroid Build Coastguard Worker return get(BB, AvailableValue::getUndef());
218*9880d681SAndroid Build Coastguard Worker }
219*9880d681SAndroid Build Coastguard Worker
220*9880d681SAndroid Build Coastguard Worker /// Emit code at the end of this block to adjust the value defined here to
221*9880d681SAndroid Build Coastguard Worker /// the specified type. This handles various coercion cases.
MaterializeAdjustedValuellvm::gvn::AvailableValueInBlock222*9880d681SAndroid Build Coastguard Worker Value *MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const {
223*9880d681SAndroid Build Coastguard Worker return AV.MaterializeAdjustedValue(LI, BB->getTerminator(), gvn);
224*9880d681SAndroid Build Coastguard Worker }
225*9880d681SAndroid Build Coastguard Worker };
226*9880d681SAndroid Build Coastguard Worker
227*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
228*9880d681SAndroid Build Coastguard Worker // ValueTable Internal Functions
229*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
230*9880d681SAndroid Build Coastguard Worker
createExpr(Instruction * I)231*9880d681SAndroid Build Coastguard Worker GVN::Expression GVN::ValueTable::createExpr(Instruction *I) {
232*9880d681SAndroid Build Coastguard Worker Expression e;
233*9880d681SAndroid Build Coastguard Worker e.type = I->getType();
234*9880d681SAndroid Build Coastguard Worker e.opcode = I->getOpcode();
235*9880d681SAndroid Build Coastguard Worker for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
236*9880d681SAndroid Build Coastguard Worker OI != OE; ++OI)
237*9880d681SAndroid Build Coastguard Worker e.varargs.push_back(lookupOrAdd(*OI));
238*9880d681SAndroid Build Coastguard Worker if (I->isCommutative()) {
239*9880d681SAndroid Build Coastguard Worker // Ensure that commutative instructions that only differ by a permutation
240*9880d681SAndroid Build Coastguard Worker // of their operands get the same value number by sorting the operand value
241*9880d681SAndroid Build Coastguard Worker // numbers. Since all commutative instructions have two operands it is more
242*9880d681SAndroid Build Coastguard Worker // efficient to sort by hand rather than using, say, std::sort.
243*9880d681SAndroid Build Coastguard Worker assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
244*9880d681SAndroid Build Coastguard Worker if (e.varargs[0] > e.varargs[1])
245*9880d681SAndroid Build Coastguard Worker std::swap(e.varargs[0], e.varargs[1]);
246*9880d681SAndroid Build Coastguard Worker }
247*9880d681SAndroid Build Coastguard Worker
248*9880d681SAndroid Build Coastguard Worker if (CmpInst *C = dyn_cast<CmpInst>(I)) {
249*9880d681SAndroid Build Coastguard Worker // Sort the operand value numbers so x<y and y>x get the same value number.
250*9880d681SAndroid Build Coastguard Worker CmpInst::Predicate Predicate = C->getPredicate();
251*9880d681SAndroid Build Coastguard Worker if (e.varargs[0] > e.varargs[1]) {
252*9880d681SAndroid Build Coastguard Worker std::swap(e.varargs[0], e.varargs[1]);
253*9880d681SAndroid Build Coastguard Worker Predicate = CmpInst::getSwappedPredicate(Predicate);
254*9880d681SAndroid Build Coastguard Worker }
255*9880d681SAndroid Build Coastguard Worker e.opcode = (C->getOpcode() << 8) | Predicate;
256*9880d681SAndroid Build Coastguard Worker } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
257*9880d681SAndroid Build Coastguard Worker for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
258*9880d681SAndroid Build Coastguard Worker II != IE; ++II)
259*9880d681SAndroid Build Coastguard Worker e.varargs.push_back(*II);
260*9880d681SAndroid Build Coastguard Worker }
261*9880d681SAndroid Build Coastguard Worker
262*9880d681SAndroid Build Coastguard Worker return e;
263*9880d681SAndroid Build Coastguard Worker }
264*9880d681SAndroid Build Coastguard Worker
createCmpExpr(unsigned Opcode,CmpInst::Predicate Predicate,Value * LHS,Value * RHS)265*9880d681SAndroid Build Coastguard Worker GVN::Expression GVN::ValueTable::createCmpExpr(unsigned Opcode,
266*9880d681SAndroid Build Coastguard Worker CmpInst::Predicate Predicate,
267*9880d681SAndroid Build Coastguard Worker Value *LHS, Value *RHS) {
268*9880d681SAndroid Build Coastguard Worker assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
269*9880d681SAndroid Build Coastguard Worker "Not a comparison!");
270*9880d681SAndroid Build Coastguard Worker Expression e;
271*9880d681SAndroid Build Coastguard Worker e.type = CmpInst::makeCmpResultType(LHS->getType());
272*9880d681SAndroid Build Coastguard Worker e.varargs.push_back(lookupOrAdd(LHS));
273*9880d681SAndroid Build Coastguard Worker e.varargs.push_back(lookupOrAdd(RHS));
274*9880d681SAndroid Build Coastguard Worker
275*9880d681SAndroid Build Coastguard Worker // Sort the operand value numbers so x<y and y>x get the same value number.
276*9880d681SAndroid Build Coastguard Worker if (e.varargs[0] > e.varargs[1]) {
277*9880d681SAndroid Build Coastguard Worker std::swap(e.varargs[0], e.varargs[1]);
278*9880d681SAndroid Build Coastguard Worker Predicate = CmpInst::getSwappedPredicate(Predicate);
279*9880d681SAndroid Build Coastguard Worker }
280*9880d681SAndroid Build Coastguard Worker e.opcode = (Opcode << 8) | Predicate;
281*9880d681SAndroid Build Coastguard Worker return e;
282*9880d681SAndroid Build Coastguard Worker }
283*9880d681SAndroid Build Coastguard Worker
createExtractvalueExpr(ExtractValueInst * EI)284*9880d681SAndroid Build Coastguard Worker GVN::Expression GVN::ValueTable::createExtractvalueExpr(ExtractValueInst *EI) {
285*9880d681SAndroid Build Coastguard Worker assert(EI && "Not an ExtractValueInst?");
286*9880d681SAndroid Build Coastguard Worker Expression e;
287*9880d681SAndroid Build Coastguard Worker e.type = EI->getType();
288*9880d681SAndroid Build Coastguard Worker e.opcode = 0;
289*9880d681SAndroid Build Coastguard Worker
290*9880d681SAndroid Build Coastguard Worker IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
291*9880d681SAndroid Build Coastguard Worker if (I != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
292*9880d681SAndroid Build Coastguard Worker // EI might be an extract from one of our recognised intrinsics. If it
293*9880d681SAndroid Build Coastguard Worker // is we'll synthesize a semantically equivalent expression instead on
294*9880d681SAndroid Build Coastguard Worker // an extract value expression.
295*9880d681SAndroid Build Coastguard Worker switch (I->getIntrinsicID()) {
296*9880d681SAndroid Build Coastguard Worker case Intrinsic::sadd_with_overflow:
297*9880d681SAndroid Build Coastguard Worker case Intrinsic::uadd_with_overflow:
298*9880d681SAndroid Build Coastguard Worker e.opcode = Instruction::Add;
299*9880d681SAndroid Build Coastguard Worker break;
300*9880d681SAndroid Build Coastguard Worker case Intrinsic::ssub_with_overflow:
301*9880d681SAndroid Build Coastguard Worker case Intrinsic::usub_with_overflow:
302*9880d681SAndroid Build Coastguard Worker e.opcode = Instruction::Sub;
303*9880d681SAndroid Build Coastguard Worker break;
304*9880d681SAndroid Build Coastguard Worker case Intrinsic::smul_with_overflow:
305*9880d681SAndroid Build Coastguard Worker case Intrinsic::umul_with_overflow:
306*9880d681SAndroid Build Coastguard Worker e.opcode = Instruction::Mul;
307*9880d681SAndroid Build Coastguard Worker break;
308*9880d681SAndroid Build Coastguard Worker default:
309*9880d681SAndroid Build Coastguard Worker break;
310*9880d681SAndroid Build Coastguard Worker }
311*9880d681SAndroid Build Coastguard Worker
312*9880d681SAndroid Build Coastguard Worker if (e.opcode != 0) {
313*9880d681SAndroid Build Coastguard Worker // Intrinsic recognized. Grab its args to finish building the expression.
314*9880d681SAndroid Build Coastguard Worker assert(I->getNumArgOperands() == 2 &&
315*9880d681SAndroid Build Coastguard Worker "Expect two args for recognised intrinsics.");
316*9880d681SAndroid Build Coastguard Worker e.varargs.push_back(lookupOrAdd(I->getArgOperand(0)));
317*9880d681SAndroid Build Coastguard Worker e.varargs.push_back(lookupOrAdd(I->getArgOperand(1)));
318*9880d681SAndroid Build Coastguard Worker return e;
319*9880d681SAndroid Build Coastguard Worker }
320*9880d681SAndroid Build Coastguard Worker }
321*9880d681SAndroid Build Coastguard Worker
322*9880d681SAndroid Build Coastguard Worker // Not a recognised intrinsic. Fall back to producing an extract value
323*9880d681SAndroid Build Coastguard Worker // expression.
324*9880d681SAndroid Build Coastguard Worker e.opcode = EI->getOpcode();
325*9880d681SAndroid Build Coastguard Worker for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
326*9880d681SAndroid Build Coastguard Worker OI != OE; ++OI)
327*9880d681SAndroid Build Coastguard Worker e.varargs.push_back(lookupOrAdd(*OI));
328*9880d681SAndroid Build Coastguard Worker
329*9880d681SAndroid Build Coastguard Worker for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
330*9880d681SAndroid Build Coastguard Worker II != IE; ++II)
331*9880d681SAndroid Build Coastguard Worker e.varargs.push_back(*II);
332*9880d681SAndroid Build Coastguard Worker
333*9880d681SAndroid Build Coastguard Worker return e;
334*9880d681SAndroid Build Coastguard Worker }
335*9880d681SAndroid Build Coastguard Worker
336*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
337*9880d681SAndroid Build Coastguard Worker // ValueTable External Functions
338*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
339*9880d681SAndroid Build Coastguard Worker
ValueTable()340*9880d681SAndroid Build Coastguard Worker GVN::ValueTable::ValueTable() : nextValueNumber(1) {}
ValueTable(const ValueTable & Arg)341*9880d681SAndroid Build Coastguard Worker GVN::ValueTable::ValueTable(const ValueTable &Arg)
342*9880d681SAndroid Build Coastguard Worker : valueNumbering(Arg.valueNumbering),
343*9880d681SAndroid Build Coastguard Worker expressionNumbering(Arg.expressionNumbering), AA(Arg.AA), MD(Arg.MD),
344*9880d681SAndroid Build Coastguard Worker DT(Arg.DT), nextValueNumber(Arg.nextValueNumber) {}
ValueTable(ValueTable && Arg)345*9880d681SAndroid Build Coastguard Worker GVN::ValueTable::ValueTable(ValueTable &&Arg)
346*9880d681SAndroid Build Coastguard Worker : valueNumbering(std::move(Arg.valueNumbering)),
347*9880d681SAndroid Build Coastguard Worker expressionNumbering(std::move(Arg.expressionNumbering)),
348*9880d681SAndroid Build Coastguard Worker AA(std::move(Arg.AA)), MD(std::move(Arg.MD)), DT(std::move(Arg.DT)),
349*9880d681SAndroid Build Coastguard Worker nextValueNumber(std::move(Arg.nextValueNumber)) {}
~ValueTable()350*9880d681SAndroid Build Coastguard Worker GVN::ValueTable::~ValueTable() {}
351*9880d681SAndroid Build Coastguard Worker
352*9880d681SAndroid Build Coastguard Worker /// add - Insert a value into the table with a specified value number.
add(Value * V,uint32_t num)353*9880d681SAndroid Build Coastguard Worker void GVN::ValueTable::add(Value *V, uint32_t num) {
354*9880d681SAndroid Build Coastguard Worker valueNumbering.insert(std::make_pair(V, num));
355*9880d681SAndroid Build Coastguard Worker }
356*9880d681SAndroid Build Coastguard Worker
lookupOrAddCall(CallInst * C)357*9880d681SAndroid Build Coastguard Worker uint32_t GVN::ValueTable::lookupOrAddCall(CallInst *C) {
358*9880d681SAndroid Build Coastguard Worker if (AA->doesNotAccessMemory(C)) {
359*9880d681SAndroid Build Coastguard Worker Expression exp = createExpr(C);
360*9880d681SAndroid Build Coastguard Worker uint32_t &e = expressionNumbering[exp];
361*9880d681SAndroid Build Coastguard Worker if (!e) e = nextValueNumber++;
362*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = e;
363*9880d681SAndroid Build Coastguard Worker return e;
364*9880d681SAndroid Build Coastguard Worker } else if (AA->onlyReadsMemory(C)) {
365*9880d681SAndroid Build Coastguard Worker Expression exp = createExpr(C);
366*9880d681SAndroid Build Coastguard Worker uint32_t &e = expressionNumbering[exp];
367*9880d681SAndroid Build Coastguard Worker if (!e) {
368*9880d681SAndroid Build Coastguard Worker e = nextValueNumber++;
369*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = e;
370*9880d681SAndroid Build Coastguard Worker return e;
371*9880d681SAndroid Build Coastguard Worker }
372*9880d681SAndroid Build Coastguard Worker if (!MD) {
373*9880d681SAndroid Build Coastguard Worker e = nextValueNumber++;
374*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = e;
375*9880d681SAndroid Build Coastguard Worker return e;
376*9880d681SAndroid Build Coastguard Worker }
377*9880d681SAndroid Build Coastguard Worker
378*9880d681SAndroid Build Coastguard Worker MemDepResult local_dep = MD->getDependency(C);
379*9880d681SAndroid Build Coastguard Worker
380*9880d681SAndroid Build Coastguard Worker if (!local_dep.isDef() && !local_dep.isNonLocal()) {
381*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = nextValueNumber;
382*9880d681SAndroid Build Coastguard Worker return nextValueNumber++;
383*9880d681SAndroid Build Coastguard Worker }
384*9880d681SAndroid Build Coastguard Worker
385*9880d681SAndroid Build Coastguard Worker if (local_dep.isDef()) {
386*9880d681SAndroid Build Coastguard Worker CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
387*9880d681SAndroid Build Coastguard Worker
388*9880d681SAndroid Build Coastguard Worker if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
389*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = nextValueNumber;
390*9880d681SAndroid Build Coastguard Worker return nextValueNumber++;
391*9880d681SAndroid Build Coastguard Worker }
392*9880d681SAndroid Build Coastguard Worker
393*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
394*9880d681SAndroid Build Coastguard Worker uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
395*9880d681SAndroid Build Coastguard Worker uint32_t cd_vn = lookupOrAdd(local_cdep->getArgOperand(i));
396*9880d681SAndroid Build Coastguard Worker if (c_vn != cd_vn) {
397*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = nextValueNumber;
398*9880d681SAndroid Build Coastguard Worker return nextValueNumber++;
399*9880d681SAndroid Build Coastguard Worker }
400*9880d681SAndroid Build Coastguard Worker }
401*9880d681SAndroid Build Coastguard Worker
402*9880d681SAndroid Build Coastguard Worker uint32_t v = lookupOrAdd(local_cdep);
403*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = v;
404*9880d681SAndroid Build Coastguard Worker return v;
405*9880d681SAndroid Build Coastguard Worker }
406*9880d681SAndroid Build Coastguard Worker
407*9880d681SAndroid Build Coastguard Worker // Non-local case.
408*9880d681SAndroid Build Coastguard Worker const MemoryDependenceResults::NonLocalDepInfo &deps =
409*9880d681SAndroid Build Coastguard Worker MD->getNonLocalCallDependency(CallSite(C));
410*9880d681SAndroid Build Coastguard Worker // FIXME: Move the checking logic to MemDep!
411*9880d681SAndroid Build Coastguard Worker CallInst* cdep = nullptr;
412*9880d681SAndroid Build Coastguard Worker
413*9880d681SAndroid Build Coastguard Worker // Check to see if we have a single dominating call instruction that is
414*9880d681SAndroid Build Coastguard Worker // identical to C.
415*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = deps.size(); i != e; ++i) {
416*9880d681SAndroid Build Coastguard Worker const NonLocalDepEntry *I = &deps[i];
417*9880d681SAndroid Build Coastguard Worker if (I->getResult().isNonLocal())
418*9880d681SAndroid Build Coastguard Worker continue;
419*9880d681SAndroid Build Coastguard Worker
420*9880d681SAndroid Build Coastguard Worker // We don't handle non-definitions. If we already have a call, reject
421*9880d681SAndroid Build Coastguard Worker // instruction dependencies.
422*9880d681SAndroid Build Coastguard Worker if (!I->getResult().isDef() || cdep != nullptr) {
423*9880d681SAndroid Build Coastguard Worker cdep = nullptr;
424*9880d681SAndroid Build Coastguard Worker break;
425*9880d681SAndroid Build Coastguard Worker }
426*9880d681SAndroid Build Coastguard Worker
427*9880d681SAndroid Build Coastguard Worker CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
428*9880d681SAndroid Build Coastguard Worker // FIXME: All duplicated with non-local case.
429*9880d681SAndroid Build Coastguard Worker if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
430*9880d681SAndroid Build Coastguard Worker cdep = NonLocalDepCall;
431*9880d681SAndroid Build Coastguard Worker continue;
432*9880d681SAndroid Build Coastguard Worker }
433*9880d681SAndroid Build Coastguard Worker
434*9880d681SAndroid Build Coastguard Worker cdep = nullptr;
435*9880d681SAndroid Build Coastguard Worker break;
436*9880d681SAndroid Build Coastguard Worker }
437*9880d681SAndroid Build Coastguard Worker
438*9880d681SAndroid Build Coastguard Worker if (!cdep) {
439*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = nextValueNumber;
440*9880d681SAndroid Build Coastguard Worker return nextValueNumber++;
441*9880d681SAndroid Build Coastguard Worker }
442*9880d681SAndroid Build Coastguard Worker
443*9880d681SAndroid Build Coastguard Worker if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
444*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = nextValueNumber;
445*9880d681SAndroid Build Coastguard Worker return nextValueNumber++;
446*9880d681SAndroid Build Coastguard Worker }
447*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
448*9880d681SAndroid Build Coastguard Worker uint32_t c_vn = lookupOrAdd(C->getArgOperand(i));
449*9880d681SAndroid Build Coastguard Worker uint32_t cd_vn = lookupOrAdd(cdep->getArgOperand(i));
450*9880d681SAndroid Build Coastguard Worker if (c_vn != cd_vn) {
451*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = nextValueNumber;
452*9880d681SAndroid Build Coastguard Worker return nextValueNumber++;
453*9880d681SAndroid Build Coastguard Worker }
454*9880d681SAndroid Build Coastguard Worker }
455*9880d681SAndroid Build Coastguard Worker
456*9880d681SAndroid Build Coastguard Worker uint32_t v = lookupOrAdd(cdep);
457*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = v;
458*9880d681SAndroid Build Coastguard Worker return v;
459*9880d681SAndroid Build Coastguard Worker
460*9880d681SAndroid Build Coastguard Worker } else {
461*9880d681SAndroid Build Coastguard Worker valueNumbering[C] = nextValueNumber;
462*9880d681SAndroid Build Coastguard Worker return nextValueNumber++;
463*9880d681SAndroid Build Coastguard Worker }
464*9880d681SAndroid Build Coastguard Worker }
465*9880d681SAndroid Build Coastguard Worker
466*9880d681SAndroid Build Coastguard Worker /// Returns true if a value number exists for the specified value.
exists(Value * V) const467*9880d681SAndroid Build Coastguard Worker bool GVN::ValueTable::exists(Value *V) const { return valueNumbering.count(V) != 0; }
468*9880d681SAndroid Build Coastguard Worker
469*9880d681SAndroid Build Coastguard Worker /// lookup_or_add - Returns the value number for the specified value, assigning
470*9880d681SAndroid Build Coastguard Worker /// it a new number if it did not have one before.
lookupOrAdd(Value * V)471*9880d681SAndroid Build Coastguard Worker uint32_t GVN::ValueTable::lookupOrAdd(Value *V) {
472*9880d681SAndroid Build Coastguard Worker DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
473*9880d681SAndroid Build Coastguard Worker if (VI != valueNumbering.end())
474*9880d681SAndroid Build Coastguard Worker return VI->second;
475*9880d681SAndroid Build Coastguard Worker
476*9880d681SAndroid Build Coastguard Worker if (!isa<Instruction>(V)) {
477*9880d681SAndroid Build Coastguard Worker valueNumbering[V] = nextValueNumber;
478*9880d681SAndroid Build Coastguard Worker return nextValueNumber++;
479*9880d681SAndroid Build Coastguard Worker }
480*9880d681SAndroid Build Coastguard Worker
481*9880d681SAndroid Build Coastguard Worker Instruction* I = cast<Instruction>(V);
482*9880d681SAndroid Build Coastguard Worker Expression exp;
483*9880d681SAndroid Build Coastguard Worker switch (I->getOpcode()) {
484*9880d681SAndroid Build Coastguard Worker case Instruction::Call:
485*9880d681SAndroid Build Coastguard Worker return lookupOrAddCall(cast<CallInst>(I));
486*9880d681SAndroid Build Coastguard Worker case Instruction::Add:
487*9880d681SAndroid Build Coastguard Worker case Instruction::FAdd:
488*9880d681SAndroid Build Coastguard Worker case Instruction::Sub:
489*9880d681SAndroid Build Coastguard Worker case Instruction::FSub:
490*9880d681SAndroid Build Coastguard Worker case Instruction::Mul:
491*9880d681SAndroid Build Coastguard Worker case Instruction::FMul:
492*9880d681SAndroid Build Coastguard Worker case Instruction::UDiv:
493*9880d681SAndroid Build Coastguard Worker case Instruction::SDiv:
494*9880d681SAndroid Build Coastguard Worker case Instruction::FDiv:
495*9880d681SAndroid Build Coastguard Worker case Instruction::URem:
496*9880d681SAndroid Build Coastguard Worker case Instruction::SRem:
497*9880d681SAndroid Build Coastguard Worker case Instruction::FRem:
498*9880d681SAndroid Build Coastguard Worker case Instruction::Shl:
499*9880d681SAndroid Build Coastguard Worker case Instruction::LShr:
500*9880d681SAndroid Build Coastguard Worker case Instruction::AShr:
501*9880d681SAndroid Build Coastguard Worker case Instruction::And:
502*9880d681SAndroid Build Coastguard Worker case Instruction::Or:
503*9880d681SAndroid Build Coastguard Worker case Instruction::Xor:
504*9880d681SAndroid Build Coastguard Worker case Instruction::ICmp:
505*9880d681SAndroid Build Coastguard Worker case Instruction::FCmp:
506*9880d681SAndroid Build Coastguard Worker case Instruction::Trunc:
507*9880d681SAndroid Build Coastguard Worker case Instruction::ZExt:
508*9880d681SAndroid Build Coastguard Worker case Instruction::SExt:
509*9880d681SAndroid Build Coastguard Worker case Instruction::FPToUI:
510*9880d681SAndroid Build Coastguard Worker case Instruction::FPToSI:
511*9880d681SAndroid Build Coastguard Worker case Instruction::UIToFP:
512*9880d681SAndroid Build Coastguard Worker case Instruction::SIToFP:
513*9880d681SAndroid Build Coastguard Worker case Instruction::FPTrunc:
514*9880d681SAndroid Build Coastguard Worker case Instruction::FPExt:
515*9880d681SAndroid Build Coastguard Worker case Instruction::PtrToInt:
516*9880d681SAndroid Build Coastguard Worker case Instruction::IntToPtr:
517*9880d681SAndroid Build Coastguard Worker case Instruction::BitCast:
518*9880d681SAndroid Build Coastguard Worker case Instruction::Select:
519*9880d681SAndroid Build Coastguard Worker case Instruction::ExtractElement:
520*9880d681SAndroid Build Coastguard Worker case Instruction::InsertElement:
521*9880d681SAndroid Build Coastguard Worker case Instruction::ShuffleVector:
522*9880d681SAndroid Build Coastguard Worker case Instruction::InsertValue:
523*9880d681SAndroid Build Coastguard Worker case Instruction::GetElementPtr:
524*9880d681SAndroid Build Coastguard Worker exp = createExpr(I);
525*9880d681SAndroid Build Coastguard Worker break;
526*9880d681SAndroid Build Coastguard Worker case Instruction::ExtractValue:
527*9880d681SAndroid Build Coastguard Worker exp = createExtractvalueExpr(cast<ExtractValueInst>(I));
528*9880d681SAndroid Build Coastguard Worker break;
529*9880d681SAndroid Build Coastguard Worker default:
530*9880d681SAndroid Build Coastguard Worker valueNumbering[V] = nextValueNumber;
531*9880d681SAndroid Build Coastguard Worker return nextValueNumber++;
532*9880d681SAndroid Build Coastguard Worker }
533*9880d681SAndroid Build Coastguard Worker
534*9880d681SAndroid Build Coastguard Worker uint32_t& e = expressionNumbering[exp];
535*9880d681SAndroid Build Coastguard Worker if (!e) e = nextValueNumber++;
536*9880d681SAndroid Build Coastguard Worker valueNumbering[V] = e;
537*9880d681SAndroid Build Coastguard Worker return e;
538*9880d681SAndroid Build Coastguard Worker }
539*9880d681SAndroid Build Coastguard Worker
540*9880d681SAndroid Build Coastguard Worker /// Returns the value number of the specified value. Fails if
541*9880d681SAndroid Build Coastguard Worker /// the value has not yet been numbered.
lookup(Value * V) const542*9880d681SAndroid Build Coastguard Worker uint32_t GVN::ValueTable::lookup(Value *V) const {
543*9880d681SAndroid Build Coastguard Worker DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
544*9880d681SAndroid Build Coastguard Worker assert(VI != valueNumbering.end() && "Value not numbered?");
545*9880d681SAndroid Build Coastguard Worker return VI->second;
546*9880d681SAndroid Build Coastguard Worker }
547*9880d681SAndroid Build Coastguard Worker
548*9880d681SAndroid Build Coastguard Worker /// Returns the value number of the given comparison,
549*9880d681SAndroid Build Coastguard Worker /// assigning it a new number if it did not have one before. Useful when
550*9880d681SAndroid Build Coastguard Worker /// we deduced the result of a comparison, but don't immediately have an
551*9880d681SAndroid Build Coastguard Worker /// instruction realizing that comparison to hand.
lookupOrAddCmp(unsigned Opcode,CmpInst::Predicate Predicate,Value * LHS,Value * RHS)552*9880d681SAndroid Build Coastguard Worker uint32_t GVN::ValueTable::lookupOrAddCmp(unsigned Opcode,
553*9880d681SAndroid Build Coastguard Worker CmpInst::Predicate Predicate,
554*9880d681SAndroid Build Coastguard Worker Value *LHS, Value *RHS) {
555*9880d681SAndroid Build Coastguard Worker Expression exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
556*9880d681SAndroid Build Coastguard Worker uint32_t& e = expressionNumbering[exp];
557*9880d681SAndroid Build Coastguard Worker if (!e) e = nextValueNumber++;
558*9880d681SAndroid Build Coastguard Worker return e;
559*9880d681SAndroid Build Coastguard Worker }
560*9880d681SAndroid Build Coastguard Worker
561*9880d681SAndroid Build Coastguard Worker /// Remove all entries from the ValueTable.
clear()562*9880d681SAndroid Build Coastguard Worker void GVN::ValueTable::clear() {
563*9880d681SAndroid Build Coastguard Worker valueNumbering.clear();
564*9880d681SAndroid Build Coastguard Worker expressionNumbering.clear();
565*9880d681SAndroid Build Coastguard Worker nextValueNumber = 1;
566*9880d681SAndroid Build Coastguard Worker }
567*9880d681SAndroid Build Coastguard Worker
568*9880d681SAndroid Build Coastguard Worker /// Remove a value from the value numbering.
erase(Value * V)569*9880d681SAndroid Build Coastguard Worker void GVN::ValueTable::erase(Value *V) {
570*9880d681SAndroid Build Coastguard Worker valueNumbering.erase(V);
571*9880d681SAndroid Build Coastguard Worker }
572*9880d681SAndroid Build Coastguard Worker
573*9880d681SAndroid Build Coastguard Worker /// verifyRemoved - Verify that the value is removed from all internal data
574*9880d681SAndroid Build Coastguard Worker /// structures.
verifyRemoved(const Value * V) const575*9880d681SAndroid Build Coastguard Worker void GVN::ValueTable::verifyRemoved(const Value *V) const {
576*9880d681SAndroid Build Coastguard Worker for (DenseMap<Value*, uint32_t>::const_iterator
577*9880d681SAndroid Build Coastguard Worker I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
578*9880d681SAndroid Build Coastguard Worker assert(I->first != V && "Inst still occurs in value numbering map!");
579*9880d681SAndroid Build Coastguard Worker }
580*9880d681SAndroid Build Coastguard Worker }
581*9880d681SAndroid Build Coastguard Worker
582*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
583*9880d681SAndroid Build Coastguard Worker // GVN Pass
584*9880d681SAndroid Build Coastguard Worker //===----------------------------------------------------------------------===//
585*9880d681SAndroid Build Coastguard Worker
run(Function & F,AnalysisManager<Function> & AM)586*9880d681SAndroid Build Coastguard Worker PreservedAnalyses GVN::run(Function &F, AnalysisManager<Function> &AM) {
587*9880d681SAndroid Build Coastguard Worker // FIXME: The order of evaluation of these 'getResult' calls is very
588*9880d681SAndroid Build Coastguard Worker // significant! Re-ordering these variables will cause GVN when run alone to
589*9880d681SAndroid Build Coastguard Worker // be less effective! We should fix memdep and basic-aa to not exhibit this
590*9880d681SAndroid Build Coastguard Worker // behavior, but until then don't change the order here.
591*9880d681SAndroid Build Coastguard Worker auto &AC = AM.getResult<AssumptionAnalysis>(F);
592*9880d681SAndroid Build Coastguard Worker auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
593*9880d681SAndroid Build Coastguard Worker auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
594*9880d681SAndroid Build Coastguard Worker auto &AA = AM.getResult<AAManager>(F);
595*9880d681SAndroid Build Coastguard Worker auto &MemDep = AM.getResult<MemoryDependenceAnalysis>(F);
596*9880d681SAndroid Build Coastguard Worker bool Changed = runImpl(F, AC, DT, TLI, AA, &MemDep);
597*9880d681SAndroid Build Coastguard Worker if (!Changed)
598*9880d681SAndroid Build Coastguard Worker return PreservedAnalyses::all();
599*9880d681SAndroid Build Coastguard Worker PreservedAnalyses PA;
600*9880d681SAndroid Build Coastguard Worker PA.preserve<DominatorTreeAnalysis>();
601*9880d681SAndroid Build Coastguard Worker PA.preserve<GlobalsAA>();
602*9880d681SAndroid Build Coastguard Worker return PA;
603*9880d681SAndroid Build Coastguard Worker }
604*9880d681SAndroid Build Coastguard Worker
605*9880d681SAndroid Build Coastguard Worker LLVM_DUMP_METHOD
dump(DenseMap<uint32_t,Value * > & d)606*9880d681SAndroid Build Coastguard Worker void GVN::dump(DenseMap<uint32_t, Value*>& d) {
607*9880d681SAndroid Build Coastguard Worker errs() << "{\n";
608*9880d681SAndroid Build Coastguard Worker for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
609*9880d681SAndroid Build Coastguard Worker E = d.end(); I != E; ++I) {
610*9880d681SAndroid Build Coastguard Worker errs() << I->first << "\n";
611*9880d681SAndroid Build Coastguard Worker I->second->dump();
612*9880d681SAndroid Build Coastguard Worker }
613*9880d681SAndroid Build Coastguard Worker errs() << "}\n";
614*9880d681SAndroid Build Coastguard Worker }
615*9880d681SAndroid Build Coastguard Worker
616*9880d681SAndroid Build Coastguard Worker /// Return true if we can prove that the value
617*9880d681SAndroid Build Coastguard Worker /// we're analyzing is fully available in the specified block. As we go, keep
618*9880d681SAndroid Build Coastguard Worker /// track of which blocks we know are fully alive in FullyAvailableBlocks. This
619*9880d681SAndroid Build Coastguard Worker /// map is actually a tri-state map with the following values:
620*9880d681SAndroid Build Coastguard Worker /// 0) we know the block *is not* fully available.
621*9880d681SAndroid Build Coastguard Worker /// 1) we know the block *is* fully available.
622*9880d681SAndroid Build Coastguard Worker /// 2) we do not know whether the block is fully available or not, but we are
623*9880d681SAndroid Build Coastguard Worker /// currently speculating that it will be.
624*9880d681SAndroid Build Coastguard Worker /// 3) we are speculating for this block and have used that to speculate for
625*9880d681SAndroid Build Coastguard Worker /// other blocks.
IsValueFullyAvailableInBlock(BasicBlock * BB,DenseMap<BasicBlock *,char> & FullyAvailableBlocks,uint32_t RecurseDepth)626*9880d681SAndroid Build Coastguard Worker static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
627*9880d681SAndroid Build Coastguard Worker DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
628*9880d681SAndroid Build Coastguard Worker uint32_t RecurseDepth) {
629*9880d681SAndroid Build Coastguard Worker if (RecurseDepth > MaxRecurseDepth)
630*9880d681SAndroid Build Coastguard Worker return false;
631*9880d681SAndroid Build Coastguard Worker
632*9880d681SAndroid Build Coastguard Worker // Optimistically assume that the block is fully available and check to see
633*9880d681SAndroid Build Coastguard Worker // if we already know about this block in one lookup.
634*9880d681SAndroid Build Coastguard Worker std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
635*9880d681SAndroid Build Coastguard Worker FullyAvailableBlocks.insert(std::make_pair(BB, 2));
636*9880d681SAndroid Build Coastguard Worker
637*9880d681SAndroid Build Coastguard Worker // If the entry already existed for this block, return the precomputed value.
638*9880d681SAndroid Build Coastguard Worker if (!IV.second) {
639*9880d681SAndroid Build Coastguard Worker // If this is a speculative "available" value, mark it as being used for
640*9880d681SAndroid Build Coastguard Worker // speculation of other blocks.
641*9880d681SAndroid Build Coastguard Worker if (IV.first->second == 2)
642*9880d681SAndroid Build Coastguard Worker IV.first->second = 3;
643*9880d681SAndroid Build Coastguard Worker return IV.first->second != 0;
644*9880d681SAndroid Build Coastguard Worker }
645*9880d681SAndroid Build Coastguard Worker
646*9880d681SAndroid Build Coastguard Worker // Otherwise, see if it is fully available in all predecessors.
647*9880d681SAndroid Build Coastguard Worker pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
648*9880d681SAndroid Build Coastguard Worker
649*9880d681SAndroid Build Coastguard Worker // If this block has no predecessors, it isn't live-in here.
650*9880d681SAndroid Build Coastguard Worker if (PI == PE)
651*9880d681SAndroid Build Coastguard Worker goto SpeculationFailure;
652*9880d681SAndroid Build Coastguard Worker
653*9880d681SAndroid Build Coastguard Worker for (; PI != PE; ++PI)
654*9880d681SAndroid Build Coastguard Worker // If the value isn't fully available in one of our predecessors, then it
655*9880d681SAndroid Build Coastguard Worker // isn't fully available in this block either. Undo our previous
656*9880d681SAndroid Build Coastguard Worker // optimistic assumption and bail out.
657*9880d681SAndroid Build Coastguard Worker if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
658*9880d681SAndroid Build Coastguard Worker goto SpeculationFailure;
659*9880d681SAndroid Build Coastguard Worker
660*9880d681SAndroid Build Coastguard Worker return true;
661*9880d681SAndroid Build Coastguard Worker
662*9880d681SAndroid Build Coastguard Worker // If we get here, we found out that this is not, after
663*9880d681SAndroid Build Coastguard Worker // all, a fully-available block. We have a problem if we speculated on this and
664*9880d681SAndroid Build Coastguard Worker // used the speculation to mark other blocks as available.
665*9880d681SAndroid Build Coastguard Worker SpeculationFailure:
666*9880d681SAndroid Build Coastguard Worker char &BBVal = FullyAvailableBlocks[BB];
667*9880d681SAndroid Build Coastguard Worker
668*9880d681SAndroid Build Coastguard Worker // If we didn't speculate on this, just return with it set to false.
669*9880d681SAndroid Build Coastguard Worker if (BBVal == 2) {
670*9880d681SAndroid Build Coastguard Worker BBVal = 0;
671*9880d681SAndroid Build Coastguard Worker return false;
672*9880d681SAndroid Build Coastguard Worker }
673*9880d681SAndroid Build Coastguard Worker
674*9880d681SAndroid Build Coastguard Worker // If we did speculate on this value, we could have blocks set to 1 that are
675*9880d681SAndroid Build Coastguard Worker // incorrect. Walk the (transitive) successors of this block and mark them as
676*9880d681SAndroid Build Coastguard Worker // 0 if set to one.
677*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock*, 32> BBWorklist;
678*9880d681SAndroid Build Coastguard Worker BBWorklist.push_back(BB);
679*9880d681SAndroid Build Coastguard Worker
680*9880d681SAndroid Build Coastguard Worker do {
681*9880d681SAndroid Build Coastguard Worker BasicBlock *Entry = BBWorklist.pop_back_val();
682*9880d681SAndroid Build Coastguard Worker // Note that this sets blocks to 0 (unavailable) if they happen to not
683*9880d681SAndroid Build Coastguard Worker // already be in FullyAvailableBlocks. This is safe.
684*9880d681SAndroid Build Coastguard Worker char &EntryVal = FullyAvailableBlocks[Entry];
685*9880d681SAndroid Build Coastguard Worker if (EntryVal == 0) continue; // Already unavailable.
686*9880d681SAndroid Build Coastguard Worker
687*9880d681SAndroid Build Coastguard Worker // Mark as unavailable.
688*9880d681SAndroid Build Coastguard Worker EntryVal = 0;
689*9880d681SAndroid Build Coastguard Worker
690*9880d681SAndroid Build Coastguard Worker BBWorklist.append(succ_begin(Entry), succ_end(Entry));
691*9880d681SAndroid Build Coastguard Worker } while (!BBWorklist.empty());
692*9880d681SAndroid Build Coastguard Worker
693*9880d681SAndroid Build Coastguard Worker return false;
694*9880d681SAndroid Build Coastguard Worker }
695*9880d681SAndroid Build Coastguard Worker
696*9880d681SAndroid Build Coastguard Worker
697*9880d681SAndroid Build Coastguard Worker /// Return true if CoerceAvailableValueToLoadType will succeed.
CanCoerceMustAliasedValueToLoad(Value * StoredVal,Type * LoadTy,const DataLayout & DL)698*9880d681SAndroid Build Coastguard Worker static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
699*9880d681SAndroid Build Coastguard Worker Type *LoadTy,
700*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
701*9880d681SAndroid Build Coastguard Worker // If the loaded or stored value is an first class array or struct, don't try
702*9880d681SAndroid Build Coastguard Worker // to transform them. We need to be able to bitcast to integer.
703*9880d681SAndroid Build Coastguard Worker if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
704*9880d681SAndroid Build Coastguard Worker StoredVal->getType()->isStructTy() ||
705*9880d681SAndroid Build Coastguard Worker StoredVal->getType()->isArrayTy())
706*9880d681SAndroid Build Coastguard Worker return false;
707*9880d681SAndroid Build Coastguard Worker
708*9880d681SAndroid Build Coastguard Worker // The store has to be at least as big as the load.
709*9880d681SAndroid Build Coastguard Worker if (DL.getTypeSizeInBits(StoredVal->getType()) <
710*9880d681SAndroid Build Coastguard Worker DL.getTypeSizeInBits(LoadTy))
711*9880d681SAndroid Build Coastguard Worker return false;
712*9880d681SAndroid Build Coastguard Worker
713*9880d681SAndroid Build Coastguard Worker return true;
714*9880d681SAndroid Build Coastguard Worker }
715*9880d681SAndroid Build Coastguard Worker
716*9880d681SAndroid Build Coastguard Worker /// If we saw a store of a value to memory, and
717*9880d681SAndroid Build Coastguard Worker /// then a load from a must-aliased pointer of a different type, try to coerce
718*9880d681SAndroid Build Coastguard Worker /// the stored value. LoadedTy is the type of the load we want to replace.
719*9880d681SAndroid Build Coastguard Worker /// IRB is IRBuilder used to insert new instructions.
720*9880d681SAndroid Build Coastguard Worker ///
721*9880d681SAndroid Build Coastguard Worker /// If we can't do it, return null.
CoerceAvailableValueToLoadType(Value * StoredVal,Type * LoadedTy,IRBuilder<> & IRB,const DataLayout & DL)722*9880d681SAndroid Build Coastguard Worker static Value *CoerceAvailableValueToLoadType(Value *StoredVal, Type *LoadedTy,
723*9880d681SAndroid Build Coastguard Worker IRBuilder<> &IRB,
724*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
725*9880d681SAndroid Build Coastguard Worker assert(CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL) &&
726*9880d681SAndroid Build Coastguard Worker "precondition violation - materialization can't fail");
727*9880d681SAndroid Build Coastguard Worker
728*9880d681SAndroid Build Coastguard Worker // If this is already the right type, just return it.
729*9880d681SAndroid Build Coastguard Worker Type *StoredValTy = StoredVal->getType();
730*9880d681SAndroid Build Coastguard Worker
731*9880d681SAndroid Build Coastguard Worker uint64_t StoredValSize = DL.getTypeSizeInBits(StoredValTy);
732*9880d681SAndroid Build Coastguard Worker uint64_t LoadedValSize = DL.getTypeSizeInBits(LoadedTy);
733*9880d681SAndroid Build Coastguard Worker
734*9880d681SAndroid Build Coastguard Worker // If the store and reload are the same size, we can always reuse it.
735*9880d681SAndroid Build Coastguard Worker if (StoredValSize == LoadedValSize) {
736*9880d681SAndroid Build Coastguard Worker // Pointer to Pointer -> use bitcast.
737*9880d681SAndroid Build Coastguard Worker if (StoredValTy->getScalarType()->isPointerTy() &&
738*9880d681SAndroid Build Coastguard Worker LoadedTy->getScalarType()->isPointerTy())
739*9880d681SAndroid Build Coastguard Worker return IRB.CreateBitCast(StoredVal, LoadedTy);
740*9880d681SAndroid Build Coastguard Worker
741*9880d681SAndroid Build Coastguard Worker // Convert source pointers to integers, which can be bitcast.
742*9880d681SAndroid Build Coastguard Worker if (StoredValTy->getScalarType()->isPointerTy()) {
743*9880d681SAndroid Build Coastguard Worker StoredValTy = DL.getIntPtrType(StoredValTy);
744*9880d681SAndroid Build Coastguard Worker StoredVal = IRB.CreatePtrToInt(StoredVal, StoredValTy);
745*9880d681SAndroid Build Coastguard Worker }
746*9880d681SAndroid Build Coastguard Worker
747*9880d681SAndroid Build Coastguard Worker Type *TypeToCastTo = LoadedTy;
748*9880d681SAndroid Build Coastguard Worker if (TypeToCastTo->getScalarType()->isPointerTy())
749*9880d681SAndroid Build Coastguard Worker TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
750*9880d681SAndroid Build Coastguard Worker
751*9880d681SAndroid Build Coastguard Worker if (StoredValTy != TypeToCastTo)
752*9880d681SAndroid Build Coastguard Worker StoredVal = IRB.CreateBitCast(StoredVal, TypeToCastTo);
753*9880d681SAndroid Build Coastguard Worker
754*9880d681SAndroid Build Coastguard Worker // Cast to pointer if the load needs a pointer type.
755*9880d681SAndroid Build Coastguard Worker if (LoadedTy->getScalarType()->isPointerTy())
756*9880d681SAndroid Build Coastguard Worker StoredVal = IRB.CreateIntToPtr(StoredVal, LoadedTy);
757*9880d681SAndroid Build Coastguard Worker
758*9880d681SAndroid Build Coastguard Worker return StoredVal;
759*9880d681SAndroid Build Coastguard Worker }
760*9880d681SAndroid Build Coastguard Worker
761*9880d681SAndroid Build Coastguard Worker // If the loaded value is smaller than the available value, then we can
762*9880d681SAndroid Build Coastguard Worker // extract out a piece from it. If the available value is too small, then we
763*9880d681SAndroid Build Coastguard Worker // can't do anything.
764*9880d681SAndroid Build Coastguard Worker assert(StoredValSize >= LoadedValSize &&
765*9880d681SAndroid Build Coastguard Worker "CanCoerceMustAliasedValueToLoad fail");
766*9880d681SAndroid Build Coastguard Worker
767*9880d681SAndroid Build Coastguard Worker // Convert source pointers to integers, which can be manipulated.
768*9880d681SAndroid Build Coastguard Worker if (StoredValTy->getScalarType()->isPointerTy()) {
769*9880d681SAndroid Build Coastguard Worker StoredValTy = DL.getIntPtrType(StoredValTy);
770*9880d681SAndroid Build Coastguard Worker StoredVal = IRB.CreatePtrToInt(StoredVal, StoredValTy);
771*9880d681SAndroid Build Coastguard Worker }
772*9880d681SAndroid Build Coastguard Worker
773*9880d681SAndroid Build Coastguard Worker // Convert vectors and fp to integer, which can be manipulated.
774*9880d681SAndroid Build Coastguard Worker if (!StoredValTy->isIntegerTy()) {
775*9880d681SAndroid Build Coastguard Worker StoredValTy = IntegerType::get(StoredValTy->getContext(), StoredValSize);
776*9880d681SAndroid Build Coastguard Worker StoredVal = IRB.CreateBitCast(StoredVal, StoredValTy);
777*9880d681SAndroid Build Coastguard Worker }
778*9880d681SAndroid Build Coastguard Worker
779*9880d681SAndroid Build Coastguard Worker // If this is a big-endian system, we need to shift the value down to the low
780*9880d681SAndroid Build Coastguard Worker // bits so that a truncate will work.
781*9880d681SAndroid Build Coastguard Worker if (DL.isBigEndian()) {
782*9880d681SAndroid Build Coastguard Worker uint64_t ShiftAmt = DL.getTypeStoreSizeInBits(StoredValTy) -
783*9880d681SAndroid Build Coastguard Worker DL.getTypeStoreSizeInBits(LoadedTy);
784*9880d681SAndroid Build Coastguard Worker StoredVal = IRB.CreateLShr(StoredVal, ShiftAmt, "tmp");
785*9880d681SAndroid Build Coastguard Worker }
786*9880d681SAndroid Build Coastguard Worker
787*9880d681SAndroid Build Coastguard Worker // Truncate the integer to the right size now.
788*9880d681SAndroid Build Coastguard Worker Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadedValSize);
789*9880d681SAndroid Build Coastguard Worker StoredVal = IRB.CreateTrunc(StoredVal, NewIntTy, "trunc");
790*9880d681SAndroid Build Coastguard Worker
791*9880d681SAndroid Build Coastguard Worker if (LoadedTy == NewIntTy)
792*9880d681SAndroid Build Coastguard Worker return StoredVal;
793*9880d681SAndroid Build Coastguard Worker
794*9880d681SAndroid Build Coastguard Worker // If the result is a pointer, inttoptr.
795*9880d681SAndroid Build Coastguard Worker if (LoadedTy->getScalarType()->isPointerTy())
796*9880d681SAndroid Build Coastguard Worker return IRB.CreateIntToPtr(StoredVal, LoadedTy, "inttoptr");
797*9880d681SAndroid Build Coastguard Worker
798*9880d681SAndroid Build Coastguard Worker // Otherwise, bitcast.
799*9880d681SAndroid Build Coastguard Worker return IRB.CreateBitCast(StoredVal, LoadedTy, "bitcast");
800*9880d681SAndroid Build Coastguard Worker }
801*9880d681SAndroid Build Coastguard Worker
802*9880d681SAndroid Build Coastguard Worker /// This function is called when we have a
803*9880d681SAndroid Build Coastguard Worker /// memdep query of a load that ends up being a clobbering memory write (store,
804*9880d681SAndroid Build Coastguard Worker /// memset, memcpy, memmove). This means that the write *may* provide bits used
805*9880d681SAndroid Build Coastguard Worker /// by the load but we can't be sure because the pointers don't mustalias.
806*9880d681SAndroid Build Coastguard Worker ///
807*9880d681SAndroid Build Coastguard Worker /// Check this case to see if there is anything more we can do before we give
808*9880d681SAndroid Build Coastguard Worker /// up. This returns -1 if we have to give up, or a byte number in the stored
809*9880d681SAndroid Build Coastguard Worker /// value of the piece that feeds the load.
AnalyzeLoadFromClobberingWrite(Type * LoadTy,Value * LoadPtr,Value * WritePtr,uint64_t WriteSizeInBits,const DataLayout & DL)810*9880d681SAndroid Build Coastguard Worker static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
811*9880d681SAndroid Build Coastguard Worker Value *WritePtr,
812*9880d681SAndroid Build Coastguard Worker uint64_t WriteSizeInBits,
813*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
814*9880d681SAndroid Build Coastguard Worker // If the loaded or stored value is a first class array or struct, don't try
815*9880d681SAndroid Build Coastguard Worker // to transform them. We need to be able to bitcast to integer.
816*9880d681SAndroid Build Coastguard Worker if (LoadTy->isStructTy() || LoadTy->isArrayTy())
817*9880d681SAndroid Build Coastguard Worker return -1;
818*9880d681SAndroid Build Coastguard Worker
819*9880d681SAndroid Build Coastguard Worker int64_t StoreOffset = 0, LoadOffset = 0;
820*9880d681SAndroid Build Coastguard Worker Value *StoreBase =
821*9880d681SAndroid Build Coastguard Worker GetPointerBaseWithConstantOffset(WritePtr, StoreOffset, DL);
822*9880d681SAndroid Build Coastguard Worker Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, DL);
823*9880d681SAndroid Build Coastguard Worker if (StoreBase != LoadBase)
824*9880d681SAndroid Build Coastguard Worker return -1;
825*9880d681SAndroid Build Coastguard Worker
826*9880d681SAndroid Build Coastguard Worker // If the load and store are to the exact same address, they should have been
827*9880d681SAndroid Build Coastguard Worker // a must alias. AA must have gotten confused.
828*9880d681SAndroid Build Coastguard Worker // FIXME: Study to see if/when this happens. One case is forwarding a memset
829*9880d681SAndroid Build Coastguard Worker // to a load from the base of the memset.
830*9880d681SAndroid Build Coastguard Worker #if 0
831*9880d681SAndroid Build Coastguard Worker if (LoadOffset == StoreOffset) {
832*9880d681SAndroid Build Coastguard Worker dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
833*9880d681SAndroid Build Coastguard Worker << "Base = " << *StoreBase << "\n"
834*9880d681SAndroid Build Coastguard Worker << "Store Ptr = " << *WritePtr << "\n"
835*9880d681SAndroid Build Coastguard Worker << "Store Offs = " << StoreOffset << "\n"
836*9880d681SAndroid Build Coastguard Worker << "Load Ptr = " << *LoadPtr << "\n";
837*9880d681SAndroid Build Coastguard Worker abort();
838*9880d681SAndroid Build Coastguard Worker }
839*9880d681SAndroid Build Coastguard Worker #endif
840*9880d681SAndroid Build Coastguard Worker
841*9880d681SAndroid Build Coastguard Worker // If the load and store don't overlap at all, the store doesn't provide
842*9880d681SAndroid Build Coastguard Worker // anything to the load. In this case, they really don't alias at all, AA
843*9880d681SAndroid Build Coastguard Worker // must have gotten confused.
844*9880d681SAndroid Build Coastguard Worker uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy);
845*9880d681SAndroid Build Coastguard Worker
846*9880d681SAndroid Build Coastguard Worker if ((WriteSizeInBits & 7) | (LoadSize & 7))
847*9880d681SAndroid Build Coastguard Worker return -1;
848*9880d681SAndroid Build Coastguard Worker uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
849*9880d681SAndroid Build Coastguard Worker LoadSize >>= 3;
850*9880d681SAndroid Build Coastguard Worker
851*9880d681SAndroid Build Coastguard Worker
852*9880d681SAndroid Build Coastguard Worker bool isAAFailure = false;
853*9880d681SAndroid Build Coastguard Worker if (StoreOffset < LoadOffset)
854*9880d681SAndroid Build Coastguard Worker isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
855*9880d681SAndroid Build Coastguard Worker else
856*9880d681SAndroid Build Coastguard Worker isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
857*9880d681SAndroid Build Coastguard Worker
858*9880d681SAndroid Build Coastguard Worker if (isAAFailure) {
859*9880d681SAndroid Build Coastguard Worker #if 0
860*9880d681SAndroid Build Coastguard Worker dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
861*9880d681SAndroid Build Coastguard Worker << "Base = " << *StoreBase << "\n"
862*9880d681SAndroid Build Coastguard Worker << "Store Ptr = " << *WritePtr << "\n"
863*9880d681SAndroid Build Coastguard Worker << "Store Offs = " << StoreOffset << "\n"
864*9880d681SAndroid Build Coastguard Worker << "Load Ptr = " << *LoadPtr << "\n";
865*9880d681SAndroid Build Coastguard Worker abort();
866*9880d681SAndroid Build Coastguard Worker #endif
867*9880d681SAndroid Build Coastguard Worker return -1;
868*9880d681SAndroid Build Coastguard Worker }
869*9880d681SAndroid Build Coastguard Worker
870*9880d681SAndroid Build Coastguard Worker // If the Load isn't completely contained within the stored bits, we don't
871*9880d681SAndroid Build Coastguard Worker // have all the bits to feed it. We could do something crazy in the future
872*9880d681SAndroid Build Coastguard Worker // (issue a smaller load then merge the bits in) but this seems unlikely to be
873*9880d681SAndroid Build Coastguard Worker // valuable.
874*9880d681SAndroid Build Coastguard Worker if (StoreOffset > LoadOffset ||
875*9880d681SAndroid Build Coastguard Worker StoreOffset+StoreSize < LoadOffset+LoadSize)
876*9880d681SAndroid Build Coastguard Worker return -1;
877*9880d681SAndroid Build Coastguard Worker
878*9880d681SAndroid Build Coastguard Worker // Okay, we can do this transformation. Return the number of bytes into the
879*9880d681SAndroid Build Coastguard Worker // store that the load is.
880*9880d681SAndroid Build Coastguard Worker return LoadOffset-StoreOffset;
881*9880d681SAndroid Build Coastguard Worker }
882*9880d681SAndroid Build Coastguard Worker
883*9880d681SAndroid Build Coastguard Worker /// This function is called when we have a
884*9880d681SAndroid Build Coastguard Worker /// memdep query of a load that ends up being a clobbering store.
AnalyzeLoadFromClobberingStore(Type * LoadTy,Value * LoadPtr,StoreInst * DepSI)885*9880d681SAndroid Build Coastguard Worker static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
886*9880d681SAndroid Build Coastguard Worker StoreInst *DepSI) {
887*9880d681SAndroid Build Coastguard Worker // Cannot handle reading from store of first-class aggregate yet.
888*9880d681SAndroid Build Coastguard Worker if (DepSI->getValueOperand()->getType()->isStructTy() ||
889*9880d681SAndroid Build Coastguard Worker DepSI->getValueOperand()->getType()->isArrayTy())
890*9880d681SAndroid Build Coastguard Worker return -1;
891*9880d681SAndroid Build Coastguard Worker
892*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = DepSI->getModule()->getDataLayout();
893*9880d681SAndroid Build Coastguard Worker Value *StorePtr = DepSI->getPointerOperand();
894*9880d681SAndroid Build Coastguard Worker uint64_t StoreSize =DL.getTypeSizeInBits(DepSI->getValueOperand()->getType());
895*9880d681SAndroid Build Coastguard Worker return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
896*9880d681SAndroid Build Coastguard Worker StorePtr, StoreSize, DL);
897*9880d681SAndroid Build Coastguard Worker }
898*9880d681SAndroid Build Coastguard Worker
899*9880d681SAndroid Build Coastguard Worker /// This function is called when we have a
900*9880d681SAndroid Build Coastguard Worker /// memdep query of a load that ends up being clobbered by another load. See if
901*9880d681SAndroid Build Coastguard Worker /// the other load can feed into the second load.
AnalyzeLoadFromClobberingLoad(Type * LoadTy,Value * LoadPtr,LoadInst * DepLI,const DataLayout & DL)902*9880d681SAndroid Build Coastguard Worker static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
903*9880d681SAndroid Build Coastguard Worker LoadInst *DepLI, const DataLayout &DL){
904*9880d681SAndroid Build Coastguard Worker // Cannot handle reading from store of first-class aggregate yet.
905*9880d681SAndroid Build Coastguard Worker if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
906*9880d681SAndroid Build Coastguard Worker return -1;
907*9880d681SAndroid Build Coastguard Worker
908*9880d681SAndroid Build Coastguard Worker Value *DepPtr = DepLI->getPointerOperand();
909*9880d681SAndroid Build Coastguard Worker uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType());
910*9880d681SAndroid Build Coastguard Worker int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
911*9880d681SAndroid Build Coastguard Worker if (R != -1) return R;
912*9880d681SAndroid Build Coastguard Worker
913*9880d681SAndroid Build Coastguard Worker // If we have a load/load clobber an DepLI can be widened to cover this load,
914*9880d681SAndroid Build Coastguard Worker // then we should widen it!
915*9880d681SAndroid Build Coastguard Worker int64_t LoadOffs = 0;
916*9880d681SAndroid Build Coastguard Worker const Value *LoadBase =
917*9880d681SAndroid Build Coastguard Worker GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, DL);
918*9880d681SAndroid Build Coastguard Worker unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
919*9880d681SAndroid Build Coastguard Worker
920*9880d681SAndroid Build Coastguard Worker unsigned Size = MemoryDependenceResults::getLoadLoadClobberFullWidthSize(
921*9880d681SAndroid Build Coastguard Worker LoadBase, LoadOffs, LoadSize, DepLI);
922*9880d681SAndroid Build Coastguard Worker if (Size == 0) return -1;
923*9880d681SAndroid Build Coastguard Worker
924*9880d681SAndroid Build Coastguard Worker // Check non-obvious conditions enforced by MDA which we rely on for being
925*9880d681SAndroid Build Coastguard Worker // able to materialize this potentially available value
926*9880d681SAndroid Build Coastguard Worker assert(DepLI->isSimple() && "Cannot widen volatile/atomic load!");
927*9880d681SAndroid Build Coastguard Worker assert(DepLI->getType()->isIntegerTy() && "Can't widen non-integer load");
928*9880d681SAndroid Build Coastguard Worker
929*9880d681SAndroid Build Coastguard Worker return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, DL);
930*9880d681SAndroid Build Coastguard Worker }
931*9880d681SAndroid Build Coastguard Worker
932*9880d681SAndroid Build Coastguard Worker
933*9880d681SAndroid Build Coastguard Worker
AnalyzeLoadFromClobberingMemInst(Type * LoadTy,Value * LoadPtr,MemIntrinsic * MI,const DataLayout & DL)934*9880d681SAndroid Build Coastguard Worker static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
935*9880d681SAndroid Build Coastguard Worker MemIntrinsic *MI,
936*9880d681SAndroid Build Coastguard Worker const DataLayout &DL) {
937*9880d681SAndroid Build Coastguard Worker // If the mem operation is a non-constant size, we can't handle it.
938*9880d681SAndroid Build Coastguard Worker ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
939*9880d681SAndroid Build Coastguard Worker if (!SizeCst) return -1;
940*9880d681SAndroid Build Coastguard Worker uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
941*9880d681SAndroid Build Coastguard Worker
942*9880d681SAndroid Build Coastguard Worker // If this is memset, we just need to see if the offset is valid in the size
943*9880d681SAndroid Build Coastguard Worker // of the memset..
944*9880d681SAndroid Build Coastguard Worker if (MI->getIntrinsicID() == Intrinsic::memset)
945*9880d681SAndroid Build Coastguard Worker return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
946*9880d681SAndroid Build Coastguard Worker MemSizeInBits, DL);
947*9880d681SAndroid Build Coastguard Worker
948*9880d681SAndroid Build Coastguard Worker // If we have a memcpy/memmove, the only case we can handle is if this is a
949*9880d681SAndroid Build Coastguard Worker // copy from constant memory. In that case, we can read directly from the
950*9880d681SAndroid Build Coastguard Worker // constant memory.
951*9880d681SAndroid Build Coastguard Worker MemTransferInst *MTI = cast<MemTransferInst>(MI);
952*9880d681SAndroid Build Coastguard Worker
953*9880d681SAndroid Build Coastguard Worker Constant *Src = dyn_cast<Constant>(MTI->getSource());
954*9880d681SAndroid Build Coastguard Worker if (!Src) return -1;
955*9880d681SAndroid Build Coastguard Worker
956*9880d681SAndroid Build Coastguard Worker GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, DL));
957*9880d681SAndroid Build Coastguard Worker if (!GV || !GV->isConstant()) return -1;
958*9880d681SAndroid Build Coastguard Worker
959*9880d681SAndroid Build Coastguard Worker // See if the access is within the bounds of the transfer.
960*9880d681SAndroid Build Coastguard Worker int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
961*9880d681SAndroid Build Coastguard Worker MI->getDest(), MemSizeInBits, DL);
962*9880d681SAndroid Build Coastguard Worker if (Offset == -1)
963*9880d681SAndroid Build Coastguard Worker return Offset;
964*9880d681SAndroid Build Coastguard Worker
965*9880d681SAndroid Build Coastguard Worker unsigned AS = Src->getType()->getPointerAddressSpace();
966*9880d681SAndroid Build Coastguard Worker // Otherwise, see if we can constant fold a load from the constant with the
967*9880d681SAndroid Build Coastguard Worker // offset applied as appropriate.
968*9880d681SAndroid Build Coastguard Worker Src = ConstantExpr::getBitCast(Src,
969*9880d681SAndroid Build Coastguard Worker Type::getInt8PtrTy(Src->getContext(), AS));
970*9880d681SAndroid Build Coastguard Worker Constant *OffsetCst =
971*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
972*9880d681SAndroid Build Coastguard Worker Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
973*9880d681SAndroid Build Coastguard Worker OffsetCst);
974*9880d681SAndroid Build Coastguard Worker Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
975*9880d681SAndroid Build Coastguard Worker if (ConstantFoldLoadFromConstPtr(Src, LoadTy, DL))
976*9880d681SAndroid Build Coastguard Worker return Offset;
977*9880d681SAndroid Build Coastguard Worker return -1;
978*9880d681SAndroid Build Coastguard Worker }
979*9880d681SAndroid Build Coastguard Worker
980*9880d681SAndroid Build Coastguard Worker
981*9880d681SAndroid Build Coastguard Worker /// This function is called when we have a
982*9880d681SAndroid Build Coastguard Worker /// memdep query of a load that ends up being a clobbering store. This means
983*9880d681SAndroid Build Coastguard Worker /// that the store provides bits used by the load but we the pointers don't
984*9880d681SAndroid Build Coastguard Worker /// mustalias. Check this case to see if there is anything more we can do
985*9880d681SAndroid Build Coastguard Worker /// before we give up.
GetStoreValueForLoad(Value * SrcVal,unsigned Offset,Type * LoadTy,Instruction * InsertPt,const DataLayout & DL)986*9880d681SAndroid Build Coastguard Worker static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
987*9880d681SAndroid Build Coastguard Worker Type *LoadTy,
988*9880d681SAndroid Build Coastguard Worker Instruction *InsertPt, const DataLayout &DL){
989*9880d681SAndroid Build Coastguard Worker LLVMContext &Ctx = SrcVal->getType()->getContext();
990*9880d681SAndroid Build Coastguard Worker
991*9880d681SAndroid Build Coastguard Worker uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
992*9880d681SAndroid Build Coastguard Worker uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
993*9880d681SAndroid Build Coastguard Worker
994*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(InsertPt);
995*9880d681SAndroid Build Coastguard Worker
996*9880d681SAndroid Build Coastguard Worker // Compute which bits of the stored value are being used by the load. Convert
997*9880d681SAndroid Build Coastguard Worker // to an integer type to start with.
998*9880d681SAndroid Build Coastguard Worker if (SrcVal->getType()->getScalarType()->isPointerTy())
999*9880d681SAndroid Build Coastguard Worker SrcVal = Builder.CreatePtrToInt(SrcVal,
1000*9880d681SAndroid Build Coastguard Worker DL.getIntPtrType(SrcVal->getType()));
1001*9880d681SAndroid Build Coastguard Worker if (!SrcVal->getType()->isIntegerTy())
1002*9880d681SAndroid Build Coastguard Worker SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
1003*9880d681SAndroid Build Coastguard Worker
1004*9880d681SAndroid Build Coastguard Worker // Shift the bits to the least significant depending on endianness.
1005*9880d681SAndroid Build Coastguard Worker unsigned ShiftAmt;
1006*9880d681SAndroid Build Coastguard Worker if (DL.isLittleEndian())
1007*9880d681SAndroid Build Coastguard Worker ShiftAmt = Offset*8;
1008*9880d681SAndroid Build Coastguard Worker else
1009*9880d681SAndroid Build Coastguard Worker ShiftAmt = (StoreSize-LoadSize-Offset)*8;
1010*9880d681SAndroid Build Coastguard Worker
1011*9880d681SAndroid Build Coastguard Worker if (ShiftAmt)
1012*9880d681SAndroid Build Coastguard Worker SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
1013*9880d681SAndroid Build Coastguard Worker
1014*9880d681SAndroid Build Coastguard Worker if (LoadSize != StoreSize)
1015*9880d681SAndroid Build Coastguard Worker SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
1016*9880d681SAndroid Build Coastguard Worker
1017*9880d681SAndroid Build Coastguard Worker return CoerceAvailableValueToLoadType(SrcVal, LoadTy, Builder, DL);
1018*9880d681SAndroid Build Coastguard Worker }
1019*9880d681SAndroid Build Coastguard Worker
1020*9880d681SAndroid Build Coastguard Worker /// This function is called when we have a
1021*9880d681SAndroid Build Coastguard Worker /// memdep query of a load that ends up being a clobbering load. This means
1022*9880d681SAndroid Build Coastguard Worker /// that the load *may* provide bits used by the load but we can't be sure
1023*9880d681SAndroid Build Coastguard Worker /// because the pointers don't mustalias. Check this case to see if there is
1024*9880d681SAndroid Build Coastguard Worker /// anything more we can do before we give up.
GetLoadValueForLoad(LoadInst * SrcVal,unsigned Offset,Type * LoadTy,Instruction * InsertPt,GVN & gvn)1025*9880d681SAndroid Build Coastguard Worker static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
1026*9880d681SAndroid Build Coastguard Worker Type *LoadTy, Instruction *InsertPt,
1027*9880d681SAndroid Build Coastguard Worker GVN &gvn) {
1028*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = SrcVal->getModule()->getDataLayout();
1029*9880d681SAndroid Build Coastguard Worker // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
1030*9880d681SAndroid Build Coastguard Worker // widen SrcVal out to a larger load.
1031*9880d681SAndroid Build Coastguard Worker unsigned SrcValStoreSize = DL.getTypeStoreSize(SrcVal->getType());
1032*9880d681SAndroid Build Coastguard Worker unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
1033*9880d681SAndroid Build Coastguard Worker if (Offset+LoadSize > SrcValStoreSize) {
1034*9880d681SAndroid Build Coastguard Worker assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
1035*9880d681SAndroid Build Coastguard Worker assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
1036*9880d681SAndroid Build Coastguard Worker // If we have a load/load clobber an DepLI can be widened to cover this
1037*9880d681SAndroid Build Coastguard Worker // load, then we should widen it to the next power of 2 size big enough!
1038*9880d681SAndroid Build Coastguard Worker unsigned NewLoadSize = Offset+LoadSize;
1039*9880d681SAndroid Build Coastguard Worker if (!isPowerOf2_32(NewLoadSize))
1040*9880d681SAndroid Build Coastguard Worker NewLoadSize = NextPowerOf2(NewLoadSize);
1041*9880d681SAndroid Build Coastguard Worker
1042*9880d681SAndroid Build Coastguard Worker Value *PtrVal = SrcVal->getPointerOperand();
1043*9880d681SAndroid Build Coastguard Worker
1044*9880d681SAndroid Build Coastguard Worker // Insert the new load after the old load. This ensures that subsequent
1045*9880d681SAndroid Build Coastguard Worker // memdep queries will find the new load. We can't easily remove the old
1046*9880d681SAndroid Build Coastguard Worker // load completely because it is already in the value numbering table.
1047*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
1048*9880d681SAndroid Build Coastguard Worker Type *DestPTy =
1049*9880d681SAndroid Build Coastguard Worker IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1050*9880d681SAndroid Build Coastguard Worker DestPTy = PointerType::get(DestPTy,
1051*9880d681SAndroid Build Coastguard Worker PtrVal->getType()->getPointerAddressSpace());
1052*9880d681SAndroid Build Coastguard Worker Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
1053*9880d681SAndroid Build Coastguard Worker PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1054*9880d681SAndroid Build Coastguard Worker LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1055*9880d681SAndroid Build Coastguard Worker NewLoad->takeName(SrcVal);
1056*9880d681SAndroid Build Coastguard Worker NewLoad->setAlignment(SrcVal->getAlignment());
1057*9880d681SAndroid Build Coastguard Worker
1058*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1059*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1060*9880d681SAndroid Build Coastguard Worker
1061*9880d681SAndroid Build Coastguard Worker // Replace uses of the original load with the wider load. On a big endian
1062*9880d681SAndroid Build Coastguard Worker // system, we need to shift down to get the relevant bits.
1063*9880d681SAndroid Build Coastguard Worker Value *RV = NewLoad;
1064*9880d681SAndroid Build Coastguard Worker if (DL.isBigEndian())
1065*9880d681SAndroid Build Coastguard Worker RV = Builder.CreateLShr(RV, (NewLoadSize - SrcValStoreSize) * 8);
1066*9880d681SAndroid Build Coastguard Worker RV = Builder.CreateTrunc(RV, SrcVal->getType());
1067*9880d681SAndroid Build Coastguard Worker SrcVal->replaceAllUsesWith(RV);
1068*9880d681SAndroid Build Coastguard Worker
1069*9880d681SAndroid Build Coastguard Worker // We would like to use gvn.markInstructionForDeletion here, but we can't
1070*9880d681SAndroid Build Coastguard Worker // because the load is already memoized into the leader map table that GVN
1071*9880d681SAndroid Build Coastguard Worker // tracks. It is potentially possible to remove the load from the table,
1072*9880d681SAndroid Build Coastguard Worker // but then there all of the operations based on it would need to be
1073*9880d681SAndroid Build Coastguard Worker // rehashed. Just leave the dead load around.
1074*9880d681SAndroid Build Coastguard Worker gvn.getMemDep().removeInstruction(SrcVal);
1075*9880d681SAndroid Build Coastguard Worker SrcVal = NewLoad;
1076*9880d681SAndroid Build Coastguard Worker }
1077*9880d681SAndroid Build Coastguard Worker
1078*9880d681SAndroid Build Coastguard Worker return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
1079*9880d681SAndroid Build Coastguard Worker }
1080*9880d681SAndroid Build Coastguard Worker
1081*9880d681SAndroid Build Coastguard Worker
1082*9880d681SAndroid Build Coastguard Worker /// This function is called when we have a
1083*9880d681SAndroid Build Coastguard Worker /// memdep query of a load that ends up being a clobbering mem intrinsic.
GetMemInstValueForLoad(MemIntrinsic * SrcInst,unsigned Offset,Type * LoadTy,Instruction * InsertPt,const DataLayout & DL)1084*9880d681SAndroid Build Coastguard Worker static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
1085*9880d681SAndroid Build Coastguard Worker Type *LoadTy, Instruction *InsertPt,
1086*9880d681SAndroid Build Coastguard Worker const DataLayout &DL){
1087*9880d681SAndroid Build Coastguard Worker LLVMContext &Ctx = LoadTy->getContext();
1088*9880d681SAndroid Build Coastguard Worker uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
1089*9880d681SAndroid Build Coastguard Worker
1090*9880d681SAndroid Build Coastguard Worker IRBuilder<> Builder(InsertPt);
1091*9880d681SAndroid Build Coastguard Worker
1092*9880d681SAndroid Build Coastguard Worker // We know that this method is only called when the mem transfer fully
1093*9880d681SAndroid Build Coastguard Worker // provides the bits for the load.
1094*9880d681SAndroid Build Coastguard Worker if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1095*9880d681SAndroid Build Coastguard Worker // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1096*9880d681SAndroid Build Coastguard Worker // independently of what the offset is.
1097*9880d681SAndroid Build Coastguard Worker Value *Val = MSI->getValue();
1098*9880d681SAndroid Build Coastguard Worker if (LoadSize != 1)
1099*9880d681SAndroid Build Coastguard Worker Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1100*9880d681SAndroid Build Coastguard Worker
1101*9880d681SAndroid Build Coastguard Worker Value *OneElt = Val;
1102*9880d681SAndroid Build Coastguard Worker
1103*9880d681SAndroid Build Coastguard Worker // Splat the value out to the right number of bits.
1104*9880d681SAndroid Build Coastguard Worker for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1105*9880d681SAndroid Build Coastguard Worker // If we can double the number of bytes set, do it.
1106*9880d681SAndroid Build Coastguard Worker if (NumBytesSet*2 <= LoadSize) {
1107*9880d681SAndroid Build Coastguard Worker Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1108*9880d681SAndroid Build Coastguard Worker Val = Builder.CreateOr(Val, ShVal);
1109*9880d681SAndroid Build Coastguard Worker NumBytesSet <<= 1;
1110*9880d681SAndroid Build Coastguard Worker continue;
1111*9880d681SAndroid Build Coastguard Worker }
1112*9880d681SAndroid Build Coastguard Worker
1113*9880d681SAndroid Build Coastguard Worker // Otherwise insert one byte at a time.
1114*9880d681SAndroid Build Coastguard Worker Value *ShVal = Builder.CreateShl(Val, 1*8);
1115*9880d681SAndroid Build Coastguard Worker Val = Builder.CreateOr(OneElt, ShVal);
1116*9880d681SAndroid Build Coastguard Worker ++NumBytesSet;
1117*9880d681SAndroid Build Coastguard Worker }
1118*9880d681SAndroid Build Coastguard Worker
1119*9880d681SAndroid Build Coastguard Worker return CoerceAvailableValueToLoadType(Val, LoadTy, Builder, DL);
1120*9880d681SAndroid Build Coastguard Worker }
1121*9880d681SAndroid Build Coastguard Worker
1122*9880d681SAndroid Build Coastguard Worker // Otherwise, this is a memcpy/memmove from a constant global.
1123*9880d681SAndroid Build Coastguard Worker MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1124*9880d681SAndroid Build Coastguard Worker Constant *Src = cast<Constant>(MTI->getSource());
1125*9880d681SAndroid Build Coastguard Worker unsigned AS = Src->getType()->getPointerAddressSpace();
1126*9880d681SAndroid Build Coastguard Worker
1127*9880d681SAndroid Build Coastguard Worker // Otherwise, see if we can constant fold a load from the constant with the
1128*9880d681SAndroid Build Coastguard Worker // offset applied as appropriate.
1129*9880d681SAndroid Build Coastguard Worker Src = ConstantExpr::getBitCast(Src,
1130*9880d681SAndroid Build Coastguard Worker Type::getInt8PtrTy(Src->getContext(), AS));
1131*9880d681SAndroid Build Coastguard Worker Constant *OffsetCst =
1132*9880d681SAndroid Build Coastguard Worker ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1133*9880d681SAndroid Build Coastguard Worker Src = ConstantExpr::getGetElementPtr(Type::getInt8Ty(Src->getContext()), Src,
1134*9880d681SAndroid Build Coastguard Worker OffsetCst);
1135*9880d681SAndroid Build Coastguard Worker Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
1136*9880d681SAndroid Build Coastguard Worker return ConstantFoldLoadFromConstPtr(Src, LoadTy, DL);
1137*9880d681SAndroid Build Coastguard Worker }
1138*9880d681SAndroid Build Coastguard Worker
1139*9880d681SAndroid Build Coastguard Worker
1140*9880d681SAndroid Build Coastguard Worker /// Given a set of loads specified by ValuesPerBlock,
1141*9880d681SAndroid Build Coastguard Worker /// construct SSA form, allowing us to eliminate LI. This returns the value
1142*9880d681SAndroid Build Coastguard Worker /// that should be used at LI's definition site.
ConstructSSAForLoadSet(LoadInst * LI,SmallVectorImpl<AvailableValueInBlock> & ValuesPerBlock,GVN & gvn)1143*9880d681SAndroid Build Coastguard Worker static Value *ConstructSSAForLoadSet(LoadInst *LI,
1144*9880d681SAndroid Build Coastguard Worker SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1145*9880d681SAndroid Build Coastguard Worker GVN &gvn) {
1146*9880d681SAndroid Build Coastguard Worker // Check for the fully redundant, dominating load case. In this case, we can
1147*9880d681SAndroid Build Coastguard Worker // just use the dominating value directly.
1148*9880d681SAndroid Build Coastguard Worker if (ValuesPerBlock.size() == 1 &&
1149*9880d681SAndroid Build Coastguard Worker gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1150*9880d681SAndroid Build Coastguard Worker LI->getParent())) {
1151*9880d681SAndroid Build Coastguard Worker assert(!ValuesPerBlock[0].AV.isUndefValue() &&
1152*9880d681SAndroid Build Coastguard Worker "Dead BB dominate this block");
1153*9880d681SAndroid Build Coastguard Worker return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn);
1154*9880d681SAndroid Build Coastguard Worker }
1155*9880d681SAndroid Build Coastguard Worker
1156*9880d681SAndroid Build Coastguard Worker // Otherwise, we have to construct SSA form.
1157*9880d681SAndroid Build Coastguard Worker SmallVector<PHINode*, 8> NewPHIs;
1158*9880d681SAndroid Build Coastguard Worker SSAUpdater SSAUpdate(&NewPHIs);
1159*9880d681SAndroid Build Coastguard Worker SSAUpdate.Initialize(LI->getType(), LI->getName());
1160*9880d681SAndroid Build Coastguard Worker
1161*9880d681SAndroid Build Coastguard Worker for (const AvailableValueInBlock &AV : ValuesPerBlock) {
1162*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = AV.BB;
1163*9880d681SAndroid Build Coastguard Worker
1164*9880d681SAndroid Build Coastguard Worker if (SSAUpdate.HasValueForBlock(BB))
1165*9880d681SAndroid Build Coastguard Worker continue;
1166*9880d681SAndroid Build Coastguard Worker
1167*9880d681SAndroid Build Coastguard Worker SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LI, gvn));
1168*9880d681SAndroid Build Coastguard Worker }
1169*9880d681SAndroid Build Coastguard Worker
1170*9880d681SAndroid Build Coastguard Worker // Perform PHI construction.
1171*9880d681SAndroid Build Coastguard Worker return SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1172*9880d681SAndroid Build Coastguard Worker }
1173*9880d681SAndroid Build Coastguard Worker
MaterializeAdjustedValue(LoadInst * LI,Instruction * InsertPt,GVN & gvn) const1174*9880d681SAndroid Build Coastguard Worker Value *AvailableValue::MaterializeAdjustedValue(LoadInst *LI,
1175*9880d681SAndroid Build Coastguard Worker Instruction *InsertPt,
1176*9880d681SAndroid Build Coastguard Worker GVN &gvn) const {
1177*9880d681SAndroid Build Coastguard Worker Value *Res;
1178*9880d681SAndroid Build Coastguard Worker Type *LoadTy = LI->getType();
1179*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = LI->getModule()->getDataLayout();
1180*9880d681SAndroid Build Coastguard Worker if (isSimpleValue()) {
1181*9880d681SAndroid Build Coastguard Worker Res = getSimpleValue();
1182*9880d681SAndroid Build Coastguard Worker if (Res->getType() != LoadTy) {
1183*9880d681SAndroid Build Coastguard Worker Res = GetStoreValueForLoad(Res, Offset, LoadTy, InsertPt, DL);
1184*9880d681SAndroid Build Coastguard Worker
1185*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
1186*9880d681SAndroid Build Coastguard Worker << *getSimpleValue() << '\n'
1187*9880d681SAndroid Build Coastguard Worker << *Res << '\n' << "\n\n\n");
1188*9880d681SAndroid Build Coastguard Worker }
1189*9880d681SAndroid Build Coastguard Worker } else if (isCoercedLoadValue()) {
1190*9880d681SAndroid Build Coastguard Worker LoadInst *Load = getCoercedLoadValue();
1191*9880d681SAndroid Build Coastguard Worker if (Load->getType() == LoadTy && Offset == 0) {
1192*9880d681SAndroid Build Coastguard Worker Res = Load;
1193*9880d681SAndroid Build Coastguard Worker } else {
1194*9880d681SAndroid Build Coastguard Worker Res = GetLoadValueForLoad(Load, Offset, LoadTy, InsertPt, gvn);
1195*9880d681SAndroid Build Coastguard Worker
1196*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
1197*9880d681SAndroid Build Coastguard Worker << *getCoercedLoadValue() << '\n'
1198*9880d681SAndroid Build Coastguard Worker << *Res << '\n' << "\n\n\n");
1199*9880d681SAndroid Build Coastguard Worker }
1200*9880d681SAndroid Build Coastguard Worker } else if (isMemIntrinValue()) {
1201*9880d681SAndroid Build Coastguard Worker Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy,
1202*9880d681SAndroid Build Coastguard Worker InsertPt, DL);
1203*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1204*9880d681SAndroid Build Coastguard Worker << " " << *getMemIntrinValue() << '\n'
1205*9880d681SAndroid Build Coastguard Worker << *Res << '\n' << "\n\n\n");
1206*9880d681SAndroid Build Coastguard Worker } else {
1207*9880d681SAndroid Build Coastguard Worker assert(isUndefValue() && "Should be UndefVal");
1208*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
1209*9880d681SAndroid Build Coastguard Worker return UndefValue::get(LoadTy);
1210*9880d681SAndroid Build Coastguard Worker }
1211*9880d681SAndroid Build Coastguard Worker assert(Res && "failed to materialize?");
1212*9880d681SAndroid Build Coastguard Worker return Res;
1213*9880d681SAndroid Build Coastguard Worker }
1214*9880d681SAndroid Build Coastguard Worker
isLifetimeStart(const Instruction * Inst)1215*9880d681SAndroid Build Coastguard Worker static bool isLifetimeStart(const Instruction *Inst) {
1216*9880d681SAndroid Build Coastguard Worker if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1217*9880d681SAndroid Build Coastguard Worker return II->getIntrinsicID() == Intrinsic::lifetime_start;
1218*9880d681SAndroid Build Coastguard Worker return false;
1219*9880d681SAndroid Build Coastguard Worker }
1220*9880d681SAndroid Build Coastguard Worker
AnalyzeLoadAvailability(LoadInst * LI,MemDepResult DepInfo,Value * Address,AvailableValue & Res)1221*9880d681SAndroid Build Coastguard Worker bool GVN::AnalyzeLoadAvailability(LoadInst *LI, MemDepResult DepInfo,
1222*9880d681SAndroid Build Coastguard Worker Value *Address, AvailableValue &Res) {
1223*9880d681SAndroid Build Coastguard Worker
1224*9880d681SAndroid Build Coastguard Worker assert((DepInfo.isDef() || DepInfo.isClobber()) &&
1225*9880d681SAndroid Build Coastguard Worker "expected a local dependence");
1226*9880d681SAndroid Build Coastguard Worker assert(LI->isUnordered() && "rules below are incorrect for ordered access");
1227*9880d681SAndroid Build Coastguard Worker
1228*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = LI->getModule()->getDataLayout();
1229*9880d681SAndroid Build Coastguard Worker
1230*9880d681SAndroid Build Coastguard Worker if (DepInfo.isClobber()) {
1231*9880d681SAndroid Build Coastguard Worker // If the dependence is to a store that writes to a superset of the bits
1232*9880d681SAndroid Build Coastguard Worker // read by the load, we can extract the bits we need for the load from the
1233*9880d681SAndroid Build Coastguard Worker // stored value.
1234*9880d681SAndroid Build Coastguard Worker if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1235*9880d681SAndroid Build Coastguard Worker // Can't forward from non-atomic to atomic without violating memory model.
1236*9880d681SAndroid Build Coastguard Worker if (Address && LI->isAtomic() <= DepSI->isAtomic()) {
1237*9880d681SAndroid Build Coastguard Worker int Offset =
1238*9880d681SAndroid Build Coastguard Worker AnalyzeLoadFromClobberingStore(LI->getType(), Address, DepSI);
1239*9880d681SAndroid Build Coastguard Worker if (Offset != -1) {
1240*9880d681SAndroid Build Coastguard Worker Res = AvailableValue::get(DepSI->getValueOperand(), Offset);
1241*9880d681SAndroid Build Coastguard Worker return true;
1242*9880d681SAndroid Build Coastguard Worker }
1243*9880d681SAndroid Build Coastguard Worker }
1244*9880d681SAndroid Build Coastguard Worker }
1245*9880d681SAndroid Build Coastguard Worker
1246*9880d681SAndroid Build Coastguard Worker // Check to see if we have something like this:
1247*9880d681SAndroid Build Coastguard Worker // load i32* P
1248*9880d681SAndroid Build Coastguard Worker // load i8* (P+1)
1249*9880d681SAndroid Build Coastguard Worker // if we have this, replace the later with an extraction from the former.
1250*9880d681SAndroid Build Coastguard Worker if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1251*9880d681SAndroid Build Coastguard Worker // If this is a clobber and L is the first instruction in its block, then
1252*9880d681SAndroid Build Coastguard Worker // we have the first instruction in the entry block.
1253*9880d681SAndroid Build Coastguard Worker // Can't forward from non-atomic to atomic without violating memory model.
1254*9880d681SAndroid Build Coastguard Worker if (DepLI != LI && Address && LI->isAtomic() <= DepLI->isAtomic()) {
1255*9880d681SAndroid Build Coastguard Worker int Offset =
1256*9880d681SAndroid Build Coastguard Worker AnalyzeLoadFromClobberingLoad(LI->getType(), Address, DepLI, DL);
1257*9880d681SAndroid Build Coastguard Worker
1258*9880d681SAndroid Build Coastguard Worker if (Offset != -1) {
1259*9880d681SAndroid Build Coastguard Worker Res = AvailableValue::getLoad(DepLI, Offset);
1260*9880d681SAndroid Build Coastguard Worker return true;
1261*9880d681SAndroid Build Coastguard Worker }
1262*9880d681SAndroid Build Coastguard Worker }
1263*9880d681SAndroid Build Coastguard Worker }
1264*9880d681SAndroid Build Coastguard Worker
1265*9880d681SAndroid Build Coastguard Worker // If the clobbering value is a memset/memcpy/memmove, see if we can
1266*9880d681SAndroid Build Coastguard Worker // forward a value on from it.
1267*9880d681SAndroid Build Coastguard Worker if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
1268*9880d681SAndroid Build Coastguard Worker if (Address && !LI->isAtomic()) {
1269*9880d681SAndroid Build Coastguard Worker int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
1270*9880d681SAndroid Build Coastguard Worker DepMI, DL);
1271*9880d681SAndroid Build Coastguard Worker if (Offset != -1) {
1272*9880d681SAndroid Build Coastguard Worker Res = AvailableValue::getMI(DepMI, Offset);
1273*9880d681SAndroid Build Coastguard Worker return true;
1274*9880d681SAndroid Build Coastguard Worker }
1275*9880d681SAndroid Build Coastguard Worker }
1276*9880d681SAndroid Build Coastguard Worker }
1277*9880d681SAndroid Build Coastguard Worker // Nothing known about this clobber, have to be conservative
1278*9880d681SAndroid Build Coastguard Worker DEBUG(
1279*9880d681SAndroid Build Coastguard Worker // fast print dep, using operator<< on instruction is too slow.
1280*9880d681SAndroid Build Coastguard Worker dbgs() << "GVN: load ";
1281*9880d681SAndroid Build Coastguard Worker LI->printAsOperand(dbgs());
1282*9880d681SAndroid Build Coastguard Worker Instruction *I = DepInfo.getInst();
1283*9880d681SAndroid Build Coastguard Worker dbgs() << " is clobbered by " << *I << '\n';
1284*9880d681SAndroid Build Coastguard Worker );
1285*9880d681SAndroid Build Coastguard Worker return false;
1286*9880d681SAndroid Build Coastguard Worker }
1287*9880d681SAndroid Build Coastguard Worker assert(DepInfo.isDef() && "follows from above");
1288*9880d681SAndroid Build Coastguard Worker
1289*9880d681SAndroid Build Coastguard Worker Instruction *DepInst = DepInfo.getInst();
1290*9880d681SAndroid Build Coastguard Worker
1291*9880d681SAndroid Build Coastguard Worker // Loading the allocation -> undef.
1292*9880d681SAndroid Build Coastguard Worker if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
1293*9880d681SAndroid Build Coastguard Worker // Loading immediately after lifetime begin -> undef.
1294*9880d681SAndroid Build Coastguard Worker isLifetimeStart(DepInst)) {
1295*9880d681SAndroid Build Coastguard Worker Res = AvailableValue::get(UndefValue::get(LI->getType()));
1296*9880d681SAndroid Build Coastguard Worker return true;
1297*9880d681SAndroid Build Coastguard Worker }
1298*9880d681SAndroid Build Coastguard Worker
1299*9880d681SAndroid Build Coastguard Worker // Loading from calloc (which zero initializes memory) -> zero
1300*9880d681SAndroid Build Coastguard Worker if (isCallocLikeFn(DepInst, TLI)) {
1301*9880d681SAndroid Build Coastguard Worker Res = AvailableValue::get(Constant::getNullValue(LI->getType()));
1302*9880d681SAndroid Build Coastguard Worker return true;
1303*9880d681SAndroid Build Coastguard Worker }
1304*9880d681SAndroid Build Coastguard Worker
1305*9880d681SAndroid Build Coastguard Worker if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1306*9880d681SAndroid Build Coastguard Worker // Reject loads and stores that are to the same address but are of
1307*9880d681SAndroid Build Coastguard Worker // different types if we have to. If the stored value is larger or equal to
1308*9880d681SAndroid Build Coastguard Worker // the loaded value, we can reuse it.
1309*9880d681SAndroid Build Coastguard Worker if (S->getValueOperand()->getType() != LI->getType() &&
1310*9880d681SAndroid Build Coastguard Worker !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
1311*9880d681SAndroid Build Coastguard Worker LI->getType(), DL))
1312*9880d681SAndroid Build Coastguard Worker return false;
1313*9880d681SAndroid Build Coastguard Worker
1314*9880d681SAndroid Build Coastguard Worker // Can't forward from non-atomic to atomic without violating memory model.
1315*9880d681SAndroid Build Coastguard Worker if (S->isAtomic() < LI->isAtomic())
1316*9880d681SAndroid Build Coastguard Worker return false;
1317*9880d681SAndroid Build Coastguard Worker
1318*9880d681SAndroid Build Coastguard Worker Res = AvailableValue::get(S->getValueOperand());
1319*9880d681SAndroid Build Coastguard Worker return true;
1320*9880d681SAndroid Build Coastguard Worker }
1321*9880d681SAndroid Build Coastguard Worker
1322*9880d681SAndroid Build Coastguard Worker if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1323*9880d681SAndroid Build Coastguard Worker // If the types mismatch and we can't handle it, reject reuse of the load.
1324*9880d681SAndroid Build Coastguard Worker // If the stored value is larger or equal to the loaded value, we can reuse
1325*9880d681SAndroid Build Coastguard Worker // it.
1326*9880d681SAndroid Build Coastguard Worker if (LD->getType() != LI->getType() &&
1327*9880d681SAndroid Build Coastguard Worker !CanCoerceMustAliasedValueToLoad(LD, LI->getType(), DL))
1328*9880d681SAndroid Build Coastguard Worker return false;
1329*9880d681SAndroid Build Coastguard Worker
1330*9880d681SAndroid Build Coastguard Worker // Can't forward from non-atomic to atomic without violating memory model.
1331*9880d681SAndroid Build Coastguard Worker if (LD->isAtomic() < LI->isAtomic())
1332*9880d681SAndroid Build Coastguard Worker return false;
1333*9880d681SAndroid Build Coastguard Worker
1334*9880d681SAndroid Build Coastguard Worker Res = AvailableValue::getLoad(LD);
1335*9880d681SAndroid Build Coastguard Worker return true;
1336*9880d681SAndroid Build Coastguard Worker }
1337*9880d681SAndroid Build Coastguard Worker
1338*9880d681SAndroid Build Coastguard Worker // Unknown def - must be conservative
1339*9880d681SAndroid Build Coastguard Worker DEBUG(
1340*9880d681SAndroid Build Coastguard Worker // fast print dep, using operator<< on instruction is too slow.
1341*9880d681SAndroid Build Coastguard Worker dbgs() << "GVN: load ";
1342*9880d681SAndroid Build Coastguard Worker LI->printAsOperand(dbgs());
1343*9880d681SAndroid Build Coastguard Worker dbgs() << " has unknown def " << *DepInst << '\n';
1344*9880d681SAndroid Build Coastguard Worker );
1345*9880d681SAndroid Build Coastguard Worker return false;
1346*9880d681SAndroid Build Coastguard Worker }
1347*9880d681SAndroid Build Coastguard Worker
AnalyzeLoadAvailability(LoadInst * LI,LoadDepVect & Deps,AvailValInBlkVect & ValuesPerBlock,UnavailBlkVect & UnavailableBlocks)1348*9880d681SAndroid Build Coastguard Worker void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
1349*9880d681SAndroid Build Coastguard Worker AvailValInBlkVect &ValuesPerBlock,
1350*9880d681SAndroid Build Coastguard Worker UnavailBlkVect &UnavailableBlocks) {
1351*9880d681SAndroid Build Coastguard Worker
1352*9880d681SAndroid Build Coastguard Worker // Filter out useless results (non-locals, etc). Keep track of the blocks
1353*9880d681SAndroid Build Coastguard Worker // where we have a value available in repl, also keep track of whether we see
1354*9880d681SAndroid Build Coastguard Worker // dependencies that produce an unknown value for the load (such as a call
1355*9880d681SAndroid Build Coastguard Worker // that could potentially clobber the load).
1356*9880d681SAndroid Build Coastguard Worker unsigned NumDeps = Deps.size();
1357*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = NumDeps; i != e; ++i) {
1358*9880d681SAndroid Build Coastguard Worker BasicBlock *DepBB = Deps[i].getBB();
1359*9880d681SAndroid Build Coastguard Worker MemDepResult DepInfo = Deps[i].getResult();
1360*9880d681SAndroid Build Coastguard Worker
1361*9880d681SAndroid Build Coastguard Worker if (DeadBlocks.count(DepBB)) {
1362*9880d681SAndroid Build Coastguard Worker // Dead dependent mem-op disguise as a load evaluating the same value
1363*9880d681SAndroid Build Coastguard Worker // as the load in question.
1364*9880d681SAndroid Build Coastguard Worker ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
1365*9880d681SAndroid Build Coastguard Worker continue;
1366*9880d681SAndroid Build Coastguard Worker }
1367*9880d681SAndroid Build Coastguard Worker
1368*9880d681SAndroid Build Coastguard Worker if (!DepInfo.isDef() && !DepInfo.isClobber()) {
1369*9880d681SAndroid Build Coastguard Worker UnavailableBlocks.push_back(DepBB);
1370*9880d681SAndroid Build Coastguard Worker continue;
1371*9880d681SAndroid Build Coastguard Worker }
1372*9880d681SAndroid Build Coastguard Worker
1373*9880d681SAndroid Build Coastguard Worker // The address being loaded in this non-local block may not be the same as
1374*9880d681SAndroid Build Coastguard Worker // the pointer operand of the load if PHI translation occurs. Make sure
1375*9880d681SAndroid Build Coastguard Worker // to consider the right address.
1376*9880d681SAndroid Build Coastguard Worker Value *Address = Deps[i].getAddress();
1377*9880d681SAndroid Build Coastguard Worker
1378*9880d681SAndroid Build Coastguard Worker AvailableValue AV;
1379*9880d681SAndroid Build Coastguard Worker if (AnalyzeLoadAvailability(LI, DepInfo, Address, AV)) {
1380*9880d681SAndroid Build Coastguard Worker // subtlety: because we know this was a non-local dependency, we know
1381*9880d681SAndroid Build Coastguard Worker // it's safe to materialize anywhere between the instruction within
1382*9880d681SAndroid Build Coastguard Worker // DepInfo and the end of it's block.
1383*9880d681SAndroid Build Coastguard Worker ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1384*9880d681SAndroid Build Coastguard Worker std::move(AV)));
1385*9880d681SAndroid Build Coastguard Worker } else {
1386*9880d681SAndroid Build Coastguard Worker UnavailableBlocks.push_back(DepBB);
1387*9880d681SAndroid Build Coastguard Worker }
1388*9880d681SAndroid Build Coastguard Worker }
1389*9880d681SAndroid Build Coastguard Worker
1390*9880d681SAndroid Build Coastguard Worker assert(NumDeps == ValuesPerBlock.size() + UnavailableBlocks.size() &&
1391*9880d681SAndroid Build Coastguard Worker "post condition violation");
1392*9880d681SAndroid Build Coastguard Worker }
1393*9880d681SAndroid Build Coastguard Worker
PerformLoadPRE(LoadInst * LI,AvailValInBlkVect & ValuesPerBlock,UnavailBlkVect & UnavailableBlocks)1394*9880d681SAndroid Build Coastguard Worker bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
1395*9880d681SAndroid Build Coastguard Worker UnavailBlkVect &UnavailableBlocks) {
1396*9880d681SAndroid Build Coastguard Worker // Okay, we have *some* definitions of the value. This means that the value
1397*9880d681SAndroid Build Coastguard Worker // is available in some of our (transitive) predecessors. Lets think about
1398*9880d681SAndroid Build Coastguard Worker // doing PRE of this load. This will involve inserting a new load into the
1399*9880d681SAndroid Build Coastguard Worker // predecessor when it's not available. We could do this in general, but
1400*9880d681SAndroid Build Coastguard Worker // prefer to not increase code size. As such, we only do this when we know
1401*9880d681SAndroid Build Coastguard Worker // that we only have to insert *one* load (which means we're basically moving
1402*9880d681SAndroid Build Coastguard Worker // the load, not inserting a new one).
1403*9880d681SAndroid Build Coastguard Worker
1404*9880d681SAndroid Build Coastguard Worker SmallPtrSet<BasicBlock *, 4> Blockers(UnavailableBlocks.begin(),
1405*9880d681SAndroid Build Coastguard Worker UnavailableBlocks.end());
1406*9880d681SAndroid Build Coastguard Worker
1407*9880d681SAndroid Build Coastguard Worker // Let's find the first basic block with more than one predecessor. Walk
1408*9880d681SAndroid Build Coastguard Worker // backwards through predecessors if needed.
1409*9880d681SAndroid Build Coastguard Worker BasicBlock *LoadBB = LI->getParent();
1410*9880d681SAndroid Build Coastguard Worker BasicBlock *TmpBB = LoadBB;
1411*9880d681SAndroid Build Coastguard Worker
1412*9880d681SAndroid Build Coastguard Worker while (TmpBB->getSinglePredecessor()) {
1413*9880d681SAndroid Build Coastguard Worker TmpBB = TmpBB->getSinglePredecessor();
1414*9880d681SAndroid Build Coastguard Worker if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1415*9880d681SAndroid Build Coastguard Worker return false;
1416*9880d681SAndroid Build Coastguard Worker if (Blockers.count(TmpBB))
1417*9880d681SAndroid Build Coastguard Worker return false;
1418*9880d681SAndroid Build Coastguard Worker
1419*9880d681SAndroid Build Coastguard Worker // If any of these blocks has more than one successor (i.e. if the edge we
1420*9880d681SAndroid Build Coastguard Worker // just traversed was critical), then there are other paths through this
1421*9880d681SAndroid Build Coastguard Worker // block along which the load may not be anticipated. Hoisting the load
1422*9880d681SAndroid Build Coastguard Worker // above this block would be adding the load to execution paths along
1423*9880d681SAndroid Build Coastguard Worker // which it was not previously executed.
1424*9880d681SAndroid Build Coastguard Worker if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1425*9880d681SAndroid Build Coastguard Worker return false;
1426*9880d681SAndroid Build Coastguard Worker }
1427*9880d681SAndroid Build Coastguard Worker
1428*9880d681SAndroid Build Coastguard Worker assert(TmpBB);
1429*9880d681SAndroid Build Coastguard Worker LoadBB = TmpBB;
1430*9880d681SAndroid Build Coastguard Worker
1431*9880d681SAndroid Build Coastguard Worker // Check to see how many predecessors have the loaded value fully
1432*9880d681SAndroid Build Coastguard Worker // available.
1433*9880d681SAndroid Build Coastguard Worker MapVector<BasicBlock *, Value *> PredLoads;
1434*9880d681SAndroid Build Coastguard Worker DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1435*9880d681SAndroid Build Coastguard Worker for (const AvailableValueInBlock &AV : ValuesPerBlock)
1436*9880d681SAndroid Build Coastguard Worker FullyAvailableBlocks[AV.BB] = true;
1437*9880d681SAndroid Build Coastguard Worker for (BasicBlock *UnavailableBB : UnavailableBlocks)
1438*9880d681SAndroid Build Coastguard Worker FullyAvailableBlocks[UnavailableBB] = false;
1439*9880d681SAndroid Build Coastguard Worker
1440*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 4> CriticalEdgePred;
1441*9880d681SAndroid Build Coastguard Worker for (BasicBlock *Pred : predecessors(LoadBB)) {
1442*9880d681SAndroid Build Coastguard Worker // If any predecessor block is an EH pad that does not allow non-PHI
1443*9880d681SAndroid Build Coastguard Worker // instructions before the terminator, we can't PRE the load.
1444*9880d681SAndroid Build Coastguard Worker if (Pred->getTerminator()->isEHPad()) {
1445*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs()
1446*9880d681SAndroid Build Coastguard Worker << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '"
1447*9880d681SAndroid Build Coastguard Worker << Pred->getName() << "': " << *LI << '\n');
1448*9880d681SAndroid Build Coastguard Worker return false;
1449*9880d681SAndroid Build Coastguard Worker }
1450*9880d681SAndroid Build Coastguard Worker
1451*9880d681SAndroid Build Coastguard Worker if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
1452*9880d681SAndroid Build Coastguard Worker continue;
1453*9880d681SAndroid Build Coastguard Worker }
1454*9880d681SAndroid Build Coastguard Worker
1455*9880d681SAndroid Build Coastguard Worker if (Pred->getTerminator()->getNumSuccessors() != 1) {
1456*9880d681SAndroid Build Coastguard Worker if (isa<IndirectBrInst>(Pred->getTerminator())) {
1457*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1458*9880d681SAndroid Build Coastguard Worker << Pred->getName() << "': " << *LI << '\n');
1459*9880d681SAndroid Build Coastguard Worker return false;
1460*9880d681SAndroid Build Coastguard Worker }
1461*9880d681SAndroid Build Coastguard Worker
1462*9880d681SAndroid Build Coastguard Worker if (LoadBB->isEHPad()) {
1463*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs()
1464*9880d681SAndroid Build Coastguard Worker << "COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '"
1465*9880d681SAndroid Build Coastguard Worker << Pred->getName() << "': " << *LI << '\n');
1466*9880d681SAndroid Build Coastguard Worker return false;
1467*9880d681SAndroid Build Coastguard Worker }
1468*9880d681SAndroid Build Coastguard Worker
1469*9880d681SAndroid Build Coastguard Worker CriticalEdgePred.push_back(Pred);
1470*9880d681SAndroid Build Coastguard Worker } else {
1471*9880d681SAndroid Build Coastguard Worker // Only add the predecessors that will not be split for now.
1472*9880d681SAndroid Build Coastguard Worker PredLoads[Pred] = nullptr;
1473*9880d681SAndroid Build Coastguard Worker }
1474*9880d681SAndroid Build Coastguard Worker }
1475*9880d681SAndroid Build Coastguard Worker
1476*9880d681SAndroid Build Coastguard Worker // Decide whether PRE is profitable for this load.
1477*9880d681SAndroid Build Coastguard Worker unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size();
1478*9880d681SAndroid Build Coastguard Worker assert(NumUnavailablePreds != 0 &&
1479*9880d681SAndroid Build Coastguard Worker "Fully available value should already be eliminated!");
1480*9880d681SAndroid Build Coastguard Worker
1481*9880d681SAndroid Build Coastguard Worker // If this load is unavailable in multiple predecessors, reject it.
1482*9880d681SAndroid Build Coastguard Worker // FIXME: If we could restructure the CFG, we could make a common pred with
1483*9880d681SAndroid Build Coastguard Worker // all the preds that don't have an available LI and insert a new load into
1484*9880d681SAndroid Build Coastguard Worker // that one block.
1485*9880d681SAndroid Build Coastguard Worker if (NumUnavailablePreds != 1)
1486*9880d681SAndroid Build Coastguard Worker return false;
1487*9880d681SAndroid Build Coastguard Worker
1488*9880d681SAndroid Build Coastguard Worker // Split critical edges, and update the unavailable predecessors accordingly.
1489*9880d681SAndroid Build Coastguard Worker for (BasicBlock *OrigPred : CriticalEdgePred) {
1490*9880d681SAndroid Build Coastguard Worker BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
1491*9880d681SAndroid Build Coastguard Worker assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
1492*9880d681SAndroid Build Coastguard Worker PredLoads[NewPred] = nullptr;
1493*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
1494*9880d681SAndroid Build Coastguard Worker << LoadBB->getName() << '\n');
1495*9880d681SAndroid Build Coastguard Worker }
1496*9880d681SAndroid Build Coastguard Worker
1497*9880d681SAndroid Build Coastguard Worker // Check if the load can safely be moved to all the unavailable predecessors.
1498*9880d681SAndroid Build Coastguard Worker bool CanDoPRE = true;
1499*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = LI->getModule()->getDataLayout();
1500*9880d681SAndroid Build Coastguard Worker SmallVector<Instruction*, 8> NewInsts;
1501*9880d681SAndroid Build Coastguard Worker for (auto &PredLoad : PredLoads) {
1502*9880d681SAndroid Build Coastguard Worker BasicBlock *UnavailablePred = PredLoad.first;
1503*9880d681SAndroid Build Coastguard Worker
1504*9880d681SAndroid Build Coastguard Worker // Do PHI translation to get its value in the predecessor if necessary. The
1505*9880d681SAndroid Build Coastguard Worker // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1506*9880d681SAndroid Build Coastguard Worker
1507*9880d681SAndroid Build Coastguard Worker // If all preds have a single successor, then we know it is safe to insert
1508*9880d681SAndroid Build Coastguard Worker // the load on the pred (?!?), so we can insert code to materialize the
1509*9880d681SAndroid Build Coastguard Worker // pointer if it is not available.
1510*9880d681SAndroid Build Coastguard Worker PHITransAddr Address(LI->getPointerOperand(), DL, AC);
1511*9880d681SAndroid Build Coastguard Worker Value *LoadPtr = nullptr;
1512*9880d681SAndroid Build Coastguard Worker LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1513*9880d681SAndroid Build Coastguard Worker *DT, NewInsts);
1514*9880d681SAndroid Build Coastguard Worker
1515*9880d681SAndroid Build Coastguard Worker // If we couldn't find or insert a computation of this phi translated value,
1516*9880d681SAndroid Build Coastguard Worker // we fail PRE.
1517*9880d681SAndroid Build Coastguard Worker if (!LoadPtr) {
1518*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1519*9880d681SAndroid Build Coastguard Worker << *LI->getPointerOperand() << "\n");
1520*9880d681SAndroid Build Coastguard Worker CanDoPRE = false;
1521*9880d681SAndroid Build Coastguard Worker break;
1522*9880d681SAndroid Build Coastguard Worker }
1523*9880d681SAndroid Build Coastguard Worker
1524*9880d681SAndroid Build Coastguard Worker PredLoad.second = LoadPtr;
1525*9880d681SAndroid Build Coastguard Worker }
1526*9880d681SAndroid Build Coastguard Worker
1527*9880d681SAndroid Build Coastguard Worker if (!CanDoPRE) {
1528*9880d681SAndroid Build Coastguard Worker while (!NewInsts.empty()) {
1529*9880d681SAndroid Build Coastguard Worker Instruction *I = NewInsts.pop_back_val();
1530*9880d681SAndroid Build Coastguard Worker if (MD) MD->removeInstruction(I);
1531*9880d681SAndroid Build Coastguard Worker I->eraseFromParent();
1532*9880d681SAndroid Build Coastguard Worker }
1533*9880d681SAndroid Build Coastguard Worker // HINT: Don't revert the edge-splitting as following transformation may
1534*9880d681SAndroid Build Coastguard Worker // also need to split these critical edges.
1535*9880d681SAndroid Build Coastguard Worker return !CriticalEdgePred.empty();
1536*9880d681SAndroid Build Coastguard Worker }
1537*9880d681SAndroid Build Coastguard Worker
1538*9880d681SAndroid Build Coastguard Worker // Okay, we can eliminate this load by inserting a reload in the predecessor
1539*9880d681SAndroid Build Coastguard Worker // and using PHI construction to get the value in the other predecessors, do
1540*9880d681SAndroid Build Coastguard Worker // it.
1541*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1542*9880d681SAndroid Build Coastguard Worker DEBUG(if (!NewInsts.empty())
1543*9880d681SAndroid Build Coastguard Worker dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
1544*9880d681SAndroid Build Coastguard Worker << *NewInsts.back() << '\n');
1545*9880d681SAndroid Build Coastguard Worker
1546*9880d681SAndroid Build Coastguard Worker // Assign value numbers to the new instructions.
1547*9880d681SAndroid Build Coastguard Worker for (Instruction *I : NewInsts) {
1548*9880d681SAndroid Build Coastguard Worker // FIXME: We really _ought_ to insert these value numbers into their
1549*9880d681SAndroid Build Coastguard Worker // parent's availability map. However, in doing so, we risk getting into
1550*9880d681SAndroid Build Coastguard Worker // ordering issues. If a block hasn't been processed yet, we would be
1551*9880d681SAndroid Build Coastguard Worker // marking a value as AVAIL-IN, which isn't what we intend.
1552*9880d681SAndroid Build Coastguard Worker VN.lookupOrAdd(I);
1553*9880d681SAndroid Build Coastguard Worker }
1554*9880d681SAndroid Build Coastguard Worker
1555*9880d681SAndroid Build Coastguard Worker for (const auto &PredLoad : PredLoads) {
1556*9880d681SAndroid Build Coastguard Worker BasicBlock *UnavailablePred = PredLoad.first;
1557*9880d681SAndroid Build Coastguard Worker Value *LoadPtr = PredLoad.second;
1558*9880d681SAndroid Build Coastguard Worker
1559*9880d681SAndroid Build Coastguard Worker auto *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre",
1560*9880d681SAndroid Build Coastguard Worker LI->isVolatile(), LI->getAlignment(),
1561*9880d681SAndroid Build Coastguard Worker LI->getOrdering(), LI->getSynchScope(),
1562*9880d681SAndroid Build Coastguard Worker UnavailablePred->getTerminator());
1563*9880d681SAndroid Build Coastguard Worker
1564*9880d681SAndroid Build Coastguard Worker // Transfer the old load's AA tags to the new load.
1565*9880d681SAndroid Build Coastguard Worker AAMDNodes Tags;
1566*9880d681SAndroid Build Coastguard Worker LI->getAAMetadata(Tags);
1567*9880d681SAndroid Build Coastguard Worker if (Tags)
1568*9880d681SAndroid Build Coastguard Worker NewLoad->setAAMetadata(Tags);
1569*9880d681SAndroid Build Coastguard Worker
1570*9880d681SAndroid Build Coastguard Worker if (auto *MD = LI->getMetadata(LLVMContext::MD_invariant_load))
1571*9880d681SAndroid Build Coastguard Worker NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
1572*9880d681SAndroid Build Coastguard Worker if (auto *InvGroupMD = LI->getMetadata(LLVMContext::MD_invariant_group))
1573*9880d681SAndroid Build Coastguard Worker NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
1574*9880d681SAndroid Build Coastguard Worker if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range))
1575*9880d681SAndroid Build Coastguard Worker NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
1576*9880d681SAndroid Build Coastguard Worker
1577*9880d681SAndroid Build Coastguard Worker // Transfer DebugLoc.
1578*9880d681SAndroid Build Coastguard Worker NewLoad->setDebugLoc(LI->getDebugLoc());
1579*9880d681SAndroid Build Coastguard Worker
1580*9880d681SAndroid Build Coastguard Worker // Add the newly created load.
1581*9880d681SAndroid Build Coastguard Worker ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1582*9880d681SAndroid Build Coastguard Worker NewLoad));
1583*9880d681SAndroid Build Coastguard Worker MD->invalidateCachedPointerInfo(LoadPtr);
1584*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1585*9880d681SAndroid Build Coastguard Worker }
1586*9880d681SAndroid Build Coastguard Worker
1587*9880d681SAndroid Build Coastguard Worker // Perform PHI construction.
1588*9880d681SAndroid Build Coastguard Worker Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1589*9880d681SAndroid Build Coastguard Worker LI->replaceAllUsesWith(V);
1590*9880d681SAndroid Build Coastguard Worker if (isa<PHINode>(V))
1591*9880d681SAndroid Build Coastguard Worker V->takeName(LI);
1592*9880d681SAndroid Build Coastguard Worker if (Instruction *I = dyn_cast<Instruction>(V))
1593*9880d681SAndroid Build Coastguard Worker I->setDebugLoc(LI->getDebugLoc());
1594*9880d681SAndroid Build Coastguard Worker if (V->getType()->getScalarType()->isPointerTy())
1595*9880d681SAndroid Build Coastguard Worker MD->invalidateCachedPointerInfo(V);
1596*9880d681SAndroid Build Coastguard Worker markInstructionForDeletion(LI);
1597*9880d681SAndroid Build Coastguard Worker ++NumPRELoad;
1598*9880d681SAndroid Build Coastguard Worker return true;
1599*9880d681SAndroid Build Coastguard Worker }
1600*9880d681SAndroid Build Coastguard Worker
1601*9880d681SAndroid Build Coastguard Worker /// Attempt to eliminate a load whose dependencies are
1602*9880d681SAndroid Build Coastguard Worker /// non-local by performing PHI construction.
processNonLocalLoad(LoadInst * LI)1603*9880d681SAndroid Build Coastguard Worker bool GVN::processNonLocalLoad(LoadInst *LI) {
1604*9880d681SAndroid Build Coastguard Worker // non-local speculations are not allowed under asan.
1605*9880d681SAndroid Build Coastguard Worker if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeAddress))
1606*9880d681SAndroid Build Coastguard Worker return false;
1607*9880d681SAndroid Build Coastguard Worker
1608*9880d681SAndroid Build Coastguard Worker // Step 1: Find the non-local dependencies of the load.
1609*9880d681SAndroid Build Coastguard Worker LoadDepVect Deps;
1610*9880d681SAndroid Build Coastguard Worker MD->getNonLocalPointerDependency(LI, Deps);
1611*9880d681SAndroid Build Coastguard Worker
1612*9880d681SAndroid Build Coastguard Worker // If we had to process more than one hundred blocks to find the
1613*9880d681SAndroid Build Coastguard Worker // dependencies, this load isn't worth worrying about. Optimizing
1614*9880d681SAndroid Build Coastguard Worker // it will be too expensive.
1615*9880d681SAndroid Build Coastguard Worker unsigned NumDeps = Deps.size();
1616*9880d681SAndroid Build Coastguard Worker if (NumDeps > 100)
1617*9880d681SAndroid Build Coastguard Worker return false;
1618*9880d681SAndroid Build Coastguard Worker
1619*9880d681SAndroid Build Coastguard Worker // If we had a phi translation failure, we'll have a single entry which is a
1620*9880d681SAndroid Build Coastguard Worker // clobber in the current block. Reject this early.
1621*9880d681SAndroid Build Coastguard Worker if (NumDeps == 1 &&
1622*9880d681SAndroid Build Coastguard Worker !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1623*9880d681SAndroid Build Coastguard Worker DEBUG(
1624*9880d681SAndroid Build Coastguard Worker dbgs() << "GVN: non-local load ";
1625*9880d681SAndroid Build Coastguard Worker LI->printAsOperand(dbgs());
1626*9880d681SAndroid Build Coastguard Worker dbgs() << " has unknown dependencies\n";
1627*9880d681SAndroid Build Coastguard Worker );
1628*9880d681SAndroid Build Coastguard Worker return false;
1629*9880d681SAndroid Build Coastguard Worker }
1630*9880d681SAndroid Build Coastguard Worker
1631*9880d681SAndroid Build Coastguard Worker // If this load follows a GEP, see if we can PRE the indices before analyzing.
1632*9880d681SAndroid Build Coastguard Worker if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) {
1633*9880d681SAndroid Build Coastguard Worker for (GetElementPtrInst::op_iterator OI = GEP->idx_begin(),
1634*9880d681SAndroid Build Coastguard Worker OE = GEP->idx_end();
1635*9880d681SAndroid Build Coastguard Worker OI != OE; ++OI)
1636*9880d681SAndroid Build Coastguard Worker if (Instruction *I = dyn_cast<Instruction>(OI->get()))
1637*9880d681SAndroid Build Coastguard Worker performScalarPRE(I);
1638*9880d681SAndroid Build Coastguard Worker }
1639*9880d681SAndroid Build Coastguard Worker
1640*9880d681SAndroid Build Coastguard Worker // Step 2: Analyze the availability of the load
1641*9880d681SAndroid Build Coastguard Worker AvailValInBlkVect ValuesPerBlock;
1642*9880d681SAndroid Build Coastguard Worker UnavailBlkVect UnavailableBlocks;
1643*9880d681SAndroid Build Coastguard Worker AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
1644*9880d681SAndroid Build Coastguard Worker
1645*9880d681SAndroid Build Coastguard Worker // If we have no predecessors that produce a known value for this load, exit
1646*9880d681SAndroid Build Coastguard Worker // early.
1647*9880d681SAndroid Build Coastguard Worker if (ValuesPerBlock.empty())
1648*9880d681SAndroid Build Coastguard Worker return false;
1649*9880d681SAndroid Build Coastguard Worker
1650*9880d681SAndroid Build Coastguard Worker // Step 3: Eliminate fully redundancy.
1651*9880d681SAndroid Build Coastguard Worker //
1652*9880d681SAndroid Build Coastguard Worker // If all of the instructions we depend on produce a known value for this
1653*9880d681SAndroid Build Coastguard Worker // load, then it is fully redundant and we can use PHI insertion to compute
1654*9880d681SAndroid Build Coastguard Worker // its value. Insert PHIs and remove the fully redundant value now.
1655*9880d681SAndroid Build Coastguard Worker if (UnavailableBlocks.empty()) {
1656*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1657*9880d681SAndroid Build Coastguard Worker
1658*9880d681SAndroid Build Coastguard Worker // Perform PHI construction.
1659*9880d681SAndroid Build Coastguard Worker Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1660*9880d681SAndroid Build Coastguard Worker LI->replaceAllUsesWith(V);
1661*9880d681SAndroid Build Coastguard Worker
1662*9880d681SAndroid Build Coastguard Worker if (isa<PHINode>(V))
1663*9880d681SAndroid Build Coastguard Worker V->takeName(LI);
1664*9880d681SAndroid Build Coastguard Worker if (Instruction *I = dyn_cast<Instruction>(V))
1665*9880d681SAndroid Build Coastguard Worker if (LI->getDebugLoc())
1666*9880d681SAndroid Build Coastguard Worker I->setDebugLoc(LI->getDebugLoc());
1667*9880d681SAndroid Build Coastguard Worker if (V->getType()->getScalarType()->isPointerTy())
1668*9880d681SAndroid Build Coastguard Worker MD->invalidateCachedPointerInfo(V);
1669*9880d681SAndroid Build Coastguard Worker markInstructionForDeletion(LI);
1670*9880d681SAndroid Build Coastguard Worker ++NumGVNLoad;
1671*9880d681SAndroid Build Coastguard Worker return true;
1672*9880d681SAndroid Build Coastguard Worker }
1673*9880d681SAndroid Build Coastguard Worker
1674*9880d681SAndroid Build Coastguard Worker // Step 4: Eliminate partial redundancy.
1675*9880d681SAndroid Build Coastguard Worker if (!EnablePRE || !EnableLoadPRE)
1676*9880d681SAndroid Build Coastguard Worker return false;
1677*9880d681SAndroid Build Coastguard Worker
1678*9880d681SAndroid Build Coastguard Worker return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
1679*9880d681SAndroid Build Coastguard Worker }
1680*9880d681SAndroid Build Coastguard Worker
processAssumeIntrinsic(IntrinsicInst * IntrinsicI)1681*9880d681SAndroid Build Coastguard Worker bool GVN::processAssumeIntrinsic(IntrinsicInst *IntrinsicI) {
1682*9880d681SAndroid Build Coastguard Worker assert(IntrinsicI->getIntrinsicID() == Intrinsic::assume &&
1683*9880d681SAndroid Build Coastguard Worker "This function can only be called with llvm.assume intrinsic");
1684*9880d681SAndroid Build Coastguard Worker Value *V = IntrinsicI->getArgOperand(0);
1685*9880d681SAndroid Build Coastguard Worker
1686*9880d681SAndroid Build Coastguard Worker if (ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
1687*9880d681SAndroid Build Coastguard Worker if (Cond->isZero()) {
1688*9880d681SAndroid Build Coastguard Worker Type *Int8Ty = Type::getInt8Ty(V->getContext());
1689*9880d681SAndroid Build Coastguard Worker // Insert a new store to null instruction before the load to indicate that
1690*9880d681SAndroid Build Coastguard Worker // this code is not reachable. FIXME: We could insert unreachable
1691*9880d681SAndroid Build Coastguard Worker // instruction directly because we can modify the CFG.
1692*9880d681SAndroid Build Coastguard Worker new StoreInst(UndefValue::get(Int8Ty),
1693*9880d681SAndroid Build Coastguard Worker Constant::getNullValue(Int8Ty->getPointerTo()),
1694*9880d681SAndroid Build Coastguard Worker IntrinsicI);
1695*9880d681SAndroid Build Coastguard Worker }
1696*9880d681SAndroid Build Coastguard Worker markInstructionForDeletion(IntrinsicI);
1697*9880d681SAndroid Build Coastguard Worker return false;
1698*9880d681SAndroid Build Coastguard Worker }
1699*9880d681SAndroid Build Coastguard Worker
1700*9880d681SAndroid Build Coastguard Worker Constant *True = ConstantInt::getTrue(V->getContext());
1701*9880d681SAndroid Build Coastguard Worker bool Changed = false;
1702*9880d681SAndroid Build Coastguard Worker
1703*9880d681SAndroid Build Coastguard Worker for (BasicBlock *Successor : successors(IntrinsicI->getParent())) {
1704*9880d681SAndroid Build Coastguard Worker BasicBlockEdge Edge(IntrinsicI->getParent(), Successor);
1705*9880d681SAndroid Build Coastguard Worker
1706*9880d681SAndroid Build Coastguard Worker // This property is only true in dominated successors, propagateEquality
1707*9880d681SAndroid Build Coastguard Worker // will check dominance for us.
1708*9880d681SAndroid Build Coastguard Worker Changed |= propagateEquality(V, True, Edge, false);
1709*9880d681SAndroid Build Coastguard Worker }
1710*9880d681SAndroid Build Coastguard Worker
1711*9880d681SAndroid Build Coastguard Worker // We can replace assume value with true, which covers cases like this:
1712*9880d681SAndroid Build Coastguard Worker // call void @llvm.assume(i1 %cmp)
1713*9880d681SAndroid Build Coastguard Worker // br i1 %cmp, label %bb1, label %bb2 ; will change %cmp to true
1714*9880d681SAndroid Build Coastguard Worker ReplaceWithConstMap[V] = True;
1715*9880d681SAndroid Build Coastguard Worker
1716*9880d681SAndroid Build Coastguard Worker // If one of *cmp *eq operand is const, adding it to map will cover this:
1717*9880d681SAndroid Build Coastguard Worker // %cmp = fcmp oeq float 3.000000e+00, %0 ; const on lhs could happen
1718*9880d681SAndroid Build Coastguard Worker // call void @llvm.assume(i1 %cmp)
1719*9880d681SAndroid Build Coastguard Worker // ret float %0 ; will change it to ret float 3.000000e+00
1720*9880d681SAndroid Build Coastguard Worker if (auto *CmpI = dyn_cast<CmpInst>(V)) {
1721*9880d681SAndroid Build Coastguard Worker if (CmpI->getPredicate() == CmpInst::Predicate::ICMP_EQ ||
1722*9880d681SAndroid Build Coastguard Worker CmpI->getPredicate() == CmpInst::Predicate::FCMP_OEQ ||
1723*9880d681SAndroid Build Coastguard Worker (CmpI->getPredicate() == CmpInst::Predicate::FCMP_UEQ &&
1724*9880d681SAndroid Build Coastguard Worker CmpI->getFastMathFlags().noNaNs())) {
1725*9880d681SAndroid Build Coastguard Worker Value *CmpLHS = CmpI->getOperand(0);
1726*9880d681SAndroid Build Coastguard Worker Value *CmpRHS = CmpI->getOperand(1);
1727*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(CmpLHS))
1728*9880d681SAndroid Build Coastguard Worker std::swap(CmpLHS, CmpRHS);
1729*9880d681SAndroid Build Coastguard Worker auto *RHSConst = dyn_cast<Constant>(CmpRHS);
1730*9880d681SAndroid Build Coastguard Worker
1731*9880d681SAndroid Build Coastguard Worker // If only one operand is constant.
1732*9880d681SAndroid Build Coastguard Worker if (RHSConst != nullptr && !isa<Constant>(CmpLHS))
1733*9880d681SAndroid Build Coastguard Worker ReplaceWithConstMap[CmpLHS] = RHSConst;
1734*9880d681SAndroid Build Coastguard Worker }
1735*9880d681SAndroid Build Coastguard Worker }
1736*9880d681SAndroid Build Coastguard Worker return Changed;
1737*9880d681SAndroid Build Coastguard Worker }
1738*9880d681SAndroid Build Coastguard Worker
patchReplacementInstruction(Instruction * I,Value * Repl)1739*9880d681SAndroid Build Coastguard Worker static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1740*9880d681SAndroid Build Coastguard Worker auto *ReplInst = dyn_cast<Instruction>(Repl);
1741*9880d681SAndroid Build Coastguard Worker if (!ReplInst)
1742*9880d681SAndroid Build Coastguard Worker return;
1743*9880d681SAndroid Build Coastguard Worker
1744*9880d681SAndroid Build Coastguard Worker // Patch the replacement so that it is not more restrictive than the value
1745*9880d681SAndroid Build Coastguard Worker // being replaced.
1746*9880d681SAndroid Build Coastguard Worker ReplInst->andIRFlags(I);
1747*9880d681SAndroid Build Coastguard Worker
1748*9880d681SAndroid Build Coastguard Worker // FIXME: If both the original and replacement value are part of the
1749*9880d681SAndroid Build Coastguard Worker // same control-flow region (meaning that the execution of one
1750*9880d681SAndroid Build Coastguard Worker // guarantees the execution of the other), then we can combine the
1751*9880d681SAndroid Build Coastguard Worker // noalias scopes here and do better than the general conservative
1752*9880d681SAndroid Build Coastguard Worker // answer used in combineMetadata().
1753*9880d681SAndroid Build Coastguard Worker
1754*9880d681SAndroid Build Coastguard Worker // In general, GVN unifies expressions over different control-flow
1755*9880d681SAndroid Build Coastguard Worker // regions, and so we need a conservative combination of the noalias
1756*9880d681SAndroid Build Coastguard Worker // scopes.
1757*9880d681SAndroid Build Coastguard Worker static const unsigned KnownIDs[] = {
1758*9880d681SAndroid Build Coastguard Worker LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1759*9880d681SAndroid Build Coastguard Worker LLVMContext::MD_noalias, LLVMContext::MD_range,
1760*9880d681SAndroid Build Coastguard Worker LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
1761*9880d681SAndroid Build Coastguard Worker LLVMContext::MD_invariant_group};
1762*9880d681SAndroid Build Coastguard Worker combineMetadata(ReplInst, I, KnownIDs);
1763*9880d681SAndroid Build Coastguard Worker }
1764*9880d681SAndroid Build Coastguard Worker
patchAndReplaceAllUsesWith(Instruction * I,Value * Repl)1765*9880d681SAndroid Build Coastguard Worker static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1766*9880d681SAndroid Build Coastguard Worker patchReplacementInstruction(I, Repl);
1767*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(Repl);
1768*9880d681SAndroid Build Coastguard Worker }
1769*9880d681SAndroid Build Coastguard Worker
1770*9880d681SAndroid Build Coastguard Worker /// Attempt to eliminate a load, first by eliminating it
1771*9880d681SAndroid Build Coastguard Worker /// locally, and then attempting non-local elimination if that fails.
processLoad(LoadInst * L)1772*9880d681SAndroid Build Coastguard Worker bool GVN::processLoad(LoadInst *L) {
1773*9880d681SAndroid Build Coastguard Worker if (!MD)
1774*9880d681SAndroid Build Coastguard Worker return false;
1775*9880d681SAndroid Build Coastguard Worker
1776*9880d681SAndroid Build Coastguard Worker // This code hasn't been audited for ordered or volatile memory access
1777*9880d681SAndroid Build Coastguard Worker if (!L->isUnordered())
1778*9880d681SAndroid Build Coastguard Worker return false;
1779*9880d681SAndroid Build Coastguard Worker
1780*9880d681SAndroid Build Coastguard Worker if (L->use_empty()) {
1781*9880d681SAndroid Build Coastguard Worker markInstructionForDeletion(L);
1782*9880d681SAndroid Build Coastguard Worker return true;
1783*9880d681SAndroid Build Coastguard Worker }
1784*9880d681SAndroid Build Coastguard Worker
1785*9880d681SAndroid Build Coastguard Worker // ... to a pointer that has been loaded from before...
1786*9880d681SAndroid Build Coastguard Worker MemDepResult Dep = MD->getDependency(L);
1787*9880d681SAndroid Build Coastguard Worker
1788*9880d681SAndroid Build Coastguard Worker // If it is defined in another block, try harder.
1789*9880d681SAndroid Build Coastguard Worker if (Dep.isNonLocal())
1790*9880d681SAndroid Build Coastguard Worker return processNonLocalLoad(L);
1791*9880d681SAndroid Build Coastguard Worker
1792*9880d681SAndroid Build Coastguard Worker // Only handle the local case below
1793*9880d681SAndroid Build Coastguard Worker if (!Dep.isDef() && !Dep.isClobber()) {
1794*9880d681SAndroid Build Coastguard Worker // This might be a NonFuncLocal or an Unknown
1795*9880d681SAndroid Build Coastguard Worker DEBUG(
1796*9880d681SAndroid Build Coastguard Worker // fast print dep, using operator<< on instruction is too slow.
1797*9880d681SAndroid Build Coastguard Worker dbgs() << "GVN: load ";
1798*9880d681SAndroid Build Coastguard Worker L->printAsOperand(dbgs());
1799*9880d681SAndroid Build Coastguard Worker dbgs() << " has unknown dependence\n";
1800*9880d681SAndroid Build Coastguard Worker );
1801*9880d681SAndroid Build Coastguard Worker return false;
1802*9880d681SAndroid Build Coastguard Worker }
1803*9880d681SAndroid Build Coastguard Worker
1804*9880d681SAndroid Build Coastguard Worker AvailableValue AV;
1805*9880d681SAndroid Build Coastguard Worker if (AnalyzeLoadAvailability(L, Dep, L->getPointerOperand(), AV)) {
1806*9880d681SAndroid Build Coastguard Worker Value *AvailableValue = AV.MaterializeAdjustedValue(L, L, *this);
1807*9880d681SAndroid Build Coastguard Worker
1808*9880d681SAndroid Build Coastguard Worker // Replace the load!
1809*9880d681SAndroid Build Coastguard Worker patchAndReplaceAllUsesWith(L, AvailableValue);
1810*9880d681SAndroid Build Coastguard Worker markInstructionForDeletion(L);
1811*9880d681SAndroid Build Coastguard Worker ++NumGVNLoad;
1812*9880d681SAndroid Build Coastguard Worker // Tell MDA to rexamine the reused pointer since we might have more
1813*9880d681SAndroid Build Coastguard Worker // information after forwarding it.
1814*9880d681SAndroid Build Coastguard Worker if (MD && AvailableValue->getType()->getScalarType()->isPointerTy())
1815*9880d681SAndroid Build Coastguard Worker MD->invalidateCachedPointerInfo(AvailableValue);
1816*9880d681SAndroid Build Coastguard Worker return true;
1817*9880d681SAndroid Build Coastguard Worker }
1818*9880d681SAndroid Build Coastguard Worker
1819*9880d681SAndroid Build Coastguard Worker return false;
1820*9880d681SAndroid Build Coastguard Worker }
1821*9880d681SAndroid Build Coastguard Worker
1822*9880d681SAndroid Build Coastguard Worker // In order to find a leader for a given value number at a
1823*9880d681SAndroid Build Coastguard Worker // specific basic block, we first obtain the list of all Values for that number,
1824*9880d681SAndroid Build Coastguard Worker // and then scan the list to find one whose block dominates the block in
1825*9880d681SAndroid Build Coastguard Worker // question. This is fast because dominator tree queries consist of only
1826*9880d681SAndroid Build Coastguard Worker // a few comparisons of DFS numbers.
findLeader(const BasicBlock * BB,uint32_t num)1827*9880d681SAndroid Build Coastguard Worker Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
1828*9880d681SAndroid Build Coastguard Worker LeaderTableEntry Vals = LeaderTable[num];
1829*9880d681SAndroid Build Coastguard Worker if (!Vals.Val) return nullptr;
1830*9880d681SAndroid Build Coastguard Worker
1831*9880d681SAndroid Build Coastguard Worker Value *Val = nullptr;
1832*9880d681SAndroid Build Coastguard Worker if (DT->dominates(Vals.BB, BB)) {
1833*9880d681SAndroid Build Coastguard Worker Val = Vals.Val;
1834*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(Val)) return Val;
1835*9880d681SAndroid Build Coastguard Worker }
1836*9880d681SAndroid Build Coastguard Worker
1837*9880d681SAndroid Build Coastguard Worker LeaderTableEntry* Next = Vals.Next;
1838*9880d681SAndroid Build Coastguard Worker while (Next) {
1839*9880d681SAndroid Build Coastguard Worker if (DT->dominates(Next->BB, BB)) {
1840*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(Next->Val)) return Next->Val;
1841*9880d681SAndroid Build Coastguard Worker if (!Val) Val = Next->Val;
1842*9880d681SAndroid Build Coastguard Worker }
1843*9880d681SAndroid Build Coastguard Worker
1844*9880d681SAndroid Build Coastguard Worker Next = Next->Next;
1845*9880d681SAndroid Build Coastguard Worker }
1846*9880d681SAndroid Build Coastguard Worker
1847*9880d681SAndroid Build Coastguard Worker return Val;
1848*9880d681SAndroid Build Coastguard Worker }
1849*9880d681SAndroid Build Coastguard Worker
1850*9880d681SAndroid Build Coastguard Worker /// There is an edge from 'Src' to 'Dst'. Return
1851*9880d681SAndroid Build Coastguard Worker /// true if every path from the entry block to 'Dst' passes via this edge. In
1852*9880d681SAndroid Build Coastguard Worker /// particular 'Dst' must not be reachable via another edge from 'Src'.
isOnlyReachableViaThisEdge(const BasicBlockEdge & E,DominatorTree * DT)1853*9880d681SAndroid Build Coastguard Worker static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
1854*9880d681SAndroid Build Coastguard Worker DominatorTree *DT) {
1855*9880d681SAndroid Build Coastguard Worker // While in theory it is interesting to consider the case in which Dst has
1856*9880d681SAndroid Build Coastguard Worker // more than one predecessor, because Dst might be part of a loop which is
1857*9880d681SAndroid Build Coastguard Worker // only reachable from Src, in practice it is pointless since at the time
1858*9880d681SAndroid Build Coastguard Worker // GVN runs all such loops have preheaders, which means that Dst will have
1859*9880d681SAndroid Build Coastguard Worker // been changed to have only one predecessor, namely Src.
1860*9880d681SAndroid Build Coastguard Worker const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
1861*9880d681SAndroid Build Coastguard Worker assert((!Pred || Pred == E.getStart()) &&
1862*9880d681SAndroid Build Coastguard Worker "No edge between these basic blocks!");
1863*9880d681SAndroid Build Coastguard Worker return Pred != nullptr;
1864*9880d681SAndroid Build Coastguard Worker }
1865*9880d681SAndroid Build Coastguard Worker
1866*9880d681SAndroid Build Coastguard Worker // Tries to replace instruction with const, using information from
1867*9880d681SAndroid Build Coastguard Worker // ReplaceWithConstMap.
replaceOperandsWithConsts(Instruction * Instr) const1868*9880d681SAndroid Build Coastguard Worker bool GVN::replaceOperandsWithConsts(Instruction *Instr) const {
1869*9880d681SAndroid Build Coastguard Worker bool Changed = false;
1870*9880d681SAndroid Build Coastguard Worker for (unsigned OpNum = 0; OpNum < Instr->getNumOperands(); ++OpNum) {
1871*9880d681SAndroid Build Coastguard Worker Value *Operand = Instr->getOperand(OpNum);
1872*9880d681SAndroid Build Coastguard Worker auto it = ReplaceWithConstMap.find(Operand);
1873*9880d681SAndroid Build Coastguard Worker if (it != ReplaceWithConstMap.end()) {
1874*9880d681SAndroid Build Coastguard Worker assert(!isa<Constant>(Operand) &&
1875*9880d681SAndroid Build Coastguard Worker "Replacing constants with constants is invalid");
1876*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN replacing: " << *Operand << " with " << *it->second
1877*9880d681SAndroid Build Coastguard Worker << " in instruction " << *Instr << '\n');
1878*9880d681SAndroid Build Coastguard Worker Instr->setOperand(OpNum, it->second);
1879*9880d681SAndroid Build Coastguard Worker Changed = true;
1880*9880d681SAndroid Build Coastguard Worker }
1881*9880d681SAndroid Build Coastguard Worker }
1882*9880d681SAndroid Build Coastguard Worker return Changed;
1883*9880d681SAndroid Build Coastguard Worker }
1884*9880d681SAndroid Build Coastguard Worker
1885*9880d681SAndroid Build Coastguard Worker /// The given values are known to be equal in every block
1886*9880d681SAndroid Build Coastguard Worker /// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
1887*9880d681SAndroid Build Coastguard Worker /// 'RHS' everywhere in the scope. Returns whether a change was made.
1888*9880d681SAndroid Build Coastguard Worker /// If DominatesByEdge is false, then it means that we will propagate the RHS
1889*9880d681SAndroid Build Coastguard Worker /// value starting from the end of Root.Start.
propagateEquality(Value * LHS,Value * RHS,const BasicBlockEdge & Root,bool DominatesByEdge)1890*9880d681SAndroid Build Coastguard Worker bool GVN::propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root,
1891*9880d681SAndroid Build Coastguard Worker bool DominatesByEdge) {
1892*9880d681SAndroid Build Coastguard Worker SmallVector<std::pair<Value*, Value*>, 4> Worklist;
1893*9880d681SAndroid Build Coastguard Worker Worklist.push_back(std::make_pair(LHS, RHS));
1894*9880d681SAndroid Build Coastguard Worker bool Changed = false;
1895*9880d681SAndroid Build Coastguard Worker // For speed, compute a conservative fast approximation to
1896*9880d681SAndroid Build Coastguard Worker // DT->dominates(Root, Root.getEnd());
1897*9880d681SAndroid Build Coastguard Worker const bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
1898*9880d681SAndroid Build Coastguard Worker
1899*9880d681SAndroid Build Coastguard Worker while (!Worklist.empty()) {
1900*9880d681SAndroid Build Coastguard Worker std::pair<Value*, Value*> Item = Worklist.pop_back_val();
1901*9880d681SAndroid Build Coastguard Worker LHS = Item.first; RHS = Item.second;
1902*9880d681SAndroid Build Coastguard Worker
1903*9880d681SAndroid Build Coastguard Worker if (LHS == RHS)
1904*9880d681SAndroid Build Coastguard Worker continue;
1905*9880d681SAndroid Build Coastguard Worker assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
1906*9880d681SAndroid Build Coastguard Worker
1907*9880d681SAndroid Build Coastguard Worker // Don't try to propagate equalities between constants.
1908*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(LHS) && isa<Constant>(RHS))
1909*9880d681SAndroid Build Coastguard Worker continue;
1910*9880d681SAndroid Build Coastguard Worker
1911*9880d681SAndroid Build Coastguard Worker // Prefer a constant on the right-hand side, or an Argument if no constants.
1912*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
1913*9880d681SAndroid Build Coastguard Worker std::swap(LHS, RHS);
1914*9880d681SAndroid Build Coastguard Worker assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
1915*9880d681SAndroid Build Coastguard Worker
1916*9880d681SAndroid Build Coastguard Worker // If there is no obvious reason to prefer the left-hand side over the
1917*9880d681SAndroid Build Coastguard Worker // right-hand side, ensure the longest lived term is on the right-hand side,
1918*9880d681SAndroid Build Coastguard Worker // so the shortest lived term will be replaced by the longest lived.
1919*9880d681SAndroid Build Coastguard Worker // This tends to expose more simplifications.
1920*9880d681SAndroid Build Coastguard Worker uint32_t LVN = VN.lookupOrAdd(LHS);
1921*9880d681SAndroid Build Coastguard Worker if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
1922*9880d681SAndroid Build Coastguard Worker (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
1923*9880d681SAndroid Build Coastguard Worker // Move the 'oldest' value to the right-hand side, using the value number
1924*9880d681SAndroid Build Coastguard Worker // as a proxy for age.
1925*9880d681SAndroid Build Coastguard Worker uint32_t RVN = VN.lookupOrAdd(RHS);
1926*9880d681SAndroid Build Coastguard Worker if (LVN < RVN) {
1927*9880d681SAndroid Build Coastguard Worker std::swap(LHS, RHS);
1928*9880d681SAndroid Build Coastguard Worker LVN = RVN;
1929*9880d681SAndroid Build Coastguard Worker }
1930*9880d681SAndroid Build Coastguard Worker }
1931*9880d681SAndroid Build Coastguard Worker
1932*9880d681SAndroid Build Coastguard Worker // If value numbering later sees that an instruction in the scope is equal
1933*9880d681SAndroid Build Coastguard Worker // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve
1934*9880d681SAndroid Build Coastguard Worker // the invariant that instructions only occur in the leader table for their
1935*9880d681SAndroid Build Coastguard Worker // own value number (this is used by removeFromLeaderTable), do not do this
1936*9880d681SAndroid Build Coastguard Worker // if RHS is an instruction (if an instruction in the scope is morphed into
1937*9880d681SAndroid Build Coastguard Worker // LHS then it will be turned into RHS by the next GVN iteration anyway, so
1938*9880d681SAndroid Build Coastguard Worker // using the leader table is about compiling faster, not optimizing better).
1939*9880d681SAndroid Build Coastguard Worker // The leader table only tracks basic blocks, not edges. Only add to if we
1940*9880d681SAndroid Build Coastguard Worker // have the simple case where the edge dominates the end.
1941*9880d681SAndroid Build Coastguard Worker if (RootDominatesEnd && !isa<Instruction>(RHS))
1942*9880d681SAndroid Build Coastguard Worker addToLeaderTable(LVN, RHS, Root.getEnd());
1943*9880d681SAndroid Build Coastguard Worker
1944*9880d681SAndroid Build Coastguard Worker // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
1945*9880d681SAndroid Build Coastguard Worker // LHS always has at least one use that is not dominated by Root, this will
1946*9880d681SAndroid Build Coastguard Worker // never do anything if LHS has only one use.
1947*9880d681SAndroid Build Coastguard Worker if (!LHS->hasOneUse()) {
1948*9880d681SAndroid Build Coastguard Worker unsigned NumReplacements =
1949*9880d681SAndroid Build Coastguard Worker DominatesByEdge
1950*9880d681SAndroid Build Coastguard Worker ? replaceDominatedUsesWith(LHS, RHS, *DT, Root)
1951*9880d681SAndroid Build Coastguard Worker : replaceDominatedUsesWith(LHS, RHS, *DT, Root.getStart());
1952*9880d681SAndroid Build Coastguard Worker
1953*9880d681SAndroid Build Coastguard Worker Changed |= NumReplacements > 0;
1954*9880d681SAndroid Build Coastguard Worker NumGVNEqProp += NumReplacements;
1955*9880d681SAndroid Build Coastguard Worker }
1956*9880d681SAndroid Build Coastguard Worker
1957*9880d681SAndroid Build Coastguard Worker // Now try to deduce additional equalities from this one. For example, if
1958*9880d681SAndroid Build Coastguard Worker // the known equality was "(A != B)" == "false" then it follows that A and B
1959*9880d681SAndroid Build Coastguard Worker // are equal in the scope. Only boolean equalities with an explicit true or
1960*9880d681SAndroid Build Coastguard Worker // false RHS are currently supported.
1961*9880d681SAndroid Build Coastguard Worker if (!RHS->getType()->isIntegerTy(1))
1962*9880d681SAndroid Build Coastguard Worker // Not a boolean equality - bail out.
1963*9880d681SAndroid Build Coastguard Worker continue;
1964*9880d681SAndroid Build Coastguard Worker ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
1965*9880d681SAndroid Build Coastguard Worker if (!CI)
1966*9880d681SAndroid Build Coastguard Worker // RHS neither 'true' nor 'false' - bail out.
1967*9880d681SAndroid Build Coastguard Worker continue;
1968*9880d681SAndroid Build Coastguard Worker // Whether RHS equals 'true'. Otherwise it equals 'false'.
1969*9880d681SAndroid Build Coastguard Worker bool isKnownTrue = CI->isAllOnesValue();
1970*9880d681SAndroid Build Coastguard Worker bool isKnownFalse = !isKnownTrue;
1971*9880d681SAndroid Build Coastguard Worker
1972*9880d681SAndroid Build Coastguard Worker // If "A && B" is known true then both A and B are known true. If "A || B"
1973*9880d681SAndroid Build Coastguard Worker // is known false then both A and B are known false.
1974*9880d681SAndroid Build Coastguard Worker Value *A, *B;
1975*9880d681SAndroid Build Coastguard Worker if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
1976*9880d681SAndroid Build Coastguard Worker (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
1977*9880d681SAndroid Build Coastguard Worker Worklist.push_back(std::make_pair(A, RHS));
1978*9880d681SAndroid Build Coastguard Worker Worklist.push_back(std::make_pair(B, RHS));
1979*9880d681SAndroid Build Coastguard Worker continue;
1980*9880d681SAndroid Build Coastguard Worker }
1981*9880d681SAndroid Build Coastguard Worker
1982*9880d681SAndroid Build Coastguard Worker // If we are propagating an equality like "(A == B)" == "true" then also
1983*9880d681SAndroid Build Coastguard Worker // propagate the equality A == B. When propagating a comparison such as
1984*9880d681SAndroid Build Coastguard Worker // "(A >= B)" == "true", replace all instances of "A < B" with "false".
1985*9880d681SAndroid Build Coastguard Worker if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
1986*9880d681SAndroid Build Coastguard Worker Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
1987*9880d681SAndroid Build Coastguard Worker
1988*9880d681SAndroid Build Coastguard Worker // If "A == B" is known true, or "A != B" is known false, then replace
1989*9880d681SAndroid Build Coastguard Worker // A with B everywhere in the scope.
1990*9880d681SAndroid Build Coastguard Worker if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
1991*9880d681SAndroid Build Coastguard Worker (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
1992*9880d681SAndroid Build Coastguard Worker Worklist.push_back(std::make_pair(Op0, Op1));
1993*9880d681SAndroid Build Coastguard Worker
1994*9880d681SAndroid Build Coastguard Worker // Handle the floating point versions of equality comparisons too.
1995*9880d681SAndroid Build Coastguard Worker if ((isKnownTrue && Cmp->getPredicate() == CmpInst::FCMP_OEQ) ||
1996*9880d681SAndroid Build Coastguard Worker (isKnownFalse && Cmp->getPredicate() == CmpInst::FCMP_UNE)) {
1997*9880d681SAndroid Build Coastguard Worker
1998*9880d681SAndroid Build Coastguard Worker // Floating point -0.0 and 0.0 compare equal, so we can only
1999*9880d681SAndroid Build Coastguard Worker // propagate values if we know that we have a constant and that
2000*9880d681SAndroid Build Coastguard Worker // its value is non-zero.
2001*9880d681SAndroid Build Coastguard Worker
2002*9880d681SAndroid Build Coastguard Worker // FIXME: We should do this optimization if 'no signed zeros' is
2003*9880d681SAndroid Build Coastguard Worker // applicable via an instruction-level fast-math-flag or some other
2004*9880d681SAndroid Build Coastguard Worker // indicator that relaxed FP semantics are being used.
2005*9880d681SAndroid Build Coastguard Worker
2006*9880d681SAndroid Build Coastguard Worker if (isa<ConstantFP>(Op1) && !cast<ConstantFP>(Op1)->isZero())
2007*9880d681SAndroid Build Coastguard Worker Worklist.push_back(std::make_pair(Op0, Op1));
2008*9880d681SAndroid Build Coastguard Worker }
2009*9880d681SAndroid Build Coastguard Worker
2010*9880d681SAndroid Build Coastguard Worker // If "A >= B" is known true, replace "A < B" with false everywhere.
2011*9880d681SAndroid Build Coastguard Worker CmpInst::Predicate NotPred = Cmp->getInversePredicate();
2012*9880d681SAndroid Build Coastguard Worker Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
2013*9880d681SAndroid Build Coastguard Worker // Since we don't have the instruction "A < B" immediately to hand, work
2014*9880d681SAndroid Build Coastguard Worker // out the value number that it would have and use that to find an
2015*9880d681SAndroid Build Coastguard Worker // appropriate instruction (if any).
2016*9880d681SAndroid Build Coastguard Worker uint32_t NextNum = VN.getNextUnusedValueNumber();
2017*9880d681SAndroid Build Coastguard Worker uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1);
2018*9880d681SAndroid Build Coastguard Worker // If the number we were assigned was brand new then there is no point in
2019*9880d681SAndroid Build Coastguard Worker // looking for an instruction realizing it: there cannot be one!
2020*9880d681SAndroid Build Coastguard Worker if (Num < NextNum) {
2021*9880d681SAndroid Build Coastguard Worker Value *NotCmp = findLeader(Root.getEnd(), Num);
2022*9880d681SAndroid Build Coastguard Worker if (NotCmp && isa<Instruction>(NotCmp)) {
2023*9880d681SAndroid Build Coastguard Worker unsigned NumReplacements =
2024*9880d681SAndroid Build Coastguard Worker DominatesByEdge
2025*9880d681SAndroid Build Coastguard Worker ? replaceDominatedUsesWith(NotCmp, NotVal, *DT, Root)
2026*9880d681SAndroid Build Coastguard Worker : replaceDominatedUsesWith(NotCmp, NotVal, *DT,
2027*9880d681SAndroid Build Coastguard Worker Root.getStart());
2028*9880d681SAndroid Build Coastguard Worker Changed |= NumReplacements > 0;
2029*9880d681SAndroid Build Coastguard Worker NumGVNEqProp += NumReplacements;
2030*9880d681SAndroid Build Coastguard Worker }
2031*9880d681SAndroid Build Coastguard Worker }
2032*9880d681SAndroid Build Coastguard Worker // Ensure that any instruction in scope that gets the "A < B" value number
2033*9880d681SAndroid Build Coastguard Worker // is replaced with false.
2034*9880d681SAndroid Build Coastguard Worker // The leader table only tracks basic blocks, not edges. Only add to if we
2035*9880d681SAndroid Build Coastguard Worker // have the simple case where the edge dominates the end.
2036*9880d681SAndroid Build Coastguard Worker if (RootDominatesEnd)
2037*9880d681SAndroid Build Coastguard Worker addToLeaderTable(Num, NotVal, Root.getEnd());
2038*9880d681SAndroid Build Coastguard Worker
2039*9880d681SAndroid Build Coastguard Worker continue;
2040*9880d681SAndroid Build Coastguard Worker }
2041*9880d681SAndroid Build Coastguard Worker }
2042*9880d681SAndroid Build Coastguard Worker
2043*9880d681SAndroid Build Coastguard Worker return Changed;
2044*9880d681SAndroid Build Coastguard Worker }
2045*9880d681SAndroid Build Coastguard Worker
2046*9880d681SAndroid Build Coastguard Worker /// When calculating availability, handle an instruction
2047*9880d681SAndroid Build Coastguard Worker /// by inserting it into the appropriate sets
processInstruction(Instruction * I)2048*9880d681SAndroid Build Coastguard Worker bool GVN::processInstruction(Instruction *I) {
2049*9880d681SAndroid Build Coastguard Worker // Ignore dbg info intrinsics.
2050*9880d681SAndroid Build Coastguard Worker if (isa<DbgInfoIntrinsic>(I))
2051*9880d681SAndroid Build Coastguard Worker return false;
2052*9880d681SAndroid Build Coastguard Worker
2053*9880d681SAndroid Build Coastguard Worker // If the instruction can be easily simplified then do so now in preference
2054*9880d681SAndroid Build Coastguard Worker // to value numbering it. Value numbering often exposes redundancies, for
2055*9880d681SAndroid Build Coastguard Worker // example if it determines that %y is equal to %x then the instruction
2056*9880d681SAndroid Build Coastguard Worker // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
2057*9880d681SAndroid Build Coastguard Worker const DataLayout &DL = I->getModule()->getDataLayout();
2058*9880d681SAndroid Build Coastguard Worker if (Value *V = SimplifyInstruction(I, DL, TLI, DT, AC)) {
2059*9880d681SAndroid Build Coastguard Worker bool Changed = false;
2060*9880d681SAndroid Build Coastguard Worker if (!I->use_empty()) {
2061*9880d681SAndroid Build Coastguard Worker I->replaceAllUsesWith(V);
2062*9880d681SAndroid Build Coastguard Worker Changed = true;
2063*9880d681SAndroid Build Coastguard Worker }
2064*9880d681SAndroid Build Coastguard Worker if (isInstructionTriviallyDead(I, TLI)) {
2065*9880d681SAndroid Build Coastguard Worker markInstructionForDeletion(I);
2066*9880d681SAndroid Build Coastguard Worker Changed = true;
2067*9880d681SAndroid Build Coastguard Worker }
2068*9880d681SAndroid Build Coastguard Worker if (Changed) {
2069*9880d681SAndroid Build Coastguard Worker if (MD && V->getType()->getScalarType()->isPointerTy())
2070*9880d681SAndroid Build Coastguard Worker MD->invalidateCachedPointerInfo(V);
2071*9880d681SAndroid Build Coastguard Worker ++NumGVNSimpl;
2072*9880d681SAndroid Build Coastguard Worker return true;
2073*9880d681SAndroid Build Coastguard Worker }
2074*9880d681SAndroid Build Coastguard Worker }
2075*9880d681SAndroid Build Coastguard Worker
2076*9880d681SAndroid Build Coastguard Worker if (IntrinsicInst *IntrinsicI = dyn_cast<IntrinsicInst>(I))
2077*9880d681SAndroid Build Coastguard Worker if (IntrinsicI->getIntrinsicID() == Intrinsic::assume)
2078*9880d681SAndroid Build Coastguard Worker return processAssumeIntrinsic(IntrinsicI);
2079*9880d681SAndroid Build Coastguard Worker
2080*9880d681SAndroid Build Coastguard Worker if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2081*9880d681SAndroid Build Coastguard Worker if (processLoad(LI))
2082*9880d681SAndroid Build Coastguard Worker return true;
2083*9880d681SAndroid Build Coastguard Worker
2084*9880d681SAndroid Build Coastguard Worker unsigned Num = VN.lookupOrAdd(LI);
2085*9880d681SAndroid Build Coastguard Worker addToLeaderTable(Num, LI, LI->getParent());
2086*9880d681SAndroid Build Coastguard Worker return false;
2087*9880d681SAndroid Build Coastguard Worker }
2088*9880d681SAndroid Build Coastguard Worker
2089*9880d681SAndroid Build Coastguard Worker // For conditional branches, we can perform simple conditional propagation on
2090*9880d681SAndroid Build Coastguard Worker // the condition value itself.
2091*9880d681SAndroid Build Coastguard Worker if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
2092*9880d681SAndroid Build Coastguard Worker if (!BI->isConditional())
2093*9880d681SAndroid Build Coastguard Worker return false;
2094*9880d681SAndroid Build Coastguard Worker
2095*9880d681SAndroid Build Coastguard Worker if (isa<Constant>(BI->getCondition()))
2096*9880d681SAndroid Build Coastguard Worker return processFoldableCondBr(BI);
2097*9880d681SAndroid Build Coastguard Worker
2098*9880d681SAndroid Build Coastguard Worker Value *BranchCond = BI->getCondition();
2099*9880d681SAndroid Build Coastguard Worker BasicBlock *TrueSucc = BI->getSuccessor(0);
2100*9880d681SAndroid Build Coastguard Worker BasicBlock *FalseSucc = BI->getSuccessor(1);
2101*9880d681SAndroid Build Coastguard Worker // Avoid multiple edges early.
2102*9880d681SAndroid Build Coastguard Worker if (TrueSucc == FalseSucc)
2103*9880d681SAndroid Build Coastguard Worker return false;
2104*9880d681SAndroid Build Coastguard Worker
2105*9880d681SAndroid Build Coastguard Worker BasicBlock *Parent = BI->getParent();
2106*9880d681SAndroid Build Coastguard Worker bool Changed = false;
2107*9880d681SAndroid Build Coastguard Worker
2108*9880d681SAndroid Build Coastguard Worker Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
2109*9880d681SAndroid Build Coastguard Worker BasicBlockEdge TrueE(Parent, TrueSucc);
2110*9880d681SAndroid Build Coastguard Worker Changed |= propagateEquality(BranchCond, TrueVal, TrueE, true);
2111*9880d681SAndroid Build Coastguard Worker
2112*9880d681SAndroid Build Coastguard Worker Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
2113*9880d681SAndroid Build Coastguard Worker BasicBlockEdge FalseE(Parent, FalseSucc);
2114*9880d681SAndroid Build Coastguard Worker Changed |= propagateEquality(BranchCond, FalseVal, FalseE, true);
2115*9880d681SAndroid Build Coastguard Worker
2116*9880d681SAndroid Build Coastguard Worker return Changed;
2117*9880d681SAndroid Build Coastguard Worker }
2118*9880d681SAndroid Build Coastguard Worker
2119*9880d681SAndroid Build Coastguard Worker // For switches, propagate the case values into the case destinations.
2120*9880d681SAndroid Build Coastguard Worker if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2121*9880d681SAndroid Build Coastguard Worker Value *SwitchCond = SI->getCondition();
2122*9880d681SAndroid Build Coastguard Worker BasicBlock *Parent = SI->getParent();
2123*9880d681SAndroid Build Coastguard Worker bool Changed = false;
2124*9880d681SAndroid Build Coastguard Worker
2125*9880d681SAndroid Build Coastguard Worker // Remember how many outgoing edges there are to every successor.
2126*9880d681SAndroid Build Coastguard Worker SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2127*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
2128*9880d681SAndroid Build Coastguard Worker ++SwitchEdges[SI->getSuccessor(i)];
2129*9880d681SAndroid Build Coastguard Worker
2130*9880d681SAndroid Build Coastguard Worker for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2131*9880d681SAndroid Build Coastguard Worker i != e; ++i) {
2132*9880d681SAndroid Build Coastguard Worker BasicBlock *Dst = i.getCaseSuccessor();
2133*9880d681SAndroid Build Coastguard Worker // If there is only a single edge, propagate the case value into it.
2134*9880d681SAndroid Build Coastguard Worker if (SwitchEdges.lookup(Dst) == 1) {
2135*9880d681SAndroid Build Coastguard Worker BasicBlockEdge E(Parent, Dst);
2136*9880d681SAndroid Build Coastguard Worker Changed |= propagateEquality(SwitchCond, i.getCaseValue(), E, true);
2137*9880d681SAndroid Build Coastguard Worker }
2138*9880d681SAndroid Build Coastguard Worker }
2139*9880d681SAndroid Build Coastguard Worker return Changed;
2140*9880d681SAndroid Build Coastguard Worker }
2141*9880d681SAndroid Build Coastguard Worker
2142*9880d681SAndroid Build Coastguard Worker // Instructions with void type don't return a value, so there's
2143*9880d681SAndroid Build Coastguard Worker // no point in trying to find redundancies in them.
2144*9880d681SAndroid Build Coastguard Worker if (I->getType()->isVoidTy())
2145*9880d681SAndroid Build Coastguard Worker return false;
2146*9880d681SAndroid Build Coastguard Worker
2147*9880d681SAndroid Build Coastguard Worker uint32_t NextNum = VN.getNextUnusedValueNumber();
2148*9880d681SAndroid Build Coastguard Worker unsigned Num = VN.lookupOrAdd(I);
2149*9880d681SAndroid Build Coastguard Worker
2150*9880d681SAndroid Build Coastguard Worker // Allocations are always uniquely numbered, so we can save time and memory
2151*9880d681SAndroid Build Coastguard Worker // by fast failing them.
2152*9880d681SAndroid Build Coastguard Worker if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
2153*9880d681SAndroid Build Coastguard Worker addToLeaderTable(Num, I, I->getParent());
2154*9880d681SAndroid Build Coastguard Worker return false;
2155*9880d681SAndroid Build Coastguard Worker }
2156*9880d681SAndroid Build Coastguard Worker
2157*9880d681SAndroid Build Coastguard Worker // If the number we were assigned was a brand new VN, then we don't
2158*9880d681SAndroid Build Coastguard Worker // need to do a lookup to see if the number already exists
2159*9880d681SAndroid Build Coastguard Worker // somewhere in the domtree: it can't!
2160*9880d681SAndroid Build Coastguard Worker if (Num >= NextNum) {
2161*9880d681SAndroid Build Coastguard Worker addToLeaderTable(Num, I, I->getParent());
2162*9880d681SAndroid Build Coastguard Worker return false;
2163*9880d681SAndroid Build Coastguard Worker }
2164*9880d681SAndroid Build Coastguard Worker
2165*9880d681SAndroid Build Coastguard Worker // Perform fast-path value-number based elimination of values inherited from
2166*9880d681SAndroid Build Coastguard Worker // dominators.
2167*9880d681SAndroid Build Coastguard Worker Value *Repl = findLeader(I->getParent(), Num);
2168*9880d681SAndroid Build Coastguard Worker if (!Repl) {
2169*9880d681SAndroid Build Coastguard Worker // Failure, just remember this instance for future use.
2170*9880d681SAndroid Build Coastguard Worker addToLeaderTable(Num, I, I->getParent());
2171*9880d681SAndroid Build Coastguard Worker return false;
2172*9880d681SAndroid Build Coastguard Worker } else if (Repl == I) {
2173*9880d681SAndroid Build Coastguard Worker // If I was the result of a shortcut PRE, it might already be in the table
2174*9880d681SAndroid Build Coastguard Worker // and the best replacement for itself. Nothing to do.
2175*9880d681SAndroid Build Coastguard Worker return false;
2176*9880d681SAndroid Build Coastguard Worker }
2177*9880d681SAndroid Build Coastguard Worker
2178*9880d681SAndroid Build Coastguard Worker // Remove it!
2179*9880d681SAndroid Build Coastguard Worker patchAndReplaceAllUsesWith(I, Repl);
2180*9880d681SAndroid Build Coastguard Worker if (MD && Repl->getType()->getScalarType()->isPointerTy())
2181*9880d681SAndroid Build Coastguard Worker MD->invalidateCachedPointerInfo(Repl);
2182*9880d681SAndroid Build Coastguard Worker markInstructionForDeletion(I);
2183*9880d681SAndroid Build Coastguard Worker return true;
2184*9880d681SAndroid Build Coastguard Worker }
2185*9880d681SAndroid Build Coastguard Worker
2186*9880d681SAndroid Build Coastguard Worker /// runOnFunction - This is the main transformation entry point for a function.
runImpl(Function & F,AssumptionCache & RunAC,DominatorTree & RunDT,const TargetLibraryInfo & RunTLI,AAResults & RunAA,MemoryDependenceResults * RunMD)2187*9880d681SAndroid Build Coastguard Worker bool GVN::runImpl(Function &F, AssumptionCache &RunAC, DominatorTree &RunDT,
2188*9880d681SAndroid Build Coastguard Worker const TargetLibraryInfo &RunTLI, AAResults &RunAA,
2189*9880d681SAndroid Build Coastguard Worker MemoryDependenceResults *RunMD) {
2190*9880d681SAndroid Build Coastguard Worker AC = &RunAC;
2191*9880d681SAndroid Build Coastguard Worker DT = &RunDT;
2192*9880d681SAndroid Build Coastguard Worker VN.setDomTree(DT);
2193*9880d681SAndroid Build Coastguard Worker TLI = &RunTLI;
2194*9880d681SAndroid Build Coastguard Worker VN.setAliasAnalysis(&RunAA);
2195*9880d681SAndroid Build Coastguard Worker MD = RunMD;
2196*9880d681SAndroid Build Coastguard Worker VN.setMemDep(MD);
2197*9880d681SAndroid Build Coastguard Worker
2198*9880d681SAndroid Build Coastguard Worker bool Changed = false;
2199*9880d681SAndroid Build Coastguard Worker bool ShouldContinue = true;
2200*9880d681SAndroid Build Coastguard Worker
2201*9880d681SAndroid Build Coastguard Worker // Merge unconditional branches, allowing PRE to catch more
2202*9880d681SAndroid Build Coastguard Worker // optimization opportunities.
2203*9880d681SAndroid Build Coastguard Worker for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
2204*9880d681SAndroid Build Coastguard Worker BasicBlock *BB = &*FI++;
2205*9880d681SAndroid Build Coastguard Worker
2206*9880d681SAndroid Build Coastguard Worker bool removedBlock =
2207*9880d681SAndroid Build Coastguard Worker MergeBlockIntoPredecessor(BB, DT, /* LoopInfo */ nullptr, MD);
2208*9880d681SAndroid Build Coastguard Worker if (removedBlock) ++NumGVNBlocks;
2209*9880d681SAndroid Build Coastguard Worker
2210*9880d681SAndroid Build Coastguard Worker Changed |= removedBlock;
2211*9880d681SAndroid Build Coastguard Worker }
2212*9880d681SAndroid Build Coastguard Worker
2213*9880d681SAndroid Build Coastguard Worker unsigned Iteration = 0;
2214*9880d681SAndroid Build Coastguard Worker while (ShouldContinue) {
2215*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
2216*9880d681SAndroid Build Coastguard Worker ShouldContinue = iterateOnFunction(F);
2217*9880d681SAndroid Build Coastguard Worker Changed |= ShouldContinue;
2218*9880d681SAndroid Build Coastguard Worker ++Iteration;
2219*9880d681SAndroid Build Coastguard Worker }
2220*9880d681SAndroid Build Coastguard Worker
2221*9880d681SAndroid Build Coastguard Worker if (EnablePRE) {
2222*9880d681SAndroid Build Coastguard Worker // Fabricate val-num for dead-code in order to suppress assertion in
2223*9880d681SAndroid Build Coastguard Worker // performPRE().
2224*9880d681SAndroid Build Coastguard Worker assignValNumForDeadCode();
2225*9880d681SAndroid Build Coastguard Worker bool PREChanged = true;
2226*9880d681SAndroid Build Coastguard Worker while (PREChanged) {
2227*9880d681SAndroid Build Coastguard Worker PREChanged = performPRE(F);
2228*9880d681SAndroid Build Coastguard Worker Changed |= PREChanged;
2229*9880d681SAndroid Build Coastguard Worker }
2230*9880d681SAndroid Build Coastguard Worker }
2231*9880d681SAndroid Build Coastguard Worker
2232*9880d681SAndroid Build Coastguard Worker // FIXME: Should perform GVN again after PRE does something. PRE can move
2233*9880d681SAndroid Build Coastguard Worker // computations into blocks where they become fully redundant. Note that
2234*9880d681SAndroid Build Coastguard Worker // we can't do this until PRE's critical edge splitting updates memdep.
2235*9880d681SAndroid Build Coastguard Worker // Actually, when this happens, we should just fully integrate PRE into GVN.
2236*9880d681SAndroid Build Coastguard Worker
2237*9880d681SAndroid Build Coastguard Worker cleanupGlobalSets();
2238*9880d681SAndroid Build Coastguard Worker // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
2239*9880d681SAndroid Build Coastguard Worker // iteration.
2240*9880d681SAndroid Build Coastguard Worker DeadBlocks.clear();
2241*9880d681SAndroid Build Coastguard Worker
2242*9880d681SAndroid Build Coastguard Worker return Changed;
2243*9880d681SAndroid Build Coastguard Worker }
2244*9880d681SAndroid Build Coastguard Worker
processBlock(BasicBlock * BB)2245*9880d681SAndroid Build Coastguard Worker bool GVN::processBlock(BasicBlock *BB) {
2246*9880d681SAndroid Build Coastguard Worker // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2247*9880d681SAndroid Build Coastguard Worker // (and incrementing BI before processing an instruction).
2248*9880d681SAndroid Build Coastguard Worker assert(InstrsToErase.empty() &&
2249*9880d681SAndroid Build Coastguard Worker "We expect InstrsToErase to be empty across iterations");
2250*9880d681SAndroid Build Coastguard Worker if (DeadBlocks.count(BB))
2251*9880d681SAndroid Build Coastguard Worker return false;
2252*9880d681SAndroid Build Coastguard Worker
2253*9880d681SAndroid Build Coastguard Worker // Clearing map before every BB because it can be used only for single BB.
2254*9880d681SAndroid Build Coastguard Worker ReplaceWithConstMap.clear();
2255*9880d681SAndroid Build Coastguard Worker bool ChangedFunction = false;
2256*9880d681SAndroid Build Coastguard Worker
2257*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2258*9880d681SAndroid Build Coastguard Worker BI != BE;) {
2259*9880d681SAndroid Build Coastguard Worker if (!ReplaceWithConstMap.empty())
2260*9880d681SAndroid Build Coastguard Worker ChangedFunction |= replaceOperandsWithConsts(&*BI);
2261*9880d681SAndroid Build Coastguard Worker ChangedFunction |= processInstruction(&*BI);
2262*9880d681SAndroid Build Coastguard Worker
2263*9880d681SAndroid Build Coastguard Worker if (InstrsToErase.empty()) {
2264*9880d681SAndroid Build Coastguard Worker ++BI;
2265*9880d681SAndroid Build Coastguard Worker continue;
2266*9880d681SAndroid Build Coastguard Worker }
2267*9880d681SAndroid Build Coastguard Worker
2268*9880d681SAndroid Build Coastguard Worker // If we need some instructions deleted, do it now.
2269*9880d681SAndroid Build Coastguard Worker NumGVNInstr += InstrsToErase.size();
2270*9880d681SAndroid Build Coastguard Worker
2271*9880d681SAndroid Build Coastguard Worker // Avoid iterator invalidation.
2272*9880d681SAndroid Build Coastguard Worker bool AtStart = BI == BB->begin();
2273*9880d681SAndroid Build Coastguard Worker if (!AtStart)
2274*9880d681SAndroid Build Coastguard Worker --BI;
2275*9880d681SAndroid Build Coastguard Worker
2276*9880d681SAndroid Build Coastguard Worker for (SmallVectorImpl<Instruction *>::iterator I = InstrsToErase.begin(),
2277*9880d681SAndroid Build Coastguard Worker E = InstrsToErase.end(); I != E; ++I) {
2278*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN removed: " << **I << '\n');
2279*9880d681SAndroid Build Coastguard Worker if (MD) MD->removeInstruction(*I);
2280*9880d681SAndroid Build Coastguard Worker DEBUG(verifyRemoved(*I));
2281*9880d681SAndroid Build Coastguard Worker (*I)->eraseFromParent();
2282*9880d681SAndroid Build Coastguard Worker }
2283*9880d681SAndroid Build Coastguard Worker InstrsToErase.clear();
2284*9880d681SAndroid Build Coastguard Worker
2285*9880d681SAndroid Build Coastguard Worker if (AtStart)
2286*9880d681SAndroid Build Coastguard Worker BI = BB->begin();
2287*9880d681SAndroid Build Coastguard Worker else
2288*9880d681SAndroid Build Coastguard Worker ++BI;
2289*9880d681SAndroid Build Coastguard Worker }
2290*9880d681SAndroid Build Coastguard Worker
2291*9880d681SAndroid Build Coastguard Worker return ChangedFunction;
2292*9880d681SAndroid Build Coastguard Worker }
2293*9880d681SAndroid Build Coastguard Worker
2294*9880d681SAndroid Build Coastguard Worker // Instantiate an expression in a predecessor that lacked it.
performScalarPREInsertion(Instruction * Instr,BasicBlock * Pred,unsigned int ValNo)2295*9880d681SAndroid Build Coastguard Worker bool GVN::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
2296*9880d681SAndroid Build Coastguard Worker unsigned int ValNo) {
2297*9880d681SAndroid Build Coastguard Worker // Because we are going top-down through the block, all value numbers
2298*9880d681SAndroid Build Coastguard Worker // will be available in the predecessor by the time we need them. Any
2299*9880d681SAndroid Build Coastguard Worker // that weren't originally present will have been instantiated earlier
2300*9880d681SAndroid Build Coastguard Worker // in this loop.
2301*9880d681SAndroid Build Coastguard Worker bool success = true;
2302*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) {
2303*9880d681SAndroid Build Coastguard Worker Value *Op = Instr->getOperand(i);
2304*9880d681SAndroid Build Coastguard Worker if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2305*9880d681SAndroid Build Coastguard Worker continue;
2306*9880d681SAndroid Build Coastguard Worker // This could be a newly inserted instruction, in which case, we won't
2307*9880d681SAndroid Build Coastguard Worker // find a value number, and should give up before we hurt ourselves.
2308*9880d681SAndroid Build Coastguard Worker // FIXME: Rewrite the infrastructure to let it easier to value number
2309*9880d681SAndroid Build Coastguard Worker // and process newly inserted instructions.
2310*9880d681SAndroid Build Coastguard Worker if (!VN.exists(Op)) {
2311*9880d681SAndroid Build Coastguard Worker success = false;
2312*9880d681SAndroid Build Coastguard Worker break;
2313*9880d681SAndroid Build Coastguard Worker }
2314*9880d681SAndroid Build Coastguard Worker if (Value *V = findLeader(Pred, VN.lookup(Op))) {
2315*9880d681SAndroid Build Coastguard Worker Instr->setOperand(i, V);
2316*9880d681SAndroid Build Coastguard Worker } else {
2317*9880d681SAndroid Build Coastguard Worker success = false;
2318*9880d681SAndroid Build Coastguard Worker break;
2319*9880d681SAndroid Build Coastguard Worker }
2320*9880d681SAndroid Build Coastguard Worker }
2321*9880d681SAndroid Build Coastguard Worker
2322*9880d681SAndroid Build Coastguard Worker // Fail out if we encounter an operand that is not available in
2323*9880d681SAndroid Build Coastguard Worker // the PRE predecessor. This is typically because of loads which
2324*9880d681SAndroid Build Coastguard Worker // are not value numbered precisely.
2325*9880d681SAndroid Build Coastguard Worker if (!success)
2326*9880d681SAndroid Build Coastguard Worker return false;
2327*9880d681SAndroid Build Coastguard Worker
2328*9880d681SAndroid Build Coastguard Worker Instr->insertBefore(Pred->getTerminator());
2329*9880d681SAndroid Build Coastguard Worker Instr->setName(Instr->getName() + ".pre");
2330*9880d681SAndroid Build Coastguard Worker Instr->setDebugLoc(Instr->getDebugLoc());
2331*9880d681SAndroid Build Coastguard Worker VN.add(Instr, ValNo);
2332*9880d681SAndroid Build Coastguard Worker
2333*9880d681SAndroid Build Coastguard Worker // Update the availability map to include the new instruction.
2334*9880d681SAndroid Build Coastguard Worker addToLeaderTable(ValNo, Instr, Pred);
2335*9880d681SAndroid Build Coastguard Worker return true;
2336*9880d681SAndroid Build Coastguard Worker }
2337*9880d681SAndroid Build Coastguard Worker
performScalarPRE(Instruction * CurInst)2338*9880d681SAndroid Build Coastguard Worker bool GVN::performScalarPRE(Instruction *CurInst) {
2339*9880d681SAndroid Build Coastguard Worker if (isa<AllocaInst>(CurInst) || isa<TerminatorInst>(CurInst) ||
2340*9880d681SAndroid Build Coastguard Worker isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
2341*9880d681SAndroid Build Coastguard Worker CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
2342*9880d681SAndroid Build Coastguard Worker isa<DbgInfoIntrinsic>(CurInst))
2343*9880d681SAndroid Build Coastguard Worker return false;
2344*9880d681SAndroid Build Coastguard Worker
2345*9880d681SAndroid Build Coastguard Worker // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
2346*9880d681SAndroid Build Coastguard Worker // sinking the compare again, and it would force the code generator to
2347*9880d681SAndroid Build Coastguard Worker // move the i1 from processor flags or predicate registers into a general
2348*9880d681SAndroid Build Coastguard Worker // purpose register.
2349*9880d681SAndroid Build Coastguard Worker if (isa<CmpInst>(CurInst))
2350*9880d681SAndroid Build Coastguard Worker return false;
2351*9880d681SAndroid Build Coastguard Worker
2352*9880d681SAndroid Build Coastguard Worker // We don't currently value number ANY inline asm calls.
2353*9880d681SAndroid Build Coastguard Worker if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2354*9880d681SAndroid Build Coastguard Worker if (CallI->isInlineAsm())
2355*9880d681SAndroid Build Coastguard Worker return false;
2356*9880d681SAndroid Build Coastguard Worker
2357*9880d681SAndroid Build Coastguard Worker uint32_t ValNo = VN.lookup(CurInst);
2358*9880d681SAndroid Build Coastguard Worker
2359*9880d681SAndroid Build Coastguard Worker // Look for the predecessors for PRE opportunities. We're
2360*9880d681SAndroid Build Coastguard Worker // only trying to solve the basic diamond case, where
2361*9880d681SAndroid Build Coastguard Worker // a value is computed in the successor and one predecessor,
2362*9880d681SAndroid Build Coastguard Worker // but not the other. We also explicitly disallow cases
2363*9880d681SAndroid Build Coastguard Worker // where the successor is its own predecessor, because they're
2364*9880d681SAndroid Build Coastguard Worker // more complicated to get right.
2365*9880d681SAndroid Build Coastguard Worker unsigned NumWith = 0;
2366*9880d681SAndroid Build Coastguard Worker unsigned NumWithout = 0;
2367*9880d681SAndroid Build Coastguard Worker BasicBlock *PREPred = nullptr;
2368*9880d681SAndroid Build Coastguard Worker BasicBlock *CurrentBlock = CurInst->getParent();
2369*9880d681SAndroid Build Coastguard Worker
2370*9880d681SAndroid Build Coastguard Worker SmallVector<std::pair<Value *, BasicBlock *>, 8> predMap;
2371*9880d681SAndroid Build Coastguard Worker for (BasicBlock *P : predecessors(CurrentBlock)) {
2372*9880d681SAndroid Build Coastguard Worker // We're not interested in PRE where the block is its
2373*9880d681SAndroid Build Coastguard Worker // own predecessor, or in blocks with predecessors
2374*9880d681SAndroid Build Coastguard Worker // that are not reachable.
2375*9880d681SAndroid Build Coastguard Worker if (P == CurrentBlock) {
2376*9880d681SAndroid Build Coastguard Worker NumWithout = 2;
2377*9880d681SAndroid Build Coastguard Worker break;
2378*9880d681SAndroid Build Coastguard Worker } else if (!DT->isReachableFromEntry(P)) {
2379*9880d681SAndroid Build Coastguard Worker NumWithout = 2;
2380*9880d681SAndroid Build Coastguard Worker break;
2381*9880d681SAndroid Build Coastguard Worker }
2382*9880d681SAndroid Build Coastguard Worker
2383*9880d681SAndroid Build Coastguard Worker Value *predV = findLeader(P, ValNo);
2384*9880d681SAndroid Build Coastguard Worker if (!predV) {
2385*9880d681SAndroid Build Coastguard Worker predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
2386*9880d681SAndroid Build Coastguard Worker PREPred = P;
2387*9880d681SAndroid Build Coastguard Worker ++NumWithout;
2388*9880d681SAndroid Build Coastguard Worker } else if (predV == CurInst) {
2389*9880d681SAndroid Build Coastguard Worker /* CurInst dominates this predecessor. */
2390*9880d681SAndroid Build Coastguard Worker NumWithout = 2;
2391*9880d681SAndroid Build Coastguard Worker break;
2392*9880d681SAndroid Build Coastguard Worker } else {
2393*9880d681SAndroid Build Coastguard Worker predMap.push_back(std::make_pair(predV, P));
2394*9880d681SAndroid Build Coastguard Worker ++NumWith;
2395*9880d681SAndroid Build Coastguard Worker }
2396*9880d681SAndroid Build Coastguard Worker }
2397*9880d681SAndroid Build Coastguard Worker
2398*9880d681SAndroid Build Coastguard Worker // Don't do PRE when it might increase code size, i.e. when
2399*9880d681SAndroid Build Coastguard Worker // we would need to insert instructions in more than one pred.
2400*9880d681SAndroid Build Coastguard Worker if (NumWithout > 1 || NumWith == 0)
2401*9880d681SAndroid Build Coastguard Worker return false;
2402*9880d681SAndroid Build Coastguard Worker
2403*9880d681SAndroid Build Coastguard Worker // We may have a case where all predecessors have the instruction,
2404*9880d681SAndroid Build Coastguard Worker // and we just need to insert a phi node. Otherwise, perform
2405*9880d681SAndroid Build Coastguard Worker // insertion.
2406*9880d681SAndroid Build Coastguard Worker Instruction *PREInstr = nullptr;
2407*9880d681SAndroid Build Coastguard Worker
2408*9880d681SAndroid Build Coastguard Worker if (NumWithout != 0) {
2409*9880d681SAndroid Build Coastguard Worker // Don't do PRE across indirect branch.
2410*9880d681SAndroid Build Coastguard Worker if (isa<IndirectBrInst>(PREPred->getTerminator()))
2411*9880d681SAndroid Build Coastguard Worker return false;
2412*9880d681SAndroid Build Coastguard Worker
2413*9880d681SAndroid Build Coastguard Worker // We can't do PRE safely on a critical edge, so instead we schedule
2414*9880d681SAndroid Build Coastguard Worker // the edge to be split and perform the PRE the next time we iterate
2415*9880d681SAndroid Build Coastguard Worker // on the function.
2416*9880d681SAndroid Build Coastguard Worker unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2417*9880d681SAndroid Build Coastguard Worker if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2418*9880d681SAndroid Build Coastguard Worker toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2419*9880d681SAndroid Build Coastguard Worker return false;
2420*9880d681SAndroid Build Coastguard Worker }
2421*9880d681SAndroid Build Coastguard Worker // We need to insert somewhere, so let's give it a shot
2422*9880d681SAndroid Build Coastguard Worker PREInstr = CurInst->clone();
2423*9880d681SAndroid Build Coastguard Worker if (!performScalarPREInsertion(PREInstr, PREPred, ValNo)) {
2424*9880d681SAndroid Build Coastguard Worker // If we failed insertion, make sure we remove the instruction.
2425*9880d681SAndroid Build Coastguard Worker DEBUG(verifyRemoved(PREInstr));
2426*9880d681SAndroid Build Coastguard Worker delete PREInstr;
2427*9880d681SAndroid Build Coastguard Worker return false;
2428*9880d681SAndroid Build Coastguard Worker }
2429*9880d681SAndroid Build Coastguard Worker }
2430*9880d681SAndroid Build Coastguard Worker
2431*9880d681SAndroid Build Coastguard Worker // Either we should have filled in the PRE instruction, or we should
2432*9880d681SAndroid Build Coastguard Worker // not have needed insertions.
2433*9880d681SAndroid Build Coastguard Worker assert (PREInstr != nullptr || NumWithout == 0);
2434*9880d681SAndroid Build Coastguard Worker
2435*9880d681SAndroid Build Coastguard Worker ++NumGVNPRE;
2436*9880d681SAndroid Build Coastguard Worker
2437*9880d681SAndroid Build Coastguard Worker // Create a PHI to make the value available in this block.
2438*9880d681SAndroid Build Coastguard Worker PHINode *Phi =
2439*9880d681SAndroid Build Coastguard Worker PHINode::Create(CurInst->getType(), predMap.size(),
2440*9880d681SAndroid Build Coastguard Worker CurInst->getName() + ".pre-phi", &CurrentBlock->front());
2441*9880d681SAndroid Build Coastguard Worker for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
2442*9880d681SAndroid Build Coastguard Worker if (Value *V = predMap[i].first)
2443*9880d681SAndroid Build Coastguard Worker Phi->addIncoming(V, predMap[i].second);
2444*9880d681SAndroid Build Coastguard Worker else
2445*9880d681SAndroid Build Coastguard Worker Phi->addIncoming(PREInstr, PREPred);
2446*9880d681SAndroid Build Coastguard Worker }
2447*9880d681SAndroid Build Coastguard Worker
2448*9880d681SAndroid Build Coastguard Worker VN.add(Phi, ValNo);
2449*9880d681SAndroid Build Coastguard Worker addToLeaderTable(ValNo, Phi, CurrentBlock);
2450*9880d681SAndroid Build Coastguard Worker Phi->setDebugLoc(CurInst->getDebugLoc());
2451*9880d681SAndroid Build Coastguard Worker CurInst->replaceAllUsesWith(Phi);
2452*9880d681SAndroid Build Coastguard Worker if (MD && Phi->getType()->getScalarType()->isPointerTy())
2453*9880d681SAndroid Build Coastguard Worker MD->invalidateCachedPointerInfo(Phi);
2454*9880d681SAndroid Build Coastguard Worker VN.erase(CurInst);
2455*9880d681SAndroid Build Coastguard Worker removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2456*9880d681SAndroid Build Coastguard Worker
2457*9880d681SAndroid Build Coastguard Worker DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2458*9880d681SAndroid Build Coastguard Worker if (MD)
2459*9880d681SAndroid Build Coastguard Worker MD->removeInstruction(CurInst);
2460*9880d681SAndroid Build Coastguard Worker DEBUG(verifyRemoved(CurInst));
2461*9880d681SAndroid Build Coastguard Worker CurInst->eraseFromParent();
2462*9880d681SAndroid Build Coastguard Worker ++NumGVNInstr;
2463*9880d681SAndroid Build Coastguard Worker
2464*9880d681SAndroid Build Coastguard Worker return true;
2465*9880d681SAndroid Build Coastguard Worker }
2466*9880d681SAndroid Build Coastguard Worker
2467*9880d681SAndroid Build Coastguard Worker /// Perform a purely local form of PRE that looks for diamond
2468*9880d681SAndroid Build Coastguard Worker /// control flow patterns and attempts to perform simple PRE at the join point.
performPRE(Function & F)2469*9880d681SAndroid Build Coastguard Worker bool GVN::performPRE(Function &F) {
2470*9880d681SAndroid Build Coastguard Worker bool Changed = false;
2471*9880d681SAndroid Build Coastguard Worker for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
2472*9880d681SAndroid Build Coastguard Worker // Nothing to PRE in the entry block.
2473*9880d681SAndroid Build Coastguard Worker if (CurrentBlock == &F.getEntryBlock())
2474*9880d681SAndroid Build Coastguard Worker continue;
2475*9880d681SAndroid Build Coastguard Worker
2476*9880d681SAndroid Build Coastguard Worker // Don't perform PRE on an EH pad.
2477*9880d681SAndroid Build Coastguard Worker if (CurrentBlock->isEHPad())
2478*9880d681SAndroid Build Coastguard Worker continue;
2479*9880d681SAndroid Build Coastguard Worker
2480*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator BI = CurrentBlock->begin(),
2481*9880d681SAndroid Build Coastguard Worker BE = CurrentBlock->end();
2482*9880d681SAndroid Build Coastguard Worker BI != BE;) {
2483*9880d681SAndroid Build Coastguard Worker Instruction *CurInst = &*BI++;
2484*9880d681SAndroid Build Coastguard Worker Changed |= performScalarPRE(CurInst);
2485*9880d681SAndroid Build Coastguard Worker }
2486*9880d681SAndroid Build Coastguard Worker }
2487*9880d681SAndroid Build Coastguard Worker
2488*9880d681SAndroid Build Coastguard Worker if (splitCriticalEdges())
2489*9880d681SAndroid Build Coastguard Worker Changed = true;
2490*9880d681SAndroid Build Coastguard Worker
2491*9880d681SAndroid Build Coastguard Worker return Changed;
2492*9880d681SAndroid Build Coastguard Worker }
2493*9880d681SAndroid Build Coastguard Worker
2494*9880d681SAndroid Build Coastguard Worker /// Split the critical edge connecting the given two blocks, and return
2495*9880d681SAndroid Build Coastguard Worker /// the block inserted to the critical edge.
splitCriticalEdges(BasicBlock * Pred,BasicBlock * Succ)2496*9880d681SAndroid Build Coastguard Worker BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
2497*9880d681SAndroid Build Coastguard Worker BasicBlock *BB =
2498*9880d681SAndroid Build Coastguard Worker SplitCriticalEdge(Pred, Succ, CriticalEdgeSplittingOptions(DT));
2499*9880d681SAndroid Build Coastguard Worker if (MD)
2500*9880d681SAndroid Build Coastguard Worker MD->invalidateCachedPredecessors();
2501*9880d681SAndroid Build Coastguard Worker return BB;
2502*9880d681SAndroid Build Coastguard Worker }
2503*9880d681SAndroid Build Coastguard Worker
2504*9880d681SAndroid Build Coastguard Worker /// Split critical edges found during the previous
2505*9880d681SAndroid Build Coastguard Worker /// iteration that may enable further optimization.
splitCriticalEdges()2506*9880d681SAndroid Build Coastguard Worker bool GVN::splitCriticalEdges() {
2507*9880d681SAndroid Build Coastguard Worker if (toSplit.empty())
2508*9880d681SAndroid Build Coastguard Worker return false;
2509*9880d681SAndroid Build Coastguard Worker do {
2510*9880d681SAndroid Build Coastguard Worker std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2511*9880d681SAndroid Build Coastguard Worker SplitCriticalEdge(Edge.first, Edge.second,
2512*9880d681SAndroid Build Coastguard Worker CriticalEdgeSplittingOptions(DT));
2513*9880d681SAndroid Build Coastguard Worker } while (!toSplit.empty());
2514*9880d681SAndroid Build Coastguard Worker if (MD) MD->invalidateCachedPredecessors();
2515*9880d681SAndroid Build Coastguard Worker return true;
2516*9880d681SAndroid Build Coastguard Worker }
2517*9880d681SAndroid Build Coastguard Worker
2518*9880d681SAndroid Build Coastguard Worker /// Executes one iteration of GVN
iterateOnFunction(Function & F)2519*9880d681SAndroid Build Coastguard Worker bool GVN::iterateOnFunction(Function &F) {
2520*9880d681SAndroid Build Coastguard Worker cleanupGlobalSets();
2521*9880d681SAndroid Build Coastguard Worker
2522*9880d681SAndroid Build Coastguard Worker // Top-down walk of the dominator tree
2523*9880d681SAndroid Build Coastguard Worker bool Changed = false;
2524*9880d681SAndroid Build Coastguard Worker // Save the blocks this function have before transformation begins. GVN may
2525*9880d681SAndroid Build Coastguard Worker // split critical edge, and hence may invalidate the RPO/DT iterator.
2526*9880d681SAndroid Build Coastguard Worker //
2527*9880d681SAndroid Build Coastguard Worker std::vector<BasicBlock *> BBVect;
2528*9880d681SAndroid Build Coastguard Worker BBVect.reserve(256);
2529*9880d681SAndroid Build Coastguard Worker // Needed for value numbering with phi construction to work.
2530*9880d681SAndroid Build Coastguard Worker ReversePostOrderTraversal<Function *> RPOT(&F);
2531*9880d681SAndroid Build Coastguard Worker for (ReversePostOrderTraversal<Function *>::rpo_iterator RI = RPOT.begin(),
2532*9880d681SAndroid Build Coastguard Worker RE = RPOT.end();
2533*9880d681SAndroid Build Coastguard Worker RI != RE; ++RI)
2534*9880d681SAndroid Build Coastguard Worker BBVect.push_back(*RI);
2535*9880d681SAndroid Build Coastguard Worker
2536*9880d681SAndroid Build Coastguard Worker for (std::vector<BasicBlock *>::iterator I = BBVect.begin(), E = BBVect.end();
2537*9880d681SAndroid Build Coastguard Worker I != E; I++)
2538*9880d681SAndroid Build Coastguard Worker Changed |= processBlock(*I);
2539*9880d681SAndroid Build Coastguard Worker
2540*9880d681SAndroid Build Coastguard Worker return Changed;
2541*9880d681SAndroid Build Coastguard Worker }
2542*9880d681SAndroid Build Coastguard Worker
cleanupGlobalSets()2543*9880d681SAndroid Build Coastguard Worker void GVN::cleanupGlobalSets() {
2544*9880d681SAndroid Build Coastguard Worker VN.clear();
2545*9880d681SAndroid Build Coastguard Worker LeaderTable.clear();
2546*9880d681SAndroid Build Coastguard Worker TableAllocator.Reset();
2547*9880d681SAndroid Build Coastguard Worker }
2548*9880d681SAndroid Build Coastguard Worker
2549*9880d681SAndroid Build Coastguard Worker /// Verify that the specified instruction does not occur in our
2550*9880d681SAndroid Build Coastguard Worker /// internal data structures.
verifyRemoved(const Instruction * Inst) const2551*9880d681SAndroid Build Coastguard Worker void GVN::verifyRemoved(const Instruction *Inst) const {
2552*9880d681SAndroid Build Coastguard Worker VN.verifyRemoved(Inst);
2553*9880d681SAndroid Build Coastguard Worker
2554*9880d681SAndroid Build Coastguard Worker // Walk through the value number scope to make sure the instruction isn't
2555*9880d681SAndroid Build Coastguard Worker // ferreted away in it.
2556*9880d681SAndroid Build Coastguard Worker for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
2557*9880d681SAndroid Build Coastguard Worker I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
2558*9880d681SAndroid Build Coastguard Worker const LeaderTableEntry *Node = &I->second;
2559*9880d681SAndroid Build Coastguard Worker assert(Node->Val != Inst && "Inst still in value numbering scope!");
2560*9880d681SAndroid Build Coastguard Worker
2561*9880d681SAndroid Build Coastguard Worker while (Node->Next) {
2562*9880d681SAndroid Build Coastguard Worker Node = Node->Next;
2563*9880d681SAndroid Build Coastguard Worker assert(Node->Val != Inst && "Inst still in value numbering scope!");
2564*9880d681SAndroid Build Coastguard Worker }
2565*9880d681SAndroid Build Coastguard Worker }
2566*9880d681SAndroid Build Coastguard Worker }
2567*9880d681SAndroid Build Coastguard Worker
2568*9880d681SAndroid Build Coastguard Worker /// BB is declared dead, which implied other blocks become dead as well. This
2569*9880d681SAndroid Build Coastguard Worker /// function is to add all these blocks to "DeadBlocks". For the dead blocks'
2570*9880d681SAndroid Build Coastguard Worker /// live successors, update their phi nodes by replacing the operands
2571*9880d681SAndroid Build Coastguard Worker /// corresponding to dead blocks with UndefVal.
addDeadBlock(BasicBlock * BB)2572*9880d681SAndroid Build Coastguard Worker void GVN::addDeadBlock(BasicBlock *BB) {
2573*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 4> NewDead;
2574*9880d681SAndroid Build Coastguard Worker SmallSetVector<BasicBlock *, 4> DF;
2575*9880d681SAndroid Build Coastguard Worker
2576*9880d681SAndroid Build Coastguard Worker NewDead.push_back(BB);
2577*9880d681SAndroid Build Coastguard Worker while (!NewDead.empty()) {
2578*9880d681SAndroid Build Coastguard Worker BasicBlock *D = NewDead.pop_back_val();
2579*9880d681SAndroid Build Coastguard Worker if (DeadBlocks.count(D))
2580*9880d681SAndroid Build Coastguard Worker continue;
2581*9880d681SAndroid Build Coastguard Worker
2582*9880d681SAndroid Build Coastguard Worker // All blocks dominated by D are dead.
2583*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 8> Dom;
2584*9880d681SAndroid Build Coastguard Worker DT->getDescendants(D, Dom);
2585*9880d681SAndroid Build Coastguard Worker DeadBlocks.insert(Dom.begin(), Dom.end());
2586*9880d681SAndroid Build Coastguard Worker
2587*9880d681SAndroid Build Coastguard Worker // Figure out the dominance-frontier(D).
2588*9880d681SAndroid Build Coastguard Worker for (BasicBlock *B : Dom) {
2589*9880d681SAndroid Build Coastguard Worker for (BasicBlock *S : successors(B)) {
2590*9880d681SAndroid Build Coastguard Worker if (DeadBlocks.count(S))
2591*9880d681SAndroid Build Coastguard Worker continue;
2592*9880d681SAndroid Build Coastguard Worker
2593*9880d681SAndroid Build Coastguard Worker bool AllPredDead = true;
2594*9880d681SAndroid Build Coastguard Worker for (BasicBlock *P : predecessors(S))
2595*9880d681SAndroid Build Coastguard Worker if (!DeadBlocks.count(P)) {
2596*9880d681SAndroid Build Coastguard Worker AllPredDead = false;
2597*9880d681SAndroid Build Coastguard Worker break;
2598*9880d681SAndroid Build Coastguard Worker }
2599*9880d681SAndroid Build Coastguard Worker
2600*9880d681SAndroid Build Coastguard Worker if (!AllPredDead) {
2601*9880d681SAndroid Build Coastguard Worker // S could be proved dead later on. That is why we don't update phi
2602*9880d681SAndroid Build Coastguard Worker // operands at this moment.
2603*9880d681SAndroid Build Coastguard Worker DF.insert(S);
2604*9880d681SAndroid Build Coastguard Worker } else {
2605*9880d681SAndroid Build Coastguard Worker // While S is not dominated by D, it is dead by now. This could take
2606*9880d681SAndroid Build Coastguard Worker // place if S already have a dead predecessor before D is declared
2607*9880d681SAndroid Build Coastguard Worker // dead.
2608*9880d681SAndroid Build Coastguard Worker NewDead.push_back(S);
2609*9880d681SAndroid Build Coastguard Worker }
2610*9880d681SAndroid Build Coastguard Worker }
2611*9880d681SAndroid Build Coastguard Worker }
2612*9880d681SAndroid Build Coastguard Worker }
2613*9880d681SAndroid Build Coastguard Worker
2614*9880d681SAndroid Build Coastguard Worker // For the dead blocks' live successors, update their phi nodes by replacing
2615*9880d681SAndroid Build Coastguard Worker // the operands corresponding to dead blocks with UndefVal.
2616*9880d681SAndroid Build Coastguard Worker for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
2617*9880d681SAndroid Build Coastguard Worker I != E; I++) {
2618*9880d681SAndroid Build Coastguard Worker BasicBlock *B = *I;
2619*9880d681SAndroid Build Coastguard Worker if (DeadBlocks.count(B))
2620*9880d681SAndroid Build Coastguard Worker continue;
2621*9880d681SAndroid Build Coastguard Worker
2622*9880d681SAndroid Build Coastguard Worker SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
2623*9880d681SAndroid Build Coastguard Worker for (BasicBlock *P : Preds) {
2624*9880d681SAndroid Build Coastguard Worker if (!DeadBlocks.count(P))
2625*9880d681SAndroid Build Coastguard Worker continue;
2626*9880d681SAndroid Build Coastguard Worker
2627*9880d681SAndroid Build Coastguard Worker if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
2628*9880d681SAndroid Build Coastguard Worker if (BasicBlock *S = splitCriticalEdges(P, B))
2629*9880d681SAndroid Build Coastguard Worker DeadBlocks.insert(P = S);
2630*9880d681SAndroid Build Coastguard Worker }
2631*9880d681SAndroid Build Coastguard Worker
2632*9880d681SAndroid Build Coastguard Worker for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); ++II) {
2633*9880d681SAndroid Build Coastguard Worker PHINode &Phi = cast<PHINode>(*II);
2634*9880d681SAndroid Build Coastguard Worker Phi.setIncomingValue(Phi.getBasicBlockIndex(P),
2635*9880d681SAndroid Build Coastguard Worker UndefValue::get(Phi.getType()));
2636*9880d681SAndroid Build Coastguard Worker }
2637*9880d681SAndroid Build Coastguard Worker }
2638*9880d681SAndroid Build Coastguard Worker }
2639*9880d681SAndroid Build Coastguard Worker }
2640*9880d681SAndroid Build Coastguard Worker
2641*9880d681SAndroid Build Coastguard Worker // If the given branch is recognized as a foldable branch (i.e. conditional
2642*9880d681SAndroid Build Coastguard Worker // branch with constant condition), it will perform following analyses and
2643*9880d681SAndroid Build Coastguard Worker // transformation.
2644*9880d681SAndroid Build Coastguard Worker // 1) If the dead out-coming edge is a critical-edge, split it. Let
2645*9880d681SAndroid Build Coastguard Worker // R be the target of the dead out-coming edge.
2646*9880d681SAndroid Build Coastguard Worker // 1) Identify the set of dead blocks implied by the branch's dead outcoming
2647*9880d681SAndroid Build Coastguard Worker // edge. The result of this step will be {X| X is dominated by R}
2648*9880d681SAndroid Build Coastguard Worker // 2) Identify those blocks which haves at least one dead predecessor. The
2649*9880d681SAndroid Build Coastguard Worker // result of this step will be dominance-frontier(R).
2650*9880d681SAndroid Build Coastguard Worker // 3) Update the PHIs in DF(R) by replacing the operands corresponding to
2651*9880d681SAndroid Build Coastguard Worker // dead blocks with "UndefVal" in an hope these PHIs will optimized away.
2652*9880d681SAndroid Build Coastguard Worker //
2653*9880d681SAndroid Build Coastguard Worker // Return true iff *NEW* dead code are found.
processFoldableCondBr(BranchInst * BI)2654*9880d681SAndroid Build Coastguard Worker bool GVN::processFoldableCondBr(BranchInst *BI) {
2655*9880d681SAndroid Build Coastguard Worker if (!BI || BI->isUnconditional())
2656*9880d681SAndroid Build Coastguard Worker return false;
2657*9880d681SAndroid Build Coastguard Worker
2658*9880d681SAndroid Build Coastguard Worker // If a branch has two identical successors, we cannot declare either dead.
2659*9880d681SAndroid Build Coastguard Worker if (BI->getSuccessor(0) == BI->getSuccessor(1))
2660*9880d681SAndroid Build Coastguard Worker return false;
2661*9880d681SAndroid Build Coastguard Worker
2662*9880d681SAndroid Build Coastguard Worker ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
2663*9880d681SAndroid Build Coastguard Worker if (!Cond)
2664*9880d681SAndroid Build Coastguard Worker return false;
2665*9880d681SAndroid Build Coastguard Worker
2666*9880d681SAndroid Build Coastguard Worker BasicBlock *DeadRoot =
2667*9880d681SAndroid Build Coastguard Worker Cond->getZExtValue() ? BI->getSuccessor(1) : BI->getSuccessor(0);
2668*9880d681SAndroid Build Coastguard Worker if (DeadBlocks.count(DeadRoot))
2669*9880d681SAndroid Build Coastguard Worker return false;
2670*9880d681SAndroid Build Coastguard Worker
2671*9880d681SAndroid Build Coastguard Worker if (!DeadRoot->getSinglePredecessor())
2672*9880d681SAndroid Build Coastguard Worker DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
2673*9880d681SAndroid Build Coastguard Worker
2674*9880d681SAndroid Build Coastguard Worker addDeadBlock(DeadRoot);
2675*9880d681SAndroid Build Coastguard Worker return true;
2676*9880d681SAndroid Build Coastguard Worker }
2677*9880d681SAndroid Build Coastguard Worker
2678*9880d681SAndroid Build Coastguard Worker // performPRE() will trigger assert if it comes across an instruction without
2679*9880d681SAndroid Build Coastguard Worker // associated val-num. As it normally has far more live instructions than dead
2680*9880d681SAndroid Build Coastguard Worker // instructions, it makes more sense just to "fabricate" a val-number for the
2681*9880d681SAndroid Build Coastguard Worker // dead code than checking if instruction involved is dead or not.
assignValNumForDeadCode()2682*9880d681SAndroid Build Coastguard Worker void GVN::assignValNumForDeadCode() {
2683*9880d681SAndroid Build Coastguard Worker for (BasicBlock *BB : DeadBlocks) {
2684*9880d681SAndroid Build Coastguard Worker for (Instruction &Inst : *BB) {
2685*9880d681SAndroid Build Coastguard Worker unsigned ValNum = VN.lookupOrAdd(&Inst);
2686*9880d681SAndroid Build Coastguard Worker addToLeaderTable(ValNum, &Inst, BB);
2687*9880d681SAndroid Build Coastguard Worker }
2688*9880d681SAndroid Build Coastguard Worker }
2689*9880d681SAndroid Build Coastguard Worker }
2690*9880d681SAndroid Build Coastguard Worker
2691*9880d681SAndroid Build Coastguard Worker class llvm::gvn::GVNLegacyPass : public FunctionPass {
2692*9880d681SAndroid Build Coastguard Worker public:
2693*9880d681SAndroid Build Coastguard Worker static char ID; // Pass identification, replacement for typeid
GVNLegacyPass(bool NoLoads=false)2694*9880d681SAndroid Build Coastguard Worker explicit GVNLegacyPass(bool NoLoads = false)
2695*9880d681SAndroid Build Coastguard Worker : FunctionPass(ID), NoLoads(NoLoads) {
2696*9880d681SAndroid Build Coastguard Worker initializeGVNLegacyPassPass(*PassRegistry::getPassRegistry());
2697*9880d681SAndroid Build Coastguard Worker }
2698*9880d681SAndroid Build Coastguard Worker
runOnFunction(Function & F)2699*9880d681SAndroid Build Coastguard Worker bool runOnFunction(Function &F) override {
2700*9880d681SAndroid Build Coastguard Worker if (skipFunction(F))
2701*9880d681SAndroid Build Coastguard Worker return false;
2702*9880d681SAndroid Build Coastguard Worker
2703*9880d681SAndroid Build Coastguard Worker return Impl.runImpl(
2704*9880d681SAndroid Build Coastguard Worker F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2705*9880d681SAndroid Build Coastguard Worker getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2706*9880d681SAndroid Build Coastguard Worker getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
2707*9880d681SAndroid Build Coastguard Worker getAnalysis<AAResultsWrapperPass>().getAAResults(),
2708*9880d681SAndroid Build Coastguard Worker NoLoads ? nullptr
2709*9880d681SAndroid Build Coastguard Worker : &getAnalysis<MemoryDependenceWrapperPass>().getMemDep());
2710*9880d681SAndroid Build Coastguard Worker }
2711*9880d681SAndroid Build Coastguard Worker
getAnalysisUsage(AnalysisUsage & AU) const2712*9880d681SAndroid Build Coastguard Worker void getAnalysisUsage(AnalysisUsage &AU) const override {
2713*9880d681SAndroid Build Coastguard Worker AU.addRequired<AssumptionCacheTracker>();
2714*9880d681SAndroid Build Coastguard Worker AU.addRequired<DominatorTreeWrapperPass>();
2715*9880d681SAndroid Build Coastguard Worker AU.addRequired<TargetLibraryInfoWrapperPass>();
2716*9880d681SAndroid Build Coastguard Worker if (!NoLoads)
2717*9880d681SAndroid Build Coastguard Worker AU.addRequired<MemoryDependenceWrapperPass>();
2718*9880d681SAndroid Build Coastguard Worker AU.addRequired<AAResultsWrapperPass>();
2719*9880d681SAndroid Build Coastguard Worker
2720*9880d681SAndroid Build Coastguard Worker AU.addPreserved<DominatorTreeWrapperPass>();
2721*9880d681SAndroid Build Coastguard Worker AU.addPreserved<GlobalsAAWrapperPass>();
2722*9880d681SAndroid Build Coastguard Worker }
2723*9880d681SAndroid Build Coastguard Worker
2724*9880d681SAndroid Build Coastguard Worker private:
2725*9880d681SAndroid Build Coastguard Worker bool NoLoads;
2726*9880d681SAndroid Build Coastguard Worker GVN Impl;
2727*9880d681SAndroid Build Coastguard Worker };
2728*9880d681SAndroid Build Coastguard Worker
2729*9880d681SAndroid Build Coastguard Worker char GVNLegacyPass::ID = 0;
2730*9880d681SAndroid Build Coastguard Worker
2731*9880d681SAndroid Build Coastguard Worker // The public interface to this file...
createGVNPass(bool NoLoads)2732*9880d681SAndroid Build Coastguard Worker FunctionPass *llvm::createGVNPass(bool NoLoads) {
2733*9880d681SAndroid Build Coastguard Worker return new GVNLegacyPass(NoLoads);
2734*9880d681SAndroid Build Coastguard Worker }
2735*9880d681SAndroid Build Coastguard Worker
2736*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_BEGIN(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
2737*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2738*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
2739*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2740*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2741*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2742*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2743*9880d681SAndroid Build Coastguard Worker INITIALIZE_PASS_END(GVNLegacyPass, "gvn", "Global Value Numbering", false, false)
2744