OSDN Git Service

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