blob: b7514a6d579312d0b23aef248815dd5bc2e81ec6 [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.
Geoff Berry635e5052017-04-10 20:45:17 +000020//
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
Sebastian Pop41774802016-07-15 13:45:20 +000042//===----------------------------------------------------------------------===//
43
Sebastian Pop5ba9f242016-10-13 01:39:10 +000044#include "llvm/Transforms/Scalar/GVN.h"
Sebastian Pop41774802016-07-15 13:45:20 +000045#include "llvm/ADT/DenseMap.h"
46#include "llvm/ADT/SmallPtrSet.h"
47#include "llvm/ADT/Statistic.h"
Nikolai Bozhenov9e4a1c32017-04-18 13:25:49 +000048#include "llvm/Analysis/GlobalsModRef.h"
Daniel Berlin554dcd82017-04-11 20:06:36 +000049#include "llvm/Analysis/MemorySSA.h"
50#include "llvm/Analysis/MemorySSAUpdater.h"
Sebastian Pop41774802016-07-15 13:45:20 +000051#include "llvm/Analysis/ValueTracking.h"
52#include "llvm/Transforms/Scalar.h"
David Majnemer68623a02016-07-25 02:21:25 +000053#include "llvm/Transforms/Utils/Local.h"
Sebastian Pop41774802016-07-15 13:45:20 +000054
55using namespace llvm;
56
57#define DEBUG_TYPE "gvn-hoist"
58
59STATISTIC(NumHoisted, "Number of instructions hoisted");
60STATISTIC(NumRemoved, "Number of instructions removed");
61STATISTIC(NumLoadsHoisted, "Number of loads hoisted");
62STATISTIC(NumLoadsRemoved, "Number of loads removed");
63STATISTIC(NumStoresHoisted, "Number of stores hoisted");
64STATISTIC(NumStoresRemoved, "Number of stores removed");
65STATISTIC(NumCallsHoisted, "Number of calls hoisted");
66STATISTIC(NumCallsRemoved, "Number of calls removed");
67
68static 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)"));
72static 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
Sebastian Pop38422b12016-07-26 00:15:08 +000077static 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
Sebastian Pop5ba9f242016-10-13 01:39:10 +000082static 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)"));
Sebastian Pop2aadad72016-08-03 20:54:38 +000086
Daniel Berlindcb004f2017-03-02 23:06:46 +000087namespace llvm {
Sebastian Pop41774802016-07-15 13:45:20 +000088
89// Provides a sorting function based on the execution order of two instructions.
90struct SortByDFSIn {
91private:
Sebastian Pop91d4a302016-07-26 00:15:10 +000092 DenseMap<const Value *, unsigned> &DFSNumber;
Sebastian Pop41774802016-07-15 13:45:20 +000093
94public:
Sebastian Pop91d4a302016-07-26 00:15:10 +000095 SortByDFSIn(DenseMap<const Value *, unsigned> &D) : DFSNumber(D) {}
Sebastian Pop41774802016-07-15 13:45:20 +000096
97 // Returns true when A executes before B.
98 bool operator()(const Instruction *A, const Instruction *B) const {
Sebastian Pop4ba7c882016-08-03 20:54:36 +000099 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 }
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000109 assert(ADFS && BDFS);
Sebastian Pop91d4a302016-07-26 00:15:10 +0000110 return ADFS < BDFS;
Sebastian Pop41774802016-07-15 13:45:20 +0000111 }
112};
113
David Majnemer04c7c222016-07-18 06:11:37 +0000114// A map from a pair of VNs to all the instructions with those VNs.
115typedef 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.
Reid Kleckner3498ad12016-07-18 18:53:50 +0000119enum : unsigned { InvalidVN = ~2U };
Sebastian Pop41774802016-07-15 13:45:20 +0000120
121// Records all scalar instructions candidate for code hoisting.
122class InsnInfo {
123 VNtoInsns VNtoScalars;
124
125public:
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);
David Majnemer04c7c222016-07-18 06:11:37 +0000130 VNtoScalars[{V, InvalidVN}].push_back(I);
Sebastian Pop41774802016-07-15 13:45:20 +0000131 }
132
133 const VNtoInsns &getVNTable() const { return VNtoScalars; }
134};
135
136// Records all load instructions candidate for code hoisting.
137class LoadInfo {
138 VNtoInsns VNtoLoads;
139
140public:
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());
David Majnemer04c7c222016-07-18 06:11:37 +0000145 VNtoLoads[{V, InvalidVN}].push_back(Load);
Sebastian Pop41774802016-07-15 13:45:20 +0000146 }
147 }
148
149 const VNtoInsns &getVNTable() const { return VNtoLoads; }
150};
151
152// Records all store instructions candidate for code hoisting.
153class StoreInfo {
154 VNtoInsns VNtoStores;
155
156public:
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();
David Majnemer04c7c222016-07-18 06:11:37 +0000165 VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);
Sebastian Pop41774802016-07-15 13:45:20 +0000166 }
167
168 const VNtoInsns &getVNTable() const { return VNtoStores; }
169};
170
171// Records all call instructions candidate for code hoisting.
172class CallInfo {
173 VNtoInsns VNtoCallsScalars;
174 VNtoInsns VNtoCallsLoads;
175 VNtoInsns VNtoCallsStores;
176
177public:
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);
David Majnemer04c7c222016-07-18 06:11:37 +0000184 auto Entry = std::make_pair(V, InvalidVN);
Sebastian Pop41774802016-07-15 13:45:20 +0000185
186 if (Call->doesNotAccessMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000187 VNtoCallsScalars[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000188 else if (Call->onlyReadsMemory())
David Majnemer04c7c222016-07-18 06:11:37 +0000189 VNtoCallsLoads[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000190 else
David Majnemer04c7c222016-07-18 06:11:37 +0000191 VNtoCallsStores[Entry].push_back(Call);
Sebastian Pop41774802016-07-15 13:45:20 +0000192 }
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
201typedef DenseMap<const BasicBlock *, bool> BBSideEffectsSet;
202typedef SmallVector<Instruction *, 4> SmallVecInsn;
203typedef SmallVectorImpl<Instruction *> SmallVecImplInsn;
204
David Majnemer68623a02016-07-25 02:21:25 +0000205static 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
Sebastian Pop41774802016-07-15 13:45:20 +0000214// 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).
217class GVNHoist {
218public:
Daniel Berlinea02eee2016-08-23 05:42:41 +0000219 GVNHoist(DominatorTree *DT, AliasAnalysis *AA, MemoryDependenceResults *MD,
Hans Wennborg19c0be92017-03-01 17:15:08 +0000220 MemorySSA *MSSA)
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000221 : DT(DT), AA(AA), MD(MD), MSSA(MSSA),
222 MSSAUpdater(make_unique<MemorySSAUpdater>(MSSA)),
Hans Wennborg19c0be92017-03-01 17:15:08 +0000223 HoistingGeps(false),
224 HoistedCtr(0)
225 { }
Aditya Kumar07cb3042016-11-29 14:34:01 +0000226
Daniel Berlin65af45d2016-07-25 17:24:22 +0000227 bool run(Function &F) {
228 VN.setDomTree(DT);
229 VN.setAliasAnalysis(AA);
230 VN.setMemDep(MD);
231 bool Res = false;
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000232 // 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;
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000237 for (auto &Inst : *BB)
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000238 DFSNumber[&Inst] = ++I;
239 }
Daniel Berlin65af45d2016-07-25 17:24:22 +0000240
Sebastian Pop2aadad72016-08-03 20:54:38 +0000241 int ChainLength = 0;
242
Daniel Berlin65af45d2016-07-25 17:24:22 +0000243 // FIXME: use lazy evaluation of VN to avoid the fix-point computation.
244 while (1) {
Sebastian Pop2aadad72016-08-03 20:54:38 +0000245 if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)
246 return Res;
247
Daniel Berlin65af45d2016-07-25 17:24:22 +0000248 auto HoistStat = hoistExpressions(F);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000249 if (HoistStat.first + HoistStat.second == 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000250 return Res;
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000251
252 if (HoistStat.second > 0)
Daniel Berlin65af45d2016-07-25 17:24:22 +0000253 // To address a limitation of the current GVN, we need to rerun the
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000254 // hoisting after we hoisted loads or stores in order to be able to
255 // hoist all scalars dependent on the hoisted ld/st.
Daniel Berlin65af45d2016-07-25 17:24:22 +0000256 VN.clear();
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000257
Daniel Berlin65af45d2016-07-25 17:24:22 +0000258 Res = true;
259 }
260
261 return Res;
262 }
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000263
Daniel Berlin65af45d2016-07-25 17:24:22 +0000264private:
Sebastian Pop41774802016-07-15 13:45:20 +0000265 GVN::ValueTable VN;
266 DominatorTree *DT;
267 AliasAnalysis *AA;
268 MemoryDependenceResults *MD;
Daniel Berlinea02eee2016-08-23 05:42:41 +0000269 MemorySSA *MSSA;
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000270 std::unique_ptr<MemorySSAUpdater> MSSAUpdater;
Sebastian Pop55c30072016-07-27 05:48:12 +0000271 const bool HoistingGeps;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000272 DenseMap<const Value *, unsigned> DFSNumber;
Sebastian Pop41774802016-07-15 13:45:20 +0000273 BBSideEffectsSet BBSideEffects;
Geoff Berry635e5052017-04-10 20:45:17 +0000274 DenseSet<const BasicBlock*> HoistBarrier;
David Majnemeraa241782016-07-18 00:35:01 +0000275 int HoistedCtr;
276
Sebastian Pop41774802016-07-15 13:45:20 +0000277 enum InsKind { Unknown, Scalar, Load, Store };
278
Sebastian Pop41774802016-07-15 13:45:20 +0000279 // 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
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000299 // 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;
Sebastian Pop41774802016-07-15 13:45:20 +0000304
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000305 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())
Sebastian Pop41774802016-07-15 13:45:20 +0000321 return false;
322
323 const BasicBlock *BB = *It;
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000324 if (WorkList.erase(BB)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000325 // Stop DFS traversal when BB is in the work list.
326 It.skipChildren();
327 continue;
328 }
329
Geoff Berry635e5052017-04-10 20:45:17 +0000330 // We reached the leaf Basic Block => not all paths have this instruction.
331 if (!BB->getTerminator()->getNumSuccessors())
Sebastian Pop41774802016-07-15 13:45:20 +0000332 return false;
333
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000334 // 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
Sebastian Pop41774802016-07-15 13:45:20 +0000339 // 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. */
Sebastian Pop91d4a302016-07-26 00:15:10 +0000347 bool firstInBB(const Instruction *I1, const Instruction *I2) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000348 assert(I1->getParent() == I2->getParent());
Sebastian Pop91d4a302016-07-26 00:15:10 +0000349 unsigned I1DFS = DFSNumber.lookup(I1);
350 unsigned I2DFS = DFSNumber.lookup(I2);
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000351 assert(I1DFS && I2DFS);
Sebastian Pop91d4a302016-07-26 00:15:10 +0000352 return I1DFS < I2DFS;
Daniel Berlin40765a62016-07-25 18:19:49 +0000353 }
Sebastian Pop91d4a302016-07-26 00:15:10 +0000354
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000355 // 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();
Sebastian Pop41774802016-07-15 13:45:20 +0000363 const BasicBlock *OldBB = OldPt->getParent();
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000364 const BasicBlock *NewBB = NewPt->getParent();
365 bool ReachedNewPt = false;
Sebastian Pop41774802016-07-15 13:45:20 +0000366
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000367 for (const MemoryAccess &MA : *Acc)
368 if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {
369 Instruction *Insn = MU->getMemoryInst();
Sebastian Pop1531f302016-09-22 17:22:58 +0000370
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000371 // 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 }
Sebastian Pop41774802016-07-15 13:45:20 +0000382 }
Daniel Berlindcb004f2017-03-02 23:06:46 +0000383 if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA))
Hans Wennborgc7957ef2016-09-22 21:20:53 +0000384 return true;
385 }
Sebastian Pop8e6e3312016-09-22 15:33:51 +0000386
Sebastian Pop41774802016-07-15 13:45:20 +0000387 return false;
388 }
389
390 // Return true when there are exception handling or loads of memory Def
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000391 // between Def and NewPt. This function is only called for stores: Def is
392 // the MemoryDef of the store to be hoisted.
Sebastian Pop41774802016-07-15 13:45:20 +0000393
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.
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000397 bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,
398 int &NBBsOnAllPaths) {
Sebastian Pop41774802016-07-15 13:45:20 +0000399 const BasicBlock *NewBB = NewPt->getParent();
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000400 const BasicBlock *OldBB = Def->getBlock();
Sebastian Pop41774802016-07-15 13:45:20 +0000401 assert(DT->dominates(NewBB, OldBB) && "invalid path");
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000402 assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&
Sebastian Pop41774802016-07-15 13:45:20 +0000403 "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;) {
Geoff Berry635e5052017-04-10 20:45:17 +0000410 const BasicBlock *BB = *I;
411 if (BB == NewBB) {
Sebastian Pop41774802016-07-15 13:45:20 +0000412 // Stop traversal when reaching HoistPt.
413 I.skipChildren();
414 continue;
415 }
416
Aditya Kumar314ebe02016-11-29 14:36:27 +0000417 // Stop walk once the limit is reached.
418 if (NBBsOnAllPaths == 0)
419 return true;
420
Sebastian Pop41774802016-07-15 13:45:20 +0000421 // Impossible to hoist with exceptions on the path.
Geoff Berry635e5052017-04-10 20:45:17 +0000422 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))
Sebastian Pop41774802016-07-15 13:45:20 +0000429 return true;
430
431 // Check that we do not move a store past loads.
Geoff Berry635e5052017-04-10 20:45:17 +0000432 if (hasMemoryUse(NewPt, Def, BB))
Sebastian Pop41774802016-07-15 13:45:20 +0000433 return true;
434
Sebastian Pop41774802016-07-15 13:45:20 +0000435 // -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.
Geoff Berry635e5052017-04-10 20:45:17 +0000449 bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,
Sebastian Pop41774802016-07-15 13:45:20 +0000450 int &NBBsOnAllPaths) {
Geoff Berry635e5052017-04-10 20:45:17 +0000451 assert(DT->dominates(HoistPt, SrcBB) && "Invalid path");
Sebastian Pop41774802016-07-15 13:45:20 +0000452
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.
Geoff Berry635e5052017-04-10 20:45:17 +0000458 for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) {
459 const BasicBlock *BB = *I;
460 if (BB == HoistPt) {
Sebastian Pop41774802016-07-15 13:45:20 +0000461 // Stop traversal when reaching NewHoistPt.
462 I.skipChildren();
463 continue;
464 }
465
Sebastian Pop41774802016-07-15 13:45:20 +0000466 // Stop walk once the limit is reached.
467 if (NBBsOnAllPaths == 0)
468 return true;
469
Aditya Kumar314ebe02016-11-29 14:36:27 +0000470 // Impossible to hoist with exceptions on the path.
Geoff Berry635e5052017-04-10 20:45:17 +0000471 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))
Aditya Kumar314ebe02016-11-29 14:36:27 +0000478 return true;
479
Sebastian Pop41774802016-07-15 13:45:20 +0000480 // -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))
David Majnemer4c66a712016-07-18 00:34:58 +0000511 if (auto *UD = dyn_cast<MemoryUseOrDef>(D))
Sebastian Pop91d4a302016-07-26 00:15:10 +0000512 if (firstInBB(NewPt, UD->getMemoryInst()))
Sebastian Pop41774802016-07-15 13:45:20 +0000513 // 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) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000518 if (hasEHOrLoadsOnPath(NewPt, dyn_cast<MemoryDef>(U), NBBsOnAllPaths))
Sebastian Pop41774802016-07-15 13:45:20 +0000519 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
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000534 // 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) {
Aditya Kumar07cb3042016-11-29 14:34:01 +0000539 // Check that the hoisted expression is needed on all paths.
540 if (!hoistingFromAllPaths(HoistBB, WL))
Sebastian Pop41774802016-07-15 13:45:20 +0000541 return false;
542
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000543 for (const BasicBlock *BB : WL)
544 if (hasEHOnPath(HoistBB, BB, NBBsOnAllPaths))
545 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000546
Sebastian Pop41774802016-07-15 13:45:20 +0000547 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
Aditya Kumar314ebe02016-11-29 14:36:27 +0000567 int NumBBsOnAllPaths = MaxNumberOfBBSInPath;
Sebastian Pop41774802016-07-15 13:45:20 +0000568
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)
George Burgess IV66837ab2016-11-01 21:17:46 +0000575 UD = MSSA->getMemoryAccess(HoistPt);
Sebastian Pop41774802016-07-15 13:45:20 +0000576
577 for (++II; II != InstructionsToHoist.end(); ++II) {
578 Instruction *Insn = *II;
579 BasicBlock *BB = Insn->getParent();
580 BasicBlock *NewHoistBB;
581 Instruction *NewHoistPt;
582
Aditya Kumar314ebe02016-11-29 14:36:27 +0000583 if (BB == HoistBB) { // Both are in the same Basic Block.
Sebastian Pop41774802016-07-15 13:45:20 +0000584 NewHoistBB = HoistBB;
Sebastian Pop91d4a302016-07-26 00:15:10 +0000585 NewHoistPt = firstInBB(Insn, HoistPt) ? Insn : HoistPt;
Sebastian Pop41774802016-07-15 13:45:20 +0000586 } else {
Aditya Kumar314ebe02016-11-29 14:36:27 +0000587 // If the hoisting point contains one of the instructions,
588 // then hoist there, otherwise hoist before the terminator.
Sebastian Pop41774802016-07-15 13:45:20 +0000589 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
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000598 SmallPtrSet<const BasicBlock *, 2> WL;
599 WL.insert(HoistBB);
600 WL.insert(BB);
601
Sebastian Pop41774802016-07-15 13:45:20 +0000602 if (K == InsKind::Scalar) {
Aditya Kumar314ebe02016-11-29 14:36:27 +0000603 if (safeToHoistScalar(NewHoistBB, WL, NumBBsOnAllPaths)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000604 // 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 ||
Sebastian Pop5f0d0e62016-08-25 11:55:47 +0000617 hoistingFromAllPaths(NewHoistBB, WL)) &&
Sebastian Pop41774802016-07-15 13:45:20 +0000618 // Also check that it is safe to move the load or store from HoistPt
619 // to NewHoistPt, and from Insn to NewHoistPt.
Aditya Kumar314ebe02016-11-29 14:36:27 +0000620 safeToHoistLdSt(NewHoistPt, HoistPt, UD, K, NumBBsOnAllPaths) &&
George Burgess IV66837ab2016-11-01 21:17:46 +0000621 safeToHoistLdSt(NewHoistPt, Insn, MSSA->getMemoryAccess(Insn),
Aditya Kumar314ebe02016-11-29 14:36:27 +0000622 K, NumBBsOnAllPaths)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000623 // 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)
David Majnemer4c66a712016-07-18 00:34:58 +0000633 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000634
635 // Start over from BB.
636 Start = II;
637 if (K != InsKind::Scalar)
George Burgess IV66837ab2016-11-01 21:17:46 +0000638 UD = MSSA->getMemoryAccess(*Start);
Sebastian Pop41774802016-07-15 13:45:20 +0000639 HoistPt = Insn;
640 HoistBB = BB;
Aditya Kumar314ebe02016-11-29 14:36:27 +0000641 NumBBsOnAllPaths = MaxNumberOfBBSInPath;
Sebastian Pop41774802016-07-15 13:45:20 +0000642 }
643
644 // Save the last partition.
645 if (std::distance(Start, II) > 1)
David Majnemer4c66a712016-07-18 00:34:58 +0000646 HPL.push_back({HoistBB, SmallVecInsn(Start, II)});
Sebastian Pop41774802016-07-15 13:45:20 +0000647 }
648
649 // Initialize HPL from Map.
650 void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,
651 InsKind K) {
David Majnemer4c66a712016-07-18 00:34:58 +0000652 for (const auto &Entry : Map) {
Sebastian Pop41774802016-07-15 13:45:20 +0000653 if (MaxHoistedThreshold != -1 && ++HoistedCtr > MaxHoistedThreshold)
654 return;
655
David Majnemer4c66a712016-07-18 00:34:58 +0000656 const SmallVecInsn &V = Entry.second;
Sebastian Pop41774802016-07-15 13:45:20 +0000657 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)
Geoff Berry635e5052017-04-10 20:45:17 +0000663 // We don't need to check for hoist-barriers here because if
664 // I->getParent() is a barrier then I precedes the barrier.
Sebastian Pop41774802016-07-15 13:45:20 +0000665 if (!hasEH(I->getParent()))
666 InstructionsToHoist.push_back(I);
667
David Majnemer4c66a712016-07-18 00:34:58 +0000668 if (!InstructionsToHoist.empty())
Sebastian Pop41774802016-07-15 13:45:20 +0000669 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 {
David Majnemer4c66a712016-07-18 00:34:58 +0000679 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;
Sebastian Pop41774802016-07-15 13:45:20 +0000683
684 return true;
685 }
686
Sebastian Pop55c30072016-07-27 05:48:12 +0000687 // 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)) {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000693 if (const GetElementPtrInst *GepOp =
694 dyn_cast<GetElementPtrInst>(Inst)) {
Sebastian Pop55c30072016-07-27 05:48:12 +0000695 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 {
Sebastian Pop5ba9f242016-10-13 01:39:10 +0000711 assert(allGepOperandsAvailable(Gep, HoistPt) &&
712 "GEP operands not available");
Sebastian Pop55c30072016-07-27 05:48:12 +0000713
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());
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +0000744 ClonedGep->andIRFlags(OtherGep);
Sebastian Pop55c30072016-07-27 05:48:12 +0000745 }
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 {
Sebastian Pop41774802016-07-15 13:45:20 +0000756 // Check whether the GEP of a ld/st can be synthesized at HoistPt.
David Majnemerbd210122016-07-20 21:05:01 +0000757 GetElementPtrInst *Gep = nullptr;
Sebastian Pop41774802016-07-15 13:45:20 +0000758 Instruction *Val = nullptr;
Sebastian Pop55c30072016-07-27 05:48:12 +0000759 if (auto *Ld = dyn_cast<LoadInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000760 Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());
Sebastian Pop55c30072016-07-27 05:48:12 +0000761 } else if (auto *St = dyn_cast<StoreInst>(Repl)) {
David Majnemerbd210122016-07-20 21:05:01 +0000762 Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());
Sebastian Pop41774802016-07-15 13:45:20 +0000763 Val = dyn_cast<Instruction>(St->getValueOperand());
Sebastian Pop31fd5062016-07-21 23:22:10 +0000764 // Check that the stored value is available.
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000765 if (Val) {
766 if (isa<GetElementPtrInst>(Val)) {
767 // Check whether we can compute the GEP at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000768 if (!allGepOperandsAvailable(Val, HoistPt))
Sebastian Pop0e2cec02016-07-22 00:07:01 +0000769 return false;
770 } else if (!DT->dominates(Val->getParent(), HoistPt))
771 return false;
772 }
Sebastian Pop41774802016-07-15 13:45:20 +0000773 }
774
Sebastian Pop41774802016-07-15 13:45:20 +0000775 // Check whether we can compute the Gep at HoistPt.
Sebastian Pop55c30072016-07-27 05:48:12 +0000776 if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))
Sebastian Pop41774802016-07-15 13:45:20 +0000777 return false;
778
Sebastian Pop55c30072016-07-27 05:48:12 +0000779 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);
Sebastian Pop41774802016-07-15 13:45:20 +0000780
Sebastian Pop55c30072016-07-27 05:48:12 +0000781 if (Val && isa<GetElementPtrInst>(Val))
782 makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);
Sebastian Pop41774802016-07-15 13:45:20 +0000783
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)
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000796 if (I->getParent() == HoistPt)
Sebastian Pop41774802016-07-15 13:45:20 +0000797 // 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.
Sebastian Pop586d3ea2016-07-27 05:13:52 +0000800 if (!Repl || firstInBB(I, Repl))
801 Repl = I;
Sebastian Pop41774802016-07-15 13:45:20 +0000802
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000803 // Keep track of whether we moved the instruction so we know whether we
804 // should move the MemoryAccess.
805 bool MoveAccess = true;
Sebastian Pop41774802016-07-15 13:45:20 +0000806 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");
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000810 MoveAccess = false;
Sebastian Pop41774802016-07-15 13:45:20 +0000811 } 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.
Sebastian Pop429740a2016-08-04 23:49:05 +0000819 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 }
Sebastian Pop55c30072016-07-27 05:48:12 +0000830
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000831 // Move the instruction at the end of HoistPt.
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000832 Instruction *Last = HoistPt->getTerminator();
Eli Friedmanc6885fc2016-12-07 19:55:59 +0000833 MD->removeInstruction(Repl);
Sebastian Pop4ba7c882016-08-03 20:54:36 +0000834 Repl->moveBefore(Last);
835
836 DFSNumber[Repl] = DFSNumber[Last]++;
Sebastian Pop41774802016-07-15 13:45:20 +0000837 }
838
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000839 MemoryAccess *NewMemAcc = MSSA->getMemoryAccess(Repl);
840
841 if (MoveAccess) {
842 if (MemoryUseOrDef *OldMemAcc =
843 dyn_cast_or_null<MemoryUseOrDef>(NewMemAcc)) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000844 // 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();
Daniel Berlinf75fd1b2016-08-11 20:32:43 +0000847 NewMemAcc =
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000848 MSSAUpdater->createMemoryAccessInBB(Repl, Def, HoistPt, MemorySSA::End);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000849 OldMemAcc->replaceAllUsesWith(NewMemAcc);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000850 MSSAUpdater->removeMemoryAccess(OldMemAcc);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000851 }
852 }
853
Sebastian Pop41774802016-07-15 13:45:20 +0000854 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;
David Majnemer47285692016-07-25 02:21:23 +0000867 if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {
868 ReplacementLoad->setAlignment(
869 std::min(ReplacementLoad->getAlignment(),
870 cast<LoadInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000871 ++NumLoadsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000872 } else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {
873 ReplacementStore->setAlignment(
874 std::min(ReplacementStore->getAlignment(),
875 cast<StoreInst>(I)->getAlignment()));
Sebastian Pop41774802016-07-15 13:45:20 +0000876 ++NumStoresRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000877 } 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)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000882 ++NumCallsRemoved;
David Majnemer47285692016-07-25 02:21:23 +0000883 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000884
885 if (NewMemAcc) {
886 // Update the uses of the old MSSA access with NewMemAcc.
887 MemoryAccess *OldMA = MSSA->getMemoryAccess(I);
888 OldMA->replaceAllUsesWith(NewMemAcc);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000889 MSSAUpdater->removeMemoryAccess(OldMA);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000890 }
891
Peter Collingbourne8f1dd5c2016-09-07 23:39:04 +0000892 Repl->andIRFlags(I);
David Majnemer68623a02016-07-25 02:21:25 +0000893 combineKnownMetadata(Repl, I);
Sebastian Pop41774802016-07-15 13:45:20 +0000894 I->replaceAllUsesWith(Repl);
Sebastian Pop46601992016-08-27 02:48:41 +0000895 // Also invalidate the Alias Analysis cache.
896 MD->removeInstruction(I);
Sebastian Pop41774802016-07-15 13:45:20 +0000897 I->eraseFromParent();
898 }
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000899
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();
David Majnemer0a16c222016-08-11 21:15:00 +0000909 if (all_of(In, [&](Use &U) { return U == NewMemAcc; })) {
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000910 Phi->replaceAllUsesWith(NewMemAcc);
Daniel Berlin17e8d0e2017-02-22 22:19:55 +0000911 MSSAUpdater->removeMemoryAccess(Phi);
Sebastian Pop5d3822f2016-08-03 20:54:33 +0000912 }
913 }
914 }
Sebastian Pop41774802016-07-15 13:45:20 +0000915 }
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())) {
Sebastian Pop38422b12016-07-26 00:15:08 +0000933 int InstructionNb = 0;
Sebastian Pop41774802016-07-15 13:45:20 +0000934 for (Instruction &I1 : *BB) {
Geoff Berry635e5052017-04-10 20:45:17 +0000935 // 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 }
Sebastian Pop38422b12016-07-26 00:15:08 +0000941 // 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
Sebastian Pop440f15b2016-09-22 14:45:40 +0000946 // Do not value number terminator instructions.
Sebastian Pop5d68aa72016-09-22 15:08:09 +0000947 if (isa<TerminatorInst>(&I1))
Sebastian Pop440f15b2016-09-22 14:45:40 +0000948 break;
949
David Majnemer4c66a712016-07-18 00:34:58 +0000950 if (auto *Load = dyn_cast<LoadInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000951 LI.insert(Load, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000952 else if (auto *Store = dyn_cast<StoreInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000953 SI.insert(Store, VN);
David Majnemer4c66a712016-07-18 00:34:58 +0000954 else if (auto *Call = dyn_cast<CallInst>(&I1)) {
955 if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {
Sebastian Pop41774802016-07-15 13:45:20 +0000956 if (isa<DbgInfoIntrinsic>(Intr) ||
957 Intr->getIntrinsicID() == Intrinsic::assume)
958 continue;
959 }
Hans Wennborg19c0be92017-03-01 17:15:08 +0000960 if (Call->mayHaveSideEffects())
961 break;
Matt Arsenault6ad97732016-08-04 20:52:57 +0000962
963 if (Call->isConvergent())
964 break;
965
Sebastian Pop41774802016-07-15 13:45:20 +0000966 CI.insert(Call, VN);
Sebastian Pop55c30072016-07-27 05:48:12 +0000967 } else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))
Sebastian Pop41774802016-07-15 13:45:20 +0000968 // 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 }
Sebastian Pop41774802016-07-15 13:45:20 +0000985};
986
987class GVNHoistLegacyPass : public FunctionPass {
988public:
989 static char ID;
990
991 GVNHoistLegacyPass() : FunctionPass(ID) {
992 initializeGVNHoistLegacyPassPass(*PassRegistry::getPassRegistry());
993 }
994
995 bool runOnFunction(Function &F) override {
Paul Robinson2d23c022016-07-19 22:57:14 +0000996 if (skipFunction(F))
997 return false;
Sebastian Pop41774802016-07-15 13:45:20 +0000998 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
999 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1000 auto &MD = getAnalysis<MemoryDependenceWrapperPass>().getMemDep();
Daniel Berlinea02eee2016-08-23 05:42:41 +00001001 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
Sebastian Pop41774802016-07-15 13:45:20 +00001002
Hans Wennborg19c0be92017-03-01 17:15:08 +00001003 GVNHoist G(&DT, &AA, &MD, &MSSA);
Sebastian Pop41774802016-07-15 13:45:20 +00001004 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>();
Daniel Berlinea02eee2016-08-23 05:42:41 +00001011 AU.addRequired<MemorySSAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +00001012 AU.addPreserved<DominatorTreeWrapperPass>();
Daniel Berlinea02eee2016-08-23 05:42:41 +00001013 AU.addPreserved<MemorySSAWrapperPass>();
Nikolai Bozhenov9e4a1c32017-04-18 13:25:49 +00001014 AU.addPreserved<GlobalsAAWrapperPass>();
Sebastian Pop41774802016-07-15 13:45:20 +00001015 }
1016};
1017} // namespace
1018
Sebastian Pop5ba9f242016-10-13 01:39:10 +00001019PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) {
Sebastian Pop41774802016-07-15 13:45:20 +00001020 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);
1021 AliasAnalysis &AA = AM.getResult<AAManager>(F);
1022 MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);
Daniel Berlinea02eee2016-08-23 05:42:41 +00001023 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();
Hans Wennborg19c0be92017-03-01 17:15:08 +00001024 GVNHoist G(&DT, &AA, &MD, &MSSA);
Sebastian Pop41774802016-07-15 13:45:20 +00001025 if (!G.run(F))
1026 return PreservedAnalyses::all();
1027
1028 PreservedAnalyses PA;
1029 PA.preserve<DominatorTreeAnalysis>();
Daniel Berlinea02eee2016-08-23 05:42:41 +00001030 PA.preserve<MemorySSAAnalysis>();
Nikolai Bozhenov9e4a1c32017-04-18 13:25:49 +00001031 PA.preserve<GlobalsAA>();
Sebastian Pop41774802016-07-15 13:45:20 +00001032 return PA;
1033}
1034
1035char GVNHoistLegacyPass::ID = 0;
1036INITIALIZE_PASS_BEGIN(GVNHoistLegacyPass, "gvn-hoist",
1037 "Early GVN Hoisting of Expressions", false, false)
1038INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
Daniel Berlinea02eee2016-08-23 05:42:41 +00001039INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Sebastian Pop41774802016-07-15 13:45:20 +00001040INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1041INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1042INITIALIZE_PASS_END(GVNHoistLegacyPass, "gvn-hoist",
1043 "Early GVN Hoisting of Expressions", false, false)
1044
1045FunctionPass *llvm::createGVNHoistPass() { return new GVNHoistLegacyPass(); }