blob: a10733952be46988e8587c098cd262ac03216847 [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
30// / \
31// / \
32// / \
33// 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
39// \ /
40// \ /
41// \ /
42// 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
50// / \
51// / \
52// / \
53// if.then: if.else:
54// <use %l> <use %l>
55// <...> <...>
56// br label %if.end br label %if.end
57// \ /
58// \ /
59// \ /
60// 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"
84#include "llvm/IR/Metadata.h"
85#include "llvm/IR/PatternMatch.h"
86#include "llvm/Support/Allocator.h"
87#include "llvm/Support/CommandLine.h"
88#include "llvm/Support/Debug.h"
89#include "llvm/Target/TargetLibraryInfo.h"
90#include "llvm/Transforms/Utils/BasicBlockUtils.h"
91#include "llvm/Transforms/Utils/SSAUpdater.h"
92#include <vector>
93using namespace llvm;
94
95#define DEBUG_TYPE "mldst-motion"
96
97//===----------------------------------------------------------------------===//
98// MergedLoadStoreMotion Pass
99//===----------------------------------------------------------------------===//
100static cl::opt<bool>
101EnableMLSM("mlsm", cl::desc("Enable motion of merged load and store"),
102 cl::init(true));
103
104namespace {
105class MergedLoadStoreMotion : public FunctionPass {
106 AliasAnalysis *AA;
107 MemoryDependenceAnalysis *MD;
108
109public:
110 static char ID; // Pass identification, replacement for typeid
111 explicit MergedLoadStoreMotion(void) : FunctionPass(ID), MD(nullptr) {
112 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 {
120 AU.addRequired<TargetLibraryInfo>();
121 AU.addRequired<MemoryDependenceAnalysis>();
122 AU.addRequired<AliasAnalysis>();
123 AU.addPreserved<AliasAnalysis>();
124 }
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
136 bool isLoadHoistBarrier(Instruction *Inst);
137 LoadInst *canHoistFromBlock(BasicBlock *BB, LoadInst *LI);
138 void hoistInstruction(BasicBlock *BB, Instruction *HoistCand,
139 Instruction *ElseInst);
140 bool isSafeToHoist(Instruction *I) const;
141 bool hoistLoad(BasicBlock *BB, LoadInst *HoistCand, LoadInst *ElseInst);
142 bool mergeLoads(BasicBlock *BB);
143 // Routines for sinking stores
144 StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
145 PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
146 bool isStoreSinkBarrier(Instruction *Inst);
147 bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
148 bool mergeStores(BasicBlock *BB);
149 // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
150 // where Size0 and Size1 are the #instructions on the two sides of
151 // the diamond. The constant chosen here is arbitrary. Compiler Time
152 // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
153 const int MagicCompileTimeControl = 250;
154};
155
156char MergedLoadStoreMotion::ID = 0;
157}
158
159///
160/// \brief createMergedLoadStoreMotionPass - The public interface to this file.
161///
162FunctionPass *llvm::createMergedLoadStoreMotionPass() {
163 return new MergedLoadStoreMotion();
164}
165
166INITIALIZE_PASS_BEGIN(MergedLoadStoreMotion, "mldst-motion",
167 "MergedLoadStoreMotion", false, false)
168INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
169INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
170INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
171INITIALIZE_PASS_END(MergedLoadStoreMotion, "mldst-motion",
172 "MergedLoadStoreMotion", false, false)
173
174///
175/// \brief Remove instruction from parent and update memory dependence analysis.
176///
177void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
178 // Notify the memory dependence analysis.
179 if (MD) {
180 MD->removeInstruction(Inst);
181 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
182 MD->invalidateCachedPointerInfo(LI->getPointerOperand());
183 if (Inst->getType()->getScalarType()->isPointerTy()) {
184 MD->invalidateCachedPointerInfo(Inst);
185 }
186 }
187 Inst->eraseFromParent();
188}
189
190///
191/// \brief Return tail block of a diamond.
192///
193BasicBlock *MergedLoadStoreMotion::getDiamondTail(BasicBlock *BB) {
194 assert(isDiamondHead(BB) && "Basic block is not head of a diamond");
195 BranchInst *BI = (BranchInst *)(BB->getTerminator());
196 BasicBlock *Succ0 = BI->getSuccessor(0);
197 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
198 return Tail;
199}
200
201///
202/// \brief True when BB is the head of a diamond (hammock)
203///
204bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
205 if (!BB)
206 return false;
207 if (!isa<BranchInst>(BB->getTerminator()))
208 return false;
209 if (BB->getTerminator()->getNumSuccessors() != 2)
210 return false;
211
212 BranchInst *BI = (BranchInst *)(BB->getTerminator());
213 BasicBlock *Succ0 = BI->getSuccessor(0);
214 BasicBlock *Succ1 = BI->getSuccessor(1);
215
216 if (!Succ0->getSinglePredecessor() ||
217 Succ0->getTerminator()->getNumSuccessors() != 1)
218 return false;
219 if (!Succ1->getSinglePredecessor() ||
220 Succ1->getTerminator()->getNumSuccessors() != 1)
221 return false;
222
223 BasicBlock *Tail = Succ0->getTerminator()->getSuccessor(0);
224 // Ignore triangles.
225 if (Succ1->getTerminator()->getSuccessor(0) != Tail)
226 return false;
227 return true;
228}
229
230///
231/// \brief True when instruction is a hoist barrier for a load
232///
233/// Whenever an instruction could possibly modify the value
234/// being loaded or protect against the load from happening
235/// it is considered a hoist barrier.
236///
237bool MergedLoadStoreMotion::isLoadHoistBarrier(Instruction *Inst) {
238 // FIXME: A call with no side effects should not be a barrier.
239 // Aren't all such calls covered by mayHaveSideEffects() below?
240 // Then this check can be removed.
241 if (isa<CallInst>(Inst))
242 return true;
243 if (isa<TerminatorInst>(Inst))
244 return true;
245 // Note: mayHaveSideEffects covers all instructions that could
246 // trigger a change to state. Eg. in-flight stores have to be executed
247 // before ordered loads or fences, calls could invoke functions that store
248 // data to memory etc.
249 if (Inst->mayHaveSideEffects()) {
250 return true;
251 }
252 DEBUG(dbgs() << "No Hoist Barrier\n");
253 return false;
254}
255
256///
257/// \brief Decide if a load can be hoisted
258///
259/// When there is a load in \p BB to the same address as \p LI
260/// and it can be hoisted from \p BB, return that load.
261/// Otherwise return Null.
262///
263LoadInst *MergedLoadStoreMotion::canHoistFromBlock(BasicBlock *BB,
264 LoadInst *LI) {
265 LoadInst *I = nullptr;
266 assert(isa<LoadInst>(LI));
267 if (LI->isUsedOutsideOfBlock(LI->getParent()))
268 return nullptr;
269
270 for (BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); BBI != BBE;
271 ++BBI) {
272 Instruction *Inst = BBI;
273
274 // Only merge and hoist loads when their result in used only in BB
275 if (isLoadHoistBarrier(Inst))
276 break;
277 if (!isa<LoadInst>(Inst))
278 continue;
279 if (Inst->isUsedOutsideOfBlock(Inst->getParent()))
280 continue;
281
282 AliasAnalysis::Location LocLI = AA->getLocation(LI);
283 AliasAnalysis::Location LocInst = AA->getLocation((LoadInst *)Inst);
284 if (AA->isMustAlias(LocLI, LocInst) && LI->getType() == Inst->getType()) {
285 I = (LoadInst *)Inst;
286 break;
287 }
288 }
289 return I;
290}
291
292///
293/// \brief Merge two equivalent instructions \p HoistCand and \p ElseInst into
294/// \p BB
295///
296/// BB is the head of a diamond
297///
298void MergedLoadStoreMotion::hoistInstruction(BasicBlock *BB,
299 Instruction *HoistCand,
300 Instruction *ElseInst) {
301 DEBUG(dbgs() << " Hoist Instruction into BB \n"; BB->dump();
302 dbgs() << "Instruction Left\n"; HoistCand->dump(); dbgs() << "\n";
303 dbgs() << "Instruction Right\n"; ElseInst->dump(); dbgs() << "\n");
304 // Hoist the instruction.
305 assert(HoistCand->getParent() != BB);
306
307 // Intersect optional metadata.
308 HoistCand->intersectOptionalDataWith(ElseInst);
309 HoistCand->dropUnknownMetadata();
310
311 // Prepend point for instruction insert
312 Instruction *HoistPt = BB->getTerminator();
313
314 // Merged instruction
315 Instruction *HoistedInst = HoistCand->clone();
316
317 // Notify AA of the new value.
318 if (isa<LoadInst>(HoistCand))
319 AA->copyValue(HoistCand, HoistedInst);
320
321 // Hoist instruction.
322 HoistedInst->insertBefore(HoistPt);
323
324 HoistCand->replaceAllUsesWith(HoistedInst);
325 removeInstruction(HoistCand);
326 // Replace the else block instruction.
327 ElseInst->replaceAllUsesWith(HoistedInst);
328 removeInstruction(ElseInst);
329}
330
331///
332/// \brief Return true if no operand of \p I is defined in I's parent block
333///
334bool MergedLoadStoreMotion::isSafeToHoist(Instruction *I) const {
335 BasicBlock *Parent = I->getParent();
336 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
337 Instruction *Instr = dyn_cast<Instruction>(I->getOperand(i));
338 if (Instr && Instr->getParent() == Parent)
339 return false;
340 }
341 return true;
342}
343
344///
345/// \brief Merge two equivalent loads and GEPs and hoist into diamond head
346///
347bool MergedLoadStoreMotion::hoistLoad(BasicBlock *BB, LoadInst *L0,
348 LoadInst *L1) {
349 // Only one definition?
350 Instruction *A0 = dyn_cast<Instruction>(L0->getPointerOperand());
351 Instruction *A1 = dyn_cast<Instruction>(L1->getPointerOperand());
352 if (A0 && A1 && A0->isIdenticalTo(A1) && isSafeToHoist(A0) &&
353 A0->hasOneUse() && (A0->getParent() == L0->getParent()) &&
354 A1->hasOneUse() && (A1->getParent() == L1->getParent()) &&
355 isa<GetElementPtrInst>(A0)) {
356 DEBUG(dbgs() << "Hoist Instruction into BB \n"; BB->dump();
357 dbgs() << "Instruction Left\n"; L0->dump(); dbgs() << "\n";
358 dbgs() << "Instruction Right\n"; L1->dump(); dbgs() << "\n");
359 hoistInstruction(BB, A0, A1);
360 hoistInstruction(BB, L0, L1);
361 return true;
362 } else
363 return false;
364}
365
366///
367/// \brief Try to hoist two loads to same address into diamond header
368///
369/// Starting from a diamond head block, iterate over the instructions in one
370/// successor block and try to match a load in the second successor.
371///
372bool MergedLoadStoreMotion::mergeLoads(BasicBlock *BB) {
373 bool MergedLoads = false;
374 assert(isDiamondHead(BB));
375 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
376 BasicBlock *Succ0 = BI->getSuccessor(0);
377 BasicBlock *Succ1 = BI->getSuccessor(1);
378 // #Instructions in Succ1 for Compile Time Control
379 int Size1 = Succ1->size();
380 int NLoads = 0;
381 for (BasicBlock::iterator BBI = Succ0->begin(), BBE = Succ0->end();
382 BBI != BBE;) {
383
384 Instruction *I = BBI;
385 ++BBI;
386 if (isLoadHoistBarrier(I))
387 break;
388
389 // Only move non-simple (atomic, volatile) loads.
390 if (!isa<LoadInst>(I))
391 continue;
392
393 LoadInst *L0 = (LoadInst *)I;
394 if (!L0->isSimple())
395 continue;
396
397 ++NLoads;
398 if (NLoads * Size1 >= MagicCompileTimeControl)
399 break;
400 if (LoadInst *L1 = canHoistFromBlock(Succ1, L0)) {
401 bool Res = hoistLoad(BB, L0, L1);
402 MergedLoads |= Res;
403 // Don't attempt to hoist above loads that had not been hoisted.
404 if (!Res)
405 break;
406 }
407 }
408 return MergedLoads;
409}
410
411///
412/// \brief True when instruction is sink barrier for a store
413///
414bool MergedLoadStoreMotion::isStoreSinkBarrier(Instruction *Inst) {
415 if (isa<CallInst>(Inst))
416 return true;
417 if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst))
418 return true;
419 // Note: mayHaveSideEffects covers all instructions that could
420 // trigger a change to state. Eg. in-flight stores have to be executed
421 // before ordered loads or fences, calls could invoke functions that store
422 // data to memory etc.
423 if (!isa<StoreInst>(Inst) && Inst->mayHaveSideEffects()) {
424 return true;
425 }
426 DEBUG(dbgs() << "No Sink Barrier\n");
427 return false;
428}
429
430///
431/// \brief Check if \p BB contains a store to the same address as \p SI
432///
433/// \return The store in \p when it is safe to sink. Otherwise return Null.
434///
435StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB,
436 StoreInst *SI) {
437 StoreInst *I = 0;
438 DEBUG(dbgs() << "can Sink? : "; SI->dump(); dbgs() << "\n");
439 for (BasicBlock::reverse_iterator RBI = BB->rbegin(), RBE = BB->rend();
440 RBI != RBE; ++RBI) {
441 Instruction *Inst = &*RBI;
442
443 // Only move loads if they are used in the block.
444 if (isStoreSinkBarrier(Inst))
445 break;
446 if (isa<StoreInst>(Inst)) {
447 AliasAnalysis::Location LocSI = AA->getLocation(SI);
448 AliasAnalysis::Location LocInst = AA->getLocation((StoreInst *)Inst);
449 if (AA->isMustAlias(LocSI, LocInst)) {
450 I = (StoreInst *)Inst;
451 break;
452 }
453 }
454 }
455 return I;
456}
457
458///
459/// \brief Create a PHI node in BB for the operands of S0 and S1
460///
461PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
462 StoreInst *S1) {
463 // Create a phi if the values mismatch.
464 PHINode *NewPN = 0;
465 Value *Opd1 = S0->getValueOperand();
466 Value *Opd2 = S1->getValueOperand();
467 if (Opd1 != Opd2) {
468 NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
469 BB->begin());
470 NewPN->addIncoming(Opd1, S0->getParent());
471 NewPN->addIncoming(Opd2, S1->getParent());
472 if (NewPN->getType()->getScalarType()->isPointerTy()) {
473 // Notify AA of the new value.
474 AA->copyValue(Opd1, NewPN);
475 AA->copyValue(Opd2, NewPN);
476 // AA needs to be informed when a PHI-use of the pointer value is added
477 for (unsigned I = 0, E = NewPN->getNumIncomingValues(); I != E; ++I) {
478 unsigned J = PHINode::getOperandNumForIncomingValue(I);
479 AA->addEscapingUse(NewPN->getOperandUse(J));
480 }
481 if (MD)
482 MD->invalidateCachedPointerInfo(NewPN);
483 }
484 }
485 return NewPN;
486}
487
488///
489/// \brief Merge two stores to same address and sink into \p BB
490///
491/// Also sinks GEP instruction computing the store address
492///
493bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
494 StoreInst *S1) {
495 // Only one definition?
496 Instruction *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
497 Instruction *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
498 if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
499 (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
500 (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
501 DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
502 dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
503 dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
504 // Hoist the instruction.
505 BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
506 // Intersect optional metadata.
507 S0->intersectOptionalDataWith(S1);
508 S0->dropUnknownMetadata();
509
510 // Create the new store to be inserted at the join point.
511 StoreInst *SNew = (StoreInst *)(S0->clone());
512 Instruction *ANew = A0->clone();
513 AA->copyValue(S0, SNew);
514 SNew->insertBefore(InsertPt);
515 ANew->insertBefore(SNew);
516
517 assert(S0->getParent() == A0->getParent());
518 assert(S1->getParent() == A1->getParent());
519
520 PHINode *NewPN = getPHIOperand(BB, S0, S1);
521 // New PHI operand? Use it.
522 if (NewPN)
523 SNew->setOperand(0, NewPN);
524 removeInstruction(S0);
525 removeInstruction(S1);
526 A0->replaceAllUsesWith(ANew);
527 removeInstruction(A0);
528 A1->replaceAllUsesWith(ANew);
529 removeInstruction(A1);
530 return true;
531 }
532 return false;
533}
534
535///
536/// \brief True when two stores are equivalent and can sink into the footer
537///
538/// Starting from a diamond tail block, iterate over the instructions in one
539/// predecessor block and try to match a store in the second predecessor.
540///
541bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
542
543 bool MergedStores = false;
544 assert(T && "Footer of a diamond cannot be empty");
545
546 pred_iterator PI = pred_begin(T), E = pred_end(T);
547 assert(PI != E);
548 BasicBlock *Pred0 = *PI;
549 ++PI;
550 BasicBlock *Pred1 = *PI;
551 ++PI;
552 // tail block of a diamond/hammock?
553 if (Pred0 == Pred1)
554 return false; // No.
555 if (PI != E)
556 return false; // No. More than 2 predecessors.
557
558 // #Instructions in Succ1 for Compile Time Control
559 int Size1 = Pred1->size();
560 int NStores = 0;
561
562 for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
563 RBI != RBE;) {
564
565 Instruction *I = &*RBI;
566 ++RBI;
567 if (isStoreSinkBarrier(I))
568 break;
569 // Sink move non-simple (atomic, volatile) stores
570 if (!isa<StoreInst>(I))
571 continue;
572 StoreInst *S0 = (StoreInst *)I;
573 if (!S0->isSimple())
574 continue;
575
576 ++NStores;
577 if (NStores * Size1 >= MagicCompileTimeControl)
578 break;
579 if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
580 bool Res = sinkStore(T, S0, S1);
581 MergedStores |= Res;
582 // Don't attempt to sink below stores that had to stick around
583 // But after removal of a store and some of its feeding
584 // instruction search again from the beginning since the iterator
585 // is likely stale at this point.
586 if (!Res)
587 break;
588 else {
589 RBI = Pred0->rbegin();
590 RBE = Pred0->rend();
591 DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
592 }
593 }
594 }
595 return MergedStores;
596}
597///
598/// \brief Run the transformation for each function
599///
600bool MergedLoadStoreMotion::runOnFunction(Function &F) {
601 MD = &getAnalysis<MemoryDependenceAnalysis>();
602 AA = &getAnalysis<AliasAnalysis>();
603
604 bool Changed = false;
605 if (!EnableMLSM)
606 return false;
607 DEBUG(dbgs() << "Instruction Merger\n");
608
609 // Merge unconditional branches, allowing PRE to catch more
610 // optimization opportunities.
611 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
612 BasicBlock *BB = FI++;
613
614 // Hoist equivalent loads and sink stores
615 // outside diamonds when possible
616 // Run outside core GVN
617 if (isDiamondHead(BB)) {
618 Changed |= mergeLoads(BB);
619 Changed |= mergeStores(getDiamondTail(BB));
620 }
621 }
622 return Changed;
623}