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     // Also handled are constrained intrinsic that look like the types
112     // of instruction handled below (UnaryOperator, etc.).
113     if (CallInst *CI = dyn_cast<CallInst>(Inst)) {
114       if (Function *F = CI->getCalledFunction()) {
115         switch ((Intrinsic::ID)F->getIntrinsicID()) {
116         case Intrinsic::experimental_constrained_fadd:
117         case Intrinsic::experimental_constrained_fsub:
118         case Intrinsic::experimental_constrained_fmul:
119         case Intrinsic::experimental_constrained_fdiv:
120         case Intrinsic::experimental_constrained_frem:
121         case Intrinsic::experimental_constrained_fptosi:
122         case Intrinsic::experimental_constrained_sitofp:
123         case Intrinsic::experimental_constrained_fptoui:
124         case Intrinsic::experimental_constrained_uitofp:
125         case Intrinsic::experimental_constrained_fcmp:
126         case Intrinsic::experimental_constrained_fcmps: {
127           auto *CFP = cast<ConstrainedFPIntrinsic>(CI);
128           return CFP->isDefaultFPEnvironment();
129         }
130         }
131       }
132       return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
133     }
134     return isa<CastInst>(Inst) || isa<UnaryOperator>(Inst) ||
135            isa<BinaryOperator>(Inst) || isa<GetElementPtrInst>(Inst) ||
136            isa<CmpInst>(Inst) || isa<SelectInst>(Inst) ||
137            isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
138            isa<ShuffleVectorInst>(Inst) || isa<ExtractValueInst>(Inst) ||
139            isa<InsertValueInst>(Inst) || isa<FreezeInst>(Inst);
140   }
141 };
142 
143 } // end anonymous namespace
144 
145 namespace llvm {
146 
147 template <> struct DenseMapInfo<SimpleValue> {
148   static inline SimpleValue getEmptyKey() {
149     return DenseMapInfo<Instruction *>::getEmptyKey();
150   }
151 
152   static inline SimpleValue getTombstoneKey() {
153     return DenseMapInfo<Instruction *>::getTombstoneKey();
154   }
155 
156   static unsigned getHashValue(SimpleValue Val);
157   static bool isEqual(SimpleValue LHS, SimpleValue RHS);
158 };
159 
160 } // end namespace llvm
161 
162 /// Match a 'select' including an optional 'not's of the condition.
163 static bool matchSelectWithOptionalNotCond(Value *V, Value *&Cond, Value *&A,
164                                            Value *&B,
165                                            SelectPatternFlavor &Flavor) {
166   // Return false if V is not even a select.
167   if (!match(V, m_Select(m_Value(Cond), m_Value(A), m_Value(B))))
168     return false;
169 
170   // Look through a 'not' of the condition operand by swapping A/B.
171   Value *CondNot;
172   if (match(Cond, m_Not(m_Value(CondNot)))) {
173     Cond = CondNot;
174     std::swap(A, B);
175   }
176 
177   // Match canonical forms of min/max. We are not using ValueTracking's
178   // more powerful matchSelectPattern() because it may rely on instruction flags
179   // such as "nsw". That would be incompatible with the current hashing
180   // mechanism that may remove flags to increase the likelihood of CSE.
181 
182   Flavor = SPF_UNKNOWN;
183   CmpInst::Predicate Pred;
184 
185   if (!match(Cond, m_ICmp(Pred, m_Specific(A), m_Specific(B)))) {
186     // Check for commuted variants of min/max by swapping predicate.
187     // If we do not match the standard or commuted patterns, this is not a
188     // recognized form of min/max, but it is still a select, so return true.
189     if (!match(Cond, m_ICmp(Pred, m_Specific(B), m_Specific(A))))
190       return true;
191     Pred = ICmpInst::getSwappedPredicate(Pred);
192   }
193 
194   switch (Pred) {
195   case CmpInst::ICMP_UGT: Flavor = SPF_UMAX; break;
196   case CmpInst::ICMP_ULT: Flavor = SPF_UMIN; break;
197   case CmpInst::ICMP_SGT: Flavor = SPF_SMAX; break;
198   case CmpInst::ICMP_SLT: Flavor = SPF_SMIN; break;
199   // Non-strict inequalities.
200   case CmpInst::ICMP_ULE: Flavor = SPF_UMIN; break;
201   case CmpInst::ICMP_UGE: Flavor = SPF_UMAX; break;
202   case CmpInst::ICMP_SLE: Flavor = SPF_SMIN; break;
203   case CmpInst::ICMP_SGE: Flavor = SPF_SMAX; break;
204   default: break;
205   }
206 
207   return true;
208 }
209 
210 static unsigned getHashValueImpl(SimpleValue Val) {
211   Instruction *Inst = Val.Inst;
212   // Hash in all of the operands as pointers.
213   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
214     Value *LHS = BinOp->getOperand(0);
215     Value *RHS = BinOp->getOperand(1);
216     if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
217       std::swap(LHS, RHS);
218 
219     return hash_combine(BinOp->getOpcode(), LHS, RHS);
220   }
221 
222   if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
223     // Compares can be commuted by swapping the comparands and
224     // updating the predicate.  Choose the form that has the
225     // comparands in sorted order, or in the case of a tie, the
226     // one with the lower predicate.
227     Value *LHS = CI->getOperand(0);
228     Value *RHS = CI->getOperand(1);
229     CmpInst::Predicate Pred = CI->getPredicate();
230     CmpInst::Predicate SwappedPred = CI->getSwappedPredicate();
231     if (std::tie(LHS, Pred) > std::tie(RHS, SwappedPred)) {
232       std::swap(LHS, RHS);
233       Pred = SwappedPred;
234     }
235     return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
236   }
237 
238   // Hash general selects to allow matching commuted true/false operands.
239   SelectPatternFlavor SPF;
240   Value *Cond, *A, *B;
241   if (matchSelectWithOptionalNotCond(Inst, Cond, A, B, SPF)) {
242     // Hash min/max (cmp + select) to allow for commuted operands.
243     // Min/max may also have non-canonical compare predicate (eg, the compare for
244     // smin may use 'sgt' rather than 'slt'), and non-canonical operands in the
245     // compare.
246     // TODO: We should also detect FP min/max.
247     if (SPF == SPF_SMIN || SPF == SPF_SMAX ||
248         SPF == SPF_UMIN || SPF == SPF_UMAX) {
249       if (A > B)
250         std::swap(A, B);
251       return hash_combine(Inst->getOpcode(), SPF, A, B);
252     }
253 
254     // Hash general selects to allow matching commuted true/false operands.
255 
256     // If we do not have a compare as the condition, just hash in the condition.
257     CmpInst::Predicate Pred;
258     Value *X, *Y;
259     if (!match(Cond, m_Cmp(Pred, m_Value(X), m_Value(Y))))
260       return hash_combine(Inst->getOpcode(), Cond, A, B);
261 
262     // Similar to cmp normalization (above) - canonicalize the predicate value:
263     // select (icmp Pred, X, Y), A, B --> select (icmp InvPred, X, Y), B, A
264     if (CmpInst::getInversePredicate(Pred) < Pred) {
265       Pred = CmpInst::getInversePredicate(Pred);
266       std::swap(A, B);
267     }
268     return hash_combine(Inst->getOpcode(), Pred, X, Y, A, B);
269   }
270 
271   if (CastInst *CI = dyn_cast<CastInst>(Inst))
272     return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
273 
274   if (FreezeInst *FI = dyn_cast<FreezeInst>(Inst))
275     return hash_combine(FI->getOpcode(), FI->getOperand(0));
276 
277   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
278     return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
279                         hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
280 
281   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
282     return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
283                         IVI->getOperand(1),
284                         hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
285 
286   assert((isa<CallInst>(Inst) || isa<GetElementPtrInst>(Inst) ||
287           isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
288           isa<ShuffleVectorInst>(Inst) || isa<UnaryOperator>(Inst) ||
289           isa<FreezeInst>(Inst)) &&
290          "Invalid/unknown instruction");
291 
292   // Handle intrinsics with commutative operands.
293   // TODO: Extend this to handle intrinsics with >2 operands where the 1st
294   //       2 operands are commutative.
295   auto *II = dyn_cast<IntrinsicInst>(Inst);
296   if (II && II->isCommutative() && II->arg_size() == 2) {
297     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
298     if (LHS > RHS)
299       std::swap(LHS, RHS);
300     return hash_combine(II->getOpcode(), LHS, RHS);
301   }
302 
303   // gc.relocate is 'special' call: its second and third operands are
304   // not real values, but indices into statepoint's argument list.
305   // Get values they point to.
306   if (const GCRelocateInst *GCR = dyn_cast<GCRelocateInst>(Inst))
307     return hash_combine(GCR->getOpcode(), GCR->getOperand(0),
308                         GCR->getBasePtr(), GCR->getDerivedPtr());
309 
310   // Mix in the opcode.
311   return hash_combine(
312       Inst->getOpcode(),
313       hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
314 }
315 
316 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
317 #ifndef NDEBUG
318   // If -earlycse-debug-hash was specified, return a constant -- this
319   // will force all hashing to collide, so we'll exhaustively search
320   // the table for a match, and the assertion in isEqual will fire if
321   // there's a bug causing equal keys to hash differently.
322   if (EarlyCSEDebugHash)
323     return 0;
324 #endif
325   return getHashValueImpl(Val);
326 }
327 
328 static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS) {
329   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
330 
331   if (LHS.isSentinel() || RHS.isSentinel())
332     return LHSI == RHSI;
333 
334   if (LHSI->getOpcode() != RHSI->getOpcode())
335     return false;
336   if (LHSI->isIdenticalToWhenDefined(RHSI))
337     return true;
338 
339   // If we're not strictly identical, we still might be a commutable instruction
340   if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
341     if (!LHSBinOp->isCommutative())
342       return false;
343 
344     assert(isa<BinaryOperator>(RHSI) &&
345            "same opcode, but different instruction type?");
346     BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
347 
348     // Commuted equality
349     return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
350            LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
351   }
352   if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
353     assert(isa<CmpInst>(RHSI) &&
354            "same opcode, but different instruction type?");
355     CmpInst *RHSCmp = cast<CmpInst>(RHSI);
356     // Commuted equality
357     return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
358            LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
359            LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
360   }
361 
362   // TODO: Extend this for >2 args by matching the trailing N-2 args.
363   auto *LII = dyn_cast<IntrinsicInst>(LHSI);
364   auto *RII = dyn_cast<IntrinsicInst>(RHSI);
365   if (LII && RII && LII->getIntrinsicID() == RII->getIntrinsicID() &&
366       LII->isCommutative() && LII->arg_size() == 2) {
367     return LII->getArgOperand(0) == RII->getArgOperand(1) &&
368            LII->getArgOperand(1) == RII->getArgOperand(0);
369   }
370 
371   // See comment above in `getHashValue()`.
372   if (const GCRelocateInst *GCR1 = dyn_cast<GCRelocateInst>(LHSI))
373     if (const GCRelocateInst *GCR2 = dyn_cast<GCRelocateInst>(RHSI))
374       return GCR1->getOperand(0) == GCR2->getOperand(0) &&
375              GCR1->getBasePtr() == GCR2->getBasePtr() &&
376              GCR1->getDerivedPtr() == GCR2->getDerivedPtr();
377 
378   // Min/max can occur with commuted operands, non-canonical predicates,
379   // and/or non-canonical operands.
380   // Selects can be non-trivially equivalent via inverted conditions and swaps.
381   SelectPatternFlavor LSPF, RSPF;
382   Value *CondL, *CondR, *LHSA, *RHSA, *LHSB, *RHSB;
383   if (matchSelectWithOptionalNotCond(LHSI, CondL, LHSA, LHSB, LSPF) &&
384       matchSelectWithOptionalNotCond(RHSI, CondR, RHSA, RHSB, RSPF)) {
385     if (LSPF == RSPF) {
386       // TODO: We should also detect FP min/max.
387       if (LSPF == SPF_SMIN || LSPF == SPF_SMAX ||
388           LSPF == SPF_UMIN || LSPF == SPF_UMAX)
389         return ((LHSA == RHSA && LHSB == RHSB) ||
390                 (LHSA == RHSB && LHSB == RHSA));
391 
392       // select Cond, A, B <--> select not(Cond), B, A
393       if (CondL == CondR && LHSA == RHSA && LHSB == RHSB)
394         return true;
395     }
396 
397     // If the true/false operands are swapped and the conditions are compares
398     // with inverted predicates, the selects are equal:
399     // select (icmp Pred, X, Y), A, B <--> select (icmp InvPred, X, Y), B, A
400     //
401     // This also handles patterns with a double-negation in the sense of not +
402     // inverse, because we looked through a 'not' in the matching function and
403     // swapped A/B:
404     // select (cmp Pred, X, Y), A, B <--> select (not (cmp InvPred, X, Y)), B, A
405     //
406     // This intentionally does NOT handle patterns with a double-negation in
407     // the sense of not + not, because doing so could result in values
408     // comparing
409     // as equal that hash differently in the min/max cases like:
410     // select (cmp slt, X, Y), X, Y <--> select (not (not (cmp slt, X, Y))), X, Y
411     //   ^ hashes as min                  ^ would not hash as min
412     // In the context of the EarlyCSE pass, however, such cases never reach
413     // this code, as we simplify the double-negation before hashing the second
414     // select (and so still succeed at CSEing them).
415     if (LHSA == RHSB && LHSB == RHSA) {
416       CmpInst::Predicate PredL, PredR;
417       Value *X, *Y;
418       if (match(CondL, m_Cmp(PredL, m_Value(X), m_Value(Y))) &&
419           match(CondR, m_Cmp(PredR, m_Specific(X), m_Specific(Y))) &&
420           CmpInst::getInversePredicate(PredL) == PredR)
421         return true;
422     }
423   }
424 
425   return false;
426 }
427 
428 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
429   // These comparisons are nontrivial, so assert that equality implies
430   // hash equality (DenseMap demands this as an invariant).
431   bool Result = isEqualImpl(LHS, RHS);
432   assert(!Result || (LHS.isSentinel() && LHS.Inst == RHS.Inst) ||
433          getHashValueImpl(LHS) == getHashValueImpl(RHS));
434   return Result;
435 }
436 
437 //===----------------------------------------------------------------------===//
438 // CallValue
439 //===----------------------------------------------------------------------===//
440 
441 namespace {
442 
443 /// Struct representing the available call values in the scoped hash
444 /// table.
445 struct CallValue {
446   Instruction *Inst;
447 
448   CallValue(Instruction *I) : Inst(I) {
449     assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
450   }
451 
452   bool isSentinel() const {
453     return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
454            Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
455   }
456 
457   static bool canHandle(Instruction *Inst) {
458     // Don't value number anything that returns void.
459     if (Inst->getType()->isVoidTy())
460       return false;
461 
462     CallInst *CI = dyn_cast<CallInst>(Inst);
463     if (!CI || !CI->onlyReadsMemory())
464       return false;
465     return true;
466   }
467 };
468 
469 } // end anonymous namespace
470 
471 namespace llvm {
472 
473 template <> struct DenseMapInfo<CallValue> {
474   static inline CallValue getEmptyKey() {
475     return DenseMapInfo<Instruction *>::getEmptyKey();
476   }
477 
478   static inline CallValue getTombstoneKey() {
479     return DenseMapInfo<Instruction *>::getTombstoneKey();
480   }
481 
482   static unsigned getHashValue(CallValue Val);
483   static bool isEqual(CallValue LHS, CallValue RHS);
484 };
485 
486 } // end namespace llvm
487 
488 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
489   Instruction *Inst = Val.Inst;
490 
491   // Hash all of the operands as pointers and mix in the opcode.
492   return hash_combine(
493       Inst->getOpcode(),
494       hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
495 }
496 
497 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
498   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
499   if (LHS.isSentinel() || RHS.isSentinel())
500     return LHSI == RHSI;
501 
502   return LHSI->isIdenticalTo(RHSI);
503 }
504 
505 //===----------------------------------------------------------------------===//
506 // EarlyCSE implementation
507 //===----------------------------------------------------------------------===//
508 
509 namespace {
510 
511 /// A simple and fast domtree-based CSE pass.
512 ///
513 /// This pass does a simple depth-first walk over the dominator tree,
514 /// eliminating trivially redundant instructions and using instsimplify to
515 /// canonicalize things as it goes. It is intended to be fast and catch obvious
516 /// cases so that instcombine and other passes are more effective. It is
517 /// expected that a later pass of GVN will catch the interesting/hard cases.
518 class EarlyCSE {
519 public:
520   const TargetLibraryInfo &TLI;
521   const TargetTransformInfo &TTI;
522   DominatorTree &DT;
523   AssumptionCache &AC;
524   const SimplifyQuery SQ;
525   MemorySSA *MSSA;
526   std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
527 
528   using AllocatorTy =
529       RecyclingAllocator<BumpPtrAllocator,
530                          ScopedHashTableVal<SimpleValue, Value *>>;
531   using ScopedHTType =
532       ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
533                       AllocatorTy>;
534 
535   /// A scoped hash table of the current values of all of our simple
536   /// scalar expressions.
537   ///
538   /// As we walk down the domtree, we look to see if instructions are in this:
539   /// if so, we replace them with what we find, otherwise we insert them so
540   /// that dominated values can succeed in their lookup.
541   ScopedHTType AvailableValues;
542 
543   /// A scoped hash table of the current values of previously encountered
544   /// memory locations.
545   ///
546   /// This allows us to get efficient access to dominating loads or stores when
547   /// we have a fully redundant load.  In addition to the most recent load, we
548   /// keep track of a generation count of the read, which is compared against
549   /// the current generation count.  The current generation count is incremented
550   /// after every possibly writing memory operation, which ensures that we only
551   /// CSE loads with other loads that have no intervening store.  Ordering
552   /// events (such as fences or atomic instructions) increment the generation
553   /// count as well; essentially, we model these as writes to all possible
554   /// locations.  Note that atomic and/or volatile loads and stores can be
555   /// present the table; it is the responsibility of the consumer to inspect
556   /// the atomicity/volatility if needed.
557   struct LoadValue {
558     Instruction *DefInst = nullptr;
559     unsigned Generation = 0;
560     int MatchingId = -1;
561     bool IsAtomic = false;
562 
563     LoadValue() = default;
564     LoadValue(Instruction *Inst, unsigned Generation, unsigned MatchingId,
565               bool IsAtomic)
566         : DefInst(Inst), Generation(Generation), MatchingId(MatchingId),
567           IsAtomic(IsAtomic) {}
568   };
569 
570   using LoadMapAllocator =
571       RecyclingAllocator<BumpPtrAllocator,
572                          ScopedHashTableVal<Value *, LoadValue>>;
573   using LoadHTType =
574       ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
575                       LoadMapAllocator>;
576 
577   LoadHTType AvailableLoads;
578 
579   // A scoped hash table mapping memory locations (represented as typed
580   // addresses) to generation numbers at which that memory location became
581   // (henceforth indefinitely) invariant.
582   using InvariantMapAllocator =
583       RecyclingAllocator<BumpPtrAllocator,
584                          ScopedHashTableVal<MemoryLocation, unsigned>>;
585   using InvariantHTType =
586       ScopedHashTable<MemoryLocation, unsigned, DenseMapInfo<MemoryLocation>,
587                       InvariantMapAllocator>;
588   InvariantHTType AvailableInvariants;
589 
590   /// A scoped hash table of the current values of read-only call
591   /// values.
592   ///
593   /// It uses the same generation count as loads.
594   using CallHTType =
595       ScopedHashTable<CallValue, std::pair<Instruction *, unsigned>>;
596   CallHTType AvailableCalls;
597 
598   /// This is the current generation of the memory value.
599   unsigned CurrentGeneration = 0;
600 
601   /// Set up the EarlyCSE runner for a particular function.
602   EarlyCSE(const DataLayout &DL, const TargetLibraryInfo &TLI,
603            const TargetTransformInfo &TTI, DominatorTree &DT,
604            AssumptionCache &AC, MemorySSA *MSSA)
605       : TLI(TLI), TTI(TTI), DT(DT), AC(AC), SQ(DL, &TLI, &DT, &AC), MSSA(MSSA),
606         MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {}
607 
608   bool run();
609 
610 private:
611   unsigned ClobberCounter = 0;
612   // Almost a POD, but needs to call the constructors for the scoped hash
613   // tables so that a new scope gets pushed on. These are RAII so that the
614   // scope gets popped when the NodeScope is destroyed.
615   class NodeScope {
616   public:
617     NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
618               InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls)
619       : Scope(AvailableValues), LoadScope(AvailableLoads),
620         InvariantScope(AvailableInvariants), CallScope(AvailableCalls) {}
621     NodeScope(const NodeScope &) = delete;
622     NodeScope &operator=(const NodeScope &) = delete;
623 
624   private:
625     ScopedHTType::ScopeTy Scope;
626     LoadHTType::ScopeTy LoadScope;
627     InvariantHTType::ScopeTy InvariantScope;
628     CallHTType::ScopeTy CallScope;
629   };
630 
631   // Contains all the needed information to create a stack for doing a depth
632   // first traversal of the tree. This includes scopes for values, loads, and
633   // calls as well as the generation. There is a child iterator so that the
634   // children do not need to be store separately.
635   class StackNode {
636   public:
637     StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
638               InvariantHTType &AvailableInvariants, CallHTType &AvailableCalls,
639               unsigned cg, DomTreeNode *n, DomTreeNode::const_iterator child,
640               DomTreeNode::const_iterator end)
641         : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
642           EndIter(end),
643           Scopes(AvailableValues, AvailableLoads, AvailableInvariants,
644                  AvailableCalls)
645           {}
646     StackNode(const StackNode &) = delete;
647     StackNode &operator=(const StackNode &) = delete;
648 
649     // Accessors.
650     unsigned currentGeneration() const { return CurrentGeneration; }
651     unsigned childGeneration() const { return ChildGeneration; }
652     void childGeneration(unsigned generation) { ChildGeneration = generation; }
653     DomTreeNode *node() { return Node; }
654     DomTreeNode::const_iterator childIter() const { return ChildIter; }
655 
656     DomTreeNode *nextChild() {
657       DomTreeNode *child = *ChildIter;
658       ++ChildIter;
659       return child;
660     }
661 
662     DomTreeNode::const_iterator end() const { return EndIter; }
663     bool isProcessed() const { return Processed; }
664     void process() { Processed = true; }
665 
666   private:
667     unsigned CurrentGeneration;
668     unsigned ChildGeneration;
669     DomTreeNode *Node;
670     DomTreeNode::const_iterator ChildIter;
671     DomTreeNode::const_iterator EndIter;
672     NodeScope Scopes;
673     bool Processed = false;
674   };
675 
676   /// Wrapper class to handle memory instructions, including loads,
677   /// stores and intrinsic loads and stores defined by the target.
678   class ParseMemoryInst {
679   public:
680     ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
681       : Inst(Inst) {
682       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
683         IntrID = II->getIntrinsicID();
684         if (TTI.getTgtMemIntrinsic(II, Info))
685           return;
686         if (isHandledNonTargetIntrinsic(IntrID)) {
687           switch (IntrID) {
688           case Intrinsic::masked_load:
689             Info.PtrVal = Inst->getOperand(0);
690             Info.MatchingId = Intrinsic::masked_load;
691             Info.ReadMem = true;
692             Info.WriteMem = false;
693             Info.IsVolatile = false;
694             break;
695           case Intrinsic::masked_store:
696             Info.PtrVal = Inst->getOperand(1);
697             // Use the ID of masked load as the "matching id". This will
698             // prevent matching non-masked loads/stores with masked ones
699             // (which could be done), but at the moment, the code here
700             // does not support matching intrinsics with non-intrinsics,
701             // so keep the MatchingIds specific to masked instructions
702             // for now (TODO).
703             Info.MatchingId = Intrinsic::masked_load;
704             Info.ReadMem = false;
705             Info.WriteMem = true;
706             Info.IsVolatile = false;
707             break;
708           }
709         }
710       }
711     }
712 
713     Instruction *get() { return Inst; }
714     const Instruction *get() const { return Inst; }
715 
716     bool isLoad() const {
717       if (IntrID != 0)
718         return Info.ReadMem;
719       return isa<LoadInst>(Inst);
720     }
721 
722     bool isStore() const {
723       if (IntrID != 0)
724         return Info.WriteMem;
725       return isa<StoreInst>(Inst);
726     }
727 
728     bool isAtomic() const {
729       if (IntrID != 0)
730         return Info.Ordering != AtomicOrdering::NotAtomic;
731       return Inst->isAtomic();
732     }
733 
734     bool isUnordered() const {
735       if (IntrID != 0)
736         return Info.isUnordered();
737 
738       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
739         return LI->isUnordered();
740       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
741         return SI->isUnordered();
742       }
743       // Conservative answer
744       return !Inst->isAtomic();
745     }
746 
747     bool isVolatile() const {
748       if (IntrID != 0)
749         return Info.IsVolatile;
750 
751       if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
752         return LI->isVolatile();
753       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
754         return SI->isVolatile();
755       }
756       // Conservative answer
757       return true;
758     }
759 
760     bool isInvariantLoad() const {
761       if (auto *LI = dyn_cast<LoadInst>(Inst))
762         return LI->hasMetadata(LLVMContext::MD_invariant_load);
763       return false;
764     }
765 
766     bool isValid() const { return getPointerOperand() != nullptr; }
767 
768     // For regular (non-intrinsic) loads/stores, this is set to -1. For
769     // intrinsic loads/stores, the id is retrieved from the corresponding
770     // field in the MemIntrinsicInfo structure.  That field contains
771     // non-negative values only.
772     int getMatchingId() const {
773       if (IntrID != 0)
774         return Info.MatchingId;
775       return -1;
776     }
777 
778     Value *getPointerOperand() const {
779       if (IntrID != 0)
780         return Info.PtrVal;
781       return getLoadStorePointerOperand(Inst);
782     }
783 
784     Type *getValueType() const {
785       // TODO: handle target-specific intrinsics.
786       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
787         switch (II->getIntrinsicID()) {
788         case Intrinsic::masked_load:
789           return II->getType();
790         case Intrinsic::masked_store:
791           return II->getArgOperand(0)->getType();
792         default:
793           return nullptr;
794         }
795       }
796       return getLoadStoreType(Inst);
797     }
798 
799     bool mayReadFromMemory() const {
800       if (IntrID != 0)
801         return Info.ReadMem;
802       return Inst->mayReadFromMemory();
803     }
804 
805     bool mayWriteToMemory() const {
806       if (IntrID != 0)
807         return Info.WriteMem;
808       return Inst->mayWriteToMemory();
809     }
810 
811   private:
812     Intrinsic::ID IntrID = 0;
813     MemIntrinsicInfo Info;
814     Instruction *Inst;
815   };
816 
817   // This function is to prevent accidentally passing a non-target
818   // intrinsic ID to TargetTransformInfo.
819   static bool isHandledNonTargetIntrinsic(Intrinsic::ID ID) {
820     switch (ID) {
821     case Intrinsic::masked_load:
822     case Intrinsic::masked_store:
823       return true;
824     }
825     return false;
826   }
827   static bool isHandledNonTargetIntrinsic(const Value *V) {
828     if (auto *II = dyn_cast<IntrinsicInst>(V))
829       return isHandledNonTargetIntrinsic(II->getIntrinsicID());
830     return false;
831   }
832 
833   bool processNode(DomTreeNode *Node);
834 
835   bool handleBranchCondition(Instruction *CondInst, const BranchInst *BI,
836                              const BasicBlock *BB, const BasicBlock *Pred);
837 
838   Value *getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
839                           unsigned CurrentGeneration);
840 
841   bool overridingStores(const ParseMemoryInst &Earlier,
842                         const ParseMemoryInst &Later);
843 
844   Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
845     // TODO: We could insert relevant casts on type mismatch here.
846     if (auto *LI = dyn_cast<LoadInst>(Inst))
847       return LI->getType() == ExpectedType ? LI : nullptr;
848     else if (auto *SI = dyn_cast<StoreInst>(Inst)) {
849       Value *V = SI->getValueOperand();
850       return V->getType() == ExpectedType ? V : nullptr;
851     }
852     assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
853     auto *II = cast<IntrinsicInst>(Inst);
854     if (isHandledNonTargetIntrinsic(II->getIntrinsicID()))
855       return getOrCreateResultNonTargetMemIntrinsic(II, ExpectedType);
856     return TTI.getOrCreateResultFromMemIntrinsic(II, ExpectedType);
857   }
858 
859   Value *getOrCreateResultNonTargetMemIntrinsic(IntrinsicInst *II,
860                                                 Type *ExpectedType) const {
861     switch (II->getIntrinsicID()) {
862     case Intrinsic::masked_load:
863       return II;
864     case Intrinsic::masked_store:
865       return II->getOperand(0);
866     }
867     return nullptr;
868   }
869 
870   /// Return true if the instruction is known to only operate on memory
871   /// provably invariant in the given "generation".
872   bool isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt);
873 
874   bool isSameMemGeneration(unsigned EarlierGeneration, unsigned LaterGeneration,
875                            Instruction *EarlierInst, Instruction *LaterInst);
876 
877   bool isNonTargetIntrinsicMatch(const IntrinsicInst *Earlier,
878                                  const IntrinsicInst *Later) {
879     auto IsSubmask = [](const Value *Mask0, const Value *Mask1) {
880       // Is Mask0 a submask of Mask1?
881       if (Mask0 == Mask1)
882         return true;
883       if (isa<UndefValue>(Mask0) || isa<UndefValue>(Mask1))
884         return false;
885       auto *Vec0 = dyn_cast<ConstantVector>(Mask0);
886       auto *Vec1 = dyn_cast<ConstantVector>(Mask1);
887       if (!Vec0 || !Vec1)
888         return false;
889       assert(Vec0->getType() == Vec1->getType() &&
890              "Masks should have the same type");
891       for (int i = 0, e = Vec0->getNumOperands(); i != e; ++i) {
892         Constant *Elem0 = Vec0->getOperand(i);
893         Constant *Elem1 = Vec1->getOperand(i);
894         auto *Int0 = dyn_cast<ConstantInt>(Elem0);
895         if (Int0 && Int0->isZero())
896           continue;
897         auto *Int1 = dyn_cast<ConstantInt>(Elem1);
898         if (Int1 && !Int1->isZero())
899           continue;
900         if (isa<UndefValue>(Elem0) || isa<UndefValue>(Elem1))
901           return false;
902         if (Elem0 == Elem1)
903           continue;
904         return false;
905       }
906       return true;
907     };
908     auto PtrOp = [](const IntrinsicInst *II) {
909       if (II->getIntrinsicID() == Intrinsic::masked_load)
910         return II->getOperand(0);
911       if (II->getIntrinsicID() == Intrinsic::masked_store)
912         return II->getOperand(1);
913       llvm_unreachable("Unexpected IntrinsicInst");
914     };
915     auto MaskOp = [](const IntrinsicInst *II) {
916       if (II->getIntrinsicID() == Intrinsic::masked_load)
917         return II->getOperand(2);
918       if (II->getIntrinsicID() == Intrinsic::masked_store)
919         return II->getOperand(3);
920       llvm_unreachable("Unexpected IntrinsicInst");
921     };
922     auto ThruOp = [](const IntrinsicInst *II) {
923       if (II->getIntrinsicID() == Intrinsic::masked_load)
924         return II->getOperand(3);
925       llvm_unreachable("Unexpected IntrinsicInst");
926     };
927 
928     if (PtrOp(Earlier) != PtrOp(Later))
929       return false;
930 
931     Intrinsic::ID IDE = Earlier->getIntrinsicID();
932     Intrinsic::ID IDL = Later->getIntrinsicID();
933     // We could really use specific intrinsic classes for masked loads
934     // and stores in IntrinsicInst.h.
935     if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_load) {
936       // Trying to replace later masked load with the earlier one.
937       // Check that the pointers are the same, and
938       // - masks and pass-throughs are the same, or
939       // - replacee's pass-through is "undef" and replacer's mask is a
940       //   super-set of the replacee's mask.
941       if (MaskOp(Earlier) == MaskOp(Later) && ThruOp(Earlier) == ThruOp(Later))
942         return true;
943       if (!isa<UndefValue>(ThruOp(Later)))
944         return false;
945       return IsSubmask(MaskOp(Later), MaskOp(Earlier));
946     }
947     if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_load) {
948       // Trying to replace a load of a stored value with the store's value.
949       // Check that the pointers are the same, and
950       // - load's mask is a subset of store's mask, and
951       // - load's pass-through is "undef".
952       if (!IsSubmask(MaskOp(Later), MaskOp(Earlier)))
953         return false;
954       return isa<UndefValue>(ThruOp(Later));
955     }
956     if (IDE == Intrinsic::masked_load && IDL == Intrinsic::masked_store) {
957       // Trying to remove a store of the loaded value.
958       // Check that the pointers are the same, and
959       // - store's mask is a subset of the load's mask.
960       return IsSubmask(MaskOp(Later), MaskOp(Earlier));
961     }
962     if (IDE == Intrinsic::masked_store && IDL == Intrinsic::masked_store) {
963       // Trying to remove a dead store (earlier).
964       // Check that the pointers are the same,
965       // - the to-be-removed store's mask is a subset of the other store's
966       //   mask.
967       return IsSubmask(MaskOp(Earlier), MaskOp(Later));
968     }
969     return false;
970   }
971 
972   void removeMSSA(Instruction &Inst) {
973     if (!MSSA)
974       return;
975     if (VerifyMemorySSA)
976       MSSA->verifyMemorySSA();
977     // Removing a store here can leave MemorySSA in an unoptimized state by
978     // creating MemoryPhis that have identical arguments and by creating
979     // MemoryUses whose defining access is not an actual clobber. The phi case
980     // is handled by MemorySSA when passing OptimizePhis = true to
981     // removeMemoryAccess.  The non-optimized MemoryUse case is lazily updated
982     // by MemorySSA's getClobberingMemoryAccess.
983     MSSAUpdater->removeMemoryAccess(&Inst, true);
984   }
985 };
986 
987 } // end anonymous namespace
988 
989 /// Determine if the memory referenced by LaterInst is from the same heap
990 /// version as EarlierInst.
991 /// This is currently called in two scenarios:
992 ///
993 ///   load p
994 ///   ...
995 ///   load p
996 ///
997 /// and
998 ///
999 ///   x = load p
1000 ///   ...
1001 ///   store x, p
1002 ///
1003 /// in both cases we want to verify that there are no possible writes to the
1004 /// memory referenced by p between the earlier and later instruction.
1005 bool EarlyCSE::isSameMemGeneration(unsigned EarlierGeneration,
1006                                    unsigned LaterGeneration,
1007                                    Instruction *EarlierInst,
1008                                    Instruction *LaterInst) {
1009   // Check the simple memory generation tracking first.
1010   if (EarlierGeneration == LaterGeneration)
1011     return true;
1012 
1013   if (!MSSA)
1014     return false;
1015 
1016   // If MemorySSA has determined that one of EarlierInst or LaterInst does not
1017   // read/write memory, then we can safely return true here.
1018   // FIXME: We could be more aggressive when checking doesNotAccessMemory(),
1019   // onlyReadsMemory(), mayReadFromMemory(), and mayWriteToMemory() in this pass
1020   // by also checking the MemorySSA MemoryAccess on the instruction.  Initial
1021   // experiments suggest this isn't worthwhile, at least for C/C++ code compiled
1022   // with the default optimization pipeline.
1023   auto *EarlierMA = MSSA->getMemoryAccess(EarlierInst);
1024   if (!EarlierMA)
1025     return true;
1026   auto *LaterMA = MSSA->getMemoryAccess(LaterInst);
1027   if (!LaterMA)
1028     return true;
1029 
1030   // Since we know LaterDef dominates LaterInst and EarlierInst dominates
1031   // LaterInst, if LaterDef dominates EarlierInst then it can't occur between
1032   // EarlierInst and LaterInst and neither can any other write that potentially
1033   // clobbers LaterInst.
1034   MemoryAccess *LaterDef;
1035   if (ClobberCounter < EarlyCSEMssaOptCap) {
1036     LaterDef = MSSA->getWalker()->getClobberingMemoryAccess(LaterInst);
1037     ClobberCounter++;
1038   } else
1039     LaterDef = LaterMA->getDefiningAccess();
1040 
1041   return MSSA->dominates(LaterDef, EarlierMA);
1042 }
1043 
1044 bool EarlyCSE::isOperatingOnInvariantMemAt(Instruction *I, unsigned GenAt) {
1045   // A location loaded from with an invariant_load is assumed to *never* change
1046   // within the visible scope of the compilation.
1047   if (auto *LI = dyn_cast<LoadInst>(I))
1048     if (LI->hasMetadata(LLVMContext::MD_invariant_load))
1049       return true;
1050 
1051   auto MemLocOpt = MemoryLocation::getOrNone(I);
1052   if (!MemLocOpt)
1053     // "target" intrinsic forms of loads aren't currently known to
1054     // MemoryLocation::get.  TODO
1055     return false;
1056   MemoryLocation MemLoc = *MemLocOpt;
1057   if (!AvailableInvariants.count(MemLoc))
1058     return false;
1059 
1060   // Is the generation at which this became invariant older than the
1061   // current one?
1062   return AvailableInvariants.lookup(MemLoc) <= GenAt;
1063 }
1064 
1065 bool EarlyCSE::handleBranchCondition(Instruction *CondInst,
1066                                      const BranchInst *BI, const BasicBlock *BB,
1067                                      const BasicBlock *Pred) {
1068   assert(BI->isConditional() && "Should be a conditional branch!");
1069   assert(BI->getCondition() == CondInst && "Wrong condition?");
1070   assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
1071   auto *TorF = (BI->getSuccessor(0) == BB)
1072                    ? ConstantInt::getTrue(BB->getContext())
1073                    : ConstantInt::getFalse(BB->getContext());
1074   auto MatchBinOp = [](Instruction *I, unsigned Opcode, Value *&LHS,
1075                        Value *&RHS) {
1076     if (Opcode == Instruction::And &&
1077         match(I, m_LogicalAnd(m_Value(LHS), m_Value(RHS))))
1078       return true;
1079     else if (Opcode == Instruction::Or &&
1080              match(I, m_LogicalOr(m_Value(LHS), m_Value(RHS))))
1081       return true;
1082     return false;
1083   };
1084   // If the condition is AND operation, we can propagate its operands into the
1085   // true branch. If it is OR operation, we can propagate them into the false
1086   // branch.
1087   unsigned PropagateOpcode =
1088       (BI->getSuccessor(0) == BB) ? Instruction::And : Instruction::Or;
1089 
1090   bool MadeChanges = false;
1091   SmallVector<Instruction *, 4> WorkList;
1092   SmallPtrSet<Instruction *, 4> Visited;
1093   WorkList.push_back(CondInst);
1094   while (!WorkList.empty()) {
1095     Instruction *Curr = WorkList.pop_back_val();
1096 
1097     AvailableValues.insert(Curr, TorF);
1098     LLVM_DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
1099                       << Curr->getName() << "' as " << *TorF << " in "
1100                       << BB->getName() << "\n");
1101     if (!DebugCounter::shouldExecute(CSECounter)) {
1102       LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1103     } else {
1104       // Replace all dominated uses with the known value.
1105       if (unsigned Count = replaceDominatedUsesWith(Curr, TorF, DT,
1106                                                     BasicBlockEdge(Pred, BB))) {
1107         NumCSECVP += Count;
1108         MadeChanges = true;
1109       }
1110     }
1111 
1112     Value *LHS, *RHS;
1113     if (MatchBinOp(Curr, PropagateOpcode, LHS, RHS))
1114       for (auto &Op : { LHS, RHS })
1115         if (Instruction *OPI = dyn_cast<Instruction>(Op))
1116           if (SimpleValue::canHandle(OPI) && Visited.insert(OPI).second)
1117             WorkList.push_back(OPI);
1118   }
1119 
1120   return MadeChanges;
1121 }
1122 
1123 Value *EarlyCSE::getMatchingValue(LoadValue &InVal, ParseMemoryInst &MemInst,
1124                                   unsigned CurrentGeneration) {
1125   if (InVal.DefInst == nullptr)
1126     return nullptr;
1127   if (InVal.MatchingId != MemInst.getMatchingId())
1128     return nullptr;
1129   // We don't yet handle removing loads with ordering of any kind.
1130   if (MemInst.isVolatile() || !MemInst.isUnordered())
1131     return nullptr;
1132   // We can't replace an atomic load with one which isn't also atomic.
1133   if (MemInst.isLoad() && !InVal.IsAtomic && MemInst.isAtomic())
1134     return nullptr;
1135   // The value V returned from this function is used differently depending
1136   // on whether MemInst is a load or a store. If it's a load, we will replace
1137   // MemInst with V, if it's a store, we will check if V is the same as the
1138   // available value.
1139   bool MemInstMatching = !MemInst.isLoad();
1140   Instruction *Matching = MemInstMatching ? MemInst.get() : InVal.DefInst;
1141   Instruction *Other = MemInstMatching ? InVal.DefInst : MemInst.get();
1142 
1143   // For stores check the result values before checking memory generation
1144   // (otherwise isSameMemGeneration may crash).
1145   Value *Result = MemInst.isStore()
1146                       ? getOrCreateResult(Matching, Other->getType())
1147                       : nullptr;
1148   if (MemInst.isStore() && InVal.DefInst != Result)
1149     return nullptr;
1150 
1151   // Deal with non-target memory intrinsics.
1152   bool MatchingNTI = isHandledNonTargetIntrinsic(Matching);
1153   bool OtherNTI = isHandledNonTargetIntrinsic(Other);
1154   if (OtherNTI != MatchingNTI)
1155     return nullptr;
1156   if (OtherNTI && MatchingNTI) {
1157     if (!isNonTargetIntrinsicMatch(cast<IntrinsicInst>(InVal.DefInst),
1158                                    cast<IntrinsicInst>(MemInst.get())))
1159       return nullptr;
1160   }
1161 
1162   if (!isOperatingOnInvariantMemAt(MemInst.get(), InVal.Generation) &&
1163       !isSameMemGeneration(InVal.Generation, CurrentGeneration, InVal.DefInst,
1164                            MemInst.get()))
1165     return nullptr;
1166 
1167   if (!Result)
1168     Result = getOrCreateResult(Matching, Other->getType());
1169   return Result;
1170 }
1171 
1172 bool EarlyCSE::overridingStores(const ParseMemoryInst &Earlier,
1173                                 const ParseMemoryInst &Later) {
1174   // Can we remove Earlier store because of Later store?
1175 
1176   assert(Earlier.isUnordered() && !Earlier.isVolatile() &&
1177          "Violated invariant");
1178   if (Earlier.getPointerOperand() != Later.getPointerOperand())
1179     return false;
1180   if (!Earlier.getValueType() || !Later.getValueType() ||
1181       Earlier.getValueType() != Later.getValueType())
1182     return false;
1183   if (Earlier.getMatchingId() != Later.getMatchingId())
1184     return false;
1185   // At the moment, we don't remove ordered stores, but do remove
1186   // unordered atomic stores.  There's no special requirement (for
1187   // unordered atomics) about removing atomic stores only in favor of
1188   // other atomic stores since we were going to execute the non-atomic
1189   // one anyway and the atomic one might never have become visible.
1190   if (!Earlier.isUnordered() || !Later.isUnordered())
1191     return false;
1192 
1193   // Deal with non-target memory intrinsics.
1194   bool ENTI = isHandledNonTargetIntrinsic(Earlier.get());
1195   bool LNTI = isHandledNonTargetIntrinsic(Later.get());
1196   if (ENTI && LNTI)
1197     return isNonTargetIntrinsicMatch(cast<IntrinsicInst>(Earlier.get()),
1198                                      cast<IntrinsicInst>(Later.get()));
1199 
1200   // Because of the check above, at least one of them is false.
1201   // For now disallow matching intrinsics with non-intrinsics,
1202   // so assume that the stores match if neither is an intrinsic.
1203   return ENTI == LNTI;
1204 }
1205 
1206 bool EarlyCSE::processNode(DomTreeNode *Node) {
1207   bool Changed = false;
1208   BasicBlock *BB = Node->getBlock();
1209 
1210   // If this block has a single predecessor, then the predecessor is the parent
1211   // of the domtree node and all of the live out memory values are still current
1212   // in this block.  If this block has multiple predecessors, then they could
1213   // have invalidated the live-out memory values of our parent value.  For now,
1214   // just be conservative and invalidate memory if this block has multiple
1215   // predecessors.
1216   if (!BB->getSinglePredecessor())
1217     ++CurrentGeneration;
1218 
1219   // If this node has a single predecessor which ends in a conditional branch,
1220   // we can infer the value of the branch condition given that we took this
1221   // path.  We need the single predecessor to ensure there's not another path
1222   // which reaches this block where the condition might hold a different
1223   // value.  Since we're adding this to the scoped hash table (like any other
1224   // def), it will have been popped if we encounter a future merge block.
1225   if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1226     auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
1227     if (BI && BI->isConditional()) {
1228       auto *CondInst = dyn_cast<Instruction>(BI->getCondition());
1229       if (CondInst && SimpleValue::canHandle(CondInst))
1230         Changed |= handleBranchCondition(CondInst, BI, BB, Pred);
1231     }
1232   }
1233 
1234   /// LastStore - Keep track of the last non-volatile store that we saw... for
1235   /// as long as there in no instruction that reads memory.  If we see a store
1236   /// to the same location, we delete the dead store.  This zaps trivial dead
1237   /// stores which can occur in bitfield code among other things.
1238   Instruction *LastStore = nullptr;
1239 
1240   // See if any instructions in the block can be eliminated.  If so, do it.  If
1241   // not, add them to AvailableValues.
1242   for (Instruction &Inst : make_early_inc_range(BB->getInstList())) {
1243     // Dead instructions should just be removed.
1244     if (isInstructionTriviallyDead(&Inst, &TLI)) {
1245       LLVM_DEBUG(dbgs() << "EarlyCSE DCE: " << Inst << '\n');
1246       if (!DebugCounter::shouldExecute(CSECounter)) {
1247         LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1248         continue;
1249       }
1250 
1251       salvageKnowledge(&Inst, &AC);
1252       salvageDebugInfo(Inst);
1253       removeMSSA(Inst);
1254       Inst.eraseFromParent();
1255       Changed = true;
1256       ++NumSimplify;
1257       continue;
1258     }
1259 
1260     // Skip assume intrinsics, they don't really have side effects (although
1261     // they're marked as such to ensure preservation of control dependencies),
1262     // and this pass will not bother with its removal. However, we should mark
1263     // its condition as true for all dominated blocks.
1264     if (auto *Assume = dyn_cast<AssumeInst>(&Inst)) {
1265       auto *CondI = dyn_cast<Instruction>(Assume->getArgOperand(0));
1266       if (CondI && SimpleValue::canHandle(CondI)) {
1267         LLVM_DEBUG(dbgs() << "EarlyCSE considering assumption: " << Inst
1268                           << '\n');
1269         AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
1270       } else
1271         LLVM_DEBUG(dbgs() << "EarlyCSE skipping assumption: " << Inst << '\n');
1272       continue;
1273     }
1274 
1275     // Likewise, noalias intrinsics don't actually write.
1276     if (match(&Inst,
1277               m_Intrinsic<Intrinsic::experimental_noalias_scope_decl>())) {
1278       LLVM_DEBUG(dbgs() << "EarlyCSE skipping noalias intrinsic: " << Inst
1279                         << '\n');
1280       continue;
1281     }
1282 
1283     // Skip sideeffect intrinsics, for the same reason as assume intrinsics.
1284     if (match(&Inst, m_Intrinsic<Intrinsic::sideeffect>())) {
1285       LLVM_DEBUG(dbgs() << "EarlyCSE skipping sideeffect: " << Inst << '\n');
1286       continue;
1287     }
1288 
1289     // Skip pseudoprobe intrinsics, for the same reason as assume intrinsics.
1290     if (match(&Inst, m_Intrinsic<Intrinsic::pseudoprobe>())) {
1291       LLVM_DEBUG(dbgs() << "EarlyCSE skipping pseudoprobe: " << Inst << '\n');
1292       continue;
1293     }
1294 
1295     // We can skip all invariant.start intrinsics since they only read memory,
1296     // and we can forward values across it. For invariant starts without
1297     // invariant ends, we can use the fact that the invariantness never ends to
1298     // start a scope in the current generaton which is true for all future
1299     // generations.  Also, we dont need to consume the last store since the
1300     // semantics of invariant.start allow us to perform   DSE of the last
1301     // store, if there was a store following invariant.start. Consider:
1302     //
1303     // store 30, i8* p
1304     // invariant.start(p)
1305     // store 40, i8* p
1306     // We can DSE the store to 30, since the store 40 to invariant location p
1307     // causes undefined behaviour.
1308     if (match(&Inst, m_Intrinsic<Intrinsic::invariant_start>())) {
1309       // If there are any uses, the scope might end.
1310       if (!Inst.use_empty())
1311         continue;
1312       MemoryLocation MemLoc =
1313           MemoryLocation::getForArgument(&cast<CallInst>(Inst), 1, TLI);
1314       // Don't start a scope if we already have a better one pushed
1315       if (!AvailableInvariants.count(MemLoc))
1316         AvailableInvariants.insert(MemLoc, CurrentGeneration);
1317       continue;
1318     }
1319 
1320     if (isGuard(&Inst)) {
1321       if (auto *CondI =
1322               dyn_cast<Instruction>(cast<CallInst>(Inst).getArgOperand(0))) {
1323         if (SimpleValue::canHandle(CondI)) {
1324           // Do we already know the actual value of this condition?
1325           if (auto *KnownCond = AvailableValues.lookup(CondI)) {
1326             // Is the condition known to be true?
1327             if (isa<ConstantInt>(KnownCond) &&
1328                 cast<ConstantInt>(KnownCond)->isOne()) {
1329               LLVM_DEBUG(dbgs()
1330                          << "EarlyCSE removing guard: " << Inst << '\n');
1331               salvageKnowledge(&Inst, &AC);
1332               removeMSSA(Inst);
1333               Inst.eraseFromParent();
1334               Changed = true;
1335               continue;
1336             } else
1337               // Use the known value if it wasn't true.
1338               cast<CallInst>(Inst).setArgOperand(0, KnownCond);
1339           }
1340           // The condition we're on guarding here is true for all dominated
1341           // locations.
1342           AvailableValues.insert(CondI, ConstantInt::getTrue(BB->getContext()));
1343         }
1344       }
1345 
1346       // Guard intrinsics read all memory, but don't write any memory.
1347       // Accordingly, don't update the generation but consume the last store (to
1348       // avoid an incorrect DSE).
1349       LastStore = nullptr;
1350       continue;
1351     }
1352 
1353     // If the instruction can be simplified (e.g. X+0 = X) then replace it with
1354     // its simpler value.
1355     if (Value *V = SimplifyInstruction(&Inst, SQ)) {
1356       LLVM_DEBUG(dbgs() << "EarlyCSE Simplify: " << Inst << "  to: " << *V
1357                         << '\n');
1358       if (!DebugCounter::shouldExecute(CSECounter)) {
1359         LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1360       } else {
1361         bool Killed = false;
1362         if (!Inst.use_empty()) {
1363           Inst.replaceAllUsesWith(V);
1364           Changed = true;
1365         }
1366         if (isInstructionTriviallyDead(&Inst, &TLI)) {
1367           salvageKnowledge(&Inst, &AC);
1368           removeMSSA(Inst);
1369           Inst.eraseFromParent();
1370           Changed = true;
1371           Killed = true;
1372         }
1373         if (Changed)
1374           ++NumSimplify;
1375         if (Killed)
1376           continue;
1377       }
1378     }
1379 
1380     // If this is a simple instruction that we can value number, process it.
1381     if (SimpleValue::canHandle(&Inst)) {
1382       // See if the instruction has an available value.  If so, use it.
1383       if (Value *V = AvailableValues.lookup(&Inst)) {
1384         LLVM_DEBUG(dbgs() << "EarlyCSE CSE: " << Inst << "  to: " << *V
1385                           << '\n');
1386         if (!DebugCounter::shouldExecute(CSECounter)) {
1387           LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1388           continue;
1389         }
1390         if (auto *I = dyn_cast<Instruction>(V)) {
1391           // If I being poison triggers UB, there is no need to drop those
1392           // flags. Otherwise, only retain flags present on both I and Inst.
1393           // TODO: Currently some fast-math flags are not treated as
1394           // poison-generating even though they should. Until this is fixed,
1395           // always retain flags present on both I and Inst for floating point
1396           // instructions.
1397           if (isa<FPMathOperator>(I) || (I->hasPoisonGeneratingFlags() && !programUndefinedIfPoison(I)))
1398             I->andIRFlags(&Inst);
1399         }
1400         Inst.replaceAllUsesWith(V);
1401         salvageKnowledge(&Inst, &AC);
1402         removeMSSA(Inst);
1403         Inst.eraseFromParent();
1404         Changed = true;
1405         ++NumCSE;
1406         continue;
1407       }
1408 
1409       // Otherwise, just remember that this value is available.
1410       AvailableValues.insert(&Inst, &Inst);
1411       continue;
1412     }
1413 
1414     ParseMemoryInst MemInst(&Inst, TTI);
1415     // If this is a non-volatile load, process it.
1416     if (MemInst.isValid() && MemInst.isLoad()) {
1417       // (conservatively) we can't peak past the ordering implied by this
1418       // operation, but we can add this load to our set of available values
1419       if (MemInst.isVolatile() || !MemInst.isUnordered()) {
1420         LastStore = nullptr;
1421         ++CurrentGeneration;
1422       }
1423 
1424       if (MemInst.isInvariantLoad()) {
1425         // If we pass an invariant load, we know that memory location is
1426         // indefinitely constant from the moment of first dereferenceability.
1427         // We conservatively treat the invariant_load as that moment.  If we
1428         // pass a invariant load after already establishing a scope, don't
1429         // restart it since we want to preserve the earliest point seen.
1430         auto MemLoc = MemoryLocation::get(&Inst);
1431         if (!AvailableInvariants.count(MemLoc))
1432           AvailableInvariants.insert(MemLoc, CurrentGeneration);
1433       }
1434 
1435       // If we have an available version of this load, and if it is the right
1436       // generation or the load is known to be from an invariant location,
1437       // replace this instruction.
1438       //
1439       // If either the dominating load or the current load are invariant, then
1440       // we can assume the current load loads the same value as the dominating
1441       // load.
1442       LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1443       if (Value *Op = getMatchingValue(InVal, MemInst, CurrentGeneration)) {
1444         LLVM_DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << Inst
1445                           << "  to: " << *InVal.DefInst << '\n');
1446         if (!DebugCounter::shouldExecute(CSECounter)) {
1447           LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1448           continue;
1449         }
1450         if (!Inst.use_empty())
1451           Inst.replaceAllUsesWith(Op);
1452         salvageKnowledge(&Inst, &AC);
1453         removeMSSA(Inst);
1454         Inst.eraseFromParent();
1455         Changed = true;
1456         ++NumCSELoad;
1457         continue;
1458       }
1459 
1460       // Otherwise, remember that we have this instruction.
1461       AvailableLoads.insert(MemInst.getPointerOperand(),
1462                             LoadValue(&Inst, CurrentGeneration,
1463                                       MemInst.getMatchingId(),
1464                                       MemInst.isAtomic()));
1465       LastStore = nullptr;
1466       continue;
1467     }
1468 
1469     // If this instruction may read from memory or throw (and potentially read
1470     // from memory in the exception handler), forget LastStore.  Load/store
1471     // intrinsics will indicate both a read and a write to memory.  The target
1472     // may override this (e.g. so that a store intrinsic does not read from
1473     // memory, and thus will be treated the same as a regular store for
1474     // commoning purposes).
1475     if ((Inst.mayReadFromMemory() || Inst.mayThrow()) &&
1476         !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
1477       LastStore = nullptr;
1478 
1479     // If this is a read-only call, process it.
1480     if (CallValue::canHandle(&Inst)) {
1481       // If we have an available version of this call, and if it is the right
1482       // generation, replace this instruction.
1483       std::pair<Instruction *, unsigned> InVal = AvailableCalls.lookup(&Inst);
1484       if (InVal.first != nullptr &&
1485           isSameMemGeneration(InVal.second, CurrentGeneration, InVal.first,
1486                               &Inst)) {
1487         LLVM_DEBUG(dbgs() << "EarlyCSE CSE CALL: " << Inst
1488                           << "  to: " << *InVal.first << '\n');
1489         if (!DebugCounter::shouldExecute(CSECounter)) {
1490           LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1491           continue;
1492         }
1493         if (!Inst.use_empty())
1494           Inst.replaceAllUsesWith(InVal.first);
1495         salvageKnowledge(&Inst, &AC);
1496         removeMSSA(Inst);
1497         Inst.eraseFromParent();
1498         Changed = true;
1499         ++NumCSECall;
1500         continue;
1501       }
1502 
1503       // Otherwise, remember that we have this instruction.
1504       AvailableCalls.insert(&Inst, std::make_pair(&Inst, CurrentGeneration));
1505       continue;
1506     }
1507 
1508     // A release fence requires that all stores complete before it, but does
1509     // not prevent the reordering of following loads 'before' the fence.  As a
1510     // result, we don't need to consider it as writing to memory and don't need
1511     // to advance the generation.  We do need to prevent DSE across the fence,
1512     // but that's handled above.
1513     if (auto *FI = dyn_cast<FenceInst>(&Inst))
1514       if (FI->getOrdering() == AtomicOrdering::Release) {
1515         assert(Inst.mayReadFromMemory() && "relied on to prevent DSE above");
1516         continue;
1517       }
1518 
1519     // write back DSE - If we write back the same value we just loaded from
1520     // the same location and haven't passed any intervening writes or ordering
1521     // operations, we can remove the write.  The primary benefit is in allowing
1522     // the available load table to remain valid and value forward past where
1523     // the store originally was.
1524     if (MemInst.isValid() && MemInst.isStore()) {
1525       LoadValue InVal = AvailableLoads.lookup(MemInst.getPointerOperand());
1526       if (InVal.DefInst &&
1527           InVal.DefInst == getMatchingValue(InVal, MemInst, CurrentGeneration)) {
1528         // It is okay to have a LastStore to a different pointer here if MemorySSA
1529         // tells us that the load and store are from the same memory generation.
1530         // In that case, LastStore should keep its present value since we're
1531         // removing the current store.
1532         assert((!LastStore ||
1533                 ParseMemoryInst(LastStore, TTI).getPointerOperand() ==
1534                     MemInst.getPointerOperand() ||
1535                 MSSA) &&
1536                "can't have an intervening store if not using MemorySSA!");
1537         LLVM_DEBUG(dbgs() << "EarlyCSE DSE (writeback): " << Inst << '\n');
1538         if (!DebugCounter::shouldExecute(CSECounter)) {
1539           LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1540           continue;
1541         }
1542         salvageKnowledge(&Inst, &AC);
1543         removeMSSA(Inst);
1544         Inst.eraseFromParent();
1545         Changed = true;
1546         ++NumDSE;
1547         // We can avoid incrementing the generation count since we were able
1548         // to eliminate this store.
1549         continue;
1550       }
1551     }
1552 
1553     // Okay, this isn't something we can CSE at all.  Check to see if it is
1554     // something that could modify memory.  If so, our available memory values
1555     // cannot be used so bump the generation count.
1556     if (Inst.mayWriteToMemory()) {
1557       ++CurrentGeneration;
1558 
1559       if (MemInst.isValid() && MemInst.isStore()) {
1560         // We do a trivial form of DSE if there are two stores to the same
1561         // location with no intervening loads.  Delete the earlier store.
1562         if (LastStore) {
1563           if (overridingStores(ParseMemoryInst(LastStore, TTI), MemInst)) {
1564             LLVM_DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
1565                               << "  due to: " << Inst << '\n');
1566             if (!DebugCounter::shouldExecute(CSECounter)) {
1567               LLVM_DEBUG(dbgs() << "Skipping due to debug counter\n");
1568             } else {
1569               salvageKnowledge(&Inst, &AC);
1570               removeMSSA(*LastStore);
1571               LastStore->eraseFromParent();
1572               Changed = true;
1573               ++NumDSE;
1574               LastStore = nullptr;
1575             }
1576           }
1577           // fallthrough - we can exploit information about this store
1578         }
1579 
1580         // Okay, we just invalidated anything we knew about loaded values.  Try
1581         // to salvage *something* by remembering that the stored value is a live
1582         // version of the pointer.  It is safe to forward from volatile stores
1583         // to non-volatile loads, so we don't have to check for volatility of
1584         // the store.
1585         AvailableLoads.insert(MemInst.getPointerOperand(),
1586                               LoadValue(&Inst, CurrentGeneration,
1587                                         MemInst.getMatchingId(),
1588                                         MemInst.isAtomic()));
1589 
1590         // Remember that this was the last unordered store we saw for DSE. We
1591         // don't yet handle DSE on ordered or volatile stores since we don't
1592         // have a good way to model the ordering requirement for following
1593         // passes  once the store is removed.  We could insert a fence, but
1594         // since fences are slightly stronger than stores in their ordering,
1595         // it's not clear this is a profitable transform. Another option would
1596         // be to merge the ordering with that of the post dominating store.
1597         if (MemInst.isUnordered() && !MemInst.isVolatile())
1598           LastStore = &Inst;
1599         else
1600           LastStore = nullptr;
1601       }
1602     }
1603   }
1604 
1605   return Changed;
1606 }
1607 
1608 bool EarlyCSE::run() {
1609   // Note, deque is being used here because there is significant performance
1610   // gains over vector when the container becomes very large due to the
1611   // specific access patterns. For more information see the mailing list
1612   // discussion on this:
1613   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
1614   std::deque<StackNode *> nodesToProcess;
1615 
1616   bool Changed = false;
1617 
1618   // Process the root node.
1619   nodesToProcess.push_back(new StackNode(
1620       AvailableValues, AvailableLoads, AvailableInvariants, AvailableCalls,
1621       CurrentGeneration, DT.getRootNode(),
1622       DT.getRootNode()->begin(), DT.getRootNode()->end()));
1623 
1624   assert(!CurrentGeneration && "Create a new EarlyCSE instance to rerun it.");
1625 
1626   // Process the stack.
1627   while (!nodesToProcess.empty()) {
1628     // Grab the first item off the stack. Set the current generation, remove
1629     // the node from the stack, and process it.
1630     StackNode *NodeToProcess = nodesToProcess.back();
1631 
1632     // Initialize class members.
1633     CurrentGeneration = NodeToProcess->currentGeneration();
1634 
1635     // Check if the node needs to be processed.
1636     if (!NodeToProcess->isProcessed()) {
1637       // Process the node.
1638       Changed |= processNode(NodeToProcess->node());
1639       NodeToProcess->childGeneration(CurrentGeneration);
1640       NodeToProcess->process();
1641     } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
1642       // Push the next child onto the stack.
1643       DomTreeNode *child = NodeToProcess->nextChild();
1644       nodesToProcess.push_back(
1645           new StackNode(AvailableValues, AvailableLoads, AvailableInvariants,
1646                         AvailableCalls, NodeToProcess->childGeneration(),
1647                         child, child->begin(), child->end()));
1648     } else {
1649       // It has been processed, and there are no more children to process,
1650       // so delete it and pop it off the stack.
1651       delete NodeToProcess;
1652       nodesToProcess.pop_back();
1653     }
1654   } // while (!nodes...)
1655 
1656   return Changed;
1657 }
1658 
1659 PreservedAnalyses EarlyCSEPass::run(Function &F,
1660                                     FunctionAnalysisManager &AM) {
1661   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1662   auto &TTI = AM.getResult<TargetIRAnalysis>(F);
1663   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
1664   auto &AC = AM.getResult<AssumptionAnalysis>(F);
1665   auto *MSSA =
1666       UseMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : nullptr;
1667 
1668   EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
1669 
1670   if (!CSE.run())
1671     return PreservedAnalyses::all();
1672 
1673   PreservedAnalyses PA;
1674   PA.preserveSet<CFGAnalyses>();
1675   if (UseMemorySSA)
1676     PA.preserve<MemorySSAAnalysis>();
1677   return PA;
1678 }
1679 
1680 void EarlyCSEPass::printPipeline(
1681     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
1682   static_cast<PassInfoMixin<EarlyCSEPass> *>(this)->printPipeline(
1683       OS, MapClassName2PassName);
1684   OS << "<";
1685   if (UseMemorySSA)
1686     OS << "memssa";
1687   OS << ">";
1688 }
1689 
1690 namespace {
1691 
1692 /// A simple and fast domtree-based CSE pass.
1693 ///
1694 /// This pass does a simple depth-first walk over the dominator tree,
1695 /// eliminating trivially redundant instructions and using instsimplify to
1696 /// canonicalize things as it goes. It is intended to be fast and catch obvious
1697 /// cases so that instcombine and other passes are more effective. It is
1698 /// expected that a later pass of GVN will catch the interesting/hard cases.
1699 template<bool UseMemorySSA>
1700 class EarlyCSELegacyCommonPass : public FunctionPass {
1701 public:
1702   static char ID;
1703 
1704   EarlyCSELegacyCommonPass() : FunctionPass(ID) {
1705     if (UseMemorySSA)
1706       initializeEarlyCSEMemSSALegacyPassPass(*PassRegistry::getPassRegistry());
1707     else
1708       initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
1709   }
1710 
1711   bool runOnFunction(Function &F) override {
1712     if (skipFunction(F))
1713       return false;
1714 
1715     auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1716     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
1717     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1718     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1719     auto *MSSA =
1720         UseMemorySSA ? &getAnalysis<MemorySSAWrapperPass>().getMSSA() : nullptr;
1721 
1722     EarlyCSE CSE(F.getParent()->getDataLayout(), TLI, TTI, DT, AC, MSSA);
1723 
1724     return CSE.run();
1725   }
1726 
1727   void getAnalysisUsage(AnalysisUsage &AU) const override {
1728     AU.addRequired<AssumptionCacheTracker>();
1729     AU.addRequired<DominatorTreeWrapperPass>();
1730     AU.addRequired<TargetLibraryInfoWrapperPass>();
1731     AU.addRequired<TargetTransformInfoWrapperPass>();
1732     if (UseMemorySSA) {
1733       AU.addRequired<AAResultsWrapperPass>();
1734       AU.addRequired<MemorySSAWrapperPass>();
1735       AU.addPreserved<MemorySSAWrapperPass>();
1736     }
1737     AU.addPreserved<GlobalsAAWrapperPass>();
1738     AU.addPreserved<AAResultsWrapperPass>();
1739     AU.setPreservesCFG();
1740   }
1741 };
1742 
1743 } // end anonymous namespace
1744 
1745 using EarlyCSELegacyPass = EarlyCSELegacyCommonPass</*UseMemorySSA=*/false>;
1746 
1747 template<>
1748 char EarlyCSELegacyPass::ID = 0;
1749 
1750 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
1751                       false)
1752 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1753 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1754 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1755 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1756 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)
1757 
1758 using EarlyCSEMemSSALegacyPass =
1759     EarlyCSELegacyCommonPass</*UseMemorySSA=*/true>;
1760 
1761 template<>
1762 char EarlyCSEMemSSALegacyPass::ID = 0;
1763 
1764 FunctionPass *llvm::createEarlyCSEPass(bool UseMemorySSA) {
1765   if (UseMemorySSA)
1766     return new EarlyCSEMemSSALegacyPass();
1767   else
1768     return new EarlyCSELegacyPass();
1769 }
1770 
1771 INITIALIZE_PASS_BEGIN(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1772                       "Early CSE w/ MemorySSA", false, false)
1773 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
1774 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1775 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1776 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1777 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1778 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1779 INITIALIZE_PASS_END(EarlyCSEMemSSALegacyPass, "early-cse-memssa",
1780                     "Early CSE w/ MemorySSA", false, false)
1781