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