blob: 95b4bddcc83d5a626a81351ddac544b36e85a53b [file] [log] [blame]
Chris Lattner71c7ec92002-08-30 20:28:10 +00001//===- LoadValueNumbering.cpp - Load Value #'ing Implementation -*- C++ -*-===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattner71c7ec92002-08-30 20:28:10 +00009//
10// This file implements a value numbering pass that value #'s load instructions.
11// To do this, it finds lexically identical load instructions, and uses alias
12// analysis to determine which loads are guaranteed to produce the same value.
13//
14// This pass builds off of another value numbering pass to implement value
15// numbering for non-load instructions. It uses Alias Analysis so that it can
16// disambiguate the load instructions. The more powerful these base analyses
17// are, the more powerful the resultant analysis will be.
18//
19//===----------------------------------------------------------------------===//
20
21#include "llvm/Analysis/LoadValueNumbering.h"
22#include "llvm/Analysis/ValueNumbering.h"
23#include "llvm/Analysis/AliasAnalysis.h"
24#include "llvm/Analysis/Dominators.h"
Chris Lattnerf98d8d82003-02-26 19:27:35 +000025#include "llvm/Target/TargetData.h"
Chris Lattner71c7ec92002-08-30 20:28:10 +000026#include "llvm/Pass.h"
Chris Lattneraed2c6d2003-06-29 00:53:34 +000027#include "llvm/Type.h"
Chris Lattner71c7ec92002-08-30 20:28:10 +000028#include "llvm/iMemory.h"
29#include "llvm/BasicBlock.h"
30#include "llvm/Support/CFG.h"
Chris Lattner71c7ec92002-08-30 20:28:10 +000031#include <set>
Chris Lattner270db362004-02-05 05:51:40 +000032using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000033
Chris Lattner71c7ec92002-08-30 20:28:10 +000034namespace {
Chris Lattner28c6cf22003-06-16 12:06:41 +000035 // FIXME: This should not be a FunctionPass.
Chris Lattner71c7ec92002-08-30 20:28:10 +000036 struct LoadVN : public FunctionPass, public ValueNumbering {
37
38 /// Pass Implementation stuff. This doesn't do any analysis.
39 ///
40 bool runOnFunction(Function &) { return false; }
41
42 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering
43 /// and Alias Analysis.
44 ///
45 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
46
47 /// getEqualNumberNodes - Return nodes with the same value number as the
48 /// specified Value. This fills in the argument vector with any equal
49 /// values.
50 ///
51 virtual void getEqualNumberNodes(Value *V1,
52 std::vector<Value*> &RetVals) const;
53 private:
54 /// haveEqualValueNumber - Given two load instructions, determine if they
55 /// both produce the same value on every execution of the program, assuming
56 /// that their source operands always give the same value. This uses the
57 /// AliasAnalysis implementation to invalidate loads when stores or function
58 /// calls occur that could modify the value produced by the load.
59 ///
60 bool haveEqualValueNumber(LoadInst *LI, LoadInst *LI2, AliasAnalysis &AA,
61 DominatorSet &DomSetInfo) const;
Chris Lattner28c6cf22003-06-16 12:06:41 +000062 bool haveEqualValueNumber(LoadInst *LI, StoreInst *SI, AliasAnalysis &AA,
63 DominatorSet &DomSetInfo) const;
Chris Lattner71c7ec92002-08-30 20:28:10 +000064 };
65
66 // Register this pass...
67 RegisterOpt<LoadVN> X("load-vn", "Load Value Numbering");
68
69 // Declare that we implement the ValueNumbering interface
70 RegisterAnalysisGroup<ValueNumbering, LoadVN> Y;
71}
72
Chris Lattner270db362004-02-05 05:51:40 +000073Pass *llvm::createLoadValueNumberingPass() { return new LoadVN(); }
Chris Lattner71c7ec92002-08-30 20:28:10 +000074
75
76/// getAnalysisUsage - Does not modify anything. It uses Value Numbering and
77/// Alias Analysis.
78///
79void LoadVN::getAnalysisUsage(AnalysisUsage &AU) const {
80 AU.setPreservesAll();
81 AU.addRequired<AliasAnalysis>();
82 AU.addRequired<ValueNumbering>();
83 AU.addRequired<DominatorSet>();
Chris Lattnerf98d8d82003-02-26 19:27:35 +000084 AU.addRequired<TargetData>();
Chris Lattner71c7ec92002-08-30 20:28:10 +000085}
86
87// getEqualNumberNodes - Return nodes with the same value number as the
88// specified Value. This fills in the argument vector with any equal values.
89//
90void LoadVN::getEqualNumberNodes(Value *V,
91 std::vector<Value*> &RetVals) const {
Chris Lattneraed2c6d2003-06-29 00:53:34 +000092 // If the alias analysis has any must alias information to share with us, we
Misha Brukman7bc439a2003-09-11 15:31:17 +000093 // can definitely use it.
Chris Lattneraed2c6d2003-06-29 00:53:34 +000094 if (isa<PointerType>(V->getType()))
95 getAnalysis<AliasAnalysis>().getMustAliases(V, RetVals);
Chris Lattner71c7ec92002-08-30 20:28:10 +000096
Chris Lattner57ef9a22004-02-05 05:56:23 +000097 if (!isa<LoadInst>(V)) {
98 // Not a load instruction? Just chain to the base value numbering
99 // implementation to satisfy the request...
Chris Lattner71c7ec92002-08-30 20:28:10 +0000100 assert(&getAnalysis<ValueNumbering>() != (ValueNumbering*)this &&
101 "getAnalysis() returned this!");
102
Chris Lattner71c7ec92002-08-30 20:28:10 +0000103 return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
104 }
Chris Lattner57ef9a22004-02-05 05:56:23 +0000105
106 // Volatile loads cannot be replaced with the value of other loads.
107 LoadInst *LI = cast<LoadInst>(V);
108 if (LI->isVolatile())
109 return getAnalysis<ValueNumbering>().getEqualNumberNodes(V, RetVals);
110
111 // If we have a load instruction, find all of the load and store instructions
112 // that use the same source operand. We implement this recursively, because
113 // there could be a load of a load of a load that are all identical. We are
114 // guaranteed that this cannot be an infinite recursion because load
115 // instructions would have to pass through a PHI node in order for there to be
116 // a cycle. The PHI node would be handled by the else case here, breaking the
117 // infinite recursion.
118 //
119 std::vector<Value*> PointerSources;
120 getEqualNumberNodes(LI->getOperand(0), PointerSources);
121 PointerSources.push_back(LI->getOperand(0));
122
123 Function *F = LI->getParent()->getParent();
124
125 // Now that we know the set of equivalent source pointers for the load
126 // instruction, look to see if there are any load or store candidates that are
127 // identical.
128 //
129 std::vector<LoadInst*> CandidateLoads;
130 std::vector<StoreInst*> CandidateStores;
131
132 while (!PointerSources.empty()) {
133 Value *Source = PointerSources.back();
134 PointerSources.pop_back(); // Get a source pointer...
135
136 for (Value::use_iterator UI = Source->use_begin(), UE = Source->use_end();
137 UI != UE; ++UI)
138 if (LoadInst *Cand = dyn_cast<LoadInst>(*UI)) {// Is a load of source?
139 if (Cand->getParent()->getParent() == F && // In the same function?
140 Cand != LI && !Cand->isVolatile()) // Not LI itself?
141 CandidateLoads.push_back(Cand); // Got one...
142 } else if (StoreInst *Cand = dyn_cast<StoreInst>(*UI)) {
143 if (Cand->getParent()->getParent() == F && !Cand->isVolatile() &&
144 Cand->getOperand(1) == Source) // It's a store THROUGH the ptr...
145 CandidateStores.push_back(Cand);
146 }
147 }
148
149 // Get Alias Analysis...
150 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
151 DominatorSet &DomSetInfo = getAnalysis<DominatorSet>();
152
153 // Loop over all of the candidate loads. If they are not invalidated by
154 // stores or calls between execution of them and LI, then add them to RetVals.
155 for (unsigned i = 0, e = CandidateLoads.size(); i != e; ++i)
156 if (haveEqualValueNumber(LI, CandidateLoads[i], AA, DomSetInfo))
157 RetVals.push_back(CandidateLoads[i]);
158 for (unsigned i = 0, e = CandidateStores.size(); i != e; ++i)
159 if (haveEqualValueNumber(LI, CandidateStores[i], AA, DomSetInfo))
160 RetVals.push_back(CandidateStores[i]->getOperand(0));
161
Chris Lattner71c7ec92002-08-30 20:28:10 +0000162}
163
164// CheckForInvalidatingInst - Return true if BB or any of the predecessors of BB
165// (until DestBB) contain an instruction that might invalidate Ptr.
166//
167static bool CheckForInvalidatingInst(BasicBlock *BB, BasicBlock *DestBB,
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000168 Value *Ptr, unsigned Size,
169 AliasAnalysis &AA,
Chris Lattner71c7ec92002-08-30 20:28:10 +0000170 std::set<BasicBlock*> &VisitedSet) {
171 // Found the termination point!
172 if (BB == DestBB || VisitedSet.count(BB)) return false;
173
174 // Avoid infinite recursion!
175 VisitedSet.insert(BB);
176
177 // Can this basic block modify Ptr?
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000178 if (AA.canBasicBlockModify(*BB, Ptr, Size))
Chris Lattner71c7ec92002-08-30 20:28:10 +0000179 return true;
180
181 // Check all of our predecessor blocks...
182 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000183 if (CheckForInvalidatingInst(*PI, DestBB, Ptr, Size, AA, VisitedSet))
Chris Lattner71c7ec92002-08-30 20:28:10 +0000184 return true;
185
186 // None of our predecessor blocks contain an invalidating instruction, and we
187 // don't either!
188 return false;
189}
190
191
192/// haveEqualValueNumber - Given two load instructions, determine if they both
193/// produce the same value on every execution of the program, assuming that
194/// their source operands always give the same value. This uses the
195/// AliasAnalysis implementation to invalidate loads when stores or function
196/// calls occur that could modify the value produced by the load.
197///
198bool LoadVN::haveEqualValueNumber(LoadInst *L1, LoadInst *L2,
199 AliasAnalysis &AA,
200 DominatorSet &DomSetInfo) const {
Chris Lattneradf9b902004-02-05 00:36:43 +0000201 assert(L1 != L2 && "haveEqualValueNumber assumes differing loads!");
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000202 assert(L1->getType() == L2->getType() &&
203 "How could the same source pointer return different types?");
Chris Lattneradf9b902004-02-05 00:36:43 +0000204 Value *LoadAddress = L1->getOperand(0);
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000205
206 // Find out how many bytes of memory are loaded by the load instruction...
207 unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(L1->getType());
208
Chris Lattneradf9b902004-02-05 00:36:43 +0000209 // If the two loads are in the same basic block, just do a local analysis.
210 if (L1->getParent() == L2->getParent()) {
211 // It can be _very_ expensive to determine which instruction occurs first in
212 // the basic block if the block is large (see PR209). For this reason,
213 // instead of figuring out which block is first, then scanning all of the
214 // instructions, we scan the instructions both ways from L1 until we find
215 // L2. Along the way if we find a potentially modifying instruction, we
216 // kill the search. This helps in cases where we have large blocks the have
217 // potentially modifying instructions in them which stop the search.
Chris Lattner71c7ec92002-08-30 20:28:10 +0000218
Chris Lattneradf9b902004-02-05 00:36:43 +0000219 BasicBlock *BB = L1->getParent();
220 BasicBlock::iterator UpIt = L1, DownIt = L1; ++DownIt;
221 bool NoModifiesUp = true, NoModifiesDown = true;
222
223 // Scan up and down looking for L2, a modifying instruction, or the end of a
224 // basic block.
225 while (UpIt != BB->begin() && DownIt != BB->end()) {
226 // Scan up...
227 --UpIt;
228 if (&*UpIt == L2)
229 return NoModifiesUp; // No instructions invalidate the loads!
230 if (NoModifiesUp)
231 NoModifiesUp &=
232 !(AA.getModRefInfo(UpIt, LoadAddress, LoadSize) & AliasAnalysis::Mod);
233
234 if (&*DownIt == L2)
235 return NoModifiesDown;
236 if (NoModifiesDown)
237 NoModifiesDown &=
238 !(AA.getModRefInfo(DownIt, LoadAddress, LoadSize)
239 & AliasAnalysis::Mod);
240 ++DownIt;
241 }
242
243 // If we got here, we ran into one end of the basic block or the other.
244 if (UpIt != BB->begin()) {
245 // If we know that the upward scan found a modifier, return false.
246 if (!NoModifiesUp) return false;
247
248 // Otherwise, continue the scan looking for a modifier or L2.
249 for (--UpIt; &*UpIt != L2; --UpIt)
250 if (AA.getModRefInfo(UpIt, LoadAddress, LoadSize) & AliasAnalysis::Mod)
251 return false;
252 return true;
253 } else {
254 // If we know that the downward scan found a modifier, return false.
Tanya Lattner1ad5bc52004-02-05 04:45:21 +0000255 assert(DownIt != BB->end() && "Didn't find instructions??");
Chris Lattneradf9b902004-02-05 00:36:43 +0000256 if (!NoModifiesDown) return false;
257
258 // Otherwise, continue the scan looking for a modifier or L2.
259 for (; &*DownIt != L2; ++DownIt) {
260 if (AA.getModRefInfo(DownIt, LoadAddress, LoadSize) &AliasAnalysis::Mod)
261 return false;
262 }
263 return true;
264 }
Chris Lattner71c7ec92002-08-30 20:28:10 +0000265 } else {
Chris Lattneradf9b902004-02-05 00:36:43 +0000266 // Figure out which load dominates the other one. If neither dominates the
267 // other we cannot eliminate them.
268 //
269 // FIXME: This could be enhanced greatly!
270 //
271 if (DomSetInfo.dominates(L2, L1))
272 std::swap(L1, L2); // Make L1 dominate L2
273 else if (!DomSetInfo.dominates(L1, L2))
274 return false; // Neither instruction dominates the other one...
275
276 BasicBlock *BB1 = L1->getParent(), *BB2 = L2->getParent();
277
278 // L1 now dominates L2. Check to see if the intervening instructions
279 // between the two loads might modify the loaded location.
280
281 // Make sure that there are no modifying instructions between L1 and the end
282 // of its basic block.
Chris Lattner71c7ec92002-08-30 20:28:10 +0000283 //
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000284 if (AA.canInstructionRangeModify(*L1, *BB1->getTerminator(), LoadAddress,
285 LoadSize))
Chris Lattner71c7ec92002-08-30 20:28:10 +0000286 return false; // Cannot eliminate load
287
Chris Lattneradf9b902004-02-05 00:36:43 +0000288 // Make sure that there are no modifying instructions between the start of
289 // BB2 and the second load instruction.
Chris Lattner71c7ec92002-08-30 20:28:10 +0000290 //
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000291 if (AA.canInstructionRangeModify(BB2->front(), *L2, LoadAddress, LoadSize))
Chris Lattner71c7ec92002-08-30 20:28:10 +0000292 return false; // Cannot eliminate load
293
294 // Do a depth first traversal of the inverse CFG starting at L2's block,
295 // looking for L1's block. The inverse CFG is made up of the predecessor
296 // nodes of a block... so all of the edges in the graph are "backward".
297 //
298 std::set<BasicBlock*> VisitedSet;
299 for (pred_iterator PI = pred_begin(BB2), PE = pred_end(BB2); PI != PE; ++PI)
Chris Lattnerf98d8d82003-02-26 19:27:35 +0000300 if (CheckForInvalidatingInst(*PI, BB1, LoadAddress, LoadSize, AA,
301 VisitedSet))
Chris Lattner71c7ec92002-08-30 20:28:10 +0000302 return false;
Chris Lattneradf9b902004-02-05 00:36:43 +0000303
Chris Lattner71c7ec92002-08-30 20:28:10 +0000304 // If we passed all of these checks then we are sure that the two loads
305 // produce the same value.
306 return true;
307 }
308}
Chris Lattner28c6cf22003-06-16 12:06:41 +0000309
310
311/// haveEqualValueNumber - Given a load instruction and a store instruction,
312/// determine if the stored value reaches the loaded value unambiguously on
313/// every execution of the program. This uses the AliasAnalysis implementation
314/// to invalidate the stored value when stores or function calls occur that
315/// could modify the value produced by the load.
316///
317bool LoadVN::haveEqualValueNumber(LoadInst *Load, StoreInst *Store,
318 AliasAnalysis &AA,
319 DominatorSet &DomSetInfo) const {
320 // If the store does not dominate the load, we cannot do anything...
321 if (!DomSetInfo.dominates(Store, Load))
322 return false;
323
324 BasicBlock *BB1 = Store->getParent(), *BB2 = Load->getParent();
325 Value *LoadAddress = Load->getOperand(0);
326
327 assert(LoadAddress->getType() == Store->getOperand(1)->getType() &&
328 "How could the same source pointer return different types?");
329
330 // Find out how many bytes of memory are loaded by the load instruction...
331 unsigned LoadSize = getAnalysis<TargetData>().getTypeSize(Load->getType());
332
333 // Compute a basic block iterator pointing to the instruction after the store.
334 BasicBlock::iterator StoreIt = Store; ++StoreIt;
335
336 // Check to see if the intervening instructions between the two store and load
337 // include a store or call...
338 //
339 if (BB1 == BB2) { // In same basic block?
340 // In this degenerate case, no checking of global basic blocks has to occur
341 // just check the instructions BETWEEN Store & Load...
342 //
343 if (AA.canInstructionRangeModify(*StoreIt, *Load, LoadAddress, LoadSize))
344 return false; // Cannot eliminate load
345
346 // No instructions invalidate the stored value, they produce the same value!
347 return true;
348 } else {
349 // Make sure that there are no store instructions between the Store and the
350 // end of its basic block...
351 //
352 if (AA.canInstructionRangeModify(*StoreIt, *BB1->getTerminator(),
353 LoadAddress, LoadSize))
354 return false; // Cannot eliminate load
355
356 // Make sure that there are no store instructions between the start of BB2
357 // and the second load instruction...
358 //
359 if (AA.canInstructionRangeModify(BB2->front(), *Load, LoadAddress,LoadSize))
360 return false; // Cannot eliminate load
361
362 // Do a depth first traversal of the inverse CFG starting at L2's block,
363 // looking for L1's block. The inverse CFG is made up of the predecessor
364 // nodes of a block... so all of the edges in the graph are "backward".
365 //
366 std::set<BasicBlock*> VisitedSet;
367 for (pred_iterator PI = pred_begin(BB2), PE = pred_end(BB2); PI != PE; ++PI)
368 if (CheckForInvalidatingInst(*PI, BB1, LoadAddress, LoadSize, AA,
369 VisitedSet))
370 return false;
371
372 // If we passed all of these checks then we are sure that the two loads
373 // produce the same value.
374 return true;
375 }
376}