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