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