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 // Hoisting may affect the performance in some cases. To mitigate that, hoisting
17 // is disabled in the following cases.
18 // 1. Scalars across calls.
19 // 2. geps when corresponding load/store cannot be hoisted.
20 //
21 // TODO: Hoist from >2 successors. Currently GVNHoist will not hoist stores
22 // in this case because it works on two instructions at a time.
23 // entry:
24 //   switch i32 %c1, label %exit1 [
25 //     i32 0, label %sw0
26 //     i32 1, label %sw1
27 //   ]
28 //
29 // sw0:
30 //   store i32 1, i32* @G
31 //   br label %exit
32 //
33 // sw1:
34 //   store i32 1, i32* @G
35 //   br label %exit
36 //
37 // exit1:
38 //   store i32 1, i32* @G
39 //   ret void
40 // exit:
41 //   ret void
42 //===----------------------------------------------------------------------===//
43 
44 #include "llvm/ADT/DenseMap.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Analysis/GlobalsModRef.h"
48 #include "llvm/Analysis/MemorySSA.h"
49 #include "llvm/Analysis/MemorySSAUpdater.h"
50 #include "llvm/Analysis/ValueTracking.h"
51 #include "llvm/Transforms/Scalar.h"
52 #include "llvm/Transforms/Scalar/GVN.h"
53 #include "llvm/Transforms/Utils/Local.h"
54 
55 using namespace llvm;
56 
57 #define DEBUG_TYPE "gvn-hoist"
58 
59 STATISTIC(NumHoisted, "Number of instructions hoisted");
60 STATISTIC(NumRemoved, "Number of instructions removed");
61 STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
62 STATISTIC(NumLoadsRemoved, "Number of loads removed");
63 STATISTIC(NumStoresHoisted, "Number of stores hoisted");
64 STATISTIC(NumStoresRemoved, "Number of stores removed");
65 STATISTIC(NumCallsHoisted, "Number of calls hoisted");
66 STATISTIC(NumCallsRemoved, "Number of calls removed");
67 
68 static cl::opt<int>
69     MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1),
70                         cl::desc("Max number of instructions to hoist "
71                                  "(default unlimited = -1)"));
72 static cl::opt<int> MaxNumberOfBBSInPath(
73     "gvn-hoist-max-bbs", cl::Hidden, cl::init(4),
74     cl::desc("Max number of basic blocks on the path between "
75              "hoisting locations (default = 4, unlimited = -1)"));
76 
77 static cl::opt<int> MaxDepthInBB(
78     "gvn-hoist-max-depth", cl::Hidden, cl::init(100),
79     cl::desc("Hoist instructions from the beginning of the BB up to the "
80              "maximum specified depth (default = 100, unlimited = -1)"));
81 
82 static cl::opt<int>
83     MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10),
84                    cl::desc("Maximum length of dependent chains to hoist "
85                             "(default = 10, unlimited = -1)"));
86 
87 namespace llvm {
88 
89 // Provides a sorting function based on the execution order of two instructions.
90 struct SortByDFSIn {
91 private:
92   DenseMap<const Value *, unsigned> &DFSNumber;
93 
94 public:
95   SortByDFSIn(DenseMap<const Value *, unsigned> &D) : DFSNumber(D) {}
96 
97   // Returns true when A executes before B.
98   bool operator()(const Instruction *A, const Instruction *B) const {
99     const BasicBlock *BA = A->getParent();
100     const BasicBlock *BB = B->getParent();
101     unsigned ADFS, BDFS;
102     if (BA == BB) {
103       ADFS = DFSNumber.lookup(A);
104       BDFS = DFSNumber.lookup(B);
105     } else {
106       ADFS = DFSNumber.lookup(BA);
107       BDFS = DFSNumber.lookup(BB);
108     }
109     assert(ADFS && BDFS);
110     return ADFS < BDFS;
111   }
112 };
113 
114 // A map from a pair of VNs to all the instructions with those VNs.
115 typedef DenseMap<std::pair<unsigned, unsigned>, SmallVector<Instruction *, 4>>
116     VNtoInsns;
117 // An invalid value number Used when inserting a single value number into
118 // VNtoInsns.
119 enum : unsigned { InvalidVN = ~2U };
120 
121 // Records all scalar instructions candidate for code hoisting.
122 class InsnInfo {
123   VNtoInsns VNtoScalars;
124 
125 public:
126   // Inserts I and its value number in VNtoScalars.
127   void insert(Instruction *I, GVN::ValueTable &VN) {
128     // Scalar instruction.
129     unsigned V = VN.lookupOrAdd(I);
130     VNtoScalars[{V, InvalidVN}].push_back(I);
131   }
132 
133   const VNtoInsns &getVNTable() const { return VNtoScalars; }
134 };
135 
136 // Records all load instructions candidate for code hoisting.
137 class LoadInfo {
138   VNtoInsns VNtoLoads;
139 
140 public:
141   // Insert Load and the value number of its memory address in VNtoLoads.
142   void insert(LoadInst *Load, GVN::ValueTable &VN) {
143     if (Load->isSimple()) {
144       unsigned V = VN.lookupOrAdd(Load->getPointerOperand());
145       VNtoLoads[{V, InvalidVN}].push_back(Load);
146     }
147   }
148 
149   const VNtoInsns &getVNTable() const { return VNtoLoads; }
150 };
151 
152 // Records all store instructions candidate for code hoisting.
153 class StoreInfo {
154   VNtoInsns VNtoStores;
155 
156 public:
157   // Insert the Store and a hash number of the store address and the stored
158   // value in VNtoStores.
159   void insert(StoreInst *Store, GVN::ValueTable &VN) {
160     if (!Store->isSimple())
161       return;
162     // Hash the store address and the stored value.
163     Value *Ptr = Store->getPointerOperand();
164     Value *Val = Store->getValueOperand();
165     VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
166   }
167 
168   const VNtoInsns &getVNTable() const { return VNtoStores; }
169 };
170 
171 // Records all call instructions candidate for code hoisting.
172 class CallInfo {
173   VNtoInsns VNtoCallsScalars;
174   VNtoInsns VNtoCallsLoads;
175   VNtoInsns VNtoCallsStores;
176 
177 public:
178   // Insert Call and its value numbering in one of the VNtoCalls* containers.
179   void insert(CallInst *Call, GVN::ValueTable &VN) {
180     // A call that doesNotAccessMemory is handled as a Scalar,
181     // onlyReadsMemory will be handled as a Load instruction,
182     // all other calls will be handled as stores.
183     unsigned V = VN.lookupOrAdd(Call);
184     auto Entry = std::make_pair(V, InvalidVN);
185 
186     if (Call->doesNotAccessMemory())
187       VNtoCallsScalars[Entry].push_back(Call);
188     else if (Call->onlyReadsMemory())
189       VNtoCallsLoads[Entry].push_back(Call);
190     else
191       VNtoCallsStores[Entry].push_back(Call);
192   }
193 
194   const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }
195 
196   const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }
197 
198   const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }
199 };
200 
201 typedef DenseMap<const BasicBlock *, bool> BBSideEffectsSet;
202 typedef SmallVector<Instruction *, 4> SmallVecInsn;
203 typedef SmallVectorImpl<Instruction *> SmallVecImplInsn;
204 
205 static void combineKnownMetadata(Instruction *ReplInst, Instruction *I) {
206   static const unsigned KnownIDs[] = {
207       LLVMContext::MD_tbaa,           LLVMContext::MD_alias_scope,
208       LLVMContext::MD_noalias,        LLVMContext::MD_range,
209       LLVMContext::MD_fpmath,         LLVMContext::MD_invariant_load,
210       LLVMContext::MD_invariant_group};
211   combineMetadata(ReplInst, I, KnownIDs);
212 }
213 
214 // This pass hoists common computations across branches sharing common
215 // dominator. The primary goal is to reduce the code size, and in some
216 // cases reduce critical path (by exposing more ILP).
217 class GVNHoist {
218 public:
219   GVNHoist(DominatorTree *DT, AliasAnalysis *AA, MemoryDependenceResults *MD,
220            MemorySSA *MSSA)
221       : DT(DT), AA(AA), MD(MD), MSSA(MSSA),
222         MSSAUpdater(make_unique<MemorySSAUpdater>(MSSA)),
223         HoistingGeps(false),
224         HoistedCtr(0)
225   { }
226 
227   bool run(Function &F) {
228     VN.setDomTree(DT);
229     VN.setAliasAnalysis(AA);
230     VN.setMemDep(MD);
231     bool Res = false;
232     // Perform DFS Numbering of instructions.
233     unsigned BBI = 0;
234     for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) {
235       DFSNumber[BB] = ++BBI;
236       unsigned I = 0;
237       for (auto &Inst : *BB)
238         DFSNumber[&Inst] = ++I;
239     }
240 
241     int ChainLength = 0;
242 
243     // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
244     while (1) {
245       if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)
246         return Res;
247 
248       auto HoistStat = hoistExpressions(F);
249       if (HoistStat.first + HoistStat.second == 0)
250         return Res;
251 
252       if (HoistStat.second > 0)
253         // To address a limitation of the current GVN, we need to rerun the
254         // hoisting after we hoisted loads or stores in order to be able to
255         // hoist all scalars dependent on the hoisted ld/st.
256         VN.clear();
257 
258       Res = true;
259     }
260 
261     return Res;
262   }
263 
264 private:
265   GVN::ValueTable VN;
266   DominatorTree *DT;
267   AliasAnalysis *AA;
268   MemoryDependenceResults *MD;
269   MemorySSA *MSSA;
270   std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
271   const bool HoistingGeps;
272   DenseMap<const Value *, unsigned> DFSNumber;
273   BBSideEffectsSet BBSideEffects;
274   DenseSet<const BasicBlock*> HoistBarrier;
275   int HoistedCtr;
276 
277   enum InsKind { Unknown, Scalar, Load, Store };
278 
279   // Return true when there are exception handling in BB.
280   bool hasEH(const BasicBlock *BB) {
281     auto It = BBSideEffects.find(BB);
282     if (It != BBSideEffects.end())
283       return It->second;
284 
285     if (BB->isEHPad() || BB->hasAddressTaken()) {
286       BBSideEffects[BB] = true;
287       return true;
288     }
289 
290     if (BB->getTerminator()->mayThrow()) {
291       BBSideEffects[BB] = true;
292       return true;
293     }
294 
295     BBSideEffects[BB] = false;
296     return false;
297   }
298 
299   // Return true when a successor of BB dominates A.
300   bool successorDominate(const BasicBlock *BB, const BasicBlock *A) {
301     for (const BasicBlock *Succ : BB->getTerminator()->successors())
302       if (DT->dominates(Succ, A))
303         return true;
304 
305     return false;
306   }
307 
308   // Return true when all paths from HoistBB to the end of the function pass
309   // through one of the blocks in WL.
310   bool hoistingFromAllPaths(const BasicBlock *HoistBB,
311                             SmallPtrSetImpl<const BasicBlock *> &WL) {
312 
313     // Copy WL as the loop will remove elements from it.
314     SmallPtrSet<const BasicBlock *, 2> WorkList(WL.begin(), WL.end());
315 
316     for (auto It = df_begin(HoistBB), E = df_end(HoistBB); It != E;) {
317       // There exists a path from HoistBB to the exit of the function if we are
318       // still iterating in DF traversal and we removed all instructions from
319       // the work list.
320       if (WorkList.empty())
321         return false;
322 
323       const BasicBlock *BB = *It;
324       if (WorkList.erase(BB)) {
325         // Stop DFS traversal when BB is in the work list.
326         It.skipChildren();
327         continue;
328       }
329 
330       // We reached the leaf Basic Block => not all paths have this instruction.
331       if (!BB->getTerminator()->getNumSuccessors())
332         return false;
333 
334       // When reaching the back-edge of a loop, there may be a path through the
335       // loop that does not pass through B or C before exiting the loop.
336       if (successorDominate(BB, HoistBB))
337         return false;
338 
339       // Increment DFS traversal when not skipping children.
340       ++It;
341     }
342 
343     return true;
344   }
345 
346   /* Return true when I1 appears before I2 in the instructions of BB.  */
347   bool firstInBB(const Instruction *I1, const Instruction *I2) {
348     assert(I1->getParent() == I2->getParent());
349     unsigned I1DFS = DFSNumber.lookup(I1);
350     unsigned I2DFS = DFSNumber.lookup(I2);
351     assert(I1DFS && I2DFS);
352     return I1DFS < I2DFS;
353   }
354 
355   // Return true when there are memory uses of Def in BB.
356   bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,
357                     const BasicBlock *BB) {
358     const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
359     if (!Acc)
360       return false;
361 
362     Instruction *OldPt = Def->getMemoryInst();
363     const BasicBlock *OldBB = OldPt->getParent();
364     const BasicBlock *NewBB = NewPt->getParent();
365     bool ReachedNewPt = false;
366 
367     for (const MemoryAccess &MA : *Acc)
368       if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {
369         Instruction *Insn = MU->getMemoryInst();
370 
371         // Do not check whether MU aliases Def when MU occurs after OldPt.
372         if (BB == OldBB && firstInBB(OldPt, Insn))
373           break;
374 
375         // Do not check whether MU aliases Def when MU occurs before NewPt.
376         if (BB == NewBB) {
377           if (!ReachedNewPt) {
378             if (firstInBB(Insn, NewPt))
379               continue;
380             ReachedNewPt = true;
381           }
382         }
383         if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA))
384           return true;
385       }
386 
387     return false;
388   }
389 
390   // Return true when there are exception handling or loads of memory Def
391   // between Def and NewPt.  This function is only called for stores: Def is
392   // the MemoryDef of the store to be hoisted.
393 
394   // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
395   // return true when the counter NBBsOnAllPaths reaces 0, except when it is
396   // initialized to -1 which is unlimited.
397   bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
398                           int &NBBsOnAllPaths) {
399     const BasicBlock *NewBB = NewPt->getParent();
400     const BasicBlock *OldBB = Def->getBlock();
401     assert(DT->dominates(NewBB, OldBB) && "invalid path");
402     assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&
403            "def does not dominate new hoisting point");
404 
405     // Walk all basic blocks reachable in depth-first iteration on the inverse
406     // CFG from OldBB to NewBB. These blocks are all the blocks that may be
407     // executed between the execution of NewBB and OldBB. Hoisting an expression
408     // from OldBB into NewBB has to be safe on all execution paths.
409     for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {
410       const BasicBlock *BB = *I;
411       if (BB == NewBB) {
412         // Stop traversal when reaching HoistPt.
413         I.skipChildren();
414         continue;
415       }
416 
417       // Stop walk once the limit is reached.
418       if (NBBsOnAllPaths == 0)
419         return true;
420 
421       // Impossible to hoist with exceptions on the path.
422       if (hasEH(BB))
423         return true;
424 
425       // No such instruction after HoistBarrier in a basic block was
426       // selected for hoisting so instructions selected within basic block with
427       // a hoist barrier can be hoisted.
428       if ((BB != OldBB) && HoistBarrier.count(BB))
429         return true;
430 
431       // Check that we do not move a store past loads.
432       if (hasMemoryUse(NewPt, Def, BB))
433         return true;
434 
435       // -1 is unlimited number of blocks on all paths.
436       if (NBBsOnAllPaths != -1)
437         --NBBsOnAllPaths;
438 
439       ++I;
440     }
441 
442     return false;
443   }
444 
445   // Return true when there are exception handling between HoistPt and BB.
446   // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
447   // return true when the counter NBBsOnAllPaths reaches 0, except when it is
448   // initialized to -1 which is unlimited.
449   bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
450                    int &NBBsOnAllPaths) {
451     assert(DT->dominates(HoistPt, SrcBB) && "Invalid path");
452 
453     // Walk all basic blocks reachable in depth-first iteration on
454     // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the
455     // blocks that may be executed between the execution of NewHoistPt and
456     // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe
457     // on all execution paths.
458     for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) {
459       const BasicBlock *BB = *I;
460       if (BB == HoistPt) {
461         // Stop traversal when reaching NewHoistPt.
462         I.skipChildren();
463         continue;
464       }
465 
466       // Stop walk once the limit is reached.
467       if (NBBsOnAllPaths == 0)
468         return true;
469 
470       // Impossible to hoist with exceptions on the path.
471       if (hasEH(BB))
472         return true;
473 
474       // No such instruction after HoistBarrier in a basic block was
475       // selected for hoisting so instructions selected within basic block with
476       // a hoist barrier can be hoisted.
477       if ((BB != SrcBB) && HoistBarrier.count(BB))
478         return true;
479 
480       // -1 is unlimited number of blocks on all paths.
481       if (NBBsOnAllPaths != -1)
482         --NBBsOnAllPaths;
483 
484       ++I;
485     }
486 
487     return false;
488   }
489 
490   // Return true when it is safe to hoist a memory load or store U from OldPt
491   // to NewPt.
492   bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
493                        MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths) {
494 
495     // In place hoisting is safe.
496     if (NewPt == OldPt)
497       return true;
498 
499     const BasicBlock *NewBB = NewPt->getParent();
500     const BasicBlock *OldBB = OldPt->getParent();
501     const BasicBlock *UBB = U->getBlock();
502 
503     // Check for dependences on the Memory SSA.
504     MemoryAccess *D = U->getDefiningAccess();
505     BasicBlock *DBB = D->getBlock();
506     if (DT->properlyDominates(NewBB, DBB))
507       // Cannot move the load or store to NewBB above its definition in DBB.
508       return false;
509 
510     if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))
511       if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
512         if (firstInBB(NewPt, UD->getMemoryInst()))
513           // Cannot move the load or store to NewPt above its definition in D.
514           return false;
515 
516     // Check for unsafe hoistings due to side effects.
517     if (K == InsKind::Store) {
518       if (hasEHOrLoadsOnPath(NewPt, dyn_cast<MemoryDef>(U), NBBsOnAllPaths))
519         return false;
520     } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
521       return false;
522 
523     if (UBB == NewBB) {
524       if (DT->properlyDominates(DBB, NewBB))
525         return true;
526       assert(UBB == DBB);
527       assert(MSSA->locallyDominates(D, U));
528     }
529 
530     // No side effects: it is safe to hoist.
531     return true;
532   }
533 
534   // Return true when it is safe to hoist scalar instructions from all blocks in
535   // WL to HoistBB.
536   bool safeToHoistScalar(const BasicBlock *HoistBB,
537                          SmallPtrSetImpl<const BasicBlock *> &WL,
538                          int &NBBsOnAllPaths) {
539     // Check that the hoisted expression is needed on all paths.
540     if (!hoistingFromAllPaths(HoistBB, WL))
541       return false;
542 
543     for (const BasicBlock *BB : WL)
544       if (hasEHOnPath(HoistBB, BB, NBBsOnAllPaths))
545         return false;
546 
547     return true;
548   }
549 
550   // Each element of a hoisting list contains the basic block where to hoist and
551   // a list of instructions to be hoisted.
552   typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo;
553   typedef SmallVector<HoistingPointInfo, 4> HoistingPointList;
554 
555   // Partition InstructionsToHoist into a set of candidates which can share a
556   // common hoisting point. The partitions are collected in HPL. IsScalar is
557   // true when the instructions in InstructionsToHoist are scalars. IsLoad is
558   // true when the InstructionsToHoist are loads, false when they are stores.
559   void partitionCandidates(SmallVecImplInsn &InstructionsToHoist,
560                            HoistingPointList &HPL, InsKind K) {
561     // No need to sort for two instructions.
562     if (InstructionsToHoist.size() > 2) {
563       SortByDFSIn Pred(DFSNumber);
564       std::sort(InstructionsToHoist.begin(), InstructionsToHoist.end(), Pred);
565     }
566 
567     int NumBBsOnAllPaths = MaxNumberOfBBSInPath;
568 
569     SmallVecImplInsn::iterator II = InstructionsToHoist.begin();
570     SmallVecImplInsn::iterator Start = II;
571     Instruction *HoistPt = *II;
572     BasicBlock *HoistBB = HoistPt->getParent();
573     MemoryUseOrDef *UD;
574     if (K != InsKind::Scalar)
575       UD = MSSA->getMemoryAccess(HoistPt);
576 
577     for (++II; II != InstructionsToHoist.end(); ++II) {
578       Instruction *Insn = *II;
579       BasicBlock *BB = Insn->getParent();
580       BasicBlock *NewHoistBB;
581       Instruction *NewHoistPt;
582 
583       if (BB == HoistBB) { // Both are in the same Basic Block.
584         NewHoistBB = HoistBB;
585         NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt;
586       } else {
587         // If the hoisting point contains one of the instructions,
588         // then hoist there, otherwise hoist before the terminator.
589         NewHoistBB = DT->findNearestCommonDominator(HoistBB, BB);
590         if (NewHoistBB == BB)
591           NewHoistPt = Insn;
592         else if (NewHoistBB == HoistBB)
593           NewHoistPt = HoistPt;
594         else
595           NewHoistPt = NewHoistBB->getTerminator();
596       }
597 
598       SmallPtrSet<const BasicBlock *, 2> WL;
599       WL.insert(HoistBB);
600       WL.insert(BB);
601 
602       if (K == InsKind::Scalar) {
603         if (safeToHoistScalar(NewHoistBB, WL, NumBBsOnAllPaths)) {
604           // Extend HoistPt to NewHoistPt.
605           HoistPt = NewHoistPt;
606           HoistBB = NewHoistBB;
607           continue;
608         }
609       } else {
610         // When NewBB already contains an instruction to be hoisted, the
611         // expression is needed on all paths.
612         // Check that the hoisted expression is needed on all paths: it is
613         // unsafe to hoist loads to a place where there may be a path not
614         // loading from the same address: for instance there may be a branch on
615         // which the address of the load may not be initialized.
616         if ((HoistBB == NewHoistBB || BB == NewHoistBB ||
617              hoistingFromAllPaths(NewHoistBB, WL)) &&
618             // Also check that it is safe to move the load or store from HoistPt
619             // to NewHoistPt, and from Insn to NewHoistPt.
620             safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NumBBsOnAllPaths) &&
621             safeToHoistLdSt(NewHoistPt, Insn, MSSA->getMemoryAccess(Insn),
622                             K, NumBBsOnAllPaths)) {
623           // Extend HoistPt to NewHoistPt.
624           HoistPt = NewHoistPt;
625           HoistBB = NewHoistBB;
626           continue;
627         }
628       }
629 
630       // At this point it is not safe to extend the current hoisting to
631       // NewHoistPt: save the hoisting list so far.
632       if (std::distance(Start, II) > 1)
633         HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
634 
635       // Start over from BB.
636       Start = II;
637       if (K != InsKind::Scalar)
638         UD = MSSA->getMemoryAccess(*Start);
639       HoistPt = Insn;
640       HoistBB = BB;
641       NumBBsOnAllPaths = MaxNumberOfBBSInPath;
642     }
643 
644     // Save the last partition.
645     if (std::distance(Start, II) > 1)
646       HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
647   }
648 
649   // Initialize HPL from Map.
650   void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
651                               InsKind K) {
652     for (const auto &Entry : Map) {
653       if (MaxHoistedThreshold != -1 && ++HoistedCtr > MaxHoistedThreshold)
654         return;
655 
656       const SmallVecInsn &V = Entry.second;
657       if (V.size() < 2)
658         continue;
659 
660       // Compute the insertion point and the list of expressions to be hoisted.
661       SmallVecInsn InstructionsToHoist;
662       for (auto I : V)
663         // We don't need to check for hoist-barriers here because if
664         // I->getParent() is a barrier then I precedes the barrier.
665         if (!hasEH(I->getParent()))
666           InstructionsToHoist.push_back(I);
667 
668       if (!InstructionsToHoist.empty())
669         partitionCandidates(InstructionsToHoist, HPL, K);
670     }
671   }
672 
673   // Return true when all operands of Instr are available at insertion point
674   // HoistPt. When limiting the number of hoisted expressions, one could hoist
675   // a load without hoisting its access function. So before hoisting any
676   // expression, make sure that all its operands are available at insert point.
677   bool allOperandsAvailable(const Instruction *I,
678                             const BasicBlock *HoistPt) const {
679     for (const Use &Op : I->operands())
680       if (const auto *Inst = dyn_cast<Instruction>(&Op))
681         if (!DT->dominates(Inst->getParent(), HoistPt))
682           return false;
683 
684     return true;
685   }
686 
687   // Same as allOperandsAvailable with recursive check for GEP operands.
688   bool allGepOperandsAvailable(const Instruction *I,
689                                const BasicBlock *HoistPt) const {
690     for (const Use &Op : I->operands())
691       if (const auto *Inst = dyn_cast<Instruction>(&Op))
692         if (!DT->dominates(Inst->getParent(), HoistPt)) {
693           if (const GetElementPtrInst *GepOp =
694                   dyn_cast<GetElementPtrInst>(Inst)) {
695             if (!allGepOperandsAvailable(GepOp, HoistPt))
696               return false;
697             // Gep is available if all operands of GepOp are available.
698           } else {
699             // Gep is not available if it has operands other than GEPs that are
700             // defined in blocks not dominating HoistPt.
701             return false;
702           }
703         }
704     return true;
705   }
706 
707   // Make all operands of the GEP available.
708   void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
709                          const SmallVecInsn &InstructionsToHoist,
710                          Instruction *Gep) const {
711     assert(allGepOperandsAvailable(Gep, HoistPt) &&
712            "GEP operands not available");
713 
714     Instruction *ClonedGep = Gep->clone();
715     for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
716       if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
717 
718         // Check whether the operand is already available.
719         if (DT->dominates(Op->getParent(), HoistPt))
720           continue;
721 
722         // As a GEP can refer to other GEPs, recursively make all the operands
723         // of this GEP available at HoistPt.
724         if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
725           makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
726       }
727 
728     // Copy Gep and replace its uses in Repl with ClonedGep.
729     ClonedGep->insertBefore(HoistPt->getTerminator());
730 
731     // Conservatively discard any optimization hints, they may differ on the
732     // other paths.
733     ClonedGep->dropUnknownNonDebugMetadata();
734 
735     // If we have optimization hints which agree with each other along different
736     // paths, preserve them.
737     for (const Instruction *OtherInst : InstructionsToHoist) {
738       const GetElementPtrInst *OtherGep;
739       if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
740         OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
741       else
742         OtherGep = cast<GetElementPtrInst>(
743             cast<StoreInst>(OtherInst)->getPointerOperand());
744       ClonedGep->andIRFlags(OtherGep);
745     }
746 
747     // Replace uses of Gep with ClonedGep in Repl.
748     Repl->replaceUsesOfWith(Gep, ClonedGep);
749   }
750 
751   // In the case Repl is a load or a store, we make all their GEPs
752   // available: GEPs are not hoisted by default to avoid the address
753   // computations to be hoisted without the associated load or store.
754   bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
755                                 const SmallVecInsn &InstructionsToHoist) const {
756     // Check whether the GEP of a ld/st can be synthesized at HoistPt.
757     GetElementPtrInst *Gep = nullptr;
758     Instruction *Val = nullptr;
759     if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
760       Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
761     } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
762       Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
763       Val = dyn_cast<Instruction>(St->getValueOperand());
764       // Check that the stored value is available.
765       if (Val) {
766         if (isa<GetElementPtrInst>(Val)) {
767           // Check whether we can compute the GEP at HoistPt.
768           if (!allGepOperandsAvailable(Val, HoistPt))
769             return false;
770         } else if (!DT->dominates(Val->getParent(), HoistPt))
771           return false;
772       }
773     }
774 
775     // Check whether we can compute the Gep at HoistPt.
776     if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
777       return false;
778 
779     makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
780 
781     if (Val && isa<GetElementPtrInst>(Val))
782       makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
783 
784     return true;
785   }
786 
787   std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) {
788     unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
789     for (const HoistingPointInfo &HP : HPL) {
790       // Find out whether we already have one of the instructions in HoistPt,
791       // in which case we do not have to move it.
792       BasicBlock *HoistPt = HP.first;
793       const SmallVecInsn &InstructionsToHoist = HP.second;
794       Instruction *Repl = nullptr;
795       for (Instruction *I : InstructionsToHoist)
796         if (I->getParent() == HoistPt)
797           // If there are two instructions in HoistPt to be hoisted in place:
798           // update Repl to be the first one, such that we can rename the uses
799           // of the second based on the first.
800           if (!Repl || firstInBB(I, Repl))
801             Repl = I;
802 
803       // Keep track of whether we moved the instruction so we know whether we
804       // should move the MemoryAccess.
805       bool MoveAccess = true;
806       if (Repl) {
807         // Repl is already in HoistPt: it remains in place.
808         assert(allOperandsAvailable(Repl, HoistPt) &&
809                "instruction depends on operands that are not available");
810         MoveAccess = false;
811       } else {
812         // When we do not find Repl in HoistPt, select the first in the list
813         // and move it to HoistPt.
814         Repl = InstructionsToHoist.front();
815 
816         // We can move Repl in HoistPt only when all operands are available.
817         // The order in which hoistings are done may influence the availability
818         // of operands.
819         if (!allOperandsAvailable(Repl, HoistPt)) {
820 
821           // When HoistingGeps there is nothing more we can do to make the
822           // operands available: just continue.
823           if (HoistingGeps)
824             continue;
825 
826           // When not HoistingGeps we need to copy the GEPs.
827           if (!makeGepOperandsAvailable(Repl, HoistPt, InstructionsToHoist))
828             continue;
829         }
830 
831         // Move the instruction at the end of HoistPt.
832         Instruction *Last = HoistPt->getTerminator();
833         MD->removeInstruction(Repl);
834         Repl->moveBefore(Last);
835 
836         DFSNumber[Repl] = DFSNumber[Last]++;
837       }
838 
839       MemoryAccess *NewMemAcc = MSSA->getMemoryAccess(Repl);
840 
841       if (MoveAccess) {
842         if (MemoryUseOrDef *OldMemAcc =
843                 dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) {
844           // The definition of this ld/st will not change: ld/st hoisting is
845           // legal when the ld/st is not moved past its current definition.
846           MemoryAccess *Def = OldMemAcc->getDefiningAccess();
847           NewMemAcc =
848             MSSAUpdater->createMemoryAccessInBB(Repl, Def, HoistPt, MemorySSA::End);
849           OldMemAcc->replaceAllUsesWith(NewMemAcc);
850           MSSAUpdater->removeMemoryAccess(OldMemAcc);
851         }
852       }
853 
854       if (isa<LoadInst>(Repl))
855         ++NL;
856       else if (isa<StoreInst>(Repl))
857         ++NS;
858       else if (isa<CallInst>(Repl))
859         ++NC;
860       else // Scalar
861         ++NI;
862 
863       // Remove and rename all other instructions.
864       for (Instruction *I : InstructionsToHoist)
865         if (I != Repl) {
866           ++NR;
867           if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
868             ReplacementLoad->setAlignment(
869                 std::min(ReplacementLoad->getAlignment(),
870                          cast<LoadInst>(I)->getAlignment()));
871             ++NumLoadsRemoved;
872           } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
873             ReplacementStore->setAlignment(
874                 std::min(ReplacementStore->getAlignment(),
875                          cast<StoreInst>(I)->getAlignment()));
876             ++NumStoresRemoved;
877           } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
878             ReplacementAlloca->setAlignment(
879                 std::max(ReplacementAlloca->getAlignment(),
880                          cast<AllocaInst>(I)->getAlignment()));
881           } else if (isa<CallInst>(Repl)) {
882             ++NumCallsRemoved;
883           }
884 
885           if (NewMemAcc) {
886             // Update the uses of the old MSSA access with NewMemAcc.
887             MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
888             OldMA->replaceAllUsesWith(NewMemAcc);
889             MSSAUpdater->removeMemoryAccess(OldMA);
890           }
891 
892           Repl->andIRFlags(I);
893           combineKnownMetadata(Repl, I);
894           I->replaceAllUsesWith(Repl);
895           // Also invalidate the Alias Analysis cache.
896           MD->removeInstruction(I);
897           I->eraseFromParent();
898         }
899 
900       // Remove MemorySSA phi nodes with the same arguments.
901       if (NewMemAcc) {
902         SmallPtrSet<MemoryPhi *, 4> UsePhis;
903         for (User *U : NewMemAcc->users())
904           if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
905             UsePhis.insert(Phi);
906 
907         for (auto *Phi : UsePhis) {
908           auto In = Phi->incoming_values();
909           if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
910             Phi->replaceAllUsesWith(NewMemAcc);
911             MSSAUpdater->removeMemoryAccess(Phi);
912           }
913         }
914       }
915     }
916 
917     NumHoisted += NL + NS + NC + NI;
918     NumRemoved += NR;
919     NumLoadsHoisted += NL;
920     NumStoresHoisted += NS;
921     NumCallsHoisted += NC;
922     return {NI, NL + NC + NS};
923   }
924 
925   // Hoist all expressions. Returns Number of scalars hoisted
926   // and number of non-scalars hoisted.
927   std::pair<unsigned, unsigned> hoistExpressions(Function &F) {
928     InsnInfo II;
929     LoadInfo LI;
930     StoreInfo SI;
931     CallInfo CI;
932     for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
933       int InstructionNb = 0;
934       for (Instruction &I1 : *BB) {
935         // If I1 cannot guarantee progress, subsequent instructions
936         // in BB cannot be hoisted anyways.
937         if (!isGuaranteedToTransferExecutionToSuccessor(&I1)) {
938            HoistBarrier.insert(BB);
939            break;
940         }
941         // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
942         // deeper may increase the register pressure and compilation time.
943         if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)
944           break;
945 
946         // Do not value number terminator instructions.
947         if (isa<TerminatorInst>(&I1))
948           break;
949 
950         if (auto *Load = dyn_cast<LoadInst>(&I1))
951           LI.insert(Load, VN);
952         else if (auto *Store = dyn_cast<StoreInst>(&I1))
953           SI.insert(Store, VN);
954         else if (auto *Call = dyn_cast<CallInst>(&I1)) {
955           if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
956             if (isa<DbgInfoIntrinsic>(Intr) ||
957                 Intr->getIntrinsicID() == Intrinsic::assume)
958               continue;
959           }
960           if (Call->mayHaveSideEffects())
961             break;
962 
963           if (Call->isConvergent())
964             break;
965 
966           CI.insert(Call, VN);
967         } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
968           // Do not hoist scalars past calls that may write to memory because
969           // that could result in spills later. geps are handled separately.
970           // TODO: We can relax this for targets like AArch64 as they have more
971           // registers than X86.
972           II.insert(&I1, VN);
973       }
974     }
975 
976     HoistingPointList HPL;
977     computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
978     computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
979     computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
980     computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
981     computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
982     computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
983     return hoist(HPL);
984   }
985 };
986 
987 class GVNHoistLegacyPass : public FunctionPass {
988 public:
989   static char ID;
990 
991   GVNHoistLegacyPass() : FunctionPass(ID) {
992     initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry());
993   }
994 
995   bool runOnFunction(Function &F) override {
996     if (skipFunction(F))
997       return false;
998     auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
999     auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1000     auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
1001     auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1002 
1003     GVNHoist G(&DT, &AA, &MD, &MSSA);
1004     return G.run(F);
1005   }
1006 
1007   void getAnalysisUsage(AnalysisUsage &AU) const override {
1008     AU.addRequired<DominatorTreeWrapperPass>();
1009     AU.addRequired<AAResultsWrapperPass>();
1010     AU.addRequired<MemoryDependenceWrapperPass>();
1011     AU.addRequired<MemorySSAWrapperPass>();
1012     AU.addPreserved<DominatorTreeWrapperPass>();
1013     AU.addPreserved<MemorySSAWrapperPass>();
1014     AU.addPreserved<GlobalsAAWrapperPass>();
1015   }
1016 };
1017 } // namespace
1018 
1019 PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) {
1020   DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
1021   AliasAnalysis &AA = AM.getResult<AAManager>(F);
1022   MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
1023   MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
1024   GVNHoist G(&DT, &AA, &MD, &MSSA);
1025   if (!G.run(F))
1026     return PreservedAnalyses::all();
1027 
1028   PreservedAnalyses PA;
1029   PA.preserve<DominatorTreeAnalysis>();
1030   PA.preserve<MemorySSAAnalysis>();
1031   PA.preserve<GlobalsAA>();
1032   return PA;
1033 }
1034 
1035 char GVNHoistLegacyPass::ID = 0;
1036 INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist",
1037                       "Early GVN Hoisting of Expressions", false, false)
1038 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
1039 INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
1040 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1041 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1042 INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist",
1043                     "Early GVN Hoisting of Expressions", false, false)
1044 
1045 FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); }
1046