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