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