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