de539d53a4f55b3adf2c07da85d42d53c3031d0c
[oota-llvm.git] / lib / Transforms / Scalar / EarlyCSE.cpp
1 //===- EarlyCSE.cpp - Simple and fast CSE pass ----------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs a simple dominator tree walk that eliminates trivially
11 // redundant instructions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Scalar/EarlyCSE.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/ADT/ScopedHashTable.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/GlobalsModRef.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/Dominators.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/RecyclingAllocator.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Transforms/Scalar.h"
34 #include "llvm/Transforms/Utils/Local.h"
35 #include <deque>
36 using namespace llvm;
37 using namespace llvm::PatternMatch;
38
39 #define DEBUG_TYPE "early-cse"
40
41 STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
42 STATISTIC(NumCSE,      "Number of instructions CSE'd");
43 STATISTIC(NumCSELoad,  "Number of load instructions CSE'd");
44 STATISTIC(NumCSECall,  "Number of call instructions CSE'd");
45 STATISTIC(NumDSE,      "Number of trivial dead stores removed");
46
47 //===----------------------------------------------------------------------===//
48 // SimpleValue
49 //===----------------------------------------------------------------------===//
50
51 namespace {
52 /// \brief Struct representing the available values in the scoped hash table.
53 struct SimpleValue {
54   Instruction *Inst;
55
56   SimpleValue(Instruction *I) : Inst(I) {
57     assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
58   }
59
60   bool isSentinel() const {
61     return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
62            Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
63   }
64
65   static bool canHandle(Instruction *Inst) {
66     // This can only handle non-void readnone functions.
67     if (CallInst *CI = dyn_cast<CallInst>(Inst))
68       return CI->doesNotAccessMemory() && !CI->getType()->isVoidTy();
69     return isa<CastInst>(Inst) || isa<BinaryOperator>(Inst) ||
70            isa<GetElementPtrInst>(Inst) || isa<CmpInst>(Inst) ||
71            isa<SelectInst>(Inst) || isa<ExtractElementInst>(Inst) ||
72            isa<InsertElementInst>(Inst) || isa<ShuffleVectorInst>(Inst) ||
73            isa<ExtractValueInst>(Inst) || isa<InsertValueInst>(Inst);
74   }
75 };
76 }
77
78 namespace llvm {
79 template <> struct DenseMapInfo<SimpleValue> {
80   static inline SimpleValue getEmptyKey() {
81     return DenseMapInfo<Instruction *>::getEmptyKey();
82   }
83   static inline SimpleValue getTombstoneKey() {
84     return DenseMapInfo<Instruction *>::getTombstoneKey();
85   }
86   static unsigned getHashValue(SimpleValue Val);
87   static bool isEqual(SimpleValue LHS, SimpleValue RHS);
88 };
89 }
90
91 unsigned DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
92   Instruction *Inst = Val.Inst;
93   // Hash in all of the operands as pointers.
94   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst)) {
95     Value *LHS = BinOp->getOperand(0);
96     Value *RHS = BinOp->getOperand(1);
97     if (BinOp->isCommutative() && BinOp->getOperand(0) > BinOp->getOperand(1))
98       std::swap(LHS, RHS);
99
100     if (isa<OverflowingBinaryOperator>(BinOp)) {
101       // Hash the overflow behavior
102       unsigned Overflow =
103           BinOp->hasNoSignedWrap() * OverflowingBinaryOperator::NoSignedWrap |
104           BinOp->hasNoUnsignedWrap() *
105               OverflowingBinaryOperator::NoUnsignedWrap;
106       return hash_combine(BinOp->getOpcode(), Overflow, LHS, RHS);
107     }
108
109     return hash_combine(BinOp->getOpcode(), LHS, RHS);
110   }
111
112   if (CmpInst *CI = dyn_cast<CmpInst>(Inst)) {
113     Value *LHS = CI->getOperand(0);
114     Value *RHS = CI->getOperand(1);
115     CmpInst::Predicate Pred = CI->getPredicate();
116     if (Inst->getOperand(0) > Inst->getOperand(1)) {
117       std::swap(LHS, RHS);
118       Pred = CI->getSwappedPredicate();
119     }
120     return hash_combine(Inst->getOpcode(), Pred, LHS, RHS);
121   }
122
123   if (CastInst *CI = dyn_cast<CastInst>(Inst))
124     return hash_combine(CI->getOpcode(), CI->getType(), CI->getOperand(0));
125
126   if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Inst))
127     return hash_combine(EVI->getOpcode(), EVI->getOperand(0),
128                         hash_combine_range(EVI->idx_begin(), EVI->idx_end()));
129
130   if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(Inst))
131     return hash_combine(IVI->getOpcode(), IVI->getOperand(0),
132                         IVI->getOperand(1),
133                         hash_combine_range(IVI->idx_begin(), IVI->idx_end()));
134
135   assert((isa<CallInst>(Inst) || isa<BinaryOperator>(Inst) ||
136           isa<GetElementPtrInst>(Inst) || isa<SelectInst>(Inst) ||
137           isa<ExtractElementInst>(Inst) || isa<InsertElementInst>(Inst) ||
138           isa<ShuffleVectorInst>(Inst)) &&
139          "Invalid/unknown instruction");
140
141   // Mix in the opcode.
142   return hash_combine(
143       Inst->getOpcode(),
144       hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
145 }
146
147 bool DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS, SimpleValue RHS) {
148   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
149
150   if (LHS.isSentinel() || RHS.isSentinel())
151     return LHSI == RHSI;
152
153   if (LHSI->getOpcode() != RHSI->getOpcode())
154     return false;
155   if (LHSI->isIdenticalTo(RHSI))
156     return true;
157
158   // If we're not strictly identical, we still might be a commutable instruction
159   if (BinaryOperator *LHSBinOp = dyn_cast<BinaryOperator>(LHSI)) {
160     if (!LHSBinOp->isCommutative())
161       return false;
162
163     assert(isa<BinaryOperator>(RHSI) &&
164            "same opcode, but different instruction type?");
165     BinaryOperator *RHSBinOp = cast<BinaryOperator>(RHSI);
166
167     // Check overflow attributes
168     if (isa<OverflowingBinaryOperator>(LHSBinOp)) {
169       assert(isa<OverflowingBinaryOperator>(RHSBinOp) &&
170              "same opcode, but different operator type?");
171       if (LHSBinOp->hasNoUnsignedWrap() != RHSBinOp->hasNoUnsignedWrap() ||
172           LHSBinOp->hasNoSignedWrap() != RHSBinOp->hasNoSignedWrap())
173         return false;
174     }
175
176     // Commuted equality
177     return LHSBinOp->getOperand(0) == RHSBinOp->getOperand(1) &&
178            LHSBinOp->getOperand(1) == RHSBinOp->getOperand(0);
179   }
180   if (CmpInst *LHSCmp = dyn_cast<CmpInst>(LHSI)) {
181     assert(isa<CmpInst>(RHSI) &&
182            "same opcode, but different instruction type?");
183     CmpInst *RHSCmp = cast<CmpInst>(RHSI);
184     // Commuted equality
185     return LHSCmp->getOperand(0) == RHSCmp->getOperand(1) &&
186            LHSCmp->getOperand(1) == RHSCmp->getOperand(0) &&
187            LHSCmp->getSwappedPredicate() == RHSCmp->getPredicate();
188   }
189
190   return false;
191 }
192
193 //===----------------------------------------------------------------------===//
194 // CallValue
195 //===----------------------------------------------------------------------===//
196
197 namespace {
198 /// \brief Struct representing the available call values in the scoped hash
199 /// table.
200 struct CallValue {
201   Instruction *Inst;
202
203   CallValue(Instruction *I) : Inst(I) {
204     assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
205   }
206
207   bool isSentinel() const {
208     return Inst == DenseMapInfo<Instruction *>::getEmptyKey() ||
209            Inst == DenseMapInfo<Instruction *>::getTombstoneKey();
210   }
211
212   static bool canHandle(Instruction *Inst) {
213     // Don't value number anything that returns void.
214     if (Inst->getType()->isVoidTy())
215       return false;
216
217     CallInst *CI = dyn_cast<CallInst>(Inst);
218     if (!CI || !CI->onlyReadsMemory())
219       return false;
220     return true;
221   }
222 };
223 }
224
225 namespace llvm {
226 template <> struct DenseMapInfo<CallValue> {
227   static inline CallValue getEmptyKey() {
228     return DenseMapInfo<Instruction *>::getEmptyKey();
229   }
230   static inline CallValue getTombstoneKey() {
231     return DenseMapInfo<Instruction *>::getTombstoneKey();
232   }
233   static unsigned getHashValue(CallValue Val);
234   static bool isEqual(CallValue LHS, CallValue RHS);
235 };
236 }
237
238 unsigned DenseMapInfo<CallValue>::getHashValue(CallValue Val) {
239   Instruction *Inst = Val.Inst;
240   // Hash all of the operands as pointers and mix in the opcode.
241   return hash_combine(
242       Inst->getOpcode(),
243       hash_combine_range(Inst->value_op_begin(), Inst->value_op_end()));
244 }
245
246 bool DenseMapInfo<CallValue>::isEqual(CallValue LHS, CallValue RHS) {
247   Instruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
248   if (LHS.isSentinel() || RHS.isSentinel())
249     return LHSI == RHSI;
250   return LHSI->isIdenticalTo(RHSI);
251 }
252
253 //===----------------------------------------------------------------------===//
254 // EarlyCSE implementation
255 //===----------------------------------------------------------------------===//
256
257 namespace {
258 /// \brief A simple and fast domtree-based CSE pass.
259 ///
260 /// This pass does a simple depth-first walk over the dominator tree,
261 /// eliminating trivially redundant instructions and using instsimplify to
262 /// canonicalize things as it goes. It is intended to be fast and catch obvious
263 /// cases so that instcombine and other passes are more effective. It is
264 /// expected that a later pass of GVN will catch the interesting/hard cases.
265 class EarlyCSE {
266 public:
267   const TargetLibraryInfo &TLI;
268   const TargetTransformInfo &TTI;
269   DominatorTree &DT;
270   AssumptionCache &AC;
271   typedef RecyclingAllocator<
272       BumpPtrAllocator, ScopedHashTableVal<SimpleValue, Value *>> AllocatorTy;
273   typedef ScopedHashTable<SimpleValue, Value *, DenseMapInfo<SimpleValue>,
274                           AllocatorTy> ScopedHTType;
275
276   /// \brief A scoped hash table of the current values of all of our simple
277   /// scalar expressions.
278   ///
279   /// As we walk down the domtree, we look to see if instructions are in this:
280   /// if so, we replace them with what we find, otherwise we insert them so
281   /// that dominated values can succeed in their lookup.
282   ScopedHTType AvailableValues;
283
284   /// \brief A scoped hash table of the current values of loads.
285   ///
286   /// This allows us to get efficient access to dominating loads when we have
287   /// a fully redundant load.  In addition to the most recent load, we keep
288   /// track of a generation count of the read, which is compared against the
289   /// current generation count.  The current generation count is incremented
290   /// after every possibly writing memory operation, which ensures that we only
291   /// CSE loads with other loads that have no intervening store.
292   struct LoadValue {
293     Value *Data;
294     unsigned Generation;
295     int MatchingId;
296     LoadValue() : Data(nullptr), Generation(0), MatchingId(-1) {}
297     LoadValue(Value *Data, unsigned Generation, unsigned MatchingId)
298         : Data(Data), Generation(Generation), MatchingId(MatchingId) {}
299   };
300   typedef RecyclingAllocator<BumpPtrAllocator,
301                              ScopedHashTableVal<Value *, LoadValue>>
302       LoadMapAllocator;
303   typedef ScopedHashTable<Value *, LoadValue, DenseMapInfo<Value *>,
304                           LoadMapAllocator> LoadHTType;
305   LoadHTType AvailableLoads;
306
307   /// \brief A scoped hash table of the current values of read-only call
308   /// values.
309   ///
310   /// It uses the same generation count as loads.
311   typedef ScopedHashTable<CallValue, std::pair<Value *, unsigned>> CallHTType;
312   CallHTType AvailableCalls;
313
314   /// \brief This is the current generation of the memory value.
315   unsigned CurrentGeneration;
316
317   /// \brief Set up the EarlyCSE runner for a particular function.
318   EarlyCSE(const TargetLibraryInfo &TLI, const TargetTransformInfo &TTI,
319            DominatorTree &DT, AssumptionCache &AC)
320       : TLI(TLI), TTI(TTI), DT(DT), AC(AC), CurrentGeneration(0) {}
321
322   bool run();
323
324 private:
325   // Almost a POD, but needs to call the constructors for the scoped hash
326   // tables so that a new scope gets pushed on. These are RAII so that the
327   // scope gets popped when the NodeScope is destroyed.
328   class NodeScope {
329   public:
330     NodeScope(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
331               CallHTType &AvailableCalls)
332         : Scope(AvailableValues), LoadScope(AvailableLoads),
333           CallScope(AvailableCalls) {}
334
335   private:
336     NodeScope(const NodeScope &) = delete;
337     void operator=(const NodeScope &) = delete;
338
339     ScopedHTType::ScopeTy Scope;
340     LoadHTType::ScopeTy LoadScope;
341     CallHTType::ScopeTy CallScope;
342   };
343
344   // Contains all the needed information to create a stack for doing a depth
345   // first tranversal of the tree. This includes scopes for values, loads, and
346   // calls as well as the generation. There is a child iterator so that the
347   // children do not need to be store spearately.
348   class StackNode {
349   public:
350     StackNode(ScopedHTType &AvailableValues, LoadHTType &AvailableLoads,
351               CallHTType &AvailableCalls, unsigned cg, DomTreeNode *n,
352               DomTreeNode::iterator child, DomTreeNode::iterator end)
353         : CurrentGeneration(cg), ChildGeneration(cg), Node(n), ChildIter(child),
354           EndIter(end), Scopes(AvailableValues, AvailableLoads, AvailableCalls),
355           Processed(false) {}
356
357     // Accessors.
358     unsigned currentGeneration() { return CurrentGeneration; }
359     unsigned childGeneration() { return ChildGeneration; }
360     void childGeneration(unsigned generation) { ChildGeneration = generation; }
361     DomTreeNode *node() { return Node; }
362     DomTreeNode::iterator childIter() { return ChildIter; }
363     DomTreeNode *nextChild() {
364       DomTreeNode *child = *ChildIter;
365       ++ChildIter;
366       return child;
367     }
368     DomTreeNode::iterator end() { return EndIter; }
369     bool isProcessed() { return Processed; }
370     void process() { Processed = true; }
371
372   private:
373     StackNode(const StackNode &) = delete;
374     void operator=(const StackNode &) = delete;
375
376     // Members.
377     unsigned CurrentGeneration;
378     unsigned ChildGeneration;
379     DomTreeNode *Node;
380     DomTreeNode::iterator ChildIter;
381     DomTreeNode::iterator EndIter;
382     NodeScope Scopes;
383     bool Processed;
384   };
385
386   /// \brief Wrapper class to handle memory instructions, including loads,
387   /// stores and intrinsic loads and stores defined by the target.
388   class ParseMemoryInst {
389   public:
390     ParseMemoryInst(Instruction *Inst, const TargetTransformInfo &TTI)
391         : Load(false), Store(false), Vol(false), MayReadFromMemory(false),
392           MayWriteToMemory(false), MatchingId(-1), Ptr(nullptr) {
393       MayReadFromMemory = Inst->mayReadFromMemory();
394       MayWriteToMemory = Inst->mayWriteToMemory();
395       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
396         MemIntrinsicInfo Info;
397         if (!TTI.getTgtMemIntrinsic(II, Info))
398           return;
399         if (Info.NumMemRefs == 1) {
400           Store = Info.WriteMem;
401           Load = Info.ReadMem;
402           MatchingId = Info.MatchingId;
403           MayReadFromMemory = Info.ReadMem;
404           MayWriteToMemory = Info.WriteMem;
405           Vol = Info.Vol;
406           Ptr = Info.PtrVal;
407         }
408       } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
409         Load = true;
410         Vol = !LI->isSimple();
411         Ptr = LI->getPointerOperand();
412       } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
413         Store = true;
414         Vol = !SI->isSimple();
415         Ptr = SI->getPointerOperand();
416       }
417     }
418     bool isLoad() const { return Load; }
419     bool isStore() const { return Store; }
420     bool isVolatile() const { return Vol; }
421     bool isMatchingMemLoc(const ParseMemoryInst &Inst) const {
422       return Ptr == Inst.Ptr && MatchingId == Inst.MatchingId;
423     }
424     bool isValid() const { return Ptr != nullptr; }
425     int getMatchingId() const { return MatchingId; }
426     Value *getPtr() const { return Ptr; }
427     bool mayReadFromMemory() const { return MayReadFromMemory; }
428     bool mayWriteToMemory() const { return MayWriteToMemory; }
429
430   private:
431     bool Load;
432     bool Store;
433     bool Vol;
434     bool MayReadFromMemory;
435     bool MayWriteToMemory;
436     // For regular (non-intrinsic) loads/stores, this is set to -1. For
437     // intrinsic loads/stores, the id is retrieved from the corresponding
438     // field in the MemIntrinsicInfo structure.  That field contains
439     // non-negative values only.
440     int MatchingId;
441     Value *Ptr;
442   };
443
444   bool processNode(DomTreeNode *Node);
445
446   Value *getOrCreateResult(Value *Inst, Type *ExpectedType) const {
447     if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
448       return LI;
449     else if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
450       return SI->getValueOperand();
451     assert(isa<IntrinsicInst>(Inst) && "Instruction not supported");
452     return TTI.getOrCreateResultFromMemIntrinsic(cast<IntrinsicInst>(Inst),
453                                                  ExpectedType);
454   }
455 };
456 }
457
458 bool EarlyCSE::processNode(DomTreeNode *Node) {
459   BasicBlock *BB = Node->getBlock();
460
461   // If this block has a single predecessor, then the predecessor is the parent
462   // of the domtree node and all of the live out memory values are still current
463   // in this block.  If this block has multiple predecessors, then they could
464   // have invalidated the live-out memory values of our parent value.  For now,
465   // just be conservative and invalidate memory if this block has multiple
466   // predecessors.
467   if (!BB->getSinglePredecessor())
468     ++CurrentGeneration;
469
470   // If this node has a single predecessor which ends in a conditional branch,
471   // we can infer the value of the branch condition given that we took this
472   // path.  We need the single predeccesor to ensure there's not another path
473   // which reaches this block where the condition might hold a different
474   // value.  Since we're adding this to the scoped hash table (like any other
475   // def), it will have been popped if we encounter a future merge block.
476   if (BasicBlock *Pred = BB->getSinglePredecessor())
477     if (auto *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
478       if (BI->isConditional())
479         if (auto *CondInst = dyn_cast<Instruction>(BI->getCondition()))
480           if (SimpleValue::canHandle(CondInst)) {
481             assert(BI->getSuccessor(0) == BB || BI->getSuccessor(1) == BB);
482             auto *ConditionalConstant = (BI->getSuccessor(0) == BB) ?
483               ConstantInt::getTrue(BB->getContext()) :
484               ConstantInt::getFalse(BB->getContext());
485             AvailableValues.insert(CondInst, ConditionalConstant);
486             DEBUG(dbgs() << "EarlyCSE CVP: Add conditional value for '"
487                   << CondInst->getName() << "' as " << *ConditionalConstant
488                   << " in " << BB->getName() << "\n");
489             // Replace all dominated uses with the known value
490             replaceDominatedUsesWith(CondInst, ConditionalConstant, DT,
491                                      BasicBlockEdge(Pred, BB));
492           }
493
494   /// LastStore - Keep track of the last non-volatile store that we saw... for
495   /// as long as there in no instruction that reads memory.  If we see a store
496   /// to the same location, we delete the dead store.  This zaps trivial dead
497   /// stores which can occur in bitfield code among other things.
498   Instruction *LastStore = nullptr;
499
500   bool Changed = false;
501   const DataLayout &DL = BB->getModule()->getDataLayout();
502
503   // See if any instructions in the block can be eliminated.  If so, do it.  If
504   // not, add them to AvailableValues.
505   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
506     Instruction *Inst = &*I++;
507
508     // Dead instructions should just be removed.
509     if (isInstructionTriviallyDead(Inst, &TLI)) {
510       DEBUG(dbgs() << "EarlyCSE DCE: " << *Inst << '\n');
511       Inst->eraseFromParent();
512       Changed = true;
513       ++NumSimplify;
514       continue;
515     }
516
517     // Skip assume intrinsics, they don't really have side effects (although
518     // they're marked as such to ensure preservation of control dependencies),
519     // and this pass will not disturb any of the assumption's control
520     // dependencies.
521     if (match(Inst, m_Intrinsic<Intrinsic::assume>())) {
522       DEBUG(dbgs() << "EarlyCSE skipping assumption: " << *Inst << '\n');
523       continue;
524     }
525
526     // If the instruction can be simplified (e.g. X+0 = X) then replace it with
527     // its simpler value.
528     if (Value *V = SimplifyInstruction(Inst, DL, &TLI, &DT, &AC)) {
529       DEBUG(dbgs() << "EarlyCSE Simplify: " << *Inst << "  to: " << *V << '\n');
530       Inst->replaceAllUsesWith(V);
531       Inst->eraseFromParent();
532       Changed = true;
533       ++NumSimplify;
534       continue;
535     }
536
537     // If this is a simple instruction that we can value number, process it.
538     if (SimpleValue::canHandle(Inst)) {
539       // See if the instruction has an available value.  If so, use it.
540       if (Value *V = AvailableValues.lookup(Inst)) {
541         DEBUG(dbgs() << "EarlyCSE CSE: " << *Inst << "  to: " << *V << '\n');
542         Inst->replaceAllUsesWith(V);
543         Inst->eraseFromParent();
544         Changed = true;
545         ++NumCSE;
546         continue;
547       }
548
549       // Otherwise, just remember that this value is available.
550       AvailableValues.insert(Inst, Inst);
551       continue;
552     }
553
554     ParseMemoryInst MemInst(Inst, TTI);
555     // If this is a non-volatile load, process it.
556     if (MemInst.isValid() && MemInst.isLoad()) {
557       // Ignore volatile loads.
558       if (MemInst.isVolatile()) {
559         LastStore = nullptr;
560         // Don't CSE across synchronization boundaries.
561         if (Inst->mayWriteToMemory())
562           ++CurrentGeneration;
563         continue;
564       }
565
566       // If we have an available version of this load, and if it is the right
567       // generation, replace this instruction.
568       LoadValue InVal = AvailableLoads.lookup(MemInst.getPtr());
569       if (InVal.Data != nullptr && InVal.Generation == CurrentGeneration &&
570           InVal.MatchingId == MemInst.getMatchingId()) {
571         Value *Op = getOrCreateResult(InVal.Data, Inst->getType());
572         if (Op != nullptr) {
573           DEBUG(dbgs() << "EarlyCSE CSE LOAD: " << *Inst
574                        << "  to: " << *InVal.Data << '\n');
575           if (!Inst->use_empty())
576             Inst->replaceAllUsesWith(Op);
577           Inst->eraseFromParent();
578           Changed = true;
579           ++NumCSELoad;
580           continue;
581         }
582       }
583
584       // Otherwise, remember that we have this instruction.
585       AvailableLoads.insert(
586           MemInst.getPtr(),
587           LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId()));
588       LastStore = nullptr;
589       continue;
590     }
591
592     // If this instruction may read from memory, forget LastStore.
593     // Load/store intrinsics will indicate both a read and a write to
594     // memory.  The target may override this (e.g. so that a store intrinsic
595     // does not read  from memory, and thus will be treated the same as a
596     // regular store for commoning purposes).
597     if (Inst->mayReadFromMemory() &&
598         !(MemInst.isValid() && !MemInst.mayReadFromMemory()))
599       LastStore = nullptr;
600
601     // If this is a read-only call, process it.
602     if (CallValue::canHandle(Inst)) {
603       // If we have an available version of this call, and if it is the right
604       // generation, replace this instruction.
605       std::pair<Value *, unsigned> InVal = AvailableCalls.lookup(Inst);
606       if (InVal.first != nullptr && InVal.second == CurrentGeneration) {
607         DEBUG(dbgs() << "EarlyCSE CSE CALL: " << *Inst
608                      << "  to: " << *InVal.first << '\n');
609         if (!Inst->use_empty())
610           Inst->replaceAllUsesWith(InVal.first);
611         Inst->eraseFromParent();
612         Changed = true;
613         ++NumCSECall;
614         continue;
615       }
616
617       // Otherwise, remember that we have this instruction.
618       AvailableCalls.insert(
619           Inst, std::pair<Value *, unsigned>(Inst, CurrentGeneration));
620       continue;
621     }
622
623     // A release fence requires that all stores complete before it, but does
624     // not prevent the reordering of following loads 'before' the fence.  As a
625     // result, we don't need to consider it as writing to memory and don't need
626     // to advance the generation.  We do need to prevent DSE across the fence,
627     // but that's handled above.
628     if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
629       if (FI->getOrdering() == Release) {
630         assert(Inst->mayReadFromMemory() && "relied on to prevent DSE above");
631         continue;
632       }
633
634     // Okay, this isn't something we can CSE at all.  Check to see if it is
635     // something that could modify memory.  If so, our available memory values
636     // cannot be used so bump the generation count.
637     if (Inst->mayWriteToMemory()) {
638       ++CurrentGeneration;
639
640       if (MemInst.isValid() && MemInst.isStore()) {
641         // We do a trivial form of DSE if there are two stores to the same
642         // location with no intervening loads.  Delete the earlier store.
643         if (LastStore) {
644           ParseMemoryInst LastStoreMemInst(LastStore, TTI);
645           if (LastStoreMemInst.isMatchingMemLoc(MemInst)) {
646             DEBUG(dbgs() << "EarlyCSE DEAD STORE: " << *LastStore
647                          << "  due to: " << *Inst << '\n');
648             LastStore->eraseFromParent();
649             Changed = true;
650             ++NumDSE;
651             LastStore = nullptr;
652           }
653           // fallthrough - we can exploit information about this store
654         }
655
656         // Okay, we just invalidated anything we knew about loaded values.  Try
657         // to salvage *something* by remembering that the stored value is a live
658         // version of the pointer.  It is safe to forward from volatile stores
659         // to non-volatile loads, so we don't have to check for volatility of
660         // the store.
661         AvailableLoads.insert(
662             MemInst.getPtr(),
663             LoadValue(Inst, CurrentGeneration, MemInst.getMatchingId()));
664
665         // Remember that this was the last store we saw for DSE.
666         if (!MemInst.isVolatile())
667           LastStore = Inst;
668       }
669     }
670   }
671
672   return Changed;
673 }
674
675 bool EarlyCSE::run() {
676   // Note, deque is being used here because there is significant performance
677   // gains over vector when the container becomes very large due to the
678   // specific access patterns. For more information see the mailing list
679   // discussion on this:
680   // http://lists.llvm.org/pipermail/llvm-commits/Week-of-Mon-20120116/135228.html
681   std::deque<StackNode *> nodesToProcess;
682
683   bool Changed = false;
684
685   // Process the root node.
686   nodesToProcess.push_back(new StackNode(
687       AvailableValues, AvailableLoads, AvailableCalls, CurrentGeneration,
688       DT.getRootNode(), DT.getRootNode()->begin(), DT.getRootNode()->end()));
689
690   // Save the current generation.
691   unsigned LiveOutGeneration = CurrentGeneration;
692
693   // Process the stack.
694   while (!nodesToProcess.empty()) {
695     // Grab the first item off the stack. Set the current generation, remove
696     // the node from the stack, and process it.
697     StackNode *NodeToProcess = nodesToProcess.back();
698
699     // Initialize class members.
700     CurrentGeneration = NodeToProcess->currentGeneration();
701
702     // Check if the node needs to be processed.
703     if (!NodeToProcess->isProcessed()) {
704       // Process the node.
705       Changed |= processNode(NodeToProcess->node());
706       NodeToProcess->childGeneration(CurrentGeneration);
707       NodeToProcess->process();
708     } else if (NodeToProcess->childIter() != NodeToProcess->end()) {
709       // Push the next child onto the stack.
710       DomTreeNode *child = NodeToProcess->nextChild();
711       nodesToProcess.push_back(
712           new StackNode(AvailableValues, AvailableLoads, AvailableCalls,
713                         NodeToProcess->childGeneration(), child, child->begin(),
714                         child->end()));
715     } else {
716       // It has been processed, and there are no more children to process,
717       // so delete it and pop it off the stack.
718       delete NodeToProcess;
719       nodesToProcess.pop_back();
720     }
721   } // while (!nodes...)
722
723   // Reset the current generation.
724   CurrentGeneration = LiveOutGeneration;
725
726   return Changed;
727 }
728
729 PreservedAnalyses EarlyCSEPass::run(Function &F,
730                                     AnalysisManager<Function> *AM) {
731   auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
732   auto &TTI = AM->getResult<TargetIRAnalysis>(F);
733   auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
734   auto &AC = AM->getResult<AssumptionAnalysis>(F);
735
736   EarlyCSE CSE(TLI, TTI, DT, AC);
737
738   if (!CSE.run())
739     return PreservedAnalyses::all();
740
741   // CSE preserves the dominator tree because it doesn't mutate the CFG.
742   // FIXME: Bundle this with other CFG-preservation.
743   PreservedAnalyses PA;
744   PA.preserve<DominatorTreeAnalysis>();
745   return PA;
746 }
747
748 namespace {
749 /// \brief A simple and fast domtree-based CSE pass.
750 ///
751 /// This pass does a simple depth-first walk over the dominator tree,
752 /// eliminating trivially redundant instructions and using instsimplify to
753 /// canonicalize things as it goes. It is intended to be fast and catch obvious
754 /// cases so that instcombine and other passes are more effective. It is
755 /// expected that a later pass of GVN will catch the interesting/hard cases.
756 class EarlyCSELegacyPass : public FunctionPass {
757 public:
758   static char ID;
759
760   EarlyCSELegacyPass() : FunctionPass(ID) {
761     initializeEarlyCSELegacyPassPass(*PassRegistry::getPassRegistry());
762   }
763
764   bool runOnFunction(Function &F) override {
765     if (skipOptnoneFunction(F))
766       return false;
767
768     auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
769     auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
770     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
771     auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
772
773     EarlyCSE CSE(TLI, TTI, DT, AC);
774
775     return CSE.run();
776   }
777
778   void getAnalysisUsage(AnalysisUsage &AU) const override {
779     AU.addRequired<AssumptionCacheTracker>();
780     AU.addRequired<DominatorTreeWrapperPass>();
781     AU.addRequired<TargetLibraryInfoWrapperPass>();
782     AU.addRequired<TargetTransformInfoWrapperPass>();
783     AU.addPreserved<GlobalsAAWrapperPass>();
784     AU.setPreservesCFG();
785   }
786 };
787 }
788
789 char EarlyCSELegacyPass::ID = 0;
790
791 FunctionPass *llvm::createEarlyCSEPass() { return new EarlyCSELegacyPass(); }
792
793 INITIALIZE_PASS_BEGIN(EarlyCSELegacyPass, "early-cse", "Early CSE", false,
794                       false)
795 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
796 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
797 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
798 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
799 INITIALIZE_PASS_END(EarlyCSELegacyPass, "early-cse", "Early CSE", false, false)