1 //===- GVNHoist.cpp - Hoist scalar and load expressions -------------------===//
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 hoists expressions from branches to a common dominator. It uses
11 // GVN (global value numbering) to discover expressions computing the same
12 // values. The primary goals of code-hoisting are:
13 // 1. To reduce the code size.
14 // 2. In some cases reduce critical path (by exposing more ILP).
15 //
16 // The algorithm factors out the reachability of values such that multiple
17 // queries to find reachability of values are fast. This is based on finding the
18 // ANTIC points in the CFG which do not change during hoisting. The ANTIC points
19 // are basically the dominance-frontiers in the inverse graph. So we introduce a
20 // data structure (CHI nodes) to keep track of values flowing out of a basic
21 // block. We only do this for values with multiple occurrences in the function
22 // as they are the potential hoistable candidates. This approach allows us to
23 // hoist instructions to a basic block with more than two successors, as well as
24 // deal with infinite loops in a trivial way.
25 //
26 // Limitations: This pass does not hoist fully redundant expressions because
27 // they are already handled by GVN-PRE. It is advisable to run gvn-hoist before
28 // and after gvn-pre because gvn-pre creates opportunities for more instructions
29 // to be hoisted.
30 //
31 // Hoisting may affect the performance in some cases. To mitigate that, hoisting
32 // is disabled in the following cases.
33 // 1. Scalars across calls.
34 // 2. geps when corresponding load/store cannot be hoisted.
35 //===----------------------------------------------------------------------===//
36 
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/Analysis/GlobalsModRef.h"
41 #include "llvm/Analysis/IteratedDominanceFrontier.h"
42 #include "llvm/Analysis/MemorySSA.h"
43 #include "llvm/Analysis/MemorySSAUpdater.h"
44 #include "llvm/Analysis/PostDominators.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/IR/IntrinsicInst.h"
47 #include "llvm/Transforms/Scalar.h"
48 #include "llvm/Transforms/Scalar/GVN.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 
51 #include <stack>
52 
53 using namespace llvm;
54 
55 #define DEBUG_TYPE "gvn-hoist"
56 
57 STATISTIC(NumHoisted, "Number of instructions hoisted");
58 STATISTIC(NumRemoved, "Number of instructions removed");
59 STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
60 STATISTIC(NumLoadsRemoved, "Number of loads removed");
61 STATISTIC(NumStoresHoisted, "Number of stores hoisted");
62 STATISTIC(NumStoresRemoved, "Number of stores removed");
63 STATISTIC(NumCallsHoisted, "Number of calls hoisted");
64 STATISTIC(NumCallsRemoved, "Number of calls removed");
65 
66 static cl::opt<int>
67     MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1),
68                         cl::desc("Max number of instructions to hoist "
69                                  "(default unlimited = -1)"));
70 static cl::opt<int> MaxNumberOfBBSInPath(
71     "gvn-hoist-max-bbs", cl::Hidden, cl::init(4),
72     cl::desc("Max number of basic blocks on the path between "
73              "hoisting locations (default = 4, unlimited = -1)"));
74 
75 static cl::opt<int> MaxDepthInBB(
76     "gvn-hoist-max-depth", cl::Hidden, cl::init(100),
77     cl::desc("Hoist instructions from the beginning of the BB up to the "
78              "maximum specified depth (default = 100, unlimited = -1)"));
79 
80 static cl::opt<int>
81     MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10),
82                    cl::desc("Maximum length of dependent chains to hoist "
83                             "(default = 10, unlimited = -1)"));
84 
85 namespace llvm {
86 
87 typedef DenseMap<const BasicBlock *, bool> BBSideEffectsSet;
88 typedef SmallVector<Instruction *, 4> SmallVecInsn;
89 typedef SmallVectorImpl<Instruction *> SmallVecImplInsn;
90 // Each element of a hoisting list contains the basic block where to hoist and
91 // a list of instructions to be hoisted.
92 typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo;
93 typedef SmallVector<HoistingPointInfo, 4> HoistingPointList;
94 // A map from a pair of VNs to all the instructions with those VNs.
95 typedef std::pair<unsigned, unsigned> VNType;
96 typedef DenseMap<VNType, SmallVector<Instruction *, 4>> VNtoInsns;
97 
98 // CHI keeps information about values flowing out of a basic block.  It is
99 // similar to PHI but in the inverse graph, and used for outgoing values on each
100 // edge. For conciseness, it is computed only for instructions with multiple
101 // occurrences in the CFG because they are the only hoistable candidates.
102 //     A (CHI[{V, B, I1}, {V, C, I2}]
103 //  /     \
104 // /       \
105 // B(I1)  C (I2)
106 // The Value number for both I1 and I2 is V, the CHI node will save the
107 // instruction as well as the edge where the value is flowing to.
108 struct CHIArg {
109   VNType VN;
110   // Edge destination (shows the direction of flow), may not be where the I is.
111   BasicBlock *Dest;
112   // The instruction (VN) which uses the values flowing out of CHI.
113   Instruction *I;
114   bool operator==(const CHIArg &A) { return VN == A.VN; }
115   bool operator!=(const CHIArg &A) { return !(*this == A); }
116 };
117 
118 typedef SmallVectorImpl<CHIArg>::iterator CHIIt;
119 typedef iterator_range<CHIIt> CHIArgs;
120 typedef DenseMap<BasicBlock *, SmallVector<CHIArg, 2>> OutValuesType;
121 typedef DenseMap<BasicBlock *, SmallVector<std::pair<VNType, Instruction *>, 2>>
122     InValuesType;
123 
124 // An invalid value number Used when inserting a single value number into
125 // VNtoInsns.
126 enum : unsigned { InvalidVN = ~2U };
127 
128 // Records all scalar instructions candidate for code hoisting.
129 class InsnInfo {
130   VNtoInsns VNtoScalars;
131 
132 public:
133   // Inserts I and its value number in VNtoScalars.
134   void insert(Instruction *I, GVN::ValueTable &VN) {
135     // Scalar instruction.
136     unsigned V = VN.lookupOrAdd(I);
137     VNtoScalars[{V, InvalidVN}].push_back(I);
138   }
139 
140   const VNtoInsns &getVNTable() const { return VNtoScalars; }
141 };
142 
143 // Records all load instructions candidate for code hoisting.
144 class LoadInfo {
145   VNtoInsns VNtoLoads;
146 
147 public:
148   // Insert Load and the value number of its memory address in VNtoLoads.
149   void insert(LoadInst *Load, GVN::ValueTable &VN) {
150     if (Load->isSimple()) {
151       unsigned V = VN.lookupOrAdd(Load->getPointerOperand());
152       VNtoLoads[{V, InvalidVN}].push_back(Load);
153     }
154   }
155 
156   const VNtoInsns &getVNTable() const { return VNtoLoads; }
157 };
158 
159 // Records all store instructions candidate for code hoisting.
160 class StoreInfo {
161   VNtoInsns VNtoStores;
162 
163 public:
164   // Insert the Store and a hash number of the store address and the stored
165   // value in VNtoStores.
166   void insert(StoreInst *Store, GVN::ValueTable &VN) {
167     if (!Store->isSimple())
168       return;
169     // Hash the store address and the stored value.
170     Value *Ptr = Store->getPointerOperand();
171     Value *Val = Store->getValueOperand();
172     VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
173   }
174 
175   const VNtoInsns &getVNTable() const { return VNtoStores; }
176 };
177 
178 // Records all call instructions candidate for code hoisting.
179 class CallInfo {
180   VNtoInsns VNtoCallsScalars;
181   VNtoInsns VNtoCallsLoads;
182   VNtoInsns VNtoCallsStores;
183 
184 public:
185   // Insert Call and its value numbering in one of the VNtoCalls* containers.
186   void insert(CallInst *Call, GVN::ValueTable &VN) {
187     // A call that doesNotAccessMemory is handled as a Scalar,
188     // onlyReadsMemory will be handled as a Load instruction,
189     // all other calls will be handled as stores.
190     unsigned V = VN.lookupOrAdd(Call);
191     auto Entry = std::make_pair(V, InvalidVN);
192 
193     if (Call->doesNotAccessMemory())
194       VNtoCallsScalars[Entry].push_back(Call);
195     else if (Call->onlyReadsMemory())
196       VNtoCallsLoads[Entry].push_back(Call);
197     else
198       VNtoCallsStores[Entry].push_back(Call);
199   }
200 
201   const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }
202 
203   const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }
204 
205   const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }
206 };
207 
208 static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) {
209   static const unsigned KnownIDs[] = {
210       LLVMContext::MD_tbaa,           LLVMContext::MD_alias_scope,
211       LLVMContext::MD_noalias,        LLVMContext::MD_range,
212       LLVMContext::MD_fpmath,         LLVMContext::MD_invariant_load,
213       LLVMContext::MD_invariant_group};
214   combineMetadata(ReplInst, I, KnownIDs);
215 }
216 
217 // This pass hoists common computations across branches sharing common
218 // dominator. The primary goal is to reduce the code size, and in some
219 // cases reduce critical path (by exposing more ILP).
220 class GVNHoist {
221 public:
222   GVNHoist(DominatorTree *DT, PostDominatorTree *PDT, AliasAnalysis *AA,
223            MemoryDependenceResults *MD, MemorySSA *MSSA)
224       : DT(DT), PDT(PDT), AA(AA), MD(MD), MSSA(MSSA),
225         MSSAUpdater(make_unique<MemorySSAUpdater>(MSSA)),
226         HoistingGeps(false) {}
227 
228   bool run(Function &F) {
229     NumFuncArgs = F.arg_size();
230     VN.setDomTree(DT);
231     VN.setAliasAnalysis(AA);
232     VN.setMemDep(MD);
233     bool Res = false;
234     // Perform DFS Numbering of instructions.
235     unsigned BBI = 0;
236     for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) {
237       DFSNumber[BB] = ++BBI;
238       unsigned I = 0;
239       for (auto &Inst : *BB)
240         DFSNumber[&Inst] = ++I;
241     }
242 
243     int ChainLength = 0;
244 
245     // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
246     while (1) {
247       if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)
248         return Res;
249 
250       auto HoistStat = hoistExpressions(F);
251       if (HoistStat.first + HoistStat.second == 0)
252         return Res;
253 
254       if (HoistStat.second > 0)
255         // To address a limitation of the current GVN, we need to rerun the
256         // hoisting after we hoisted loads or stores in order to be able to
257         // hoist all scalars dependent on the hoisted ld/st.
258         VN.clear();
259 
260       Res = true;
261     }
262 
263     return Res;
264   }
265 
266   // Copied from NewGVN.cpp
267   // This function provides global ranking of operations so that we can place
268   // them in a canonical order.  Note that rank alone is not necessarily enough
269   // for a complete ordering, as constants all have the same rank.  However,
270   // generally, we will simplify an operation with all constants so that it
271   // doesn't matter what order they appear in.
272   unsigned int rank(const Value *V) const {
273     // Prefer constants to undef to anything else
274     // Undef is a constant, have to check it first.
275     // Prefer smaller constants to constantexprs
276     if (isa<ConstantExpr>(V))
277       return 2;
278     if (isa<UndefValue>(V))
279       return 1;
280     if (isa<Constant>(V))
281       return 0;
282     else if (auto *A = dyn_cast<Argument>(V))
283       return 3 + A->getArgNo();
284 
285     // Need to shift the instruction DFS by number of arguments + 3 to account
286     // for the constant and argument ranking above.
287     auto Result = DFSNumber.lookup(V);
288     if (Result > 0)
289       return 4 + NumFuncArgs + Result;
290     // Unreachable or something else, just return a really large number.
291     return ~0;
292   }
293 
294 private:
295   GVN::ValueTable VN;
296   DominatorTree *DT;
297   PostDominatorTree *PDT;
298   AliasAnalysis *AA;
299   MemoryDependenceResults *MD;
300   MemorySSA *MSSA;
301   std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
302   DenseMap<const Value *, unsigned> DFSNumber;
303   BBSideEffectsSet BBSideEffects;
304   DenseSet<const BasicBlock *> HoistBarrier;
305 
306   SmallVector<BasicBlock *, 32> IDFBlocks;
307   unsigned NumFuncArgs;
308   const bool HoistingGeps;
309 
310   enum InsKind { Unknown, Scalar, Load, Store };
311 
312   // Return true when there are exception handling in BB.
313   bool hasEH(const BasicBlock *BB) {
314     auto It = BBSideEffects.find(BB);
315     if (It != BBSideEffects.end())
316       return It->second;
317 
318     if (BB->isEHPad() || BB->hasAddressTaken()) {
319       BBSideEffects[BB] = true;
320       return true;
321     }
322 
323     if (BB->getTerminator()->mayThrow()) {
324       BBSideEffects[BB] = true;
325       return true;
326     }
327 
328     BBSideEffects[BB] = false;
329     return false;
330   }
331 
332   // Return true when a successor of BB dominates A.
333   bool successorDominate(const BasicBlock *BB, const BasicBlock *A) {
334     for (const BasicBlock *Succ : BB->getTerminator()->successors())
335       if (DT->dominates(Succ, A))
336         return true;
337 
338     return false;
339   }
340 
341   /* Return true when I1 appears before I2 in the instructions of BB.  */
342   bool firstInBB(const Instruction *I1, const Instruction *I2) {
343     assert(I1->getParent() == I2->getParent());
344     unsigned I1DFS = DFSNumber.lookup(I1);
345     unsigned I2DFS = DFSNumber.lookup(I2);
346     assert(I1DFS && I2DFS);
347     return I1DFS < I2DFS;
348   }
349 
350   // Return true when there are memory uses of Def in BB.
351   bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
352                     const BasicBlock *BB) {
353     const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
354     if (!Acc)
355       return false;
356 
357     Instruction *OldPt = Def->getMemoryInst();
358     const BasicBlock *OldBB = OldPt->getParent();
359     const BasicBlock *NewBB = NewPt->getParent();
360     bool ReachedNewPt = false;
361 
362     for (const MemoryAccess &MA : *Acc)
363       if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {
364         Instruction *Insn = MU->getMemoryInst();
365 
366         // Do not check whether MU aliases Def when MU occurs after OldPt.
367         if (BB == OldBB && firstInBB(OldPt, Insn))
368           break;
369 
370         // Do not check whether MU aliases Def when MU occurs before NewPt.
371         if (BB == NewBB) {
372           if (!ReachedNewPt) {
373             if (firstInBB(Insn, NewPt))
374               continue;
375             ReachedNewPt = true;
376           }
377         }
378         if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA))
379           return true;
380       }
381 
382     return false;
383   }
384 
385   bool hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,
386                    int &NBBsOnAllPaths) {
387     // Stop walk once the limit is reached.
388     if (NBBsOnAllPaths == 0)
389       return true;
390 
391     // Impossible to hoist with exceptions on the path.
392     if (hasEH(BB))
393       return true;
394 
395     // No such instruction after HoistBarrier in a basic block was
396     // selected for hoisting so instructions selected within basic block with
397     // a hoist barrier can be hoisted.
398     if ((BB != SrcBB) && HoistBarrier.count(BB))
399       return true;
400 
401     return false;
402   }
403 
404   // Return true when there are exception handling or loads of memory Def
405   // between Def and NewPt.  This function is only called for stores: Def is
406   // the MemoryDef of the store to be hoisted.
407 
408   // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
409   // return true when the counter NBBsOnAllPaths reaces 0, except when it is
410   // initialized to -1 which is unlimited.
411   bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
412                           int &NBBsOnAllPaths) {
413     const BasicBlock *NewBB = NewPt->getParent();
414     const BasicBlock *OldBB = Def->getBlock();
415     assert(DT->dominates(NewBB, OldBB) && "invalid path");
416     assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&
417            "def does not dominate new hoisting point");
418 
419     // Walk all basic blocks reachable in depth-first iteration on the inverse
420     // CFG from OldBB to NewBB. These blocks are all the blocks that may be
421     // executed between the execution of NewBB and OldBB. Hoisting an expression
422     // from OldBB into NewBB has to be safe on all execution paths.
423     for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {
424       const BasicBlock *BB = *I;
425       if (BB == NewBB) {
426         // Stop traversal when reaching HoistPt.
427         I.skipChildren();
428         continue;
429       }
430 
431       if (hasEHhelper(BB, OldBB, NBBsOnAllPaths))
432         return true;
433 
434       // Check that we do not move a store past loads.
435       if (hasMemoryUse(NewPt, Def, BB))
436         return true;
437 
438       // -1 is unlimited number of blocks on all paths.
439       if (NBBsOnAllPaths != -1)
440         --NBBsOnAllPaths;
441 
442       ++I;
443     }
444 
445     return false;
446   }
447 
448   // Return true when there are exception handling between HoistPt and BB.
449   // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
450   // return true when the counter NBBsOnAllPaths reaches 0, except when it is
451   // initialized to -1 which is unlimited.
452   bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
453                    int &NBBsOnAllPaths) {
454     assert(DT->dominates(HoistPt, SrcBB) && "Invalid path");
455 
456     // Walk all basic blocks reachable in depth-first iteration on
457     // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the
458     // blocks that may be executed between the execution of NewHoistPt and
459     // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe
460     // on all execution paths.
461     for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) {
462       const BasicBlock *BB = *I;
463       if (BB == HoistPt) {
464         // Stop traversal when reaching NewHoistPt.
465         I.skipChildren();
466         continue;
467       }
468 
469       if (hasEHhelper(BB, SrcBB, NBBsOnAllPaths))
470         return true;
471 
472       // -1 is unlimited number of blocks on all paths.
473       if (NBBsOnAllPaths != -1)
474         --NBBsOnAllPaths;
475 
476       ++I;
477     }
478 
479     return false;
480   }
481 
482   // Return true when it is safe to hoist a memory load or store U from OldPt
483   // to NewPt.
484   bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
485                        MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths) {
486 
487     // In place hoisting is safe.
488     if (NewPt == OldPt)
489       return true;
490 
491     const BasicBlock *NewBB = NewPt->getParent();
492     const BasicBlock *OldBB = OldPt->getParent();
493     const BasicBlock *UBB = U->getBlock();
494 
495     // Check for dependences on the Memory SSA.
496     MemoryAccess *D = U->getDefiningAccess();
497     BasicBlock *DBB = D->getBlock();
498     if (DT->properlyDominates(NewBB, DBB))
499       // Cannot move the load or store to NewBB above its definition in DBB.
500       return false;
501 
502     if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))
503       if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
504         if (firstInBB(NewPt, UD->getMemoryInst()))
505           // Cannot move the load or store to NewPt above its definition in D.
506           return false;
507 
508     // Check for unsafe hoistings due to side effects.
509     if (K == InsKind::Store) {
510       if (hasEHOrLoadsOnPath(NewPt, dyn_cast<MemoryDef>(U), NBBsOnAllPaths))
511         return false;
512     } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
513       return false;
514 
515     if (UBB == NewBB) {
516       if (DT->properlyDominates(DBB, NewBB))
517         return true;
518       assert(UBB == DBB);
519       assert(MSSA->locallyDominates(D, U));
520     }
521 
522     // No side effects: it is safe to hoist.
523     return true;
524   }
525 
526   // Return true when it is safe to hoist scalar instructions from all blocks in
527   // WL to HoistBB.
528   bool safeToHoistScalar(const BasicBlock *HoistBB, const BasicBlock *BB,
529                          int &NBBsOnAllPaths) {
530     return !hasEHOnPath(HoistBB, BB, NBBsOnAllPaths);
531   }
532 
533   // In the inverse CFG, the dominance frontier of basic block (BB) is the
534   // point where ANTIC needs to be computed for instructions which are going
535   // to be hoisted. Since this point does not change during gvn-hoist,
536   // we compute it only once (on demand).
537   // The ides is inspired from:
538   // "Partial Redundancy Elimination in SSA Form"
539   // ROBERT KENNEDY, SUN CHAN, SHIN-MING LIU, RAYMOND LO, PENG TU and FRED CHOW
540   // They use similar idea in the forward graph to to find fully redundant and
541   // partially redundant expressions, here it is used in the inverse graph to
542   // find fully anticipable instructions at merge point (post-dominator in
543   // the inverse CFG).
544   // Returns the edge via which an instruction in BB will get the values from.
545 
546   // Returns true when the values are flowing out to each edge.
547   bool valueAnticipable(CHIArgs C, TerminatorInst *TI) const {
548     if (TI->getNumSuccessors() > std::distance(C.begin(), C.end()))
549       return false; // Not enough args in this CHI.
550 
551     for (auto CHI : C) {
552       BasicBlock *Dest = CHI.Dest;
553       // Find if all the edges have values flowing out of BB.
554       bool Found = any_of(TI->successors(), [Dest](const BasicBlock *BB) {
555           return BB == Dest; });
556       if (!Found)
557         return false;
558     }
559     return true;
560   }
561 
562   // Check if it is safe to hoist values tracked by CHI in the range
563   // [Begin, End) and accumulate them in Safe.
564   void checkSafety(CHIArgs C, BasicBlock *BB, InsKind K,
565                    SmallVectorImpl<CHIArg> &Safe) {
566     int NumBBsOnAllPaths = MaxNumberOfBBSInPath;
567     for (auto CHI : C) {
568       Instruction *Insn = CHI.I;
569       if (!Insn) // No instruction was inserted in this CHI.
570         continue;
571       if (K == InsKind::Scalar) {
572         if (safeToHoistScalar(BB, Insn->getParent(), NumBBsOnAllPaths))
573           Safe.push_back(CHI);
574       } else {
575         MemoryUseOrDef *UD = MSSA->getMemoryAccess(Insn);
576         if (safeToHoistLdSt(BB->getTerminator(), Insn, UD, K, NumBBsOnAllPaths))
577           Safe.push_back(CHI);
578       }
579     }
580   }
581 
582   typedef DenseMap<VNType, SmallVector<Instruction *, 2>> RenameStackType;
583   // Push all the VNs corresponding to BB into RenameStack.
584   void fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,
585                        RenameStackType &RenameStack) {
586     auto it1 = ValueBBs.find(BB);
587     if (it1 != ValueBBs.end()) {
588       // Iterate in reverse order to keep lower ranked values on the top.
589       for (std::pair<VNType, Instruction *> &VI : reverse(it1->second)) {
590         // Get the value of instruction I
591         DEBUG(dbgs() << "\nPushing on stack: " << *VI.second);
592         RenameStack[VI.first].push_back(VI.second);
593       }
594     }
595   }
596 
597   void fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,
598                    RenameStackType &RenameStack) {
599     // For each *predecessor* (because Post-DOM) of BB check if it has a CHI
600     for (auto Pred : predecessors(BB)) {
601       auto P = CHIBBs.find(Pred);
602       if (P == CHIBBs.end()) {
603         continue;
604       }
605       DEBUG(dbgs() << "\nLooking at CHIs in: " << Pred->getName(););
606       // A CHI is found (BB -> Pred is an edge in the CFG)
607       // Pop the stack until Top(V) = Ve.
608       auto &VCHI = P->second;
609       for (auto It = VCHI.begin(), E = VCHI.end(); It != E;) {
610         CHIArg &C = *It;
611         if (!C.Dest) {
612           auto si = RenameStack.find(C.VN);
613           // The Basic Block where CHI is must dominate the value we want to
614           // track in a CHI. In the PDom walk, there can be values in the
615           // stack which are not control dependent e.g., nested loop.
616           if (si != RenameStack.end() && si->second.size() &&
617               DT->dominates(Pred, si->second.back()->getParent())) {
618             C.Dest = BB;                     // Assign the edge
619             C.I = si->second.pop_back_val(); // Assign the argument
620             DEBUG(dbgs() << "\nCHI Inserted in BB: " << C.Dest->getName()
621                          << *C.I << ", VN: " << C.VN.first << ", "
622                          << C.VN.second);
623           }
624           // Move to next CHI of a different value
625           It = std::find_if(It, VCHI.end(),
626                             [It](CHIArg &A) { return A != *It; });
627         } else
628           ++It;
629       }
630     }
631   }
632 
633   // Walk the post-dominator tree top-down and use a stack for each value to
634   // store the last value you see. When you hit a CHI from a given edge, the
635   // value to use as the argument is at the top of the stack, add the value to
636   // CHI and pop.
637   void insertCHI(InValuesType &ValueBBs, OutValuesType &CHIBBs) {
638     auto Root = PDT->getNode(nullptr);
639     if (!Root)
640       return;
641     // Depth first walk on PDom tree to fill the CHIargs at each PDF.
642     RenameStackType RenameStack;
643     for (auto Node : depth_first(Root)) {
644       BasicBlock *BB = Node->getBlock();
645       if (!BB)
646         continue;
647 
648       // Collect all values in BB and push to stack.
649       fillRenameStack(BB, ValueBBs, RenameStack);
650 
651       // Fill outgoing values in each CHI corresponding to BB.
652       fillChiArgs(BB, CHIBBs, RenameStack);
653     }
654   }
655 
656   // Walk all the CHI-nodes to find ones which have a empty-entry and remove
657   // them Then collect all the instructions which are safe to hoist and see if
658   // they form a list of anticipable values. OutValues contains CHIs
659   // corresponding to each basic block.
660   void findHoistableCandidates(OutValuesType &CHIBBs, InsKind K,
661                                HoistingPointList &HPL) {
662     auto cmpVN = [](const CHIArg &A, const CHIArg &B) { return A.VN < B.VN; };
663 
664     // CHIArgs now have the outgoing values, so check for anticipability and
665     // accumulate hoistable candidates in HPL.
666     for (std::pair<BasicBlock *, SmallVector<CHIArg, 2>> &A : CHIBBs) {
667       BasicBlock *BB = A.first;
668       SmallVectorImpl<CHIArg> &CHIs = A.second;
669       // Vector of PHIs contains PHIs for different instructions.
670       // Sort the args according to their VNs, such that identical
671       // instructions are together.
672       std::sort(CHIs.begin(), CHIs.end(), cmpVN);
673       auto TI = BB->getTerminator();
674       auto B = CHIs.begin();
675       // [PreIt, PHIIt) form a range of CHIs which have identical VNs.
676       auto PHIIt = std::find_if(CHIs.begin(), CHIs.end(),
677                                  [B](CHIArg &A) { return A != *B; });
678       auto PrevIt = CHIs.begin();
679       while (PrevIt != PHIIt) {
680         // Collect values which satisfy safety checks.
681         SmallVector<CHIArg, 2> Safe;
682         // We check for safety first because there might be multiple values in
683         // the same path, some of which are not safe to be hoisted, but overall
684         // each edge has at least one value which can be hoisted, making the
685         // value anticipable along that path.
686         checkSafety(make_range(PrevIt, PHIIt), BB, K, Safe);
687 
688         // List of safe values should be anticipable at TI.
689         if (valueAnticipable(make_range(Safe.begin(), Safe.end()), TI)) {
690           HPL.push_back({BB, SmallVecInsn()});
691           SmallVecInsn &V = HPL.back().second;
692           for (auto B : Safe)
693             V.push_back(B.I);
694         }
695 
696         // Check other VNs
697         PrevIt = PHIIt;
698         PHIIt = std::find_if(PrevIt, CHIs.end(),
699                              [PrevIt](CHIArg &A) { return A != *PrevIt; });
700       }
701     }
702   }
703 
704   // Compute insertion points for each values which can be fully anticipated at
705   // a dominator. HPL contains all such values.
706   void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
707                               InsKind K) {
708     // Sort VNs based on their rankings
709     std::vector<VNType> Ranks;
710     for (const auto &Entry : Map) {
711       Ranks.push_back(Entry.first);
712     }
713 
714     // TODO: Remove fully-redundant expressions.
715     // Get instruction from the Map, assume that all the Instructions
716     // with same VNs have same rank (this is an approximation).
717     std::sort(Ranks.begin(), Ranks.end(),
718               [this, &Map](const VNType &r1, const VNType &r2) {
719                 return (rank(*Map.lookup(r1).begin()) <
720                         rank(*Map.lookup(r2).begin()));
721               });
722 
723     // - Sort VNs according to their rank, and start with lowest ranked VN
724     // - Take a VN and for each instruction with same VN
725     //   - Find the dominance frontier in the inverse graph (PDF)
726     //   - Insert the chi-node at PDF
727     // - Remove the chi-nodes with missing entries
728     // - Remove values from CHI-nodes which do not truly flow out, e.g.,
729     //   modified along the path.
730     // - Collect the remaining values that are still anticipable
731     SmallVector<BasicBlock *, 2> IDFBlocks;
732     ReverseIDFCalculator IDFs(*PDT);
733     OutValuesType OutValue;
734     InValuesType InValue;
735     for (const auto &R : Ranks) {
736       const SmallVecInsn &V = Map.lookup(R);
737       if (V.size() < 2)
738         continue;
739       const VNType &VN = R;
740       SmallPtrSet<BasicBlock *, 2> VNBlocks;
741       for (auto &I : V) {
742         BasicBlock *BBI = I->getParent();
743         if (!hasEH(BBI))
744           VNBlocks.insert(BBI);
745       }
746       // Compute the Post Dominance Frontiers of each basic block
747       // The dominance frontier of a live block X in the reverse
748       // control graph is the set of blocks upon which X is control
749       // dependent. The following sequence computes the set of blocks
750       // which currently have dead terminators that are control
751       // dependence sources of a block which is in NewLiveBlocks.
752       IDFs.setDefiningBlocks(VNBlocks);
753       IDFs.calculate(IDFBlocks);
754 
755       // Make a map of BB vs instructions to be hoisted.
756       for (unsigned i = 0; i < V.size(); ++i) {
757         InValue[V[i]->getParent()].push_back(std::make_pair(VN, V[i]));
758       }
759       // Insert empty CHI node for this VN. This is used to factor out
760       // basic blocks where the ANTIC can potentially change.
761       for (auto IDFB : IDFBlocks) { // TODO: Prune out useless CHI insertions.
762         for (unsigned i = 0; i < V.size(); ++i) {
763           CHIArg C = {VN, nullptr, nullptr};
764           if (DT->dominates(IDFB, V[i]->getParent())) { // Ignore spurious PDFs.
765             // InValue[V[i]->getParent()].push_back(std::make_pair(VN, V[i]));
766             OutValue[IDFB].push_back(C);
767             DEBUG(dbgs() << "\nInsertion a CHI for BB: " << IDFB->getName()
768                          << ", for Insn: " << *V[i]);
769           }
770         }
771       }
772     }
773 
774     // Insert CHI args at each PDF to iterate on factored graph of
775     // control dependence.
776     insertCHI(InValue, OutValue);
777     // Using the CHI args inserted at each PDF, find fully anticipable values.
778     findHoistableCandidates(OutValue, K, HPL);
779   }
780 
781   // Return true when all operands of Instr are available at insertion point
782   // HoistPt. When limiting the number of hoisted expressions, one could hoist
783   // a load without hoisting its access function. So before hoisting any
784   // expression, make sure that all its operands are available at insert point.
785   bool allOperandsAvailable(const Instruction *I,
786                             const BasicBlock *HoistPt) const {
787     for (const Use &Op : I->operands())
788       if (const auto *Inst = dyn_cast<Instruction>(&Op))
789         if (!DT->dominates(Inst->getParent(), HoistPt))
790           return false;
791 
792     return true;
793   }
794 
795   // Same as allOperandsAvailable with recursive check for GEP operands.
796   bool allGepOperandsAvailable(const Instruction *I,
797                                const BasicBlock *HoistPt) const {
798     for (const Use &Op : I->operands())
799       if (const auto *Inst = dyn_cast<Instruction>(&Op))
800         if (!DT->dominates(Inst->getParent(), HoistPt)) {
801           if (const GetElementPtrInst *GepOp =
802                   dyn_cast<GetElementPtrInst>(Inst)) {
803             if (!allGepOperandsAvailable(GepOp, HoistPt))
804               return false;
805             // Gep is available if all operands of GepOp are available.
806           } else {
807             // Gep is not available if it has operands other than GEPs that are
808             // defined in blocks not dominating HoistPt.
809             return false;
810           }
811         }
812     return true;
813   }
814 
815   // Make all operands of the GEP available.
816   void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
817                          const SmallVecInsn &InstructionsToHoist,
818                          Instruction *Gep) const {
819     assert(allGepOperandsAvailable(Gep, HoistPt) &&
820            "GEP operands not available");
821 
822     Instruction *ClonedGep = Gep->clone();
823     for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
824       if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
825 
826         // Check whether the operand is already available.
827         if (DT->dominates(Op->getParent(), HoistPt))
828           continue;
829 
830         // As a GEP can refer to other GEPs, recursively make all the operands
831         // of this GEP available at HoistPt.
832         if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
833           makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
834       }
835 
836     // Copy Gep and replace its uses in Repl with ClonedGep.
837     ClonedGep->insertBefore(HoistPt->getTerminator());
838 
839     // Conservatively discard any optimization hints, they may differ on the
840     // other paths.
841     ClonedGep->dropUnknownNonDebugMetadata();
842 
843     // If we have optimization hints which agree with each other along different
844     // paths, preserve them.
845     for (const Instruction *OtherInst : InstructionsToHoist) {
846       const GetElementPtrInst *OtherGep;
847       if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
848         OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
849       else
850         OtherGep = cast<GetElementPtrInst>(
851             cast<StoreInst>(OtherInst)->getPointerOperand());
852       ClonedGep->andIRFlags(OtherGep);
853     }
854 
855     // Replace uses of Gep with ClonedGep in Repl.
856     Repl->replaceUsesOfWith(Gep, ClonedGep);
857   }
858 
859   void updateAlignment(Instruction *I, Instruction *Repl) {
860     if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
861       ReplacementLoad->setAlignment(
862           std::min(ReplacementLoad->getAlignment(),
863                    cast<LoadInst>(I)->getAlignment()));
864       ++NumLoadsRemoved;
865     } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
866       ReplacementStore->setAlignment(
867           std::min(ReplacementStore->getAlignment(),
868                    cast<StoreInst>(I)->getAlignment()));
869       ++NumStoresRemoved;
870     } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
871       ReplacementAlloca->setAlignment(
872           std::max(ReplacementAlloca->getAlignment(),
873                    cast<AllocaInst>(I)->getAlignment()));
874     } else if (isa<CallInst>(Repl)) {
875       ++NumCallsRemoved;
876     }
877   }
878 
879   // Remove all the instructions in Candidates and replace their usage with Repl.
880   // Returns the number of instructions removed.
881   unsigned rauw(const SmallVecInsn &Candidates, Instruction *Repl,
882                 MemoryUseOrDef *NewMemAcc) {
883     unsigned NR = 0;
884     for (Instruction *I : Candidates) {
885       if (I != Repl) {
886         ++NR;
887         updateAlignment(I, Repl);
888         if (NewMemAcc) {
889           // Update the uses of the old MSSA access with NewMemAcc.
890           MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
891           OldMA->replaceAllUsesWith(NewMemAcc);
892           MSSAUpdater->removeMemoryAccess(OldMA);
893         }
894 
895         Repl->andIRFlags(I);
896         combineKnownMetadata(Repl, I);
897         I->replaceAllUsesWith(Repl);
898         // Also invalidate the Alias Analysis cache.
899         MD->removeInstruction(I);
900         I->eraseFromParent();
901       }
902     }
903     return NR;
904   }
905 
906   // Replace all Memory PHI usage with NewMemAcc.
907   void raMPHIuw(MemoryUseOrDef *NewMemAcc) {
908     SmallPtrSet<MemoryPhi *, 4> UsePhis;
909     for (User *U : NewMemAcc->users())
910       if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
911         UsePhis.insert(Phi);
912 
913     for (MemoryPhi *Phi : UsePhis) {
914       auto In = Phi->incoming_values();
915       if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
916         Phi->replaceAllUsesWith(NewMemAcc);
917         MSSAUpdater->removeMemoryAccess(Phi);
918       }
919     }
920   }
921 
922   // Remove all other instructions and replace them with Repl.
923   unsigned removeAndReplace(const SmallVecInsn &Candidates, Instruction *Repl,
924                             BasicBlock *DestBB, bool MoveAccess) {
925     MemoryUseOrDef *NewMemAcc = MSSA->getMemoryAccess(Repl);
926     if (MoveAccess && NewMemAcc) {
927         // The definition of this ld/st will not change: ld/st hoisting is
928         // legal when the ld/st is not moved past its current definition.
929         MSSAUpdater->moveToPlace(NewMemAcc, DestBB, MemorySSA::End);
930     }
931 
932     // Replace all other instructions with Repl with memory access NewMemAcc.
933     unsigned NR = rauw(Candidates, Repl, NewMemAcc);
934 
935     // Remove MemorySSA phi nodes with the same arguments.
936     if (NewMemAcc)
937       raMPHIuw(NewMemAcc);
938     return NR;
939   }
940 
941   // In the case Repl is a load or a store, we make all their GEPs
942   // available: GEPs are not hoisted by default to avoid the address
943   // computations to be hoisted without the associated load or store.
944   bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
945                                 const SmallVecInsn &InstructionsToHoist) const {
946     // Check whether the GEP of a ld/st can be synthesized at HoistPt.
947     GetElementPtrInst *Gep = nullptr;
948     Instruction *Val = nullptr;
949     if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
950       Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
951     } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
952       Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
953       Val = dyn_cast<Instruction>(St->getValueOperand());
954       // Check that the stored value is available.
955       if (Val) {
956         if (isa<GetElementPtrInst>(Val)) {
957           // Check whether we can compute the GEP at HoistPt.
958           if (!allGepOperandsAvailable(Val, HoistPt))
959             return false;
960         } else if (!DT->dominates(Val->getParent(), HoistPt))
961           return false;
962       }
963     }
964 
965     // Check whether we can compute the Gep at HoistPt.
966     if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
967       return false;
968 
969     makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
970 
971     if (Val && isa<GetElementPtrInst>(Val))
972       makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
973 
974     return true;
975   }
976 
977   std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) {
978     unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
979     for (const HoistingPointInfo &HP : HPL) {
980       // Find out whether we already have one of the instructions in HoistPt,
981       // in which case we do not have to move it.
982       BasicBlock *DestBB = HP.first;
983       const SmallVecInsn &InstructionsToHoist = HP.second;
984       Instruction *Repl = nullptr;
985       for (Instruction *I : InstructionsToHoist)
986         if (I->getParent() == DestBB)
987           // If there are two instructions in HoistPt to be hoisted in place:
988           // update Repl to be the first one, such that we can rename the uses
989           // of the second based on the first.
990           if (!Repl || firstInBB(I, Repl))
991             Repl = I;
992 
993       // Keep track of whether we moved the instruction so we know whether we
994       // should move the MemoryAccess.
995       bool MoveAccess = true;
996       if (Repl) {
997         // Repl is already in HoistPt: it remains in place.
998         assert(allOperandsAvailable(Repl, DestBB) &&
999                "instruction depends on operands that are not available");
1000         MoveAccess = false;
1001       } else {
1002         // When we do not find Repl in HoistPt, select the first in the list
1003         // and move it to HoistPt.
1004         Repl = InstructionsToHoist.front();
1005 
1006         // We can move Repl in HoistPt only when all operands are available.
1007         // The order in which hoistings are done may influence the availability
1008         // of operands.
1009         if (!allOperandsAvailable(Repl, DestBB)) {
1010 
1011           // When HoistingGeps there is nothing more we can do to make the
1012           // operands available: just continue.
1013           if (HoistingGeps)
1014             continue;
1015 
1016           // When not HoistingGeps we need to copy the GEPs.
1017           if (!makeGepOperandsAvailable(Repl, DestBB, InstructionsToHoist))
1018             continue;
1019         }
1020 
1021         // Move the instruction at the end of HoistPt.
1022         Instruction *Last = DestBB->getTerminator();
1023         MD->removeInstruction(Repl);
1024         Repl->moveBefore(Last);
1025 
1026         DFSNumber[Repl] = DFSNumber[Last]++;
1027       }
1028 
1029       NR += removeAndReplace(InstructionsToHoist, Repl, DestBB, MoveAccess);
1030 
1031 
1032       if (isa<LoadInst>(Repl))
1033         ++NL;
1034       else if (isa<StoreInst>(Repl))
1035         ++NS;
1036       else if (isa<CallInst>(Repl))
1037         ++NC;
1038       else // Scalar
1039         ++NI;
1040     }
1041 
1042     NumHoisted += NL + NS + NC + NI;
1043     NumRemoved += NR;
1044     NumLoadsHoisted += NL;
1045     NumStoresHoisted += NS;
1046     NumCallsHoisted += NC;
1047     return {NI, NL + NC + NS};
1048   }
1049 
1050   // Hoist all expressions. Returns Number of scalars hoisted
1051   // and number of non-scalars hoisted.
1052   std::pair<unsigned, unsigned> hoistExpressions(Function &F) {
1053     InsnInfo II;
1054     LoadInfo LI;
1055     StoreInfo SI;
1056     CallInfo CI;
1057     for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
1058       int InstructionNb = 0;
1059       for (Instruction &I1 : *BB) {
1060         // If I1 cannot guarantee progress, subsequent instructions
1061         // in BB cannot be hoisted anyways.
1062         if (!isGuaranteedToTransferExecutionToSuccessor(&I1)) {
1063           HoistBarrier.insert(BB);
1064           break;
1065         }
1066         // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
1067         // deeper may increase the register pressure and compilation time.
1068         if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)
1069           break;
1070 
1071         // Do not value number terminator instructions.
1072         if (isa<TerminatorInst>(&I1))
1073           break;
1074 
1075         if (auto *Load = dyn_cast<LoadInst>(&I1))
1076           LI.insert(Load, VN);
1077         else if (auto *Store = dyn_cast<StoreInst>(&I1))
1078           SI.insert(Store, VN);
1079         else if (auto *Call = dyn_cast<CallInst>(&I1)) {
1080           if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
1081             if (isa<DbgInfoIntrinsic>(Intr) ||
1082                 Intr->getIntrinsicID() == Intrinsic::assume)
1083               continue;
1084           }
1085           if (Call->mayHaveSideEffects())
1086             break;
1087 
1088           if (Call->isConvergent())
1089             break;
1090 
1091           CI.insert(Call, VN);
1092         } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
1093           // Do not hoist scalars past calls that may write to memory because
1094           // that could result in spills later. geps are handled separately.
1095           // TODO: We can relax this for targets like AArch64 as they have more
1096           // registers than X86.
1097           II.insert(&I1, VN);
1098       }
1099     }
1100 
1101     HoistingPointList HPL;
1102     computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
1103     computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
1104     computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
1105     computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
1106     computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
1107     computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
1108     return hoist(HPL);
1109   }
1110 };
1111 
1112 class GVNHoistLegacyPass : public FunctionPass {
1113 public:
1114   static char ID;
1115 
1116   GVNHoistLegacyPass() : FunctionPass(ID) {
1117     initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry());
1118   }
1119 
1120   bool runOnFunction(Function &F) override {
1121     if (skipFunction(F))
1122       return false;
1123     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1124     auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
1125     auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1126     auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1127     auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1128 
1129     GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA);
1130     return G.run(F);
1131   }
1132 
1133   void getAnalysisUsage(AnalysisUsage &AU) const override {
1134     AU.addRequired<DominatorTreeWrapperPass>();
1135     AU.addRequired<PostDominatorTreeWrapperPass>();
1136     AU.addRequired<AAResultsWrapperPass>();
1137     AU.addRequired<MemoryDependenceWrapperPass>();
1138     AU.addRequired<MemorySSAWrapperPass>();
1139     AU.addPreserved<DominatorTreeWrapperPass>();
1140     AU.addPreserved<MemorySSAWrapperPass>();
1141     AU.addPreserved<GlobalsAAWrapperPass>();
1142   }
1143 };
1144 } // namespace llvm
1145 
1146 PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) {
1147   DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
1148   PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);
1149   AliasAnalysis &AA = AM.getResult<AAManager>(F);
1150   MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
1151   MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1152   GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA);
1153   if (!G.run(F))
1154     return PreservedAnalyses::all();
1155 
1156   PreservedAnalyses PA;
1157   PA.preserve<DominatorTreeAnalysis>();
1158   PA.preserve<MemorySSAAnalysis>();
1159   PA.preserve<GlobalsAA>();
1160   return PA;
1161 }
1162 
1163 char GVNHoistLegacyPass::ID = 0;
1164 INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist",
1165                       "Early GVN Hoisting of Expressions", false, false)
1166 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
1167 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1168 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1169 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1170 INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist",
1171                     "Early GVN Hoisting of Expressions", false, false)
1172 
1173 FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); }
1174