xref: /llvm-project/llvm/lib/Transforms/Scalar/EarlyCSE.cpp (revision c00cb76274fdcc529335f55b0d19e6bc42ea9d8d)
1 //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass performs a simple dominator tree walk that eliminates trivially
10 // redundant instructions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Scalar/EarlyCSE.h"
15 #include "llvm/ADT/DenseMapInfo.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/ScopedHashTable.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/GlobalsModRef.h"
24 #include "llvm/Analysis/GuardUtils.h"
25 #include "llvm/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/MemorySSA.h"
27 #include "llvm/Analysis/MemorySSAUpdater.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/InstrTypes.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/IR/PassManager.h"
43 #include "llvm/IR/PatternMatch.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/IR/Use.h"
46 #include "llvm/IR/Value.h"
47 #include "llvm/InitializePasses.h"
48 #include "llvm/Pass.h"
49 #include "llvm/Support/Allocator.h"
50 #include "llvm/Support/AtomicOrdering.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/DebugCounter.h"
54 #include "llvm/Support/RecyclingAllocator.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include "llvm/Transforms/Scalar.h"
57 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
58 #include "llvm/Transforms/Utils/GuardUtils.h"
59 #include "llvm/Transforms/Utils/Local.h"
60 #include <cassert>
61 #include <deque>
62 #include <memory>
63 #include <utility>
64 
65 using namespace llvm;
66 using namespace llvm::PatternMatch;
67 
68 #define DEBUG_TYPE "early-cse"
69 
70 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
71 STATISTIC(NumCSE,      "Number of instructions CSE'd");
72 STATISTIC(NumCSECVP,   "Number of compare instructions CVP'd");
73 STATISTIC(NumCSELoad,  "Number of load instructions CSE'd");
74 STATISTIC(NumCSECall,  "Number of call instructions CSE'd");
75 STATISTIC(NumDSE,      "Number of trivial dead stores removed");
76 
77 DEBUG_COUNTER(CSECounter, "early-cse",
78               "Controls which instructions are removed");
79 
80 static cl::opt<unsigned> EarlyCSEMssaOptCap(
81     "earlycse-mssa-optimization-cap", cl::init(500), cl::Hidden,
82     cl::desc("Enable imprecision in EarlyCSE in pathological cases, in exchange "
83              "for faster compile. Caps the MemorySSA clobbering calls."));
84 
85 static cl::opt<bool> EarlyCSEDebugHash(
86     "earlycse-debug-hash", cl::init(false), cl::Hidden,
87     cl::desc("Perform extra assertion checking to verify that SimpleValue's hash "
88              "function is well-behaved w.r.t. its isEqual predicate"));
89 
90 //===----------------------------------------------------------------------===//
91 // SimpleValue
92 //===----------------------------------------------------------------------===//
93 
94 namespace {
95 
96 /// Struct representing the available values in the scoped hash table.
97 struct SimpleValue {
98   Instruction *Inst;
99 
100   SimpleValue(Instruction *I) : Inst(I) {
101     assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
102   }
103 
104   bool isSentinel() const {
105     return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
106            Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
107   }
108 
109   static bool canHandle(Instruction *Inst) {
110     // This can only handle non-void readnone functions.
111     if (CallInst *CI = dyn_cast<CallInst>(Inst))
112       return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
113     return isa<CastInst>(Inst) || isa<UnaryOperator>(Inst) ||
114            isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) ||
115            isa<CmpInst>(Inst) || isa<SelectInst>(Inst) ||
116            isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
117            isa<ShuffleVectorInst>(Inst) || isa<ExtractValueInst>(Inst) ||
118            isa<InsertValueInst>(Inst) || isa<FreezeInst>(Inst);
119   }
120 };
121 
122 } // end anonymous namespace
123 
124 namespace llvm {
125 
126 template <> struct DenseMapInfo<SimpleValue> {
127   static inline SimpleValue getEmptyKey() {
128     return DenseMapInfo<Instruction *>::getEmptyKey();
129   }
130 
131   static inline SimpleValue getTombstoneKey() {
132     return DenseMapInfo<Instruction *>::getTombstoneKey();
133   }
134 
135   static unsigned getHashValue(SimpleValue Val);
136   static bool isEqual(SimpleValue LHS, SimpleValue RHS);
137 };
138 
139 } // end namespace llvm
140 
141 /// Match a 'select' including an optional 'not's of the condition.
142 static bool matchSelectWithOptionalNotCond(Value *V, Value *&Cond, Value *&A,
143                                            Value *&B,
144                                            SelectPatternFlavor &Flavor) {
145   // Return false if V is not even a select.
146   if (!match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))))
147     return false;
148 
149   // Look through a 'not' of the condition operand by swapping A/B.
150   Value *CondNot;
151   if (match(Cond, m_Not(m_Value(CondNot)))) {
152     Cond = CondNot;
153     std::swap(A, B);
154   }
155 
156   // Match canonical forms of abs/nabs/min/max. We are not using ValueTracking's
157   // more powerful matchSelectPattern() because it may rely on instruction flags
158   // such as "nsw". That would be incompatible with the current hashing
159   // mechanism that may remove flags to increase the likelihood of CSE.
160 
161   // These are the canonical forms of abs(X) and nabs(X) created by instcombine:
162   // %N = sub i32 0, %X
163   // %C = icmp slt i32 %X, 0
164   // %ABS = select i1 %C, i32 %N, i32 %X
165   //
166   // %N = sub i32 0, %X
167   // %C = icmp slt i32 %X, 0
168   // %NABS = select i1 %C, i32 %X, i32 %N
169   Flavor = SPF_UNKNOWN;
170   CmpInst::Predicate Pred;
171   if (match(Cond, m_ICmp(Pred, m_Specific(B), m_ZeroInt())) &&
172       Pred == ICmpInst::ICMP_SLT && match(A, m_Neg(m_Specific(B)))) {
173     // ABS: B < 0 ? -B : B
174     Flavor = SPF_ABS;
175     return true;
176   }
177   if (match(Cond, m_ICmp(Pred, m_Specific(A), m_ZeroInt())) &&
178       Pred == ICmpInst::ICMP_SLT && match(B, m_Neg(m_Specific(A)))) {
179     // NABS: A < 0 ? A : -A
180     Flavor = SPF_NABS;
181     return true;
182   }
183 
184   if (!match(Cond, m_ICmp(Pred, m_Specific(A), m_Specific(B)))) {
185     // Check for commuted variants of min/max by swapping predicate.
186     // If we do not match the standard or commuted patterns, this is not a
187     // recognized form of min/max, but it is still a select, so return true.
188     if (!match(Cond, m_ICmp(Pred, m_Specific(B), m_Specific(A))))
189       return true;
190     Pred = ICmpInst::getSwappedPredicate(Pred);
191   }
192 
193   switch (Pred) {
194   case CmpInst::ICMP_UGT: Flavor = SPF_UMAX; break;
195   case CmpInst::ICMP_ULT: Flavor = SPF_UMIN; break;
196   case CmpInst::ICMP_SGT: Flavor = SPF_SMAX; break;
197   case CmpInst::ICMP_SLT: Flavor = SPF_SMIN; break;
198   default: break;
199   }
200 
201   return true;
202 }
203 
204 static unsigned getHashValueImpl(SimpleValue Val) {
205   Instruction *Inst = Val.Inst;
206   // Hash in all of the operands as pointers.
207   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
208     Value *LHS = BinOp->getOperand(0);
209     Value *RHS = BinOp->getOperand(1);
210     if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
211       std::swap(LHS, RHS);
212 
213     return hash_combine(BinOp->getOpcode(), LHS, RHS);
214   }
215 
216   if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
217     // Compares can be commuted by swapping the comparands and
218     // updating the predicate.  Choose the form that has the
219     // comparands in sorted order, or in the case of a tie, the
220     // one with the lower predicate.
221     Value *LHS = CI->getOperand(0);
222     Value *RHS = CI->getOperand(1);
223     CmpInst::Predicate Pred = CI->getPredicate();
224     CmpInst::Predicate SwappedPred = CI->getSwappedPredicate();
225     if (std::tie(LHS, Pred) > std::tie(RHS, SwappedPred)) {
226       std::swap(LHS, RHS);
227       Pred = SwappedPred;
228     }
229     return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
230   }
231 
232   // Hash general selects to allow matching commuted true/false operands.
233   SelectPatternFlavor SPF;
234   Value *Cond, *A, *B;
235   if (matchSelectWithOptionalNotCond(Inst, Cond, A, B, SPF)) {
236     // Hash min/max/abs (cmp + select) to allow for commuted operands.
237     // Min/max may also have non-canonical compare predicate (eg, the compare for
238     // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the
239     // compare.
240     // TODO: We should also detect FP min/max.
241     if (SPF == SPF_SMIN || SPF == SPF_SMAX ||
242         SPF == SPF_UMIN || SPF == SPF_UMAX) {
243       if (A > B)
244         std::swap(A, B);
245       return hash_combine(Inst->getOpcode(), SPF, A, B);
246     }
247     if (SPF == SPF_ABS || SPF == SPF_NABS) {
248       // ABS/NABS always puts the input in A and its negation in B.
249       return hash_combine(Inst->getOpcode(), SPF, A, B);
250     }
251 
252     // Hash general selects to allow matching commuted true/false operands.
253 
254     // If we do not have a compare as the condition, just hash in the condition.
255     CmpInst::Predicate Pred;
256     Value *X, *Y;
257     if (!match(Cond, m_Cmp(Pred, m_Value(X), m_Value(Y))))
258       return hash_combine(Inst->getOpcode(), Cond, A, B);
259 
260     // Similar to cmp normalization (above) - canonicalize the predicate value:
261     // select (icmp Pred, X, Y), A, B --> select (icmp InvPred, X, Y), B, A
262     if (CmpInst::getInversePredicate(Pred) < Pred) {
263       Pred = CmpInst::getInversePredicate(Pred);
264       std::swap(A, B);
265     }
266     return hash_combine(Inst->getOpcode(), Pred, X, Y, A, B);
267   }
268 
269   if (CastInst *CI = dyn_cast<CastInst>(Inst))
270     return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
271 
272   if (FreezeInst *FI = dyn_cast<FreezeInst>(Inst))
273     return hash_combine(FI->getOpcode(), FI->getOperand(0));
274 
275   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
276     return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
277                         hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
278 
279   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
280     return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
281                         IVI->getOperand(1),
282                         hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
283 
284   assert((isa<CallInst>(Inst) || isa<GetElementPtrInst>(Inst) ||
285           isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
286           isa<ShuffleVectorInst>(Inst) || isa<UnaryOperator>(Inst) ||
287           isa<FreezeInst>(Inst)) &&
288          "Invalid/unknown instruction");
289 
290   // Mix in the opcode.
291   return hash_combine(
292       Inst->getOpcode(),
293       hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
294 }
295 
296 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
297 #ifndef NDEBUG
298   // If -earlycse-debug-hash was specified, return a constant -- this
299   // will force all hashing to collide, so we'll exhaustively search
300   // the table for a match, and the assertion in isEqual will fire if
301   // there's a bug causing equal keys to hash differently.
302   if (EarlyCSEDebugHash)
303     return 0;
304 #endif
305   return getHashValueImpl(Val);
306 }
307 
308 static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS) {
309   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
310 
311   if (LHS.isSentinel() || RHS.isSentinel())
312     return LHSI == RHSI;
313 
314   if (LHSI->getOpcode() != RHSI->getOpcode())
315     return false;
316   if (LHSI->isIdenticalToWhenDefined(RHSI))
317     return true;
318 
319   // If we're not strictly identical, we still might be a commutable instruction
320   if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
321     if (!LHSBinOp->isCommutative())
322       return false;
323 
324     assert(isa<BinaryOperator>(RHSI) &&
325            "same opcode, but different instruction type?");
326     BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
327 
328     // Commuted equality
329     return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
330            LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
331   }
332   if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
333     assert(isa<CmpInst>(RHSI) &&
334            "same opcode, but different instruction type?");
335     CmpInst *RHSCmp = cast<CmpInst>(RHSI);
336     // Commuted equality
337     return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
338            LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
339            LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
340   }
341 
342   // Min/max/abs can occur with commuted operands, non-canonical predicates,
343   // and/or non-canonical operands.
344   // Selects can be non-trivially equivalent via inverted conditions and swaps.
345   SelectPatternFlavor LSPF, RSPF;
346   Value *CondL, *CondR, *LHSA, *RHSA, *LHSB, *RHSB;
347   if (matchSelectWithOptionalNotCond(LHSI, CondL, LHSA, LHSB, LSPF) &&
348       matchSelectWithOptionalNotCond(RHSI, CondR, RHSA, RHSB, RSPF)) {
349     if (LSPF == RSPF) {
350       // TODO: We should also detect FP min/max.
351       if (LSPF == SPF_SMIN || LSPF == SPF_SMAX ||
352           LSPF == SPF_UMIN || LSPF == SPF_UMAX)
353         return ((LHSA == RHSA && LHSB == RHSB) ||
354                 (LHSA == RHSB && LHSB == RHSA));
355 
356       if (LSPF == SPF_ABS || LSPF == SPF_NABS) {
357         // Abs results are placed in a defined order by matchSelectPattern.
358         return LHSA == RHSA && LHSB == RHSB;
359       }
360 
361       // select Cond, A, B <--> select not(Cond), B, A
362       if (CondL == CondR && LHSA == RHSA && LHSB == RHSB)
363         return true;
364     }
365 
366     // If the true/false operands are swapped and the conditions are compares
367     // with inverted predicates, the selects are equal:
368     // select (icmp Pred, X, Y), A, B <--> select (icmp InvPred, X, Y), B, A
369     //
370     // This also handles patterns with a double-negation in the sense of not +
371     // inverse, because we looked through a 'not' in the matching function and
372     // swapped A/B:
373     // select (cmp Pred, X, Y), A, B <--> select (not (cmp InvPred, X, Y)), B, A
374     //
375     // This intentionally does NOT handle patterns with a double-negation in
376     // the sense of not + not, because doing so could result in values
377     // comparing
378     // as equal that hash differently in the min/max/abs cases like:
379     // select (cmp slt, X, Y), X, Y <--> select (not (not (cmp slt, X, Y))), X, Y
380     //   ^ hashes as min                  ^ would not hash as min
381     // In the context of the EarlyCSE pass, however, such cases never reach
382     // this code, as we simplify the double-negation before hashing the second
383     // select (and so still succeed at CSEing them).
384     if (LHSA == RHSB && LHSB == RHSA) {
385       CmpInst::Predicate PredL, PredR;
386       Value *X, *Y;
387       if (match(CondL, m_Cmp(PredL, m_Value(X), m_Value(Y))) &&
388           match(CondR, m_Cmp(PredR, m_Specific(X), m_Specific(Y))) &&
389           CmpInst::getInversePredicate(PredL) == PredR)
390         return true;
391     }
392   }
393 
394   return false;
395 }
396 
397 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
398   // These comparisons are nontrivial, so assert that equality implies
399   // hash equality (DenseMap demands this as an invariant).
400   bool Result = isEqualImpl(LHS, RHS);
401   assert(!Result || (LHS.isSentinel() && LHS.Inst == RHS.Inst) ||
402          getHashValueImpl(LHS) == getHashValueImpl(RHS));
403   return Result;
404 }
405 
406 //===----------------------------------------------------------------------===//
407 // CallValue
408 //===----------------------------------------------------------------------===//
409 
410 namespace {
411 
412 /// Struct representing the available call values in the scoped hash
413 /// table.
414 struct CallValue {
415   Instruction *Inst;
416 
417   CallValue(Instruction *I) : Inst(I) {
418     assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
419   }
420 
421   bool isSentinel() const {
422     return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
423            Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
424   }
425 
426   static bool canHandle(Instruction *Inst) {
427     // Don't value number anything that returns void.
428     if (Inst->getType()->isVoidTy())
429       return false;
430 
431     CallInst *CI = dyn_cast<CallInst>(Inst);
432     if (!CI || !CI->onlyReadsMemory())
433       return false;
434     return true;
435   }
436 };
437 
438 } // end anonymous namespace
439 
440 namespace llvm {
441 
442 template <> struct DenseMapInfo<CallValue> {
443   static inline CallValue getEmptyKey() {
444     return DenseMapInfo<Instruction *>::getEmptyKey();
445   }
446 
447   static inline CallValue getTombstoneKey() {
448     return DenseMapInfo<Instruction *>::getTombstoneKey();
449   }
450 
451   static unsigned getHashValue(CallValue Val);
452   static bool isEqual(CallValue LHS, CallValue RHS);
453 };
454 
455 } // end namespace llvm
456 
457 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
458   Instruction *Inst = Val.Inst;
459   // Hash all of the operands as pointers and mix in the opcode.
460   return hash_combine(
461       Inst->getOpcode(),
462       hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
463 }
464 
465 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
466   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
467   if (LHS.isSentinel() || RHS.isSentinel())
468     return LHSI == RHSI;
469   return LHSI->isIdenticalTo(RHSI);
470 }
471 
472 //===----------------------------------------------------------------------===//
473 // EarlyCSE implementation
474 //===----------------------------------------------------------------------===//
475 
476 namespace {
477 
478 /// A simple and fast domtree-based CSE pass.
479 ///
480 /// This pass does a simple depth-first walk over the dominator tree,
481 /// eliminating trivially redundant instructions and using instsimplify to
482 /// canonicalize things as it goes. It is intended to be fast and catch obvious
483 /// cases so that instcombine and other passes are more effective. It is
484 /// expected that a later pass of GVN will catch the interesting/hard cases.
485 class EarlyCSE {
486 public:
487   const TargetLibraryInfo &TLI;
488   const TargetTransformInfo &TTI;
489   DominatorTree &DT;
490   AssumptionCache &AC;
491   const SimplifyQuery SQ;
492   MemorySSA *MSSA;
493   std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
494 
495   using AllocatorTy =
496       RecyclingAllocator<BumpPtrAllocator,
497                          ScopedHashTableVal<SimpleValue, Value *>>;
498   using ScopedHTType =
499       ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
500                       AllocatorTy>;
501 
502   /// A scoped hash table of the current values of all of our simple
503   /// scalar expressions.
504   ///
505   /// As we walk down the domtree, we look to see if instructions are in this:
506   /// if so, we replace them with what we find, otherwise we insert them so
507   /// that dominated values can succeed in their lookup.
508   ScopedHTType AvailableValues;
509 
510   /// A scoped hash table of the current values of previously encountered
511   /// memory locations.
512   ///
513   /// This allows us to get efficient access to dominating loads or stores when
514   /// we have a fully redundant load.  In addition to the most recent load, we
515   /// keep track of a generation count of the read, which is compared against
516   /// the current generation count.  The current generation count is incremented
517   /// after every possibly writing memory operation, which ensures that we only
518   /// CSE loads with other loads that have no intervening store.  Ordering
519   /// events (such as fences or atomic instructions) increment the generation
520   /// count as well; essentially, we model these as writes to all possible
521   /// locations.  Note that atomic and/or volatile loads and stores can be
522   /// present the table; it is the responsibility of the consumer to inspect
523   /// the atomicity/volatility if needed.
524   struct LoadValue {
525     Instruction *DefInst = nullptr;
526     unsigned Generation = 0;
527     int MatchingId = -1;
528     bool IsAtomic = false;
529 
530     LoadValue() = default;
531     LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
532               bool IsAtomic)
533         : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
534           IsAtomic(IsAtomic) {}
535   };
536 
537   using LoadMapAllocator =
538       RecyclingAllocator<BumpPtrAllocator,
539                          ScopedHashTableVal<Value *, LoadValue>>;
540   using LoadHTType =
541       ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
542                       LoadMapAllocator>;
543 
544   LoadHTType AvailableLoads;
545 
546   // A scoped hash table mapping memory locations (represented as typed
547   // addresses) to generation numbers at which that memory location became
548   // (henceforth indefinitely) invariant.
549   using InvariantMapAllocator =
550       RecyclingAllocator<BumpPtrAllocator,
551                          ScopedHashTableVal<MemoryLocation, unsigned>>;
552   using InvariantHTType =
553       ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
554                       InvariantMapAllocator>;
555   InvariantHTType AvailableInvariants;
556 
557   /// A scoped hash table of the current values of read-only call
558   /// values.
559   ///
560   /// It uses the same generation count as loads.
561   using CallHTType =
562       ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
563   CallHTType AvailableCalls;
564 
565   /// This is the current generation of the memory value.
566   unsigned CurrentGeneration = 0;
567 
568   /// Set up the EarlyCSE runner for a particular function.
569   EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
570            const TargetTransformInfo &TTI, DominatorTree &DT,
571            AssumptionCache &AC, MemorySSA *MSSA)
572       : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
573         MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {}
574 
575   bool run();
576 
577 private:
578   unsigned ClobberCounter = 0;
579   // Almost a POD, but needs to call the constructors for the scoped hash
580   // tables so that a new scope gets pushed on. These are RAII so that the
581   // scope gets popped when the NodeScope is destroyed.
582   class NodeScope {
583   public:
584     NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
585               InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls)
586       : Scope(AvailableValues), LoadScope(AvailableLoads),
587         InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {}
588     NodeScope(const NodeScope &) = delete;
589     NodeScope &operator=(const NodeScope &) = delete;
590 
591   private:
592     ScopedHTType::ScopeTy Scope;
593     LoadHTType::ScopeTy LoadScope;
594     InvariantHTType::ScopeTy InvariantScope;
595     CallHTType::ScopeTy CallScope;
596   };
597 
598   // Contains all the needed information to create a stack for doing a depth
599   // first traversal of the tree. This includes scopes for values, loads, and
600   // calls as well as the generation. There is a child iterator so that the
601   // children do not need to be store separately.
602   class StackNode {
603   public:
604     StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
605               InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
606               unsigned cg, DomTreeNode *n, DomTreeNode::iterator child,
607               DomTreeNode::iterator end)
608         : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
609           EndIter(end),
610           Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
611                  AvailableCalls)
612           {}
613     StackNode(const StackNode &) = delete;
614     StackNode &operator=(const StackNode &) = delete;
615 
616     // Accessors.
617     unsigned currentGeneration() { return CurrentGeneration; }
618     unsigned childGeneration() { return ChildGeneration; }
619     void childGeneration(unsigned generation) { ChildGeneration = generation; }
620     DomTreeNode *node() { return Node; }
621     DomTreeNode::iterator childIter() { return ChildIter; }
622 
623     DomTreeNode *nextChild() {
624       DomTreeNode *child = *ChildIter;
625       ++ChildIter;
626       return child;
627     }
628 
629     DomTreeNode::iterator end() { return EndIter; }
630     bool isProcessed() { return Processed; }
631     void process() { Processed = true; }
632 
633   private:
634     unsigned CurrentGeneration;
635     unsigned ChildGeneration;
636     DomTreeNode *Node;
637     DomTreeNode::iterator ChildIter;
638     DomTreeNode::iterator EndIter;
639     NodeScope Scopes;
640     bool Processed = false;
641   };
642 
643   /// Wrapper class to handle memory instructions, including loads,
644   /// stores and intrinsic loads and stores defined by the target.
645   class ParseMemoryInst {
646   public:
647     ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
648       : Inst(Inst) {
649       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
650         if (TTI.getTgtMemIntrinsic(II, Info))
651           IsTargetMemInst = true;
652     }
653 
654     bool isLoad() const {
655       if (IsTargetMemInst) return Info.ReadMem;
656       return isa<LoadInst>(Inst);
657     }
658 
659     bool isStore() const {
660       if (IsTargetMemInst) return Info.WriteMem;
661       return isa<StoreInst>(Inst);
662     }
663 
664     bool isAtomic() const {
665       if (IsTargetMemInst)
666         return Info.Ordering != AtomicOrdering::NotAtomic;
667       return Inst->isAtomic();
668     }
669 
670     bool isUnordered() const {
671       if (IsTargetMemInst)
672         return Info.isUnordered();
673 
674       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
675         return LI->isUnordered();
676       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
677         return SI->isUnordered();
678       }
679       // Conservative answer
680       return !Inst->isAtomic();
681     }
682 
683     bool isVolatile() const {
684       if (IsTargetMemInst)
685         return Info.IsVolatile;
686 
687       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
688         return LI->isVolatile();
689       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
690         return SI->isVolatile();
691       }
692       // Conservative answer
693       return true;
694     }
695 
696     bool isInvariantLoad() const {
697       if (auto *LI = dyn_cast<LoadInst>(Inst))
698         return LI->hasMetadata(LLVMContext::MD_invariant_load);
699       return false;
700     }
701 
702     bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
703       return (getPointerOperand() == Inst.getPointerOperand() &&
704               getMatchingId() == Inst.getMatchingId());
705     }
706 
707     bool isValid() const { return getPointerOperand() != nullptr; }
708 
709     // For regular (non-intrinsic) loads/stores, this is set to -1. For
710     // intrinsic loads/stores, the id is retrieved from the corresponding
711     // field in the MemIntrinsicInfo structure.  That field contains
712     // non-negative values only.
713     int getMatchingId() const {
714       if (IsTargetMemInst) return Info.MatchingId;
715       return -1;
716     }
717 
718     Value *getPointerOperand() const {
719       if (IsTargetMemInst) return Info.PtrVal;
720       return getLoadStorePointerOperand(Inst);
721     }
722 
723     bool mayReadFromMemory() const {
724       if (IsTargetMemInst) return Info.ReadMem;
725       return Inst->mayReadFromMemory();
726     }
727 
728     bool mayWriteToMemory() const {
729       if (IsTargetMemInst) return Info.WriteMem;
730       return Inst->mayWriteToMemory();
731     }
732 
733   private:
734     bool IsTargetMemInst = false;
735     MemIntrinsicInfo Info;
736     Instruction *Inst;
737   };
738 
739   bool processNode(DomTreeNode *Node);
740 
741   bool handleBranchCondition(Instruction *CondInst, const BranchInst *BI,
742                              const BasicBlock *BB, const BasicBlock *Pred);
743 
744   Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
745     if (auto *LI = dyn_cast<LoadInst>(Inst))
746       return LI;
747     if (auto *SI = dyn_cast<StoreInst>(Inst))
748       return SI->getValueOperand();
749     assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
750     return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
751                                                  ExpectedType);
752   }
753 
754   /// Return true if the instruction is known to only operate on memory
755   /// provably invariant in the given "generation".
756   bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
757 
758   bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
759                            Instruction *EarlierInst, Instruction *LaterInst);
760 
761   void removeMSSA(Instruction &Inst) {
762     if (!MSSA)
763       return;
764     if (VerifyMemorySSA)
765       MSSA->verifyMemorySSA();
766     // Removing a store here can leave MemorySSA in an unoptimized state by
767     // creating MemoryPhis that have identical arguments and by creating
768     // MemoryUses whose defining access is not an actual clobber. The phi case
769     // is handled by MemorySSA when passing OptimizePhis = true to
770     // removeMemoryAccess.  The non-optimized MemoryUse case is lazily updated
771     // by MemorySSA's getClobberingMemoryAccess.
772     MSSAUpdater->removeMemoryAccess(&Inst, true);
773   }
774 };
775 
776 } // end anonymous namespace
777 
778 /// Determine if the memory referenced by LaterInst is from the same heap
779 /// version as EarlierInst.
780 /// This is currently called in two scenarios:
781 ///
782 ///   load p
783 ///   ...
784 ///   load p
785 ///
786 /// and
787 ///
788 ///   x = load p
789 ///   ...
790 ///   store x, p
791 ///
792 /// in both cases we want to verify that there are no possible writes to the
793 /// memory referenced by p between the earlier and later instruction.
794 bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
795                                    unsigned LaterGeneration,
796                                    Instruction *EarlierInst,
797                                    Instruction *LaterInst) {
798   // Check the simple memory generation tracking first.
799   if (EarlierGeneration == LaterGeneration)
800     return true;
801 
802   if (!MSSA)
803     return false;
804 
805   // If MemorySSA has determined that one of EarlierInst or LaterInst does not
806   // read/write memory, then we can safely return true here.
807   // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
808   // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
809   // by also checking the MemorySSA MemoryAccess on the instruction.  Initial
810   // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
811   // with the default optimization pipeline.
812   auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
813   if (!EarlierMA)
814     return true;
815   auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
816   if (!LaterMA)
817     return true;
818 
819   // Since we know LaterDef dominates LaterInst and EarlierInst dominates
820   // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
821   // EarlierInst and LaterInst and neither can any other write that potentially
822   // clobbers LaterInst.
823   MemoryAccess *LaterDef;
824   if (ClobberCounter < EarlyCSEMssaOptCap) {
825     LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
826     ClobberCounter++;
827   } else
828     LaterDef = LaterMA->getDefiningAccess();
829 
830   return MSSA->dominates(LaterDef, EarlierMA);
831 }
832 
833 bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
834   // A location loaded from with an invariant_load is assumed to *never* change
835   // within the visible scope of the compilation.
836   if (auto *LI = dyn_cast<LoadInst>(I))
837     if (LI->hasMetadata(LLVMContext::MD_invariant_load))
838       return true;
839 
840   auto MemLocOpt = MemoryLocation::getOrNone(I);
841   if (!MemLocOpt)
842     // "target" intrinsic forms of loads aren't currently known to
843     // MemoryLocation::get.  TODO
844     return false;
845   MemoryLocation MemLoc = *MemLocOpt;
846   if (!AvailableInvariants.count(MemLoc))
847     return false;
848 
849   // Is the generation at which this became invariant older than the
850   // current one?
851   return AvailableInvariants.lookup(MemLoc) <= GenAt;
852 }
853 
854 bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
855                                      const BranchInst *BI, const BasicBlock *BB,
856                                      const BasicBlock *Pred) {
857   assert(BI->isConditional() && "Should be a conditional branch!");
858   assert(BI->getCondition() == CondInst && "Wrong condition?");
859   assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
860   auto *TorF = (BI->getSuccessor(0) == BB)
861                    ? ConstantInt::getTrue(BB->getContext())
862                    : ConstantInt::getFalse(BB->getContext());
863   auto MatchBinOp = [](Instruction *I, unsigned Opcode) {
864     if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I))
865       return BOp->getOpcode() == Opcode;
866     return false;
867   };
868   // If the condition is AND operation, we can propagate its operands into the
869   // true branch. If it is OR operation, we can propagate them into the false
870   // branch.
871   unsigned PropagateOpcode =
872       (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
873 
874   bool MadeChanges = false;
875   SmallVector<Instruction *, 4> WorkList;
876   SmallPtrSet<Instruction *, 4> Visited;
877   WorkList.push_back(CondInst);
878   while (!WorkList.empty()) {
879     Instruction *Curr = WorkList.pop_back_val();
880 
881     AvailableValues.insert(Curr, TorF);
882     LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
883                       << Curr->getName() << "' as " << *TorF << " in "
884                       << BB->getName() << "\n");
885     if (!DebugCounter::shouldExecute(CSECounter)) {
886       LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
887     } else {
888       // Replace all dominated uses with the known value.
889       if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
890                                                     BasicBlockEdge(Pred, BB))) {
891         NumCSECVP += Count;
892         MadeChanges = true;
893       }
894     }
895 
896     if (MatchBinOp(Curr, PropagateOpcode))
897       for (auto &Op : cast<BinaryOperator>(Curr)->operands())
898         if (Instruction *OPI = dyn_cast<Instruction>(Op))
899           if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
900             WorkList.push_back(OPI);
901   }
902 
903   return MadeChanges;
904 }
905 
906 bool EarlyCSE::processNode(DomTreeNode *Node) {
907   bool Changed = false;
908   BasicBlock *BB = Node->getBlock();
909 
910   // If this block has a single predecessor, then the predecessor is the parent
911   // of the domtree node and all of the live out memory values are still current
912   // in this block.  If this block has multiple predecessors, then they could
913   // have invalidated the live-out memory values of our parent value.  For now,
914   // just be conservative and invalidate memory if this block has multiple
915   // predecessors.
916   if (!BB->getSinglePredecessor())
917     ++CurrentGeneration;
918 
919   // If this node has a single predecessor which ends in a conditional branch,
920   // we can infer the value of the branch condition given that we took this
921   // path.  We need the single predecessor to ensure there's not another path
922   // which reaches this block where the condition might hold a different
923   // value.  Since we're adding this to the scoped hash table (like any other
924   // def), it will have been popped if we encounter a future merge block.
925   if (BasicBlock *Pred = BB->getSinglePredecessor()) {
926     auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
927     if (BI && BI->isConditional()) {
928       auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
929       if (CondInst && SimpleValue::canHandle(CondInst))
930         Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
931     }
932   }
933 
934   /// LastStore - Keep track of the last non-volatile store that we saw... for
935   /// as long as there in no instruction that reads memory.  If we see a store
936   /// to the same location, we delete the dead store.  This zaps trivial dead
937   /// stores which can occur in bitfield code among other things.
938   Instruction *LastStore = nullptr;
939 
940   // See if any instructions in the block can be eliminated.  If so, do it.  If
941   // not, add them to AvailableValues.
942   for (Instruction &Inst : make_early_inc_range(BB->getInstList())) {
943     // Dead instructions should just be removed.
944     if (isInstructionTriviallyDead(&Inst, &TLI)) {
945       LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << Inst << '\n');
946       if (!DebugCounter::shouldExecute(CSECounter)) {
947         LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
948         continue;
949       }
950 
951       salvageKnowledge(&Inst);
952       salvageDebugInfoOrMarkUndef(Inst);
953       removeMSSA(Inst);
954       Inst.eraseFromParent();
955       Changed = true;
956       ++NumSimplify;
957       continue;
958     }
959 
960     // Skip assume intrinsics, they don't really have side effects (although
961     // they're marked as such to ensure preservation of control dependencies),
962     // and this pass will not bother with its removal. However, we should mark
963     // its condition as true for all dominated blocks.
964     if (match(&Inst, m_Intrinsic<Intrinsic::assume>())) {
965       auto *CondI =
966           dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0));
967       if (CondI && SimpleValue::canHandle(CondI)) {
968         LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << Inst
969                           << '\n');
970         AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
971       } else
972         LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << Inst << '\n');
973       continue;
974     }
975 
976     // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
977     if (match(&Inst, m_Intrinsic<Intrinsic::sideeffect>())) {
978       LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << Inst << '\n');
979       continue;
980     }
981 
982     // We can skip all invariant.start intrinsics since they only read memory,
983     // and we can forward values across it. For invariant starts without
984     // invariant ends, we can use the fact that the invariantness never ends to
985     // start a scope in the current generaton which is true for all future
986     // generations.  Also, we dont need to consume the last store since the
987     // semantics of invariant.start allow us to perform   DSE of the last
988     // store, if there was a store following invariant.start. Consider:
989     //
990     // store 30, i8* p
991     // invariant.start(p)
992     // store 40, i8* p
993     // We can DSE the store to 30, since the store 40 to invariant location p
994     // causes undefined behaviour.
995     if (match(&Inst, m_Intrinsic<Intrinsic::invariant_start>())) {
996       // If there are any uses, the scope might end.
997       if (!Inst.use_empty())
998         continue;
999       MemoryLocation MemLoc =
1000           MemoryLocation::getForArgument(&cast<CallInst>(Inst), 1, TLI);
1001       // Don't start a scope if we already have a better one pushed
1002       if (!AvailableInvariants.count(MemLoc))
1003         AvailableInvariants.insert(MemLoc, CurrentGeneration);
1004       continue;
1005     }
1006 
1007     if (isGuard(&Inst)) {
1008       if (auto *CondI =
1009               dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0))) {
1010         if (SimpleValue::canHandle(CondI)) {
1011           // Do we already know the actual value of this condition?
1012           if (auto *KnownCond = AvailableValues.lookup(CondI)) {
1013             // Is the condition known to be true?
1014             if (isa<ConstantInt>(KnownCond) &&
1015                 cast<ConstantInt>(KnownCond)->isOne()) {
1016               LLVM_DEBUG(dbgs()
1017                          << "EarlyCSE removing guard: " << Inst << '\n');
1018               salvageKnowledge(&Inst);
1019               removeMSSA(Inst);
1020               Inst.eraseFromParent();
1021               Changed = true;
1022               continue;
1023             } else
1024               // Use the known value if it wasn't true.
1025               cast<CallInst>(Inst).setArgOperand(0, KnownCond);
1026           }
1027           // The condition we're on guarding here is true for all dominated
1028           // locations.
1029           AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
1030         }
1031       }
1032 
1033       // Guard intrinsics read all memory, but don't write any memory.
1034       // Accordingly, don't update the generation but consume the last store (to
1035       // avoid an incorrect DSE).
1036       LastStore = nullptr;
1037       continue;
1038     }
1039 
1040     // If the instruction can be simplified (e.g. X+0 = X) then replace it with
1041     // its simpler value.
1042     if (Value *V = SimplifyInstruction(&Inst, SQ)) {
1043       LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << Inst << "  to: " << *V
1044                         << '\n');
1045       if (!DebugCounter::shouldExecute(CSECounter)) {
1046         LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1047       } else {
1048         bool Killed = false;
1049         if (!Inst.use_empty()) {
1050           Inst.replaceAllUsesWith(V);
1051           Changed = true;
1052         }
1053         if (isInstructionTriviallyDead(&Inst, &TLI)) {
1054           salvageKnowledge(&Inst);
1055           removeMSSA(Inst);
1056           Inst.eraseFromParent();
1057           Changed = true;
1058           Killed = true;
1059         }
1060         if (Changed)
1061           ++NumSimplify;
1062         if (Killed)
1063           continue;
1064       }
1065     }
1066 
1067     // If this is a simple instruction that we can value number, process it.
1068     if (SimpleValue::canHandle(&Inst)) {
1069       // See if the instruction has an available value.  If so, use it.
1070       if (Value *V = AvailableValues.lookup(&Inst)) {
1071         LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << Inst << "  to: " << *V
1072                           << '\n');
1073         if (!DebugCounter::shouldExecute(CSECounter)) {
1074           LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1075           continue;
1076         }
1077         if (auto *I = dyn_cast<Instruction>(V))
1078           I->andIRFlags(&Inst);
1079         Inst.replaceAllUsesWith(V);
1080         salvageKnowledge(&Inst);
1081         removeMSSA(Inst);
1082         Inst.eraseFromParent();
1083         Changed = true;
1084         ++NumCSE;
1085         continue;
1086       }
1087 
1088       // Otherwise, just remember that this value is available.
1089       AvailableValues.insert(&Inst, &Inst);
1090       continue;
1091     }
1092 
1093     ParseMemoryInst MemInst(&Inst, TTI);
1094     // If this is a non-volatile load, process it.
1095     if (MemInst.isValid() && MemInst.isLoad()) {
1096       // (conservatively) we can't peak past the ordering implied by this
1097       // operation, but we can add this load to our set of available values
1098       if (MemInst.isVolatile() || !MemInst.isUnordered()) {
1099         LastStore = nullptr;
1100         ++CurrentGeneration;
1101       }
1102 
1103       if (MemInst.isInvariantLoad()) {
1104         // If we pass an invariant load, we know that memory location is
1105         // indefinitely constant from the moment of first dereferenceability.
1106         // We conservatively treat the invariant_load as that moment.  If we
1107         // pass a invariant load after already establishing a scope, don't
1108         // restart it since we want to preserve the earliest point seen.
1109         auto MemLoc = MemoryLocation::get(&Inst);
1110         if (!AvailableInvariants.count(MemLoc))
1111           AvailableInvariants.insert(MemLoc, CurrentGeneration);
1112       }
1113 
1114       // If we have an available version of this load, and if it is the right
1115       // generation or the load is known to be from an invariant location,
1116       // replace this instruction.
1117       //
1118       // If either the dominating load or the current load are invariant, then
1119       // we can assume the current load loads the same value as the dominating
1120       // load.
1121       LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1122       if (InVal.DefInst != nullptr &&
1123           InVal.MatchingId == MemInst.getMatchingId() &&
1124           // We don't yet handle removing loads with ordering of any kind.
1125           !MemInst.isVolatile() && MemInst.isUnordered() &&
1126           // We can't replace an atomic load with one which isn't also atomic.
1127           InVal.IsAtomic >= MemInst.isAtomic() &&
1128           (isOperatingOnInvariantMemAt(&Inst, InVal.Generation) ||
1129            isSameMemGeneration(InVal.Generation, CurrentGeneration,
1130                                InVal.DefInst, &Inst))) {
1131         Value *Op = getOrCreateResult(InVal.DefInst, Inst.getType());
1132         if (Op != nullptr) {
1133           LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << Inst
1134                             << "  to: " << *InVal.DefInst << '\n');
1135           if (!DebugCounter::shouldExecute(CSECounter)) {
1136             LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1137             continue;
1138           }
1139           if (!Inst.use_empty())
1140             Inst.replaceAllUsesWith(Op);
1141           salvageKnowledge(&Inst);
1142           removeMSSA(Inst);
1143           Inst.eraseFromParent();
1144           Changed = true;
1145           ++NumCSELoad;
1146           continue;
1147         }
1148       }
1149 
1150       // Otherwise, remember that we have this instruction.
1151       AvailableLoads.insert(MemInst.getPointerOperand(),
1152                             LoadValue(&Inst, CurrentGeneration,
1153                                       MemInst.getMatchingId(),
1154                                       MemInst.isAtomic()));
1155       LastStore = nullptr;
1156       continue;
1157     }
1158 
1159     // If this instruction may read from memory or throw (and potentially read
1160     // from memory in the exception handler), forget LastStore.  Load/store
1161     // intrinsics will indicate both a read and a write to memory.  The target
1162     // may override this (e.g. so that a store intrinsic does not read from
1163     // memory, and thus will be treated the same as a regular store for
1164     // commoning purposes).
1165     if ((Inst.mayReadFromMemory() || Inst.mayThrow()) &&
1166         !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
1167       LastStore = nullptr;
1168 
1169     // If this is a read-only call, process it.
1170     if (CallValue::canHandle(&Inst)) {
1171       // If we have an available version of this call, and if it is the right
1172       // generation, replace this instruction.
1173       std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(&Inst);
1174       if (InVal.first != nullptr &&
1175           isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
1176                               &Inst)) {
1177         LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << Inst
1178                           << "  to: " << *InVal.first << '\n');
1179         if (!DebugCounter::shouldExecute(CSECounter)) {
1180           LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1181           continue;
1182         }
1183         if (!Inst.use_empty())
1184           Inst.replaceAllUsesWith(InVal.first);
1185         salvageKnowledge(&Inst);
1186         removeMSSA(Inst);
1187         Inst.eraseFromParent();
1188         Changed = true;
1189         ++NumCSECall;
1190         continue;
1191       }
1192 
1193       // Otherwise, remember that we have this instruction.
1194       AvailableCalls.insert(&Inst, std::make_pair(&Inst, CurrentGeneration));
1195       continue;
1196     }
1197 
1198     // A release fence requires that all stores complete before it, but does
1199     // not prevent the reordering of following loads 'before' the fence.  As a
1200     // result, we don't need to consider it as writing to memory and don't need
1201     // to advance the generation.  We do need to prevent DSE across the fence,
1202     // but that's handled above.
1203     if (auto *FI = dyn_cast<FenceInst>(&Inst))
1204       if (FI->getOrdering() == AtomicOrdering::Release) {
1205         assert(Inst.mayReadFromMemory() && "relied on to prevent DSE above");
1206         continue;
1207       }
1208 
1209     // write back DSE - If we write back the same value we just loaded from
1210     // the same location and haven't passed any intervening writes or ordering
1211     // operations, we can remove the write.  The primary benefit is in allowing
1212     // the available load table to remain valid and value forward past where
1213     // the store originally was.
1214     if (MemInst.isValid() && MemInst.isStore()) {
1215       LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1216       if (InVal.DefInst &&
1217           InVal.DefInst == getOrCreateResult(&Inst, InVal.DefInst->getType()) &&
1218           InVal.MatchingId == MemInst.getMatchingId() &&
1219           // We don't yet handle removing stores with ordering of any kind.
1220           !MemInst.isVolatile() && MemInst.isUnordered() &&
1221           (isOperatingOnInvariantMemAt(&Inst, InVal.Generation) ||
1222            isSameMemGeneration(InVal.Generation, CurrentGeneration,
1223                                InVal.DefInst, &Inst))) {
1224         // It is okay to have a LastStore to a different pointer here if MemorySSA
1225         // tells us that the load and store are from the same memory generation.
1226         // In that case, LastStore should keep its present value since we're
1227         // removing the current store.
1228         assert((!LastStore ||
1229                 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
1230                     MemInst.getPointerOperand() ||
1231                 MSSA) &&
1232                "can't have an intervening store if not using MemorySSA!");
1233         LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << Inst << '\n');
1234         if (!DebugCounter::shouldExecute(CSECounter)) {
1235           LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1236           continue;
1237         }
1238         salvageKnowledge(&Inst);
1239         removeMSSA(Inst);
1240         Inst.eraseFromParent();
1241         Changed = true;
1242         ++NumDSE;
1243         // We can avoid incrementing the generation count since we were able
1244         // to eliminate this store.
1245         continue;
1246       }
1247     }
1248 
1249     // Okay, this isn't something we can CSE at all.  Check to see if it is
1250     // something that could modify memory.  If so, our available memory values
1251     // cannot be used so bump the generation count.
1252     if (Inst.mayWriteToMemory()) {
1253       ++CurrentGeneration;
1254 
1255       if (MemInst.isValid() && MemInst.isStore()) {
1256         // We do a trivial form of DSE if there are two stores to the same
1257         // location with no intervening loads.  Delete the earlier store.
1258         // At the moment, we don't remove ordered stores, but do remove
1259         // unordered atomic stores.  There's no special requirement (for
1260         // unordered atomics) about removing atomic stores only in favor of
1261         // other atomic stores since we were going to execute the non-atomic
1262         // one anyway and the atomic one might never have become visible.
1263         if (LastStore) {
1264           ParseMemoryInst LastStoreMemInst(LastStore, TTI);
1265           assert(LastStoreMemInst.isUnordered() &&
1266                  !LastStoreMemInst.isVolatile() &&
1267                  "Violated invariant");
1268           if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
1269             LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
1270                               << "  due to: " << Inst << '\n');
1271             if (!DebugCounter::shouldExecute(CSECounter)) {
1272               LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1273             } else {
1274               salvageKnowledge(&Inst);
1275               removeMSSA(*LastStore);
1276               LastStore->eraseFromParent();
1277               Changed = true;
1278               ++NumDSE;
1279               LastStore = nullptr;
1280             }
1281           }
1282           // fallthrough - we can exploit information about this store
1283         }
1284 
1285         // Okay, we just invalidated anything we knew about loaded values.  Try
1286         // to salvage *something* by remembering that the stored value is a live
1287         // version of the pointer.  It is safe to forward from volatile stores
1288         // to non-volatile loads, so we don't have to check for volatility of
1289         // the store.
1290         AvailableLoads.insert(MemInst.getPointerOperand(),
1291                               LoadValue(&Inst, CurrentGeneration,
1292                                         MemInst.getMatchingId(),
1293                                         MemInst.isAtomic()));
1294 
1295         // Remember that this was the last unordered store we saw for DSE. We
1296         // don't yet handle DSE on ordered or volatile stores since we don't
1297         // have a good way to model the ordering requirement for following
1298         // passes  once the store is removed.  We could insert a fence, but
1299         // since fences are slightly stronger than stores in their ordering,
1300         // it's not clear this is a profitable transform. Another option would
1301         // be to merge the ordering with that of the post dominating store.
1302         if (MemInst.isUnordered() && !MemInst.isVolatile())
1303           LastStore = &Inst;
1304         else
1305           LastStore = nullptr;
1306       }
1307     }
1308   }
1309 
1310   return Changed;
1311 }
1312 
1313 bool EarlyCSE::run() {
1314   // Note, deque is being used here because there is significant performance
1315   // gains over vector when the container becomes very large due to the
1316   // specific access patterns. For more information see the mailing list
1317   // discussion on this:
1318   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
1319   std::deque<StackNode *> nodesToProcess;
1320 
1321   bool Changed = false;
1322 
1323   // Process the root node.
1324   nodesToProcess.push_back(new StackNode(
1325       AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1326       CurrentGeneration, DT.getRootNode(),
1327       DT.getRootNode()->begin(), DT.getRootNode()->end()));
1328 
1329   assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it.");
1330 
1331   // Process the stack.
1332   while (!nodesToProcess.empty()) {
1333     // Grab the first item off the stack. Set the current generation, remove
1334     // the node from the stack, and process it.
1335     StackNode *NodeToProcess = nodesToProcess.back();
1336 
1337     // Initialize class members.
1338     CurrentGeneration = NodeToProcess->currentGeneration();
1339 
1340     // Check if the node needs to be processed.
1341     if (!NodeToProcess->isProcessed()) {
1342       // Process the node.
1343       Changed |= processNode(NodeToProcess->node());
1344       NodeToProcess->childGeneration(CurrentGeneration);
1345       NodeToProcess->process();
1346     } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
1347       // Push the next child onto the stack.
1348       DomTreeNode *child = NodeToProcess->nextChild();
1349       nodesToProcess.push_back(
1350           new StackNode(AvailableValues, AvailableLoads, AvailableInvariants,
1351                         AvailableCalls, NodeToProcess->childGeneration(),
1352                         child, child->begin(), child->end()));
1353     } else {
1354       // It has been processed, and there are no more children to process,
1355       // so delete it and pop it off the stack.
1356       delete NodeToProcess;
1357       nodesToProcess.pop_back();
1358     }
1359   } // while (!nodes...)
1360 
1361   return Changed;
1362 }
1363 
1364 PreservedAnalyses EarlyCSEPass::run(Function &F,
1365                                     FunctionAnalysisManager &AM) {
1366   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1367   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1368   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1369   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1370   auto *MSSA =
1371       UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
1372 
1373   EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
1374 
1375   if (!CSE.run())
1376     return PreservedAnalyses::all();
1377 
1378   PreservedAnalyses PA;
1379   PA.preserveSet<CFGAnalyses>();
1380   PA.preserve<GlobalsAA>();
1381   if (UseMemorySSA)
1382     PA.preserve<MemorySSAAnalysis>();
1383   return PA;
1384 }
1385 
1386 namespace {
1387 
1388 /// A simple and fast domtree-based CSE pass.
1389 ///
1390 /// This pass does a simple depth-first walk over the dominator tree,
1391 /// eliminating trivially redundant instructions and using instsimplify to
1392 /// canonicalize things as it goes. It is intended to be fast and catch obvious
1393 /// cases so that instcombine and other passes are more effective. It is
1394 /// expected that a later pass of GVN will catch the interesting/hard cases.
1395 template<bool UseMemorySSA>
1396 class EarlyCSELegacyCommonPass : public FunctionPass {
1397 public:
1398   static char ID;
1399 
1400   EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1401     if (UseMemorySSA)
1402       initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
1403     else
1404       initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
1405   }
1406 
1407   bool runOnFunction(Function &F) override {
1408     if (skipFunction(F))
1409       return false;
1410 
1411     auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1412     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1413     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1414     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1415     auto *MSSA =
1416         UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
1417 
1418     EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
1419 
1420     return CSE.run();
1421   }
1422 
1423   void getAnalysisUsage(AnalysisUsage &AU) const override {
1424     AU.addRequired<AssumptionCacheTracker>();
1425     AU.addRequired<DominatorTreeWrapperPass>();
1426     AU.addRequired<TargetLibraryInfoWrapperPass>();
1427     AU.addRequired<TargetTransformInfoWrapperPass>();
1428     if (UseMemorySSA) {
1429       AU.addRequired<MemorySSAWrapperPass>();
1430       AU.addPreserved<MemorySSAWrapperPass>();
1431     }
1432     AU.addPreserved<GlobalsAAWrapperPass>();
1433     AU.addPreserved<AAResultsWrapperPass>();
1434     AU.setPreservesCFG();
1435   }
1436 };
1437 
1438 } // end anonymous namespace
1439 
1440 using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
1441 
1442 template<>
1443 char EarlyCSELegacyPass::ID = 0;
1444 
1445 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1446                       false)
1447 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1448 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1449 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1450 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1451 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
1452 
1453 using EarlyCSEMemSSALegacyPass =
1454     EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1455 
1456 template<>
1457 char EarlyCSEMemSSALegacyPass::ID = 0;
1458 
1459 FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
1460   if (UseMemorySSA)
1461     return new EarlyCSEMemSSALegacyPass();
1462   else
1463     return new EarlyCSELegacyPass();
1464 }
1465 
1466 INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1467                       "Early CSE w/ MemorySSA", false, false)
1468 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1469 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1470 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1471 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1472 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1473 INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1474                     "Early CSE w/ MemorySSA", false, false)
1475