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