blob: 243db8d70ca28a6b0e321c4d5476a6089aa33e46 [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"
81#include "llvm/Analysis/Loads.h"
82#include "llvm/Analysis/MemoryBuiltins.h"
83#include "llvm/Analysis/MemoryDependenceAnalysis.h"
Benjamin Kramerb85d3752015-03-23 18:45:56 +000084#include "llvm/Analysis/TargetLibraryInfo.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000085#include "llvm/IR/Metadata.h"
86#include "llvm/IR/PatternMatch.h"
87#include "llvm/Support/Allocator.h"
88#include "llvm/Support/CommandLine.h"
89#include "llvm/Support/Debug.h"
Benjamin Kramerb85d3752015-03-23 18:45:56 +000090#include "llvm/Support/raw_ostream.h"
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +000091#include "llvm/Transforms/Utils/BasicBlockUtils.h"
92#include "llvm/Transforms/Utils/SSAUpdater.h"
93#include <vector>
94using namespace llvm;
95
96#define DEBUG_TYPE "mldst-motion"
97
98//===----------------------------------------------------------------------===//
99// MergedLoadStoreMotion Pass
100//===----------------------------------------------------------------------===//
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000101
102namespace {
103class MergedLoadStoreMotion : public FunctionPass {
104 AliasAnalysis *AA;
105 MemoryDependenceAnalysis *MD;
106
107public:
108 static char ID; // Pass identification, replacement for typeid
NAKAMURA Takumiab184fb2014-07-19 03:29:25 +0000109 explicit MergedLoadStoreMotion(void)
110 : FunctionPass(ID), MD(nullptr), MagicCompileTimeControl(250) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000111 initializeMergedLoadStoreMotionPass(*PassRegistry::getPassRegistry());
112 }
113
114 bool runOnFunction(Function &F) override;
115
116private:
117 // This transformation requires dominator postdominator info
118 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000119 AU.addRequired<TargetLibraryInfoWrapperPass>();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000120 AU.addRequired<AliasAnalysis>();
Daniel Berlinb3015332015-05-22 00:13:05 +0000121 AU.addPreserved<MemoryDependenceAnalysis>();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000122 AU.addPreserved<AliasAnalysis>();
123 }
124
125 // Helper routines
126
127 ///
128 /// \brief Remove instruction from parent and update memory dependence
129 /// analysis.
130 ///
131 void removeInstruction(Instruction *Inst);
132 BasicBlock *getDiamondTail(BasicBlock *BB);
133 bool isDiamondHead(BasicBlock *BB);
134 // Routines for hoisting loads
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000135 bool isLoadHoistBarrierInRange(const Instruction& Start,
136 const Instruction& End,
137 LoadInst* LI);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000138 LoadInst *canHoistFromBlock(BasicBlock *BB, LoadInst *LI);
139 void hoistInstruction(BasicBlock *BB, Instruction *HoistCand,
140 Instruction *ElseInst);
141 bool isSafeToHoist(Instruction *I) const;
142 bool hoistLoad(BasicBlock *BB, LoadInst *HoistCand, LoadInst *ElseInst);
143 bool mergeLoads(BasicBlock *BB);
144 // Routines for sinking stores
145 StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
146 PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
Chandler Carruthac80dc72015-06-17 07:18:54 +0000147 bool isStoreSinkBarrierInRange(const Instruction &Start,
148 const Instruction &End, MemoryLocation Loc);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000149 bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
150 bool mergeStores(BasicBlock *BB);
151 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
152 // where Size0 and Size1 are the #instructions on the two sides of
153 // the diamond. The constant chosen here is arbitrary. Compiler Time
154 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
NAKAMURA Takumiab184fb2014-07-19 03:29:25 +0000155 const int MagicCompileTimeControl;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000156};
157
158char MergedLoadStoreMotion::ID = 0;
159}
160
161///
162/// \brief createMergedLoadStoreMotionPass - The public interface to this file.
163///
164FunctionPass *llvm::createMergedLoadStoreMotionPass() {
165 return new MergedLoadStoreMotion();
166}
167
168INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion",
169 "MergedLoadStoreMotion", false, false)
170INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000171INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000172INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
173INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion",
174 "MergedLoadStoreMotion", false, false)
175
176///
177/// \brief Remove instruction from parent and update memory dependence analysis.
178///
179void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
180 // Notify the memory dependence analysis.
181 if (MD) {
182 MD->removeInstruction(Inst);
183 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
184 MD->invalidateCachedPointerInfo(LI->getPointerOperand());
185 if (Inst->getType()->getScalarType()->isPointerTy()) {
186 MD->invalidateCachedPointerInfo(Inst);
187 }
188 }
189 Inst->eraseFromParent();
190}
191
192///
193/// \brief Return tail block of a diamond.
194///
195BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
196 assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
197 BranchInst *BI = (BranchInst *)(BB->getTerminator());
198 BasicBlock *Succ0 = BI->getSuccessor(0);
199 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
200 return Tail;
201}
202
203///
204/// \brief True when BB is the head of a diamond (hammock)
205///
206bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
207 if (!BB)
208 return false;
209 if (!isa<BranchInst>(BB->getTerminator()))
210 return false;
211 if (BB->getTerminator()->getNumSuccessors() != 2)
212 return false;
213
214 BranchInst *BI = (BranchInst *)(BB->getTerminator());
215 BasicBlock *Succ0 = BI->getSuccessor(0);
216 BasicBlock *Succ1 = BI->getSuccessor(1);
217
218 if (!Succ0->getSinglePredecessor() ||
219 Succ0->getTerminator()->getNumSuccessors() != 1)
220 return false;
221 if (!Succ1->getSinglePredecessor() ||
222 Succ1->getTerminator()->getNumSuccessors() != 1)
223 return false;
224
225 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
226 // Ignore triangles.
227 if (Succ1->getTerminator()->getSuccessor(0) != Tail)
228 return false;
229 return true;
230}
231
232///
233/// \brief True when instruction is a hoist barrier for a load
234///
235/// Whenever an instruction could possibly modify the value
236/// being loaded or protect against the load from happening
237/// it is considered a hoist barrier.
238///
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000239
240bool MergedLoadStoreMotion::isLoadHoistBarrierInRange(const Instruction& Start,
241 const Instruction& End,
242 LoadInst* LI) {
Chandler Carruthac80dc72015-06-17 07:18:54 +0000243 MemoryLocation Loc = MemoryLocation::get(LI);
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000244 return AA->canInstructionRangeModRef(Start, End, Loc, AliasAnalysis::Mod);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000245}
246
247///
248/// \brief Decide if a load can be hoisted
249///
250/// When there is a load in \p BB to the same address as \p LI
251/// and it can be hoisted from \p BB, return that load.
252/// Otherwise return Null.
253///
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000254LoadInst *MergedLoadStoreMotion::canHoistFromBlock(BasicBlock *BB1,
255 LoadInst *Load0) {
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000256
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000257 for (BasicBlock::iterator BBI = BB1->begin(), BBE = BB1->end(); BBI != BBE;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000258 ++BBI) {
259 Instruction *Inst = BBI;
260
261 // Only merge and hoist loads when their result in used only in BB
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000262 if (!isa<LoadInst>(Inst) || Inst->isUsedOutsideOfBlock(BB1))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000263 continue;
264
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000265 LoadInst *Load1 = dyn_cast<LoadInst>(Inst);
266 BasicBlock *BB0 = Load0->getParent();
267
Chandler Carruthac80dc72015-06-17 07:18:54 +0000268 MemoryLocation Loc0 = MemoryLocation::get(Load0);
269 MemoryLocation Loc1 = MemoryLocation::get(Load1);
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000270 if (AA->isMustAlias(Loc0, Loc1) && Load0->isSameOperationAs(Load1) &&
271 !isLoadHoistBarrierInRange(BB1->front(), *Load1, Load1) &&
272 !isLoadHoistBarrierInRange(BB0->front(), *Load0, Load0)) {
273 return Load1;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000274 }
275 }
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000276 return nullptr;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000277}
278
279///
280/// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into
281/// \p BB
282///
283/// BB is the head of a diamond
284///
285void MergedLoadStoreMotion::hoistInstruction(BasicBlock *BB,
286 Instruction *HoistCand,
287 Instruction *ElseInst) {
288 DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump();
289 dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n";
290 dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n");
291 // Hoist the instruction.
292 assert(HoistCand->getParent() != BB);
293
294 // Intersect optional metadata.
295 HoistCand->intersectOptionalDataWith(ElseInst);
296 HoistCand->dropUnknownMetadata();
297
298 // Prepend point for instruction insert
299 Instruction *HoistPt = BB->getTerminator();
300
301 // Merged instruction
302 Instruction *HoistedInst = HoistCand->clone();
303
304 // Notify AA of the new value.
305 if (isa<LoadInst>(HoistCand))
306 AA->copyValue(HoistCand, HoistedInst);
307
308 // Hoist instruction.
309 HoistedInst->insertBefore(HoistPt);
310
311 HoistCand->replaceAllUsesWith(HoistedInst);
312 removeInstruction(HoistCand);
313 // Replace the else block instruction.
314 ElseInst->replaceAllUsesWith(HoistedInst);
315 removeInstruction(ElseInst);
316}
317
318///
319/// \brief Return true if no operand of \p I is defined in I's parent block
320///
321bool MergedLoadStoreMotion::isSafeToHoist(Instruction *I) const {
322 BasicBlock *Parent = I->getParent();
323 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
324 Instruction *Instr = dyn_cast<Instruction>(I->getOperand(i));
325 if (Instr && Instr->getParent() == Parent)
326 return false;
327 }
328 return true;
329}
330
331///
332/// \brief Merge two equivalent loads and GEPs and hoist into diamond head
333///
334bool MergedLoadStoreMotion::hoistLoad(BasicBlock *BB, LoadInst *L0,
335 LoadInst *L1) {
336 // Only one definition?
337 Instruction *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
338 Instruction *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
339 if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) &&
340 A0->hasOneUse() && (A0->getParent() == L0->getParent()) &&
341 A1->hasOneUse() && (A1->getParent() == L1->getParent()) &&
342 isa<GetElementPtrInst>(A0)) {
343 DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump();
344 dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n";
345 dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n");
346 hoistInstruction(BB, A0, A1);
347 hoistInstruction(BB, L0, L1);
348 return true;
349 } else
350 return false;
351}
352
353///
354/// \brief Try to hoist two loads to same address into diamond header
355///
356/// Starting from a diamond head block, iterate over the instructions in one
357/// successor block and try to match a load in the second successor.
358///
359bool MergedLoadStoreMotion::mergeLoads(BasicBlock *BB) {
360 bool MergedLoads = false;
361 assert(isDiamondHead(BB));
362 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
363 BasicBlock *Succ0 = BI->getSuccessor(0);
364 BasicBlock *Succ1 = BI->getSuccessor(1);
365 // #Instructions in Succ1 for Compile Time Control
366 int Size1 = Succ1->size();
367 int NLoads = 0;
368 for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
369 BBI != BBE;) {
370
371 Instruction *I = BBI;
372 ++BBI;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000373
374 // Only move non-simple (atomic, volatile) loads.
Elena Demikhovsky27152ae2014-11-02 08:03:05 +0000375 LoadInst *L0 = dyn_cast<LoadInst>(I);
376 if (!L0 || !L0->isSimple() || L0->isUsedOutsideOfBlock(Succ0))
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000377 continue;
378
379 ++NLoads;
380 if (NLoads * Size1 >= MagicCompileTimeControl)
381 break;
382 if (LoadInst *L1 = canHoistFromBlock(Succ1, L0)) {
383 bool Res = hoistLoad(BB, L0, L1);
384 MergedLoads |= Res;
385 // Don't attempt to hoist above loads that had not been hoisted.
386 if (!Res)
387 break;
388 }
389 }
390 return MergedLoads;
391}
392
393///
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000394/// \brief True when instruction is a sink barrier for a store
395/// located in Loc
396///
397/// Whenever an instruction could possibly read or modify the
398/// value being stored or protect against the store from
399/// happening it is considered a sink barrier.
400///
401
Chandler Carruthac80dc72015-06-17 07:18:54 +0000402bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
403 const Instruction &End,
404 MemoryLocation Loc) {
Elena Demikhovskyef035bb2015-02-17 13:10:05 +0000405 return AA->canInstructionRangeModRef(Start, End, Loc, AliasAnalysis::ModRef);
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000406}
407
408///
409/// \brief Check if \p BB contains a store to the same address as \p SI
410///
411/// \return The store in \p when it is safe to sink. Otherwise return Null.
412///
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000413StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
414 StoreInst *Store0) {
415 DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
Elena Demikhovskyef035bb2015-02-17 13:10:05 +0000416 BasicBlock *BB0 = Store0->getParent();
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000417 for (BasicBlock::reverse_iterator RBI = BB1->rbegin(), RBE = BB1->rend();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000418 RBI != RBE; ++RBI) {
419 Instruction *Inst = &*RBI;
420
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000421 if (!isa<StoreInst>(Inst))
422 continue;
423
424 StoreInst *Store1 = cast<StoreInst>(Inst);
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000425
Chandler Carruthac80dc72015-06-17 07:18:54 +0000426 MemoryLocation Loc0 = MemoryLocation::get(Store0);
427 MemoryLocation Loc1 = MemoryLocation::get(Store1);
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000428 if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
Elena Demikhovskyef035bb2015-02-17 13:10:05 +0000429 !isStoreSinkBarrierInRange(*(std::next(BasicBlock::iterator(Store1))),
430 BB1->back(), Loc1) &&
431 !isStoreSinkBarrierInRange(*(std::next(BasicBlock::iterator(Store0))),
432 BB0->back(), Loc0)) {
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000433 return Store1;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000434 }
435 }
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000436 return nullptr;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000437}
438
439///
440/// \brief Create a PHI node in BB for the operands of S0 and S1
441///
442PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
443 StoreInst *S1) {
444 // Create a phi if the values mismatch.
445 PHINode *NewPN = 0;
446 Value *Opd1 = S0->getValueOperand();
447 Value *Opd2 = S1->getValueOperand();
448 if (Opd1 != Opd2) {
449 NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
450 BB->begin());
451 NewPN->addIncoming(Opd1, S0->getParent());
452 NewPN->addIncoming(Opd2, S1->getParent());
453 if (NewPN->getType()->getScalarType()->isPointerTy()) {
454 // Notify AA of the new value.
455 AA->copyValue(Opd1, NewPN);
456 AA->copyValue(Opd2, NewPN);
457 // AA needs to be informed when a PHI-use of the pointer value is added
458 for (unsigned I = 0, E = NewPN->getNumIncomingValues(); I != E; ++I) {
459 unsigned J = PHINode::getOperandNumForIncomingValue(I);
460 AA->addEscapingUse(NewPN->getOperandUse(J));
461 }
462 if (MD)
463 MD->invalidateCachedPointerInfo(NewPN);
464 }
465 }
466 return NewPN;
467}
468
469///
470/// \brief Merge two stores to same address and sink into \p BB
471///
472/// Also sinks GEP instruction computing the store address
473///
474bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
475 StoreInst *S1) {
476 // Only one definition?
477 Instruction *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
478 Instruction *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
479 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
480 (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
481 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
482 DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
483 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
484 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
485 // Hoist the instruction.
486 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
487 // Intersect optional metadata.
488 S0->intersectOptionalDataWith(S1);
489 S0->dropUnknownMetadata();
490
491 // Create the new store to be inserted at the join point.
492 StoreInst *SNew = (StoreInst *)(S0->clone());
493 Instruction *ANew = A0->clone();
494 AA->copyValue(S0, SNew);
495 SNew->insertBefore(InsertPt);
496 ANew->insertBefore(SNew);
497
498 assert(S0->getParent() == A0->getParent());
499 assert(S1->getParent() == A1->getParent());
500
501 PHINode *NewPN = getPHIOperand(BB, S0, S1);
502 // New PHI operand? Use it.
503 if (NewPN)
504 SNew->setOperand(0, NewPN);
505 removeInstruction(S0);
506 removeInstruction(S1);
507 A0->replaceAllUsesWith(ANew);
508 removeInstruction(A0);
509 A1->replaceAllUsesWith(ANew);
510 removeInstruction(A1);
511 return true;
512 }
513 return false;
514}
515
516///
517/// \brief True when two stores are equivalent and can sink into the footer
518///
519/// Starting from a diamond tail block, iterate over the instructions in one
520/// predecessor block and try to match a store in the second predecessor.
521///
522bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
523
524 bool MergedStores = false;
525 assert(T && "Footer of a diamond cannot be empty");
526
527 pred_iterator PI = pred_begin(T), E = pred_end(T);
528 assert(PI != E);
529 BasicBlock *Pred0 = *PI;
530 ++PI;
531 BasicBlock *Pred1 = *PI;
532 ++PI;
533 // tail block of a diamond/hammock?
534 if (Pred0 == Pred1)
535 return false; // No.
536 if (PI != E)
537 return false; // No. More than 2 predecessors.
538
539 // #Instructions in Succ1 for Compile Time Control
540 int Size1 = Pred1->size();
541 int NStores = 0;
542
543 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
544 RBI != RBE;) {
545
546 Instruction *I = &*RBI;
547 ++RBI;
Elena Demikhovskya5599bf2014-12-15 14:09:53 +0000548
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000549 // Sink move non-simple (atomic, volatile) stores
550 if (!isa<StoreInst>(I))
551 continue;
552 StoreInst *S0 = (StoreInst *)I;
553 if (!S0->isSimple())
554 continue;
555
556 ++NStores;
557 if (NStores * Size1 >= MagicCompileTimeControl)
558 break;
559 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
560 bool Res = sinkStore(T, S0, S1);
561 MergedStores |= Res;
562 // Don't attempt to sink below stores that had to stick around
563 // But after removal of a store and some of its feeding
564 // instruction search again from the beginning since the iterator
565 // is likely stale at this point.
566 if (!Res)
567 break;
568 else {
569 RBI = Pred0->rbegin();
570 RBE = Pred0->rend();
571 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
572 }
573 }
574 }
575 return MergedStores;
576}
577///
578/// \brief Run the transformation for each function
579///
580bool MergedLoadStoreMotion::runOnFunction(Function &F) {
Daniel Berlinb3015332015-05-22 00:13:05 +0000581 MD = getAnalysisIfAvailable<MemoryDependenceAnalysis>();
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000582 AA = &getAnalysis<AliasAnalysis>();
583
584 bool Changed = false;
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000585 DEBUG(dbgs() << "Instruction Merger\n");
586
587 // Merge unconditional branches, allowing PRE to catch more
588 // optimization opportunities.
589 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
590 BasicBlock *BB = FI++;
591
592 // Hoist equivalent loads and sink stores
593 // outside diamonds when possible
Gerolf Hoflehnerf27ae6c2014-07-18 19:13:09 +0000594 if (isDiamondHead(BB)) {
595 Changed |= mergeLoads(BB);
596 Changed |= mergeStores(getDiamondTail(BB));
597 }
598 }
599 return Changed;
600}