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