LLVM API Documentation

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