llvm.org GIT mirror llvm / 3688f26
Remove GCSE, ValueNumbering, and LoadValueNumbering. These have been deprecated for almost a year; it's finally time for them to go away. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@54822 91177308-0d34-0410-b5e6-96231b3b80d8 Owen Anderson 11 years ago
10 changed file(s) with 0 addition(s) and 1153 deletion(s). Raw diff Collapse all Expand all
+0
-35
include/llvm/Analysis/LoadValueNumbering.h less more
None //===- llvm/Analysis/LoadValueNumbering.h - Value # Load Insts --*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines a value numbering pass that value #'s load instructions.
10 // To do this, it finds lexically identical load instructions, and uses alias
11 // analysis to determine which loads are guaranteed to produce the same value.
12 //
13 // This pass builds off of another value numbering pass to implement value
14 // numbering for non-load instructions. It uses Alias Analysis so that it can
15 // disambiguate the load instructions. The more powerful these base analyses
16 // are, the more powerful the resultant analysis will be.
17 //
18 //===----------------------------------------------------------------------===//
19
20 #ifndef LLVM_ANALYSIS_LOAD_VALUE_NUMBERING_H
21 #define LLVM_ANALYSIS_LOAD_VALUE_NUMBERING_H
22
23 namespace llvm {
24
25 class FunctionPass;
26
27 /// createLoadValueNumberingPass - Create and return a new pass that implements
28 /// the ValueNumbering interface.
29 ///
30 FunctionPass *createLoadValueNumberingPass();
31
32 } // End llvm namespace
33
34 #endif
7878
7979 //===--------------------------------------------------------------------===//
8080 //
81 // createBasicVNPass - This pass walks SSA def-use chains to trivially
82 // identify lexically identical expressions.
83 //
84 ImmutablePass *createBasicVNPass();
85
86 //===--------------------------------------------------------------------===//
87 //
8881 // createProfileLoaderPass - This pass loads information from a profile dump
8982 // file.
9083 //
+0
-75
include/llvm/Analysis/ValueNumbering.h less more
None //===- llvm/Analysis/ValueNumbering.h - Value #'ing Interface ---*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the abstract ValueNumbering interface, which is used as the
10 // common interface used by all clients of value numbering information, and
11 // implemented by all value numbering implementations.
12 //
13 // Implementations of this interface must implement the various virtual methods,
14 // which automatically provides functionality for the entire suite of client
15 // APIs.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #ifndef LLVM_ANALYSIS_VALUE_NUMBERING_H
20 #define LLVM_ANALYSIS_VALUE_NUMBERING_H
21
22 #include
23 #include "llvm/Pass.h"
24 #include "llvm/System/IncludeFile.h"
25
26 namespace llvm {
27
28 class Value;
29 class Instruction;
30
31 struct ValueNumbering {
32 static char ID; // Class identification, replacement for typeinfo
33 virtual ~ValueNumbering(); // We want to be subclassed
34
35 /// getEqualNumberNodes - Return nodes with the same value number as the
36 /// specified Value. This fills in the argument vector with any equal values.
37 ///
38 virtual void getEqualNumberNodes(Value *V1,
39 std::vector &RetVals) const = 0;
40
41 ///===-------------------------------------------------------------------===//
42 /// Interfaces to update value numbering analysis information as the client
43 /// changes the program.
44 ///
45
46 /// deleteValue - This method should be called whenever an LLVM Value is
47 /// deleted from the program, for example when an instruction is found to be
48 /// redundant and is eliminated.
49 ///
50 virtual void deleteValue(Value *V) {}
51
52 /// copyValue - This method should be used whenever a preexisting value in the
53 /// program is copied or cloned, introducing a new value. Note that analysis
54 /// implementations should tolerate clients that use this method to introduce
55 /// the same value multiple times: if the analysis already knows about a
56 /// value, it should ignore the request.
57 ///
58 virtual void copyValue(Value *From, Value *To) {}
59
60 /// replaceWithNewValue - This method is the obvious combination of the two
61 /// above, and it provided as a helper to simplify client code.
62 ///
63 void replaceWithNewValue(Value *Old, Value *New) {
64 copyValue(Old, New);
65 deleteValue(Old);
66 }
67 };
68
69 } // End llvm namespace
70
71 // Force any file including this header to get the implementation as well
72 FORCE_DEFINING_FILE_TO_BE_LINKED(BasicValueNumbering)
73
74 #endif
1717 #include "llvm/Analysis/AliasSetTracker.h"
1818 #include "llvm/Analysis/FindUsedTypes.h"
1919 #include "llvm/Analysis/IntervalPartition.h"
20 #include "llvm/Analysis/LoadValueNumbering.h"
2120 #include "llvm/Analysis/LoopVR.h"
2221 #include "llvm/Analysis/Passes.h"
2322 #include "llvm/Analysis/PostDominators.h"
4948 (void) llvm::createStructRetPromotionPass();
5049 (void) llvm::createBasicAliasAnalysisPass();
5150 (void) llvm::createLibCallAliasAnalysisPass(0);
52 (void) llvm::createBasicVNPass();
5351 (void) llvm::createBlockPlacementPass();
5452 (void) llvm::createBlockProfilerPass();
5553 (void) llvm::createBreakCriticalEdgesPass();
6462 (void) llvm::createEdgeProfilerPass();
6563 (void) llvm::createFunctionInliningPass();
6664 (void) llvm::createFunctionProfilerPass();
67 (void) llvm::createGCSEPass();
6865 (void) llvm::createGlobalDCEPass();
6966 (void) llvm::createGlobalOptimizerPass();
7067 (void) llvm::createGlobalsModRefPass();
7673 (void) llvm::createInternalizePass(false);
7774 (void) llvm::createLCSSAPass();
7875 (void) llvm::createLICMPass();
79 (void) llvm::createLoadValueNumberingPass();
8076 (void) llvm::createLoopExtractorPass();
8177 (void) llvm::createLoopSimplifyPass();
8278 (void) llvm::createLoopStrengthReducePass();
7777
7878 //===----------------------------------------------------------------------===//
7979 //
80 // GCSE - This pass is designed to be a very quick global transformation that
81 // eliminates global common subexpressions from a function. It does this by
82 // examining the SSA value graph of the function, instead of doing slow
83 // bit-vector computations.
84 //
85 FunctionPass *createGCSEPass();
86
87 //===----------------------------------------------------------------------===//
88 //
8980 // InductionVariableSimplify - Transform induction variables in a program to all
9081 // use a single canonical induction variable per loop.
9182 //
+0
-530
lib/Analysis/LoadValueNumbering.cpp less more
None //===- LoadValueNumbering.cpp - Load Value #'ing Implementation -*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a value numbering pass that value numbers load and call
10 // instructions. To do this, it finds lexically identical load instructions,
11 // and uses alias analysis to determine which loads are guaranteed to produce
12 // the same value. To value number call instructions, it looks for calls to
13 // functions that do not write to memory which do not have intervening
14 // instructions that clobber the memory that is read from.
15 //
16 // This pass builds off of another value numbering pass to implement value
17 // numbering for non-load and non-call instructions. It uses Alias Analysis so
18 // that it can disambiguate the load instructions. The more powerful these base
19 // analyses are, the more powerful the resultant value numbering will be.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "llvm/Analysis/LoadValueNumbering.h"
24 #include "llvm/Constants.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Type.h"
29 #include "llvm/Analysis/ValueNumbering.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/Analysis/Dominators.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Target/TargetData.h"
35 #include
36 #include
37 using namespace llvm;
38
39 namespace {
40 // FIXME: This should not be a FunctionPass.
41 struct VISIBILITY_HIDDEN LoadVN : public FunctionPass, public ValueNumbering {
42 static char ID; // Class identification, replacement for typeinfo
43 LoadVN() : FunctionPass((intptr_t)&ID) {}
44
45 /// Pass Implementation stuff. This doesn't do any analysis.
46 ///
47 bool runOnFunction(Function &) { return false; }
48
49 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering
50 /// and Alias Analysis.
51 ///
52 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
53
54 /// getEqualNumberNodes - Return nodes with the same value number as the
55 /// specified Value. This fills in the argument vector with any equal
56 /// values.
57 ///
58 virtual void getEqualNumberNodes(Value *V1,
59 std::vector &RetVals) const;
60
61 /// deleteValue - This method should be called whenever an LLVM Value is
62 /// deleted from the program, for example when an instruction is found to be
63 /// redundant and is eliminated.
64 ///
65 virtual void deleteValue(Value *V) {
66 getAnalysis().deleteValue(V);
67 }
68
69 /// copyValue - This method should be used whenever a preexisting value in
70 /// the program is copied or cloned, introducing a new value. Note that
71 /// analysis implementations should tolerate clients that use this method to
72 /// introduce the same value multiple times: if the analysis already knows
73 /// about a value, it should ignore the request.
74 ///
75 virtual void copyValue(Value *From, Value *To) {
76 getAnalysis().copyValue(From, To);
77 }
78
79 /// getCallEqualNumberNodes - Given a call instruction, find other calls
80 /// that have the same value number.
81 void getCallEqualNumberNodes(CallInst *CI,
82 std::vector &RetVals) const;
83 };
84 }
85
86 char LoadVN::ID = 0;
87 // Register this pass...
88 static RegisterPass
89 X("load-vn", "Load Value Numbering", false, true);
90
91 // Declare that we implement the ValueNumbering interface
92 static RegisterAnalysisGroup Y(X);
93
94 FunctionPass *llvm::createLoadValueNumberingPass() { return new LoadVN(); }
95
96
97 /// getAnalysisUsage - Does not modify anything. It uses Value Numbering and
98 /// Alias Analysis.
99 ///
100 void LoadVN::getAnalysisUsage(AnalysisUsage &AU) const {
101 AU.setPreservesAll();
102 AU.addRequiredTransitive();
103 AU.addRequired();
104 AU.addRequiredTransitive();
105 AU.addRequiredTransitive();
106 }
107
108 static bool isPathTransparentTo(BasicBlock *CurBlock, BasicBlock *Dom,
109 Value *Ptr, unsigned Size, AliasAnalysis &AA,
110 std::set &Visited,
111 std::map &TransparentBlocks){
112 // If we have already checked out this path, or if we reached our destination,
113 // stop searching, returning success.
114 if (CurBlock == Dom || !Visited.insert(CurBlock).second)
115 return true;
116
117 // Check whether this block is known transparent or not.
118 std::map::iterator TBI =
119 TransparentBlocks.find(CurBlock);
120
121 if (TBI == TransparentBlocks.end()) {
122 // If this basic block can modify the memory location, then the path is not
123 // transparent!
124 if (AA.canBasicBlockModify(*CurBlock, Ptr, Size)) {
125 TransparentBlocks.insert(TBI, std::make_pair(CurBlock, false));
126 return false;
127 }
128 TransparentBlocks.insert(TBI, std::make_pair(CurBlock, true));
129 } else if (!TBI->second)
130 // This block is known non-transparent, so that path can't be either.
131 return false;
132
133 // The current block is known to be transparent. The entire path is
134 // transparent if all of the predecessors paths to the parent is also
135 // transparent to the memory location.
136 for (pred_iterator PI = pred_begin(CurBlock), E = pred_end(CurBlock);
137 PI != E; ++PI)
138 if (!isPathTransparentTo(*PI, Dom, Ptr, Size, AA, Visited,
139 TransparentBlocks))
140 return false;
141 return true;
142 }
143
144 /// getCallEqualNumberNodes - Given a call instruction, find other calls that
145 /// have the same value number.
146 void LoadVN::getCallEqualNumberNodes(CallInst *CI,
147 std::vector &RetVals) const {
148 Function *CF = CI->getCalledFunction();
149 if (CF == 0) return; // Indirect call.
150 AliasAnalysis &AA = getAnalysis();
151 AliasAnalysis::ModRefBehavior MRB = AA.getModRefBehavior(CI);
152 if (MRB != AliasAnalysis::DoesNotAccessMemory &&
153 MRB != AliasAnalysis::OnlyReadsMemory)
154 return; // Nothing we can do for now.
155
156 // Scan all of the arguments of the function, looking for one that is not
157 // global. In particular, we would prefer to have an argument or instruction
158 // operand to chase the def-use chains of.
159 Value *Op = CF;
160 for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end(); i != e; ++i)
161 if (isa(*i) ||
162 isa(*i)) {
163 Op = *i;
164 break;
165 }
166
167 // Identify all lexically identical calls in this function.
168 std::vector IdenticalCalls;
169
170 Function *CIFunc = CI->getParent()->getParent();
171 for (Value::use_iterator UI = Op->use_begin(), E = Op->use_end(); UI != E;
172 ++UI)
173 if (CallInst *C = dyn_cast(*UI))
174 if (C->getNumOperands() == CI->getNumOperands() &&
175 C->getOperand(0) == CI->getOperand(0) &&
176 C->getParent()->getParent() == CIFunc && C != CI) {
177 bool AllOperandsEqual = true;
178 for (User::op_iterator i = CI->op_begin() + 1, j = C->op_begin() + 1,
179 e = CI->op_end(); i != e; ++i, ++j)
180 if (*j != *i) {
181 AllOperandsEqual = false;
182 break;
183 }
184
185 if (AllOperandsEqual)
186 IdenticalCalls.push_back(C);
187 }
188
189 if (IdenticalCalls.empty()) return;
190
191 // Eliminate duplicates, which could occur if we chose a value that is passed
192 // into a call site multiple times.
193 std::sort(IdenticalCalls.begin(), IdenticalCalls.end());
194 IdenticalCalls.erase(std::unique(IdenticalCalls.begin(),IdenticalCalls.end()),
195 IdenticalCalls.end());
196
197 // If the call reads memory, we must make sure that there are no stores
198 // between the calls in question.
199 //
200 // FIXME: This should use mod/ref information. What we really care about it
201 // whether an intervening instruction could modify memory that is read, not
202 // ANY memory.
203 //
204 if (MRB == AliasAnalysis::OnlyReadsMemory) {
205 DominatorTree &DT = getAnalysis();
206 BasicBlock *CIBB = CI->getParent();
207 for (unsigned i = 0; i != IdenticalCalls.size(); ++i) {
208 CallInst *C = IdenticalCalls[i];
209 bool CantEqual = false;
210
211 if (DT.dominates(CIBB, C->getParent())) {
212 // FIXME: we currently only handle the case where both calls are in the
213 // same basic block.
214 if (CIBB != C->getParent()) {
215 CantEqual = true;
216 } else {
217 Instruction *First = CI, *Second = C;
218 if (!DT.dominates(CI, C))
219 std::swap(First, Second);
220
221 // Scan the instructions between the calls, checking for stores or
222 // calls to dangerous functions.
223 BasicBlock::iterator I = First;
224 for (++First; I != BasicBlock::iterator(Second); ++I) {
225 if (isa(I)) {
226 // FIXME: We could use mod/ref information to make this much
227 // better!
228 CantEqual = true;
229 break;
230 } else if (CallInst *CI = dyn_cast(I)) {
231 if (!AA.onlyReadsMemory(CI)) {
232 CantEqual = true;
233 break;
234 }
235 } else if (I->mayWriteToMemory()) {
236 CantEqual = true;
237 break;
238 }
239 }
240 }
241
242 } else if (DT.dominates(C->getParent(), CIBB)) {
243 // FIXME: We could implement this, but we don't for now.
244 CantEqual = true;
245 } else {
246 // FIXME: if one doesn't dominate the other, we can't tell yet.
247 CantEqual = true;
248 }
249
250
251 if (CantEqual) {
252 // This call does not produce the same value as the one in the query.
253 std::swap(IdenticalCalls[i--], IdenticalCalls.back());
254 IdenticalCalls.pop_back();
255 }
256 }
257 }
258
259 // Any calls that are identical and not destroyed will produce equal values!
260 for (unsigned i = 0, e = IdenticalCalls.size(); i != e; ++i)
261 RetVals.push_back(IdenticalCalls[i]);
262 }
263
264 // getEqualNumberNodes - Return nodes with the same value number as the
265 // specified Value. This fills in the argument vector with any equal values.
266 //
267 void LoadVN::getEqualNumberNodes(Value *V,
268 std::vector &RetVals) const {
269 // If the alias analysis has any must alias information to share with us, we
270 // can definitely use it.
271 if (isa(V->getType()))
272 getAnalysis().getMustAliases(V, RetVals);
273
274 if (!isa(V)) {
275 if (CallInst *CI = dyn_cast(V))
276 getCallEqualNumberNodes(CI, RetVals);
277
278 // Not a load instruction? Just chain to the base value numbering
279 // implementation to satisfy the request...
280 assert(&getAnalysis() != (ValueNumbering*)this &&
281 "getAnalysis() returned this!");
282
283 return getAnalysis().getEqualNumberNodes(V, RetVals);
284 }
285
286 // Volatile loads cannot be replaced with the value of other loads.
287 LoadInst *LI = cast(V);
288 if (LI->isVolatile())
289 return getAnalysis().getEqualNumberNodes(V, RetVals);
290
291 Value *LoadPtr = LI->getOperand(0);
292 BasicBlock *LoadBB = LI->getParent();
293 Function *F = LoadBB->getParent();
294
295 // Find out how many bytes of memory are loaded by the load instruction...
296 unsigned LoadSize = getAnalysis().getTypeStoreSize(LI->getType());
297 AliasAnalysis &AA = getAnalysis();
298
299 // Figure out if the load is invalidated from the entry of the block it is in
300 // until the actual instruction. This scans the block backwards from LI. If
301 // we see any candidate load or store instructions, then we know that the
302 // candidates have the same value # as LI.
303 bool LoadInvalidatedInBBBefore = false;
304 for (BasicBlock::iterator I = LI; I != LoadBB->begin(); ) {
305 --I;
306 if (I == LoadPtr) {
307 // If we run into an allocation of the value being loaded, then the
308 // contents are not initialized.
309 if (isa(I))
310 RetVals.push_back(UndefValue::get(LI->getType()));
311
312 // Otherwise, since this is the definition of what we are loading, this
313 // loaded value cannot occur before this block.
314 LoadInvalidatedInBBBefore = true;
315 break;
316 } else if (LoadInst *LI = dyn_cast(I)) {
317 // If this instruction is a candidate load before LI, we know there are no
318 // invalidating instructions between it and LI, so they have the same
319 // value number.
320 if (LI->getOperand(0) == LoadPtr && !LI->isVolatile())
321 RetVals.push_back(I);
322 }
323
324 if (AA.getModRefInfo(I, LoadPtr, LoadSize) & AliasAnalysis::Mod) {
325 // If the invalidating instruction is a store, and its in our candidate
326 // set, then we can do store-load forwarding: the load has the same value
327 // # as the stored value.
328 if (StoreInst *SI = dyn_cast(I))
329 if (SI->getOperand(1) == LoadPtr)
330 RetVals.push_back(I->getOperand(0));
331
332 LoadInvalidatedInBBBefore = true;
333 break;
334 }
335 }
336
337 // Figure out if the load is invalidated between the load and the exit of the
338 // block it is defined in. While we are scanning the current basic block, if
339 // we see any candidate loads, then we know they have the same value # as LI.
340 //
341 bool LoadInvalidatedInBBAfter = false;
342 {
343 BasicBlock::iterator I = LI;
344 for (++I; I != LoadBB->end(); ++I) {
345 // If this instruction is a load, then this instruction returns the same
346 // value as LI.
347 if (isa(I) && cast(I)->getOperand(0) == LoadPtr)
348 RetVals.push_back(I);
349
350 if (AA.getModRefInfo(I, LoadPtr, LoadSize) & AliasAnalysis::Mod) {
351 LoadInvalidatedInBBAfter = true;
352 break;
353 }
354 }
355 }
356
357 // If the pointer is clobbered on entry and on exit to the function, there is
358 // no need to do any global analysis at all.
359 if (LoadInvalidatedInBBBefore && LoadInvalidatedInBBAfter)
360 return;
361
362 // Now that we know the value is not neccesarily killed on entry or exit to
363 // the BB, find out how many load and store instructions (to this location)
364 // live in each BB in the function.
365 //
366 std::map CandidateLoads;
367 std::set CandidateStores;
368
369 for (Value::use_iterator UI = LoadPtr->use_begin(), UE = LoadPtr->use_end();
370 UI != UE; ++UI)
371 if (LoadInst *Cand = dyn_cast(*UI)) {// Is a load of source?
372 if (Cand->getParent()->getParent() == F && // In the same function?
373 // Not in LI's block?
374 Cand->getParent() != LoadBB && !Cand->isVolatile())
375 ++CandidateLoads[Cand->getParent()]; // Got one.
376 } else if (StoreInst *Cand = dyn_cast(*UI)) {
377 if (Cand->getParent()->getParent() == F && !Cand->isVolatile() &&
378 Cand->getOperand(1) == LoadPtr) // It's a store THROUGH the ptr.
379 CandidateStores.insert(Cand->getParent());
380 }
381
382 // Get dominators.
383 DominatorTree &DT = getAnalysis();
384
385 // TransparentBlocks - For each basic block the load/store is alive across,
386 // figure out if the pointer is invalidated or not. If it is invalidated, the
387 // boolean is set to false, if it's not it is set to true. If we don't know
388 // yet, the entry is not in the map.
389 std::map TransparentBlocks;
390
391 // Loop over all of the basic blocks that also load the value. If the value
392 // is live across the CFG from the source to destination blocks, and if the
393 // value is not invalidated in either the source or destination blocks, add it
394 // to the equivalence sets.
395 for (std::map::iterator
396 I = CandidateLoads.begin(), E = CandidateLoads.end(); I != E; ++I) {
397 bool CantEqual = false;
398
399 // Right now we only can handle cases where one load dominates the other.
400 // FIXME: generalize this!
401 BasicBlock *BB1 = I->first, *BB2 = LoadBB;
402 if (DT.dominates(BB1, BB2)) {
403 // The other load dominates LI. If the loaded value is killed entering
404 // the LoadBB block, we know the load is not live.
405 if (LoadInvalidatedInBBBefore)
406 CantEqual = true;
407 } else if (DT.dominates(BB2, BB1)) {
408 std::swap(BB1, BB2); // Canonicalize
409 // LI dominates the other load. If the loaded value is killed exiting
410 // the LoadBB block, we know the load is not live.
411 if (LoadInvalidatedInBBAfter)
412 CantEqual = true;
413 } else {
414 // None of these loads can VN the same.
415 CantEqual = true;
416 }
417
418 if (!CantEqual) {
419 // Ok, at this point, we know that BB1 dominates BB2, and that there is
420 // nothing in the LI block that kills the loaded value. Check to see if
421 // the value is live across the CFG.
422 std::set Visited;
423 for (pred_iterator PI = pred_begin(BB2), E = pred_end(BB2); PI!=E; ++PI)
424 if (!isPathTransparentTo(*PI, BB1, LoadPtr, LoadSize, AA,
425 Visited, TransparentBlocks)) {
426 // None of these loads can VN the same.
427 CantEqual = true;
428 break;
429 }
430 }
431
432 // If the loads can equal so far, scan the basic block that contains the
433 // loads under consideration to see if they are invalidated in the block.
434 // For any loads that are not invalidated, add them to the equivalence
435 // set!
436 if (!CantEqual) {
437 unsigned NumLoads = I->second;
438 if (BB1 == LoadBB) {
439 // If LI dominates the block in question, check to see if any of the
440 // loads in this block are invalidated before they are reached.
441 for (BasicBlock::iterator BBI = I->first->begin(); ; ++BBI) {
442 if (LoadInst *LI = dyn_cast(BBI)) {
443 if (LI->getOperand(0) == LoadPtr && !LI->isVolatile()) {
444 // The load is in the set!
445 RetVals.push_back(BBI);
446 if (--NumLoads == 0) break; // Found last load to check.
447 }
448 } else if (AA.getModRefInfo(BBI, LoadPtr, LoadSize)
449 & AliasAnalysis::Mod) {
450 // If there is a modifying instruction, nothing below it will value
451 // # the same.
452 break;
453 }
454 }
455 } else {
456 // If the block dominates LI, make sure that the loads in the block are
457 // not invalidated before the block ends.
458 BasicBlock::iterator BBI = I->first->end();
459 while (1) {
460 --BBI;
461 if (LoadInst *LI = dyn_cast(BBI)) {
462 if (LI->getOperand(0) == LoadPtr && !LI->isVolatile()) {
463 // The load is the same as this load!
464 RetVals.push_back(BBI);
465 if (--NumLoads == 0) break; // Found all of the laods.
466 }
467 } else if (AA.getModRefInfo(BBI, LoadPtr, LoadSize)
468 & AliasAnalysis::Mod) {
469 // If there is a modifying instruction, nothing above it will value
470 // # the same.
471 break;
472 }
473 }
474 }
475 }
476 }
477
478 // Handle candidate stores. If the loaded location is clobbered on entrance
479 // to the LoadBB, no store outside of the LoadBB can value number equal, so
480 // quick exit.
481 if (LoadInvalidatedInBBBefore)
482 return;
483
484 // Stores in the load-bb are handled above.
485 CandidateStores.erase(LoadBB);
486
487 for (std::set::iterator I = CandidateStores.begin(),
488 E = CandidateStores.end(); I != E; ++I)
489 if (DT.dominates(*I, LoadBB)) {
490 BasicBlock *StoreBB = *I;
491
492 // Check to see if the path from the store to the load is transparent
493 // w.r.t. the memory location.
494 bool CantEqual = false;
495 std::set Visited;
496 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
497 PI != E; ++PI)
498 if (!isPathTransparentTo(*PI, StoreBB, LoadPtr, LoadSize, AA,
499 Visited, TransparentBlocks)) {
500 // None of these stores can VN the same.
501 CantEqual = true;
502 break;
503 }
504 Visited.clear();
505 if (!CantEqual) {
506 // Okay, the path from the store block to the load block is clear, and
507 // we know that there are no invalidating instructions from the start
508 // of the load block to the load itself. Now we just scan the store
509 // block.
510
511 BasicBlock::iterator BBI = StoreBB->end();
512 while (1) {
513 assert(BBI != StoreBB->begin() &&
514 "There is a store in this block of the pointer, but the store"
515 " doesn't mod the address being stored to?? Must be a bug in"
516 " the alias analysis implementation!");
517 --BBI;
518 if (AA.getModRefInfo(BBI, LoadPtr, LoadSize) & AliasAnalysis::Mod) {
519 // If the invalidating instruction is one of the candidates,
520 // then it provides the value the load loads.
521 if (StoreInst *SI = dyn_cast(BBI))
522 if (SI->getOperand(1) == LoadPtr)
523 RetVals.push_back(SI->getOperand(0));
524 break;
525 }
526 }
527 }
528 }
529 }
+0
-286
lib/Analysis/ValueNumbering.cpp less more
None //===- ValueNumbering.cpp - Value #'ing Implementation ----------*- C++ -*-===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the non-abstract Value Numbering methods as well as a
10 // default implementation for the analysis group.
11 //
12 // The ValueNumbering analysis pass is mostly deprecated. It is only used by the
13 // Global Common Subexpression Elimination pass, which is deprecated by the
14 // Global Value Numbering pass (which does its value numbering on its own).
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Analysis/Passes.h"
19 #include "llvm/Analysis/ValueNumbering.h"
20 #include "llvm/Support/InstVisitor.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Type.h"
25 #include "llvm/Support/Compiler.h"
26 using namespace llvm;
27
28 char ValueNumbering::ID = 0;
29 // Register the ValueNumbering interface, providing a nice name to refer to.
30 static RegisterAnalysisGroup V("Value Numbering");
31
32 /// ValueNumbering destructor: DO NOT move this to the header file for
33 /// ValueNumbering or else clients of the ValueNumbering class may not depend on
34 /// the ValueNumbering.o file in the current .a file, causing alias analysis
35 /// support to not be included in the tool correctly!
36 ///
37 ValueNumbering::~ValueNumbering() {}
38
39 //===----------------------------------------------------------------------===//
40 // Basic ValueNumbering Pass Implementation
41 //===----------------------------------------------------------------------===//
42 //
43 // Because of the way .a files work, the implementation of the BasicVN class
44 // MUST be in the ValueNumbering file itself, or else we run the risk of
45 // ValueNumbering being used, but the default implementation not being linked
46 // into the tool that uses it. As such, we register and implement the class
47 // here.
48 //
49
50 namespace {
51 /// BasicVN - This class is the default implementation of the ValueNumbering
52 /// interface. It walks the SSA def-use chains to trivially identify
53 /// lexically identical expressions. This does not require any ahead of time
54 /// analysis, so it is a very fast default implementation.
55 ///
56 struct VISIBILITY_HIDDEN BasicVN
57 : public ImmutablePass, public ValueNumbering {
58 static char ID; // Class identification, replacement for typeinfo
59 BasicVN() : ImmutablePass((intptr_t)&ID) {}
60
61 /// getEqualNumberNodes - Return nodes with the same value number as the
62 /// specified Value. This fills in the argument vector with any equal
63 /// values.
64 ///
65 /// This is where our implementation is.
66 ///
67 virtual void getEqualNumberNodes(Value *V1,
68 std::vector &RetVals) const;
69 };
70 }
71
72 char BasicVN::ID = 0;
73 // Register this pass...
74 static RegisterPass
75 X("basicvn", "Basic Value Numbering (default GVN impl)", false, true);
76
77 // Declare that we implement the ValueNumbering interface
78 static RegisterAnalysisGroup Y(X);
79
80 namespace {
81 /// BVNImpl - Implement BasicVN in terms of a visitor class that
82 /// handles the different types of instructions as appropriate.
83 ///
84 struct VISIBILITY_HIDDEN BVNImpl : public InstVisitor {
85 std::vector &RetVals;
86 explicit BVNImpl(std::vector &RV) : RetVals(RV) {}
87
88 void visitCastInst(CastInst &I);
89 void visitGetElementPtrInst(GetElementPtrInst &I);
90 void visitCmpInst(CmpInst &I);
91
92 void handleBinaryInst(Instruction &I);
93 void visitBinaryOperator(Instruction &I) { handleBinaryInst(I); }
94 void visitShiftInst(Instruction &I) { handleBinaryInst(I); }
95 void visitExtractElementInst(Instruction &I) { handleBinaryInst(I); }
96
97 void handleTernaryInst(Instruction &I);
98 void visitSelectInst(Instruction &I) { handleTernaryInst(I); }
99 void visitInsertElementInst(Instruction &I) { handleTernaryInst(I); }
100 void visitShuffleVectorInst(Instruction &I) { handleTernaryInst(I); }
101 void visitInstruction(Instruction &) {
102 // Cannot value number calls or terminator instructions.
103 }
104 };
105 }
106
107 ImmutablePass *llvm::createBasicVNPass() { return new BasicVN(); }
108
109 // getEqualNumberNodes - Return nodes with the same value number as the
110 // specified Value. This fills in the argument vector with any equal values.
111 //
112 void BasicVN::getEqualNumberNodes(Value *V, std::vector &RetVals) const{
113 assert(V->getType() != Type::VoidTy &&
114 "Can only value number non-void values!");
115 // We can only handle the case where I is an instruction!
116 if (Instruction *I = dyn_cast(V))
117 BVNImpl(RetVals).visit(I);
118 }
119
120 void BVNImpl::visitCastInst(CastInst &CI) {
121 Instruction &I = (Instruction&)CI;
122 Value *Op = I.getOperand(0);
123 Function *F = I.getParent()->getParent();
124
125 for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
126 UI != UE; ++UI)
127 if (CastInst *Other = dyn_cast(*UI))
128 // Check that the opcode is the same
129 if (Other->getOpcode() == Instruction::CastOps(I.getOpcode()) &&
130 // Check that the destination types are the same
131 Other->getType() == I.getType() &&
132 // Is it embedded in the same function? (This could be false if LHS
133 // is a constant or global!)
134 Other->getParent()->getParent() == F &&
135 // Check to see if this new cast is not I.
136 Other != &I) {
137 // These instructions are identical. Add to list...
138 RetVals.push_back(Other);
139 }
140 }
141
142 void BVNImpl::visitCmpInst(CmpInst &CI1) {
143 Value *LHS = CI1.getOperand(0);
144 for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
145 UI != UE; ++UI)
146 if (CmpInst *CI2 = dyn_cast(*UI))
147 // Check to see if this compare instruction is not CI, but same opcode,
148 // same predicate, and in the same function.
149 if (CI2 != &CI1 && CI2->getOpcode() == CI1.getOpcode() &&
150 CI2->getPredicate() == CI1.getPredicate() &&
151 CI2->getParent()->getParent() == CI1.getParent()->getParent())
152 // If the operands are the same
153 if ((CI2->getOperand(0) == CI1.getOperand(0) &&
154 CI2->getOperand(1) == CI1.getOperand(1)) ||
155 // Or the compare is commutative and the operands are reversed
156 (CI1.isCommutative() &&
157 CI2->getOperand(0) == CI1.getOperand(1) &&
158 CI2->getOperand(1) == CI1.getOperand(0)))
159 // Then the instructiosn are identical, add to list.
160 RetVals.push_back(CI2);
161 }
162
163
164
165 // isIdenticalBinaryInst - Return true if the two binary instructions are
166 // identical.
167 //
168 static inline bool isIdenticalBinaryInst(const Instruction &I1,
169 const Instruction *I2) {
170 // Is it embedded in the same function? (This could be false if LHS
171 // is a constant or global!)
172 if (I1.getOpcode() != I2->getOpcode() ||
173 I1.getParent()->getParent() != I2->getParent()->getParent())
174 return false;
175
176 // If they are CmpInst instructions, check their predicates
177 if (CmpInst *CI1 = dyn_cast(&const_cast(I1)))
178 if (CI1->getPredicate() != cast(I2)->getPredicate())
179 return false;
180
181 // They are identical if both operands are the same!
182 if (I1.getOperand(0) == I2->getOperand(0) &&
183 I1.getOperand(1) == I2->getOperand(1))
184 return true;
185
186 // If the instruction is commutative, the instruction can match if the
187 // operands are swapped!
188 //
189 if ((I1.getOperand(0) == I2->getOperand(1) &&
190 I1.getOperand(1) == I2->getOperand(0)) &&
191 I1.isCommutative())
192 return true;
193
194 return false;
195 }
196
197 // isIdenticalTernaryInst - Return true if the two ternary instructions are
198 // identical.
199 //
200 static inline bool isIdenticalTernaryInst(const Instruction &I1,
201 const Instruction *I2) {
202 // Is it embedded in the same function? (This could be false if LHS
203 // is a constant or global!)
204 if (I1.getParent()->getParent() != I2->getParent()->getParent())
205 return false;
206
207 // They are identical if all operands are the same!
208 return I1.getOperand(0) == I2->getOperand(0) &&
209 I1.getOperand(1) == I2->getOperand(1) &&
210 I1.getOperand(2) == I2->getOperand(2);
211 }
212
213
214
215 void BVNImpl::handleBinaryInst(Instruction &I) {
216 Value *LHS = I.getOperand(0);
217
218 for (Value::use_iterator UI = LHS->use_begin(), UE = LHS->use_end();
219 UI != UE; ++UI)
220 if (Instruction *Other = dyn_cast(*UI))
221 // Check to see if this new binary operator is not I, but same operand...
222 if (Other != &I && isIdenticalBinaryInst(I, Other)) {
223 // These instructions are identical. Handle the situation.
224 RetVals.push_back(Other);
225 }
226 }
227
228 // IdenticalComplexInst - Return true if the two instructions are the same, by
229 // using a brute force comparison. This is useful for instructions with an
230 // arbitrary number of arguments.
231 //
232 static inline bool IdenticalComplexInst(const Instruction *I1,
233 const Instruction *I2) {
234 assert(I1->getOpcode() == I2->getOpcode());
235 // Equal if they are in the same function...
236 return I1->getParent()->getParent() == I2->getParent()->getParent() &&
237 // And return the same type...
238 I1->getType() == I2->getType() &&
239 // And have the same number of operands...
240 I1->getNumOperands() == I2->getNumOperands() &&
241 // And all of the operands are equal.
242 std::equal(I1->op_begin(), I1->op_end(), I2->op_begin());
243 }
244
245 void BVNImpl::visitGetElementPtrInst(GetElementPtrInst &I) {
246 Value *Op = I.getOperand(0);
247
248 // Try to pick a local operand if possible instead of a constant or a global
249 // that might have a lot of uses.
250 for (User::op_iterator i = I.op_begin() + 1, e = I.op_end(); i != e; ++i)
251 if (isa(*i) || isa(*i)) {
252 Op = *i;
253 break;
254 }
255
256 for (Value::use_iterator UI = Op->use_begin(), UE = Op->use_end();
257 UI != UE; ++UI)
258 if (GetElementPtrInst *Other = dyn_cast(*UI))
259 // Check to see if this new getelementptr is not I, but same operand...
260 if (Other != &I && IdenticalComplexInst(&I, Other)) {
261 // These instructions are identical. Handle the situation.
262 RetVals.push_back(Other);
263 }
264 }
265
266 void BVNImpl::handleTernaryInst(Instruction &I) {
267 Value *Op0 = I.getOperand(0);
268 Instruction *OtherInst;
269
270 for (Value::use_iterator UI = Op0->use_begin(), UE = Op0->use_end();
271 UI != UE; ++UI)
272 if ((OtherInst = dyn_cast(*UI)) &&
273 OtherInst->getOpcode() == I.getOpcode()) {
274 // Check to see if this new select is not I, but has the same operands.
275 if (OtherInst != &I && isIdenticalTernaryInst(I, OtherInst)) {
276 // These instructions are identical. Handle the situation.
277 RetVals.push_back(OtherInst);
278 }
279
280 }
281 }
282
283
284 // Ensure that users of ValueNumbering.h will link with this file
285 DEFINING_FILE_FOR(BasicValueNumbering)
+0
-205
lib/Transforms/Scalar/GCSE.cpp less more
None //===-- GCSE.cpp - SSA-based Global Common Subexpression Elimination ------===//
1 //
2 // The LLVM Compiler Infrastructure
3 //
4 // This file is distributed under the University of Illinois Open Source
5 // License. See LICENSE.TXT for details.
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass is designed to be a very quick global transformation that
10 // eliminates global common subexpressions from a function. It does this by
11 // using an existing value numbering analysis pass to identify the common
12 // subexpressions, eliminating them when possible.
13 //
14 // This pass is deprecated by the Global Value Numbering pass (which does a
15 // better job with its own value numbering).
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "gcse"
20 #include "llvm/Transforms/Scalar.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Function.h"
23 #include "llvm/Type.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/ValueNumbering.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Support/Compiler.h"
30 #include
31 using namespace llvm;
32
33 STATISTIC(NumInstRemoved, "Number of instructions removed");
34 STATISTIC(NumLoadRemoved, "Number of loads removed");
35 STATISTIC(NumCallRemoved, "Number of calls removed");
36 STATISTIC(NumNonInsts , "Number of instructions removed due "
37 "to non-instruction values");
38 STATISTIC(NumArgsRepl , "Number of function arguments replaced "
39 "with constant values");
40 namespace {
41 struct VISIBILITY_HIDDEN GCSE : public FunctionPass {
42 static char ID; // Pass identification, replacement for typeid
43 GCSE() : FunctionPass((intptr_t)&ID) {}
44
45 virtual bool runOnFunction(Function &F);
46
47 private:
48 void ReplaceInstructionWith(Instruction *I, Value *V);
49
50 // This transformation requires dominator and immediate dominator info
51 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
52 AU.setPreservesCFG();
53 AU.addRequired();
54 AU.addRequired();
55 }
56 };
57 }
58
59 char GCSE::ID = 0;
60 static RegisterPass
61 X("gcse", "Global Common Subexpression Elimination");
62
63 // createGCSEPass - The public interface to this file...
64 FunctionPass *llvm::createGCSEPass() { return new GCSE(); }
65
66 // GCSE::runOnFunction - This is the main transformation entry point for a
67 // function.
68 //
69 bool GCSE::runOnFunction(Function &F) {
70 bool Changed = false;
71
72 // Get pointers to the analysis results that we will be using...
73 DominatorTree &DT = getAnalysis();
74 ValueNumbering &VN = getAnalysis();
75
76 std::vector EqualValues;
77
78 // Check for value numbers of arguments. If the value numbering
79 // implementation can prove that an incoming argument is a constant or global
80 // value address, substitute it, making the argument dead.
81 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
82 if (!AI->use_empty()) {
83 VN.getEqualNumberNodes(AI, EqualValues);
84 if (!EqualValues.empty()) {
85 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
86 if (isa(EqualValues[i])) {
87 AI->replaceAllUsesWith(EqualValues[i]);
88 ++NumArgsRepl;
89 Changed = true;
90 break;
91 }
92 EqualValues.clear();
93 }
94 }
95
96 // Traverse the CFG of the function in dominator order, so that we see each
97 // instruction after we see its operands.
98 for (df_iterator DI = df_begin(DT.getRootNode()),
99 E = df_end(DT.getRootNode()); DI != E; ++DI) {
100 BasicBlock *BB = DI->getBlock();
101
102 // Remember which instructions we've seen in this basic block as we scan.
103 std::set BlockInsts;
104
105 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
106 Instruction *Inst = I++;
107
108 if (Constant *C = ConstantFoldInstruction(Inst)) {
109 ReplaceInstructionWith(Inst, C);
110 } else if (Inst->getType() != Type::VoidTy) {
111 // If this instruction computes a value, try to fold together common
112 // instructions that compute it.
113 //
114 VN.getEqualNumberNodes(Inst, EqualValues);
115
116 // If this instruction computes a value that is already computed
117 // elsewhere, try to recycle the old value.
118 if (!EqualValues.empty()) {
119 if (Inst == &*BB->begin())
120 I = BB->end();
121 else {
122 I = Inst; --I;
123 }
124
125 // First check to see if we were able to value number this instruction
126 // to a non-instruction value. If so, prefer that value over other
127 // instructions which may compute the same thing.
128 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i)
129 if (!isa(EqualValues[i])) {
130 ++NumNonInsts; // Keep track of # of insts repl with values
131
132 // Change all users of Inst to use the replacement and remove it
133 // from the program.
134 ReplaceInstructionWith(Inst, EqualValues[i]);
135 Inst = 0;
136 EqualValues.clear(); // don't enter the next loop
137 break;
138 }
139
140 // If there were no non-instruction values that this instruction
141 // produces, find a dominating instruction that produces the same
142 // value. If we find one, use it's value instead of ours.
143 for (unsigned i = 0, e = EqualValues.size(); i != e; ++i) {
144 Instruction *OtherI = cast(EqualValues[i]);
145 bool Dominates = false;
146 if (OtherI->getParent() == BB)
147 Dominates = BlockInsts.count(OtherI);
148 else
149 Dominates = DT.dominates(OtherI->getParent(), BB);
150
151 if (Dominates) {
152 // Okay, we found an instruction with the same value as this one
153 // and that dominates this one. Replace this instruction with the
154 // specified one.
155 ReplaceInstructionWith(Inst, OtherI);
156 Inst = 0;
157 break;
158 }
159 }
160
161 EqualValues.clear();
162
163 if (Inst) {
164 I = Inst; ++I; // Deleted no instructions
165 } else if (I == BB->end()) { // Deleted first instruction
166 I = BB->begin();
167 } else { // Deleted inst in middle of block.
168 ++I;
169 }
170 }
171
172 if (Inst)
173 BlockInsts.insert(Inst);
174 }
175 }
176 }
177
178 // When the worklist is empty, return whether or not we changed anything...
179 return Changed;
180 }
181
182
183 void GCSE::ReplaceInstructionWith(Instruction *I, Value *V) {
184 if (isa(I))
185 ++NumLoadRemoved; // Keep track of loads eliminated
186 if (isa(I))
187 ++NumCallRemoved; // Keep track of calls eliminated
188 ++NumInstRemoved; // Keep track of number of insts eliminated
189
190 // Update value numbering
191 getAnalysis().deleteValue(I);
192
193 I->replaceAllUsesWith(V);
194
195 if (InvokeInst *II = dyn_cast(I)) {
196 // Removing an invoke instruction requires adding a branch to the normal
197 // destination and removing PHI node entries in the exception destination.
198 BranchInst::Create(II->getNormalDest(), II);
199 II->getUnwindDest()->removePredecessor(II->getParent());
200 }
201
202 // Erase the instruction from the program.
203 I->eraseFromParent();
204 }
1212
1313 #include "llvm/Module.h"
1414 #include "llvm/PassManager.h"
15 #include "llvm/Analysis/LoadValueNumbering.h"
1615 #include "llvm/Analysis/Passes.h"
1716 #include "llvm/Analysis/LoopPass.h"
1817 #include "llvm/Analysis/Verifier.h"
3030 #include "llvm/Analysis/Passes.h"
3131 #include "llvm/Analysis/LoopPass.h"
3232 #include "llvm/Analysis/Verifier.h"
33 #include "llvm/Analysis/LoadValueNumbering.h"
3433 #include "llvm/CodeGen/FileWriters.h"
3534 #include "llvm/Target/SubtargetFeature.h"
3635 #include "llvm/Target/TargetOptions.h"