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