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