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