blob: 35f2f2c9a679c41c79fbac520beddd485cda2026 [file] [log] [blame]
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +00001//===- MergedLoadStoreMotion.cpp - merge and hoist/sink load/stores -------===//
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//! \file
11//! \brief This pass performs merges of loads and stores on both sides of a
12// diamond (hammock). It hoists the loads and sinks the stores.
13//
14// The algorithm iteratively hoists two loads to the same address out of a
15// diamond (hammock) and merges them into a single load in the header. Similar
16// it sinks and merges two stores to the tail block (footer). The algorithm
17// iterates over the instructions of one side of the diamond and attempts to
18// find a matching load/store on the other side. It hoists / sinks when it
19// thinks it safe to do so. This optimization helps with eg. hiding load
20// latencies, triggering if-conversion, and reducing static code size.
21//
22//===----------------------------------------------------------------------===//
23//
24//
25// Example:
26// Diamond shaped code before merge:
27//
28// header:
29// br %cond, label %if.then, label %if.else
Gerolf Hoflehnerea96a3d2014-08-07 23:19:55 +000030// + +
31// + +
32// + +
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000033// if.then: if.else:
34// %lt = load %addr_l %le = load %addr_l
35// <use %lt> <use %le>
36// <...> <...>
37// store %st, %addr_s store %se, %addr_s
38// br label %if.end br label %if.end
Gerolf Hoflehnerea96a3d2014-08-07 23:19:55 +000039// + +
40// + +
41// + +
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000042// if.end ("footer"):
43// <...>
44//
45// Diamond shaped code after merge:
46//
47// header:
48// %l = load %addr_l
49// br %cond, label %if.then, label %if.else
Gerolf Hoflehnerea96a3d2014-08-07 23:19:55 +000050// + +
51// + +
52// + +
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000053// if.then: if.else:
54// <use %l> <use %l>
55// <...> <...>
56// br label %if.end br label %if.end
Gerolf Hoflehnerea96a3d2014-08-07 23:19:55 +000057// + +
58// + +
59// + +
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000060// if.end ("footer"):
61// %s.sink = phi [%st, if.then], [%se, if.else]
62// <...>
63// store %s.sink, %addr_s
64// <...>
65//
66//
67//===----------------------- TODO -----------------------------------------===//
68//
69// 1) Generalize to regions other than diamonds
70// 2) Be more aggressive merging memory operations
71// Note that both changes require register pressure control
72//
73//===----------------------------------------------------------------------===//
74
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000075#include "llvm/ADT/Statistic.h"
76#include "llvm/Analysis/AliasAnalysis.h"
77#include "llvm/Analysis/CFG.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000078#include "llvm/Analysis/GlobalsModRef.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000079#include "llvm/Analysis/Loads.h"
80#include "llvm/Analysis/MemoryBuiltins.h"
81#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Eli Friedman9f8031c2016-06-12 02:11:20 +000082#include "llvm/Analysis/ValueTracking.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000083#include "llvm/IR/Metadata.h"
84#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000085#include "llvm/Support/Debug.h"
Benjamin Kramerb85d3752015-03-23 18:45:56 +000086#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000087#include "llvm/Transforms/Scalar.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000088#include "llvm/Transforms/Utils/BasicBlockUtils.h"
89#include "llvm/Transforms/Utils/SSAUpdater.h"
Hans Wennborg083ca9b2015-10-06 23:24:35 +000090
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000091using namespace llvm;
92
93#define DEBUG_TYPE "mldst-motion"
94
95//===----------------------------------------------------------------------===//
96// MergedLoadStoreMotion Pass
97//===----------------------------------------------------------------------===//
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000098
Davide Italiano41315f72016-06-16 17:40:53 +000099namespace {
100class MergedLoadStoreMotion : public FunctionPass {
101 AliasAnalysis *AA;
102 MemoryDependenceResults *MD;
103
104public:
105 static char ID; // Pass identification, replacement for typeid
106 MergedLoadStoreMotion()
107 : FunctionPass(ID), MD(nullptr), MagicCompileTimeControl(250) {
108 initializeMergedLoadStoreMotionPass(*PassRegistry::getPassRegistry());
109 }
110
111 bool runOnFunction(Function &F) override;
112
113private:
114 // This transformation requires dominator postdominator info
115 void getAnalysisUsage(AnalysisUsage &AU) const override {
116 AU.setPreservesCFG();
117 AU.addRequired<AAResultsWrapperPass>();
118 AU.addPreserved<GlobalsAAWrapperPass>();
119 AU.addPreserved<MemoryDependenceWrapperPass>();
120 }
121
122 // Helper routines
123
124 ///
125 /// \brief Remove instruction from parent and update memory dependence
126 /// analysis.
127 ///
128 void removeInstruction(Instruction *Inst);
129 BasicBlock *getDiamondTail(BasicBlock *BB);
130 bool isDiamondHead(BasicBlock *BB);
131 // Routines for hoisting loads
132 bool isLoadHoistBarrierInRange(const Instruction &Start,
133 const Instruction &End, LoadInst *LI,
134 bool SafeToLoadUnconditionally);
135 LoadInst *canHoistFromBlock(BasicBlock *BB, LoadInst *LI);
136 void hoistInstruction(BasicBlock *BB, Instruction *HoistCand,
137 Instruction *ElseInst);
138 bool isSafeToHoist(Instruction *I) const;
139 bool hoistLoad(BasicBlock *BB, LoadInst *HoistCand, LoadInst *ElseInst);
140 bool mergeLoads(BasicBlock *BB);
141 // Routines for sinking stores
142 StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
143 PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
144 bool isStoreSinkBarrierInRange(const Instruction &Start,
145 const Instruction &End, MemoryLocation Loc);
146 bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
147 bool mergeStores(BasicBlock *BB);
148 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
149 // where Size0 and Size1 are the #instructions on the two sides of
150 // the diamond. The constant chosen here is arbitrary. Compiler Time
151 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
152 const int MagicCompileTimeControl;
153};
154
155char MergedLoadStoreMotion::ID = 0;
156} // anonymous namespace
157
158///
159/// \brief createMergedLoadStoreMotionPass - The public interface to this file.
160///
161FunctionPass *llvm::createMergedLoadStoreMotionPass() {
162 return new MergedLoadStoreMotion();
163}
164
165INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion",
166 "MergedLoadStoreMotion", false, false)
167INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
168INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
169INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion",
170 "MergedLoadStoreMotion", false, false)
Davide Italiano44faf7f2016-06-13 22:27:30 +0000171
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000172///
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000173/// \brief Remove instruction from parent and update memory dependence analysis.
174///
Davide Italiano41315f72016-06-16 17:40:53 +0000175void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000176 // Notify the memory dependence analysis.
177 if (MD) {
178 MD->removeInstruction(Inst);
David Majnemer8cce3332016-05-26 05:43:12 +0000179 if (auto *LI = dyn_cast<LoadInst>(Inst))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000180 MD->invalidateCachedPointerInfo(LI->getPointerOperand());
David Majnemer8cce3332016-05-26 05:43:12 +0000181 if (Inst->getType()->isPtrOrPtrVectorTy()) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000182 MD->invalidateCachedPointerInfo(Inst);
183 }
184 }
185 Inst->eraseFromParent();
186}
187
188///
Davide Italiano41315f72016-06-16 17:40:53 +0000189/// \brief Return tail block of a diamond.
190///
191BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
192 assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
193 return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor();
194}
195
196///
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000197/// \brief True when BB is the head of a diamond (hammock)
198///
Davide Italiano41315f72016-06-16 17:40:53 +0000199bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000200 if (!BB)
201 return false;
David Majnemer8cce3332016-05-26 05:43:12 +0000202 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
203 if (!BI || !BI->isConditional())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000204 return false;
205
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000206 BasicBlock *Succ0 = BI->getSuccessor(0);
207 BasicBlock *Succ1 = BI->getSuccessor(1);
208
David Majnemer8cce3332016-05-26 05:43:12 +0000209 if (!Succ0->getSinglePredecessor())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000210 return false;
David Majnemer8cce3332016-05-26 05:43:12 +0000211 if (!Succ1->getSinglePredecessor())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000212 return false;
213
David Majnemer8cce3332016-05-26 05:43:12 +0000214 BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
215 BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000216 // Ignore triangles.
David Majnemer8cce3332016-05-26 05:43:12 +0000217 if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000218 return false;
219 return true;
220}
221
222///
223/// \brief True when instruction is a hoist barrier for a load
224///
225/// Whenever an instruction could possibly modify the value
226/// being loaded or protect against the load from happening
227/// it is considered a hoist barrier.
228///
Davide Italiano41315f72016-06-16 17:40:53 +0000229bool MergedLoadStoreMotion::isLoadHoistBarrierInRange(
230 const Instruction &Start, const Instruction &End, LoadInst *LI,
231 bool SafeToLoadUnconditionally) {
David Majnemer47451252016-05-26 07:11:09 +0000232 if (!SafeToLoadUnconditionally)
233 for (const Instruction &Inst :
234 make_range(Start.getIterator(), End.getIterator()))
Eli Friedman9f8031c2016-06-12 02:11:20 +0000235 if (!isGuaranteedToTransferExecutionToSuccessor(&Inst))
David Majnemer47451252016-05-26 07:11:09 +0000236 return true;
Chandler Carruthac80dc72015-06-17 07:18:54 +0000237 MemoryLocation Loc = MemoryLocation::get(LI);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000238 return AA->canInstructionRangeModRef(Start, End, Loc, MRI_Mod);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000239}
240
241///
242/// \brief Decide if a load can be hoisted
243///
244/// When there is a load in \p BB to the same address as \p LI
245/// and it can be hoisted from \p BB, return that load.
246/// Otherwise return Null.
247///
Davide Italiano41315f72016-06-16 17:40:53 +0000248LoadInst *MergedLoadStoreMotion::canHoistFromBlock(BasicBlock *BB1,
249 LoadInst *Load0) {
David Majnemer47451252016-05-26 07:11:09 +0000250 BasicBlock *BB0 = Load0->getParent();
251 BasicBlock *Head = BB0->getSinglePredecessor();
252 bool SafeToLoadUnconditionally = isSafeToLoadUnconditionally(
253 Load0->getPointerOperand(), Load0->getAlignment(),
254 Load0->getModule()->getDataLayout(),
255 /*ScanFrom=*/Head->getTerminator());
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000256 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000257 ++BBI) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000258 Instruction *Inst = &*BBI;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000259
260 // Only merge and hoist loads when their result in used only in BB
David Majnemer47451252016-05-26 07:11:09 +0000261 auto *Load1 = dyn_cast<LoadInst>(Inst);
262 if (!Load1 || Inst->isUsedOutsideOfBlock(BB1))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000263 continue;
264
Chandler Carruthac80dc72015-06-17 07:18:54 +0000265 MemoryLocation Loc0 = MemoryLocation::get(Load0);
266 MemoryLocation Loc1 = MemoryLocation::get(Load1);
Chad Rosier66a9d072016-06-14 12:47:18 +0000267 if (Load0->isSameOperationAs(Load1) && AA->isMustAlias(Loc0, Loc1) &&
David Majnemer47451252016-05-26 07:11:09 +0000268 !isLoadHoistBarrierInRange(BB1->front(), *Load1, Load1,
Davide Italiano41315f72016-06-16 17:40:53 +0000269 SafeToLoadUnconditionally) &&
David Majnemer47451252016-05-26 07:11:09 +0000270 !isLoadHoistBarrierInRange(BB0->front(), *Load0, Load0,
Davide Italiano41315f72016-06-16 17:40:53 +0000271 SafeToLoadUnconditionally)) {
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000272 return Load1;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000273 }
274 }
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000275 return nullptr;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000276}
277
278///
279/// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into
280/// \p BB
281///
282/// BB is the head of a diamond
283///
Davide Italiano41315f72016-06-16 17:40:53 +0000284void MergedLoadStoreMotion::hoistInstruction(BasicBlock *BB,
285 Instruction *HoistCand,
286 Instruction *ElseInst) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000287 DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump();
288 dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n";
289 dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n");
290 // Hoist the instruction.
291 assert(HoistCand->getParent() != BB);
292
293 // Intersect optional metadata.
294 HoistCand->intersectOptionalDataWith(ElseInst);
Adrian Prantlcbdfdb72015-08-20 22:00:30 +0000295 HoistCand->dropUnknownNonDebugMetadata();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000296
297 // Prepend point for instruction insert
298 Instruction *HoistPt = BB->getTerminator();
299
300 // Merged instruction
301 Instruction *HoistedInst = HoistCand->clone();
302
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000303 // Hoist instruction.
304 HoistedInst->insertBefore(HoistPt);
305
306 HoistCand->replaceAllUsesWith(HoistedInst);
Davide Italiano41315f72016-06-16 17:40:53 +0000307 removeInstruction(HoistCand);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000308 // Replace the else block instruction.
309 ElseInst->replaceAllUsesWith(HoistedInst);
Davide Italiano41315f72016-06-16 17:40:53 +0000310 removeInstruction(ElseInst);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000311}
312
313///
314/// \brief Return true if no operand of \p I is defined in I's parent block
315///
Davide Italiano41315f72016-06-16 17:40:53 +0000316bool MergedLoadStoreMotion::isSafeToHoist(Instruction *I) const {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000317 BasicBlock *Parent = I->getParent();
David Majnemer8cce3332016-05-26 05:43:12 +0000318 for (Use &U : I->operands())
319 if (auto *Instr = dyn_cast<Instruction>(&U))
320 if (Instr->getParent() == Parent)
321 return false;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000322 return true;
323}
324
325///
326/// \brief Merge two equivalent loads and GEPs and hoist into diamond head
327///
Davide Italiano41315f72016-06-16 17:40:53 +0000328bool MergedLoadStoreMotion::hoistLoad(BasicBlock *BB, LoadInst *L0,
329 LoadInst *L1) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000330 // Only one definition?
David Majnemer8cce3332016-05-26 05:43:12 +0000331 auto *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
332 auto *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000333 if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) &&
334 A0->hasOneUse() && (A0->getParent() == L0->getParent()) &&
335 A1->hasOneUse() && (A1->getParent() == L1->getParent()) &&
336 isa<GetElementPtrInst>(A0)) {
337 DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump();
338 dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n";
339 dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n");
Davide Italiano41315f72016-06-16 17:40:53 +0000340 hoistInstruction(BB, A0, A1);
341 hoistInstruction(BB, L0, L1);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000342 return true;
David Majnemer8cce3332016-05-26 05:43:12 +0000343 }
344 return false;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000345}
346
347///
348/// \brief Try to hoist two loads to same address into diamond header
349///
350/// Starting from a diamond head block, iterate over the instructions in one
351/// successor block and try to match a load in the second successor.
352///
Davide Italiano41315f72016-06-16 17:40:53 +0000353bool MergedLoadStoreMotion::mergeLoads(BasicBlock *BB) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000354 bool MergedLoads = false;
355 assert(isDiamondHead(BB));
David Majnemer8cce3332016-05-26 05:43:12 +0000356 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000357 BasicBlock *Succ0 = BI->getSuccessor(0);
358 BasicBlock *Succ1 = BI->getSuccessor(1);
359 // #Instructions in Succ1 for Compile Time Control
360 int Size1 = Succ1->size();
361 int NLoads = 0;
362 for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
363 BBI != BBE;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000364 Instruction *I = &*BBI;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000365 ++BBI;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000366
David Majnemer8cce3332016-05-26 05:43:12 +0000367 // Don't move non-simple (atomic, volatile) loads.
368 auto *L0 = dyn_cast<LoadInst>(I);
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000369 if (!L0 || !L0->isSimple() || L0->isUsedOutsideOfBlock(Succ0))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000370 continue;
371
372 ++NLoads;
373 if (NLoads * Size1 >= MagicCompileTimeControl)
374 break;
Davide Italiano41315f72016-06-16 17:40:53 +0000375 if (LoadInst *L1 = canHoistFromBlock(Succ1, L0)) {
376 bool Res = hoistLoad(BB, L0, L1);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000377 MergedLoads |= Res;
378 // Don't attempt to hoist above loads that had not been hoisted.
379 if (!Res)
380 break;
381 }
382 }
383 return MergedLoads;
384}
385
386///
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000387/// \brief True when instruction is a sink barrier for a store
388/// located in Loc
389///
390/// Whenever an instruction could possibly read or modify the
391/// value being stored or protect against the store from
392/// happening it is considered a sink barrier.
393///
Davide Italiano41315f72016-06-16 17:40:53 +0000394bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
395 const Instruction &End,
396 MemoryLocation Loc) {
David Majnemer47451252016-05-26 07:11:09 +0000397 for (const Instruction &Inst :
398 make_range(Start.getIterator(), End.getIterator()))
399 if (Inst.mayThrow())
400 return true;
Chandler Carruth194f59c2015-07-22 23:15:57 +0000401 return AA->canInstructionRangeModRef(Start, End, Loc, MRI_ModRef);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000402}
403
404///
405/// \brief Check if \p BB contains a store to the same address as \p SI
406///
407/// \return The store in \p when it is safe to sink. Otherwise return Null.
408///
Davide Italiano41315f72016-06-16 17:40:53 +0000409StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
410 StoreInst *Store0) {
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000411 DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
Elena Demikhovskyef035bb2015-02-17 13:10:05 +0000412 BasicBlock *BB0 = Store0->getParent();
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000413 for (BasicBlock::reverse_iterator RBI = BB1->rbegin(), RBE = BB1->rend();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000414 RBI != RBE; ++RBI) {
415 Instruction *Inst = &*RBI;
416
David Majnemer47451252016-05-26 07:11:09 +0000417 auto *Store1 = dyn_cast<StoreInst>(Inst);
418 if (!Store1)
419 continue;
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000420
Chandler Carruthac80dc72015-06-17 07:18:54 +0000421 MemoryLocation Loc0 = MemoryLocation::get(Store0);
422 MemoryLocation Loc1 = MemoryLocation::get(Store1);
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000423 if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
Davide Italiano41315f72016-06-16 17:40:53 +0000424 !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) &&
425 !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) {
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000426 return Store1;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000427 }
428 }
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000429 return nullptr;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000430}
431
432///
433/// \brief Create a PHI node in BB for the operands of S0 and S1
434///
Davide Italiano41315f72016-06-16 17:40:53 +0000435PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
436 StoreInst *S1) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000437 // Create a phi if the values mismatch.
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000438 Value *Opd1 = S0->getValueOperand();
439 Value *Opd2 = S1->getValueOperand();
David Majnemer8cce3332016-05-26 05:43:12 +0000440 if (Opd1 == Opd2)
441 return nullptr;
442
443 auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
444 &BB->front());
445 NewPN->addIncoming(Opd1, S0->getParent());
446 NewPN->addIncoming(Opd2, S1->getParent());
447 if (MD && NewPN->getType()->getScalarType()->isPointerTy())
448 MD->invalidateCachedPointerInfo(NewPN);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000449 return NewPN;
450}
451
452///
453/// \brief Merge two stores to same address and sink into \p BB
454///
455/// Also sinks GEP instruction computing the store address
456///
Davide Italiano41315f72016-06-16 17:40:53 +0000457bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
458 StoreInst *S1) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000459 // Only one definition?
David Majnemer8cce3332016-05-26 05:43:12 +0000460 auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
461 auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000462 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
463 (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
464 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
465 DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
466 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
467 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
468 // Hoist the instruction.
469 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
470 // Intersect optional metadata.
471 S0->intersectOptionalDataWith(S1);
Adrian Prantlcbdfdb72015-08-20 22:00:30 +0000472 S0->dropUnknownNonDebugMetadata();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000473
474 // Create the new store to be inserted at the join point.
David Majnemer8cce3332016-05-26 05:43:12 +0000475 StoreInst *SNew = cast<StoreInst>(S0->clone());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000476 Instruction *ANew = A0->clone();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000477 SNew->insertBefore(&*InsertPt);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000478 ANew->insertBefore(SNew);
479
480 assert(S0->getParent() == A0->getParent());
481 assert(S1->getParent() == A1->getParent());
482
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000483 // New PHI operand? Use it.
Davide Italiano41315f72016-06-16 17:40:53 +0000484 if (PHINode *NewPN = getPHIOperand(BB, S0, S1))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000485 SNew->setOperand(0, NewPN);
Davide Italiano41315f72016-06-16 17:40:53 +0000486 removeInstruction(S0);
487 removeInstruction(S1);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000488 A0->replaceAllUsesWith(ANew);
Davide Italiano41315f72016-06-16 17:40:53 +0000489 removeInstruction(A0);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000490 A1->replaceAllUsesWith(ANew);
Davide Italiano41315f72016-06-16 17:40:53 +0000491 removeInstruction(A1);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000492 return true;
493 }
494 return false;
495}
496
497///
498/// \brief True when two stores are equivalent and can sink into the footer
499///
500/// Starting from a diamond tail block, iterate over the instructions in one
501/// predecessor block and try to match a store in the second predecessor.
502///
Davide Italiano41315f72016-06-16 17:40:53 +0000503bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000504
505 bool MergedStores = false;
506 assert(T && "Footer of a diamond cannot be empty");
507
508 pred_iterator PI = pred_begin(T), E = pred_end(T);
509 assert(PI != E);
510 BasicBlock *Pred0 = *PI;
511 ++PI;
512 BasicBlock *Pred1 = *PI;
513 ++PI;
514 // tail block of a diamond/hammock?
515 if (Pred0 == Pred1)
516 return false; // No.
517 if (PI != E)
518 return false; // No. More than 2 predecessors.
519
520 // #Instructions in Succ1 for Compile Time Control
521 int Size1 = Pred1->size();
522 int NStores = 0;
523
524 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
525 RBI != RBE;) {
526
527 Instruction *I = &*RBI;
528 ++RBI;
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000529
David Majnemer8cce3332016-05-26 05:43:12 +0000530 // Don't sink non-simple (atomic, volatile) stores.
531 auto *S0 = dyn_cast<StoreInst>(I);
532 if (!S0 || !S0->isSimple())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000533 continue;
534
535 ++NStores;
536 if (NStores * Size1 >= MagicCompileTimeControl)
537 break;
Davide Italiano41315f72016-06-16 17:40:53 +0000538 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
539 bool Res = sinkStore(T, S0, S1);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000540 MergedStores |= Res;
541 // Don't attempt to sink below stores that had to stick around
542 // But after removal of a store and some of its feeding
543 // instruction search again from the beginning since the iterator
544 // is likely stale at this point.
545 if (!Res)
546 break;
David Majnemer8cce3332016-05-26 05:43:12 +0000547 RBI = Pred0->rbegin();
548 RBE = Pred0->rend();
549 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000550 }
551 }
552 return MergedStores;
553}
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000554
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000555///
556/// \brief Run the transformation for each function
557///
Davide Italiano41315f72016-06-16 17:40:53 +0000558bool MergedLoadStoreMotion::runOnFunction(Function &F) {
559 if (skipFunction(F))
560 return false;
561
562 auto *MDWP = getAnalysisIfAvailable<MemoryDependenceWrapperPass>();
563 MD = MDWP ? &MDWP->getMemDep() : nullptr;
564 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
565
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000566 bool Changed = false;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000567 DEBUG(dbgs() << "Instruction Merger\n");
568
569 // Merge unconditional branches, allowing PRE to catch more
570 // optimization opportunities.
571 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000572 BasicBlock *BB = &*FI++;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000573
574 // Hoist equivalent loads and sink stores
575 // outside diamonds when possible
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000576 if (isDiamondHead(BB)) {
Davide Italiano41315f72016-06-16 17:40:53 +0000577 Changed |= mergeLoads(BB);
578 Changed |= mergeStores(getDiamondTail(BB));
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000579 }
580 }
581 return Changed;
582}