blob: 3c2ac6fcd5f7bc7a47cd3b95890112e019b8bf5b [file] [log] [blame]
Sebastian Pop41774802016-07-15 13:45:20 +00001//===- 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
Aditya Kumarf24939b2016-08-13 11:56:50 +000012// 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//
Sebastian Pop41774802016-07-15 13:45:20 +000016// 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/ADT/DenseMap.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Analysis/ValueTracking.h"
26#include "llvm/Transforms/Scalar.h"
27#include "llvm/Transforms/Scalar/GVN.h"
David Majnemer68623a02016-07-25 02:21:25 +000028#include "llvm/Transforms/Utils/Local.h"
Sebastian Pop41774802016-07-15 13:45:20 +000029#include "llvm/Transforms/Utils/MemorySSA.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "gvn-hoist"
34
35STATISTIC(NumHoisted, "Number of instructions hoisted");
36STATISTIC(NumRemoved, "Number of instructions removed");
37STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
38STATISTIC(NumLoadsRemoved, "Number of loads removed");
39STATISTIC(NumStoresHoisted, "Number of stores hoisted");
40STATISTIC(NumStoresRemoved, "Number of stores removed");
41STATISTIC(NumCallsHoisted, "Number of calls hoisted");
42STATISTIC(NumCallsRemoved, "Number of calls removed");
43
44static 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)"));
48static 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
Sebastian Pop38422b12016-07-26 00:15:08 +000053static 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
Sebastian Pop2aadad72016-08-03 20:54:38 +000058static cl::opt<int> MaxChainLength(
59 "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
Sebastian Pop41774802016-07-15 13:45:20 +000063namespace {
64
65// Provides a sorting function based on the execution order of two instructions.
66struct SortByDFSIn {
67private:
Sebastian Pop91d4a302016-07-26 00:15:10 +000068 DenseMap<const Value *, unsigned> &DFSNumber;
Sebastian Pop41774802016-07-15 13:45:20 +000069
70public:
Sebastian Pop91d4a302016-07-26 00:15:10 +000071 SortByDFSIn(DenseMap<const Value *, unsigned> &D) : DFSNumber(D) {}
Sebastian Pop41774802016-07-15 13:45:20 +000072
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
Sebastian Pop4ba7c882016-08-03 20:54:36 +000082 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 }
George Burgess IV9cf05462016-07-27 06:34:53 +000092 assert (ADFS && BDFS);
Sebastian Pop91d4a302016-07-26 00:15:10 +000093 return ADFS < BDFS;
Sebastian Pop41774802016-07-15 13:45:20 +000094 }
95};
96
David Majnemer04c7c222016-07-18 06:11:37 +000097// A map from a pair of VNs to all the instructions with those VNs.
98typedef 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.
Reid Kleckner3498ad12016-07-18 18:53:50 +0000102enum : unsigned { InvalidVN = ~2U };
Sebastian Pop41774802016-07-15 13:45:20 +0000103
104// Records all scalar instructions candidate for code hoisting.
105class InsnInfo {
106 VNtoInsns VNtoScalars;
107
108public:
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);
David Majnemer04c7c222016-07-18 06:11:37 +0000113 VNtoScalars[{V, InvalidVN}].push_back(I);
Sebastian Pop41774802016-07-15 13:45:20 +0000114 }
115
116 const VNtoInsns &getVNTable() const { return VNtoScalars; }
117};
118
119// Records all load instructions candidate for code hoisting.
120class LoadInfo {
121 VNtoInsns VNtoLoads;
122
123public:
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());
David Majnemer04c7c222016-07-18 06:11:37 +0000128 VNtoLoads[{V, InvalidVN}].push_back(Load);
Sebastian Pop41774802016-07-15 13:45:20 +0000129 }
130 }
131
132 const VNtoInsns &getVNTable() const { return VNtoLoads; }
133};
134
135// Records all store instructions candidate for code hoisting.
136class StoreInfo {
137 VNtoInsns VNtoStores;
138
139public:
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();
David Majnemer04c7c222016-07-18 06:11:37 +0000148 VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
Sebastian Pop41774802016-07-15 13:45:20 +0000149 }
150
151 const VNtoInsns &getVNTable() const { return VNtoStores; }
152};
153
154// Records all call instructions candidate for code hoisting.
155class CallInfo {
156 VNtoInsns VNtoCallsScalars;
157 VNtoInsns VNtoCallsLoads;
158 VNtoInsns VNtoCallsStores;
159
160public:
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);
David Majnemer04c7c222016-07-18 06:11:37 +0000167 auto Entry = std::make_pair(V, InvalidVN);
Sebastian Pop41774802016-07-15 13:45:20 +0000168
169 if (Call->doesNotAccessMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000170 VNtoCallsScalars[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000171 else if (Call->onlyReadsMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000172 VNtoCallsLoads[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000173 else
David Majnemer04c7c222016-07-18 06:11:37 +0000174 VNtoCallsStores[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000175 }
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
184typedef DenseMap<const BasicBlock *, bool> BBSideEffectsSet;
185typedef SmallVector<Instruction *, 4> SmallVecInsn;
186typedef SmallVectorImpl<Instruction *> SmallVecImplInsn;
187
David Majnemer68623a02016-07-25 02:21:25 +0000188static 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
Sebastian Pop41774802016-07-15 13:45:20 +0000197// 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).
200class GVNHoist {
201public:
Daniel Berlinea02eee2016-08-23 05:42:41 +0000202 GVNHoist(DominatorTree *DT, AliasAnalysis *AA, MemoryDependenceResults *MD,
203 MemorySSA *MSSA, bool OptForMinSize)
204 : DT(DT), AA(AA), MD(MD), MSSA(MSSA), OptForMinSize(OptForMinSize),
Sebastian Pop55c30072016-07-27 05:48:12 +0000205 HoistingGeps(OptForMinSize), HoistedCtr(0) {}
Daniel Berlin65af45d2016-07-25 17:24:22 +0000206 bool run(Function &F) {
207 VN.setDomTree(DT);
208 VN.setAliasAnalysis(AA);
209 VN.setMemDep(MD);
210 bool Res = false;
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000211 // 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 }
Daniel Berlin65af45d2016-07-25 17:24:22 +0000219
Sebastian Pop2aadad72016-08-03 20:54:38 +0000220 int ChainLength = 0;
221
Daniel Berlin65af45d2016-07-25 17:24:22 +0000222 // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
223 while (1) {
Sebastian Pop2aadad72016-08-03 20:54:38 +0000224 if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)
225 return Res;
226
Daniel Berlin65af45d2016-07-25 17:24:22 +0000227 auto HoistStat = hoistExpressions(F);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000228 if (HoistStat.first + HoistStat.second == 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000229 return Res;
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000230
231 if (HoistStat.second > 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000232 // To address a limitation of the current GVN, we need to rerun the
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000233 // hoisting after we hoisted loads or stores in order to be able to
234 // hoist all scalars dependent on the hoisted ld/st.
Daniel Berlin65af45d2016-07-25 17:24:22 +0000235 VN.clear();
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000236
Daniel Berlin65af45d2016-07-25 17:24:22 +0000237 Res = true;
238 }
239
240 return Res;
241 }
242private:
Sebastian Pop41774802016-07-15 13:45:20 +0000243 GVN::ValueTable VN;
244 DominatorTree *DT;
245 AliasAnalysis *AA;
246 MemoryDependenceResults *MD;
Daniel Berlinea02eee2016-08-23 05:42:41 +0000247 MemorySSA *MSSA;
Sebastian Pop41774802016-07-15 13:45:20 +0000248 const bool OptForMinSize;
Sebastian Pop55c30072016-07-27 05:48:12 +0000249 const bool HoistingGeps;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000250 DenseMap<const Value *, unsigned> DFSNumber;
Sebastian Pop41774802016-07-15 13:45:20 +0000251 BBSideEffectsSet BBSideEffects;
David Majnemeraa241782016-07-18 00:35:01 +0000252 int HoistedCtr;
253
Sebastian Pop41774802016-07-15 13:45:20 +0000254 enum InsKind { Unknown, Scalar, Load, Store };
255
Sebastian Pop41774802016-07-15 13:45:20 +0000256 // Return true when there are exception handling in BB.
257 bool hasEH(const BasicBlock *BB) {
258 auto It = BBSideEffects.find(BB);
259 if (It != BBSideEffects.end())
260 return It->second;
261
262 if (BB->isEHPad() || BB->hasAddressTaken()) {
263 BBSideEffects[BB] = true;
264 return true;
265 }
266
267 if (BB->getTerminator()->mayThrow()) {
268 BBSideEffects[BB] = true;
269 return true;
270 }
271
272 BBSideEffects[BB] = false;
273 return false;
274 }
275
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000276 // Return true when a successor of BB dominates A.
277 bool successorDominate(const BasicBlock *BB, const BasicBlock *A) {
278 for (const BasicBlock *Succ : BB->getTerminator()->successors())
279 if (DT->dominates(Succ, A))
280 return true;
Sebastian Pop41774802016-07-15 13:45:20 +0000281
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000282 return false;
283 }
284
285 // Return true when all paths from HoistBB to the end of the function pass
286 // through one of the blocks in WL.
287 bool hoistingFromAllPaths(const BasicBlock *HoistBB,
288 SmallPtrSetImpl<const BasicBlock *> &WL) {
289
290 // Copy WL as the loop will remove elements from it.
291 SmallPtrSet<const BasicBlock *, 2> WorkList(WL.begin(), WL.end());
292
293 for (auto It = df_begin(HoistBB), E = df_end(HoistBB); It != E;) {
294 // There exists a path from HoistBB to the exit of the function if we are
295 // still iterating in DF traversal and we removed all instructions from
296 // the work list.
297 if (WorkList.empty())
Sebastian Pop41774802016-07-15 13:45:20 +0000298 return false;
299
300 const BasicBlock *BB = *It;
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000301 if (WorkList.erase(BB)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000302 // Stop DFS traversal when BB is in the work list.
303 It.skipChildren();
304 continue;
305 }
306
307 // Check for end of function, calls that do not return, etc.
308 if (!isGuaranteedToTransferExecutionToSuccessor(BB->getTerminator()))
309 return false;
310
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000311 // When reaching the back-edge of a loop, there may be a path through the
312 // loop that does not pass through B or C before exiting the loop.
313 if (successorDominate(BB, HoistBB))
314 return false;
315
Sebastian Pop41774802016-07-15 13:45:20 +0000316 // Increment DFS traversal when not skipping children.
317 ++It;
318 }
319
320 return true;
321 }
322
323 /* Return true when I1 appears before I2 in the instructions of BB. */
Sebastian Pop91d4a302016-07-26 00:15:10 +0000324 bool firstInBB(const Instruction *I1, const Instruction *I2) {
325 assert (I1->getParent() == I2->getParent());
326 unsigned I1DFS = DFSNumber.lookup(I1);
327 unsigned I2DFS = DFSNumber.lookup(I2);
328 assert (I1DFS && I2DFS);
329 return I1DFS < I2DFS;
Daniel Berlin40765a62016-07-25 18:19:49 +0000330 }
Sebastian Pop91d4a302016-07-26 00:15:10 +0000331
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000332 // Return true when there are memory uses of Def in BB.
333 bool hasMemoryUseOnPath(const Instruction *NewPt, MemoryDef *Def, const BasicBlock *BB) {
334 const Instruction *OldPt = Def->getMemoryInst();
Sebastian Pop41774802016-07-15 13:45:20 +0000335 const BasicBlock *OldBB = OldPt->getParent();
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000336 const BasicBlock *NewBB = NewPt->getParent();
Sebastian Pop41774802016-07-15 13:45:20 +0000337
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000338 bool ReachedNewPt = false;
339 MemoryLocation DefLoc = MemoryLocation::get(OldPt);
340 const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
341 for (const MemoryAccess &MA : *Acc) {
342 auto *MU = dyn_cast<MemoryUse>(&MA);
343 if (!MU)
344 continue;
Sebastian Pop41774802016-07-15 13:45:20 +0000345
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000346 // Do not check whether MU aliases Def when MU occurs after OldPt.
347 if (BB == OldBB && firstInBB(OldPt, MU->getMemoryInst()))
348 break;
349
350 // Do not check whether MU aliases Def when MU occurs before NewPt.
351 if (BB == NewBB) {
352 if (!ReachedNewPt) {
353 if (firstInBB(MU->getMemoryInst(), NewPt))
354 continue;
355 ReachedNewPt = true;
Sebastian Pop41774802016-07-15 13:45:20 +0000356 }
Sebastian Pop41774802016-07-15 13:45:20 +0000357 }
358
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000359 if (!AA->isNoAlias(DefLoc, MemoryLocation::get(MU->getMemoryInst())))
360 return true;
361 }
362
Sebastian Pop41774802016-07-15 13:45:20 +0000363 return false;
364 }
365
366 // Return true when there are exception handling or loads of memory Def
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000367 // between Def and NewPt. This function is only called for stores: Def is
368 // the MemoryDef of the store to be hoisted.
Sebastian Pop41774802016-07-15 13:45:20 +0000369
370 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
371 // return true when the counter NBBsOnAllPaths reaces 0, except when it is
372 // initialized to -1 which is unlimited.
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000373 bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
374 int &NBBsOnAllPaths) {
Sebastian Pop41774802016-07-15 13:45:20 +0000375 const BasicBlock *NewBB = NewPt->getParent();
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000376 const BasicBlock *OldBB = Def->getBlock();
Sebastian Pop41774802016-07-15 13:45:20 +0000377 assert(DT->dominates(NewBB, OldBB) && "invalid path");
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000378 assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&
Sebastian Pop41774802016-07-15 13:45:20 +0000379 "def does not dominate new hoisting point");
380
381 // Walk all basic blocks reachable in depth-first iteration on the inverse
382 // CFG from OldBB to NewBB. These blocks are all the blocks that may be
383 // executed between the execution of NewBB and OldBB. Hoisting an expression
384 // from OldBB into NewBB has to be safe on all execution paths.
385 for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {
386 if (*I == NewBB) {
387 // Stop traversal when reaching HoistPt.
388 I.skipChildren();
389 continue;
390 }
391
392 // Impossible to hoist with exceptions on the path.
393 if (hasEH(*I))
394 return true;
395
396 // Check that we do not move a store past loads.
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000397 if (hasMemoryUseOnPath(NewPt, Def, *I))
Sebastian Pop41774802016-07-15 13:45:20 +0000398 return true;
399
400 // Stop walk once the limit is reached.
401 if (NBBsOnAllPaths == 0)
402 return true;
403
404 // -1 is unlimited number of blocks on all paths.
405 if (NBBsOnAllPaths != -1)
406 --NBBsOnAllPaths;
407
408 ++I;
409 }
410
411 return false;
412 }
413
414 // Return true when there are exception handling between HoistPt and BB.
415 // Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and
416 // return true when the counter NBBsOnAllPaths reaches 0, except when it is
417 // initialized to -1 which is unlimited.
418 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *BB,
419 int &NBBsOnAllPaths) {
420 assert(DT->dominates(HoistPt, BB) && "Invalid path");
421
422 // Walk all basic blocks reachable in depth-first iteration on
423 // the inverse CFG from BBInsn to NewHoistPt. These blocks are all the
424 // blocks that may be executed between the execution of NewHoistPt and
425 // BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe
426 // on all execution paths.
427 for (auto I = idf_begin(BB), E = idf_end(BB); I != E;) {
428 if (*I == HoistPt) {
429 // Stop traversal when reaching NewHoistPt.
430 I.skipChildren();
431 continue;
432 }
433
434 // Impossible to hoist with exceptions on the path.
435 if (hasEH(*I))
436 return true;
437
438 // Stop walk once the limit is reached.
439 if (NBBsOnAllPaths == 0)
440 return true;
441
442 // -1 is unlimited number of blocks on all paths.
443 if (NBBsOnAllPaths != -1)
444 --NBBsOnAllPaths;
445
446 ++I;
447 }
448
449 return false;
450 }
451
452 // Return true when it is safe to hoist a memory load or store U from OldPt
453 // to NewPt.
454 bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,
455 MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths) {
456
457 // In place hoisting is safe.
458 if (NewPt == OldPt)
459 return true;
460
461 const BasicBlock *NewBB = NewPt->getParent();
462 const BasicBlock *OldBB = OldPt->getParent();
463 const BasicBlock *UBB = U->getBlock();
464
465 // Check for dependences on the Memory SSA.
466 MemoryAccess *D = U->getDefiningAccess();
467 BasicBlock *DBB = D->getBlock();
468 if (DT->properlyDominates(NewBB, DBB))
469 // Cannot move the load or store to NewBB above its definition in DBB.
470 return false;
471
472 if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))
David Majnemer4c66a712016-07-18 00:34:58 +0000473 if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
Sebastian Pop91d4a302016-07-26 00:15:10 +0000474 if (firstInBB(NewPt, UD->getMemoryInst()))
Sebastian Pop41774802016-07-15 13:45:20 +0000475 // Cannot move the load or store to NewPt above its definition in D.
476 return false;
477
478 // Check for unsafe hoistings due to side effects.
479 if (K == InsKind::Store) {
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000480 if (hasEHOrLoadsOnPath(NewPt, dyn_cast<MemoryDef>(U), NBBsOnAllPaths))
Sebastian Pop41774802016-07-15 13:45:20 +0000481 return false;
482 } else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))
483 return false;
484
485 if (UBB == NewBB) {
486 if (DT->properlyDominates(DBB, NewBB))
487 return true;
488 assert(UBB == DBB);
489 assert(MSSA->locallyDominates(D, U));
490 }
491
492 // No side effects: it is safe to hoist.
493 return true;
494 }
495
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000496 // Return true when it is safe to hoist scalar instructions from all blocks in
497 // WL to HoistBB.
498 bool safeToHoistScalar(const BasicBlock *HoistBB,
499 SmallPtrSetImpl<const BasicBlock *> &WL,
500 int &NBBsOnAllPaths) {
501 // Check that the hoisted expression is needed on all paths. Enable scalar
502 // hoisting at -Oz as it is safe to hoist scalars to a place where they are
503 // partially needed.
504 if (!OptForMinSize && !hoistingFromAllPaths(HoistBB, WL))
Sebastian Pop41774802016-07-15 13:45:20 +0000505 return false;
506
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000507 for (const BasicBlock *BB : WL)
508 if (hasEHOnPath(HoistBB, BB, NBBsOnAllPaths))
509 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000510
Sebastian Pop41774802016-07-15 13:45:20 +0000511 return true;
512 }
513
514 // Each element of a hoisting list contains the basic block where to hoist and
515 // a list of instructions to be hoisted.
516 typedef std::pair<BasicBlock *, SmallVecInsn> HoistingPointInfo;
517 typedef SmallVector<HoistingPointInfo, 4> HoistingPointList;
518
519 // Partition InstructionsToHoist into a set of candidates which can share a
520 // common hoisting point. The partitions are collected in HPL. IsScalar is
521 // true when the instructions in InstructionsToHoist are scalars. IsLoad is
522 // true when the InstructionsToHoist are loads, false when they are stores.
523 void partitionCandidates(SmallVecImplInsn &InstructionsToHoist,
524 HoistingPointList &HPL, InsKind K) {
525 // No need to sort for two instructions.
526 if (InstructionsToHoist.size() > 2) {
527 SortByDFSIn Pred(DFSNumber);
528 std::sort(InstructionsToHoist.begin(), InstructionsToHoist.end(), Pred);
529 }
530
531 int NBBsOnAllPaths = MaxNumberOfBBSInPath;
532
533 SmallVecImplInsn::iterator II = InstructionsToHoist.begin();
534 SmallVecImplInsn::iterator Start = II;
535 Instruction *HoistPt = *II;
536 BasicBlock *HoistBB = HoistPt->getParent();
537 MemoryUseOrDef *UD;
538 if (K != InsKind::Scalar)
539 UD = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(HoistPt));
540
541 for (++II; II != InstructionsToHoist.end(); ++II) {
542 Instruction *Insn = *II;
543 BasicBlock *BB = Insn->getParent();
544 BasicBlock *NewHoistBB;
545 Instruction *NewHoistPt;
546
547 if (BB == HoistBB) {
548 NewHoistBB = HoistBB;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000549 NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt;
Sebastian Pop41774802016-07-15 13:45:20 +0000550 } else {
551 NewHoistBB = DT->findNearestCommonDominator(HoistBB, BB);
552 if (NewHoistBB == BB)
553 NewHoistPt = Insn;
554 else if (NewHoistBB == HoistBB)
555 NewHoistPt = HoistPt;
556 else
557 NewHoistPt = NewHoistBB->getTerminator();
558 }
559
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000560 SmallPtrSet<const BasicBlock *, 2> WL;
561 WL.insert(HoistBB);
562 WL.insert(BB);
563
Sebastian Pop41774802016-07-15 13:45:20 +0000564 if (K == InsKind::Scalar) {
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000565 if (safeToHoistScalar(NewHoistBB, WL, NBBsOnAllPaths)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000566 // Extend HoistPt to NewHoistPt.
567 HoistPt = NewHoistPt;
568 HoistBB = NewHoistBB;
569 continue;
570 }
571 } else {
572 // When NewBB already contains an instruction to be hoisted, the
573 // expression is needed on all paths.
574 // Check that the hoisted expression is needed on all paths: it is
575 // unsafe to hoist loads to a place where there may be a path not
576 // loading from the same address: for instance there may be a branch on
577 // which the address of the load may not be initialized.
578 if ((HoistBB == NewHoistBB || BB == NewHoistBB ||
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000579 hoistingFromAllPaths(NewHoistBB, WL)) &&
Sebastian Pop41774802016-07-15 13:45:20 +0000580 // Also check that it is safe to move the load or store from HoistPt
581 // to NewHoistPt, and from Insn to NewHoistPt.
582 safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NBBsOnAllPaths) &&
583 safeToHoistLdSt(NewHoistPt, Insn,
584 cast<MemoryUseOrDef>(MSSA->getMemoryAccess(Insn)),
585 K, NBBsOnAllPaths)) {
586 // Extend HoistPt to NewHoistPt.
587 HoistPt = NewHoistPt;
588 HoistBB = NewHoistBB;
589 continue;
590 }
591 }
592
593 // At this point it is not safe to extend the current hoisting to
594 // NewHoistPt: save the hoisting list so far.
595 if (std::distance(Start, II) > 1)
David Majnemer4c66a712016-07-18 00:34:58 +0000596 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000597
598 // Start over from BB.
599 Start = II;
600 if (K != InsKind::Scalar)
601 UD = cast<MemoryUseOrDef>(MSSA->getMemoryAccess(*Start));
602 HoistPt = Insn;
603 HoistBB = BB;
604 NBBsOnAllPaths = MaxNumberOfBBSInPath;
605 }
606
607 // Save the last partition.
608 if (std::distance(Start, II) > 1)
David Majnemer4c66a712016-07-18 00:34:58 +0000609 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000610 }
611
612 // Initialize HPL from Map.
613 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
614 InsKind K) {
David Majnemer4c66a712016-07-18 00:34:58 +0000615 for (const auto &Entry : Map) {
Sebastian Pop41774802016-07-15 13:45:20 +0000616 if (MaxHoistedThreshold != -1 && ++HoistedCtr > MaxHoistedThreshold)
617 return;
618
David Majnemer4c66a712016-07-18 00:34:58 +0000619 const SmallVecInsn &V = Entry.second;
Sebastian Pop41774802016-07-15 13:45:20 +0000620 if (V.size() < 2)
621 continue;
622
623 // Compute the insertion point and the list of expressions to be hoisted.
624 SmallVecInsn InstructionsToHoist;
625 for (auto I : V)
626 if (!hasEH(I->getParent()))
627 InstructionsToHoist.push_back(I);
628
David Majnemer4c66a712016-07-18 00:34:58 +0000629 if (!InstructionsToHoist.empty())
Sebastian Pop41774802016-07-15 13:45:20 +0000630 partitionCandidates(InstructionsToHoist, HPL, K);
631 }
632 }
633
634 // Return true when all operands of Instr are available at insertion point
635 // HoistPt. When limiting the number of hoisted expressions, one could hoist
636 // a load without hoisting its access function. So before hoisting any
637 // expression, make sure that all its operands are available at insert point.
638 bool allOperandsAvailable(const Instruction *I,
639 const BasicBlock *HoistPt) const {
David Majnemer4c66a712016-07-18 00:34:58 +0000640 for (const Use &Op : I->operands())
641 if (const auto *Inst = dyn_cast<Instruction>(&Op))
642 if (!DT->dominates(Inst->getParent(), HoistPt))
643 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000644
645 return true;
646 }
647
Sebastian Pop55c30072016-07-27 05:48:12 +0000648 // Same as allOperandsAvailable with recursive check for GEP operands.
649 bool allGepOperandsAvailable(const Instruction *I,
650 const BasicBlock *HoistPt) const {
651 for (const Use &Op : I->operands())
652 if (const auto *Inst = dyn_cast<Instruction>(&Op))
653 if (!DT->dominates(Inst->getParent(), HoistPt)) {
654 if (const GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Inst)) {
655 if (!allGepOperandsAvailable(GepOp, HoistPt))
656 return false;
657 // Gep is available if all operands of GepOp are available.
658 } else {
659 // Gep is not available if it has operands other than GEPs that are
660 // defined in blocks not dominating HoistPt.
661 return false;
662 }
663 }
664 return true;
665 }
666
667 // Make all operands of the GEP available.
668 void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,
669 const SmallVecInsn &InstructionsToHoist,
670 Instruction *Gep) const {
671 assert(allGepOperandsAvailable(Gep, HoistPt) && "GEP operands not available");
672
673 Instruction *ClonedGep = Gep->clone();
674 for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)
675 if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {
676
677 // Check whether the operand is already available.
678 if (DT->dominates(Op->getParent(), HoistPt))
679 continue;
680
681 // As a GEP can refer to other GEPs, recursively make all the operands
682 // of this GEP available at HoistPt.
683 if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))
684 makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);
685 }
686
687 // Copy Gep and replace its uses in Repl with ClonedGep.
688 ClonedGep->insertBefore(HoistPt->getTerminator());
689
690 // Conservatively discard any optimization hints, they may differ on the
691 // other paths.
692 ClonedGep->dropUnknownNonDebugMetadata();
693
694 // If we have optimization hints which agree with each other along different
695 // paths, preserve them.
696 for (const Instruction *OtherInst : InstructionsToHoist) {
697 const GetElementPtrInst *OtherGep;
698 if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))
699 OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());
700 else
701 OtherGep = cast<GetElementPtrInst>(
702 cast<StoreInst>(OtherInst)->getPointerOperand());
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +0000703 ClonedGep->andIRFlags(OtherGep);
Sebastian Pop55c30072016-07-27 05:48:12 +0000704 }
705
706 // Replace uses of Gep with ClonedGep in Repl.
707 Repl->replaceUsesOfWith(Gep, ClonedGep);
708 }
709
710 // In the case Repl is a load or a store, we make all their GEPs
711 // available: GEPs are not hoisted by default to avoid the address
712 // computations to be hoisted without the associated load or store.
713 bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,
714 const SmallVecInsn &InstructionsToHoist) const {
Sebastian Pop41774802016-07-15 13:45:20 +0000715 // Check whether the GEP of a ld/st can be synthesized at HoistPt.
David Majnemerbd210122016-07-20 21:05:01 +0000716 GetElementPtrInst *Gep = nullptr;
Sebastian Pop41774802016-07-15 13:45:20 +0000717 Instruction *Val = nullptr;
Sebastian Pop55c30072016-07-27 05:48:12 +0000718 if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000719 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
Sebastian Pop55c30072016-07-27 05:48:12 +0000720 } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000721 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
Sebastian Pop41774802016-07-15 13:45:20 +0000722 Val = dyn_cast<Instruction>(St->getValueOperand());
Sebastian Pop31fd5062016-07-21 23:22:10 +0000723 // Check that the stored value is available.
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000724 if (Val) {
725 if (isa<GetElementPtrInst>(Val)) {
726 // Check whether we can compute the GEP at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000727 if (!allGepOperandsAvailable(Val, HoistPt))
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000728 return false;
729 } else if (!DT->dominates(Val->getParent(), HoistPt))
730 return false;
731 }
Sebastian Pop41774802016-07-15 13:45:20 +0000732 }
733
Sebastian Pop41774802016-07-15 13:45:20 +0000734 // Check whether we can compute the Gep at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000735 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
Sebastian Pop41774802016-07-15 13:45:20 +0000736 return false;
737
Sebastian Pop55c30072016-07-27 05:48:12 +0000738 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
Sebastian Pop41774802016-07-15 13:45:20 +0000739
Sebastian Pop55c30072016-07-27 05:48:12 +0000740 if (Val && isa<GetElementPtrInst>(Val))
741 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
Sebastian Pop41774802016-07-15 13:45:20 +0000742
743 return true;
744 }
745
746 std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL) {
747 unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;
748 for (const HoistingPointInfo &HP : HPL) {
749 // Find out whether we already have one of the instructions in HoistPt,
750 // in which case we do not have to move it.
751 BasicBlock *HoistPt = HP.first;
752 const SmallVecInsn &InstructionsToHoist = HP.second;
753 Instruction *Repl = nullptr;
754 for (Instruction *I : InstructionsToHoist)
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000755 if (I->getParent() == HoistPt)
Sebastian Pop41774802016-07-15 13:45:20 +0000756 // If there are two instructions in HoistPt to be hoisted in place:
757 // update Repl to be the first one, such that we can rename the uses
758 // of the second based on the first.
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000759 if (!Repl || firstInBB(I, Repl))
760 Repl = I;
Sebastian Pop41774802016-07-15 13:45:20 +0000761
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000762 // Keep track of whether we moved the instruction so we know whether we
763 // should move the MemoryAccess.
764 bool MoveAccess = true;
Sebastian Pop41774802016-07-15 13:45:20 +0000765 if (Repl) {
766 // Repl is already in HoistPt: it remains in place.
767 assert(allOperandsAvailable(Repl, HoistPt) &&
768 "instruction depends on operands that are not available");
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000769 MoveAccess = false;
Sebastian Pop41774802016-07-15 13:45:20 +0000770 } else {
771 // When we do not find Repl in HoistPt, select the first in the list
772 // and move it to HoistPt.
773 Repl = InstructionsToHoist.front();
774
775 // We can move Repl in HoistPt only when all operands are available.
776 // The order in which hoistings are done may influence the availability
777 // of operands.
Sebastian Pop429740a2016-08-04 23:49:05 +0000778 if (!allOperandsAvailable(Repl, HoistPt)) {
779
780 // When HoistingGeps there is nothing more we can do to make the
781 // operands available: just continue.
782 if (HoistingGeps)
783 continue;
784
785 // When not HoistingGeps we need to copy the GEPs.
786 if (!makeGepOperandsAvailable(Repl, HoistPt, InstructionsToHoist))
787 continue;
788 }
Sebastian Pop55c30072016-07-27 05:48:12 +0000789
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000790 // Move the instruction at the end of HoistPt.
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000791 Instruction *Last = HoistPt->getTerminator();
792 Repl->moveBefore(Last);
793
794 DFSNumber[Repl] = DFSNumber[Last]++;
Sebastian Pop41774802016-07-15 13:45:20 +0000795 }
796
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000797 MemoryAccess *NewMemAcc = MSSA->getMemoryAccess(Repl);
798
799 if (MoveAccess) {
800 if (MemoryUseOrDef *OldMemAcc =
801 dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000802 // The definition of this ld/st will not change: ld/st hoisting is
803 // legal when the ld/st is not moved past its current definition.
804 MemoryAccess *Def = OldMemAcc->getDefiningAccess();
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000805 NewMemAcc =
806 MSSA->createMemoryAccessInBB(Repl, Def, HoistPt, MemorySSA::End);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000807 OldMemAcc->replaceAllUsesWith(NewMemAcc);
808 MSSA->removeMemoryAccess(OldMemAcc);
809 }
810 }
811
Sebastian Pop41774802016-07-15 13:45:20 +0000812 if (isa<LoadInst>(Repl))
813 ++NL;
814 else if (isa<StoreInst>(Repl))
815 ++NS;
816 else if (isa<CallInst>(Repl))
817 ++NC;
818 else // Scalar
819 ++NI;
820
821 // Remove and rename all other instructions.
822 for (Instruction *I : InstructionsToHoist)
823 if (I != Repl) {
824 ++NR;
David Majnemer47285692016-07-25 02:21:23 +0000825 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
826 ReplacementLoad->setAlignment(
827 std::min(ReplacementLoad->getAlignment(),
828 cast<LoadInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000829 ++NumLoadsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000830 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
831 ReplacementStore->setAlignment(
832 std::min(ReplacementStore->getAlignment(),
833 cast<StoreInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000834 ++NumStoresRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000835 } else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {
836 ReplacementAlloca->setAlignment(
837 std::max(ReplacementAlloca->getAlignment(),
838 cast<AllocaInst>(I)->getAlignment()));
839 } else if (isa<CallInst>(Repl)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000840 ++NumCallsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000841 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000842
843 if (NewMemAcc) {
844 // Update the uses of the old MSSA access with NewMemAcc.
845 MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
846 OldMA->replaceAllUsesWith(NewMemAcc);
847 MSSA->removeMemoryAccess(OldMA);
848 }
849
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +0000850 Repl->andIRFlags(I);
David Majnemer68623a02016-07-25 02:21:25 +0000851 combineKnownMetadata(Repl, I);
Sebastian Pop41774802016-07-15 13:45:20 +0000852 I->replaceAllUsesWith(Repl);
Sebastian Pop46601992016-08-27 02:48:41 +0000853 // Also invalidate the Alias Analysis cache.
854 MD->removeInstruction(I);
Sebastian Pop41774802016-07-15 13:45:20 +0000855 I->eraseFromParent();
856 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000857
858 // Remove MemorySSA phi nodes with the same arguments.
859 if (NewMemAcc) {
860 SmallPtrSet<MemoryPhi *, 4> UsePhis;
861 for (User *U : NewMemAcc->users())
862 if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))
863 UsePhis.insert(Phi);
864
865 for (auto *Phi : UsePhis) {
866 auto In = Phi->incoming_values();
David Majnemer0a16c222016-08-11 21:15:00 +0000867 if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000868 Phi->replaceAllUsesWith(NewMemAcc);
869 MSSA->removeMemoryAccess(Phi);
870 }
871 }
872 }
Sebastian Pop41774802016-07-15 13:45:20 +0000873 }
874
875 NumHoisted += NL + NS + NC + NI;
876 NumRemoved += NR;
877 NumLoadsHoisted += NL;
878 NumStoresHoisted += NS;
879 NumCallsHoisted += NC;
880 return {NI, NL + NC + NS};
881 }
882
883 // Hoist all expressions. Returns Number of scalars hoisted
884 // and number of non-scalars hoisted.
885 std::pair<unsigned, unsigned> hoistExpressions(Function &F) {
886 InsnInfo II;
887 LoadInfo LI;
888 StoreInfo SI;
889 CallInfo CI;
890 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {
Sebastian Pop38422b12016-07-26 00:15:08 +0000891 int InstructionNb = 0;
Sebastian Pop41774802016-07-15 13:45:20 +0000892 for (Instruction &I1 : *BB) {
Sebastian Pop38422b12016-07-26 00:15:08 +0000893 // Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting
894 // deeper may increase the register pressure and compilation time.
895 if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)
896 break;
897
Sebastian Pop440f15b2016-09-22 14:45:40 +0000898 // Do not value number terminator instructions.
Sebastian Pop5d68aa72016-09-22 15:08:09 +0000899 if (isa<TerminatorInst>(&I1))
Sebastian Pop440f15b2016-09-22 14:45:40 +0000900 break;
901
David Majnemer4c66a712016-07-18 00:34:58 +0000902 if (auto *Load = dyn_cast<LoadInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000903 LI.insert(Load, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000904 else if (auto *Store = dyn_cast<StoreInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000905 SI.insert(Store, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000906 else if (auto *Call = dyn_cast<CallInst>(&I1)) {
907 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000908 if (isa<DbgInfoIntrinsic>(Intr) ||
909 Intr->getIntrinsicID() == Intrinsic::assume)
910 continue;
911 }
912 if (Call->mayHaveSideEffects()) {
913 if (!OptForMinSize)
914 break;
915 // We may continue hoisting across calls which write to memory.
916 if (Call->mayThrow())
917 break;
918 }
Matt Arsenault6ad97732016-08-04 20:52:57 +0000919
920 if (Call->isConvergent())
921 break;
922
Sebastian Pop41774802016-07-15 13:45:20 +0000923 CI.insert(Call, VN);
Sebastian Pop55c30072016-07-27 05:48:12 +0000924 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000925 // Do not hoist scalars past calls that may write to memory because
926 // that could result in spills later. geps are handled separately.
927 // TODO: We can relax this for targets like AArch64 as they have more
928 // registers than X86.
929 II.insert(&I1, VN);
930 }
931 }
932
933 HoistingPointList HPL;
934 computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);
935 computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);
936 computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);
937 computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);
938 computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);
939 computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);
940 return hoist(HPL);
941 }
Sebastian Pop41774802016-07-15 13:45:20 +0000942};
943
944class GVNHoistLegacyPass : public FunctionPass {
945public:
946 static char ID;
947
948 GVNHoistLegacyPass() : FunctionPass(ID) {
949 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry());
950 }
951
952 bool runOnFunction(Function &F) override {
Paul Robinson2d23c022016-07-19 22:57:14 +0000953 if (skipFunction(F))
954 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000955 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
956 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
957 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000958 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
Sebastian Pop41774802016-07-15 13:45:20 +0000959
Daniel Berlinea02eee2016-08-23 05:42:41 +0000960 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize());
Sebastian Pop41774802016-07-15 13:45:20 +0000961 return G.run(F);
962 }
963
964 void getAnalysisUsage(AnalysisUsage &AU) const override {
965 AU.addRequired<DominatorTreeWrapperPass>();
966 AU.addRequired<AAResultsWrapperPass>();
967 AU.addRequired<MemoryDependenceWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000968 AU.addRequired<MemorySSAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +0000969 AU.addPreserved<DominatorTreeWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000970 AU.addPreserved<MemorySSAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +0000971 }
972};
973} // namespace
974
975PreservedAnalyses GVNHoistPass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +0000976 FunctionAnalysisManager &AM) {
Sebastian Pop41774802016-07-15 13:45:20 +0000977 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
978 AliasAnalysis &AA = AM.getResult<AAManager>(F);
979 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
Daniel Berlinea02eee2016-08-23 05:42:41 +0000980 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
981 GVNHoist G(&DT, &AA, &MD, &MSSA, F.optForMinSize());
Sebastian Pop41774802016-07-15 13:45:20 +0000982 if (!G.run(F))
983 return PreservedAnalyses::all();
984
985 PreservedAnalyses PA;
986 PA.preserve<DominatorTreeAnalysis>();
Daniel Berlinea02eee2016-08-23 05:42:41 +0000987 PA.preserve<MemorySSAAnalysis>();
Sebastian Pop41774802016-07-15 13:45:20 +0000988 return PA;
989}
990
991char GVNHoistLegacyPass::ID = 0;
992INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist",
993 "Early GVN Hoisting of Expressions", false, false)
994INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Daniel Berlinea02eee2016-08-23 05:42:41 +0000995INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Sebastian Pop41774802016-07-15 13:45:20 +0000996INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
997INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
998INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist",
999 "Early GVN Hoisting of Expressions", false, false)
1000
1001FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); }