]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Scalar/NewGVN.cpp
Merge ^/head r317503 through r317807.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Transforms / Scalar / NewGVN.cpp
1 //===---- NewGVN.cpp - Global Value Numbering Pass --------------*- C++ -*-===//
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 /// \file
10 /// This file implements the new LLVM's Global Value Numbering pass.
11 /// GVN partitions values computed by a function into congruence classes.
12 /// Values ending up in the same congruence class are guaranteed to be the same
13 /// for every execution of the program. In that respect, congruency is a
14 /// compile-time approximation of equivalence of values at runtime.
15 /// The algorithm implemented here uses a sparse formulation and it's based
16 /// on the ideas described in the paper:
17 /// "A Sparse Algorithm for Predicated Global Value Numbering" from
18 /// Karthik Gargi.
19 ///
20 /// A brief overview of the algorithm: The algorithm is essentially the same as
21 /// the standard RPO value numbering algorithm (a good reference is the paper
22 /// "SCC based value numbering" by L. Taylor Simpson) with one major difference:
23 /// The RPO algorithm proceeds, on every iteration, to process every reachable
24 /// block and every instruction in that block.  This is because the standard RPO
25 /// algorithm does not track what things have the same value number, it only
26 /// tracks what the value number of a given operation is (the mapping is
27 /// operation -> value number).  Thus, when a value number of an operation
28 /// changes, it must reprocess everything to ensure all uses of a value number
29 /// get updated properly.  In constrast, the sparse algorithm we use *also*
30 /// tracks what operations have a given value number (IE it also tracks the
31 /// reverse mapping from value number -> operations with that value number), so
32 /// that it only needs to reprocess the instructions that are affected when
33 /// something's value number changes.  The rest of the algorithm is devoted to
34 /// performing symbolic evaluation, forward propagation, and simplification of
35 /// operations based on the value numbers deduced so far.
36 ///
37 /// We also do not perform elimination by using any published algorithm.  All
38 /// published algorithms are O(Instructions). Instead, we use a technique that
39 /// is O(number of operations with the same value number), enabling us to skip
40 /// trying to eliminate things that have unique value numbers.
41 //===----------------------------------------------------------------------===//
42
43 #include "llvm/Transforms/Scalar/NewGVN.h"
44 #include "llvm/ADT/BitVector.h"
45 #include "llvm/ADT/DenseMap.h"
46 #include "llvm/ADT/DenseSet.h"
47 #include "llvm/ADT/DepthFirstIterator.h"
48 #include "llvm/ADT/Hashing.h"
49 #include "llvm/ADT/MapVector.h"
50 #include "llvm/ADT/PostOrderIterator.h"
51 #include "llvm/ADT/STLExtras.h"
52 #include "llvm/ADT/SmallPtrSet.h"
53 #include "llvm/ADT/SmallSet.h"
54 #include "llvm/ADT/SparseBitVector.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/ADT/TinyPtrVector.h"
57 #include "llvm/Analysis/AliasAnalysis.h"
58 #include "llvm/Analysis/AssumptionCache.h"
59 #include "llvm/Analysis/CFG.h"
60 #include "llvm/Analysis/CFGPrinter.h"
61 #include "llvm/Analysis/ConstantFolding.h"
62 #include "llvm/Analysis/GlobalsModRef.h"
63 #include "llvm/Analysis/InstructionSimplify.h"
64 #include "llvm/Analysis/MemoryBuiltins.h"
65 #include "llvm/Analysis/MemoryLocation.h"
66 #include "llvm/Analysis/MemorySSA.h"
67 #include "llvm/Analysis/TargetLibraryInfo.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/Dominators.h"
70 #include "llvm/IR/GlobalVariable.h"
71 #include "llvm/IR/IRBuilder.h"
72 #include "llvm/IR/IntrinsicInst.h"
73 #include "llvm/IR/LLVMContext.h"
74 #include "llvm/IR/Metadata.h"
75 #include "llvm/IR/PatternMatch.h"
76 #include "llvm/IR/Type.h"
77 #include "llvm/Support/Allocator.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/DebugCounter.h"
81 #include "llvm/Transforms/Scalar.h"
82 #include "llvm/Transforms/Scalar/GVNExpression.h"
83 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
84 #include "llvm/Transforms/Utils/Local.h"
85 #include "llvm/Transforms/Utils/PredicateInfo.h"
86 #include "llvm/Transforms/Utils/VNCoercion.h"
87 #include <numeric>
88 #include <unordered_map>
89 #include <utility>
90 #include <vector>
91 using namespace llvm;
92 using namespace PatternMatch;
93 using namespace llvm::GVNExpression;
94 using namespace llvm::VNCoercion;
95 #define DEBUG_TYPE "newgvn"
96
97 STATISTIC(NumGVNInstrDeleted, "Number of instructions deleted");
98 STATISTIC(NumGVNBlocksDeleted, "Number of blocks deleted");
99 STATISTIC(NumGVNOpsSimplified, "Number of Expressions simplified");
100 STATISTIC(NumGVNPhisAllSame, "Number of PHIs whos arguments are all the same");
101 STATISTIC(NumGVNMaxIterations,
102           "Maximum Number of iterations it took to converge GVN");
103 STATISTIC(NumGVNLeaderChanges, "Number of leader changes");
104 STATISTIC(NumGVNSortedLeaderChanges, "Number of sorted leader changes");
105 STATISTIC(NumGVNAvoidedSortedLeaderChanges,
106           "Number of avoided sorted leader changes");
107 STATISTIC(NumGVNNotMostDominatingLeader,
108           "Number of times a member dominated it's new classes' leader");
109 STATISTIC(NumGVNDeadStores, "Number of redundant/dead stores eliminated");
110 DEBUG_COUNTER(VNCounter, "newgvn-vn",
111               "Controls which instructions are value numbered")
112
113 // Currently store defining access refinement is too slow due to basicaa being
114 // egregiously slow.  This flag lets us keep it working while we work on this
115 // issue.
116 static cl::opt<bool> EnableStoreRefinement("enable-store-refinement",
117                                            cl::init(false), cl::Hidden);
118
119 //===----------------------------------------------------------------------===//
120 //                                GVN Pass
121 //===----------------------------------------------------------------------===//
122
123 // Anchor methods.
124 namespace llvm {
125 namespace GVNExpression {
126 Expression::~Expression() = default;
127 BasicExpression::~BasicExpression() = default;
128 CallExpression::~CallExpression() = default;
129 LoadExpression::~LoadExpression() = default;
130 StoreExpression::~StoreExpression() = default;
131 AggregateValueExpression::~AggregateValueExpression() = default;
132 PHIExpression::~PHIExpression() = default;
133 }
134 }
135
136 // Tarjan's SCC finding algorithm with Nuutila's improvements
137 // SCCIterator is actually fairly complex for the simple thing we want.
138 // It also wants to hand us SCC's that are unrelated to the phi node we ask
139 // about, and have us process them there or risk redoing work.
140 // Graph traits over a filter iterator also doesn't work that well here.
141 // This SCC finder is specialized to walk use-def chains, and only follows
142 // instructions,
143 // not generic values (arguments, etc).
144 struct TarjanSCC {
145
146   TarjanSCC() : Components(1) {}
147
148   void Start(const Instruction *Start) {
149     if (Root.lookup(Start) == 0)
150       FindSCC(Start);
151   }
152
153   const SmallPtrSetImpl<const Value *> &getComponentFor(const Value *V) const {
154     unsigned ComponentID = ValueToComponent.lookup(V);
155
156     assert(ComponentID > 0 &&
157            "Asking for a component for a value we never processed");
158     return Components[ComponentID];
159   }
160
161 private:
162   void FindSCC(const Instruction *I) {
163     Root[I] = ++DFSNum;
164     // Store the DFS Number we had before it possibly gets incremented.
165     unsigned int OurDFS = DFSNum;
166     for (auto &Op : I->operands()) {
167       if (auto *InstOp = dyn_cast<Instruction>(Op)) {
168         if (Root.lookup(Op) == 0)
169           FindSCC(InstOp);
170         if (!InComponent.count(Op))
171           Root[I] = std::min(Root.lookup(I), Root.lookup(Op));
172       }
173     }
174     // See if we really were the root of a component, by seeing if we still have
175     // our DFSNumber.
176     // If we do, we are the root of the component, and we have completed a
177     // component. If we do not,
178     // we are not the root of a component, and belong on the component stack.
179     if (Root.lookup(I) == OurDFS) {
180       unsigned ComponentID = Components.size();
181       Components.resize(Components.size() + 1);
182       auto &Component = Components.back();
183       Component.insert(I);
184       DEBUG(dbgs() << "Component root is " << *I << "\n");
185       InComponent.insert(I);
186       ValueToComponent[I] = ComponentID;
187       // Pop a component off the stack and label it.
188       while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
189         auto *Member = Stack.back();
190         DEBUG(dbgs() << "Component member is " << *Member << "\n");
191         Component.insert(Member);
192         InComponent.insert(Member);
193         ValueToComponent[Member] = ComponentID;
194         Stack.pop_back();
195       }
196     } else {
197       // Part of a component, push to stack
198       Stack.push_back(I);
199     }
200   }
201   unsigned int DFSNum = 1;
202   SmallPtrSet<const Value *, 8> InComponent;
203   DenseMap<const Value *, unsigned int> Root;
204   SmallVector<const Value *, 8> Stack;
205   // Store the components as vector of ptr sets, because we need the topo order
206   // of SCC's, but not individual member order
207   SmallVector<SmallPtrSet<const Value *, 8>, 8> Components;
208   DenseMap<const Value *, unsigned> ValueToComponent;
209 };
210 // Congruence classes represent the set of expressions/instructions
211 // that are all the same *during some scope in the function*.
212 // That is, because of the way we perform equality propagation, and
213 // because of memory value numbering, it is not correct to assume
214 // you can willy-nilly replace any member with any other at any
215 // point in the function.
216 //
217 // For any Value in the Member set, it is valid to replace any dominated member
218 // with that Value.
219 //
220 // Every congruence class has a leader, and the leader is used to symbolize
221 // instructions in a canonical way (IE every operand of an instruction that is a
222 // member of the same congruence class will always be replaced with leader
223 // during symbolization).  To simplify symbolization, we keep the leader as a
224 // constant if class can be proved to be a constant value.  Otherwise, the
225 // leader is the member of the value set with the smallest DFS number.  Each
226 // congruence class also has a defining expression, though the expression may be
227 // null.  If it exists, it can be used for forward propagation and reassociation
228 // of values.
229
230 // For memory, we also track a representative MemoryAccess, and a set of memory
231 // members for MemoryPhis (which have no real instructions). Note that for
232 // memory, it seems tempting to try to split the memory members into a
233 // MemoryCongruenceClass or something.  Unfortunately, this does not work
234 // easily.  The value numbering of a given memory expression depends on the
235 // leader of the memory congruence class, and the leader of memory congruence
236 // class depends on the value numbering of a given memory expression.  This
237 // leads to wasted propagation, and in some cases, missed optimization.  For
238 // example: If we had value numbered two stores together before, but now do not,
239 // we move them to a new value congruence class.  This in turn will move at one
240 // of the memorydefs to a new memory congruence class.  Which in turn, affects
241 // the value numbering of the stores we just value numbered (because the memory
242 // congruence class is part of the value number).  So while theoretically
243 // possible to split them up, it turns out to be *incredibly* complicated to get
244 // it to work right, because of the interdependency.  While structurally
245 // slightly messier, it is algorithmically much simpler and faster to do what we
246 // do here, and track them both at once in the same class.
247 // Note: The default iterators for this class iterate over values
248 class CongruenceClass {
249 public:
250   using MemberType = Value;
251   using MemberSet = SmallPtrSet<MemberType *, 4>;
252   using MemoryMemberType = MemoryPhi;
253   using MemoryMemberSet = SmallPtrSet<const MemoryMemberType *, 2>;
254
255   explicit CongruenceClass(unsigned ID) : ID(ID) {}
256   CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
257       : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
258   unsigned getID() const { return ID; }
259   // True if this class has no members left.  This is mainly used for assertion
260   // purposes, and for skipping empty classes.
261   bool isDead() const {
262     // If it's both dead from a value perspective, and dead from a memory
263     // perspective, it's really dead.
264     return empty() && memory_empty();
265   }
266   // Leader functions
267   Value *getLeader() const { return RepLeader; }
268   void setLeader(Value *Leader) { RepLeader = Leader; }
269   const std::pair<Value *, unsigned int> &getNextLeader() const {
270     return NextLeader;
271   }
272   void resetNextLeader() { NextLeader = {nullptr, ~0}; }
273
274   void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
275     if (LeaderPair.second < NextLeader.second)
276       NextLeader = LeaderPair;
277   }
278
279   Value *getStoredValue() const { return RepStoredValue; }
280   void setStoredValue(Value *Leader) { RepStoredValue = Leader; }
281   const MemoryAccess *getMemoryLeader() const { return RepMemoryAccess; }
282   void setMemoryLeader(const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
283
284   // Forward propagation info
285   const Expression *getDefiningExpr() const { return DefiningExpr; }
286   void setDefiningExpr(const Expression *E) { DefiningExpr = E; }
287
288   // Value member set
289   bool empty() const { return Members.empty(); }
290   unsigned size() const { return Members.size(); }
291   MemberSet::const_iterator begin() const { return Members.begin(); }
292   MemberSet::const_iterator end() const { return Members.end(); }
293   void insert(MemberType *M) { Members.insert(M); }
294   void erase(MemberType *M) { Members.erase(M); }
295   void swap(MemberSet &Other) { Members.swap(Other); }
296
297   // Memory member set
298   bool memory_empty() const { return MemoryMembers.empty(); }
299   unsigned memory_size() const { return MemoryMembers.size(); }
300   MemoryMemberSet::const_iterator memory_begin() const {
301     return MemoryMembers.begin();
302   }
303   MemoryMemberSet::const_iterator memory_end() const {
304     return MemoryMembers.end();
305   }
306   iterator_range<MemoryMemberSet::const_iterator> memory() const {
307     return make_range(memory_begin(), memory_end());
308   }
309   void memory_insert(const MemoryMemberType *M) { MemoryMembers.insert(M); }
310   void memory_erase(const MemoryMemberType *M) { MemoryMembers.erase(M); }
311
312   // Store count
313   unsigned getStoreCount() const { return StoreCount; }
314   void incStoreCount() { ++StoreCount; }
315   void decStoreCount() {
316     assert(StoreCount != 0 && "Store count went negative");
317     --StoreCount;
318   }
319
320   // Return true if two congruence classes are equivalent to each other.  This
321   // means
322   // that every field but the ID number and the dead field are equivalent.
323   bool isEquivalentTo(const CongruenceClass *Other) const {
324     if (!Other)
325       return false;
326     if (this == Other)
327       return true;
328
329     if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
330         std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
331                  Other->RepMemoryAccess))
332       return false;
333     if (DefiningExpr != Other->DefiningExpr)
334       if (!DefiningExpr || !Other->DefiningExpr ||
335           *DefiningExpr != *Other->DefiningExpr)
336         return false;
337     // We need some ordered set
338     std::set<Value *> AMembers(Members.begin(), Members.end());
339     std::set<Value *> BMembers(Members.begin(), Members.end());
340     return AMembers == BMembers;
341   }
342
343 private:
344   unsigned ID;
345   // Representative leader.
346   Value *RepLeader = nullptr;
347   // The most dominating leader after our current leader, because the member set
348   // is not sorted and is expensive to keep sorted all the time.
349   std::pair<Value *, unsigned int> NextLeader = {nullptr, ~0U};
350   // If this is represented by a store, the value of the store.
351   Value *RepStoredValue = nullptr;
352   // If this class contains MemoryDefs or MemoryPhis, this is the leading memory
353   // access.
354   const MemoryAccess *RepMemoryAccess = nullptr;
355   // Defining Expression.
356   const Expression *DefiningExpr = nullptr;
357   // Actual members of this class.
358   MemberSet Members;
359   // This is the set of MemoryPhis that exist in the class. MemoryDefs and
360   // MemoryUses have real instructions representing them, so we only need to
361   // track MemoryPhis here.
362   MemoryMemberSet MemoryMembers;
363   // Number of stores in this congruence class.
364   // This is used so we can detect store equivalence changes properly.
365   int StoreCount = 0;
366 };
367
368 namespace llvm {
369 template <> struct DenseMapInfo<const Expression *> {
370   static const Expression *getEmptyKey() {
371     auto Val = static_cast<uintptr_t>(-1);
372     Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
373     return reinterpret_cast<const Expression *>(Val);
374   }
375   static const Expression *getTombstoneKey() {
376     auto Val = static_cast<uintptr_t>(~1U);
377     Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
378     return reinterpret_cast<const Expression *>(Val);
379   }
380   static unsigned getHashValue(const Expression *V) {
381     return static_cast<unsigned>(V->getHashValue());
382   }
383   static bool isEqual(const Expression *LHS, const Expression *RHS) {
384     if (LHS == RHS)
385       return true;
386     if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
387         LHS == getEmptyKey() || RHS == getEmptyKey())
388       return false;
389     return *LHS == *RHS;
390   }
391 };
392 } // end namespace llvm
393
394 namespace {
395 class NewGVN {
396   Function &F;
397   DominatorTree *DT;
398   const TargetLibraryInfo *TLI;
399   AliasAnalysis *AA;
400   MemorySSA *MSSA;
401   MemorySSAWalker *MSSAWalker;
402   const DataLayout &DL;
403   std::unique_ptr<PredicateInfo> PredInfo;
404   BumpPtrAllocator ExpressionAllocator;
405   ArrayRecycler<Value *> ArgRecycler;
406   TarjanSCC SCCFinder;
407   const SimplifyQuery SQ;
408
409   // Number of function arguments, used by ranking
410   unsigned int NumFuncArgs;
411
412   // RPOOrdering of basic blocks
413   DenseMap<const DomTreeNode *, unsigned> RPOOrdering;
414
415   // Congruence class info.
416
417   // This class is called INITIAL in the paper. It is the class everything
418   // startsout in, and represents any value. Being an optimistic analysis,
419   // anything in the TOP class has the value TOP, which is indeterminate and
420   // equivalent to everything.
421   CongruenceClass *TOPClass;
422   std::vector<CongruenceClass *> CongruenceClasses;
423   unsigned NextCongruenceNum;
424
425   // Value Mappings.
426   DenseMap<Value *, CongruenceClass *> ValueToClass;
427   DenseMap<Value *, const Expression *> ValueToExpression;
428
429   // Mapping from predicate info we used to the instructions we used it with.
430   // In order to correctly ensure propagation, we must keep track of what
431   // comparisons we used, so that when the values of the comparisons change, we
432   // propagate the information to the places we used the comparison.
433   DenseMap<const Value *, SmallPtrSet<Instruction *, 2>> PredicateToUsers;
434   // Mapping from MemoryAccess we used to the MemoryAccess we used it with.  Has
435   // the same reasoning as PredicateToUsers.  When we skip MemoryAccesses for
436   // stores, we no longer can rely solely on the def-use chains of MemorySSA.
437   DenseMap<const MemoryAccess *, SmallPtrSet<MemoryAccess *, 2>> MemoryToUsers;
438
439   // A table storing which memorydefs/phis represent a memory state provably
440   // equivalent to another memory state.
441   // We could use the congruence class machinery, but the MemoryAccess's are
442   // abstract memory states, so they can only ever be equivalent to each other,
443   // and not to constants, etc.
444   DenseMap<const MemoryAccess *, CongruenceClass *> MemoryAccessToClass;
445
446   // We could, if we wanted, build MemoryPhiExpressions and
447   // MemoryVariableExpressions, etc, and value number them the same way we value
448   // number phi expressions.  For the moment, this seems like overkill.  They
449   // can only exist in one of three states: they can be TOP (equal to
450   // everything), Equivalent to something else, or unique.  Because we do not
451   // create expressions for them, we need to simulate leader change not just
452   // when they change class, but when they change state.  Note: We can do the
453   // same thing for phis, and avoid having phi expressions if we wanted, We
454   // should eventually unify in one direction or the other, so this is a little
455   // bit of an experiment in which turns out easier to maintain.
456   enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
457   DenseMap<const MemoryPhi *, MemoryPhiState> MemoryPhiState;
458
459   enum PhiCycleState { PCS_Unknown, PCS_CycleFree, PCS_Cycle };
460   DenseMap<const PHINode *, PhiCycleState> PhiCycleState;
461   // Expression to class mapping.
462   using ExpressionClassMap = DenseMap<const Expression *, CongruenceClass *>;
463   ExpressionClassMap ExpressionToClass;
464
465   // Which values have changed as a result of leader changes.
466   SmallPtrSet<Value *, 8> LeaderChanges;
467
468   // Reachability info.
469   using BlockEdge = BasicBlockEdge;
470   DenseSet<BlockEdge> ReachableEdges;
471   SmallPtrSet<const BasicBlock *, 8> ReachableBlocks;
472
473   // This is a bitvector because, on larger functions, we may have
474   // thousands of touched instructions at once (entire blocks,
475   // instructions with hundreds of uses, etc).  Even with optimization
476   // for when we mark whole blocks as touched, when this was a
477   // SmallPtrSet or DenseSet, for some functions, we spent >20% of all
478   // the time in GVN just managing this list.  The bitvector, on the
479   // other hand, efficiently supports test/set/clear of both
480   // individual and ranges, as well as "find next element" This
481   // enables us to use it as a worklist with essentially 0 cost.
482   BitVector TouchedInstructions;
483
484   DenseMap<const BasicBlock *, std::pair<unsigned, unsigned>> BlockInstRange;
485
486 #ifndef NDEBUG
487   // Debugging for how many times each block and instruction got processed.
488   DenseMap<const Value *, unsigned> ProcessedCount;
489 #endif
490
491   // DFS info.
492   // This contains a mapping from Instructions to DFS numbers.
493   // The numbering starts at 1. An instruction with DFS number zero
494   // means that the instruction is dead.
495   DenseMap<const Value *, unsigned> InstrDFS;
496
497   // This contains the mapping DFS numbers to instructions.
498   SmallVector<Value *, 32> DFSToInstr;
499
500   // Deletion info.
501   SmallPtrSet<Instruction *, 8> InstructionsToErase;
502
503 public:
504   NewGVN(Function &F, DominatorTree *DT, AssumptionCache *AC,
505          TargetLibraryInfo *TLI, AliasAnalysis *AA, MemorySSA *MSSA,
506          const DataLayout &DL)
507       : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
508         PredInfo(make_unique<PredicateInfo>(F, *DT, *AC)), SQ(DL, TLI, DT, AC) {
509   }
510   bool runGVN();
511
512 private:
513   // Expression handling.
514   const Expression *createExpression(Instruction *);
515   const Expression *createBinaryExpression(unsigned, Type *, Value *, Value *);
516   PHIExpression *createPHIExpression(Instruction *, bool &HasBackedge,
517                                      bool &AllConstant);
518   const VariableExpression *createVariableExpression(Value *);
519   const ConstantExpression *createConstantExpression(Constant *);
520   const Expression *createVariableOrConstant(Value *V);
521   const UnknownExpression *createUnknownExpression(Instruction *);
522   const StoreExpression *createStoreExpression(StoreInst *,
523                                                const MemoryAccess *);
524   LoadExpression *createLoadExpression(Type *, Value *, LoadInst *,
525                                        const MemoryAccess *);
526   const CallExpression *createCallExpression(CallInst *, const MemoryAccess *);
527   const AggregateValueExpression *createAggregateValueExpression(Instruction *);
528   bool setBasicExpressionInfo(Instruction *, BasicExpression *);
529
530   // Congruence class handling.
531   CongruenceClass *createCongruenceClass(Value *Leader, const Expression *E) {
532     auto *result = new CongruenceClass(NextCongruenceNum++, Leader, E);
533     CongruenceClasses.emplace_back(result);
534     return result;
535   }
536
537   CongruenceClass *createMemoryClass(MemoryAccess *MA) {
538     auto *CC = createCongruenceClass(nullptr, nullptr);
539     CC->setMemoryLeader(MA);
540     return CC;
541   }
542   CongruenceClass *ensureLeaderOfMemoryClass(MemoryAccess *MA) {
543     auto *CC = getMemoryClass(MA);
544     if (CC->getMemoryLeader() != MA)
545       CC = createMemoryClass(MA);
546     return CC;
547   }
548
549   CongruenceClass *createSingletonCongruenceClass(Value *Member) {
550     CongruenceClass *CClass = createCongruenceClass(Member, nullptr);
551     CClass->insert(Member);
552     ValueToClass[Member] = CClass;
553     return CClass;
554   }
555   void initializeCongruenceClasses(Function &F);
556
557   // Value number an Instruction or MemoryPhi.
558   void valueNumberMemoryPhi(MemoryPhi *);
559   void valueNumberInstruction(Instruction *);
560
561   // Symbolic evaluation.
562   const Expression *checkSimplificationResults(Expression *, Instruction *,
563                                                Value *);
564   const Expression *performSymbolicEvaluation(Value *);
565   const Expression *performSymbolicLoadCoercion(Type *, Value *, LoadInst *,
566                                                 Instruction *, MemoryAccess *);
567   const Expression *performSymbolicLoadEvaluation(Instruction *);
568   const Expression *performSymbolicStoreEvaluation(Instruction *);
569   const Expression *performSymbolicCallEvaluation(Instruction *);
570   const Expression *performSymbolicPHIEvaluation(Instruction *);
571   const Expression *performSymbolicAggrValueEvaluation(Instruction *);
572   const Expression *performSymbolicCmpEvaluation(Instruction *);
573   const Expression *performSymbolicPredicateInfoEvaluation(Instruction *);
574
575   // Congruence finding.
576   bool someEquivalentDominates(const Instruction *, const Instruction *) const;
577   Value *lookupOperandLeader(Value *) const;
578   void performCongruenceFinding(Instruction *, const Expression *);
579   void moveValueToNewCongruenceClass(Instruction *, const Expression *,
580                                      CongruenceClass *, CongruenceClass *);
581   void moveMemoryToNewCongruenceClass(Instruction *, MemoryAccess *,
582                                       CongruenceClass *, CongruenceClass *);
583   Value *getNextValueLeader(CongruenceClass *) const;
584   const MemoryAccess *getNextMemoryLeader(CongruenceClass *) const;
585   bool setMemoryClass(const MemoryAccess *From, CongruenceClass *To);
586   CongruenceClass *getMemoryClass(const MemoryAccess *MA) const;
587   const MemoryAccess *lookupMemoryLeader(const MemoryAccess *) const;
588   bool isMemoryAccessTop(const MemoryAccess *) const;
589
590   // Ranking
591   unsigned int getRank(const Value *) const;
592   bool shouldSwapOperands(const Value *, const Value *) const;
593
594   // Reachability handling.
595   void updateReachableEdge(BasicBlock *, BasicBlock *);
596   void processOutgoingEdges(TerminatorInst *, BasicBlock *);
597   Value *findConditionEquivalence(Value *) const;
598
599   // Elimination.
600   struct ValueDFS;
601   void convertClassToDFSOrdered(const CongruenceClass &,
602                                 SmallVectorImpl<ValueDFS> &,
603                                 DenseMap<const Value *, unsigned int> &,
604                                 SmallPtrSetImpl<Instruction *> &) const;
605   void convertClassToLoadsAndStores(const CongruenceClass &,
606                                     SmallVectorImpl<ValueDFS> &) const;
607
608   bool eliminateInstructions(Function &);
609   void replaceInstruction(Instruction *, Value *);
610   void markInstructionForDeletion(Instruction *);
611   void deleteInstructionsInBlock(BasicBlock *);
612
613   // New instruction creation.
614   void handleNewInstruction(Instruction *){};
615
616   // Various instruction touch utilities
617   void markUsersTouched(Value *);
618   void markMemoryUsersTouched(const MemoryAccess *);
619   void markMemoryDefTouched(const MemoryAccess *);
620   void markPredicateUsersTouched(Instruction *);
621   void markValueLeaderChangeTouched(CongruenceClass *CC);
622   void markMemoryLeaderChangeTouched(CongruenceClass *CC);
623   void addPredicateUsers(const PredicateBase *, Instruction *);
624   void addMemoryUsers(const MemoryAccess *To, MemoryAccess *U);
625
626   // Main loop of value numbering
627   void iterateTouchedInstructions();
628
629   // Utilities.
630   void cleanupTables();
631   std::pair<unsigned, unsigned> assignDFSNumbers(BasicBlock *, unsigned);
632   void updateProcessedCount(Value *V);
633   void verifyMemoryCongruency() const;
634   void verifyIterationSettled(Function &F);
635   bool singleReachablePHIPath(const MemoryAccess *, const MemoryAccess *) const;
636   BasicBlock *getBlockForValue(Value *V) const;
637   void deleteExpression(const Expression *E);
638   unsigned InstrToDFSNum(const Value *V) const {
639     assert(isa<Instruction>(V) && "This should not be used for MemoryAccesses");
640     return InstrDFS.lookup(V);
641   }
642
643   unsigned InstrToDFSNum(const MemoryAccess *MA) const {
644     return MemoryToDFSNum(MA);
645   }
646   Value *InstrFromDFSNum(unsigned DFSNum) { return DFSToInstr[DFSNum]; }
647   // Given a MemoryAccess, return the relevant instruction DFS number.  Note:
648   // This deliberately takes a value so it can be used with Use's, which will
649   // auto-convert to Value's but not to MemoryAccess's.
650   unsigned MemoryToDFSNum(const Value *MA) const {
651     assert(isa<MemoryAccess>(MA) &&
652            "This should not be used with instructions");
653     return isa<MemoryUseOrDef>(MA)
654                ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
655                : InstrDFS.lookup(MA);
656   }
657   bool isCycleFree(const PHINode *PN);
658   template <class T, class Range> T *getMinDFSOfRange(const Range &) const;
659   // Debug counter info.  When verifying, we have to reset the value numbering
660   // debug counter to the same state it started in to get the same results.
661   std::pair<int, int> StartingVNCounter;
662 };
663 } // end anonymous namespace
664
665 template <typename T>
666 static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS) {
667   if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
668     return false;
669   return LHS.MemoryExpression::equals(RHS);
670 }
671
672 bool LoadExpression::equals(const Expression &Other) const {
673   return equalsLoadStoreHelper(*this, Other);
674 }
675
676 bool StoreExpression::equals(const Expression &Other) const {
677   if (!equalsLoadStoreHelper(*this, Other))
678     return false;
679   // Make sure that store vs store includes the value operand.
680   if (const auto *S = dyn_cast<StoreExpression>(&Other))
681     if (getStoredValue() != S->getStoredValue())
682       return false;
683   return true;
684 }
685
686 #ifndef NDEBUG
687 static std::string getBlockName(const BasicBlock *B) {
688   return DOTGraphTraits<const Function *>::getSimpleNodeLabel(B, nullptr);
689 }
690 #endif
691
692 // Get the basic block from an instruction/memory value.
693 BasicBlock *NewGVN::getBlockForValue(Value *V) const {
694   if (auto *I = dyn_cast<Instruction>(V))
695     return I->getParent();
696   else if (auto *MP = dyn_cast<MemoryPhi>(V))
697     return MP->getBlock();
698   llvm_unreachable("Should have been able to figure out a block for our value");
699   return nullptr;
700 }
701
702 // Delete a definitely dead expression, so it can be reused by the expression
703 // allocator.  Some of these are not in creation functions, so we have to accept
704 // const versions.
705 void NewGVN::deleteExpression(const Expression *E) {
706   assert(isa<BasicExpression>(E));
707   auto *BE = cast<BasicExpression>(E);
708   const_cast<BasicExpression *>(BE)->deallocateOperands(ArgRecycler);
709   ExpressionAllocator.Deallocate(E);
710 }
711
712 PHIExpression *NewGVN::createPHIExpression(Instruction *I, bool &HasBackedge,
713                                            bool &AllConstant) {
714   BasicBlock *PHIBlock = I->getParent();
715   auto *PN = cast<PHINode>(I);
716   auto *E =
717       new (ExpressionAllocator) PHIExpression(PN->getNumOperands(), PHIBlock);
718
719   E->allocateOperands(ArgRecycler, ExpressionAllocator);
720   E->setType(I->getType());
721   E->setOpcode(I->getOpcode());
722
723   unsigned PHIRPO = RPOOrdering.lookup(DT->getNode(PHIBlock));
724
725   // Filter out unreachable phi operands.
726   auto Filtered = make_filter_range(PN->operands(), [&](const Use &U) {
727     return ReachableEdges.count({PN->getIncomingBlock(U), PHIBlock});
728   });
729
730   std::transform(Filtered.begin(), Filtered.end(), op_inserter(E),
731                  [&](const Use &U) -> Value * {
732                    auto *BB = PN->getIncomingBlock(U);
733                    auto *DTN = DT->getNode(BB);
734                    if (RPOOrdering.lookup(DTN) >= PHIRPO)
735                      HasBackedge = true;
736                    AllConstant &= isa<UndefValue>(U) || isa<Constant>(U);
737
738                    // Don't try to transform self-defined phis.
739                    if (U == PN)
740                      return PN;
741                    return lookupOperandLeader(U);
742                  });
743   return E;
744 }
745
746 // Set basic expression info (Arguments, type, opcode) for Expression
747 // E from Instruction I in block B.
748 bool NewGVN::setBasicExpressionInfo(Instruction *I, BasicExpression *E) {
749   bool AllConstant = true;
750   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
751     E->setType(GEP->getSourceElementType());
752   else
753     E->setType(I->getType());
754   E->setOpcode(I->getOpcode());
755   E->allocateOperands(ArgRecycler, ExpressionAllocator);
756
757   // Transform the operand array into an operand leader array, and keep track of
758   // whether all members are constant.
759   std::transform(I->op_begin(), I->op_end(), op_inserter(E), [&](Value *O) {
760     auto Operand = lookupOperandLeader(O);
761     AllConstant &= isa<Constant>(Operand);
762     return Operand;
763   });
764
765   return AllConstant;
766 }
767
768 const Expression *NewGVN::createBinaryExpression(unsigned Opcode, Type *T,
769                                                  Value *Arg1, Value *Arg2) {
770   auto *E = new (ExpressionAllocator) BasicExpression(2);
771
772   E->setType(T);
773   E->setOpcode(Opcode);
774   E->allocateOperands(ArgRecycler, ExpressionAllocator);
775   if (Instruction::isCommutative(Opcode)) {
776     // Ensure that commutative instructions that only differ by a permutation
777     // of their operands get the same value number by sorting the operand value
778     // numbers.  Since all commutative instructions have two operands it is more
779     // efficient to sort by hand rather than using, say, std::sort.
780     if (shouldSwapOperands(Arg1, Arg2))
781       std::swap(Arg1, Arg2);
782   }
783   E->op_push_back(lookupOperandLeader(Arg1));
784   E->op_push_back(lookupOperandLeader(Arg2));
785
786   Value *V = SimplifyBinOp(Opcode, E->getOperand(0), E->getOperand(1), SQ);
787   if (const Expression *SimplifiedE = checkSimplificationResults(E, nullptr, V))
788     return SimplifiedE;
789   return E;
790 }
791
792 // Take a Value returned by simplification of Expression E/Instruction
793 // I, and see if it resulted in a simpler expression. If so, return
794 // that expression.
795 // TODO: Once finished, this should not take an Instruction, we only
796 // use it for printing.
797 const Expression *NewGVN::checkSimplificationResults(Expression *E,
798                                                      Instruction *I, Value *V) {
799   if (!V)
800     return nullptr;
801   if (auto *C = dyn_cast<Constant>(V)) {
802     if (I)
803       DEBUG(dbgs() << "Simplified " << *I << " to "
804                    << " constant " << *C << "\n");
805     NumGVNOpsSimplified++;
806     assert(isa<BasicExpression>(E) &&
807            "We should always have had a basic expression here");
808     deleteExpression(E);
809     return createConstantExpression(C);
810   } else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
811     if (I)
812       DEBUG(dbgs() << "Simplified " << *I << " to "
813                    << " variable " << *V << "\n");
814     deleteExpression(E);
815     return createVariableExpression(V);
816   }
817
818   CongruenceClass *CC = ValueToClass.lookup(V);
819   if (CC && CC->getDefiningExpr()) {
820     if (I)
821       DEBUG(dbgs() << "Simplified " << *I << " to "
822                    << " expression " << *V << "\n");
823     NumGVNOpsSimplified++;
824     deleteExpression(E);
825     return CC->getDefiningExpr();
826   }
827   return nullptr;
828 }
829
830 const Expression *NewGVN::createExpression(Instruction *I) {
831   auto *E = new (ExpressionAllocator) BasicExpression(I->getNumOperands());
832
833   bool AllConstant = setBasicExpressionInfo(I, E);
834
835   if (I->isCommutative()) {
836     // Ensure that commutative instructions that only differ by a permutation
837     // of their operands get the same value number by sorting the operand value
838     // numbers.  Since all commutative instructions have two operands it is more
839     // efficient to sort by hand rather than using, say, std::sort.
840     assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
841     if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
842       E->swapOperands(0, 1);
843   }
844
845   // Perform simplificaiton
846   // TODO: Right now we only check to see if we get a constant result.
847   // We may get a less than constant, but still better, result for
848   // some operations.
849   // IE
850   //  add 0, x -> x
851   //  and x, x -> x
852   // We should handle this by simply rewriting the expression.
853   if (auto *CI = dyn_cast<CmpInst>(I)) {
854     // Sort the operand value numbers so x<y and y>x get the same value
855     // number.
856     CmpInst::Predicate Predicate = CI->getPredicate();
857     if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
858       E->swapOperands(0, 1);
859       Predicate = CmpInst::getSwappedPredicate(Predicate);
860     }
861     E->setOpcode((CI->getOpcode() << 8) | Predicate);
862     // TODO: 25% of our time is spent in SimplifyCmpInst with pointer operands
863     assert(I->getOperand(0)->getType() == I->getOperand(1)->getType() &&
864            "Wrong types on cmp instruction");
865     assert((E->getOperand(0)->getType() == I->getOperand(0)->getType() &&
866             E->getOperand(1)->getType() == I->getOperand(1)->getType()));
867     Value *V =
868         SimplifyCmpInst(Predicate, E->getOperand(0), E->getOperand(1), SQ);
869     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
870       return SimplifiedE;
871   } else if (isa<SelectInst>(I)) {
872     if (isa<Constant>(E->getOperand(0)) ||
873         E->getOperand(0) == E->getOperand(1)) {
874       assert(E->getOperand(1)->getType() == I->getOperand(1)->getType() &&
875              E->getOperand(2)->getType() == I->getOperand(2)->getType());
876       Value *V = SimplifySelectInst(E->getOperand(0), E->getOperand(1),
877                                     E->getOperand(2), SQ);
878       if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
879         return SimplifiedE;
880     }
881   } else if (I->isBinaryOp()) {
882     Value *V =
883         SimplifyBinOp(E->getOpcode(), E->getOperand(0), E->getOperand(1), SQ);
884     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
885       return SimplifiedE;
886   } else if (auto *BI = dyn_cast<BitCastInst>(I)) {
887     Value *V =
888         SimplifyCastInst(BI->getOpcode(), BI->getOperand(0), BI->getType(), SQ);
889     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
890       return SimplifiedE;
891   } else if (isa<GetElementPtrInst>(I)) {
892     Value *V = SimplifyGEPInst(
893         E->getType(), ArrayRef<Value *>(E->op_begin(), E->op_end()), SQ);
894     if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
895       return SimplifiedE;
896   } else if (AllConstant) {
897     // We don't bother trying to simplify unless all of the operands
898     // were constant.
899     // TODO: There are a lot of Simplify*'s we could call here, if we
900     // wanted to.  The original motivating case for this code was a
901     // zext i1 false to i8, which we don't have an interface to
902     // simplify (IE there is no SimplifyZExt).
903
904     SmallVector<Constant *, 8> C;
905     for (Value *Arg : E->operands())
906       C.emplace_back(cast<Constant>(Arg));
907
908     if (Value *V = ConstantFoldInstOperands(I, C, DL, TLI))
909       if (const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
910         return SimplifiedE;
911   }
912   return E;
913 }
914
915 const AggregateValueExpression *
916 NewGVN::createAggregateValueExpression(Instruction *I) {
917   if (auto *II = dyn_cast<InsertValueInst>(I)) {
918     auto *E = new (ExpressionAllocator)
919         AggregateValueExpression(I->getNumOperands(), II->getNumIndices());
920     setBasicExpressionInfo(I, E);
921     E->allocateIntOperands(ExpressionAllocator);
922     std::copy(II->idx_begin(), II->idx_end(), int_op_inserter(E));
923     return E;
924   } else if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
925     auto *E = new (ExpressionAllocator)
926         AggregateValueExpression(I->getNumOperands(), EI->getNumIndices());
927     setBasicExpressionInfo(EI, E);
928     E->allocateIntOperands(ExpressionAllocator);
929     std::copy(EI->idx_begin(), EI->idx_end(), int_op_inserter(E));
930     return E;
931   }
932   llvm_unreachable("Unhandled type of aggregate value operation");
933 }
934
935 const VariableExpression *NewGVN::createVariableExpression(Value *V) {
936   auto *E = new (ExpressionAllocator) VariableExpression(V);
937   E->setOpcode(V->getValueID());
938   return E;
939 }
940
941 const Expression *NewGVN::createVariableOrConstant(Value *V) {
942   if (auto *C = dyn_cast<Constant>(V))
943     return createConstantExpression(C);
944   return createVariableExpression(V);
945 }
946
947 const ConstantExpression *NewGVN::createConstantExpression(Constant *C) {
948   auto *E = new (ExpressionAllocator) ConstantExpression(C);
949   E->setOpcode(C->getValueID());
950   return E;
951 }
952
953 const UnknownExpression *NewGVN::createUnknownExpression(Instruction *I) {
954   auto *E = new (ExpressionAllocator) UnknownExpression(I);
955   E->setOpcode(I->getOpcode());
956   return E;
957 }
958
959 const CallExpression *NewGVN::createCallExpression(CallInst *CI,
960                                                    const MemoryAccess *MA) {
961   // FIXME: Add operand bundles for calls.
962   auto *E =
963       new (ExpressionAllocator) CallExpression(CI->getNumOperands(), CI, MA);
964   setBasicExpressionInfo(CI, E);
965   return E;
966 }
967
968 // Return true if some equivalent of instruction Inst dominates instruction U.
969 bool NewGVN::someEquivalentDominates(const Instruction *Inst,
970                                      const Instruction *U) const {
971   auto *CC = ValueToClass.lookup(Inst);
972   // This must be an instruction because we are only called from phi nodes
973   // in the case that the value it needs to check against is an instruction.
974
975   // The most likely candiates for dominance are the leader and the next leader.
976   // The leader or nextleader will dominate in all cases where there is an
977   // equivalent that is higher up in the dom tree.
978   // We can't *only* check them, however, because the
979   // dominator tree could have an infinite number of non-dominating siblings
980   // with instructions that are in the right congruence class.
981   //       A
982   // B C D E F G
983   // |
984   // H
985   // Instruction U could be in H,  with equivalents in every other sibling.
986   // Depending on the rpo order picked, the leader could be the equivalent in
987   // any of these siblings.
988   if (!CC)
989     return false;
990   if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
991     return true;
992   if (CC->getNextLeader().first &&
993       DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
994     return true;
995   return llvm::any_of(*CC, [&](const Value *Member) {
996     return Member != CC->getLeader() &&
997            DT->dominates(cast<Instruction>(Member), U);
998   });
999 }
1000
1001 // See if we have a congruence class and leader for this operand, and if so,
1002 // return it. Otherwise, return the operand itself.
1003 Value *NewGVN::lookupOperandLeader(Value *V) const {
1004   CongruenceClass *CC = ValueToClass.lookup(V);
1005   if (CC) {
1006     // Everything in TOP is represneted by undef, as it can be any value.
1007     // We do have to make sure we get the type right though, so we can't set the
1008     // RepLeader to undef.
1009     if (CC == TOPClass)
1010       return UndefValue::get(V->getType());
1011     return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
1012   }
1013
1014   return V;
1015 }
1016
1017 const MemoryAccess *NewGVN::lookupMemoryLeader(const MemoryAccess *MA) const {
1018   auto *CC = getMemoryClass(MA);
1019   assert(CC->getMemoryLeader() &&
1020          "Every MemoryAccess should be mapped to a "
1021          "congruence class with a represenative memory "
1022          "access");
1023   return CC->getMemoryLeader();
1024 }
1025
1026 // Return true if the MemoryAccess is really equivalent to everything. This is
1027 // equivalent to the lattice value "TOP" in most lattices.  This is the initial
1028 // state of all MemoryAccesses.
1029 bool NewGVN::isMemoryAccessTop(const MemoryAccess *MA) const {
1030   return getMemoryClass(MA) == TOPClass;
1031 }
1032
1033 LoadExpression *NewGVN::createLoadExpression(Type *LoadType, Value *PointerOp,
1034                                              LoadInst *LI,
1035                                              const MemoryAccess *MA) {
1036   auto *E =
1037       new (ExpressionAllocator) LoadExpression(1, LI, lookupMemoryLeader(MA));
1038   E->allocateOperands(ArgRecycler, ExpressionAllocator);
1039   E->setType(LoadType);
1040
1041   // Give store and loads same opcode so they value number together.
1042   E->setOpcode(0);
1043   E->op_push_back(PointerOp);
1044   if (LI)
1045     E->setAlignment(LI->getAlignment());
1046
1047   // TODO: Value number heap versions. We may be able to discover
1048   // things alias analysis can't on it's own (IE that a store and a
1049   // load have the same value, and thus, it isn't clobbering the load).
1050   return E;
1051 }
1052
1053 const StoreExpression *NewGVN::createStoreExpression(StoreInst *SI,
1054                                                      const MemoryAccess *MA) {
1055   auto *StoredValueLeader = lookupOperandLeader(SI->getValueOperand());
1056   auto *E = new (ExpressionAllocator)
1057       StoreExpression(SI->getNumOperands(), SI, StoredValueLeader, MA);
1058   E->allocateOperands(ArgRecycler, ExpressionAllocator);
1059   E->setType(SI->getValueOperand()->getType());
1060
1061   // Give store and loads same opcode so they value number together.
1062   E->setOpcode(0);
1063   E->op_push_back(lookupOperandLeader(SI->getPointerOperand()));
1064
1065   // TODO: Value number heap versions. We may be able to discover
1066   // things alias analysis can't on it's own (IE that a store and a
1067   // load have the same value, and thus, it isn't clobbering the load).
1068   return E;
1069 }
1070
1071 const Expression *NewGVN::performSymbolicStoreEvaluation(Instruction *I) {
1072   // Unlike loads, we never try to eliminate stores, so we do not check if they
1073   // are simple and avoid value numbering them.
1074   auto *SI = cast<StoreInst>(I);
1075   auto *StoreAccess = MSSA->getMemoryAccess(SI);
1076   // Get the expression, if any, for the RHS of the MemoryDef.
1077   const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1078   if (EnableStoreRefinement)
1079     StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1080   // If we bypassed the use-def chains, make sure we add a use.
1081   if (StoreRHS != StoreAccess->getDefiningAccess())
1082     addMemoryUsers(StoreRHS, StoreAccess);
1083
1084   StoreRHS = lookupMemoryLeader(StoreRHS);
1085   // If we are defined by ourselves, use the live on entry def.
1086   if (StoreRHS == StoreAccess)
1087     StoreRHS = MSSA->getLiveOnEntryDef();
1088
1089   if (SI->isSimple()) {
1090     // See if we are defined by a previous store expression, it already has a
1091     // value, and it's the same value as our current store. FIXME: Right now, we
1092     // only do this for simple stores, we should expand to cover memcpys, etc.
1093     const auto *LastStore = createStoreExpression(SI, StoreRHS);
1094     const auto *LastCC = ExpressionToClass.lookup(LastStore);
1095     // Basically, check if the congruence class the store is in is defined by a
1096     // store that isn't us, and has the same value.  MemorySSA takes care of
1097     // ensuring the store has the same memory state as us already.
1098     // The RepStoredValue gets nulled if all the stores disappear in a class, so
1099     // we don't need to check if the class contains a store besides us.
1100     if (LastCC &&
1101         LastCC->getStoredValue() == lookupOperandLeader(SI->getValueOperand()))
1102       return LastStore;
1103     deleteExpression(LastStore);
1104     // Also check if our value operand is defined by a load of the same memory
1105     // location, and the memory state is the same as it was then (otherwise, it
1106     // could have been overwritten later. See test32 in
1107     // transforms/DeadStoreElimination/simple.ll).
1108     if (auto *LI =
1109             dyn_cast<LoadInst>(lookupOperandLeader(SI->getValueOperand()))) {
1110       if ((lookupOperandLeader(LI->getPointerOperand()) ==
1111            lookupOperandLeader(SI->getPointerOperand())) &&
1112           (lookupMemoryLeader(MSSA->getMemoryAccess(LI)->getDefiningAccess()) ==
1113            StoreRHS))
1114         return createVariableExpression(LI);
1115     }
1116   }
1117
1118   // If the store is not equivalent to anything, value number it as a store that
1119   // produces a unique memory state (instead of using it's MemoryUse, we use
1120   // it's MemoryDef).
1121   return createStoreExpression(SI, StoreAccess);
1122 }
1123
1124 // See if we can extract the value of a loaded pointer from a load, a store, or
1125 // a memory instruction.
1126 const Expression *
1127 NewGVN::performSymbolicLoadCoercion(Type *LoadType, Value *LoadPtr,
1128                                     LoadInst *LI, Instruction *DepInst,
1129                                     MemoryAccess *DefiningAccess) {
1130   assert((!LI || LI->isSimple()) && "Not a simple load");
1131   if (auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1132     // Can't forward from non-atomic to atomic without violating memory model.
1133     // Also don't need to coerce if they are the same type, we will just
1134     // propogate..
1135     if (LI->isAtomic() > DepSI->isAtomic() ||
1136         LoadType == DepSI->getValueOperand()->getType())
1137       return nullptr;
1138     int Offset = analyzeLoadFromClobberingStore(LoadType, LoadPtr, DepSI, DL);
1139     if (Offset >= 0) {
1140       if (auto *C = dyn_cast<Constant>(
1141               lookupOperandLeader(DepSI->getValueOperand()))) {
1142         DEBUG(dbgs() << "Coercing load from store " << *DepSI << " to constant "
1143                      << *C << "\n");
1144         return createConstantExpression(
1145             getConstantStoreValueForLoad(C, Offset, LoadType, DL));
1146       }
1147     }
1148
1149   } else if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1150     // Can't forward from non-atomic to atomic without violating memory model.
1151     if (LI->isAtomic() > DepLI->isAtomic())
1152       return nullptr;
1153     int Offset = analyzeLoadFromClobberingLoad(LoadType, LoadPtr, DepLI, DL);
1154     if (Offset >= 0) {
1155       // We can coerce a constant load into a load
1156       if (auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1157         if (auto *PossibleConstant =
1158                 getConstantLoadValueForLoad(C, Offset, LoadType, DL)) {
1159           DEBUG(dbgs() << "Coercing load from load " << *LI << " to constant "
1160                        << *PossibleConstant << "\n");
1161           return createConstantExpression(PossibleConstant);
1162         }
1163     }
1164
1165   } else if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1166     int Offset = analyzeLoadFromClobberingMemInst(LoadType, LoadPtr, DepMI, DL);
1167     if (Offset >= 0) {
1168       if (auto *PossibleConstant =
1169               getConstantMemInstValueForLoad(DepMI, Offset, LoadType, DL)) {
1170         DEBUG(dbgs() << "Coercing load from meminst " << *DepMI
1171                      << " to constant " << *PossibleConstant << "\n");
1172         return createConstantExpression(PossibleConstant);
1173       }
1174     }
1175   }
1176
1177   // All of the below are only true if the loaded pointer is produced
1178   // by the dependent instruction.
1179   if (LoadPtr != lookupOperandLeader(DepInst) &&
1180       !AA->isMustAlias(LoadPtr, DepInst))
1181     return nullptr;
1182   // If this load really doesn't depend on anything, then we must be loading an
1183   // undef value.  This can happen when loading for a fresh allocation with no
1184   // intervening stores, for example.  Note that this is only true in the case
1185   // that the result of the allocation is pointer equal to the load ptr.
1186   if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1187     return createConstantExpression(UndefValue::get(LoadType));
1188   }
1189   // If this load occurs either right after a lifetime begin,
1190   // then the loaded value is undefined.
1191   else if (auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1192     if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1193       return createConstantExpression(UndefValue::get(LoadType));
1194   }
1195   // If this load follows a calloc (which zero initializes memory),
1196   // then the loaded value is zero
1197   else if (isCallocLikeFn(DepInst, TLI)) {
1198     return createConstantExpression(Constant::getNullValue(LoadType));
1199   }
1200
1201   return nullptr;
1202 }
1203
1204 const Expression *NewGVN::performSymbolicLoadEvaluation(Instruction *I) {
1205   auto *LI = cast<LoadInst>(I);
1206
1207   // We can eliminate in favor of non-simple loads, but we won't be able to
1208   // eliminate the loads themselves.
1209   if (!LI->isSimple())
1210     return nullptr;
1211
1212   Value *LoadAddressLeader = lookupOperandLeader(LI->getPointerOperand());
1213   // Load of undef is undef.
1214   if (isa<UndefValue>(LoadAddressLeader))
1215     return createConstantExpression(UndefValue::get(LI->getType()));
1216
1217   MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(I);
1218
1219   if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1220     if (auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1221       Instruction *DefiningInst = MD->getMemoryInst();
1222       // If the defining instruction is not reachable, replace with undef.
1223       if (!ReachableBlocks.count(DefiningInst->getParent()))
1224         return createConstantExpression(UndefValue::get(LI->getType()));
1225       // This will handle stores and memory insts.  We only do if it the
1226       // defining access has a different type, or it is a pointer produced by
1227       // certain memory operations that cause the memory to have a fixed value
1228       // (IE things like calloc).
1229       if (const auto *CoercionResult =
1230               performSymbolicLoadCoercion(LI->getType(), LoadAddressLeader, LI,
1231                                           DefiningInst, DefiningAccess))
1232         return CoercionResult;
1233     }
1234   }
1235
1236   const Expression *E = createLoadExpression(LI->getType(), LoadAddressLeader,
1237                                              LI, DefiningAccess);
1238   return E;
1239 }
1240
1241 const Expression *
1242 NewGVN::performSymbolicPredicateInfoEvaluation(Instruction *I) {
1243   auto *PI = PredInfo->getPredicateInfoFor(I);
1244   if (!PI)
1245     return nullptr;
1246
1247   DEBUG(dbgs() << "Found predicate info from instruction !\n");
1248
1249   auto *PWC = dyn_cast<PredicateWithCondition>(PI);
1250   if (!PWC)
1251     return nullptr;
1252
1253   auto *CopyOf = I->getOperand(0);
1254   auto *Cond = PWC->Condition;
1255
1256   // If this a copy of the condition, it must be either true or false depending
1257   // on the predicate info type and edge
1258   if (CopyOf == Cond) {
1259     // We should not need to add predicate users because the predicate info is
1260     // already a use of this operand.
1261     if (isa<PredicateAssume>(PI))
1262       return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1263     if (auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1264       if (PBranch->TrueEdge)
1265         return createConstantExpression(ConstantInt::getTrue(Cond->getType()));
1266       return createConstantExpression(ConstantInt::getFalse(Cond->getType()));
1267     }
1268     if (auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1269       return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
1270   }
1271
1272   // Not a copy of the condition, so see what the predicates tell us about this
1273   // value.  First, though, we check to make sure the value is actually a copy
1274   // of one of the condition operands. It's possible, in certain cases, for it
1275   // to be a copy of a predicateinfo copy. In particular, if two branch
1276   // operations use the same condition, and one branch dominates the other, we
1277   // will end up with a copy of a copy.  This is currently a small deficiency in
1278   // predicateinfo.  What will end up happening here is that we will value
1279   // number both copies the same anyway.
1280
1281   // Everything below relies on the condition being a comparison.
1282   auto *Cmp = dyn_cast<CmpInst>(Cond);
1283   if (!Cmp)
1284     return nullptr;
1285
1286   if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
1287     DEBUG(dbgs() << "Copy is not of any condition operands!");
1288     return nullptr;
1289   }
1290   Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1291   Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
1292   bool SwappedOps = false;
1293   // Sort the ops
1294   if (shouldSwapOperands(FirstOp, SecondOp)) {
1295     std::swap(FirstOp, SecondOp);
1296     SwappedOps = true;
1297   }
1298   CmpInst::Predicate Predicate =
1299       SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1300
1301   if (isa<PredicateAssume>(PI)) {
1302     // If the comparison is true when the operands are equal, then we know the
1303     // operands are equal, because assumes must always be true.
1304     if (CmpInst::isTrueWhenEqual(Predicate)) {
1305       addPredicateUsers(PI, I);
1306       return createVariableOrConstant(FirstOp);
1307     }
1308   }
1309   if (const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1310     // If we are *not* a copy of the comparison, we may equal to the other
1311     // operand when the predicate implies something about equality of
1312     // operations.  In particular, if the comparison is true/false when the
1313     // operands are equal, and we are on the right edge, we know this operation
1314     // is equal to something.
1315     if ((PBranch->TrueEdge && Predicate == CmpInst::ICMP_EQ) ||
1316         (!PBranch->TrueEdge && Predicate == CmpInst::ICMP_NE)) {
1317       addPredicateUsers(PI, I);
1318       return createVariableOrConstant(FirstOp);
1319     }
1320     // Handle the special case of floating point.
1321     if (((PBranch->TrueEdge && Predicate == CmpInst::FCMP_OEQ) ||
1322          (!PBranch->TrueEdge && Predicate == CmpInst::FCMP_UNE)) &&
1323         isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1324       addPredicateUsers(PI, I);
1325       return createConstantExpression(cast<Constant>(FirstOp));
1326     }
1327   }
1328   return nullptr;
1329 }
1330
1331 // Evaluate read only and pure calls, and create an expression result.
1332 const Expression *NewGVN::performSymbolicCallEvaluation(Instruction *I) {
1333   auto *CI = cast<CallInst>(I);
1334   if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1335     // Instrinsics with the returned attribute are copies of arguments.
1336     if (auto *ReturnedValue = II->getReturnedArgOperand()) {
1337       if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1338         if (const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1339           return Result;
1340       return createVariableOrConstant(ReturnedValue);
1341     }
1342   }
1343   if (AA->doesNotAccessMemory(CI)) {
1344     return createCallExpression(CI, TOPClass->getMemoryLeader());
1345   } else if (AA->onlyReadsMemory(CI)) {
1346     MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
1347     return createCallExpression(CI, DefiningAccess);
1348   }
1349   return nullptr;
1350 }
1351
1352 // Retrieve the memory class for a given MemoryAccess.
1353 CongruenceClass *NewGVN::getMemoryClass(const MemoryAccess *MA) const {
1354
1355   auto *Result = MemoryAccessToClass.lookup(MA);
1356   assert(Result && "Should have found memory class");
1357   return Result;
1358 }
1359
1360 // Update the MemoryAccess equivalence table to say that From is equal to To,
1361 // and return true if this is different from what already existed in the table.
1362 bool NewGVN::setMemoryClass(const MemoryAccess *From,
1363                             CongruenceClass *NewClass) {
1364   assert(NewClass &&
1365          "Every MemoryAccess should be getting mapped to a non-null class");
1366   DEBUG(dbgs() << "Setting " << *From);
1367   DEBUG(dbgs() << " equivalent to congruence class ");
1368   DEBUG(dbgs() << NewClass->getID() << " with current MemoryAccess leader ");
1369   DEBUG(dbgs() << *NewClass->getMemoryLeader());
1370   DEBUG(dbgs() << "\n");
1371
1372   auto LookupResult = MemoryAccessToClass.find(From);
1373   bool Changed = false;
1374   // If it's already in the table, see if the value changed.
1375   if (LookupResult != MemoryAccessToClass.end()) {
1376     auto *OldClass = LookupResult->second;
1377     if (OldClass != NewClass) {
1378       // If this is a phi, we have to handle memory member updates.
1379       if (auto *MP = dyn_cast<MemoryPhi>(From)) {
1380         OldClass->memory_erase(MP);
1381         NewClass->memory_insert(MP);
1382         // This may have killed the class if it had no non-memory members
1383         if (OldClass->getMemoryLeader() == From) {
1384           if (OldClass->memory_empty()) {
1385             OldClass->setMemoryLeader(nullptr);
1386           } else {
1387             OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
1388             DEBUG(dbgs() << "Memory class leader change for class "
1389                          << OldClass->getID() << " to "
1390                          << *OldClass->getMemoryLeader()
1391                          << " due to removal of a memory member " << *From
1392                          << "\n");
1393             markMemoryLeaderChangeTouched(OldClass);
1394           }
1395         }
1396       }
1397       // It wasn't equivalent before, and now it is.
1398       LookupResult->second = NewClass;
1399       Changed = true;
1400     }
1401   }
1402
1403   return Changed;
1404 }
1405
1406 // Determine if a phi is cycle-free.  That means the values in the phi don't
1407 // depend on any expressions that can change value as a result of the phi.
1408 // For example, a non-cycle free phi would be  v = phi(0, v+1).
1409 bool NewGVN::isCycleFree(const PHINode *PN) {
1410   // In order to compute cycle-freeness, we do SCC finding on the phi, and see
1411   // what kind of SCC it ends up in.  If it is a singleton, it is cycle-free.
1412   // If it is not in a singleton, it is only cycle free if the other members are
1413   // all phi nodes (as they do not compute anything, they are copies).  TODO:
1414   // There are likely a few other intrinsics or expressions that could be
1415   // included here, but this happens so infrequently already that it is not
1416   // likely to be worth it.
1417   auto PCS = PhiCycleState.lookup(PN);
1418   if (PCS == PCS_Unknown) {
1419     SCCFinder.Start(PN);
1420     auto &SCC = SCCFinder.getComponentFor(PN);
1421     // It's cycle free if it's size 1 or or the SCC is *only* phi nodes.
1422     if (SCC.size() == 1)
1423       PhiCycleState.insert({PN, PCS_CycleFree});
1424     else {
1425       bool AllPhis =
1426           llvm::all_of(SCC, [](const Value *V) { return isa<PHINode>(V); });
1427       PCS = AllPhis ? PCS_CycleFree : PCS_Cycle;
1428       for (auto *Member : SCC)
1429         if (auto *MemberPhi = dyn_cast<PHINode>(Member))
1430           PhiCycleState.insert({MemberPhi, PCS});
1431     }
1432   }
1433   if (PCS == PCS_Cycle)
1434     return false;
1435   return true;
1436 }
1437
1438 // Evaluate PHI nodes symbolically, and create an expression result.
1439 const Expression *NewGVN::performSymbolicPHIEvaluation(Instruction *I) {
1440   // True if one of the incoming phi edges is a backedge.
1441   bool HasBackedge = false;
1442   // All constant tracks the state of whether all the *original* phi operands
1443   // were constant. This is really shorthand for "this phi cannot cycle due
1444   // to forward propagation", as any change in value of the phi is guaranteed
1445   // not to later change the value of the phi.
1446   // IE it can't be v = phi(undef, v+1)
1447   bool AllConstant = true;
1448   auto *E =
1449       cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
1450   // We match the semantics of SimplifyPhiNode from InstructionSimplify here.
1451   // See if all arguments are the same.
1452   // We track if any were undef because they need special handling.
1453   bool HasUndef = false;
1454   auto Filtered = make_filter_range(E->operands(), [&](const Value *Arg) {
1455     if (Arg == I)
1456       return false;
1457     if (isa<UndefValue>(Arg)) {
1458       HasUndef = true;
1459       return false;
1460     }
1461     return true;
1462   });
1463   // If we are left with no operands, it's undef
1464   if (Filtered.begin() == Filtered.end()) {
1465     DEBUG(dbgs() << "Simplified PHI node " << *I << " to undef"
1466                  << "\n");
1467     deleteExpression(E);
1468     return createConstantExpression(UndefValue::get(I->getType()));
1469   }
1470   unsigned NumOps = 0;
1471   Value *AllSameValue = *(Filtered.begin());
1472   ++Filtered.begin();
1473   // Can't use std::equal here, sadly, because filter.begin moves.
1474   if (llvm::all_of(Filtered, [AllSameValue, &NumOps](const Value *V) {
1475         ++NumOps;
1476         return V == AllSameValue;
1477       })) {
1478     // In LLVM's non-standard representation of phi nodes, it's possible to have
1479     // phi nodes with cycles (IE dependent on other phis that are .... dependent
1480     // on the original phi node), especially in weird CFG's where some arguments
1481     // are unreachable, or uninitialized along certain paths.  This can cause
1482     // infinite loops during evaluation. We work around this by not trying to
1483     // really evaluate them independently, but instead using a variable
1484     // expression to say if one is equivalent to the other.
1485     // We also special case undef, so that if we have an undef, we can't use the
1486     // common value unless it dominates the phi block.
1487     if (HasUndef) {
1488       // If we have undef and at least one other value, this is really a
1489       // multivalued phi, and we need to know if it's cycle free in order to
1490       // evaluate whether we can ignore the undef.  The other parts of this are
1491       // just shortcuts.  If there is no backedge, or all operands are
1492       // constants, or all operands are ignored but the undef, it also must be
1493       // cycle free.
1494       if (!AllConstant && HasBackedge && NumOps > 0 &&
1495           !isa<UndefValue>(AllSameValue) && !isCycleFree(cast<PHINode>(I)))
1496         return E;
1497
1498       // Only have to check for instructions
1499       if (auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
1500         if (!someEquivalentDominates(AllSameInst, I))
1501           return E;
1502     }
1503
1504     NumGVNPhisAllSame++;
1505     DEBUG(dbgs() << "Simplified PHI node " << *I << " to " << *AllSameValue
1506                  << "\n");
1507     deleteExpression(E);
1508     return createVariableOrConstant(AllSameValue);
1509   }
1510   return E;
1511 }
1512
1513 const Expression *NewGVN::performSymbolicAggrValueEvaluation(Instruction *I) {
1514   if (auto *EI = dyn_cast<ExtractValueInst>(I)) {
1515     auto *II = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
1516     if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1517       unsigned Opcode = 0;
1518       // EI might be an extract from one of our recognised intrinsics. If it
1519       // is we'll synthesize a semantically equivalent expression instead on
1520       // an extract value expression.
1521       switch (II->getIntrinsicID()) {
1522       case Intrinsic::sadd_with_overflow:
1523       case Intrinsic::uadd_with_overflow:
1524         Opcode = Instruction::Add;
1525         break;
1526       case Intrinsic::ssub_with_overflow:
1527       case Intrinsic::usub_with_overflow:
1528         Opcode = Instruction::Sub;
1529         break;
1530       case Intrinsic::smul_with_overflow:
1531       case Intrinsic::umul_with_overflow:
1532         Opcode = Instruction::Mul;
1533         break;
1534       default:
1535         break;
1536       }
1537
1538       if (Opcode != 0) {
1539         // Intrinsic recognized. Grab its args to finish building the
1540         // expression.
1541         assert(II->getNumArgOperands() == 2 &&
1542                "Expect two args for recognised intrinsics.");
1543         return createBinaryExpression(
1544             Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
1545       }
1546     }
1547   }
1548
1549   return createAggregateValueExpression(I);
1550 }
1551 const Expression *NewGVN::performSymbolicCmpEvaluation(Instruction *I) {
1552   auto *CI = dyn_cast<CmpInst>(I);
1553   // See if our operands are equal to those of a previous predicate, and if so,
1554   // if it implies true or false.
1555   auto Op0 = lookupOperandLeader(CI->getOperand(0));
1556   auto Op1 = lookupOperandLeader(CI->getOperand(1));
1557   auto OurPredicate = CI->getPredicate();
1558   if (shouldSwapOperands(Op0, Op1)) {
1559     std::swap(Op0, Op1);
1560     OurPredicate = CI->getSwappedPredicate();
1561   }
1562
1563   // Avoid processing the same info twice
1564   const PredicateBase *LastPredInfo = nullptr;
1565   // See if we know something about the comparison itself, like it is the target
1566   // of an assume.
1567   auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1568   if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1569     return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1570
1571   if (Op0 == Op1) {
1572     // This condition does not depend on predicates, no need to add users
1573     if (CI->isTrueWhenEqual())
1574       return createConstantExpression(ConstantInt::getTrue(CI->getType()));
1575     else if (CI->isFalseWhenEqual())
1576       return createConstantExpression(ConstantInt::getFalse(CI->getType()));
1577   }
1578
1579   // NOTE: Because we are comparing both operands here and below, and using
1580   // previous comparisons, we rely on fact that predicateinfo knows to mark
1581   // comparisons that use renamed operands as users of the earlier comparisons.
1582   // It is *not* enough to just mark predicateinfo renamed operands as users of
1583   // the earlier comparisons, because the *other* operand may have changed in a
1584   // previous iteration.
1585   // Example:
1586   // icmp slt %a, %b
1587   // %b.0 = ssa.copy(%b)
1588   // false branch:
1589   // icmp slt %c, %b.0
1590
1591   // %c and %a may start out equal, and thus, the code below will say the second
1592   // %icmp is false.  c may become equal to something else, and in that case the
1593   // %second icmp *must* be reexamined, but would not if only the renamed
1594   // %operands are considered users of the icmp.
1595
1596   // *Currently* we only check one level of comparisons back, and only mark one
1597   // level back as touched when changes appen .  If you modify this code to look
1598   // back farther through comparisons, you *must* mark the appropriate
1599   // comparisons as users in PredicateInfo.cpp, or you will cause bugs.  See if
1600   // we know something just from the operands themselves
1601
1602   // See if our operands have predicate info, so that we may be able to derive
1603   // something from a previous comparison.
1604   for (const auto &Op : CI->operands()) {
1605     auto *PI = PredInfo->getPredicateInfoFor(Op);
1606     if (const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1607       if (PI == LastPredInfo)
1608         continue;
1609       LastPredInfo = PI;
1610
1611       // TODO: Along the false edge, we may know more things too, like icmp of
1612       // same operands is false.
1613       // TODO: We only handle actual comparison conditions below, not and/or.
1614       auto *BranchCond = dyn_cast<CmpInst>(PBranch->Condition);
1615       if (!BranchCond)
1616         continue;
1617       auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1618       auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1619       auto BranchPredicate = BranchCond->getPredicate();
1620       if (shouldSwapOperands(BranchOp0, BranchOp1)) {
1621         std::swap(BranchOp0, BranchOp1);
1622         BranchPredicate = BranchCond->getSwappedPredicate();
1623       }
1624       if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1625         if (PBranch->TrueEdge) {
1626           // If we know the previous predicate is true and we are in the true
1627           // edge then we may be implied true or false.
1628           if (CmpInst::isImpliedTrueByMatchingCmp(BranchPredicate,
1629                                                   OurPredicate)) {
1630             addPredicateUsers(PI, I);
1631             return createConstantExpression(
1632                 ConstantInt::getTrue(CI->getType()));
1633           }
1634
1635           if (CmpInst::isImpliedFalseByMatchingCmp(BranchPredicate,
1636                                                    OurPredicate)) {
1637             addPredicateUsers(PI, I);
1638             return createConstantExpression(
1639                 ConstantInt::getFalse(CI->getType()));
1640           }
1641
1642         } else {
1643           // Just handle the ne and eq cases, where if we have the same
1644           // operands, we may know something.
1645           if (BranchPredicate == OurPredicate) {
1646             addPredicateUsers(PI, I);
1647             // Same predicate, same ops,we know it was false, so this is false.
1648             return createConstantExpression(
1649                 ConstantInt::getFalse(CI->getType()));
1650           } else if (BranchPredicate ==
1651                      CmpInst::getInversePredicate(OurPredicate)) {
1652             addPredicateUsers(PI, I);
1653             // Inverse predicate, we know the other was false, so this is true.
1654             return createConstantExpression(
1655                 ConstantInt::getTrue(CI->getType()));
1656           }
1657         }
1658       }
1659     }
1660   }
1661   // Create expression will take care of simplifyCmpInst
1662   return createExpression(I);
1663 }
1664
1665 // Substitute and symbolize the value before value numbering.
1666 const Expression *NewGVN::performSymbolicEvaluation(Value *V) {
1667   const Expression *E = nullptr;
1668   if (auto *C = dyn_cast<Constant>(V))
1669     E = createConstantExpression(C);
1670   else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1671     E = createVariableExpression(V);
1672   } else {
1673     // TODO: memory intrinsics.
1674     // TODO: Some day, we should do the forward propagation and reassociation
1675     // parts of the algorithm.
1676     auto *I = cast<Instruction>(V);
1677     switch (I->getOpcode()) {
1678     case Instruction::ExtractValue:
1679     case Instruction::InsertValue:
1680       E = performSymbolicAggrValueEvaluation(I);
1681       break;
1682     case Instruction::PHI:
1683       E = performSymbolicPHIEvaluation(I);
1684       break;
1685     case Instruction::Call:
1686       E = performSymbolicCallEvaluation(I);
1687       break;
1688     case Instruction::Store:
1689       E = performSymbolicStoreEvaluation(I);
1690       break;
1691     case Instruction::Load:
1692       E = performSymbolicLoadEvaluation(I);
1693       break;
1694     case Instruction::BitCast: {
1695       E = createExpression(I);
1696     } break;
1697     case Instruction::ICmp:
1698     case Instruction::FCmp: {
1699       E = performSymbolicCmpEvaluation(I);
1700     } break;
1701     case Instruction::Add:
1702     case Instruction::FAdd:
1703     case Instruction::Sub:
1704     case Instruction::FSub:
1705     case Instruction::Mul:
1706     case Instruction::FMul:
1707     case Instruction::UDiv:
1708     case Instruction::SDiv:
1709     case Instruction::FDiv:
1710     case Instruction::URem:
1711     case Instruction::SRem:
1712     case Instruction::FRem:
1713     case Instruction::Shl:
1714     case Instruction::LShr:
1715     case Instruction::AShr:
1716     case Instruction::And:
1717     case Instruction::Or:
1718     case Instruction::Xor:
1719     case Instruction::Trunc:
1720     case Instruction::ZExt:
1721     case Instruction::SExt:
1722     case Instruction::FPToUI:
1723     case Instruction::FPToSI:
1724     case Instruction::UIToFP:
1725     case Instruction::SIToFP:
1726     case Instruction::FPTrunc:
1727     case Instruction::FPExt:
1728     case Instruction::PtrToInt:
1729     case Instruction::IntToPtr:
1730     case Instruction::Select:
1731     case Instruction::ExtractElement:
1732     case Instruction::InsertElement:
1733     case Instruction::ShuffleVector:
1734     case Instruction::GetElementPtr:
1735       E = createExpression(I);
1736       break;
1737     default:
1738       return nullptr;
1739     }
1740   }
1741   return E;
1742 }
1743
1744 void NewGVN::markUsersTouched(Value *V) {
1745   // Now mark the users as touched.
1746   for (auto *User : V->users()) {
1747     assert(isa<Instruction>(User) && "Use of value not within an instruction?");
1748     TouchedInstructions.set(InstrToDFSNum(User));
1749   }
1750 }
1751
1752 void NewGVN::addMemoryUsers(const MemoryAccess *To, MemoryAccess *U) {
1753   DEBUG(dbgs() << "Adding memory user " << *U << " to " << *To << "\n");
1754   MemoryToUsers[To].insert(U);
1755 }
1756
1757 void NewGVN::markMemoryDefTouched(const MemoryAccess *MA) {
1758   TouchedInstructions.set(MemoryToDFSNum(MA));
1759 }
1760
1761 void NewGVN::markMemoryUsersTouched(const MemoryAccess *MA) {
1762   if (isa<MemoryUse>(MA))
1763     return;
1764   for (auto U : MA->users())
1765     TouchedInstructions.set(MemoryToDFSNum(U));
1766   const auto Result = MemoryToUsers.find(MA);
1767   if (Result != MemoryToUsers.end()) {
1768     for (auto *User : Result->second)
1769       TouchedInstructions.set(MemoryToDFSNum(User));
1770     MemoryToUsers.erase(Result);
1771   }
1772 }
1773
1774 // Add I to the set of users of a given predicate.
1775 void NewGVN::addPredicateUsers(const PredicateBase *PB, Instruction *I) {
1776   if (auto *PBranch = dyn_cast<PredicateBranch>(PB))
1777     PredicateToUsers[PBranch->Condition].insert(I);
1778   else if (auto *PAssume = dyn_cast<PredicateBranch>(PB))
1779     PredicateToUsers[PAssume->Condition].insert(I);
1780 }
1781
1782 // Touch all the predicates that depend on this instruction.
1783 void NewGVN::markPredicateUsersTouched(Instruction *I) {
1784   const auto Result = PredicateToUsers.find(I);
1785   if (Result != PredicateToUsers.end()) {
1786     for (auto *User : Result->second)
1787       TouchedInstructions.set(InstrToDFSNum(User));
1788     PredicateToUsers.erase(Result);
1789   }
1790 }
1791
1792 // Mark users affected by a memory leader change.
1793 void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
1794   for (auto M : CC->memory())
1795     markMemoryDefTouched(M);
1796 }
1797
1798 // Touch the instructions that need to be updated after a congruence class has a
1799 // leader change, and mark changed values.
1800 void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
1801   for (auto M : *CC) {
1802     if (auto *I = dyn_cast<Instruction>(M))
1803       TouchedInstructions.set(InstrToDFSNum(I));
1804     LeaderChanges.insert(M);
1805   }
1806 }
1807
1808 // Give a range of things that have instruction DFS numbers, this will return
1809 // the member of the range with the smallest dfs number.
1810 template <class T, class Range>
1811 T *NewGVN::getMinDFSOfRange(const Range &R) const {
1812   std::pair<T *, unsigned> MinDFS = {nullptr, ~0U};
1813   for (const auto X : R) {
1814     auto DFSNum = InstrToDFSNum(X);
1815     if (DFSNum < MinDFS.second)
1816       MinDFS = {X, DFSNum};
1817   }
1818   return MinDFS.first;
1819 }
1820
1821 // This function returns the MemoryAccess that should be the next leader of
1822 // congruence class CC, under the assumption that the current leader is going to
1823 // disappear.
1824 const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC) const {
1825   // TODO: If this ends up to slow, we can maintain a next memory leader like we
1826   // do for regular leaders.
1827   // Make sure there will be a leader to find
1828   assert((CC->getStoreCount() > 0 || !CC->memory_empty()) &&
1829          "Can't get next leader if there is none");
1830   if (CC->getStoreCount() > 0) {
1831     if (auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
1832       return MSSA->getMemoryAccess(NL);
1833     // Find the store with the minimum DFS number.
1834     auto *V = getMinDFSOfRange<Value>(make_filter_range(
1835         *CC, [&](const Value *V) { return isa<StoreInst>(V); }));
1836     return MSSA->getMemoryAccess(cast<StoreInst>(V));
1837   }
1838   assert(CC->getStoreCount() == 0);
1839
1840   // Given our assertion, hitting this part must mean
1841   // !OldClass->memory_empty()
1842   if (CC->memory_size() == 1)
1843     return *CC->memory_begin();
1844   return getMinDFSOfRange<const MemoryPhi>(CC->memory());
1845 }
1846
1847 // This function returns the next value leader of a congruence class, under the
1848 // assumption that the current leader is going away.  This should end up being
1849 // the next most dominating member.
1850 Value *NewGVN::getNextValueLeader(CongruenceClass *CC) const {
1851   // We don't need to sort members if there is only 1, and we don't care about
1852   // sorting the TOP class because everything either gets out of it or is
1853   // unreachable.
1854
1855   if (CC->size() == 1 || CC == TOPClass) {
1856     return *(CC->begin());
1857   } else if (CC->getNextLeader().first) {
1858     ++NumGVNAvoidedSortedLeaderChanges;
1859     return CC->getNextLeader().first;
1860   } else {
1861     ++NumGVNSortedLeaderChanges;
1862     // NOTE: If this ends up to slow, we can maintain a dual structure for
1863     // member testing/insertion, or keep things mostly sorted, and sort only
1864     // here, or use SparseBitVector or ....
1865     return getMinDFSOfRange<Value>(*CC);
1866   }
1867 }
1868
1869 // Move a MemoryAccess, currently in OldClass, to NewClass, including updates to
1870 // the memory members, etc for the move.
1871 //
1872 // The invariants of this function are:
1873 //
1874 // I must be moving to NewClass from OldClass The StoreCount of OldClass and
1875 // NewClass is expected to have been updated for I already if it is is a store.
1876 // The OldClass memory leader has not been updated yet if I was the leader.
1877 void NewGVN::moveMemoryToNewCongruenceClass(Instruction *I,
1878                                             MemoryAccess *InstMA,
1879                                             CongruenceClass *OldClass,
1880                                             CongruenceClass *NewClass) {
1881   // If the leader is I, and we had a represenative MemoryAccess, it should
1882   // be the MemoryAccess of OldClass.
1883   assert((!InstMA || !OldClass->getMemoryLeader() ||
1884           OldClass->getLeader() != I ||
1885           OldClass->getMemoryLeader() == InstMA) &&
1886          "Representative MemoryAccess mismatch");
1887   // First, see what happens to the new class
1888   if (!NewClass->getMemoryLeader()) {
1889     // Should be a new class, or a store becoming a leader of a new class.
1890     assert(NewClass->size() == 1 ||
1891            (isa<StoreInst>(I) && NewClass->getStoreCount() == 1));
1892     NewClass->setMemoryLeader(InstMA);
1893     // Mark it touched if we didn't just create a singleton
1894     DEBUG(dbgs() << "Memory class leader change for class " << NewClass->getID()
1895                  << " due to new memory instruction becoming leader\n");
1896     markMemoryLeaderChangeTouched(NewClass);
1897   }
1898   setMemoryClass(InstMA, NewClass);
1899   // Now, fixup the old class if necessary
1900   if (OldClass->getMemoryLeader() == InstMA) {
1901     if (OldClass->getStoreCount() != 0 || !OldClass->memory_empty()) {
1902       OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
1903       DEBUG(dbgs() << "Memory class leader change for class "
1904                    << OldClass->getID() << " to "
1905                    << *OldClass->getMemoryLeader()
1906                    << " due to removal of old leader " << *InstMA << "\n");
1907       markMemoryLeaderChangeTouched(OldClass);
1908     } else
1909       OldClass->setMemoryLeader(nullptr);
1910   }
1911 }
1912
1913 // Move a value, currently in OldClass, to be part of NewClass
1914 // Update OldClass and NewClass for the move (including changing leaders, etc).
1915 void NewGVN::moveValueToNewCongruenceClass(Instruction *I, const Expression *E,
1916                                            CongruenceClass *OldClass,
1917                                            CongruenceClass *NewClass) {
1918   if (I == OldClass->getNextLeader().first)
1919     OldClass->resetNextLeader();
1920
1921   // It's possible, though unlikely, for us to discover equivalences such
1922   // that the current leader does not dominate the old one.
1923   // This statistic tracks how often this happens.
1924   // We assert on phi nodes when this happens, currently, for debugging, because
1925   // we want to make sure we name phi node cycles properly.
1926   if (isa<Instruction>(NewClass->getLeader()) && NewClass->getLeader() &&
1927       I != NewClass->getLeader()) {
1928     auto *IBB = I->getParent();
1929     auto *NCBB = cast<Instruction>(NewClass->getLeader())->getParent();
1930     bool Dominated =
1931         IBB == NCBB && InstrToDFSNum(I) < InstrToDFSNum(NewClass->getLeader());
1932     Dominated = Dominated || DT->properlyDominates(IBB, NCBB);
1933     if (Dominated) {
1934       ++NumGVNNotMostDominatingLeader;
1935       assert(
1936           !isa<PHINode>(I) &&
1937           "New class for instruction should not be dominated by instruction");
1938     }
1939   }
1940
1941   if (NewClass->getLeader() != I)
1942     NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
1943
1944   OldClass->erase(I);
1945   NewClass->insert(I);
1946   // Handle our special casing of stores.
1947   if (auto *SI = dyn_cast<StoreInst>(I)) {
1948     OldClass->decStoreCount();
1949     // Okay, so when do we want to make a store a leader of a class?
1950     // If we have a store defined by an earlier load, we want the earlier load
1951     // to lead the class.
1952     // If we have a store defined by something else, we want the store to lead
1953     // the class so everything else gets the "something else" as a value.
1954     // If we have a store as the single member of the class, we want the store
1955     // as the leader
1956     if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
1957       // If it's a store expression we are using, it means we are not equivalent
1958       // to something earlier.
1959       if (isa<StoreExpression>(E)) {
1960         assert(lookupOperandLeader(SI->getValueOperand()) !=
1961                NewClass->getLeader());
1962         NewClass->setStoredValue(lookupOperandLeader(SI->getValueOperand()));
1963         markValueLeaderChangeTouched(NewClass);
1964         // Shift the new class leader to be the store
1965         DEBUG(dbgs() << "Changing leader of congruence class "
1966                      << NewClass->getID() << " from " << *NewClass->getLeader()
1967                      << " to  " << *SI << " because store joined class\n");
1968         // If we changed the leader, we have to mark it changed because we don't
1969         // know what it will do to symbolic evlauation.
1970         NewClass->setLeader(SI);
1971       }
1972       // We rely on the code below handling the MemoryAccess change.
1973     }
1974     NewClass->incStoreCount();
1975   }
1976   // True if there is no memory instructions left in a class that had memory
1977   // instructions before.
1978
1979   // If it's not a memory use, set the MemoryAccess equivalence
1980   auto *InstMA = dyn_cast_or_null<MemoryDef>(MSSA->getMemoryAccess(I));
1981   bool InstWasMemoryLeader = InstMA && OldClass->getMemoryLeader() == InstMA;
1982   if (InstMA)
1983     moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
1984   ValueToClass[I] = NewClass;
1985   // See if we destroyed the class or need to swap leaders.
1986   if (OldClass->empty() && OldClass != TOPClass) {
1987     if (OldClass->getDefiningExpr()) {
1988       DEBUG(dbgs() << "Erasing expression " << OldClass->getDefiningExpr()
1989                    << " from table\n");
1990       ExpressionToClass.erase(OldClass->getDefiningExpr());
1991     }
1992   } else if (OldClass->getLeader() == I) {
1993     // When the leader changes, the value numbering of
1994     // everything may change due to symbolization changes, so we need to
1995     // reprocess.
1996     DEBUG(dbgs() << "Value class leader change for class " << OldClass->getID()
1997                  << "\n");
1998     ++NumGVNLeaderChanges;
1999     // Destroy the stored value if there are no more stores to represent it.
2000     // Note that this is basically clean up for the expression removal that
2001     // happens below.  If we remove stores from a class, we may leave it as a
2002     // class of equivalent memory phis.
2003     if (OldClass->getStoreCount() == 0) {
2004       if (OldClass->getStoredValue())
2005         OldClass->setStoredValue(nullptr);
2006     }
2007     // If we destroy the old access leader and it's a store, we have to
2008     // effectively destroy the congruence class.  When it comes to scalars,
2009     // anything with the same value is as good as any other.  That means that
2010     // one leader is as good as another, and as long as you have some leader for
2011     // the value, you are good.. When it comes to *memory states*, only one
2012     // particular thing really represents the definition of a given memory
2013     // state.  Once it goes away, we need to re-evaluate which pieces of memory
2014     // are really still equivalent. The best way to do this is to re-value
2015     // number things.  The only way to really make that happen is to destroy the
2016     // rest of the class.  In order to effectively destroy the class, we reset
2017     // ExpressionToClass for each by using the ValueToExpression mapping.  The
2018     // members later get marked as touched due to the leader change.  We will
2019     // create new congruence classes, and the pieces that are still equivalent
2020     // will end back together in a new class.  If this becomes too expensive, it
2021     // is possible to use a versioning scheme for the congruence classes to
2022     // avoid the expressions finding this old class.  Note that the situation is
2023     // different for memory phis, becuase they are evaluated anew each time, and
2024     // they become equal not by hashing, but by seeing if all operands are the
2025     // same (or only one is reachable).
2026     if (OldClass->getStoreCount() > 0 && InstWasMemoryLeader) {
2027       DEBUG(dbgs() << "Kicking everything out of class " << OldClass->getID()
2028                    << " because MemoryAccess leader changed");
2029       for (auto Member : *OldClass)
2030         ExpressionToClass.erase(ValueToExpression.lookup(Member));
2031     }
2032     OldClass->setLeader(getNextValueLeader(OldClass));
2033     OldClass->resetNextLeader();
2034     markValueLeaderChangeTouched(OldClass);
2035   }
2036 }
2037
2038 // Perform congruence finding on a given value numbering expression.
2039 void NewGVN::performCongruenceFinding(Instruction *I, const Expression *E) {
2040   ValueToExpression[I] = E;
2041   // This is guaranteed to return something, since it will at least find
2042   // TOP.
2043
2044   CongruenceClass *IClass = ValueToClass[I];
2045   assert(IClass && "Should have found a IClass");
2046   // Dead classes should have been eliminated from the mapping.
2047   assert(!IClass->isDead() && "Found a dead class");
2048
2049   CongruenceClass *EClass;
2050   if (const auto *VE = dyn_cast<VariableExpression>(E)) {
2051     EClass = ValueToClass[VE->getVariableValue()];
2052   } else {
2053     auto lookupResult = ExpressionToClass.insert({E, nullptr});
2054
2055     // If it's not in the value table, create a new congruence class.
2056     if (lookupResult.second) {
2057       CongruenceClass *NewClass = createCongruenceClass(nullptr, E);
2058       auto place = lookupResult.first;
2059       place->second = NewClass;
2060
2061       // Constants and variables should always be made the leader.
2062       if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2063         NewClass->setLeader(CE->getConstantValue());
2064       } else if (const auto *SE = dyn_cast<StoreExpression>(E)) {
2065         StoreInst *SI = SE->getStoreInst();
2066         NewClass->setLeader(SI);
2067         NewClass->setStoredValue(lookupOperandLeader(SI->getValueOperand()));
2068         // The RepMemoryAccess field will be filled in properly by the
2069         // moveValueToNewCongruenceClass call.
2070       } else {
2071         NewClass->setLeader(I);
2072       }
2073       assert(!isa<VariableExpression>(E) &&
2074              "VariableExpression should have been handled already");
2075
2076       EClass = NewClass;
2077       DEBUG(dbgs() << "Created new congruence class for " << *I
2078                    << " using expression " << *E << " at " << NewClass->getID()
2079                    << " and leader " << *(NewClass->getLeader()));
2080       if (NewClass->getStoredValue())
2081         DEBUG(dbgs() << " and stored value " << *(NewClass->getStoredValue()));
2082       DEBUG(dbgs() << "\n");
2083     } else {
2084       EClass = lookupResult.first->second;
2085       if (isa<ConstantExpression>(E))
2086         assert((isa<Constant>(EClass->getLeader()) ||
2087                 (EClass->getStoredValue() &&
2088                  isa<Constant>(EClass->getStoredValue()))) &&
2089                "Any class with a constant expression should have a "
2090                "constant leader");
2091
2092       assert(EClass && "Somehow don't have an eclass");
2093
2094       assert(!EClass->isDead() && "We accidentally looked up a dead class");
2095     }
2096   }
2097   bool ClassChanged = IClass != EClass;
2098   bool LeaderChanged = LeaderChanges.erase(I);
2099   if (ClassChanged || LeaderChanged) {
2100     DEBUG(dbgs() << "New class " << EClass->getID() << " for expression " << *E
2101                  << "\n");
2102     if (ClassChanged)
2103       moveValueToNewCongruenceClass(I, E, IClass, EClass);
2104     markUsersTouched(I);
2105     if (MemoryAccess *MA = MSSA->getMemoryAccess(I))
2106       markMemoryUsersTouched(MA);
2107     if (auto *CI = dyn_cast<CmpInst>(I))
2108       markPredicateUsersTouched(CI);
2109   }
2110 }
2111
2112 // Process the fact that Edge (from, to) is reachable, including marking
2113 // any newly reachable blocks and instructions for processing.
2114 void NewGVN::updateReachableEdge(BasicBlock *From, BasicBlock *To) {
2115   // Check if the Edge was reachable before.
2116   if (ReachableEdges.insert({From, To}).second) {
2117     // If this block wasn't reachable before, all instructions are touched.
2118     if (ReachableBlocks.insert(To).second) {
2119       DEBUG(dbgs() << "Block " << getBlockName(To) << " marked reachable\n");
2120       const auto &InstRange = BlockInstRange.lookup(To);
2121       TouchedInstructions.set(InstRange.first, InstRange.second);
2122     } else {
2123       DEBUG(dbgs() << "Block " << getBlockName(To)
2124                    << " was reachable, but new edge {" << getBlockName(From)
2125                    << "," << getBlockName(To) << "} to it found\n");
2126
2127       // We've made an edge reachable to an existing block, which may
2128       // impact predicates. Otherwise, only mark the phi nodes as touched, as
2129       // they are the only thing that depend on new edges. Anything using their
2130       // values will get propagated to if necessary.
2131       if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(To))
2132         TouchedInstructions.set(InstrToDFSNum(MemPhi));
2133
2134       auto BI = To->begin();
2135       while (isa<PHINode>(BI)) {
2136         TouchedInstructions.set(InstrToDFSNum(&*BI));
2137         ++BI;
2138       }
2139     }
2140   }
2141 }
2142
2143 // Given a predicate condition (from a switch, cmp, or whatever) and a block,
2144 // see if we know some constant value for it already.
2145 Value *NewGVN::findConditionEquivalence(Value *Cond) const {
2146   auto Result = lookupOperandLeader(Cond);
2147   if (isa<Constant>(Result))
2148     return Result;
2149   return nullptr;
2150 }
2151
2152 // Process the outgoing edges of a block for reachability.
2153 void NewGVN::processOutgoingEdges(TerminatorInst *TI, BasicBlock *B) {
2154   // Evaluate reachability of terminator instruction.
2155   BranchInst *BR;
2156   if ((BR = dyn_cast<BranchInst>(TI)) && BR->isConditional()) {
2157     Value *Cond = BR->getCondition();
2158     Value *CondEvaluated = findConditionEquivalence(Cond);
2159     if (!CondEvaluated) {
2160       if (auto *I = dyn_cast<Instruction>(Cond)) {
2161         const Expression *E = createExpression(I);
2162         if (const auto *CE = dyn_cast<ConstantExpression>(E)) {
2163           CondEvaluated = CE->getConstantValue();
2164         }
2165       } else if (isa<ConstantInt>(Cond)) {
2166         CondEvaluated = Cond;
2167       }
2168     }
2169     ConstantInt *CI;
2170     BasicBlock *TrueSucc = BR->getSuccessor(0);
2171     BasicBlock *FalseSucc = BR->getSuccessor(1);
2172     if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2173       if (CI->isOne()) {
2174         DEBUG(dbgs() << "Condition for Terminator " << *TI
2175                      << " evaluated to true\n");
2176         updateReachableEdge(B, TrueSucc);
2177       } else if (CI->isZero()) {
2178         DEBUG(dbgs() << "Condition for Terminator " << *TI
2179                      << " evaluated to false\n");
2180         updateReachableEdge(B, FalseSucc);
2181       }
2182     } else {
2183       updateReachableEdge(B, TrueSucc);
2184       updateReachableEdge(B, FalseSucc);
2185     }
2186   } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
2187     // For switches, propagate the case values into the case
2188     // destinations.
2189
2190     // Remember how many outgoing edges there are to every successor.
2191     SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2192
2193     Value *SwitchCond = SI->getCondition();
2194     Value *CondEvaluated = findConditionEquivalence(SwitchCond);
2195     // See if we were able to turn this switch statement into a constant.
2196     if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
2197       auto *CondVal = cast<ConstantInt>(CondEvaluated);
2198       // We should be able to get case value for this.
2199       auto Case = *SI->findCaseValue(CondVal);
2200       if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
2201         // We proved the value is outside of the range of the case.
2202         // We can't do anything other than mark the default dest as reachable,
2203         // and go home.
2204         updateReachableEdge(B, SI->getDefaultDest());
2205         return;
2206       }
2207       // Now get where it goes and mark it reachable.
2208       BasicBlock *TargetBlock = Case.getCaseSuccessor();
2209       updateReachableEdge(B, TargetBlock);
2210     } else {
2211       for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2212         BasicBlock *TargetBlock = SI->getSuccessor(i);
2213         ++SwitchEdges[TargetBlock];
2214         updateReachableEdge(B, TargetBlock);
2215       }
2216     }
2217   } else {
2218     // Otherwise this is either unconditional, or a type we have no
2219     // idea about. Just mark successors as reachable.
2220     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2221       BasicBlock *TargetBlock = TI->getSuccessor(i);
2222       updateReachableEdge(B, TargetBlock);
2223     }
2224
2225     // This also may be a memory defining terminator, in which case, set it
2226     // equivalent only to itself.
2227     //
2228     auto *MA = MSSA->getMemoryAccess(TI);
2229     if (MA && !isa<MemoryUse>(MA)) {
2230       auto *CC = ensureLeaderOfMemoryClass(MA);
2231       if (setMemoryClass(MA, CC))
2232         markMemoryUsersTouched(MA);
2233     }
2234   }
2235 }
2236
2237 // The algorithm initially places the values of the routine in the TOP
2238 // congruence class. The leader of TOP is the undetermined value `undef`.
2239 // When the algorithm has finished, values still in TOP are unreachable.
2240 void NewGVN::initializeCongruenceClasses(Function &F) {
2241   NextCongruenceNum = 0;
2242
2243   // Note that even though we use the live on entry def as a representative
2244   // MemoryAccess, it is *not* the same as the actual live on entry def. We
2245   // have no real equivalemnt to undef for MemoryAccesses, and so we really
2246   // should be checking whether the MemoryAccess is top if we want to know if it
2247   // is equivalent to everything.  Otherwise, what this really signifies is that
2248   // the access "it reaches all the way back to the beginning of the function"
2249
2250   // Initialize all other instructions to be in TOP class.
2251   TOPClass = createCongruenceClass(nullptr, nullptr);
2252   TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
2253   //  The live on entry def gets put into it's own class
2254   MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2255       createMemoryClass(MSSA->getLiveOnEntryDef());
2256
2257   for (auto DTN : nodes(DT)) {
2258     BasicBlock *BB = DTN->getBlock();
2259     // All MemoryAccesses are equivalent to live on entry to start. They must
2260     // be initialized to something so that initial changes are noticed. For
2261     // the maximal answer, we initialize them all to be the same as
2262     // liveOnEntry.
2263     auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
2264     if (MemoryBlockDefs)
2265       for (const auto &Def : *MemoryBlockDefs) {
2266         MemoryAccessToClass[&Def] = TOPClass;
2267         auto *MD = dyn_cast<MemoryDef>(&Def);
2268         // Insert the memory phis into the member list.
2269         if (!MD) {
2270           const MemoryPhi *MP = cast<MemoryPhi>(&Def);
2271           TOPClass->memory_insert(MP);
2272           MemoryPhiState.insert({MP, MPS_TOP});
2273         }
2274
2275         if (MD && isa<StoreInst>(MD->getMemoryInst()))
2276           TOPClass->incStoreCount();
2277       }
2278     for (auto &I : *BB) {
2279       // Don't insert void terminators into the class. We don't value number
2280       // them, and they just end up sitting in TOP.
2281       if (isa<TerminatorInst>(I) && I.getType()->isVoidTy())
2282         continue;
2283       TOPClass->insert(&I);
2284       ValueToClass[&I] = TOPClass;
2285     }
2286   }
2287
2288   // Initialize arguments to be in their own unique congruence classes
2289   for (auto &FA : F.args())
2290     createSingletonCongruenceClass(&FA);
2291 }
2292
2293 void NewGVN::cleanupTables() {
2294   for (unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
2295     DEBUG(dbgs() << "Congruence class " << CongruenceClasses[i]->getID()
2296                  << " has " << CongruenceClasses[i]->size() << " members\n");
2297     // Make sure we delete the congruence class (probably worth switching to
2298     // a unique_ptr at some point.
2299     delete CongruenceClasses[i];
2300     CongruenceClasses[i] = nullptr;
2301   }
2302
2303   ValueToClass.clear();
2304   ArgRecycler.clear(ExpressionAllocator);
2305   ExpressionAllocator.Reset();
2306   CongruenceClasses.clear();
2307   ExpressionToClass.clear();
2308   ValueToExpression.clear();
2309   ReachableBlocks.clear();
2310   ReachableEdges.clear();
2311 #ifndef NDEBUG
2312   ProcessedCount.clear();
2313 #endif
2314   InstrDFS.clear();
2315   InstructionsToErase.clear();
2316   DFSToInstr.clear();
2317   BlockInstRange.clear();
2318   TouchedInstructions.clear();
2319   MemoryAccessToClass.clear();
2320   PredicateToUsers.clear();
2321   MemoryToUsers.clear();
2322 }
2323
2324 std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(BasicBlock *B,
2325                                                        unsigned Start) {
2326   unsigned End = Start;
2327   if (MemoryAccess *MemPhi = MSSA->getMemoryAccess(B)) {
2328     InstrDFS[MemPhi] = End++;
2329     DFSToInstr.emplace_back(MemPhi);
2330   }
2331
2332   for (auto &I : *B) {
2333     // There's no need to call isInstructionTriviallyDead more than once on
2334     // an instruction. Therefore, once we know that an instruction is dead
2335     // we change its DFS number so that it doesn't get value numbered.
2336     if (isInstructionTriviallyDead(&I, TLI)) {
2337       InstrDFS[&I] = 0;
2338       DEBUG(dbgs() << "Skipping trivially dead instruction " << I << "\n");
2339       markInstructionForDeletion(&I);
2340       continue;
2341     }
2342
2343     InstrDFS[&I] = End++;
2344     DFSToInstr.emplace_back(&I);
2345   }
2346
2347   // All of the range functions taken half-open ranges (open on the end side).
2348   // So we do not subtract one from count, because at this point it is one
2349   // greater than the last instruction.
2350   return std::make_pair(Start, End);
2351 }
2352
2353 void NewGVN::updateProcessedCount(Value *V) {
2354 #ifndef NDEBUG
2355   if (ProcessedCount.count(V) == 0) {
2356     ProcessedCount.insert({V, 1});
2357   } else {
2358     ++ProcessedCount[V];
2359     assert(ProcessedCount[V] < 100 &&
2360            "Seem to have processed the same Value a lot");
2361   }
2362 #endif
2363 }
2364 // Evaluate MemoryPhi nodes symbolically, just like PHI nodes
2365 void NewGVN::valueNumberMemoryPhi(MemoryPhi *MP) {
2366   // If all the arguments are the same, the MemoryPhi has the same value as the
2367   // argument.
2368   // Filter out unreachable blocks and self phis from our operands.
2369   const BasicBlock *PHIBlock = MP->getBlock();
2370   auto Filtered = make_filter_range(MP->operands(), [&](const Use &U) {
2371     return lookupMemoryLeader(cast<MemoryAccess>(U)) != MP &&
2372            !isMemoryAccessTop(cast<MemoryAccess>(U)) &&
2373            ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
2374   });
2375   // If all that is left is nothing, our memoryphi is undef. We keep it as
2376   // InitialClass.  Note: The only case this should happen is if we have at
2377   // least one self-argument.
2378   if (Filtered.begin() == Filtered.end()) {
2379     if (setMemoryClass(MP, TOPClass))
2380       markMemoryUsersTouched(MP);
2381     return;
2382   }
2383
2384   // Transform the remaining operands into operand leaders.
2385   // FIXME: mapped_iterator should have a range version.
2386   auto LookupFunc = [&](const Use &U) {
2387     return lookupMemoryLeader(cast<MemoryAccess>(U));
2388   };
2389   auto MappedBegin = map_iterator(Filtered.begin(), LookupFunc);
2390   auto MappedEnd = map_iterator(Filtered.end(), LookupFunc);
2391
2392   // and now check if all the elements are equal.
2393   // Sadly, we can't use std::equals since these are random access iterators.
2394   const auto *AllSameValue = *MappedBegin;
2395   ++MappedBegin;
2396   bool AllEqual = std::all_of(
2397       MappedBegin, MappedEnd,
2398       [&AllSameValue](const MemoryAccess *V) { return V == AllSameValue; });
2399
2400   if (AllEqual)
2401     DEBUG(dbgs() << "Memory Phi value numbered to " << *AllSameValue << "\n");
2402   else
2403     DEBUG(dbgs() << "Memory Phi value numbered to itself\n");
2404   // If it's equal to something, it's in that class. Otherwise, it has to be in
2405   // a class where it is the leader (other things may be equivalent to it, but
2406   // it needs to start off in its own class, which means it must have been the
2407   // leader, and it can't have stopped being the leader because it was never
2408   // removed).
2409   CongruenceClass *CC =
2410       AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2411   auto OldState = MemoryPhiState.lookup(MP);
2412   assert(OldState != MPS_Invalid && "Invalid memory phi state");
2413   auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2414   MemoryPhiState[MP] = NewState;
2415   if (setMemoryClass(MP, CC) || OldState != NewState)
2416     markMemoryUsersTouched(MP);
2417 }
2418
2419 // Value number a single instruction, symbolically evaluating, performing
2420 // congruence finding, and updating mappings.
2421 void NewGVN::valueNumberInstruction(Instruction *I) {
2422   DEBUG(dbgs() << "Processing instruction " << *I << "\n");
2423   if (!I->isTerminator()) {
2424     const Expression *Symbolized = nullptr;
2425     if (DebugCounter::shouldExecute(VNCounter)) {
2426       Symbolized = performSymbolicEvaluation(I);
2427     } else {
2428       // Mark the instruction as unused so we don't value number it again.
2429       InstrDFS[I] = 0;
2430     }
2431     // If we couldn't come up with a symbolic expression, use the unknown
2432     // expression
2433     if (Symbolized == nullptr) {
2434       Symbolized = createUnknownExpression(I);
2435     }
2436
2437     performCongruenceFinding(I, Symbolized);
2438   } else {
2439     // Handle terminators that return values. All of them produce values we
2440     // don't currently understand.  We don't place non-value producing
2441     // terminators in a class.
2442     if (!I->getType()->isVoidTy()) {
2443       auto *Symbolized = createUnknownExpression(I);
2444       performCongruenceFinding(I, Symbolized);
2445     }
2446     processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->getParent());
2447   }
2448 }
2449
2450 // Check if there is a path, using single or equal argument phi nodes, from
2451 // First to Second.
2452 bool NewGVN::singleReachablePHIPath(const MemoryAccess *First,
2453                                     const MemoryAccess *Second) const {
2454   if (First == Second)
2455     return true;
2456   if (MSSA->isLiveOnEntryDef(First))
2457     return false;
2458
2459   const auto *EndDef = First;
2460   for (auto *ChainDef : optimized_def_chain(First)) {
2461     if (ChainDef == Second)
2462       return true;
2463     if (MSSA->isLiveOnEntryDef(ChainDef))
2464       return false;
2465     EndDef = ChainDef;
2466   }
2467   auto *MP = cast<MemoryPhi>(EndDef);
2468   auto ReachableOperandPred = [&](const Use &U) {
2469     return ReachableEdges.count({MP->getIncomingBlock(U), MP->getBlock()});
2470   };
2471   auto FilteredPhiArgs =
2472       make_filter_range(MP->operands(), ReachableOperandPred);
2473   SmallVector<const Value *, 32> OperandList;
2474   std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2475             std::back_inserter(OperandList));
2476   bool Okay = OperandList.size() == 1;
2477   if (!Okay)
2478     Okay =
2479         std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2480   if (Okay)
2481     return singleReachablePHIPath(cast<MemoryAccess>(OperandList[0]), Second);
2482   return false;
2483 }
2484
2485 // Verify the that the memory equivalence table makes sense relative to the
2486 // congruence classes.  Note that this checking is not perfect, and is currently
2487 // subject to very rare false negatives. It is only useful for
2488 // testing/debugging.
2489 void NewGVN::verifyMemoryCongruency() const {
2490 #ifndef NDEBUG
2491   // Verify that the memory table equivalence and memory member set match
2492   for (const auto *CC : CongruenceClasses) {
2493     if (CC == TOPClass || CC->isDead())
2494       continue;
2495     if (CC->getStoreCount() != 0) {
2496       assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
2497              "Any class with a store as a "
2498              "leader should have a "
2499              "representative stored value\n");
2500       assert(CC->getMemoryLeader() &&
2501              "Any congruence class with a store should "
2502              "have a representative access\n");
2503     }
2504
2505     if (CC->getMemoryLeader())
2506       assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
2507              "Representative MemoryAccess does not appear to be reverse "
2508              "mapped properly");
2509     for (auto M : CC->memory())
2510       assert(MemoryAccessToClass.lookup(M) == CC &&
2511              "Memory member does not appear to be reverse mapped properly");
2512   }
2513
2514   // Anything equivalent in the MemoryAccess table should be in the same
2515   // congruence class.
2516
2517   // Filter out the unreachable and trivially dead entries, because they may
2518   // never have been updated if the instructions were not processed.
2519   auto ReachableAccessPred =
2520       [&](const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
2521         bool Result = ReachableBlocks.count(Pair.first->getBlock());
2522         if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
2523             MemoryToDFSNum(Pair.first) == 0)
2524           return false;
2525         if (auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2526           return !isInstructionTriviallyDead(MemDef->getMemoryInst());
2527         return true;
2528       };
2529
2530   auto Filtered = make_filter_range(MemoryAccessToClass, ReachableAccessPred);
2531   for (auto KV : Filtered) {
2532     assert(KV.second != TOPClass &&
2533            "Memory not unreachable but ended up in TOP");
2534     if (auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
2535       auto *SecondMUD = dyn_cast<MemoryUseOrDef>(KV.second->getMemoryLeader());
2536       if (FirstMUD && SecondMUD)
2537         assert((singleReachablePHIPath(FirstMUD, SecondMUD) ||
2538                 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2539                     ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2540                "The instructions for these memory operations should have "
2541                "been in the same congruence class or reachable through"
2542                "a single argument phi");
2543     } else if (auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
2544       // We can only sanely verify that MemoryDefs in the operand list all have
2545       // the same class.
2546       auto ReachableOperandPred = [&](const Use &U) {
2547         return ReachableEdges.count(
2548                    {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
2549                isa<MemoryDef>(U);
2550
2551       };
2552       // All arguments should in the same class, ignoring unreachable arguments
2553       auto FilteredPhiArgs =
2554           make_filter_range(FirstMP->operands(), ReachableOperandPred);
2555       SmallVector<const CongruenceClass *, 16> PhiOpClasses;
2556       std::transform(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2557                      std::back_inserter(PhiOpClasses), [&](const Use &U) {
2558                        const MemoryDef *MD = cast<MemoryDef>(U);
2559                        return ValueToClass.lookup(MD->getMemoryInst());
2560                      });
2561       assert(std::equal(PhiOpClasses.begin(), PhiOpClasses.end(),
2562                         PhiOpClasses.begin()) &&
2563              "All MemoryPhi arguments should be in the same class");
2564     }
2565   }
2566 #endif
2567 }
2568
2569 // Verify that the sparse propagation we did actually found the maximal fixpoint
2570 // We do this by storing the value to class mapping, touching all instructions,
2571 // and redoing the iteration to see if anything changed.
2572 void NewGVN::verifyIterationSettled(Function &F) {
2573 #ifndef NDEBUG
2574   DEBUG(dbgs() << "Beginning iteration verification\n");
2575   if (DebugCounter::isCounterSet(VNCounter))
2576     DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2577
2578   // Note that we have to store the actual classes, as we may change existing
2579   // classes during iteration.  This is because our memory iteration propagation
2580   // is not perfect, and so may waste a little work.  But it should generate
2581   // exactly the same congruence classes we have now, with different IDs.
2582   std::map<const Value *, CongruenceClass> BeforeIteration;
2583
2584   for (auto &KV : ValueToClass) {
2585     if (auto *I = dyn_cast<Instruction>(KV.first))
2586       // Skip unused/dead instructions.
2587       if (InstrToDFSNum(I) == 0)
2588         continue;
2589     BeforeIteration.insert({KV.first, *KV.second});
2590   }
2591
2592   TouchedInstructions.set();
2593   TouchedInstructions.reset(0);
2594   iterateTouchedInstructions();
2595   DenseSet<std::pair<const CongruenceClass *, const CongruenceClass *>>
2596       EqualClasses;
2597   for (const auto &KV : ValueToClass) {
2598     if (auto *I = dyn_cast<Instruction>(KV.first))
2599       // Skip unused/dead instructions.
2600       if (InstrToDFSNum(I) == 0)
2601         continue;
2602     // We could sink these uses, but i think this adds a bit of clarity here as
2603     // to what we are comparing.
2604     auto *BeforeCC = &BeforeIteration.find(KV.first)->second;
2605     auto *AfterCC = KV.second;
2606     // Note that the classes can't change at this point, so we memoize the set
2607     // that are equal.
2608     if (!EqualClasses.count({BeforeCC, AfterCC})) {
2609       assert(BeforeCC->isEquivalentTo(AfterCC) &&
2610              "Value number changed after main loop completed!");
2611       EqualClasses.insert({BeforeCC, AfterCC});
2612     }
2613   }
2614 #endif
2615 }
2616
2617 // This is the main value numbering loop, it iterates over the initial touched
2618 // instruction set, propagating value numbers, marking things touched, etc,
2619 // until the set of touched instructions is completely empty.
2620 void NewGVN::iterateTouchedInstructions() {
2621   unsigned int Iterations = 0;
2622   // Figure out where touchedinstructions starts
2623   int FirstInstr = TouchedInstructions.find_first();
2624   // Nothing set, nothing to iterate, just return.
2625   if (FirstInstr == -1)
2626     return;
2627   BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
2628   while (TouchedInstructions.any()) {
2629     ++Iterations;
2630     // Walk through all the instructions in all the blocks in RPO.
2631     // TODO: As we hit a new block, we should push and pop equalities into a
2632     // table lookupOperandLeader can use, to catch things PredicateInfo
2633     // might miss, like edge-only equivalences.
2634     for (int InstrNum = TouchedInstructions.find_first(); InstrNum != -1;
2635          InstrNum = TouchedInstructions.find_next(InstrNum)) {
2636
2637       // This instruction was found to be dead. We don't bother looking
2638       // at it again.
2639       if (InstrNum == 0) {
2640         TouchedInstructions.reset(InstrNum);
2641         continue;
2642       }
2643
2644       Value *V = InstrFromDFSNum(InstrNum);
2645       BasicBlock *CurrBlock = getBlockForValue(V);
2646
2647       // If we hit a new block, do reachability processing.
2648       if (CurrBlock != LastBlock) {
2649         LastBlock = CurrBlock;
2650         bool BlockReachable = ReachableBlocks.count(CurrBlock);
2651         const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
2652
2653         // If it's not reachable, erase any touched instructions and move on.
2654         if (!BlockReachable) {
2655           TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
2656           DEBUG(dbgs() << "Skipping instructions in block "
2657                        << getBlockName(CurrBlock)
2658                        << " because it is unreachable\n");
2659           continue;
2660         }
2661         updateProcessedCount(CurrBlock);
2662       }
2663
2664       if (auto *MP = dyn_cast<MemoryPhi>(V)) {
2665         DEBUG(dbgs() << "Processing MemoryPhi " << *MP << "\n");
2666         valueNumberMemoryPhi(MP);
2667       } else if (auto *I = dyn_cast<Instruction>(V)) {
2668         valueNumberInstruction(I);
2669       } else {
2670         llvm_unreachable("Should have been a MemoryPhi or Instruction");
2671       }
2672       updateProcessedCount(V);
2673       // Reset after processing (because we may mark ourselves as touched when
2674       // we propagate equalities).
2675       TouchedInstructions.reset(InstrNum);
2676     }
2677   }
2678   NumGVNMaxIterations = std::max(NumGVNMaxIterations.getValue(), Iterations);
2679 }
2680
2681 // This is the main transformation entry point.
2682 bool NewGVN::runGVN() {
2683   if (DebugCounter::isCounterSet(VNCounter))
2684     StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
2685   bool Changed = false;
2686   NumFuncArgs = F.arg_size();
2687   MSSAWalker = MSSA->getWalker();
2688
2689   // Count number of instructions for sizing of hash tables, and come
2690   // up with a global dfs numbering for instructions.
2691   unsigned ICount = 1;
2692   // Add an empty instruction to account for the fact that we start at 1
2693   DFSToInstr.emplace_back(nullptr);
2694   // Note: We want ideal RPO traversal of the blocks, which is not quite the
2695   // same as dominator tree order, particularly with regard whether backedges
2696   // get visited first or second, given a block with multiple successors.
2697   // If we visit in the wrong order, we will end up performing N times as many
2698   // iterations.
2699   // The dominator tree does guarantee that, for a given dom tree node, it's
2700   // parent must occur before it in the RPO ordering. Thus, we only need to sort
2701   // the siblings.
2702   ReversePostOrderTraversal<Function *> RPOT(&F);
2703   unsigned Counter = 0;
2704   for (auto &B : RPOT) {
2705     auto *Node = DT->getNode(B);
2706     assert(Node && "RPO and Dominator tree should have same reachability");
2707     RPOOrdering[Node] = ++Counter;
2708   }
2709   // Sort dominator tree children arrays into RPO.
2710   for (auto &B : RPOT) {
2711     auto *Node = DT->getNode(B);
2712     if (Node->getChildren().size() > 1)
2713       std::sort(Node->begin(), Node->end(),
2714                 [&](const DomTreeNode *A, const DomTreeNode *B) {
2715                   return RPOOrdering[A] < RPOOrdering[B];
2716                 });
2717   }
2718
2719   // Now a standard depth first ordering of the domtree is equivalent to RPO.
2720   for (auto DTN : depth_first(DT->getRootNode())) {
2721     BasicBlock *B = DTN->getBlock();
2722     const auto &BlockRange = assignDFSNumbers(B, ICount);
2723     BlockInstRange.insert({B, BlockRange});
2724     ICount += BlockRange.second - BlockRange.first;
2725   }
2726
2727   TouchedInstructions.resize(ICount);
2728   // Ensure we don't end up resizing the expressionToClass map, as
2729   // that can be quite expensive. At most, we have one expression per
2730   // instruction.
2731   ExpressionToClass.reserve(ICount);
2732
2733   // Initialize the touched instructions to include the entry block.
2734   const auto &InstRange = BlockInstRange.lookup(&F.getEntryBlock());
2735   TouchedInstructions.set(InstRange.first, InstRange.second);
2736   ReachableBlocks.insert(&F.getEntryBlock());
2737
2738   initializeCongruenceClasses(F);
2739   iterateTouchedInstructions();
2740   verifyMemoryCongruency();
2741   verifyIterationSettled(F);
2742
2743   Changed |= eliminateInstructions(F);
2744
2745   // Delete all instructions marked for deletion.
2746   for (Instruction *ToErase : InstructionsToErase) {
2747     if (!ToErase->use_empty())
2748       ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
2749
2750     ToErase->eraseFromParent();
2751   }
2752
2753   // Delete all unreachable blocks.
2754   auto UnreachableBlockPred = [&](const BasicBlock &BB) {
2755     return !ReachableBlocks.count(&BB);
2756   };
2757
2758   for (auto &BB : make_filter_range(F, UnreachableBlockPred)) {
2759     DEBUG(dbgs() << "We believe block " << getBlockName(&BB)
2760                  << " is unreachable\n");
2761     deleteInstructionsInBlock(&BB);
2762     Changed = true;
2763   }
2764
2765   cleanupTables();
2766   return Changed;
2767 }
2768
2769 // Return true if V is a value that will always be available (IE can
2770 // be placed anywhere) in the function.  We don't do globals here
2771 // because they are often worse to put in place.
2772 // TODO: Separate cost from availability
2773 static bool alwaysAvailable(Value *V) {
2774   return isa<Constant>(V) || isa<Argument>(V);
2775 }
2776
2777 struct NewGVN::ValueDFS {
2778   int DFSIn = 0;
2779   int DFSOut = 0;
2780   int LocalNum = 0;
2781   // Only one of Def and U will be set.
2782   // The bool in the Def tells us whether the Def is the stored value of a
2783   // store.
2784   PointerIntPair<Value *, 1, bool> Def;
2785   Use *U = nullptr;
2786   bool operator<(const ValueDFS &Other) const {
2787     // It's not enough that any given field be less than - we have sets
2788     // of fields that need to be evaluated together to give a proper ordering.
2789     // For example, if you have;
2790     // DFS (1, 3)
2791     // Val 0
2792     // DFS (1, 2)
2793     // Val 50
2794     // We want the second to be less than the first, but if we just go field
2795     // by field, we will get to Val 0 < Val 50 and say the first is less than
2796     // the second. We only want it to be less than if the DFS orders are equal.
2797     //
2798     // Each LLVM instruction only produces one value, and thus the lowest-level
2799     // differentiator that really matters for the stack (and what we use as as a
2800     // replacement) is the local dfs number.
2801     // Everything else in the structure is instruction level, and only affects
2802     // the order in which we will replace operands of a given instruction.
2803     //
2804     // For a given instruction (IE things with equal dfsin, dfsout, localnum),
2805     // the order of replacement of uses does not matter.
2806     // IE given,
2807     //  a = 5
2808     //  b = a + a
2809     // When you hit b, you will have two valuedfs with the same dfsin, out, and
2810     // localnum.
2811     // The .val will be the same as well.
2812     // The .u's will be different.
2813     // You will replace both, and it does not matter what order you replace them
2814     // in (IE whether you replace operand 2, then operand 1, or operand 1, then
2815     // operand 2).
2816     // Similarly for the case of same dfsin, dfsout, localnum, but different
2817     // .val's
2818     //  a = 5
2819     //  b  = 6
2820     //  c = a + b
2821     // in c, we will a valuedfs for a, and one for b,with everything the same
2822     // but .val  and .u.
2823     // It does not matter what order we replace these operands in.
2824     // You will always end up with the same IR, and this is guaranteed.
2825     return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
2826            std::tie(Other.DFSIn, Other.DFSOut, Other.LocalNum, Other.Def,
2827                     Other.U);
2828   }
2829 };
2830
2831 // This function converts the set of members for a congruence class from values,
2832 // to sets of defs and uses with associated DFS info.  The total number of
2833 // reachable uses for each value is stored in UseCount, and instructions that
2834 // seem
2835 // dead (have no non-dead uses) are stored in ProbablyDead.
2836 void NewGVN::convertClassToDFSOrdered(
2837     const CongruenceClass &Dense, SmallVectorImpl<ValueDFS> &DFSOrderedSet,
2838     DenseMap<const Value *, unsigned int> &UseCounts,
2839     SmallPtrSetImpl<Instruction *> &ProbablyDead) const {
2840   for (auto D : Dense) {
2841     // First add the value.
2842     BasicBlock *BB = getBlockForValue(D);
2843     // Constants are handled prior to ever calling this function, so
2844     // we should only be left with instructions as members.
2845     assert(BB && "Should have figured out a basic block for value");
2846     ValueDFS VDDef;
2847     DomTreeNode *DomNode = DT->getNode(BB);
2848     VDDef.DFSIn = DomNode->getDFSNumIn();
2849     VDDef.DFSOut = DomNode->getDFSNumOut();
2850     // If it's a store, use the leader of the value operand, if it's always
2851     // available, or the value operand.  TODO: We could do dominance checks to
2852     // find a dominating leader, but not worth it ATM.
2853     if (auto *SI = dyn_cast<StoreInst>(D)) {
2854       auto Leader = lookupOperandLeader(SI->getValueOperand());
2855       if (alwaysAvailable(Leader)) {
2856         VDDef.Def.setPointer(Leader);
2857       } else {
2858         VDDef.Def.setPointer(SI->getValueOperand());
2859         VDDef.Def.setInt(true);
2860       }
2861     } else {
2862       VDDef.Def.setPointer(D);
2863     }
2864     assert(isa<Instruction>(D) &&
2865            "The dense set member should always be an instruction");
2866     VDDef.LocalNum = InstrToDFSNum(D);
2867     DFSOrderedSet.emplace_back(VDDef);
2868     Instruction *Def = cast<Instruction>(D);
2869     unsigned int UseCount = 0;
2870     // Now add the uses.
2871     for (auto &U : Def->uses()) {
2872       if (auto *I = dyn_cast<Instruction>(U.getUser())) {
2873         // Don't try to replace into dead uses
2874         if (InstructionsToErase.count(I))
2875           continue;
2876         ValueDFS VDUse;
2877         // Put the phi node uses in the incoming block.
2878         BasicBlock *IBlock;
2879         if (auto *P = dyn_cast<PHINode>(I)) {
2880           IBlock = P->getIncomingBlock(U);
2881           // Make phi node users appear last in the incoming block
2882           // they are from.
2883           VDUse.LocalNum = InstrDFS.size() + 1;
2884         } else {
2885           IBlock = I->getParent();
2886           VDUse.LocalNum = InstrToDFSNum(I);
2887         }
2888
2889         // Skip uses in unreachable blocks, as we're going
2890         // to delete them.
2891         if (ReachableBlocks.count(IBlock) == 0)
2892           continue;
2893
2894         DomTreeNode *DomNode = DT->getNode(IBlock);
2895         VDUse.DFSIn = DomNode->getDFSNumIn();
2896         VDUse.DFSOut = DomNode->getDFSNumOut();
2897         VDUse.U = &U;
2898         ++UseCount;
2899         DFSOrderedSet.emplace_back(VDUse);
2900       }
2901     }
2902
2903     // If there are no uses, it's probably dead (but it may have side-effects,
2904     // so not definitely dead. Otherwise, store the number of uses so we can
2905     // track if it becomes dead later).
2906     if (UseCount == 0)
2907       ProbablyDead.insert(Def);
2908     else
2909       UseCounts[Def] = UseCount;
2910   }
2911 }
2912
2913 // This function converts the set of members for a congruence class from values,
2914 // to the set of defs for loads and stores, with associated DFS info.
2915 void NewGVN::convertClassToLoadsAndStores(
2916     const CongruenceClass &Dense,
2917     SmallVectorImpl<ValueDFS> &LoadsAndStores) const {
2918   for (auto D : Dense) {
2919     if (!isa<LoadInst>(D) && !isa<StoreInst>(D))
2920       continue;
2921
2922     BasicBlock *BB = getBlockForValue(D);
2923     ValueDFS VD;
2924     DomTreeNode *DomNode = DT->getNode(BB);
2925     VD.DFSIn = DomNode->getDFSNumIn();
2926     VD.DFSOut = DomNode->getDFSNumOut();
2927     VD.Def.setPointer(D);
2928
2929     // If it's an instruction, use the real local dfs number.
2930     if (auto *I = dyn_cast<Instruction>(D))
2931       VD.LocalNum = InstrToDFSNum(I);
2932     else
2933       llvm_unreachable("Should have been an instruction");
2934
2935     LoadsAndStores.emplace_back(VD);
2936   }
2937 }
2938
2939 static void patchReplacementInstruction(Instruction *I, Value *Repl) {
2940   auto *ReplInst = dyn_cast<Instruction>(Repl);
2941   if (!ReplInst)
2942     return;
2943
2944   // Patch the replacement so that it is not more restrictive than the value
2945   // being replaced.
2946   // Note that if 'I' is a load being replaced by some operation,
2947   // for example, by an arithmetic operation, then andIRFlags()
2948   // would just erase all math flags from the original arithmetic
2949   // operation, which is clearly not wanted and not needed.
2950   if (!isa<LoadInst>(I))
2951     ReplInst->andIRFlags(I);
2952
2953   // FIXME: If both the original and replacement value are part of the
2954   // same control-flow region (meaning that the execution of one
2955   // guarantees the execution of the other), then we can combine the
2956   // noalias scopes here and do better than the general conservative
2957   // answer used in combineMetadata().
2958
2959   // In general, GVN unifies expressions over different control-flow
2960   // regions, and so we need a conservative combination of the noalias
2961   // scopes.
2962   static const unsigned KnownIDs[] = {
2963       LLVMContext::MD_tbaa,           LLVMContext::MD_alias_scope,
2964       LLVMContext::MD_noalias,        LLVMContext::MD_range,
2965       LLVMContext::MD_fpmath,         LLVMContext::MD_invariant_load,
2966       LLVMContext::MD_invariant_group};
2967   combineMetadata(ReplInst, I, KnownIDs);
2968 }
2969
2970 static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
2971   patchReplacementInstruction(I, Repl);
2972   I->replaceAllUsesWith(Repl);
2973 }
2974
2975 void NewGVN::deleteInstructionsInBlock(BasicBlock *BB) {
2976   DEBUG(dbgs() << "  BasicBlock Dead:" << *BB);
2977   ++NumGVNBlocksDeleted;
2978
2979   // Delete the instructions backwards, as it has a reduced likelihood of having
2980   // to update as many def-use and use-def chains. Start after the terminator.
2981   auto StartPoint = BB->rbegin();
2982   ++StartPoint;
2983   // Note that we explicitly recalculate BB->rend() on each iteration,
2984   // as it may change when we remove the first instruction.
2985   for (BasicBlock::reverse_iterator I(StartPoint); I != BB->rend();) {
2986     Instruction &Inst = *I++;
2987     if (!Inst.use_empty())
2988       Inst.replaceAllUsesWith(UndefValue::get(Inst.getType()));
2989     if (isa<LandingPadInst>(Inst))
2990       continue;
2991
2992     Inst.eraseFromParent();
2993     ++NumGVNInstrDeleted;
2994   }
2995   // Now insert something that simplifycfg will turn into an unreachable.
2996   Type *Int8Ty = Type::getInt8Ty(BB->getContext());
2997   new StoreInst(UndefValue::get(Int8Ty),
2998                 Constant::getNullValue(Int8Ty->getPointerTo()),
2999                 BB->getTerminator());
3000 }
3001
3002 void NewGVN::markInstructionForDeletion(Instruction *I) {
3003   DEBUG(dbgs() << "Marking " << *I << " for deletion\n");
3004   InstructionsToErase.insert(I);
3005 }
3006
3007 void NewGVN::replaceInstruction(Instruction *I, Value *V) {
3008
3009   DEBUG(dbgs() << "Replacing " << *I << " with " << *V << "\n");
3010   patchAndReplaceAllUsesWith(I, V);
3011   // We save the actual erasing to avoid invalidating memory
3012   // dependencies until we are done with everything.
3013   markInstructionForDeletion(I);
3014 }
3015
3016 namespace {
3017
3018 // This is a stack that contains both the value and dfs info of where
3019 // that value is valid.
3020 class ValueDFSStack {
3021 public:
3022   Value *back() const { return ValueStack.back(); }
3023   std::pair<int, int> dfs_back() const { return DFSStack.back(); }
3024
3025   void push_back(Value *V, int DFSIn, int DFSOut) {
3026     ValueStack.emplace_back(V);
3027     DFSStack.emplace_back(DFSIn, DFSOut);
3028   }
3029   bool empty() const { return DFSStack.empty(); }
3030   bool isInScope(int DFSIn, int DFSOut) const {
3031     if (empty())
3032       return false;
3033     return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3034   }
3035
3036   void popUntilDFSScope(int DFSIn, int DFSOut) {
3037
3038     // These two should always be in sync at this point.
3039     assert(ValueStack.size() == DFSStack.size() &&
3040            "Mismatch between ValueStack and DFSStack");
3041     while (
3042         !DFSStack.empty() &&
3043         !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3044       DFSStack.pop_back();
3045       ValueStack.pop_back();
3046     }
3047   }
3048
3049 private:
3050   SmallVector<Value *, 8> ValueStack;
3051   SmallVector<std::pair<int, int>, 8> DFSStack;
3052 };
3053 }
3054
3055 bool NewGVN::eliminateInstructions(Function &F) {
3056   // This is a non-standard eliminator. The normal way to eliminate is
3057   // to walk the dominator tree in order, keeping track of available
3058   // values, and eliminating them.  However, this is mildly
3059   // pointless. It requires doing lookups on every instruction,
3060   // regardless of whether we will ever eliminate it.  For
3061   // instructions part of most singleton congruence classes, we know we
3062   // will never eliminate them.
3063
3064   // Instead, this eliminator looks at the congruence classes directly, sorts
3065   // them into a DFS ordering of the dominator tree, and then we just
3066   // perform elimination straight on the sets by walking the congruence
3067   // class member uses in order, and eliminate the ones dominated by the
3068   // last member.   This is worst case O(E log E) where E = number of
3069   // instructions in a single congruence class.  In theory, this is all
3070   // instructions.   In practice, it is much faster, as most instructions are
3071   // either in singleton congruence classes or can't possibly be eliminated
3072   // anyway (if there are no overlapping DFS ranges in class).
3073   // When we find something not dominated, it becomes the new leader
3074   // for elimination purposes.
3075   // TODO: If we wanted to be faster, We could remove any members with no
3076   // overlapping ranges while sorting, as we will never eliminate anything
3077   // with those members, as they don't dominate anything else in our set.
3078
3079   bool AnythingReplaced = false;
3080
3081   // Since we are going to walk the domtree anyway, and we can't guarantee the
3082   // DFS numbers are updated, we compute some ourselves.
3083   DT->updateDFSNumbers();
3084
3085   for (auto &B : F) {
3086     if (!ReachableBlocks.count(&B)) {
3087       for (const auto S : successors(&B)) {
3088         for (auto II = S->begin(); isa<PHINode>(II); ++II) {
3089           auto &Phi = cast<PHINode>(*II);
3090           DEBUG(dbgs() << "Replacing incoming value of " << *II << " for block "
3091                        << getBlockName(&B)
3092                        << " with undef due to it being unreachable\n");
3093           for (auto &Operand : Phi.incoming_values())
3094             if (Phi.getIncomingBlock(Operand) == &B)
3095               Operand.set(UndefValue::get(Phi.getType()));
3096         }
3097       }
3098     }
3099   }
3100
3101   // Map to store the use counts
3102   DenseMap<const Value *, unsigned int> UseCounts;
3103   for (CongruenceClass *CC : reverse(CongruenceClasses)) {
3104     // Track the equivalent store info so we can decide whether to try
3105     // dead store elimination.
3106     SmallVector<ValueDFS, 8> PossibleDeadStores;
3107     SmallPtrSet<Instruction *, 8> ProbablyDead;
3108     if (CC->isDead() || CC->empty())
3109       continue;
3110     // Everything still in the TOP class is unreachable or dead.
3111     if (CC == TOPClass) {
3112 #ifndef NDEBUG
3113       for (auto M : *CC)
3114         assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3115                 InstructionsToErase.count(cast<Instruction>(M))) &&
3116                "Everything in TOP should be unreachable or dead at this "
3117                "point");
3118 #endif
3119       continue;
3120     }
3121
3122     assert(CC->getLeader() && "We should have had a leader");
3123     // If this is a leader that is always available, and it's a
3124     // constant or has no equivalences, just replace everything with
3125     // it. We then update the congruence class with whatever members
3126     // are left.
3127     Value *Leader =
3128         CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
3129     if (alwaysAvailable(Leader)) {
3130       CongruenceClass::MemberSet MembersLeft;
3131       for (auto M : *CC) {
3132         Value *Member = M;
3133         // Void things have no uses we can replace.
3134         if (Member == Leader || !isa<Instruction>(Member) ||
3135             Member->getType()->isVoidTy()) {
3136           MembersLeft.insert(Member);
3137           continue;
3138         }
3139         DEBUG(dbgs() << "Found replacement " << *(Leader) << " for " << *Member
3140                      << "\n");
3141         auto *I = cast<Instruction>(Member);
3142         assert(Leader != I && "About to accidentally remove our leader");
3143         replaceInstruction(I, Leader);
3144         AnythingReplaced = true;
3145       }
3146       CC->swap(MembersLeft);
3147     } else {
3148       DEBUG(dbgs() << "Eliminating in congruence class " << CC->getID()
3149                    << "\n");
3150       // If this is a singleton, we can skip it.
3151       if (CC->size() != 1) {
3152         // This is a stack because equality replacement/etc may place
3153         // constants in the middle of the member list, and we want to use
3154         // those constant values in preference to the current leader, over
3155         // the scope of those constants.
3156         ValueDFSStack EliminationStack;
3157
3158         // Convert the members to DFS ordered sets and then merge them.
3159         SmallVector<ValueDFS, 8> DFSOrderedSet;
3160         convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
3161
3162         // Sort the whole thing.
3163         std::sort(DFSOrderedSet.begin(), DFSOrderedSet.end());
3164         for (auto &VD : DFSOrderedSet) {
3165           int MemberDFSIn = VD.DFSIn;
3166           int MemberDFSOut = VD.DFSOut;
3167           Value *Def = VD.Def.getPointer();
3168           bool FromStore = VD.Def.getInt();
3169           Use *U = VD.U;
3170           // We ignore void things because we can't get a value from them.
3171           if (Def && Def->getType()->isVoidTy())
3172             continue;
3173
3174           if (EliminationStack.empty()) {
3175             DEBUG(dbgs() << "Elimination Stack is empty\n");
3176           } else {
3177             DEBUG(dbgs() << "Elimination Stack Top DFS numbers are ("
3178                          << EliminationStack.dfs_back().first << ","
3179                          << EliminationStack.dfs_back().second << ")\n");
3180           }
3181
3182           DEBUG(dbgs() << "Current DFS numbers are (" << MemberDFSIn << ","
3183                        << MemberDFSOut << ")\n");
3184           // First, we see if we are out of scope or empty.  If so,
3185           // and there equivalences, we try to replace the top of
3186           // stack with equivalences (if it's on the stack, it must
3187           // not have been eliminated yet).
3188           // Then we synchronize to our current scope, by
3189           // popping until we are back within a DFS scope that
3190           // dominates the current member.
3191           // Then, what happens depends on a few factors
3192           // If the stack is now empty, we need to push
3193           // If we have a constant or a local equivalence we want to
3194           // start using, we also push.
3195           // Otherwise, we walk along, processing members who are
3196           // dominated by this scope, and eliminate them.
3197           bool ShouldPush = Def && EliminationStack.empty();
3198           bool OutOfScope =
3199               !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3200
3201           if (OutOfScope || ShouldPush) {
3202             // Sync to our current scope.
3203             EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3204             bool ShouldPush = Def && EliminationStack.empty();
3205             if (ShouldPush) {
3206               EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
3207             }
3208           }
3209
3210           // Skip the Def's, we only want to eliminate on their uses.  But mark
3211           // dominated defs as dead.
3212           if (Def) {
3213             // For anything in this case, what and how we value number
3214             // guarantees that any side-effets that would have occurred (ie
3215             // throwing, etc) can be proven to either still occur (because it's
3216             // dominated by something that has the same side-effects), or never
3217             // occur.  Otherwise, we would not have been able to prove it value
3218             // equivalent to something else. For these things, we can just mark
3219             // it all dead.  Note that this is different from the "ProbablyDead"
3220             // set, which may not be dominated by anything, and thus, are only
3221             // easy to prove dead if they are also side-effect free. Note that
3222             // because stores are put in terms of the stored value, we skip
3223             // stored values here. If the stored value is really dead, it will
3224             // still be marked for deletion when we process it in its own class.
3225             if (!EliminationStack.empty() && Def != EliminationStack.back() &&
3226                 isa<Instruction>(Def) && !FromStore)
3227               markInstructionForDeletion(cast<Instruction>(Def));
3228             continue;
3229           }
3230           // At this point, we know it is a Use we are trying to possibly
3231           // replace.
3232
3233           assert(isa<Instruction>(U->get()) &&
3234                  "Current def should have been an instruction");
3235           assert(isa<Instruction>(U->getUser()) &&
3236                  "Current user should have been an instruction");
3237
3238           // If the thing we are replacing into is already marked to be dead,
3239           // this use is dead.  Note that this is true regardless of whether
3240           // we have anything dominating the use or not.  We do this here
3241           // because we are already walking all the uses anyway.
3242           Instruction *InstUse = cast<Instruction>(U->getUser());
3243           if (InstructionsToErase.count(InstUse)) {
3244             auto &UseCount = UseCounts[U->get()];
3245             if (--UseCount == 0) {
3246               ProbablyDead.insert(cast<Instruction>(U->get()));
3247             }
3248           }
3249
3250           // If we get to this point, and the stack is empty we must have a use
3251           // with nothing we can use to eliminate this use, so just skip it.
3252           if (EliminationStack.empty())
3253             continue;
3254
3255           Value *DominatingLeader = EliminationStack.back();
3256
3257           // Don't replace our existing users with ourselves.
3258           if (U->get() == DominatingLeader)
3259             continue;
3260           DEBUG(dbgs() << "Found replacement " << *DominatingLeader << " for "
3261                        << *U->get() << " in " << *(U->getUser()) << "\n");
3262
3263           // If we replaced something in an instruction, handle the patching of
3264           // metadata.  Skip this if we are replacing predicateinfo with its
3265           // original operand, as we already know we can just drop it.
3266           auto *ReplacedInst = cast<Instruction>(U->get());
3267           auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3268           if (!PI || DominatingLeader != PI->OriginalOp)
3269             patchReplacementInstruction(ReplacedInst, DominatingLeader);
3270           U->set(DominatingLeader);
3271           // This is now a use of the dominating leader, which means if the
3272           // dominating leader was dead, it's now live!
3273           auto &LeaderUseCount = UseCounts[DominatingLeader];
3274           // It's about to be alive again.
3275           if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3276             ProbablyDead.erase(cast<Instruction>(DominatingLeader));
3277           ++LeaderUseCount;
3278           AnythingReplaced = true;
3279         }
3280       }
3281     }
3282
3283     // At this point, anything still in the ProbablyDead set is actually dead if
3284     // would be trivially dead.
3285     for (auto *I : ProbablyDead)
3286       if (wouldInstructionBeTriviallyDead(I))
3287         markInstructionForDeletion(I);
3288
3289     // Cleanup the congruence class.
3290     CongruenceClass::MemberSet MembersLeft;
3291     for (auto *Member : *CC)
3292       if (!isa<Instruction>(Member) ||
3293           !InstructionsToErase.count(cast<Instruction>(Member)))
3294         MembersLeft.insert(Member);
3295     CC->swap(MembersLeft);
3296
3297     // If we have possible dead stores to look at, try to eliminate them.
3298     if (CC->getStoreCount() > 0) {
3299       convertClassToLoadsAndStores(*CC, PossibleDeadStores);
3300       std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3301       ValueDFSStack EliminationStack;
3302       for (auto &VD : PossibleDeadStores) {
3303         int MemberDFSIn = VD.DFSIn;
3304         int MemberDFSOut = VD.DFSOut;
3305         Instruction *Member = cast<Instruction>(VD.Def.getPointer());
3306         if (EliminationStack.empty() ||
3307             !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3308           // Sync to our current scope.
3309           EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3310           if (EliminationStack.empty()) {
3311             EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3312             continue;
3313           }
3314         }
3315         // We already did load elimination, so nothing to do here.
3316         if (isa<LoadInst>(Member))
3317           continue;
3318         assert(!EliminationStack.empty());
3319         Instruction *Leader = cast<Instruction>(EliminationStack.back());
3320         (void)Leader;
3321         assert(DT->dominates(Leader->getParent(), Member->getParent()));
3322         // Member is dominater by Leader, and thus dead
3323         DEBUG(dbgs() << "Marking dead store " << *Member
3324                      << " that is dominated by " << *Leader << "\n");
3325         markInstructionForDeletion(Member);
3326         CC->erase(Member);
3327         ++NumGVNDeadStores;
3328       }
3329     }
3330   }
3331
3332   return AnythingReplaced;
3333 }
3334
3335 // This function provides global ranking of operations so that we can place them
3336 // in a canonical order.  Note that rank alone is not necessarily enough for a
3337 // complete ordering, as constants all have the same rank.  However, generally,
3338 // we will simplify an operation with all constants so that it doesn't matter
3339 // what order they appear in.
3340 unsigned int NewGVN::getRank(const Value *V) const {
3341   // Prefer undef to anything else
3342   if (isa<UndefValue>(V))
3343     return 0;
3344   if (isa<Constant>(V))
3345     return 1;
3346   else if (auto *A = dyn_cast<Argument>(V))
3347     return 2 + A->getArgNo();
3348
3349   // Need to shift the instruction DFS by number of arguments + 3 to account for
3350   // the constant and argument ranking above.
3351   unsigned Result = InstrToDFSNum(V);
3352   if (Result > 0)
3353     return 3 + NumFuncArgs + Result;
3354   // Unreachable or something else, just return a really large number.
3355   return ~0;
3356 }
3357
3358 // This is a function that says whether two commutative operations should
3359 // have their order swapped when canonicalizing.
3360 bool NewGVN::shouldSwapOperands(const Value *A, const Value *B) const {
3361   // Because we only care about a total ordering, and don't rewrite expressions
3362   // in this order, we order by rank, which will give a strict weak ordering to
3363   // everything but constants, and then we order by pointer address.
3364   return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
3365 }
3366
3367 class NewGVNLegacyPass : public FunctionPass {
3368 public:
3369   static char ID; // Pass identification, replacement for typeid.
3370   NewGVNLegacyPass() : FunctionPass(ID) {
3371     initializeNewGVNLegacyPassPass(*PassRegistry::getPassRegistry());
3372   }
3373   bool runOnFunction(Function &F) override;
3374
3375 private:
3376   void getAnalysisUsage(AnalysisUsage &AU) const override {
3377     AU.addRequired<AssumptionCacheTracker>();
3378     AU.addRequired<DominatorTreeWrapperPass>();
3379     AU.addRequired<TargetLibraryInfoWrapperPass>();
3380     AU.addRequired<MemorySSAWrapperPass>();
3381     AU.addRequired<AAResultsWrapperPass>();
3382     AU.addPreserved<DominatorTreeWrapperPass>();
3383     AU.addPreserved<GlobalsAAWrapperPass>();
3384   }
3385 };
3386
3387 bool NewGVNLegacyPass::runOnFunction(Function &F) {
3388   if (skipFunction(F))
3389     return false;
3390   return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3391                 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3392                 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3393                 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3394                 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3395                 F.getParent()->getDataLayout())
3396       .runGVN();
3397 }
3398
3399 INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering",
3400                       false, false)
3401 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3402 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
3403 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3404 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3405 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3406 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3407 INITIALIZE_PASS_END(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false,
3408                     false)
3409
3410 char NewGVNLegacyPass::ID = 0;
3411
3412 // createGVNPass - The public interface to this file.
3413 FunctionPass *llvm::createNewGVNPass() { return new NewGVNLegacyPass(); }
3414
3415 PreservedAnalyses NewGVNPass::run(Function &F, AnalysisManager<Function> &AM) {
3416   // Apparently the order in which we get these results matter for
3417   // the old GVN (see Chandler's comment in GVN.cpp). I'll keep
3418   // the same order here, just in case.
3419   auto &AC = AM.getResult<AssumptionAnalysis>(F);
3420   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3421   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3422   auto &AA = AM.getResult<AAManager>(F);
3423   auto &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
3424   bool Changed =
3425       NewGVN(F, &DT, &AC, &TLI, &AA, &MSSA, F.getParent()->getDataLayout())
3426           .runGVN();
3427   if (!Changed)
3428     return PreservedAnalyses::all();
3429   PreservedAnalyses PA;
3430   PA.preserve<DominatorTreeAnalysis>();
3431   PA.preserve<GlobalsAA>();
3432   return PA;
3433 }