LLVM  5.0.0
MergedLoadStoreMotion.cpp
Go to the documentation of this file.
1 //===- 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 // NOTE: This code no longer performs load hoisting, it is subsumed by GVNHoist.
23 //
24 //===----------------------------------------------------------------------===//
25 //
26 //
27 // Example:
28 // Diamond shaped code before merge:
29 //
30 // header:
31 // br %cond, label %if.then, label %if.else
32 // + +
33 // + +
34 // + +
35 // if.then: if.else:
36 // %lt = load %addr_l %le = load %addr_l
37 // <use %lt> <use %le>
38 // <...> <...>
39 // store %st, %addr_s store %se, %addr_s
40 // br label %if.end br label %if.end
41 // + +
42 // + +
43 // + +
44 // if.end ("footer"):
45 // <...>
46 //
47 // Diamond shaped code after merge:
48 //
49 // header:
50 // %l = load %addr_l
51 // br %cond, label %if.then, label %if.else
52 // + +
53 // + +
54 // + +
55 // if.then: if.else:
56 // <use %l> <use %l>
57 // <...> <...>
58 // br label %if.end br label %if.end
59 // + +
60 // + +
61 // + +
62 // if.end ("footer"):
63 // %s.sink = phi [%st, if.then], [%se, if.else]
64 // <...>
65 // store %s.sink, %addr_s
66 // <...>
67 //
68 //
69 //===----------------------- TODO -----------------------------------------===//
70 //
71 // 1) Generalize to regions other than diamonds
72 // 2) Be more aggressive merging memory operations
73 // Note that both changes require register pressure control
74 //
75 //===----------------------------------------------------------------------===//
76 
78 #include "llvm/ADT/Statistic.h"
80 #include "llvm/Analysis/CFG.h"
82 #include "llvm/Analysis/Loads.h"
86 #include "llvm/IR/Metadata.h"
87 #include "llvm/IR/PatternMatch.h"
88 #include "llvm/Support/Debug.h"
90 #include "llvm/Transforms/Scalar.h"
92 
93 using namespace llvm;
94 
95 #define DEBUG_TYPE "mldst-motion"
96 
97 namespace {
98 //===----------------------------------------------------------------------===//
99 // MergedLoadStoreMotion Pass
100 //===----------------------------------------------------------------------===//
101 class MergedLoadStoreMotion {
102  MemoryDependenceResults *MD = nullptr;
103  AliasAnalysis *AA = nullptr;
104 
105  // The mergeLoad/Store algorithms could have Size0 * Size1 complexity,
106  // where Size0 and Size1 are the #instructions on the two sides of
107  // the diamond. The constant chosen here is arbitrary. Compiler Time
108  // Control is enforced by the check Size0 * Size1 < MagicCompileTimeControl.
109  const int MagicCompileTimeControl = 250;
110 
111 public:
112  bool run(Function &F, MemoryDependenceResults *MD, AliasAnalysis &AA);
113 
114 private:
115  ///
116  /// \brief Remove instruction from parent and update memory dependence
117  /// analysis.
118  ///
119  void removeInstruction(Instruction *Inst);
120  BasicBlock *getDiamondTail(BasicBlock *BB);
121  bool isDiamondHead(BasicBlock *BB);
122  // Routines for sinking stores
123  StoreInst *canSinkFromBlock(BasicBlock *BB, StoreInst *SI);
124  PHINode *getPHIOperand(BasicBlock *BB, StoreInst *S0, StoreInst *S1);
125  bool isStoreSinkBarrierInRange(const Instruction &Start,
126  const Instruction &End, MemoryLocation Loc);
127  bool sinkStore(BasicBlock *BB, StoreInst *SinkCand, StoreInst *ElseInst);
128  bool mergeStores(BasicBlock *BB);
129 };
130 } // end anonymous namespace
131 
132 ///
133 /// \brief Remove instruction from parent and update memory dependence analysis.
134 ///
135 void MergedLoadStoreMotion::removeInstruction(Instruction *Inst) {
136  // Notify the memory dependence analysis.
137  if (MD) {
138  MD->removeInstruction(Inst);
139  if (auto *LI = dyn_cast<LoadInst>(Inst))
140  MD->invalidateCachedPointerInfo(LI->getPointerOperand());
141  if (Inst->getType()->isPtrOrPtrVectorTy()) {
142  MD->invalidateCachedPointerInfo(Inst);
143  }
144  }
145  Inst->eraseFromParent();
146 }
147 
148 ///
149 /// \brief Return tail block of a diamond.
150 ///
151 BasicBlock *MergedLoadStoreMotion::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 ///
157 /// \brief True when BB is the head of a diamond (hammock)
158 ///
159 bool MergedLoadStoreMotion::isDiamondHead(BasicBlock *BB) {
160  if (!BB)
161  return false;
162  auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
163  if (!BI || !BI->isConditional())
164  return false;
165 
166  BasicBlock *Succ0 = BI->getSuccessor(0);
167  BasicBlock *Succ1 = BI->getSuccessor(1);
168 
169  if (!Succ0->getSinglePredecessor())
170  return false;
171  if (!Succ1->getSinglePredecessor())
172  return false;
173 
174  BasicBlock *Succ0Succ = Succ0->getSingleSuccessor();
175  BasicBlock *Succ1Succ = Succ1->getSingleSuccessor();
176  // Ignore triangles.
177  if (!Succ0Succ || !Succ1Succ || Succ0Succ != Succ1Succ)
178  return false;
179  return true;
180 }
181 
182 
183 ///
184 /// \brief True when instruction is a sink barrier for a store
185 /// located in Loc
186 ///
187 /// Whenever an instruction could possibly read or modify the
188 /// value being stored or protect against the store from
189 /// happening it is considered a sink barrier.
190 ///
191 bool MergedLoadStoreMotion::isStoreSinkBarrierInRange(const Instruction &Start,
192  const Instruction &End,
193  MemoryLocation Loc) {
194  for (const Instruction &Inst :
195  make_range(Start.getIterator(), End.getIterator()))
196  if (Inst.mayThrow())
197  return true;
198  return AA->canInstructionRangeModRef(Start, End, Loc, MRI_ModRef);
199 }
200 
201 ///
202 /// \brief Check if \p BB contains a store to the same address as \p SI
203 ///
204 /// \return The store in \p when it is safe to sink. Otherwise return Null.
205 ///
206 StoreInst *MergedLoadStoreMotion::canSinkFromBlock(BasicBlock *BB1,
207  StoreInst *Store0) {
208  DEBUG(dbgs() << "can Sink? : "; Store0->dump(); dbgs() << "\n");
209  BasicBlock *BB0 = Store0->getParent();
210  for (Instruction &Inst : reverse(*BB1)) {
211  auto *Store1 = dyn_cast<StoreInst>(&Inst);
212  if (!Store1)
213  continue;
214 
215  MemoryLocation Loc0 = MemoryLocation::get(Store0);
216  MemoryLocation Loc1 = MemoryLocation::get(Store1);
217  if (AA->isMustAlias(Loc0, Loc1) && Store0->isSameOperationAs(Store1) &&
218  !isStoreSinkBarrierInRange(*Store1->getNextNode(), BB1->back(), Loc1) &&
219  !isStoreSinkBarrierInRange(*Store0->getNextNode(), BB0->back(), Loc0)) {
220  return Store1;
221  }
222  }
223  return nullptr;
224 }
225 
226 ///
227 /// \brief Create a PHI node in BB for the operands of S0 and S1
228 ///
229 PHINode *MergedLoadStoreMotion::getPHIOperand(BasicBlock *BB, StoreInst *S0,
230  StoreInst *S1) {
231  // Create a phi if the values mismatch.
232  Value *Opd1 = S0->getValueOperand();
233  Value *Opd2 = S1->getValueOperand();
234  if (Opd1 == Opd2)
235  return nullptr;
236 
237  auto *NewPN = PHINode::Create(Opd1->getType(), 2, Opd2->getName() + ".sink",
238  &BB->front());
239  NewPN->addIncoming(Opd1, S0->getParent());
240  NewPN->addIncoming(Opd2, S1->getParent());
241  if (MD && NewPN->getType()->isPtrOrPtrVectorTy())
242  MD->invalidateCachedPointerInfo(NewPN);
243  return NewPN;
244 }
245 
246 ///
247 /// \brief Merge two stores to same address and sink into \p BB
248 ///
249 /// Also sinks GEP instruction computing the store address
250 ///
251 bool MergedLoadStoreMotion::sinkStore(BasicBlock *BB, StoreInst *S0,
252  StoreInst *S1) {
253  // Only one definition?
254  auto *A0 = dyn_cast<Instruction>(S0->getPointerOperand());
255  auto *A1 = dyn_cast<Instruction>(S1->getPointerOperand());
256  if (A0 && A1 && A0->isIdenticalTo(A1) && A0->hasOneUse() &&
257  (A0->getParent() == S0->getParent()) && A1->hasOneUse() &&
258  (A1->getParent() == S1->getParent()) && isa<GetElementPtrInst>(A0)) {
259  DEBUG(dbgs() << "Sink Instruction into BB \n"; BB->dump();
260  dbgs() << "Instruction Left\n"; S0->dump(); dbgs() << "\n";
261  dbgs() << "Instruction Right\n"; S1->dump(); dbgs() << "\n");
262  // Hoist the instruction.
263  BasicBlock::iterator InsertPt = BB->getFirstInsertionPt();
264  // Intersect optional metadata.
265  S0->andIRFlags(S1);
267 
268  // Create the new store to be inserted at the join point.
269  StoreInst *SNew = cast<StoreInst>(S0->clone());
270  Instruction *ANew = A0->clone();
271  SNew->insertBefore(&*InsertPt);
272  ANew->insertBefore(SNew);
273 
274  assert(S0->getParent() == A0->getParent());
275  assert(S1->getParent() == A1->getParent());
276 
277  // New PHI operand? Use it.
278  if (PHINode *NewPN = getPHIOperand(BB, S0, S1))
279  SNew->setOperand(0, NewPN);
280  removeInstruction(S0);
281  removeInstruction(S1);
282  A0->replaceAllUsesWith(ANew);
283  removeInstruction(A0);
284  A1->replaceAllUsesWith(ANew);
285  removeInstruction(A1);
286  return true;
287  }
288  return false;
289 }
290 
291 ///
292 /// \brief True when two stores are equivalent and can sink into the footer
293 ///
294 /// Starting from a diamond tail block, iterate over the instructions in one
295 /// predecessor block and try to match a store in the second predecessor.
296 ///
297 bool MergedLoadStoreMotion::mergeStores(BasicBlock *T) {
298 
299  bool MergedStores = false;
300  assert(T && "Footer of a diamond cannot be empty");
301 
302  pred_iterator PI = pred_begin(T), E = pred_end(T);
303  assert(PI != E);
304  BasicBlock *Pred0 = *PI;
305  ++PI;
306  BasicBlock *Pred1 = *PI;
307  ++PI;
308  // tail block of a diamond/hammock?
309  if (Pred0 == Pred1)
310  return false; // No.
311  if (PI != E)
312  return false; // No. More than 2 predecessors.
313 
314  // #Instructions in Succ1 for Compile Time Control
315  int Size1 = Pred1->size();
316  int NStores = 0;
317 
318  for (BasicBlock::reverse_iterator RBI = Pred0->rbegin(), RBE = Pred0->rend();
319  RBI != RBE;) {
320 
321  Instruction *I = &*RBI;
322  ++RBI;
323 
324  // Don't sink non-simple (atomic, volatile) stores.
325  auto *S0 = dyn_cast<StoreInst>(I);
326  if (!S0 || !S0->isSimple())
327  continue;
328 
329  ++NStores;
330  if (NStores * Size1 >= MagicCompileTimeControl)
331  break;
332  if (StoreInst *S1 = canSinkFromBlock(Pred1, S0)) {
333  bool Res = sinkStore(T, S0, S1);
334  MergedStores |= Res;
335  // Don't attempt to sink below stores that had to stick around
336  // But after removal of a store and some of its feeding
337  // instruction search again from the beginning since the iterator
338  // is likely stale at this point.
339  if (!Res)
340  break;
341  RBI = Pred0->rbegin();
342  RBE = Pred0->rend();
343  DEBUG(dbgs() << "Search again\n"; Instruction *I = &*RBI; I->dump());
344  }
345  }
346  return MergedStores;
347 }
348 
349 bool MergedLoadStoreMotion::run(Function &F, MemoryDependenceResults *MD,
350  AliasAnalysis &AA) {
351  this->MD = MD;
352  this->AA = &AA;
353 
354  bool Changed = false;
355  DEBUG(dbgs() << "Instruction Merger\n");
356 
357  // Merge unconditional branches, allowing PRE to catch more
358  // optimization opportunities.
359  for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
360  BasicBlock *BB = &*FI++;
361 
362  // Hoist equivalent loads and sink stores
363  // outside diamonds when possible
364  if (isDiamondHead(BB)) {
365  Changed |= mergeStores(getDiamondTail(BB));
366  }
367  }
368  return Changed;
369 }
370 
371 namespace {
372 class MergedLoadStoreMotionLegacyPass : public FunctionPass {
373 public:
374  static char ID; // Pass identification, replacement for typeid
375  MergedLoadStoreMotionLegacyPass() : FunctionPass(ID) {
378  }
379 
380  ///
381  /// \brief Run the transformation for each function
382  ///
383  bool runOnFunction(Function &F) override {
384  if (skipFunction(F))
385  return false;
387  auto *MDWP = getAnalysisIfAvailable<MemoryDependenceWrapperPass>();
388  return Impl.run(F, MDWP ? &MDWP->getMemDep() : nullptr,
389  getAnalysis<AAResultsWrapperPass>().getAAResults());
390  }
391 
392 private:
393  void getAnalysisUsage(AnalysisUsage &AU) const override {
394  AU.setPreservesCFG();
398  }
399 };
400 
402 } // anonymous namespace
403 
404 ///
405 /// \brief createMergedLoadStoreMotionPass - The public interface to this file.
406 ///
408  return new MergedLoadStoreMotionLegacyPass();
409 }
410 
411 INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass, "mldst-motion",
412  "MergedLoadStoreMotion", false, false)
415 INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass, "mldst-motion",
416  "MergedLoadStoreMotion", false, false)
417 
420  MergedLoadStoreMotion Impl;
421  auto *MD = AM.getCachedResult<MemoryDependenceAnalysis>(F);
422  auto &AA = AM.getResult<AAManager>(F);
423  if (!Impl.run(F, MD, AA))
424  return PreservedAnalyses::all();
425 
427  PA.preserveSet<CFGAnalyses>();
428  PA.preserve<GlobalsAA>();
430  return PA;
431 }
Legacy wrapper pass to provide the GlobalsAAResult object.
Value * getValueOperand()
Definition: Instructions.h:395
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
Definition: Instruction.cpp:69
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Provides a lazy, caching interface for making common memory aliasing information queries, backed by LLVM's alias analysis passes.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const Instruction & back() const
Definition: BasicBlock.h:266
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition: ilist_node.h:289
This is the interface for a simple mod/ref and alias analysis over globals.
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
Definition: Metadata.cpp:1187
iterator end()
Definition: Function.h:582
bool isSimple() const
Definition: Instructions.h:387
This file contains the declarations for metadata subclasses.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:224
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
const Instruction & front() const
Definition: BasicBlock.h:264
reverse_iterator rend()
Definition: BasicBlock.h:259
reverse_iterator rbegin()
Definition: BasicBlock.h:257
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
mldst false
mldst motion
mldst MergedLoadStoreMotion
An analysis that produces MemoryDependenceResults for a function.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:250
#define F(x, y, z)
Definition: MD5.cpp:55
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
An instruction for storing to memory.
Definition: Instructions.h:306
iterator begin()
Definition: Function.h:580
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:244
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
Definition: Instruction.cpp:75
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
Conditional or Unconditional Branch instruction.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:200
A manager for alias analyses.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:116
Represent the analysis usage information of a pass.
Analysis pass providing a never-invalidated alias analysis result.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
static const unsigned End
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:119
self_iterator getIterator()
Definition: ilist_node.h:82
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance...
void dump() const
Support for debugging, callable in GDB: V->dump()
Definition: AsmWriter.cpp:3606
Representation for a specific memory location.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Iterator for intrusive lists based on ilist_node.
#define E
Definition: LargeTest.cpp:27
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:278
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:217
void setOperand(unsigned i, Value *Val)
Definition: User.h:159
FunctionPass * createMergedLoadStoreMotionPass()
createMergedLoadStoreMotionPass - The public interface to this file.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
INITIALIZE_PASS_BEGIN(MergedLoadStoreMotionLegacyPass,"mldst-motion","MergedLoadStoreMotion", false, false) INITIALIZE_PASS_END(MergedLoadStoreMotionLegacyPass
Represents analyses that only rely on functions' control flow.
Definition: PassManager.h:114
This pass performs merges of loads and stores on both sides of a.
bool mayThrow() const
Return true if this instruction may throw an exception.
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:189
The access both references and modifies the value stored in memory.
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
void preserve()
Mark an analysis as preserved.
Definition: PassManager.h:174
size_t size() const
Definition: BasicBlock.h:262
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
#define DEBUG(X)
Definition: Debug.h:118
A container for analyses that lazily runs them and caches their results.
bool isSameOperationAs(const Instruction *I, unsigned flags=0) const
This function determines if the specified instruction executes the same operation as the current one...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:120
void initializeMergedLoadStoreMotionLegacyPassPass(PassRegistry &)
Value * getPointerOperand()
Definition: Instructions.h:398
const BasicBlock * getParent() const
Definition: Instruction.h:66