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