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