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