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