blob: 37a4bfda39b1043ffbb3de9105b523a240f159c9 [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
Davide Italiano89ab89d2016-06-14 00:49:23 +000075#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000076#include "llvm/ADT/Statistic.h"
77#include "llvm/Analysis/AliasAnalysis.h"
78#include "llvm/Analysis/CFG.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000079#include "llvm/Analysis/GlobalsModRef.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000080#include "llvm/Analysis/Loads.h"
81#include "llvm/Analysis/MemoryBuiltins.h"
82#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Eli Friedman9f8031c2016-06-12 02:11:20 +000083#include "llvm/Analysis/ValueTracking.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000084#include "llvm/IR/Metadata.h"
85#include "llvm/IR/PatternMatch.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000086#include "llvm/Support/Debug.h"
Benjamin Kramerb85d3752015-03-23 18:45:56 +000087#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000088#include "llvm/Transforms/Scalar.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000089#include "llvm/Transforms/Utils/BasicBlockUtils.h"
90#include "llvm/Transforms/Utils/SSAUpdater.h"
Hans Wennborg083ca9b2015-10-06 23:24:35 +000091
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000092using namespace llvm;
93
94#define DEBUG_TYPE "mldst-motion"
95
96//===----------------------------------------------------------------------===//
97// MergedLoadStoreMotion Pass
98//===----------------------------------------------------------------------===//
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000099
Davide Italiano44faf7f2016-06-13 22:27:30 +0000100// The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
101// where Size0 and Size1 are the #instructions on the two sides of
102// the diamond. The constant chosen here is arbitrary. Compiler Time
103// Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
104const int MagicCompileTimeControl = 250;
105
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000106///
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000107/// \brief Remove instruction from parent and update memory dependence analysis.
108///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000109static void removeInstruction(Instruction *Inst, MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000110 // Notify the memory dependence analysis.
111 if (MD) {
112 MD->removeInstruction(Inst);
David Majnemer8cce3332016-05-26 05:43:12 +0000113 if (auto *LI = dyn_cast<LoadInst>(Inst))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000114 MD->invalidateCachedPointerInfo(LI->getPointerOperand());
David Majnemer8cce3332016-05-26 05:43:12 +0000115 if (Inst->getType()->isPtrOrPtrVectorTy()) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000116 MD->invalidateCachedPointerInfo(Inst);
117 }
118 }
119 Inst->eraseFromParent();
120}
121
122///
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000123/// \brief True when BB is the head of a diamond (hammock)
124///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000125static bool isDiamondHead(BasicBlock *BB) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000126 if (!BB)
127 return false;
David Majnemer8cce3332016-05-26 05:43:12 +0000128 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
129 if (!BI || !BI->isConditional())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000130 return false;
131
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000132 BasicBlock *Succ0 = BI->getSuccessor(0);
133 BasicBlock *Succ1 = BI->getSuccessor(1);
134
David Majnemer8cce3332016-05-26 05:43:12 +0000135 if (!Succ0->getSinglePredecessor())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000136 return false;
David Majnemer8cce3332016-05-26 05:43:12 +0000137 if (!Succ1->getSinglePredecessor())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000138 return false;
139
David Majnemer8cce3332016-05-26 05:43:12 +0000140 BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
141 BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000142 // Ignore triangles.
David Majnemer8cce3332016-05-26 05:43:12 +0000143 if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000144 return false;
145 return true;
146}
147
148///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000149/// \brief Return tail block of a diamond.
150///
151static BasicBlock *getDiamondTail(BasicBlock *BB) {
152 assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
153 return BB->getTerminator()->getSuccessor(0)->getSingleSuccessor();
154}
155
156///
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000157/// \brief True when instruction is a hoist barrier for a load
158///
159/// Whenever an instruction could possibly modify the value
160/// being loaded or protect against the load from happening
161/// it is considered a hoist barrier.
162///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000163static bool isLoadHoistBarrierInRange(const Instruction &Start,
164 const Instruction &End, LoadInst *LI,
165 bool SafeToLoadUnconditionally,
166 AliasAnalysis *AA) {
David Majnemer47451252016-05-26 07:11:09 +0000167 if (!SafeToLoadUnconditionally)
168 for (const Instruction &Inst :
169 make_range(Start.getIterator(), End.getIterator()))
Eli Friedman9f8031c2016-06-12 02:11:20 +0000170 if (!isGuaranteedToTransferExecutionToSuccessor(&Inst))
David Majnemer47451252016-05-26 07:11:09 +0000171 return true;
Chandler Carruthac80dc72015-06-17 07:18:54 +0000172 MemoryLocation Loc = MemoryLocation::get(LI);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000173 return AA->canInstructionRangeModRef(Start, End, Loc, MRI_Mod);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000174}
175
176///
177/// \brief Decide if a load can be hoisted
178///
179/// When there is a load in \p BB to the same address as \p LI
180/// and it can be hoisted from \p BB, return that load.
181/// Otherwise return Null.
182///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000183static LoadInst *canHoistFromBlock(BasicBlock *BB1, LoadInst *Load0,
184 AliasAnalysis *AA) {
David Majnemer47451252016-05-26 07:11:09 +0000185 BasicBlock *BB0 = Load0->getParent();
186 BasicBlock *Head = BB0->getSinglePredecessor();
187 bool SafeToLoadUnconditionally = isSafeToLoadUnconditionally(
188 Load0->getPointerOperand(), Load0->getAlignment(),
189 Load0->getModule()->getDataLayout(),
190 /*ScanFrom=*/Head->getTerminator());
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000191 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000192 ++BBI) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000193 Instruction *Inst = &*BBI;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000194
195 // Only merge and hoist loads when their result in used only in BB
David Majnemer47451252016-05-26 07:11:09 +0000196 auto *Load1 = dyn_cast<LoadInst>(Inst);
197 if (!Load1 || Inst->isUsedOutsideOfBlock(BB1))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000198 continue;
199
Chandler Carruthac80dc72015-06-17 07:18:54 +0000200 MemoryLocation Loc0 = MemoryLocation::get(Load0);
201 MemoryLocation Loc1 = MemoryLocation::get(Load1);
Chad Rosier66a9d072016-06-14 12:47:18 +0000202 if (Load0->isSameOperationAs(Load1) && AA->isMustAlias(Loc0, Loc1) &&
David Majnemer47451252016-05-26 07:11:09 +0000203 !isLoadHoistBarrierInRange(BB1->front(), *Load1, Load1,
Davide Italiano44faf7f2016-06-13 22:27:30 +0000204 SafeToLoadUnconditionally, AA) &&
David Majnemer47451252016-05-26 07:11:09 +0000205 !isLoadHoistBarrierInRange(BB0->front(), *Load0, Load0,
Davide Italiano44faf7f2016-06-13 22:27:30 +0000206 SafeToLoadUnconditionally, AA)) {
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000207 return Load1;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000208 }
209 }
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000210 return nullptr;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000211}
212
213///
214/// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into
215/// \p BB
216///
217/// BB is the head of a diamond
218///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000219static void hoistInstruction(BasicBlock *BB, Instruction *HoistCand,
220 Instruction *ElseInst,
221 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000222 DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump();
223 dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n";
224 dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n");
225 // Hoist the instruction.
226 assert(HoistCand->getParent() != BB);
227
228 // Intersect optional metadata.
229 HoistCand->intersectOptionalDataWith(ElseInst);
Adrian Prantlcbdfdb72015-08-20 22:00:30 +0000230 HoistCand->dropUnknownNonDebugMetadata();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000231
232 // Prepend point for instruction insert
233 Instruction *HoistPt = BB->getTerminator();
234
235 // Merged instruction
236 Instruction *HoistedInst = HoistCand->clone();
237
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000238 // Hoist instruction.
239 HoistedInst->insertBefore(HoistPt);
240
241 HoistCand->replaceAllUsesWith(HoistedInst);
Davide Italiano44faf7f2016-06-13 22:27:30 +0000242 removeInstruction(HoistCand, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000243 // Replace the else block instruction.
244 ElseInst->replaceAllUsesWith(HoistedInst);
Davide Italiano44faf7f2016-06-13 22:27:30 +0000245 removeInstruction(ElseInst, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000246}
247
248///
249/// \brief Return true if no operand of \p I is defined in I's parent block
250///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000251static bool isSafeToHoist(Instruction *I) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000252 BasicBlock *Parent = I->getParent();
David Majnemer8cce3332016-05-26 05:43:12 +0000253 for (Use &U : I->operands())
254 if (auto *Instr = dyn_cast<Instruction>(&U))
255 if (Instr->getParent() == Parent)
256 return false;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000257 return true;
258}
259
260///
261/// \brief Merge two equivalent loads and GEPs and hoist into diamond head
262///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000263static bool hoistLoad(BasicBlock *BB, LoadInst *L0, LoadInst *L1,
264 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000265 // Only one definition?
David Majnemer8cce3332016-05-26 05:43:12 +0000266 auto *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
267 auto *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000268 if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) &&
269 A0->hasOneUse() && (A0->getParent() == L0->getParent()) &&
270 A1->hasOneUse() && (A1->getParent() == L1->getParent()) &&
271 isa<GetElementPtrInst>(A0)) {
272 DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump();
273 dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n";
274 dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n");
Davide Italiano44faf7f2016-06-13 22:27:30 +0000275 hoistInstruction(BB, A0, A1, MD);
276 hoistInstruction(BB, L0, L1, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000277 return true;
David Majnemer8cce3332016-05-26 05:43:12 +0000278 }
279 return false;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000280}
281
282///
283/// \brief Try to hoist two loads to same address into diamond header
284///
285/// Starting from a diamond head block, iterate over the instructions in one
286/// successor block and try to match a load in the second successor.
287///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000288static bool mergeLoads(BasicBlock *BB, AliasAnalysis *AA,
289 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000290 bool MergedLoads = false;
291 assert(isDiamondHead(BB));
David Majnemer8cce3332016-05-26 05:43:12 +0000292 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000293 BasicBlock *Succ0 = BI->getSuccessor(0);
294 BasicBlock *Succ1 = BI->getSuccessor(1);
295 // #Instructions in Succ1 for Compile Time Control
296 int Size1 = Succ1->size();
297 int NLoads = 0;
298 for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
299 BBI != BBE;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000300 Instruction *I = &*BBI;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000301 ++BBI;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000302
David Majnemer8cce3332016-05-26 05:43:12 +0000303 // Don't move non-simple (atomic, volatile) loads.
304 auto *L0 = dyn_cast<LoadInst>(I);
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000305 if (!L0 || !L0->isSimple() || L0->isUsedOutsideOfBlock(Succ0))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000306 continue;
307
308 ++NLoads;
309 if (NLoads * Size1 >= MagicCompileTimeControl)
310 break;
Davide Italiano44faf7f2016-06-13 22:27:30 +0000311 if (LoadInst *L1 = canHoistFromBlock(Succ1, L0, AA)) {
312 bool Res = hoistLoad(BB, L0, L1, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000313 MergedLoads |= Res;
314 // Don't attempt to hoist above loads that had not been hoisted.
315 if (!Res)
316 break;
317 }
318 }
319 return MergedLoads;
320}
321
322///
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000323/// \brief True when instruction is a sink barrier for a store
324/// located in Loc
325///
326/// Whenever an instruction could possibly read or modify the
327/// value being stored or protect against the store from
328/// happening it is considered a sink barrier.
329///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000330static bool isStoreSinkBarrierInRange(const Instruction &Start,
331 const Instruction &End,
332 MemoryLocation Loc, AliasAnalysis *AA) {
David Majnemer47451252016-05-26 07:11:09 +0000333 for (const Instruction &Inst :
334 make_range(Start.getIterator(), End.getIterator()))
335 if (Inst.mayThrow())
336 return true;
Chandler Carruth194f59c2015-07-22 23:15:57 +0000337 return AA->canInstructionRangeModRef(Start, End, Loc, MRI_ModRef);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000338}
339
340///
341/// \brief Check if \p BB contains a store to the same address as \p SI
342///
343/// \return The store in \p when it is safe to sink. Otherwise return Null.
344///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000345static StoreInst *canSinkFromBlock(BasicBlock *BB1, StoreInst *Store0,
346 AliasAnalysis *AA) {
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000347 DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
Elena Demikhovskyef035bb2015-02-17 13:10:05 +0000348 BasicBlock *BB0 = Store0->getParent();
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000349 for (BasicBlock::reverse_iterator RBI = BB1->rbegin(), RBE = BB1->rend();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000350 RBI != RBE; ++RBI) {
351 Instruction *Inst = &*RBI;
352
David Majnemer47451252016-05-26 07:11:09 +0000353 auto *Store1 = dyn_cast<StoreInst>(Inst);
354 if (!Store1)
355 continue;
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000356
Chandler Carruthac80dc72015-06-17 07:18:54 +0000357 MemoryLocation Loc0 = MemoryLocation::get(Store0);
358 MemoryLocation Loc1 = MemoryLocation::get(Store1);
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000359 if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
Davide Italiano44faf7f2016-06-13 22:27:30 +0000360 !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1,
361 AA) &&
362 !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0,
363 AA)) {
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000364 return Store1;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000365 }
366 }
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000367 return nullptr;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000368}
369
370///
371/// \brief Create a PHI node in BB for the operands of S0 and S1
372///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000373static PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1,
374 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000375 // Create a phi if the values mismatch.
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000376 Value *Opd1 = S0->getValueOperand();
377 Value *Opd2 = S1->getValueOperand();
David Majnemer8cce3332016-05-26 05:43:12 +0000378 if (Opd1 == Opd2)
379 return nullptr;
380
381 auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
382 &BB->front());
383 NewPN->addIncoming(Opd1, S0->getParent());
384 NewPN->addIncoming(Opd2, S1->getParent());
385 if (MD && NewPN->getType()->getScalarType()->isPointerTy())
386 MD->invalidateCachedPointerInfo(NewPN);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000387 return NewPN;
388}
389
390///
391/// \brief Merge two stores to same address and sink into \p BB
392///
393/// Also sinks GEP instruction computing the store address
394///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000395static bool sinkStore(BasicBlock *BB, StoreInst *S0, StoreInst *S1,
396 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000397 // Only one definition?
David Majnemer8cce3332016-05-26 05:43:12 +0000398 auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
399 auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000400 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
401 (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
402 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
403 DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
404 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
405 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
406 // Hoist the instruction.
407 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
408 // Intersect optional metadata.
409 S0->intersectOptionalDataWith(S1);
Adrian Prantlcbdfdb72015-08-20 22:00:30 +0000410 S0->dropUnknownNonDebugMetadata();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000411
412 // Create the new store to be inserted at the join point.
David Majnemer8cce3332016-05-26 05:43:12 +0000413 StoreInst *SNew = cast<StoreInst>(S0->clone());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000414 Instruction *ANew = A0->clone();
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000415 SNew->insertBefore(&*InsertPt);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000416 ANew->insertBefore(SNew);
417
418 assert(S0->getParent() == A0->getParent());
419 assert(S1->getParent() == A1->getParent());
420
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000421 // New PHI operand? Use it.
Davide Italiano44faf7f2016-06-13 22:27:30 +0000422 if (PHINode *NewPN = getPHIOperand(BB, S0, S1, MD))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000423 SNew->setOperand(0, NewPN);
Davide Italiano44faf7f2016-06-13 22:27:30 +0000424 removeInstruction(S0, MD);
425 removeInstruction(S1, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000426 A0->replaceAllUsesWith(ANew);
Davide Italiano44faf7f2016-06-13 22:27:30 +0000427 removeInstruction(A0, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000428 A1->replaceAllUsesWith(ANew);
Davide Italiano44faf7f2016-06-13 22:27:30 +0000429 removeInstruction(A1, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000430 return true;
431 }
432 return false;
433}
434
435///
436/// \brief True when two stores are equivalent and can sink into the footer
437///
438/// Starting from a diamond tail block, iterate over the instructions in one
439/// predecessor block and try to match a store in the second predecessor.
440///
Davide Italiano44faf7f2016-06-13 22:27:30 +0000441static bool mergeStores(BasicBlock *T, AliasAnalysis *AA,
442 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000443
444 bool MergedStores = false;
445 assert(T && "Footer of a diamond cannot be empty");
446
447 pred_iterator PI = pred_begin(T), E = pred_end(T);
448 assert(PI != E);
449 BasicBlock *Pred0 = *PI;
450 ++PI;
451 BasicBlock *Pred1 = *PI;
452 ++PI;
453 // tail block of a diamond/hammock?
454 if (Pred0 == Pred1)
455 return false; // No.
456 if (PI != E)
457 return false; // No. More than 2 predecessors.
458
459 // #Instructions in Succ1 for Compile Time Control
460 int Size1 = Pred1->size();
461 int NStores = 0;
462
463 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
464 RBI != RBE;) {
465
466 Instruction *I = &*RBI;
467 ++RBI;
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000468
David Majnemer8cce3332016-05-26 05:43:12 +0000469 // Don't sink non-simple (atomic, volatile) stores.
470 auto *S0 = dyn_cast<StoreInst>(I);
471 if (!S0 || !S0->isSimple())
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000472 continue;
473
474 ++NStores;
475 if (NStores * Size1 >= MagicCompileTimeControl)
476 break;
Davide Italiano44faf7f2016-06-13 22:27:30 +0000477 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0, AA)) {
478 bool Res = sinkStore(T, S0, S1, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000479 MergedStores |= Res;
480 // Don't attempt to sink below stores that had to stick around
481 // But after removal of a store and some of its feeding
482 // instruction search again from the beginning since the iterator
483 // is likely stale at this point.
484 if (!Res)
485 break;
David Majnemer8cce3332016-05-26 05:43:12 +0000486 RBI = Pred0->rbegin();
487 RBE = Pred0->rend();
488 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000489 }
490 }
491 return MergedStores;
492}
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000493
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000494///
495/// \brief Run the transformation for each function
496///
Davide Italiano89ab89d2016-06-14 00:49:23 +0000497static bool runMergedLoadStoreMotion(Function &F, AliasAnalysis *AA,
498 MemoryDependenceResults *MD) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000499 bool Changed = false;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000500 DEBUG(dbgs() << "Instruction Merger\n");
501
502 // Merge unconditional branches, allowing PRE to catch more
503 // optimization opportunities.
504 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000505 BasicBlock *BB = &*FI++;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000506
507 // Hoist equivalent loads and sink stores
508 // outside diamonds when possible
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000509 if (isDiamondHead(BB)) {
Davide Italiano44faf7f2016-06-13 22:27:30 +0000510 Changed |= mergeLoads(BB, AA, MD);
511 Changed |= mergeStores(getDiamondTail(BB), AA, MD);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000512 }
513 }
514 return Changed;
515}
Davide Italiano89ab89d2016-06-14 00:49:23 +0000516
517PreservedAnalyses
518MergedLoadStoreMotionPass::run(Function &F, AnalysisManager<Function> &AM) {
519 auto &AA = AM.getResult<AAManager>(F);
520 auto *MD = AM.getCachedResult<MemoryDependenceAnalysis>(F);
521 if (!runMergedLoadStoreMotion(F, &AA, MD))
522 return PreservedAnalyses::all();
Davide Italiano3ab1b582016-06-14 01:23:31 +0000523 // FIXME: This pass should also 'preserve the CFG'.
524 // The new pass manager has currently no way to do it.
525 PreservedAnalyses PA;
526 PA.preserve<GlobalsAA>();
527 PA.preserve<MemoryDependenceAnalysis>();
528 return PA;
Davide Italiano89ab89d2016-06-14 00:49:23 +0000529}
530
531namespace {
532class MergedLoadStoreMotionLegacyPass : public FunctionPass {
533 AliasAnalysis *AA;
534 MemoryDependenceResults *MD;
535
536public:
537 static char ID; // Pass identification, replacement for typeid
538 MergedLoadStoreMotionLegacyPass() : FunctionPass(ID), MD(nullptr) {
539 initializeMergedLoadStoreMotionLegacyPassPass(
540 *PassRegistry::getPassRegistry());
541 }
542
543 bool runOnFunction(Function &F) override {
544 if (skipFunction(F))
545 return false;
546
547 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
548 auto *MDWP = getAnalysisIfAvailable<MemoryDependenceWrapperPass>();
549 MD = MDWP ? &MDWP->getMemDep() : nullptr;
550 return runMergedLoadStoreMotion(F, AA, MD);
551 }
552
553private:
554 // This transformation requires dominator postdominator info
555 void getAnalysisUsage(AnalysisUsage &AU) const override {
556 AU.setPreservesCFG();
557 AU.addRequired<AAResultsWrapperPass>();
558 AU.addPreserved<GlobalsAAWrapperPass>();
559 AU.addPreserved<MemoryDependenceWrapperPass>();
560 }
561};
562
563char MergedLoadStoreMotionLegacyPass::ID = 0;
564} // anonymous namespace
565
566///
567/// \brief createMergedLoadStoreMotionPass - The public interface to this file.
568///
569FunctionPass *llvm::createMergedLoadStoreMotionPass() {
570 return new MergedLoadStoreMotionLegacyPass();
571}
572
573INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion",
574 "MergedLoadStoreMotion", false, false)
575INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
576INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
577INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion",
578 "MergedLoadStoreMotion", false, false)