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