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