blob: 557281583b8372d580ffc8d8e9c5186c9ee57ad8 [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
75#include "llvm/Transforms/Scalar.h"
76#include "llvm/ADT/SetVector.h"
77#include "llvm/ADT/SmallPtrSet.h"
78#include "llvm/ADT/Statistic.h"
79#include "llvm/Analysis/AliasAnalysis.h"
80#include "llvm/Analysis/CFG.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000081#include "llvm/Analysis/GlobalsModRef.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000082#include "llvm/Analysis/Loads.h"
83#include "llvm/Analysis/MemoryBuiltins.h"
84#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Benjamin Kramerb85d3752015-03-23 18:45:56 +000085#include "llvm/Analysis/TargetLibraryInfo.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000086#include "llvm/IR/Metadata.h"
87#include "llvm/IR/PatternMatch.h"
88#include "llvm/Support/Allocator.h"
89#include "llvm/Support/CommandLine.h"
90#include "llvm/Support/Debug.h"
Benjamin Kramerb85d3752015-03-23 18:45:56 +000091#include "llvm/Support/raw_ostream.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000092#include "llvm/Transforms/Utils/BasicBlockUtils.h"
93#include "llvm/Transforms/Utils/SSAUpdater.h"
94#include <vector>
95using namespace llvm;
96
97#define DEBUG_TYPE "mldst-motion"
98
99//===----------------------------------------------------------------------===//
100// MergedLoadStoreMotion Pass
101//===----------------------------------------------------------------------===//
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000102
103namespace {
104class MergedLoadStoreMotion : public FunctionPass {
105 AliasAnalysis *AA;
106 MemoryDependenceAnalysis *MD;
107
108public:
109 static char ID; // Pass identification, replacement for typeid
NAKAMURA Takumiab184fb2014-07-19 03:29:25 +0000110 explicit MergedLoadStoreMotion(void)
111 : FunctionPass(ID), MD(nullptr), MagicCompileTimeControl(250) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000112 initializeMergedLoadStoreMotionPass(*PassRegistry::getPassRegistry());
113 }
114
115 bool runOnFunction(Function &F) override;
116
117private:
118 // This transformation requires dominator postdominator info
119 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000120 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000121 AU.addRequired<AAResultsWrapperPass>();
122 AU.addPreserved<GlobalsAAWrapperPass>();
Daniel Berlinb3015332015-05-22 00:13:05 +0000123 AU.addPreserved<MemoryDependenceAnalysis>();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000124 }
125
126 // Helper routines
127
128 ///
129 /// \brief Remove instruction from parent and update memory dependence
130 /// analysis.
131 ///
132 void removeInstruction(Instruction *Inst);
133 BasicBlock *getDiamondTail(BasicBlock *BB);
134 bool isDiamondHead(BasicBlock *BB);
135 // Routines for hoisting loads
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000136 bool isLoadHoistBarrierInRange(const Instruction& Start,
137 const Instruction& End,
138 LoadInst* LI);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000139 LoadInst *canHoistFromBlock(BasicBlock *BB, LoadInst *LI);
140 void hoistInstruction(BasicBlock *BB, Instruction *HoistCand,
141 Instruction *ElseInst);
142 bool isSafeToHoist(Instruction *I) const;
143 bool hoistLoad(BasicBlock *BB, LoadInst *HoistCand, LoadInst *ElseInst);
144 bool mergeLoads(BasicBlock *BB);
145 // Routines for sinking stores
146 StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
147 PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
Chandler Carruthac80dc72015-06-17 07:18:54 +0000148 bool isStoreSinkBarrierInRange(const Instruction &Start,
149 const Instruction &End, MemoryLocation Loc);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000150 bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
151 bool mergeStores(BasicBlock *BB);
152 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
153 // where Size0 and Size1 are the #instructions on the two sides of
154 // the diamond. The constant chosen here is arbitrary. Compiler Time
155 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
NAKAMURA Takumiab184fb2014-07-19 03:29:25 +0000156 const int MagicCompileTimeControl;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000157};
158
159char MergedLoadStoreMotion::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000160}
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000161
162///
163/// \brief createMergedLoadStoreMotionPass - The public interface to this file.
164///
165FunctionPass *llvm::createMergedLoadStoreMotionPass() {
166 return new MergedLoadStoreMotion();
167}
168
169INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion",
170 "MergedLoadStoreMotion", false, false)
171INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000172INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000173INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
174INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000175INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion",
176 "MergedLoadStoreMotion", false, false)
177
178///
179/// \brief Remove instruction from parent and update memory dependence analysis.
180///
181void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
182 // Notify the memory dependence analysis.
183 if (MD) {
184 MD->removeInstruction(Inst);
185 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
186 MD->invalidateCachedPointerInfo(LI->getPointerOperand());
187 if (Inst->getType()->getScalarType()->isPointerTy()) {
188 MD->invalidateCachedPointerInfo(Inst);
189 }
190 }
191 Inst->eraseFromParent();
192}
193
194///
195/// \brief Return tail block of a diamond.
196///
197BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
198 assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
199 BranchInst *BI = (BranchInst *)(BB->getTerminator());
200 BasicBlock *Succ0 = BI->getSuccessor(0);
201 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
202 return Tail;
203}
204
205///
206/// \brief True when BB is the head of a diamond (hammock)
207///
208bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
209 if (!BB)
210 return false;
211 if (!isa<BranchInst>(BB->getTerminator()))
212 return false;
213 if (BB->getTerminator()->getNumSuccessors() != 2)
214 return false;
215
216 BranchInst *BI = (BranchInst *)(BB->getTerminator());
217 BasicBlock *Succ0 = BI->getSuccessor(0);
218 BasicBlock *Succ1 = BI->getSuccessor(1);
219
220 if (!Succ0->getSinglePredecessor() ||
221 Succ0->getTerminator()->getNumSuccessors() != 1)
222 return false;
223 if (!Succ1->getSinglePredecessor() ||
224 Succ1->getTerminator()->getNumSuccessors() != 1)
225 return false;
226
227 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
228 // Ignore triangles.
229 if (Succ1->getTerminator()->getSuccessor(0) != Tail)
230 return false;
231 return true;
232}
233
234///
235/// \brief True when instruction is a hoist barrier for a load
236///
237/// Whenever an instruction could possibly modify the value
238/// being loaded or protect against the load from happening
239/// it is considered a hoist barrier.
240///
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000241
242bool MergedLoadStoreMotion::isLoadHoistBarrierInRange(const Instruction& Start,
243 const Instruction& End,
244 LoadInst* LI) {
Chandler Carruthac80dc72015-06-17 07:18:54 +0000245 MemoryLocation Loc = MemoryLocation::get(LI);
Chandler Carruth194f59c2015-07-22 23:15:57 +0000246 return AA->canInstructionRangeModRef(Start, End, Loc, MRI_Mod);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000247}
248
249///
250/// \brief Decide if a load can be hoisted
251///
252/// When there is a load in \p BB to the same address as \p LI
253/// and it can be hoisted from \p BB, return that load.
254/// Otherwise return Null.
255///
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000256LoadInst *MergedLoadStoreMotion::canHoistFromBlock(BasicBlock *BB1,
257 LoadInst *Load0) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000258
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000259 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000260 ++BBI) {
261 Instruction *Inst = BBI;
262
263 // Only merge and hoist loads when their result in used only in BB
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000264 if (!isa<LoadInst>(Inst) || Inst->isUsedOutsideOfBlock(BB1))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000265 continue;
266
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000267 LoadInst *Load1 = dyn_cast<LoadInst>(Inst);
268 BasicBlock *BB0 = Load0->getParent();
269
Chandler Carruthac80dc72015-06-17 07:18:54 +0000270 MemoryLocation Loc0 = MemoryLocation::get(Load0);
271 MemoryLocation Loc1 = MemoryLocation::get(Load1);
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000272 if (AA->isMustAlias(Loc0, Loc1) && Load0->isSameOperationAs(Load1) &&
273 !isLoadHoistBarrierInRange(BB1->front(), *Load1, Load1) &&
274 !isLoadHoistBarrierInRange(BB0->front(), *Load0, Load0)) {
275 return Load1;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000276 }
277 }
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000278 return nullptr;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000279}
280
281///
282/// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into
283/// \p BB
284///
285/// BB is the head of a diamond
286///
287void MergedLoadStoreMotion::hoistInstruction(BasicBlock *BB,
288 Instruction *HoistCand,
289 Instruction *ElseInst) {
290 DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump();
291 dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n";
292 dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n");
293 // Hoist the instruction.
294 assert(HoistCand->getParent() != BB);
295
296 // Intersect optional metadata.
297 HoistCand->intersectOptionalDataWith(ElseInst);
Adrian Prantlcbdfdb72015-08-20 22:00:30 +0000298 HoistCand->dropUnknownNonDebugMetadata();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000299
300 // Prepend point for instruction insert
301 Instruction *HoistPt = BB->getTerminator();
302
303 // Merged instruction
304 Instruction *HoistedInst = HoistCand->clone();
305
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000306 // Hoist instruction.
307 HoistedInst->insertBefore(HoistPt);
308
309 HoistCand->replaceAllUsesWith(HoistedInst);
310 removeInstruction(HoistCand);
311 // Replace the else block instruction.
312 ElseInst->replaceAllUsesWith(HoistedInst);
313 removeInstruction(ElseInst);
314}
315
316///
317/// \brief Return true if no operand of \p I is defined in I's parent block
318///
319bool MergedLoadStoreMotion::isSafeToHoist(Instruction *I) const {
320 BasicBlock *Parent = I->getParent();
321 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
322 Instruction *Instr = dyn_cast<Instruction>(I->getOperand(i));
323 if (Instr && Instr->getParent() == Parent)
324 return false;
325 }
326 return true;
327}
328
329///
330/// \brief Merge two equivalent loads and GEPs and hoist into diamond head
331///
332bool MergedLoadStoreMotion::hoistLoad(BasicBlock *BB, LoadInst *L0,
333 LoadInst *L1) {
334 // Only one definition?
335 Instruction *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
336 Instruction *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
337 if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) &&
338 A0->hasOneUse() && (A0->getParent() == L0->getParent()) &&
339 A1->hasOneUse() && (A1->getParent() == L1->getParent()) &&
340 isa<GetElementPtrInst>(A0)) {
341 DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump();
342 dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n";
343 dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n");
344 hoistInstruction(BB, A0, A1);
345 hoistInstruction(BB, L0, L1);
346 return true;
347 } else
348 return false;
349}
350
351///
352/// \brief Try to hoist two loads to same address into diamond header
353///
354/// Starting from a diamond head block, iterate over the instructions in one
355/// successor block and try to match a load in the second successor.
356///
357bool MergedLoadStoreMotion::mergeLoads(BasicBlock *BB) {
358 bool MergedLoads = false;
359 assert(isDiamondHead(BB));
360 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
361 BasicBlock *Succ0 = BI->getSuccessor(0);
362 BasicBlock *Succ1 = BI->getSuccessor(1);
363 // #Instructions in Succ1 for Compile Time Control
364 int Size1 = Succ1->size();
365 int NLoads = 0;
366 for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
367 BBI != BBE;) {
368
369 Instruction *I = BBI;
370 ++BBI;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000371
372 // Only move non-simple (atomic, volatile) loads.
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000373 LoadInst *L0 = dyn_cast<LoadInst>(I);
374 if (!L0 || !L0->isSimple() || L0->isUsedOutsideOfBlock(Succ0))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000375 continue;
376
377 ++NLoads;
378 if (NLoads * Size1 >= MagicCompileTimeControl)
379 break;
380 if (LoadInst *L1 = canHoistFromBlock(Succ1, L0)) {
381 bool Res = hoistLoad(BB, L0, L1);
382 MergedLoads |= Res;
383 // Don't attempt to hoist above loads that had not been hoisted.
384 if (!Res)
385 break;
386 }
387 }
388 return MergedLoads;
389}
390
391///
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000392/// \brief True when instruction is a sink barrier for a store
393/// located in Loc
394///
395/// Whenever an instruction could possibly read or modify the
396/// value being stored or protect against the store from
397/// happening it is considered a sink barrier.
398///
399
Chandler Carruthac80dc72015-06-17 07:18:54 +0000400bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
401 const Instruction &End,
402 MemoryLocation Loc) {
Chandler Carruth194f59c2015-07-22 23:15:57 +0000403 return AA->canInstructionRangeModRef(Start, End, Loc, MRI_ModRef);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000404}
405
406///
407/// \brief Check if \p BB contains a store to the same address as \p SI
408///
409/// \return The store in \p when it is safe to sink. Otherwise return Null.
410///
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000411StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
412 StoreInst *Store0) {
413 DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
Elena Demikhovskyef035bb2015-02-17 13:10:05 +0000414 BasicBlock *BB0 = Store0->getParent();
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000415 for (BasicBlock::reverse_iterator RBI = BB1->rbegin(), RBE = BB1->rend();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000416 RBI != RBE; ++RBI) {
417 Instruction *Inst = &*RBI;
418
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000419 if (!isa<StoreInst>(Inst))
420 continue;
421
422 StoreInst *Store1 = cast<StoreInst>(Inst);
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000423
Chandler Carruthac80dc72015-06-17 07:18:54 +0000424 MemoryLocation Loc0 = MemoryLocation::get(Store0);
425 MemoryLocation Loc1 = MemoryLocation::get(Store1);
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000426 if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
Elena Demikhovskyef035bb2015-02-17 13:10:05 +0000427 !isStoreSinkBarrierInRange(*(std::next(BasicBlock::iterator(Store1))),
428 BB1->back(), Loc1) &&
429 !isStoreSinkBarrierInRange(*(std::next(BasicBlock::iterator(Store0))),
430 BB0->back(), Loc0)) {
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000431 return Store1;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000432 }
433 }
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000434 return nullptr;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000435}
436
437///
438/// \brief Create a PHI node in BB for the operands of S0 and S1
439///
440PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
441 StoreInst *S1) {
442 // Create a phi if the values mismatch.
443 PHINode *NewPN = 0;
444 Value *Opd1 = S0->getValueOperand();
445 Value *Opd2 = S1->getValueOperand();
446 if (Opd1 != Opd2) {
447 NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
448 BB->begin());
449 NewPN->addIncoming(Opd1, S0->getParent());
450 NewPN->addIncoming(Opd2, S1->getParent());
Chandler Carruth9f2bf1af2015-07-18 03:26:46 +0000451 if (MD && NewPN->getType()->getScalarType()->isPointerTy())
452 MD->invalidateCachedPointerInfo(NewPN);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000453 }
454 return NewPN;
455}
456
457///
458/// \brief Merge two stores to same address and sink into \p BB
459///
460/// Also sinks GEP instruction computing the store address
461///
462bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
463 StoreInst *S1) {
464 // Only one definition?
465 Instruction *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
466 Instruction *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
467 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
468 (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
469 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
470 DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
471 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
472 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
473 // Hoist the instruction.
474 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
475 // Intersect optional metadata.
476 S0->intersectOptionalDataWith(S1);
Adrian Prantlcbdfdb72015-08-20 22:00:30 +0000477 S0->dropUnknownNonDebugMetadata();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000478
479 // Create the new store to be inserted at the join point.
480 StoreInst *SNew = (StoreInst *)(S0->clone());
481 Instruction *ANew = A0->clone();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000482 SNew->insertBefore(InsertPt);
483 ANew->insertBefore(SNew);
484
485 assert(S0->getParent() == A0->getParent());
486 assert(S1->getParent() == A1->getParent());
487
488 PHINode *NewPN = getPHIOperand(BB, S0, S1);
489 // New PHI operand? Use it.
490 if (NewPN)
491 SNew->setOperand(0, NewPN);
492 removeInstruction(S0);
493 removeInstruction(S1);
494 A0->replaceAllUsesWith(ANew);
495 removeInstruction(A0);
496 A1->replaceAllUsesWith(ANew);
497 removeInstruction(A1);
498 return true;
499 }
500 return false;
501}
502
503///
504/// \brief True when two stores are equivalent and can sink into the footer
505///
506/// Starting from a diamond tail block, iterate over the instructions in one
507/// predecessor block and try to match a store in the second predecessor.
508///
509bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
510
511 bool MergedStores = false;
512 assert(T && "Footer of a diamond cannot be empty");
513
514 pred_iterator PI = pred_begin(T), E = pred_end(T);
515 assert(PI != E);
516 BasicBlock *Pred0 = *PI;
517 ++PI;
518 BasicBlock *Pred1 = *PI;
519 ++PI;
520 // tail block of a diamond/hammock?
521 if (Pred0 == Pred1)
522 return false; // No.
523 if (PI != E)
524 return false; // No. More than 2 predecessors.
525
526 // #Instructions in Succ1 for Compile Time Control
527 int Size1 = Pred1->size();
528 int NStores = 0;
529
530 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
531 RBI != RBE;) {
532
533 Instruction *I = &*RBI;
534 ++RBI;
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000535
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000536 // Sink move non-simple (atomic, volatile) stores
537 if (!isa<StoreInst>(I))
538 continue;
539 StoreInst *S0 = (StoreInst *)I;
540 if (!S0->isSimple())
541 continue;
542
543 ++NStores;
544 if (NStores * Size1 >= MagicCompileTimeControl)
545 break;
546 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
547 bool Res = sinkStore(T, S0, S1);
548 MergedStores |= Res;
549 // Don't attempt to sink below stores that had to stick around
550 // But after removal of a store and some of its feeding
551 // instruction search again from the beginning since the iterator
552 // is likely stale at this point.
553 if (!Res)
554 break;
555 else {
556 RBI = Pred0->rbegin();
557 RBE = Pred0->rend();
558 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
559 }
560 }
561 }
562 return MergedStores;
563}
564///
565/// \brief Run the transformation for each function
566///
567bool MergedLoadStoreMotion::runOnFunction(Function &F) {
Daniel Berlinb3015332015-05-22 00:13:05 +0000568 MD = getAnalysisIfAvailable<MemoryDependenceAnalysis>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000569 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000570
571 bool Changed = false;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000572 DEBUG(dbgs() << "Instruction Merger\n");
573
574 // Merge unconditional branches, allowing PRE to catch more
575 // optimization opportunities.
576 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
577 BasicBlock *BB = FI++;
578
579 // Hoist equivalent loads and sink stores
580 // outside diamonds when possible
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000581 if (isDiamondHead(BB)) {
582 Changed |= mergeLoads(BB);
583 Changed |= mergeStores(getDiamondTail(BB));
584 }
585 }
586 return Changed;
587}