LLVM  mainline
GVN.cpp
Go to the documentation of this file.
00001 //===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass performs global value numbering to eliminate fully redundant
00011 // instructions.  It also performs simple dead load elimination.
00012 //
00013 // Note that this pass does the value numbering itself; it does not use the
00014 // ValueNumbering analysis passes.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #include "llvm/Transforms/Scalar.h"
00019 #include "llvm/ADT/DenseMap.h"
00020 #include "llvm/ADT/DepthFirstIterator.h"
00021 #include "llvm/ADT/Hashing.h"
00022 #include "llvm/ADT/MapVector.h"
00023 #include "llvm/ADT/PostOrderIterator.h"
00024 #include "llvm/ADT/SetVector.h"
00025 #include "llvm/ADT/SmallPtrSet.h"
00026 #include "llvm/ADT/Statistic.h"
00027 #include "llvm/Analysis/AliasAnalysis.h"
00028 #include "llvm/Analysis/AssumptionCache.h"
00029 #include "llvm/Analysis/CFG.h"
00030 #include "llvm/Analysis/ConstantFolding.h"
00031 #include "llvm/Analysis/InstructionSimplify.h"
00032 #include "llvm/Analysis/Loads.h"
00033 #include "llvm/Analysis/MemoryBuiltins.h"
00034 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
00035 #include "llvm/Analysis/PHITransAddr.h"
00036 #include "llvm/Analysis/TargetLibraryInfo.h"
00037 #include "llvm/Analysis/ValueTracking.h"
00038 #include "llvm/IR/DataLayout.h"
00039 #include "llvm/IR/Dominators.h"
00040 #include "llvm/IR/GlobalVariable.h"
00041 #include "llvm/IR/IRBuilder.h"
00042 #include "llvm/IR/IntrinsicInst.h"
00043 #include "llvm/IR/LLVMContext.h"
00044 #include "llvm/IR/Metadata.h"
00045 #include "llvm/IR/PatternMatch.h"
00046 #include "llvm/Support/Allocator.h"
00047 #include "llvm/Support/CommandLine.h"
00048 #include "llvm/Support/Debug.h"
00049 #include "llvm/Support/raw_ostream.h"
00050 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00051 #include "llvm/Transforms/Utils/Local.h"
00052 #include "llvm/Transforms/Utils/SSAUpdater.h"
00053 #include <vector>
00054 using namespace llvm;
00055 using namespace PatternMatch;
00056 
00057 #define DEBUG_TYPE "gvn"
00058 
00059 STATISTIC(NumGVNInstr,  "Number of instructions deleted");
00060 STATISTIC(NumGVNLoad,   "Number of loads deleted");
00061 STATISTIC(NumGVNPRE,    "Number of instructions PRE'd");
00062 STATISTIC(NumGVNBlocks, "Number of blocks merged");
00063 STATISTIC(NumGVNSimpl,  "Number of instructions simplified");
00064 STATISTIC(NumGVNEqProp, "Number of equalities propagated");
00065 STATISTIC(NumPRELoad,   "Number of loads PRE'd");
00066 
00067 static cl::opt<bool> EnablePRE("enable-pre",
00068                                cl::init(true), cl::Hidden);
00069 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
00070 
00071 // Maximum allowed recursion depth.
00072 static cl::opt<uint32_t>
00073 MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
00074                 cl::desc("Max recurse depth (default = 1000)"));
00075 
00076 //===----------------------------------------------------------------------===//
00077 //                         ValueTable Class
00078 //===----------------------------------------------------------------------===//
00079 
00080 /// This class holds the mapping between values and value numbers.  It is used
00081 /// as an efficient mechanism to determine the expression-wise equivalence of
00082 /// two values.
00083 namespace {
00084   struct Expression {
00085     uint32_t opcode;
00086     Type *type;
00087     SmallVector<uint32_t, 4> varargs;
00088 
00089     Expression(uint32_t o = ~2U) : opcode(o) { }
00090 
00091     bool operator==(const Expression &other) const {
00092       if (opcode != other.opcode)
00093         return false;
00094       if (opcode == ~0U || opcode == ~1U)
00095         return true;
00096       if (type != other.type)
00097         return false;
00098       if (varargs != other.varargs)
00099         return false;
00100       return true;
00101     }
00102 
00103     friend hash_code hash_value(const Expression &Value) {
00104       return hash_combine(Value.opcode, Value.type,
00105                           hash_combine_range(Value.varargs.begin(),
00106                                              Value.varargs.end()));
00107     }
00108   };
00109 
00110   class ValueTable {
00111     DenseMap<Value*, uint32_t> valueNumbering;
00112     DenseMap<Expression, uint32_t> expressionNumbering;
00113     AliasAnalysis *AA;
00114     MemoryDependenceAnalysis *MD;
00115     DominatorTree *DT;
00116 
00117     uint32_t nextValueNumber;
00118 
00119     Expression create_expression(Instruction* I);
00120     Expression create_cmp_expression(unsigned Opcode,
00121                                      CmpInst::Predicate Predicate,
00122                                      Value *LHS, Value *RHS);
00123     Expression create_extractvalue_expression(ExtractValueInst* EI);
00124     uint32_t lookup_or_add_call(CallInst* C);
00125   public:
00126     ValueTable() : nextValueNumber(1) { }
00127     uint32_t lookup_or_add(Value *V);
00128     uint32_t lookup(Value *V) const;
00129     uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
00130                                Value *LHS, Value *RHS);
00131     void add(Value *V, uint32_t num);
00132     void clear();
00133     void erase(Value *v);
00134     void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
00135     AliasAnalysis *getAliasAnalysis() const { return AA; }
00136     void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
00137     void setDomTree(DominatorTree* D) { DT = D; }
00138     uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
00139     void verifyRemoved(const Value *) const;
00140   };
00141 }
00142 
00143 namespace llvm {
00144 template <> struct DenseMapInfo<Expression> {
00145   static inline Expression getEmptyKey() {
00146     return ~0U;
00147   }
00148 
00149   static inline Expression getTombstoneKey() {
00150     return ~1U;
00151   }
00152 
00153   static unsigned getHashValue(const Expression e) {
00154     using llvm::hash_value;
00155     return static_cast<unsigned>(hash_value(e));
00156   }
00157   static bool isEqual(const Expression &LHS, const Expression &RHS) {
00158     return LHS == RHS;
00159   }
00160 };
00161 
00162 }
00163 
00164 //===----------------------------------------------------------------------===//
00165 //                     ValueTable Internal Functions
00166 //===----------------------------------------------------------------------===//
00167 
00168 Expression ValueTable::create_expression(Instruction *I) {
00169   Expression e;
00170   e.type = I->getType();
00171   e.opcode = I->getOpcode();
00172   for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
00173        OI != OE; ++OI)
00174     e.varargs.push_back(lookup_or_add(*OI));
00175   if (I->isCommutative()) {
00176     // Ensure that commutative instructions that only differ by a permutation
00177     // of their operands get the same value number by sorting the operand value
00178     // numbers.  Since all commutative instructions have two operands it is more
00179     // efficient to sort by hand rather than using, say, std::sort.
00180     assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
00181     if (e.varargs[0] > e.varargs[1])
00182       std::swap(e.varargs[0], e.varargs[1]);
00183   }
00184 
00185   if (CmpInst *C = dyn_cast<CmpInst>(I)) {
00186     // Sort the operand value numbers so x<y and y>x get the same value number.
00187     CmpInst::Predicate Predicate = C->getPredicate();
00188     if (e.varargs[0] > e.varargs[1]) {
00189       std::swap(e.varargs[0], e.varargs[1]);
00190       Predicate = CmpInst::getSwappedPredicate(Predicate);
00191     }
00192     e.opcode = (C->getOpcode() << 8) | Predicate;
00193   } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
00194     for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
00195          II != IE; ++II)
00196       e.varargs.push_back(*II);
00197   }
00198 
00199   return e;
00200 }
00201 
00202 Expression ValueTable::create_cmp_expression(unsigned Opcode,
00203                                              CmpInst::Predicate Predicate,
00204                                              Value *LHS, Value *RHS) {
00205   assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
00206          "Not a comparison!");
00207   Expression e;
00208   e.type = CmpInst::makeCmpResultType(LHS->getType());
00209   e.varargs.push_back(lookup_or_add(LHS));
00210   e.varargs.push_back(lookup_or_add(RHS));
00211 
00212   // Sort the operand value numbers so x<y and y>x get the same value number.
00213   if (e.varargs[0] > e.varargs[1]) {
00214     std::swap(e.varargs[0], e.varargs[1]);
00215     Predicate = CmpInst::getSwappedPredicate(Predicate);
00216   }
00217   e.opcode = (Opcode << 8) | Predicate;
00218   return e;
00219 }
00220 
00221 Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
00222   assert(EI && "Not an ExtractValueInst?");
00223   Expression e;
00224   e.type = EI->getType();
00225   e.opcode = 0;
00226 
00227   IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
00228   if (I != nullptr && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
00229     // EI might be an extract from one of our recognised intrinsics. If it
00230     // is we'll synthesize a semantically equivalent expression instead on
00231     // an extract value expression.
00232     switch (I->getIntrinsicID()) {
00233       case Intrinsic::sadd_with_overflow:
00234       case Intrinsic::uadd_with_overflow:
00235         e.opcode = Instruction::Add;
00236         break;
00237       case Intrinsic::ssub_with_overflow:
00238       case Intrinsic::usub_with_overflow:
00239         e.opcode = Instruction::Sub;
00240         break;
00241       case Intrinsic::smul_with_overflow:
00242       case Intrinsic::umul_with_overflow:
00243         e.opcode = Instruction::Mul;
00244         break;
00245       default:
00246         break;
00247     }
00248 
00249     if (e.opcode != 0) {
00250       // Intrinsic recognized. Grab its args to finish building the expression.
00251       assert(I->getNumArgOperands() == 2 &&
00252              "Expect two args for recognised intrinsics.");
00253       e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
00254       e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
00255       return e;
00256     }
00257   }
00258 
00259   // Not a recognised intrinsic. Fall back to producing an extract value
00260   // expression.
00261   e.opcode = EI->getOpcode();
00262   for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
00263        OI != OE; ++OI)
00264     e.varargs.push_back(lookup_or_add(*OI));
00265 
00266   for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
00267          II != IE; ++II)
00268     e.varargs.push_back(*II);
00269 
00270   return e;
00271 }
00272 
00273 //===----------------------------------------------------------------------===//
00274 //                     ValueTable External Functions
00275 //===----------------------------------------------------------------------===//
00276 
00277 /// add - Insert a value into the table with a specified value number.
00278 void ValueTable::add(Value *V, uint32_t num) {
00279   valueNumbering.insert(std::make_pair(V, num));
00280 }
00281 
00282 uint32_t ValueTable::lookup_or_add_call(CallInst *C) {
00283   if (AA->doesNotAccessMemory(C)) {
00284     Expression exp = create_expression(C);
00285     uint32_t &e = expressionNumbering[exp];
00286     if (!e) e = nextValueNumber++;
00287     valueNumbering[C] = e;
00288     return e;
00289   } else if (AA->onlyReadsMemory(C)) {
00290     Expression exp = create_expression(C);
00291     uint32_t &e = expressionNumbering[exp];
00292     if (!e) {
00293       e = nextValueNumber++;
00294       valueNumbering[C] = e;
00295       return e;
00296     }
00297     if (!MD) {
00298       e = nextValueNumber++;
00299       valueNumbering[C] = e;
00300       return e;
00301     }
00302 
00303     MemDepResult local_dep = MD->getDependency(C);
00304 
00305     if (!local_dep.isDef() && !local_dep.isNonLocal()) {
00306       valueNumbering[C] =  nextValueNumber;
00307       return nextValueNumber++;
00308     }
00309 
00310     if (local_dep.isDef()) {
00311       CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
00312 
00313       if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
00314         valueNumbering[C] = nextValueNumber;
00315         return nextValueNumber++;
00316       }
00317 
00318       for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
00319         uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
00320         uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
00321         if (c_vn != cd_vn) {
00322           valueNumbering[C] = nextValueNumber;
00323           return nextValueNumber++;
00324         }
00325       }
00326 
00327       uint32_t v = lookup_or_add(local_cdep);
00328       valueNumbering[C] = v;
00329       return v;
00330     }
00331 
00332     // Non-local case.
00333     const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
00334       MD->getNonLocalCallDependency(CallSite(C));
00335     // FIXME: Move the checking logic to MemDep!
00336     CallInst* cdep = nullptr;
00337 
00338     // Check to see if we have a single dominating call instruction that is
00339     // identical to C.
00340     for (unsigned i = 0, e = deps.size(); i != e; ++i) {
00341       const NonLocalDepEntry *I = &deps[i];
00342       if (I->getResult().isNonLocal())
00343         continue;
00344 
00345       // We don't handle non-definitions.  If we already have a call, reject
00346       // instruction dependencies.
00347       if (!I->getResult().isDef() || cdep != nullptr) {
00348         cdep = nullptr;
00349         break;
00350       }
00351 
00352       CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
00353       // FIXME: All duplicated with non-local case.
00354       if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
00355         cdep = NonLocalDepCall;
00356         continue;
00357       }
00358 
00359       cdep = nullptr;
00360       break;
00361     }
00362 
00363     if (!cdep) {
00364       valueNumbering[C] = nextValueNumber;
00365       return nextValueNumber++;
00366     }
00367 
00368     if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
00369       valueNumbering[C] = nextValueNumber;
00370       return nextValueNumber++;
00371     }
00372     for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
00373       uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
00374       uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
00375       if (c_vn != cd_vn) {
00376         valueNumbering[C] = nextValueNumber;
00377         return nextValueNumber++;
00378       }
00379     }
00380 
00381     uint32_t v = lookup_or_add(cdep);
00382     valueNumbering[C] = v;
00383     return v;
00384 
00385   } else {
00386     valueNumbering[C] = nextValueNumber;
00387     return nextValueNumber++;
00388   }
00389 }
00390 
00391 /// lookup_or_add - Returns the value number for the specified value, assigning
00392 /// it a new number if it did not have one before.
00393 uint32_t ValueTable::lookup_or_add(Value *V) {
00394   DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
00395   if (VI != valueNumbering.end())
00396     return VI->second;
00397 
00398   if (!isa<Instruction>(V)) {
00399     valueNumbering[V] = nextValueNumber;
00400     return nextValueNumber++;
00401   }
00402 
00403   Instruction* I = cast<Instruction>(V);
00404   Expression exp;
00405   switch (I->getOpcode()) {
00406     case Instruction::Call:
00407       return lookup_or_add_call(cast<CallInst>(I));
00408     case Instruction::Add:
00409     case Instruction::FAdd:
00410     case Instruction::Sub:
00411     case Instruction::FSub:
00412     case Instruction::Mul:
00413     case Instruction::FMul:
00414     case Instruction::UDiv:
00415     case Instruction::SDiv:
00416     case Instruction::FDiv:
00417     case Instruction::URem:
00418     case Instruction::SRem:
00419     case Instruction::FRem:
00420     case Instruction::Shl:
00421     case Instruction::LShr:
00422     case Instruction::AShr:
00423     case Instruction::And:
00424     case Instruction::Or:
00425     case Instruction::Xor:
00426     case Instruction::ICmp:
00427     case Instruction::FCmp:
00428     case Instruction::Trunc:
00429     case Instruction::ZExt:
00430     case Instruction::SExt:
00431     case Instruction::FPToUI:
00432     case Instruction::FPToSI:
00433     case Instruction::UIToFP:
00434     case Instruction::SIToFP:
00435     case Instruction::FPTrunc:
00436     case Instruction::FPExt:
00437     case Instruction::PtrToInt:
00438     case Instruction::IntToPtr:
00439     case Instruction::BitCast:
00440     case Instruction::Select:
00441     case Instruction::ExtractElement:
00442     case Instruction::InsertElement:
00443     case Instruction::ShuffleVector:
00444     case Instruction::InsertValue:
00445     case Instruction::GetElementPtr:
00446       exp = create_expression(I);
00447       break;
00448     case Instruction::ExtractValue:
00449       exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
00450       break;
00451     default:
00452       valueNumbering[V] = nextValueNumber;
00453       return nextValueNumber++;
00454   }
00455 
00456   uint32_t& e = expressionNumbering[exp];
00457   if (!e) e = nextValueNumber++;
00458   valueNumbering[V] = e;
00459   return e;
00460 }
00461 
00462 /// Returns the value number of the specified value. Fails if
00463 /// the value has not yet been numbered.
00464 uint32_t ValueTable::lookup(Value *V) const {
00465   DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
00466   assert(VI != valueNumbering.end() && "Value not numbered?");
00467   return VI->second;
00468 }
00469 
00470 /// Returns the value number of the given comparison,
00471 /// assigning it a new number if it did not have one before.  Useful when
00472 /// we deduced the result of a comparison, but don't immediately have an
00473 /// instruction realizing that comparison to hand.
00474 uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
00475                                        CmpInst::Predicate Predicate,
00476                                        Value *LHS, Value *RHS) {
00477   Expression exp = create_cmp_expression(Opcode, Predicate, LHS, RHS);
00478   uint32_t& e = expressionNumbering[exp];
00479   if (!e) e = nextValueNumber++;
00480   return e;
00481 }
00482 
00483 /// Remove all entries from the ValueTable.
00484 void ValueTable::clear() {
00485   valueNumbering.clear();
00486   expressionNumbering.clear();
00487   nextValueNumber = 1;
00488 }
00489 
00490 /// Remove a value from the value numbering.
00491 void ValueTable::erase(Value *V) {
00492   valueNumbering.erase(V);
00493 }
00494 
00495 /// verifyRemoved - Verify that the value is removed from all internal data
00496 /// structures.
00497 void ValueTable::verifyRemoved(const Value *V) const {
00498   for (DenseMap<Value*, uint32_t>::const_iterator
00499          I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
00500     assert(I->first != V && "Inst still occurs in value numbering map!");
00501   }
00502 }
00503 
00504 //===----------------------------------------------------------------------===//
00505 //                                GVN Pass
00506 //===----------------------------------------------------------------------===//
00507 
00508 namespace {
00509   class GVN;
00510   struct AvailableValueInBlock {
00511     /// BB - The basic block in question.
00512     BasicBlock *BB;
00513     enum ValType {
00514       SimpleVal,  // A simple offsetted value that is accessed.
00515       LoadVal,    // A value produced by a load.
00516       MemIntrin,  // A memory intrinsic which is loaded from.
00517       UndefVal    // A UndefValue representing a value from dead block (which
00518                   // is not yet physically removed from the CFG). 
00519     };
00520   
00521     /// V - The value that is live out of the block.
00522     PointerIntPair<Value *, 2, ValType> Val;
00523   
00524     /// Offset - The byte offset in Val that is interesting for the load query.
00525     unsigned Offset;
00526   
00527     static AvailableValueInBlock get(BasicBlock *BB, Value *V,
00528                                      unsigned Offset = 0) {
00529       AvailableValueInBlock Res;
00530       Res.BB = BB;
00531       Res.Val.setPointer(V);
00532       Res.Val.setInt(SimpleVal);
00533       Res.Offset = Offset;
00534       return Res;
00535     }
00536   
00537     static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
00538                                        unsigned Offset = 0) {
00539       AvailableValueInBlock Res;
00540       Res.BB = BB;
00541       Res.Val.setPointer(MI);
00542       Res.Val.setInt(MemIntrin);
00543       Res.Offset = Offset;
00544       return Res;
00545     }
00546   
00547     static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
00548                                          unsigned Offset = 0) {
00549       AvailableValueInBlock Res;
00550       Res.BB = BB;
00551       Res.Val.setPointer(LI);
00552       Res.Val.setInt(LoadVal);
00553       Res.Offset = Offset;
00554       return Res;
00555     }
00556 
00557     static AvailableValueInBlock getUndef(BasicBlock *BB) {
00558       AvailableValueInBlock Res;
00559       Res.BB = BB;
00560       Res.Val.setPointer(nullptr);
00561       Res.Val.setInt(UndefVal);
00562       Res.Offset = 0;
00563       return Res;
00564     }
00565 
00566     bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
00567     bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
00568     bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
00569     bool isUndefValue() const { return Val.getInt() == UndefVal; }
00570   
00571     Value *getSimpleValue() const {
00572       assert(isSimpleValue() && "Wrong accessor");
00573       return Val.getPointer();
00574     }
00575   
00576     LoadInst *getCoercedLoadValue() const {
00577       assert(isCoercedLoadValue() && "Wrong accessor");
00578       return cast<LoadInst>(Val.getPointer());
00579     }
00580   
00581     MemIntrinsic *getMemIntrinValue() const {
00582       assert(isMemIntrinValue() && "Wrong accessor");
00583       return cast<MemIntrinsic>(Val.getPointer());
00584     }
00585   
00586     /// Emit code into this block to adjust the value defined here to the
00587     /// specified type. This handles various coercion cases.
00588     Value *MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const;
00589   };
00590 
00591   class GVN : public FunctionPass {
00592     bool NoLoads;
00593     MemoryDependenceAnalysis *MD;
00594     DominatorTree *DT;
00595     const TargetLibraryInfo *TLI;
00596     AssumptionCache *AC;
00597     SetVector<BasicBlock *> DeadBlocks;
00598 
00599     ValueTable VN;
00600 
00601     /// A mapping from value numbers to lists of Value*'s that
00602     /// have that value number.  Use findLeader to query it.
00603     struct LeaderTableEntry {
00604       Value *Val;
00605       const BasicBlock *BB;
00606       LeaderTableEntry *Next;
00607     };
00608     DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
00609     BumpPtrAllocator TableAllocator;
00610 
00611     SmallVector<Instruction*, 8> InstrsToErase;
00612 
00613     typedef SmallVector<NonLocalDepResult, 64> LoadDepVect;
00614     typedef SmallVector<AvailableValueInBlock, 64> AvailValInBlkVect;
00615     typedef SmallVector<BasicBlock*, 64> UnavailBlkVect;
00616 
00617   public:
00618     static char ID; // Pass identification, replacement for typeid
00619     explicit GVN(bool noloads = false)
00620         : FunctionPass(ID), NoLoads(noloads), MD(nullptr) {
00621       initializeGVNPass(*PassRegistry::getPassRegistry());
00622     }
00623 
00624     bool runOnFunction(Function &F) override;
00625 
00626     /// This removes the specified instruction from
00627     /// our various maps and marks it for deletion.
00628     void markInstructionForDeletion(Instruction *I) {
00629       VN.erase(I);
00630       InstrsToErase.push_back(I);
00631     }
00632 
00633     DominatorTree &getDominatorTree() const { return *DT; }
00634     AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
00635     MemoryDependenceAnalysis &getMemDep() const { return *MD; }
00636   private:
00637     /// Push a new Value to the LeaderTable onto the list for its value number.
00638     void addToLeaderTable(uint32_t N, Value *V, const BasicBlock *BB) {
00639       LeaderTableEntry &Curr = LeaderTable[N];
00640       if (!Curr.Val) {
00641         Curr.Val = V;
00642         Curr.BB = BB;
00643         return;
00644       }
00645 
00646       LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
00647       Node->Val = V;
00648       Node->BB = BB;
00649       Node->Next = Curr.Next;
00650       Curr.Next = Node;
00651     }
00652 
00653     /// Scan the list of values corresponding to a given
00654     /// value number, and remove the given instruction if encountered.
00655     void removeFromLeaderTable(uint32_t N, Instruction *I, BasicBlock *BB) {
00656       LeaderTableEntry* Prev = nullptr;
00657       LeaderTableEntry* Curr = &LeaderTable[N];
00658 
00659       while (Curr->Val != I || Curr->BB != BB) {
00660         Prev = Curr;
00661         Curr = Curr->Next;
00662       }
00663 
00664       if (Prev) {
00665         Prev->Next = Curr->Next;
00666       } else {
00667         if (!Curr->Next) {
00668           Curr->Val = nullptr;
00669           Curr->BB = nullptr;
00670         } else {
00671           LeaderTableEntry* Next = Curr->Next;
00672           Curr->Val = Next->Val;
00673           Curr->BB = Next->BB;
00674           Curr->Next = Next->Next;
00675         }
00676       }
00677     }
00678 
00679     // List of critical edges to be split between iterations.
00680     SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
00681 
00682     // This transformation requires dominator postdominator info
00683     void getAnalysisUsage(AnalysisUsage &AU) const override {
00684       AU.addRequired<AssumptionCacheTracker>();
00685       AU.addRequired<DominatorTreeWrapperPass>();
00686       AU.addRequired<TargetLibraryInfoWrapperPass>();
00687       if (!NoLoads)
00688         AU.addRequired<MemoryDependenceAnalysis>();
00689       AU.addRequired<AliasAnalysis>();
00690 
00691       AU.addPreserved<DominatorTreeWrapperPass>();
00692       AU.addPreserved<AliasAnalysis>();
00693     }
00694 
00695 
00696     // Helper fuctions of redundant load elimination 
00697     bool processLoad(LoadInst *L);
00698     bool processNonLocalLoad(LoadInst *L);
00699     void AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps, 
00700                                  AvailValInBlkVect &ValuesPerBlock,
00701                                  UnavailBlkVect &UnavailableBlocks);
00702     bool PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock, 
00703                         UnavailBlkVect &UnavailableBlocks);
00704 
00705     // Other helper routines
00706     bool processInstruction(Instruction *I);
00707     bool processBlock(BasicBlock *BB);
00708     void dump(DenseMap<uint32_t, Value*> &d);
00709     bool iterateOnFunction(Function &F);
00710     bool performPRE(Function &F);
00711     bool performScalarPRE(Instruction *I);
00712     bool performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
00713                                    unsigned int ValNo);
00714     Value *findLeader(const BasicBlock *BB, uint32_t num);
00715     void cleanupGlobalSets();
00716     void verifyRemoved(const Instruction *I) const;
00717     bool splitCriticalEdges();
00718     BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
00719     unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
00720                                          const BasicBlockEdge &Root);
00721     bool propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root);
00722     bool processFoldableCondBr(BranchInst *BI);
00723     void addDeadBlock(BasicBlock *BB);
00724     void assignValNumForDeadCode();
00725   };
00726 
00727   char GVN::ID = 0;
00728 }
00729 
00730 // The public interface to this file...
00731 FunctionPass *llvm::createGVNPass(bool NoLoads) {
00732   return new GVN(NoLoads);
00733 }
00734 
00735 INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
00736 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00737 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
00738 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00739 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00740 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
00741 INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
00742 
00743 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
00744 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
00745   errs() << "{\n";
00746   for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
00747        E = d.end(); I != E; ++I) {
00748       errs() << I->first << "\n";
00749       I->second->dump();
00750   }
00751   errs() << "}\n";
00752 }
00753 #endif
00754 
00755 /// Return true if we can prove that the value
00756 /// we're analyzing is fully available in the specified block.  As we go, keep
00757 /// track of which blocks we know are fully alive in FullyAvailableBlocks.  This
00758 /// map is actually a tri-state map with the following values:
00759 ///   0) we know the block *is not* fully available.
00760 ///   1) we know the block *is* fully available.
00761 ///   2) we do not know whether the block is fully available or not, but we are
00762 ///      currently speculating that it will be.
00763 ///   3) we are speculating for this block and have used that to speculate for
00764 ///      other blocks.
00765 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
00766                             DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
00767                             uint32_t RecurseDepth) {
00768   if (RecurseDepth > MaxRecurseDepth)
00769     return false;
00770 
00771   // Optimistically assume that the block is fully available and check to see
00772   // if we already know about this block in one lookup.
00773   std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
00774     FullyAvailableBlocks.insert(std::make_pair(BB, 2));
00775 
00776   // If the entry already existed for this block, return the precomputed value.
00777   if (!IV.second) {
00778     // If this is a speculative "available" value, mark it as being used for
00779     // speculation of other blocks.
00780     if (IV.first->second == 2)
00781       IV.first->second = 3;
00782     return IV.first->second != 0;
00783   }
00784 
00785   // Otherwise, see if it is fully available in all predecessors.
00786   pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
00787 
00788   // If this block has no predecessors, it isn't live-in here.
00789   if (PI == PE)
00790     goto SpeculationFailure;
00791 
00792   for (; PI != PE; ++PI)
00793     // If the value isn't fully available in one of our predecessors, then it
00794     // isn't fully available in this block either.  Undo our previous
00795     // optimistic assumption and bail out.
00796     if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
00797       goto SpeculationFailure;
00798 
00799   return true;
00800 
00801 // If we get here, we found out that this is not, after
00802 // all, a fully-available block.  We have a problem if we speculated on this and
00803 // used the speculation to mark other blocks as available.
00804 SpeculationFailure:
00805   char &BBVal = FullyAvailableBlocks[BB];
00806 
00807   // If we didn't speculate on this, just return with it set to false.
00808   if (BBVal == 2) {
00809     BBVal = 0;
00810     return false;
00811   }
00812 
00813   // If we did speculate on this value, we could have blocks set to 1 that are
00814   // incorrect.  Walk the (transitive) successors of this block and mark them as
00815   // 0 if set to one.
00816   SmallVector<BasicBlock*, 32> BBWorklist;
00817   BBWorklist.push_back(BB);
00818 
00819   do {
00820     BasicBlock *Entry = BBWorklist.pop_back_val();
00821     // Note that this sets blocks to 0 (unavailable) if they happen to not
00822     // already be in FullyAvailableBlocks.  This is safe.
00823     char &EntryVal = FullyAvailableBlocks[Entry];
00824     if (EntryVal == 0) continue;  // Already unavailable.
00825 
00826     // Mark as unavailable.
00827     EntryVal = 0;
00828 
00829     BBWorklist.append(succ_begin(Entry), succ_end(Entry));
00830   } while (!BBWorklist.empty());
00831 
00832   return false;
00833 }
00834 
00835 
00836 /// Return true if CoerceAvailableValueToLoadType will succeed.
00837 static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
00838                                             Type *LoadTy,
00839                                             const DataLayout &DL) {
00840   // If the loaded or stored value is an first class array or struct, don't try
00841   // to transform them.  We need to be able to bitcast to integer.
00842   if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
00843       StoredVal->getType()->isStructTy() ||
00844       StoredVal->getType()->isArrayTy())
00845     return false;
00846 
00847   // The store has to be at least as big as the load.
00848   if (DL.getTypeSizeInBits(StoredVal->getType()) <
00849         DL.getTypeSizeInBits(LoadTy))
00850     return false;
00851 
00852   return true;
00853 }
00854 
00855 /// If we saw a store of a value to memory, and
00856 /// then a load from a must-aliased pointer of a different type, try to coerce
00857 /// the stored value.  LoadedTy is the type of the load we want to replace and
00858 /// InsertPt is the place to insert new instructions.
00859 ///
00860 /// If we can't do it, return null.
00861 static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
00862                                              Type *LoadedTy,
00863                                              Instruction *InsertPt,
00864                                              const DataLayout &DL) {
00865   if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL))
00866     return nullptr;
00867 
00868   // If this is already the right type, just return it.
00869   Type *StoredValTy = StoredVal->getType();
00870 
00871   uint64_t StoreSize = DL.getTypeSizeInBits(StoredValTy);
00872   uint64_t LoadSize = DL.getTypeSizeInBits(LoadedTy);
00873 
00874   // If the store and reload are the same size, we can always reuse it.
00875   if (StoreSize == LoadSize) {
00876     // Pointer to Pointer -> use bitcast.
00877     if (StoredValTy->getScalarType()->isPointerTy() &&
00878         LoadedTy->getScalarType()->isPointerTy())
00879       return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
00880 
00881     // Convert source pointers to integers, which can be bitcast.
00882     if (StoredValTy->getScalarType()->isPointerTy()) {
00883       StoredValTy = DL.getIntPtrType(StoredValTy);
00884       StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
00885     }
00886 
00887     Type *TypeToCastTo = LoadedTy;
00888     if (TypeToCastTo->getScalarType()->isPointerTy())
00889       TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
00890 
00891     if (StoredValTy != TypeToCastTo)
00892       StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
00893 
00894     // Cast to pointer if the load needs a pointer type.
00895     if (LoadedTy->getScalarType()->isPointerTy())
00896       StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
00897 
00898     return StoredVal;
00899   }
00900 
00901   // If the loaded value is smaller than the available value, then we can
00902   // extract out a piece from it.  If the available value is too small, then we
00903   // can't do anything.
00904   assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
00905 
00906   // Convert source pointers to integers, which can be manipulated.
00907   if (StoredValTy->getScalarType()->isPointerTy()) {
00908     StoredValTy = DL.getIntPtrType(StoredValTy);
00909     StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
00910   }
00911 
00912   // Convert vectors and fp to integer, which can be manipulated.
00913   if (!StoredValTy->isIntegerTy()) {
00914     StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
00915     StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
00916   }
00917 
00918   // If this is a big-endian system, we need to shift the value down to the low
00919   // bits so that a truncate will work.
00920   if (DL.isBigEndian()) {
00921     Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
00922     StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
00923   }
00924 
00925   // Truncate the integer to the right size now.
00926   Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
00927   StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
00928 
00929   if (LoadedTy == NewIntTy)
00930     return StoredVal;
00931 
00932   // If the result is a pointer, inttoptr.
00933   if (LoadedTy->getScalarType()->isPointerTy())
00934     return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
00935 
00936   // Otherwise, bitcast.
00937   return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
00938 }
00939 
00940 /// This function is called when we have a
00941 /// memdep query of a load that ends up being a clobbering memory write (store,
00942 /// memset, memcpy, memmove).  This means that the write *may* provide bits used
00943 /// by the load but we can't be sure because the pointers don't mustalias.
00944 ///
00945 /// Check this case to see if there is anything more we can do before we give
00946 /// up.  This returns -1 if we have to give up, or a byte number in the stored
00947 /// value of the piece that feeds the load.
00948 static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
00949                                           Value *WritePtr,
00950                                           uint64_t WriteSizeInBits,
00951                                           const DataLayout &DL) {
00952   // If the loaded or stored value is a first class array or struct, don't try
00953   // to transform them.  We need to be able to bitcast to integer.
00954   if (LoadTy->isStructTy() || LoadTy->isArrayTy())
00955     return -1;
00956 
00957   int64_t StoreOffset = 0, LoadOffset = 0;
00958   Value *StoreBase =
00959       GetPointerBaseWithConstantOffset(WritePtr, StoreOffset, DL);
00960   Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, DL);
00961   if (StoreBase != LoadBase)
00962     return -1;
00963 
00964   // If the load and store are to the exact same address, they should have been
00965   // a must alias.  AA must have gotten confused.
00966   // FIXME: Study to see if/when this happens.  One case is forwarding a memset
00967   // to a load from the base of the memset.
00968 #if 0
00969   if (LoadOffset == StoreOffset) {
00970     dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
00971     << "Base       = " << *StoreBase << "\n"
00972     << "Store Ptr  = " << *WritePtr << "\n"
00973     << "Store Offs = " << StoreOffset << "\n"
00974     << "Load Ptr   = " << *LoadPtr << "\n";
00975     abort();
00976   }
00977 #endif
00978 
00979   // If the load and store don't overlap at all, the store doesn't provide
00980   // anything to the load.  In this case, they really don't alias at all, AA
00981   // must have gotten confused.
00982   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy);
00983 
00984   if ((WriteSizeInBits & 7) | (LoadSize & 7))
00985     return -1;
00986   uint64_t StoreSize = WriteSizeInBits >> 3;  // Convert to bytes.
00987   LoadSize >>= 3;
00988 
00989 
00990   bool isAAFailure = false;
00991   if (StoreOffset < LoadOffset)
00992     isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
00993   else
00994     isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
00995 
00996   if (isAAFailure) {
00997 #if 0
00998     dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
00999     << "Base       = " << *StoreBase << "\n"
01000     << "Store Ptr  = " << *WritePtr << "\n"
01001     << "Store Offs = " << StoreOffset << "\n"
01002     << "Load Ptr   = " << *LoadPtr << "\n";
01003     abort();
01004 #endif
01005     return -1;
01006   }
01007 
01008   // If the Load isn't completely contained within the stored bits, we don't
01009   // have all the bits to feed it.  We could do something crazy in the future
01010   // (issue a smaller load then merge the bits in) but this seems unlikely to be
01011   // valuable.
01012   if (StoreOffset > LoadOffset ||
01013       StoreOffset+StoreSize < LoadOffset+LoadSize)
01014     return -1;
01015 
01016   // Okay, we can do this transformation.  Return the number of bytes into the
01017   // store that the load is.
01018   return LoadOffset-StoreOffset;
01019 }
01020 
01021 /// This function is called when we have a
01022 /// memdep query of a load that ends up being a clobbering store.
01023 static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
01024                                           StoreInst *DepSI) {
01025   // Cannot handle reading from store of first-class aggregate yet.
01026   if (DepSI->getValueOperand()->getType()->isStructTy() ||
01027       DepSI->getValueOperand()->getType()->isArrayTy())
01028     return -1;
01029 
01030   const DataLayout &DL = DepSI->getModule()->getDataLayout();
01031   Value *StorePtr = DepSI->getPointerOperand();
01032   uint64_t StoreSize =DL.getTypeSizeInBits(DepSI->getValueOperand()->getType());
01033   return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
01034                                         StorePtr, StoreSize, DL);
01035 }
01036 
01037 /// This function is called when we have a
01038 /// memdep query of a load that ends up being clobbered by another load.  See if
01039 /// the other load can feed into the second load.
01040 static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
01041                                          LoadInst *DepLI, const DataLayout &DL){
01042   // Cannot handle reading from store of first-class aggregate yet.
01043   if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
01044     return -1;
01045 
01046   Value *DepPtr = DepLI->getPointerOperand();
01047   uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType());
01048   int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
01049   if (R != -1) return R;
01050 
01051   // If we have a load/load clobber an DepLI can be widened to cover this load,
01052   // then we should widen it!
01053   int64_t LoadOffs = 0;
01054   const Value *LoadBase =
01055       GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, DL);
01056   unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
01057 
01058   unsigned Size = MemoryDependenceAnalysis::getLoadLoadClobberFullWidthSize(
01059       LoadBase, LoadOffs, LoadSize, DepLI);
01060   if (Size == 0) return -1;
01061 
01062   return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, DL);
01063 }
01064 
01065 
01066 
01067 static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
01068                                             MemIntrinsic *MI,
01069                                             const DataLayout &DL) {
01070   // If the mem operation is a non-constant size, we can't handle it.
01071   ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
01072   if (!SizeCst) return -1;
01073   uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
01074 
01075   // If this is memset, we just need to see if the offset is valid in the size
01076   // of the memset..
01077   if (MI->getIntrinsicID() == Intrinsic::memset)
01078     return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
01079                                           MemSizeInBits, DL);
01080 
01081   // If we have a memcpy/memmove, the only case we can handle is if this is a
01082   // copy from constant memory.  In that case, we can read directly from the
01083   // constant memory.
01084   MemTransferInst *MTI = cast<MemTransferInst>(MI);
01085 
01086   Constant *Src = dyn_cast<Constant>(MTI->getSource());
01087   if (!Src) return -1;
01088 
01089   GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, DL));
01090   if (!GV || !GV->isConstant()) return -1;
01091 
01092   // See if the access is within the bounds of the transfer.
01093   int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
01094                                               MI->getDest(), MemSizeInBits, DL);
01095   if (Offset == -1)
01096     return Offset;
01097 
01098   unsigned AS = Src->getType()->getPointerAddressSpace();
01099   // Otherwise, see if we can constant fold a load from the constant with the
01100   // offset applied as appropriate.
01101   Src = ConstantExpr::getBitCast(Src,
01102                                  Type::getInt8PtrTy(Src->getContext(), AS));
01103   Constant *OffsetCst =
01104     ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
01105   Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
01106   Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
01107   if (ConstantFoldLoadFromConstPtr(Src, DL))
01108     return Offset;
01109   return -1;
01110 }
01111 
01112 
01113 /// This function is called when we have a
01114 /// memdep query of a load that ends up being a clobbering store.  This means
01115 /// that the store provides bits used by the load but we the pointers don't
01116 /// mustalias.  Check this case to see if there is anything more we can do
01117 /// before we give up.
01118 static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
01119                                    Type *LoadTy,
01120                                    Instruction *InsertPt, const DataLayout &DL){
01121   LLVMContext &Ctx = SrcVal->getType()->getContext();
01122 
01123   uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
01124   uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
01125 
01126   IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
01127 
01128   // Compute which bits of the stored value are being used by the load.  Convert
01129   // to an integer type to start with.
01130   if (SrcVal->getType()->getScalarType()->isPointerTy())
01131     SrcVal = Builder.CreatePtrToInt(SrcVal,
01132         DL.getIntPtrType(SrcVal->getType()));
01133   if (!SrcVal->getType()->isIntegerTy())
01134     SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
01135 
01136   // Shift the bits to the least significant depending on endianness.
01137   unsigned ShiftAmt;
01138   if (DL.isLittleEndian())
01139     ShiftAmt = Offset*8;
01140   else
01141     ShiftAmt = (StoreSize-LoadSize-Offset)*8;
01142 
01143   if (ShiftAmt)
01144     SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
01145 
01146   if (LoadSize != StoreSize)
01147     SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
01148 
01149   return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, DL);
01150 }
01151 
01152 /// This function is called when we have a
01153 /// memdep query of a load that ends up being a clobbering load.  This means
01154 /// that the load *may* provide bits used by the load but we can't be sure
01155 /// because the pointers don't mustalias.  Check this case to see if there is
01156 /// anything more we can do before we give up.
01157 static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
01158                                   Type *LoadTy, Instruction *InsertPt,
01159                                   GVN &gvn) {
01160   const DataLayout &DL = SrcVal->getModule()->getDataLayout();
01161   // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
01162   // widen SrcVal out to a larger load.
01163   unsigned SrcValSize = DL.getTypeStoreSize(SrcVal->getType());
01164   unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
01165   if (Offset+LoadSize > SrcValSize) {
01166     assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
01167     assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
01168     // If we have a load/load clobber an DepLI can be widened to cover this
01169     // load, then we should widen it to the next power of 2 size big enough!
01170     unsigned NewLoadSize = Offset+LoadSize;
01171     if (!isPowerOf2_32(NewLoadSize))
01172       NewLoadSize = NextPowerOf2(NewLoadSize);
01173 
01174     Value *PtrVal = SrcVal->getPointerOperand();
01175 
01176     // Insert the new load after the old load.  This ensures that subsequent
01177     // memdep queries will find the new load.  We can't easily remove the old
01178     // load completely because it is already in the value numbering table.
01179     IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
01180     Type *DestPTy =
01181       IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
01182     DestPTy = PointerType::get(DestPTy,
01183                                PtrVal->getType()->getPointerAddressSpace());
01184     Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
01185     PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
01186     LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
01187     NewLoad->takeName(SrcVal);
01188     NewLoad->setAlignment(SrcVal->getAlignment());
01189 
01190     DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
01191     DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
01192 
01193     // Replace uses of the original load with the wider load.  On a big endian
01194     // system, we need to shift down to get the relevant bits.
01195     Value *RV = NewLoad;
01196     if (DL.isBigEndian())
01197       RV = Builder.CreateLShr(RV,
01198                     NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
01199     RV = Builder.CreateTrunc(RV, SrcVal->getType());
01200     SrcVal->replaceAllUsesWith(RV);
01201 
01202     // We would like to use gvn.markInstructionForDeletion here, but we can't
01203     // because the load is already memoized into the leader map table that GVN
01204     // tracks.  It is potentially possible to remove the load from the table,
01205     // but then there all of the operations based on it would need to be
01206     // rehashed.  Just leave the dead load around.
01207     gvn.getMemDep().removeInstruction(SrcVal);
01208     SrcVal = NewLoad;
01209   }
01210 
01211   return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
01212 }
01213 
01214 
01215 /// This function is called when we have a
01216 /// memdep query of a load that ends up being a clobbering mem intrinsic.
01217 static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
01218                                      Type *LoadTy, Instruction *InsertPt,
01219                                      const DataLayout &DL){
01220   LLVMContext &Ctx = LoadTy->getContext();
01221   uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
01222 
01223   IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
01224 
01225   // We know that this method is only called when the mem transfer fully
01226   // provides the bits for the load.
01227   if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
01228     // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
01229     // independently of what the offset is.
01230     Value *Val = MSI->getValue();
01231     if (LoadSize != 1)
01232       Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
01233 
01234     Value *OneElt = Val;
01235 
01236     // Splat the value out to the right number of bits.
01237     for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
01238       // If we can double the number of bytes set, do it.
01239       if (NumBytesSet*2 <= LoadSize) {
01240         Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
01241         Val = Builder.CreateOr(Val, ShVal);
01242         NumBytesSet <<= 1;
01243         continue;
01244       }
01245 
01246       // Otherwise insert one byte at a time.
01247       Value *ShVal = Builder.CreateShl(Val, 1*8);
01248       Val = Builder.CreateOr(OneElt, ShVal);
01249       ++NumBytesSet;
01250     }
01251 
01252     return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, DL);
01253   }
01254 
01255   // Otherwise, this is a memcpy/memmove from a constant global.
01256   MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
01257   Constant *Src = cast<Constant>(MTI->getSource());
01258   unsigned AS = Src->getType()->getPointerAddressSpace();
01259 
01260   // Otherwise, see if we can constant fold a load from the constant with the
01261   // offset applied as appropriate.
01262   Src = ConstantExpr::getBitCast(Src,
01263                                  Type::getInt8PtrTy(Src->getContext(), AS));
01264   Constant *OffsetCst =
01265     ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
01266   Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
01267   Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
01268   return ConstantFoldLoadFromConstPtr(Src, DL);
01269 }
01270 
01271 
01272 /// Given a set of loads specified by ValuesPerBlock,
01273 /// construct SSA form, allowing us to eliminate LI.  This returns the value
01274 /// that should be used at LI's definition site.
01275 static Value *ConstructSSAForLoadSet(LoadInst *LI,
01276                          SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
01277                                      GVN &gvn) {
01278   // Check for the fully redundant, dominating load case.  In this case, we can
01279   // just use the dominating value directly.
01280   if (ValuesPerBlock.size() == 1 &&
01281       gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
01282                                                LI->getParent())) {
01283     assert(!ValuesPerBlock[0].isUndefValue() && "Dead BB dominate this block");
01284     return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn);
01285   }
01286 
01287   // Otherwise, we have to construct SSA form.
01288   SmallVector<PHINode*, 8> NewPHIs;
01289   SSAUpdater SSAUpdate(&NewPHIs);
01290   SSAUpdate.Initialize(LI->getType(), LI->getName());
01291 
01292   for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
01293     const AvailableValueInBlock &AV = ValuesPerBlock[i];
01294     BasicBlock *BB = AV.BB;
01295 
01296     if (SSAUpdate.HasValueForBlock(BB))
01297       continue;
01298 
01299     SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LI, gvn));
01300   }
01301 
01302   // Perform PHI construction.
01303   Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
01304 
01305   // If new PHI nodes were created, notify alias analysis.
01306   if (V->getType()->getScalarType()->isPointerTy()) {
01307     AliasAnalysis *AA = gvn.getAliasAnalysis();
01308 
01309     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
01310       AA->copyValue(LI, NewPHIs[i]);
01311 
01312     // Now that we've copied information to the new PHIs, scan through
01313     // them again and inform alias analysis that we've added potentially
01314     // escaping uses to any values that are operands to these PHIs.
01315     for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
01316       PHINode *P = NewPHIs[i];
01317       for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
01318         unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
01319         AA->addEscapingUse(P->getOperandUse(jj));
01320       }
01321     }
01322   }
01323 
01324   return V;
01325 }
01326 
01327 Value *AvailableValueInBlock::MaterializeAdjustedValue(LoadInst *LI,
01328                                                        GVN &gvn) const {
01329   Value *Res;
01330   Type *LoadTy = LI->getType();
01331   const DataLayout &DL = LI->getModule()->getDataLayout();
01332   if (isSimpleValue()) {
01333     Res = getSimpleValue();
01334     if (Res->getType() != LoadTy) {
01335       Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(), DL);
01336 
01337       DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << "  "
01338                    << *getSimpleValue() << '\n'
01339                    << *Res << '\n' << "\n\n\n");
01340     }
01341   } else if (isCoercedLoadValue()) {
01342     LoadInst *Load = getCoercedLoadValue();
01343     if (Load->getType() == LoadTy && Offset == 0) {
01344       Res = Load;
01345     } else {
01346       Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
01347                                 gvn);
01348   
01349       DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << "  "
01350                    << *getCoercedLoadValue() << '\n'
01351                    << *Res << '\n' << "\n\n\n");
01352     }
01353   } else if (isMemIntrinValue()) {
01354     Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset, LoadTy,
01355                                  BB->getTerminator(), DL);
01356     DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
01357                  << "  " << *getMemIntrinValue() << '\n'
01358                  << *Res << '\n' << "\n\n\n");
01359   } else {
01360     assert(isUndefValue() && "Should be UndefVal");
01361     DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
01362     return UndefValue::get(LoadTy);
01363   }
01364   return Res;
01365 }
01366 
01367 static bool isLifetimeStart(const Instruction *Inst) {
01368   if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
01369     return II->getIntrinsicID() == Intrinsic::lifetime_start;
01370   return false;
01371 }
01372 
01373 void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps, 
01374                                   AvailValInBlkVect &ValuesPerBlock,
01375                                   UnavailBlkVect &UnavailableBlocks) {
01376 
01377   // Filter out useless results (non-locals, etc).  Keep track of the blocks
01378   // where we have a value available in repl, also keep track of whether we see
01379   // dependencies that produce an unknown value for the load (such as a call
01380   // that could potentially clobber the load).
01381   unsigned NumDeps = Deps.size();
01382   const DataLayout &DL = LI->getModule()->getDataLayout();
01383   for (unsigned i = 0, e = NumDeps; i != e; ++i) {
01384     BasicBlock *DepBB = Deps[i].getBB();
01385     MemDepResult DepInfo = Deps[i].getResult();
01386 
01387     if (DeadBlocks.count(DepBB)) {
01388       // Dead dependent mem-op disguise as a load evaluating the same value
01389       // as the load in question.
01390       ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
01391       continue;
01392     }
01393 
01394     if (!DepInfo.isDef() && !DepInfo.isClobber()) {
01395       UnavailableBlocks.push_back(DepBB);
01396       continue;
01397     }
01398 
01399     if (DepInfo.isClobber()) {
01400       // The address being loaded in this non-local block may not be the same as
01401       // the pointer operand of the load if PHI translation occurs.  Make sure
01402       // to consider the right address.
01403       Value *Address = Deps[i].getAddress();
01404 
01405       // If the dependence is to a store that writes to a superset of the bits
01406       // read by the load, we can extract the bits we need for the load from the
01407       // stored value.
01408       if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
01409         if (Address) {
01410           int Offset =
01411               AnalyzeLoadFromClobberingStore(LI->getType(), Address, DepSI);
01412           if (Offset != -1) {
01413             ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
01414                                                        DepSI->getValueOperand(),
01415                                                                 Offset));
01416             continue;
01417           }
01418         }
01419       }
01420 
01421       // Check to see if we have something like this:
01422       //    load i32* P
01423       //    load i8* (P+1)
01424       // if we have this, replace the later with an extraction from the former.
01425       if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
01426         // If this is a clobber and L is the first instruction in its block, then
01427         // we have the first instruction in the entry block.
01428         if (DepLI != LI && Address) {
01429           int Offset =
01430               AnalyzeLoadFromClobberingLoad(LI->getType(), Address, DepLI, DL);
01431 
01432           if (Offset != -1) {
01433             ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
01434                                                                     Offset));
01435             continue;
01436           }
01437         }
01438       }
01439 
01440       // If the clobbering value is a memset/memcpy/memmove, see if we can
01441       // forward a value on from it.
01442       if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
01443         if (Address) {
01444           int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
01445                                                         DepMI, DL);
01446           if (Offset != -1) {
01447             ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
01448                                                                   Offset));
01449             continue;
01450           }
01451         }
01452       }
01453 
01454       UnavailableBlocks.push_back(DepBB);
01455       continue;
01456     }
01457 
01458     // DepInfo.isDef() here
01459 
01460     Instruction *DepInst = DepInfo.getInst();
01461 
01462     // Loading the allocation -> undef.
01463     if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
01464         // Loading immediately after lifetime begin -> undef.
01465         isLifetimeStart(DepInst)) {
01466       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
01467                                              UndefValue::get(LI->getType())));
01468       continue;
01469     }
01470 
01471     // Loading from calloc (which zero initializes memory) -> zero
01472     if (isCallocLikeFn(DepInst, TLI)) {
01473       ValuesPerBlock.push_back(AvailableValueInBlock::get(
01474           DepBB, Constant::getNullValue(LI->getType())));
01475       continue;
01476     }
01477 
01478     if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
01479       // Reject loads and stores that are to the same address but are of
01480       // different types if we have to.
01481       if (S->getValueOperand()->getType() != LI->getType()) {
01482         // If the stored value is larger or equal to the loaded value, we can
01483         // reuse it.
01484         if (!CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
01485                                              LI->getType(), DL)) {
01486           UnavailableBlocks.push_back(DepBB);
01487           continue;
01488         }
01489       }
01490 
01491       ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
01492                                                          S->getValueOperand()));
01493       continue;
01494     }
01495 
01496     if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
01497       // If the types mismatch and we can't handle it, reject reuse of the load.
01498       if (LD->getType() != LI->getType()) {
01499         // If the stored value is larger or equal to the loaded value, we can
01500         // reuse it.
01501         if (!CanCoerceMustAliasedValueToLoad(LD, LI->getType(), DL)) {
01502           UnavailableBlocks.push_back(DepBB);
01503           continue;
01504         }
01505       }
01506       ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
01507       continue;
01508     }
01509 
01510     UnavailableBlocks.push_back(DepBB);
01511   }
01512 }
01513 
01514 bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock, 
01515                          UnavailBlkVect &UnavailableBlocks) {
01516   // Okay, we have *some* definitions of the value.  This means that the value
01517   // is available in some of our (transitive) predecessors.  Lets think about
01518   // doing PRE of this load.  This will involve inserting a new load into the
01519   // predecessor when it's not available.  We could do this in general, but
01520   // prefer to not increase code size.  As such, we only do this when we know
01521   // that we only have to insert *one* load (which means we're basically moving
01522   // the load, not inserting a new one).
01523 
01524   SmallPtrSet<BasicBlock *, 4> Blockers;
01525   for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
01526     Blockers.insert(UnavailableBlocks[i]);
01527 
01528   // Let's find the first basic block with more than one predecessor.  Walk
01529   // backwards through predecessors if needed.
01530   BasicBlock *LoadBB = LI->getParent();
01531   BasicBlock *TmpBB = LoadBB;
01532 
01533   while (TmpBB->getSinglePredecessor()) {
01534     TmpBB = TmpBB->getSinglePredecessor();
01535     if (TmpBB == LoadBB) // Infinite (unreachable) loop.
01536       return false;
01537     if (Blockers.count(TmpBB))
01538       return false;
01539 
01540     // If any of these blocks has more than one successor (i.e. if the edge we
01541     // just traversed was critical), then there are other paths through this
01542     // block along which the load may not be anticipated.  Hoisting the load
01543     // above this block would be adding the load to execution paths along
01544     // which it was not previously executed.
01545     if (TmpBB->getTerminator()->getNumSuccessors() != 1)
01546       return false;
01547   }
01548 
01549   assert(TmpBB);
01550   LoadBB = TmpBB;
01551 
01552   // Check to see how many predecessors have the loaded value fully
01553   // available.
01554   MapVector<BasicBlock *, Value *> PredLoads;
01555   DenseMap<BasicBlock*, char> FullyAvailableBlocks;
01556   for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
01557     FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
01558   for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
01559     FullyAvailableBlocks[UnavailableBlocks[i]] = false;
01560 
01561   SmallVector<BasicBlock *, 4> CriticalEdgePred;
01562   for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
01563        PI != E; ++PI) {
01564     BasicBlock *Pred = *PI;
01565     if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
01566       continue;
01567     }
01568 
01569     if (Pred->getTerminator()->getNumSuccessors() != 1) {
01570       if (isa<IndirectBrInst>(Pred->getTerminator())) {
01571         DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
01572               << Pred->getName() << "': " << *LI << '\n');
01573         return false;
01574       }
01575 
01576       if (LoadBB->isLandingPad()) {
01577         DEBUG(dbgs()
01578               << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
01579               << Pred->getName() << "': " << *LI << '\n');
01580         return false;
01581       }
01582 
01583       CriticalEdgePred.push_back(Pred);
01584     } else {
01585       // Only add the predecessors that will not be split for now.
01586       PredLoads[Pred] = nullptr;
01587     }
01588   }
01589 
01590   // Decide whether PRE is profitable for this load.
01591   unsigned NumUnavailablePreds = PredLoads.size() + CriticalEdgePred.size();
01592   assert(NumUnavailablePreds != 0 &&
01593          "Fully available value should already be eliminated!");
01594 
01595   // If this load is unavailable in multiple predecessors, reject it.
01596   // FIXME: If we could restructure the CFG, we could make a common pred with
01597   // all the preds that don't have an available LI and insert a new load into
01598   // that one block.
01599   if (NumUnavailablePreds != 1)
01600       return false;
01601 
01602   // Split critical edges, and update the unavailable predecessors accordingly.
01603   for (BasicBlock *OrigPred : CriticalEdgePred) {
01604     BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
01605     assert(!PredLoads.count(OrigPred) && "Split edges shouldn't be in map!");
01606     PredLoads[NewPred] = nullptr;
01607     DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
01608                  << LoadBB->getName() << '\n');
01609   }
01610 
01611   // Check if the load can safely be moved to all the unavailable predecessors.
01612   bool CanDoPRE = true;
01613   const DataLayout &DL = LI->getModule()->getDataLayout();
01614   SmallVector<Instruction*, 8> NewInsts;
01615   for (auto &PredLoad : PredLoads) {
01616     BasicBlock *UnavailablePred = PredLoad.first;
01617 
01618     // Do PHI translation to get its value in the predecessor if necessary.  The
01619     // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
01620 
01621     // If all preds have a single successor, then we know it is safe to insert
01622     // the load on the pred (?!?), so we can insert code to materialize the
01623     // pointer if it is not available.
01624     PHITransAddr Address(LI->getPointerOperand(), DL, AC);
01625     Value *LoadPtr = nullptr;
01626     LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
01627                                                 *DT, NewInsts);
01628 
01629     // If we couldn't find or insert a computation of this phi translated value,
01630     // we fail PRE.
01631     if (!LoadPtr) {
01632       DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
01633             << *LI->getPointerOperand() << "\n");
01634       CanDoPRE = false;
01635       break;
01636     }
01637 
01638     PredLoad.second = LoadPtr;
01639   }
01640 
01641   if (!CanDoPRE) {
01642     while (!NewInsts.empty()) {
01643       Instruction *I = NewInsts.pop_back_val();
01644       if (MD) MD->removeInstruction(I);
01645       I->eraseFromParent();
01646     }
01647     // HINT: Don't revert the edge-splitting as following transformation may
01648     // also need to split these critical edges.
01649     return !CriticalEdgePred.empty();
01650   }
01651 
01652   // Okay, we can eliminate this load by inserting a reload in the predecessor
01653   // and using PHI construction to get the value in the other predecessors, do
01654   // it.
01655   DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
01656   DEBUG(if (!NewInsts.empty())
01657           dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
01658                  << *NewInsts.back() << '\n');
01659 
01660   // Assign value numbers to the new instructions.
01661   for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
01662     // FIXME: We really _ought_ to insert these value numbers into their
01663     // parent's availability map.  However, in doing so, we risk getting into
01664     // ordering issues.  If a block hasn't been processed yet, we would be
01665     // marking a value as AVAIL-IN, which isn't what we intend.
01666     VN.lookup_or_add(NewInsts[i]);
01667   }
01668 
01669   for (const auto &PredLoad : PredLoads) {
01670     BasicBlock *UnavailablePred = PredLoad.first;
01671     Value *LoadPtr = PredLoad.second;
01672 
01673     Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
01674                                         LI->getAlignment(),
01675                                         UnavailablePred->getTerminator());
01676 
01677     // Transfer the old load's AA tags to the new load.
01678     AAMDNodes Tags;
01679     LI->getAAMetadata(Tags);
01680     if (Tags)
01681       NewLoad->setAAMetadata(Tags);
01682 
01683     // Transfer DebugLoc.
01684     NewLoad->setDebugLoc(LI->getDebugLoc());
01685 
01686     // Add the newly created load.
01687     ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
01688                                                         NewLoad));
01689     MD->invalidateCachedPointerInfo(LoadPtr);
01690     DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
01691   }
01692 
01693   // Perform PHI construction.
01694   Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
01695   LI->replaceAllUsesWith(V);
01696   if (isa<PHINode>(V))
01697     V->takeName(LI);
01698   if (V->getType()->getScalarType()->isPointerTy())
01699     MD->invalidateCachedPointerInfo(V);
01700   markInstructionForDeletion(LI);
01701   ++NumPRELoad;
01702   return true;
01703 }
01704 
01705 /// Attempt to eliminate a load whose dependencies are
01706 /// non-local by performing PHI construction.
01707 bool GVN::processNonLocalLoad(LoadInst *LI) {
01708   // Step 1: Find the non-local dependencies of the load.
01709   LoadDepVect Deps;
01710   MD->getNonLocalPointerDependency(LI, Deps);
01711 
01712   // If we had to process more than one hundred blocks to find the
01713   // dependencies, this load isn't worth worrying about.  Optimizing
01714   // it will be too expensive.
01715   unsigned NumDeps = Deps.size();
01716   if (NumDeps > 100)
01717     return false;
01718 
01719   // If we had a phi translation failure, we'll have a single entry which is a
01720   // clobber in the current block.  Reject this early.
01721   if (NumDeps == 1 &&
01722       !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
01723     DEBUG(
01724       dbgs() << "GVN: non-local load ";
01725       LI->printAsOperand(dbgs());
01726       dbgs() << " has unknown dependencies\n";
01727     );
01728     return false;
01729   }
01730 
01731   // If this load follows a GEP, see if we can PRE the indices before analyzing.
01732   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0))) {
01733     for (GetElementPtrInst::op_iterator OI = GEP->idx_begin(),
01734                                         OE = GEP->idx_end();
01735          OI != OE; ++OI)
01736       if (Instruction *I = dyn_cast<Instruction>(OI->get()))
01737         performScalarPRE(I);
01738   }
01739 
01740   // Step 2: Analyze the availability of the load
01741   AvailValInBlkVect ValuesPerBlock;
01742   UnavailBlkVect UnavailableBlocks;
01743   AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
01744 
01745   // If we have no predecessors that produce a known value for this load, exit
01746   // early.
01747   if (ValuesPerBlock.empty())
01748     return false;
01749 
01750   // Step 3: Eliminate fully redundancy.
01751   //
01752   // If all of the instructions we depend on produce a known value for this
01753   // load, then it is fully redundant and we can use PHI insertion to compute
01754   // its value.  Insert PHIs and remove the fully redundant value now.
01755   if (UnavailableBlocks.empty()) {
01756     DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
01757 
01758     // Perform PHI construction.
01759     Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
01760     LI->replaceAllUsesWith(V);
01761 
01762     if (isa<PHINode>(V))
01763       V->takeName(LI);
01764     if (V->getType()->getScalarType()->isPointerTy())
01765       MD->invalidateCachedPointerInfo(V);
01766     markInstructionForDeletion(LI);
01767     ++NumGVNLoad;
01768     return true;
01769   }
01770 
01771   // Step 4: Eliminate partial redundancy.
01772   if (!EnablePRE || !EnableLoadPRE)
01773     return false;
01774 
01775   return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
01776 }
01777 
01778 
01779 static void patchReplacementInstruction(Instruction *I, Value *Repl) {
01780   // Patch the replacement so that it is not more restrictive than the value
01781   // being replaced.
01782   BinaryOperator *Op = dyn_cast<BinaryOperator>(I);
01783   BinaryOperator *ReplOp = dyn_cast<BinaryOperator>(Repl);
01784   if (Op && ReplOp && isa<OverflowingBinaryOperator>(Op) &&
01785       isa<OverflowingBinaryOperator>(ReplOp)) {
01786     if (ReplOp->hasNoSignedWrap() && !Op->hasNoSignedWrap())
01787       ReplOp->setHasNoSignedWrap(false);
01788     if (ReplOp->hasNoUnsignedWrap() && !Op->hasNoUnsignedWrap())
01789       ReplOp->setHasNoUnsignedWrap(false);
01790   }
01791   if (Instruction *ReplInst = dyn_cast<Instruction>(Repl)) {
01792     // FIXME: If both the original and replacement value are part of the
01793     // same control-flow region (meaning that the execution of one
01794     // guarentees the executation of the other), then we can combine the
01795     // noalias scopes here and do better than the general conservative
01796     // answer used in combineMetadata().
01797 
01798     // In general, GVN unifies expressions over different control-flow
01799     // regions, and so we need a conservative combination of the noalias
01800     // scopes.
01801     unsigned KnownIDs[] = {
01802       LLVMContext::MD_tbaa,
01803       LLVMContext::MD_alias_scope,
01804       LLVMContext::MD_noalias,
01805       LLVMContext::MD_range,
01806       LLVMContext::MD_fpmath,
01807       LLVMContext::MD_invariant_load,
01808     };
01809     combineMetadata(ReplInst, I, KnownIDs);
01810   }
01811 }
01812 
01813 static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
01814   patchReplacementInstruction(I, Repl);
01815   I->replaceAllUsesWith(Repl);
01816 }
01817 
01818 /// Attempt to eliminate a load, first by eliminating it
01819 /// locally, and then attempting non-local elimination if that fails.
01820 bool GVN::processLoad(LoadInst *L) {
01821   if (!MD)
01822     return false;
01823 
01824   if (!L->isSimple())
01825     return false;
01826 
01827   if (L->use_empty()) {
01828     markInstructionForDeletion(L);
01829     return true;
01830   }
01831 
01832   // ... to a pointer that has been loaded from before...
01833   MemDepResult Dep = MD->getDependency(L);
01834   const DataLayout &DL = L->getModule()->getDataLayout();
01835 
01836   // If we have a clobber and target data is around, see if this is a clobber
01837   // that we can fix up through code synthesis.
01838   if (Dep.isClobber()) {
01839     // Check to see if we have something like this:
01840     //   store i32 123, i32* %P
01841     //   %A = bitcast i32* %P to i8*
01842     //   %B = gep i8* %A, i32 1
01843     //   %C = load i8* %B
01844     //
01845     // We could do that by recognizing if the clobber instructions are obviously
01846     // a common base + constant offset, and if the previous store (or memset)
01847     // completely covers this load.  This sort of thing can happen in bitfield
01848     // access code.
01849     Value *AvailVal = nullptr;
01850     if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
01851       int Offset = AnalyzeLoadFromClobberingStore(
01852           L->getType(), L->getPointerOperand(), DepSI);
01853       if (Offset != -1)
01854         AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
01855                                         L->getType(), L, DL);
01856     }
01857 
01858     // Check to see if we have something like this:
01859     //    load i32* P
01860     //    load i8* (P+1)
01861     // if we have this, replace the later with an extraction from the former.
01862     if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
01863       // If this is a clobber and L is the first instruction in its block, then
01864       // we have the first instruction in the entry block.
01865       if (DepLI == L)
01866         return false;
01867 
01868       int Offset = AnalyzeLoadFromClobberingLoad(
01869           L->getType(), L->getPointerOperand(), DepLI, DL);
01870       if (Offset != -1)
01871         AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
01872     }
01873 
01874     // If the clobbering value is a memset/memcpy/memmove, see if we can forward
01875     // a value on from it.
01876     if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
01877       int Offset = AnalyzeLoadFromClobberingMemInst(
01878           L->getType(), L->getPointerOperand(), DepMI, DL);
01879       if (Offset != -1)
01880         AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, DL);
01881     }
01882 
01883     if (AvailVal) {
01884       DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
01885             << *AvailVal << '\n' << *L << "\n\n\n");
01886 
01887       // Replace the load!
01888       L->replaceAllUsesWith(AvailVal);
01889       if (AvailVal->getType()->getScalarType()->isPointerTy())
01890         MD->invalidateCachedPointerInfo(AvailVal);
01891       markInstructionForDeletion(L);
01892       ++NumGVNLoad;
01893       return true;
01894     }
01895   }
01896 
01897   // If the value isn't available, don't do anything!
01898   if (Dep.isClobber()) {
01899     DEBUG(
01900       // fast print dep, using operator<< on instruction is too slow.
01901       dbgs() << "GVN: load ";
01902       L->printAsOperand(dbgs());
01903       Instruction *I = Dep.getInst();
01904       dbgs() << " is clobbered by " << *I << '\n';
01905     );
01906     return false;
01907   }
01908 
01909   // If it is defined in another block, try harder.
01910   if (Dep.isNonLocal())
01911     return processNonLocalLoad(L);
01912 
01913   if (!Dep.isDef()) {
01914     DEBUG(
01915       // fast print dep, using operator<< on instruction is too slow.
01916       dbgs() << "GVN: load ";
01917       L->printAsOperand(dbgs());
01918       dbgs() << " has unknown dependence\n";
01919     );
01920     return false;
01921   }
01922 
01923   Instruction *DepInst = Dep.getInst();
01924   if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
01925     Value *StoredVal = DepSI->getValueOperand();
01926 
01927     // The store and load are to a must-aliased pointer, but they may not
01928     // actually have the same type.  See if we know how to reuse the stored
01929     // value (depending on its type).
01930     if (StoredVal->getType() != L->getType()) {
01931       StoredVal =
01932           CoerceAvailableValueToLoadType(StoredVal, L->getType(), L, DL);
01933       if (!StoredVal)
01934         return false;
01935 
01936       DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
01937                    << '\n' << *L << "\n\n\n");
01938     }
01939 
01940     // Remove it!
01941     L->replaceAllUsesWith(StoredVal);
01942     if (StoredVal->getType()->getScalarType()->isPointerTy())
01943       MD->invalidateCachedPointerInfo(StoredVal);
01944     markInstructionForDeletion(L);
01945     ++NumGVNLoad;
01946     return true;
01947   }
01948 
01949   if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
01950     Value *AvailableVal = DepLI;
01951 
01952     // The loads are of a must-aliased pointer, but they may not actually have
01953     // the same type.  See if we know how to reuse the previously loaded value
01954     // (depending on its type).
01955     if (DepLI->getType() != L->getType()) {
01956       AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(), L, DL);
01957       if (!AvailableVal)
01958         return false;
01959 
01960       DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
01961                    << "\n" << *L << "\n\n\n");
01962     }
01963 
01964     // Remove it!
01965     patchAndReplaceAllUsesWith(L, AvailableVal);
01966     if (DepLI->getType()->getScalarType()->isPointerTy())
01967       MD->invalidateCachedPointerInfo(DepLI);
01968     markInstructionForDeletion(L);
01969     ++NumGVNLoad;
01970     return true;
01971   }
01972 
01973   // If this load really doesn't depend on anything, then we must be loading an
01974   // undef value.  This can happen when loading for a fresh allocation with no
01975   // intervening stores, for example.
01976   if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
01977     L->replaceAllUsesWith(UndefValue::get(L->getType()));
01978     markInstructionForDeletion(L);
01979     ++NumGVNLoad;
01980     return true;
01981   }
01982 
01983   // If this load occurs either right after a lifetime begin,
01984   // then the loaded value is undefined.
01985   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
01986     if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
01987       L->replaceAllUsesWith(UndefValue::get(L->getType()));
01988       markInstructionForDeletion(L);
01989       ++NumGVNLoad;
01990       return true;
01991     }
01992   }
01993 
01994   // If this load follows a calloc (which zero initializes memory),
01995   // then the loaded value is zero
01996   if (isCallocLikeFn(DepInst, TLI)) {
01997     L->replaceAllUsesWith(Constant::getNullValue(L->getType()));
01998     markInstructionForDeletion(L);
01999     ++NumGVNLoad;
02000     return true;
02001   }
02002 
02003   return false;
02004 }
02005 
02006 // In order to find a leader for a given value number at a
02007 // specific basic block, we first obtain the list of all Values for that number,
02008 // and then scan the list to find one whose block dominates the block in
02009 // question.  This is fast because dominator tree queries consist of only
02010 // a few comparisons of DFS numbers.
02011 Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
02012   LeaderTableEntry Vals = LeaderTable[num];
02013   if (!Vals.Val) return nullptr;
02014 
02015   Value *Val = nullptr;
02016   if (DT->dominates(Vals.BB, BB)) {
02017     Val = Vals.Val;
02018     if (isa<Constant>(Val)) return Val;
02019   }
02020 
02021   LeaderTableEntry* Next = Vals.Next;
02022   while (Next) {
02023     if (DT->dominates(Next->BB, BB)) {
02024       if (isa<Constant>(Next->Val)) return Next->Val;
02025       if (!Val) Val = Next->Val;
02026     }
02027 
02028     Next = Next->Next;
02029   }
02030 
02031   return Val;
02032 }
02033 
02034 /// Replace all uses of 'From' with 'To' if the use is dominated by the given
02035 /// basic block.  Returns the number of uses that were replaced.
02036 unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
02037                                           const BasicBlockEdge &Root) {
02038   unsigned Count = 0;
02039   for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
02040        UI != UE; ) {
02041     Use &U = *UI++;
02042 
02043     if (DT->dominates(Root, U)) {
02044       U.set(To);
02045       ++Count;
02046     }
02047   }
02048   return Count;
02049 }
02050 
02051 /// There is an edge from 'Src' to 'Dst'.  Return
02052 /// true if every path from the entry block to 'Dst' passes via this edge.  In
02053 /// particular 'Dst' must not be reachable via another edge from 'Src'.
02054 static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
02055                                        DominatorTree *DT) {
02056   // While in theory it is interesting to consider the case in which Dst has
02057   // more than one predecessor, because Dst might be part of a loop which is
02058   // only reachable from Src, in practice it is pointless since at the time
02059   // GVN runs all such loops have preheaders, which means that Dst will have
02060   // been changed to have only one predecessor, namely Src.
02061   const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
02062   const BasicBlock *Src = E.getStart();
02063   assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
02064   (void)Src;
02065   return Pred != nullptr;
02066 }
02067 
02068 /// The given values are known to be equal in every block
02069 /// dominated by 'Root'.  Exploit this, for example by replacing 'LHS' with
02070 /// 'RHS' everywhere in the scope.  Returns whether a change was made.
02071 bool GVN::propagateEquality(Value *LHS, Value *RHS,
02072                             const BasicBlockEdge &Root) {
02073   SmallVector<std::pair<Value*, Value*>, 4> Worklist;
02074   Worklist.push_back(std::make_pair(LHS, RHS));
02075   bool Changed = false;
02076   // For speed, compute a conservative fast approximation to
02077   // DT->dominates(Root, Root.getEnd());
02078   bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
02079 
02080   while (!Worklist.empty()) {
02081     std::pair<Value*, Value*> Item = Worklist.pop_back_val();
02082     LHS = Item.first; RHS = Item.second;
02083 
02084     if (LHS == RHS) continue;
02085     assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
02086 
02087     // Don't try to propagate equalities between constants.
02088     if (isa<Constant>(LHS) && isa<Constant>(RHS)) continue;
02089 
02090     // Prefer a constant on the right-hand side, or an Argument if no constants.
02091     if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
02092       std::swap(LHS, RHS);
02093     assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
02094 
02095     // If there is no obvious reason to prefer the left-hand side over the
02096     // right-hand side, ensure the longest lived term is on the right-hand side,
02097     // so the shortest lived term will be replaced by the longest lived.
02098     // This tends to expose more simplifications.
02099     uint32_t LVN = VN.lookup_or_add(LHS);
02100     if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
02101         (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
02102       // Move the 'oldest' value to the right-hand side, using the value number
02103       // as a proxy for age.
02104       uint32_t RVN = VN.lookup_or_add(RHS);
02105       if (LVN < RVN) {
02106         std::swap(LHS, RHS);
02107         LVN = RVN;
02108       }
02109     }
02110 
02111     // If value numbering later sees that an instruction in the scope is equal
02112     // to 'LHS' then ensure it will be turned into 'RHS'.  In order to preserve
02113     // the invariant that instructions only occur in the leader table for their
02114     // own value number (this is used by removeFromLeaderTable), do not do this
02115     // if RHS is an instruction (if an instruction in the scope is morphed into
02116     // LHS then it will be turned into RHS by the next GVN iteration anyway, so
02117     // using the leader table is about compiling faster, not optimizing better).
02118     // The leader table only tracks basic blocks, not edges. Only add to if we
02119     // have the simple case where the edge dominates the end.
02120     if (RootDominatesEnd && !isa<Instruction>(RHS))
02121       addToLeaderTable(LVN, RHS, Root.getEnd());
02122 
02123     // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope.  As
02124     // LHS always has at least one use that is not dominated by Root, this will
02125     // never do anything if LHS has only one use.
02126     if (!LHS->hasOneUse()) {
02127       unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
02128       Changed |= NumReplacements > 0;
02129       NumGVNEqProp += NumReplacements;
02130     }
02131 
02132     // Now try to deduce additional equalities from this one. For example, if
02133     // the known equality was "(A != B)" == "false" then it follows that A and B
02134     // are equal in the scope. Only boolean equalities with an explicit true or
02135     // false RHS are currently supported.
02136     if (!RHS->getType()->isIntegerTy(1))
02137       // Not a boolean equality - bail out.
02138       continue;
02139     ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
02140     if (!CI)
02141       // RHS neither 'true' nor 'false' - bail out.
02142       continue;
02143     // Whether RHS equals 'true'.  Otherwise it equals 'false'.
02144     bool isKnownTrue = CI->isAllOnesValue();
02145     bool isKnownFalse = !isKnownTrue;
02146 
02147     // If "A && B" is known true then both A and B are known true.  If "A || B"
02148     // is known false then both A and B are known false.
02149     Value *A, *B;
02150     if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
02151         (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
02152       Worklist.push_back(std::make_pair(A, RHS));
02153       Worklist.push_back(std::make_pair(B, RHS));
02154       continue;
02155     }
02156 
02157     // If we are propagating an equality like "(A == B)" == "true" then also
02158     // propagate the equality A == B.  When propagating a comparison such as
02159     // "(A >= B)" == "true", replace all instances of "A < B" with "false".
02160     if (CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
02161       Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
02162 
02163       // If "A == B" is known true, or "A != B" is known false, then replace
02164       // A with B everywhere in the scope.
02165       if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
02166           (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
02167         Worklist.push_back(std::make_pair(Op0, Op1));
02168 
02169       // Handle the floating point versions of equality comparisons too.
02170       if ((isKnownTrue && Cmp->getPredicate() == CmpInst::FCMP_OEQ) ||
02171           (isKnownFalse && Cmp->getPredicate() == CmpInst::FCMP_UNE)) {
02172 
02173         // Floating point -0.0 and 0.0 compare equal, so we can only
02174         // propagate values if we know that we have a constant and that
02175         // its value is non-zero.
02176         
02177         // FIXME: We should do this optimization if 'no signed zeros' is
02178         // applicable via an instruction-level fast-math-flag or some other
02179         // indicator that relaxed FP semantics are being used.
02180 
02181         if (isa<ConstantFP>(Op1) && !cast<ConstantFP>(Op1)->isZero())
02182           Worklist.push_back(std::make_pair(Op0, Op1));
02183       }
02184  
02185       // If "A >= B" is known true, replace "A < B" with false everywhere.
02186       CmpInst::Predicate NotPred = Cmp->getInversePredicate();
02187       Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
02188       // Since we don't have the instruction "A < B" immediately to hand, work
02189       // out the value number that it would have and use that to find an
02190       // appropriate instruction (if any).
02191       uint32_t NextNum = VN.getNextUnusedValueNumber();
02192       uint32_t Num = VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0, Op1);
02193       // If the number we were assigned was brand new then there is no point in
02194       // looking for an instruction realizing it: there cannot be one!
02195       if (Num < NextNum) {
02196         Value *NotCmp = findLeader(Root.getEnd(), Num);
02197         if (NotCmp && isa<Instruction>(NotCmp)) {
02198           unsigned NumReplacements =
02199             replaceAllDominatedUsesWith(NotCmp, NotVal, Root);
02200           Changed |= NumReplacements > 0;
02201           NumGVNEqProp += NumReplacements;
02202         }
02203       }
02204       // Ensure that any instruction in scope that gets the "A < B" value number
02205       // is replaced with false.
02206       // The leader table only tracks basic blocks, not edges. Only add to if we
02207       // have the simple case where the edge dominates the end.
02208       if (RootDominatesEnd)
02209         addToLeaderTable(Num, NotVal, Root.getEnd());
02210 
02211       continue;
02212     }
02213   }
02214 
02215   return Changed;
02216 }
02217 
02218 /// When calculating availability, handle an instruction
02219 /// by inserting it into the appropriate sets
02220 bool GVN::processInstruction(Instruction *I) {
02221   // Ignore dbg info intrinsics.
02222   if (isa<DbgInfoIntrinsic>(I))
02223     return false;
02224 
02225   // If the instruction can be easily simplified then do so now in preference
02226   // to value numbering it.  Value numbering often exposes redundancies, for
02227   // example if it determines that %y is equal to %x then the instruction
02228   // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
02229   const DataLayout &DL = I->getModule()->getDataLayout();
02230   if (Value *V = SimplifyInstruction(I, DL, TLI, DT, AC)) {
02231     I->replaceAllUsesWith(V);
02232     if (MD && V->getType()->getScalarType()->isPointerTy())
02233       MD->invalidateCachedPointerInfo(V);
02234     markInstructionForDeletion(I);
02235     ++NumGVNSimpl;
02236     return true;
02237   }
02238 
02239   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
02240     if (processLoad(LI))
02241       return true;
02242 
02243     unsigned Num = VN.lookup_or_add(LI);
02244     addToLeaderTable(Num, LI, LI->getParent());
02245     return false;
02246   }
02247 
02248   // For conditional branches, we can perform simple conditional propagation on
02249   // the condition value itself.
02250   if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
02251     if (!BI->isConditional())
02252       return false;
02253 
02254     if (isa<Constant>(BI->getCondition()))
02255       return processFoldableCondBr(BI);
02256 
02257     Value *BranchCond = BI->getCondition();
02258     BasicBlock *TrueSucc = BI->getSuccessor(0);
02259     BasicBlock *FalseSucc = BI->getSuccessor(1);
02260     // Avoid multiple edges early.
02261     if (TrueSucc == FalseSucc)
02262       return false;
02263 
02264     BasicBlock *Parent = BI->getParent();
02265     bool Changed = false;
02266 
02267     Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
02268     BasicBlockEdge TrueE(Parent, TrueSucc);
02269     Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
02270 
02271     Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
02272     BasicBlockEdge FalseE(Parent, FalseSucc);
02273     Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
02274 
02275     return Changed;
02276   }
02277 
02278   // For switches, propagate the case values into the case destinations.
02279   if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
02280     Value *SwitchCond = SI->getCondition();
02281     BasicBlock *Parent = SI->getParent();
02282     bool Changed = false;
02283 
02284     // Remember how many outgoing edges there are to every successor.
02285     SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
02286     for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
02287       ++SwitchEdges[SI->getSuccessor(i)];
02288 
02289     for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
02290          i != e; ++i) {
02291       BasicBlock *Dst = i.getCaseSuccessor();
02292       // If there is only a single edge, propagate the case value into it.
02293       if (SwitchEdges.lookup(Dst) == 1) {
02294         BasicBlockEdge E(Parent, Dst);
02295         Changed |= propagateEquality(SwitchCond, i.getCaseValue(), E);
02296       }
02297     }
02298     return Changed;
02299   }
02300 
02301   // Instructions with void type don't return a value, so there's
02302   // no point in trying to find redundancies in them.
02303   if (I->getType()->isVoidTy()) return false;
02304 
02305   uint32_t NextNum = VN.getNextUnusedValueNumber();
02306   unsigned Num = VN.lookup_or_add(I);
02307 
02308   // Allocations are always uniquely numbered, so we can save time and memory
02309   // by fast failing them.
02310   if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
02311     addToLeaderTable(Num, I, I->getParent());
02312     return false;
02313   }
02314 
02315   // If the number we were assigned was a brand new VN, then we don't
02316   // need to do a lookup to see if the number already exists
02317   // somewhere in the domtree: it can't!
02318   if (Num >= NextNum) {
02319     addToLeaderTable(Num, I, I->getParent());
02320     return false;
02321   }
02322 
02323   // Perform fast-path value-number based elimination of values inherited from
02324   // dominators.
02325   Value *repl = findLeader(I->getParent(), Num);
02326   if (!repl) {
02327     // Failure, just remember this instance for future use.
02328     addToLeaderTable(Num, I, I->getParent());
02329     return false;
02330   }
02331 
02332   // Remove it!
02333   patchAndReplaceAllUsesWith(I, repl);
02334   if (MD && repl->getType()->getScalarType()->isPointerTy())
02335     MD->invalidateCachedPointerInfo(repl);
02336   markInstructionForDeletion(I);
02337   return true;
02338 }
02339 
02340 /// runOnFunction - This is the main transformation entry point for a function.
02341 bool GVN::runOnFunction(Function& F) {
02342   if (skipOptnoneFunction(F))
02343     return false;
02344 
02345   if (!NoLoads)
02346     MD = &getAnalysis<MemoryDependenceAnalysis>();
02347   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
02348   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
02349   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
02350   VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
02351   VN.setMemDep(MD);
02352   VN.setDomTree(DT);
02353 
02354   bool Changed = false;
02355   bool ShouldContinue = true;
02356 
02357   // Merge unconditional branches, allowing PRE to catch more
02358   // optimization opportunities.
02359   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
02360     BasicBlock *BB = FI++;
02361 
02362     bool removedBlock = MergeBlockIntoPredecessor(
02363         BB, DT, /* LoopInfo */ nullptr, VN.getAliasAnalysis(), MD);
02364     if (removedBlock) ++NumGVNBlocks;
02365 
02366     Changed |= removedBlock;
02367   }
02368 
02369   unsigned Iteration = 0;
02370   while (ShouldContinue) {
02371     DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
02372     ShouldContinue = iterateOnFunction(F);
02373     Changed |= ShouldContinue;
02374     ++Iteration;
02375   }
02376 
02377   if (EnablePRE) {
02378     // Fabricate val-num for dead-code in order to suppress assertion in
02379     // performPRE().
02380     assignValNumForDeadCode();
02381     bool PREChanged = true;
02382     while (PREChanged) {
02383       PREChanged = performPRE(F);
02384       Changed |= PREChanged;
02385     }
02386   }
02387 
02388   // FIXME: Should perform GVN again after PRE does something.  PRE can move
02389   // computations into blocks where they become fully redundant.  Note that
02390   // we can't do this until PRE's critical edge splitting updates memdep.
02391   // Actually, when this happens, we should just fully integrate PRE into GVN.
02392 
02393   cleanupGlobalSets();
02394   // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
02395   // iteration. 
02396   DeadBlocks.clear();
02397 
02398   return Changed;
02399 }
02400 
02401 
02402 bool GVN::processBlock(BasicBlock *BB) {
02403   // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
02404   // (and incrementing BI before processing an instruction).
02405   assert(InstrsToErase.empty() &&
02406          "We expect InstrsToErase to be empty across iterations");
02407   if (DeadBlocks.count(BB))
02408     return false;
02409 
02410   bool ChangedFunction = false;
02411 
02412   for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
02413        BI != BE;) {
02414     ChangedFunction |= processInstruction(BI);
02415     if (InstrsToErase.empty()) {
02416       ++BI;
02417       continue;
02418     }
02419 
02420     // If we need some instructions deleted, do it now.
02421     NumGVNInstr += InstrsToErase.size();
02422 
02423     // Avoid iterator invalidation.
02424     bool AtStart = BI == BB->begin();
02425     if (!AtStart)
02426       --BI;
02427 
02428     for (SmallVectorImpl<Instruction *>::iterator I = InstrsToErase.begin(),
02429          E = InstrsToErase.end(); I != E; ++I) {
02430       DEBUG(dbgs() << "GVN removed: " << **I << '\n');
02431       if (MD) MD->removeInstruction(*I);
02432       DEBUG(verifyRemoved(*I));
02433       (*I)->eraseFromParent();
02434     }
02435     InstrsToErase.clear();
02436 
02437     if (AtStart)
02438       BI = BB->begin();
02439     else
02440       ++BI;
02441   }
02442 
02443   return ChangedFunction;
02444 }
02445 
02446 // Instantiate an expression in a predecessor that lacked it.
02447 bool GVN::performScalarPREInsertion(Instruction *Instr, BasicBlock *Pred,
02448                                     unsigned int ValNo) {
02449   // Because we are going top-down through the block, all value numbers
02450   // will be available in the predecessor by the time we need them.  Any
02451   // that weren't originally present will have been instantiated earlier
02452   // in this loop.
02453   bool success = true;
02454   for (unsigned i = 0, e = Instr->getNumOperands(); i != e; ++i) {
02455     Value *Op = Instr->getOperand(i);
02456     if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
02457       continue;
02458 
02459     if (Value *V = findLeader(Pred, VN.lookup(Op))) {
02460       Instr->setOperand(i, V);
02461     } else {
02462       success = false;
02463       break;
02464     }
02465   }
02466 
02467   // Fail out if we encounter an operand that is not available in
02468   // the PRE predecessor.  This is typically because of loads which
02469   // are not value numbered precisely.
02470   if (!success)
02471     return false;
02472 
02473   Instr->insertBefore(Pred->getTerminator());
02474   Instr->setName(Instr->getName() + ".pre");
02475   Instr->setDebugLoc(Instr->getDebugLoc());
02476   VN.add(Instr, ValNo);
02477 
02478   // Update the availability map to include the new instruction.
02479   addToLeaderTable(ValNo, Instr, Pred);
02480   return true;
02481 }
02482 
02483 bool GVN::performScalarPRE(Instruction *CurInst) {
02484   SmallVector<std::pair<Value*, BasicBlock*>, 8> predMap;
02485 
02486   if (isa<AllocaInst>(CurInst) || isa<TerminatorInst>(CurInst) ||
02487       isa<PHINode>(CurInst) || CurInst->getType()->isVoidTy() ||
02488       CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
02489       isa<DbgInfoIntrinsic>(CurInst))
02490     return false;
02491 
02492   // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
02493   // sinking the compare again, and it would force the code generator to
02494   // move the i1 from processor flags or predicate registers into a general
02495   // purpose register.
02496   if (isa<CmpInst>(CurInst))
02497     return false;
02498 
02499   // We don't currently value number ANY inline asm calls.
02500   if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
02501     if (CallI->isInlineAsm())
02502       return false;
02503 
02504   uint32_t ValNo = VN.lookup(CurInst);
02505 
02506   // Look for the predecessors for PRE opportunities.  We're
02507   // only trying to solve the basic diamond case, where
02508   // a value is computed in the successor and one predecessor,
02509   // but not the other.  We also explicitly disallow cases
02510   // where the successor is its own predecessor, because they're
02511   // more complicated to get right.
02512   unsigned NumWith = 0;
02513   unsigned NumWithout = 0;
02514   BasicBlock *PREPred = nullptr;
02515   BasicBlock *CurrentBlock = CurInst->getParent();
02516   predMap.clear();
02517 
02518   for (pred_iterator PI = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
02519        PI != PE; ++PI) {
02520     BasicBlock *P = *PI;
02521     // We're not interested in PRE where the block is its
02522     // own predecessor, or in blocks with predecessors
02523     // that are not reachable.
02524     if (P == CurrentBlock) {
02525       NumWithout = 2;
02526       break;
02527     } else if (!DT->isReachableFromEntry(P)) {
02528       NumWithout = 2;
02529       break;
02530     }
02531 
02532     Value *predV = findLeader(P, ValNo);
02533     if (!predV) {
02534       predMap.push_back(std::make_pair(static_cast<Value *>(nullptr), P));
02535       PREPred = P;
02536       ++NumWithout;
02537     } else if (predV == CurInst) {
02538       /* CurInst dominates this predecessor. */
02539       NumWithout = 2;
02540       break;
02541     } else {
02542       predMap.push_back(std::make_pair(predV, P));
02543       ++NumWith;
02544     }
02545   }
02546 
02547   // Don't do PRE when it might increase code size, i.e. when
02548   // we would need to insert instructions in more than one pred.
02549   if (NumWithout > 1 || NumWith == 0)
02550     return false;
02551 
02552   // We may have a case where all predecessors have the instruction,
02553   // and we just need to insert a phi node. Otherwise, perform
02554   // insertion.
02555   Instruction *PREInstr = nullptr;
02556 
02557   if (NumWithout != 0) {
02558     // Don't do PRE across indirect branch.
02559     if (isa<IndirectBrInst>(PREPred->getTerminator()))
02560       return false;
02561 
02562     // We can't do PRE safely on a critical edge, so instead we schedule
02563     // the edge to be split and perform the PRE the next time we iterate
02564     // on the function.
02565     unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
02566     if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
02567       toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
02568       return false;
02569     }
02570     // We need to insert somewhere, so let's give it a shot
02571     PREInstr = CurInst->clone();
02572     if (!performScalarPREInsertion(PREInstr, PREPred, ValNo)) {
02573       // If we failed insertion, make sure we remove the instruction.
02574       DEBUG(verifyRemoved(PREInstr));
02575       delete PREInstr;
02576       return false;
02577     }
02578   }
02579 
02580   // Either we should have filled in the PRE instruction, or we should
02581   // not have needed insertions.
02582   assert (PREInstr != nullptr || NumWithout == 0);
02583 
02584   ++NumGVNPRE;
02585 
02586   // Create a PHI to make the value available in this block.
02587   PHINode *Phi =
02588       PHINode::Create(CurInst->getType(), predMap.size(),
02589                       CurInst->getName() + ".pre-phi", CurrentBlock->begin());
02590   for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
02591     if (Value *V = predMap[i].first)
02592       Phi->addIncoming(V, predMap[i].second);
02593     else
02594       Phi->addIncoming(PREInstr, PREPred);
02595   }
02596 
02597   VN.add(Phi, ValNo);
02598   addToLeaderTable(ValNo, Phi, CurrentBlock);
02599   Phi->setDebugLoc(CurInst->getDebugLoc());
02600   CurInst->replaceAllUsesWith(Phi);
02601   if (Phi->getType()->getScalarType()->isPointerTy()) {
02602     // Because we have added a PHI-use of the pointer value, it has now
02603     // "escaped" from alias analysis' perspective.  We need to inform
02604     // AA of this.
02605     for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee; ++ii) {
02606       unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
02607       VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
02608     }
02609 
02610     if (MD)
02611       MD->invalidateCachedPointerInfo(Phi);
02612   }
02613   VN.erase(CurInst);
02614   removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
02615 
02616   DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
02617   if (MD)
02618     MD->removeInstruction(CurInst);
02619   DEBUG(verifyRemoved(CurInst));
02620   CurInst->eraseFromParent();
02621   ++NumGVNInstr;
02622   
02623   return true;
02624 }
02625 
02626 /// Perform a purely local form of PRE that looks for diamond
02627 /// control flow patterns and attempts to perform simple PRE at the join point.
02628 bool GVN::performPRE(Function &F) {
02629   bool Changed = false;
02630   for (BasicBlock *CurrentBlock : depth_first(&F.getEntryBlock())) {
02631     // Nothing to PRE in the entry block.
02632     if (CurrentBlock == &F.getEntryBlock())
02633       continue;
02634 
02635     // Don't perform PRE on a landing pad.
02636     if (CurrentBlock->isLandingPad())
02637       continue;
02638 
02639     for (BasicBlock::iterator BI = CurrentBlock->begin(),
02640                               BE = CurrentBlock->end();
02641          BI != BE;) {
02642       Instruction *CurInst = BI++;
02643       Changed = performScalarPRE(CurInst);
02644     }
02645   }
02646 
02647   if (splitCriticalEdges())
02648     Changed = true;
02649 
02650   return Changed;
02651 }
02652 
02653 /// Split the critical edge connecting the given two blocks, and return
02654 /// the block inserted to the critical edge.
02655 BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
02656   BasicBlock *BB = SplitCriticalEdge(
02657       Pred, Succ, CriticalEdgeSplittingOptions(getAliasAnalysis(), DT));
02658   if (MD)
02659     MD->invalidateCachedPredecessors();
02660   return BB;
02661 }
02662 
02663 /// Split critical edges found during the previous
02664 /// iteration that may enable further optimization.
02665 bool GVN::splitCriticalEdges() {
02666   if (toSplit.empty())
02667     return false;
02668   do {
02669     std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
02670     SplitCriticalEdge(Edge.first, Edge.second,
02671                       CriticalEdgeSplittingOptions(getAliasAnalysis(), DT));
02672   } while (!toSplit.empty());
02673   if (MD) MD->invalidateCachedPredecessors();
02674   return true;
02675 }
02676 
02677 /// Executes one iteration of GVN
02678 bool GVN::iterateOnFunction(Function &F) {
02679   cleanupGlobalSets();
02680 
02681   // Top-down walk of the dominator tree
02682   bool Changed = false;
02683   // Save the blocks this function have before transformation begins. GVN may
02684   // split critical edge, and hence may invalidate the RPO/DT iterator.
02685   //
02686   std::vector<BasicBlock *> BBVect;
02687   BBVect.reserve(256);
02688   // Needed for value numbering with phi construction to work.
02689   ReversePostOrderTraversal<Function *> RPOT(&F);
02690   for (ReversePostOrderTraversal<Function *>::rpo_iterator RI = RPOT.begin(),
02691                                                            RE = RPOT.end();
02692        RI != RE; ++RI)
02693     BBVect.push_back(*RI);
02694 
02695   for (std::vector<BasicBlock *>::iterator I = BBVect.begin(), E = BBVect.end();
02696        I != E; I++)
02697     Changed |= processBlock(*I);
02698 
02699   return Changed;
02700 }
02701 
02702 void GVN::cleanupGlobalSets() {
02703   VN.clear();
02704   LeaderTable.clear();
02705   TableAllocator.Reset();
02706 }
02707 
02708 /// Verify that the specified instruction does not occur in our
02709 /// internal data structures.
02710 void GVN::verifyRemoved(const Instruction *Inst) const {
02711   VN.verifyRemoved(Inst);
02712 
02713   // Walk through the value number scope to make sure the instruction isn't
02714   // ferreted away in it.
02715   for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
02716        I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
02717     const LeaderTableEntry *Node = &I->second;
02718     assert(Node->Val != Inst && "Inst still in value numbering scope!");
02719 
02720     while (Node->Next) {
02721       Node = Node->Next;
02722       assert(Node->Val != Inst && "Inst still in value numbering scope!");
02723     }
02724   }
02725 }
02726 
02727 /// BB is declared dead, which implied other blocks become dead as well. This
02728 /// function is to add all these blocks to "DeadBlocks". For the dead blocks'
02729 /// live successors, update their phi nodes by replacing the operands
02730 /// corresponding to dead blocks with UndefVal.
02731 void GVN::addDeadBlock(BasicBlock *BB) {
02732   SmallVector<BasicBlock *, 4> NewDead;
02733   SmallSetVector<BasicBlock *, 4> DF;
02734 
02735   NewDead.push_back(BB);
02736   while (!NewDead.empty()) {
02737     BasicBlock *D = NewDead.pop_back_val();
02738     if (DeadBlocks.count(D))
02739       continue;
02740 
02741     // All blocks dominated by D are dead.
02742     SmallVector<BasicBlock *, 8> Dom;
02743     DT->getDescendants(D, Dom);
02744     DeadBlocks.insert(Dom.begin(), Dom.end());
02745     
02746     // Figure out the dominance-frontier(D).
02747     for (SmallVectorImpl<BasicBlock *>::iterator I = Dom.begin(),
02748            E = Dom.end(); I != E; I++) {
02749       BasicBlock *B = *I;
02750       for (succ_iterator SI = succ_begin(B), SE = succ_end(B); SI != SE; SI++) {
02751         BasicBlock *S = *SI;
02752         if (DeadBlocks.count(S))
02753           continue;
02754 
02755         bool AllPredDead = true;
02756         for (pred_iterator PI = pred_begin(S), PE = pred_end(S); PI != PE; PI++)
02757           if (!DeadBlocks.count(*PI)) {
02758             AllPredDead = false;
02759             break;
02760           }
02761 
02762         if (!AllPredDead) {
02763           // S could be proved dead later on. That is why we don't update phi
02764           // operands at this moment.
02765           DF.insert(S);
02766         } else {
02767           // While S is not dominated by D, it is dead by now. This could take
02768           // place if S already have a dead predecessor before D is declared
02769           // dead.
02770           NewDead.push_back(S);
02771         }
02772       }
02773     }
02774   }
02775 
02776   // For the dead blocks' live successors, update their phi nodes by replacing
02777   // the operands corresponding to dead blocks with UndefVal.
02778   for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
02779         I != E; I++) {
02780     BasicBlock *B = *I;
02781     if (DeadBlocks.count(B))
02782       continue;
02783 
02784     SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
02785     for (SmallVectorImpl<BasicBlock *>::iterator PI = Preds.begin(),
02786            PE = Preds.end(); PI != PE; PI++) {
02787       BasicBlock *P = *PI;
02788 
02789       if (!DeadBlocks.count(P))
02790         continue;
02791 
02792       if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
02793         if (BasicBlock *S = splitCriticalEdges(P, B))
02794           DeadBlocks.insert(P = S);
02795       }
02796 
02797       for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); ++II) {
02798         PHINode &Phi = cast<PHINode>(*II);
02799         Phi.setIncomingValue(Phi.getBasicBlockIndex(P),
02800                              UndefValue::get(Phi.getType()));
02801       }
02802     }
02803   }
02804 }
02805 
02806 // If the given branch is recognized as a foldable branch (i.e. conditional
02807 // branch with constant condition), it will perform following analyses and
02808 // transformation.
02809 //  1) If the dead out-coming edge is a critical-edge, split it. Let 
02810 //     R be the target of the dead out-coming edge.
02811 //  1) Identify the set of dead blocks implied by the branch's dead outcoming
02812 //     edge. The result of this step will be {X| X is dominated by R}
02813 //  2) Identify those blocks which haves at least one dead prodecessor. The
02814 //     result of this step will be dominance-frontier(R).
02815 //  3) Update the PHIs in DF(R) by replacing the operands corresponding to 
02816 //     dead blocks with "UndefVal" in an hope these PHIs will optimized away.
02817 //
02818 // Return true iff *NEW* dead code are found.
02819 bool GVN::processFoldableCondBr(BranchInst *BI) {
02820   if (!BI || BI->isUnconditional())
02821     return false;
02822 
02823   ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
02824   if (!Cond)
02825     return false;
02826 
02827   BasicBlock *DeadRoot = Cond->getZExtValue() ? 
02828                          BI->getSuccessor(1) : BI->getSuccessor(0);
02829   if (DeadBlocks.count(DeadRoot))
02830     return false;
02831 
02832   if (!DeadRoot->getSinglePredecessor())
02833     DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
02834 
02835   addDeadBlock(DeadRoot);
02836   return true;
02837 }
02838 
02839 // performPRE() will trigger assert if it comes across an instruction without
02840 // associated val-num. As it normally has far more live instructions than dead
02841 // instructions, it makes more sense just to "fabricate" a val-number for the
02842 // dead code than checking if instruction involved is dead or not.
02843 void GVN::assignValNumForDeadCode() {
02844   for (SetVector<BasicBlock *>::iterator I = DeadBlocks.begin(),
02845         E = DeadBlocks.end(); I != E; I++) {
02846     BasicBlock *BB = *I;
02847     for (BasicBlock::iterator II = BB->begin(), EE = BB->end();
02848           II != EE; II++) {
02849       Instruction *Inst = &*II;
02850       unsigned ValNum = VN.lookup_or_add(Inst);
02851       addToLeaderTable(ValNum, Inst, BB);
02852     }
02853   }
02854 }