1 //===- GVN.cpp - Eliminate redundant values and loads ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the Owen Anderson and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs global value numbering to eliminate fully redundant
11 // instructions. It also performs simple dead load elimination.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "gvn"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Value.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DepthFirstIterator.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Compiler.h"
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 /// This class holds the mapping between values and value numbers. It is used
41 /// as an efficient mechanism to determine the expression-wise equivalence of
44 struct VISIBILITY_HIDDEN Expression {
45 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
46 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
47 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
48 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
49 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
50 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
51 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
52 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
53 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
54 PTRTOINT, INTTOPTR, BITCAST, GEP, EMPTY,
57 ExpressionOpcode opcode;
62 SmallVector<uint32_t, 4> varargs;
65 Expression(ExpressionOpcode o) : opcode(o) { }
67 bool operator==(const Expression &other) const {
68 if (opcode != other.opcode)
70 else if (opcode == EMPTY || opcode == TOMBSTONE)
72 else if (type != other.type)
74 else if (firstVN != other.firstVN)
76 else if (secondVN != other.secondVN)
78 else if (thirdVN != other.thirdVN)
81 if (varargs.size() != other.varargs.size())
84 for (size_t i = 0; i < varargs.size(); ++i)
85 if (varargs[i] != other.varargs[i])
92 bool operator!=(const Expression &other) const {
93 if (opcode != other.opcode)
95 else if (opcode == EMPTY || opcode == TOMBSTONE)
97 else if (type != other.type)
99 else if (firstVN != other.firstVN)
101 else if (secondVN != other.secondVN)
103 else if (thirdVN != other.thirdVN)
106 if (varargs.size() != other.varargs.size())
109 for (size_t i = 0; i < varargs.size(); ++i)
110 if (varargs[i] != other.varargs[i])
118 class VISIBILITY_HIDDEN ValueTable {
120 DenseMap<Value*, uint32_t> valueNumbering;
121 DenseMap<Expression, uint32_t> expressionNumbering;
123 uint32_t nextValueNumber;
125 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
126 Expression::ExpressionOpcode getOpcode(CmpInst* C);
127 Expression::ExpressionOpcode getOpcode(CastInst* C);
128 Expression create_expression(BinaryOperator* BO);
129 Expression create_expression(CmpInst* C);
130 Expression create_expression(ShuffleVectorInst* V);
131 Expression create_expression(ExtractElementInst* C);
132 Expression create_expression(InsertElementInst* V);
133 Expression create_expression(SelectInst* V);
134 Expression create_expression(CastInst* C);
135 Expression create_expression(GetElementPtrInst* G);
137 ValueTable() { nextValueNumber = 1; }
138 uint32_t lookup_or_add(Value* V);
139 uint32_t lookup(Value* V) const;
140 void add(Value* V, uint32_t num);
142 void erase(Value* v);
148 template <> struct DenseMapKeyInfo<Expression> {
149 static inline Expression getEmptyKey() {
150 return Expression(Expression::EMPTY);
153 static inline Expression getTombstoneKey() {
154 return Expression(Expression::TOMBSTONE);
157 static unsigned getHashValue(const Expression e) {
158 unsigned hash = e.opcode;
160 hash = e.firstVN + hash * 37;
161 hash = e.secondVN + hash * 37;
162 hash = e.thirdVN + hash * 37;
164 hash = (unsigned)((uintptr_t)e.type >> 4) ^
165 (unsigned)((uintptr_t)e.type >> 9) +
168 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
169 E = e.varargs.end(); I != E; ++I)
170 hash = *I + hash * 37;
174 static bool isPod() { return true; }
178 //===----------------------------------------------------------------------===//
179 // ValueTable Internal Functions
180 //===----------------------------------------------------------------------===//
181 Expression::ExpressionOpcode
182 ValueTable::getOpcode(BinaryOperator* BO) {
183 switch(BO->getOpcode()) {
184 case Instruction::Add:
185 return Expression::ADD;
186 case Instruction::Sub:
187 return Expression::SUB;
188 case Instruction::Mul:
189 return Expression::MUL;
190 case Instruction::UDiv:
191 return Expression::UDIV;
192 case Instruction::SDiv:
193 return Expression::SDIV;
194 case Instruction::FDiv:
195 return Expression::FDIV;
196 case Instruction::URem:
197 return Expression::UREM;
198 case Instruction::SRem:
199 return Expression::SREM;
200 case Instruction::FRem:
201 return Expression::FREM;
202 case Instruction::Shl:
203 return Expression::SHL;
204 case Instruction::LShr:
205 return Expression::LSHR;
206 case Instruction::AShr:
207 return Expression::ASHR;
208 case Instruction::And:
209 return Expression::AND;
210 case Instruction::Or:
211 return Expression::OR;
212 case Instruction::Xor:
213 return Expression::XOR;
215 // THIS SHOULD NEVER HAPPEN
217 assert(0 && "Binary operator with unknown opcode?");
218 return Expression::ADD;
222 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
223 if (C->getOpcode() == Instruction::ICmp) {
224 switch (C->getPredicate()) {
225 case ICmpInst::ICMP_EQ:
226 return Expression::ICMPEQ;
227 case ICmpInst::ICMP_NE:
228 return Expression::ICMPNE;
229 case ICmpInst::ICMP_UGT:
230 return Expression::ICMPUGT;
231 case ICmpInst::ICMP_UGE:
232 return Expression::ICMPUGE;
233 case ICmpInst::ICMP_ULT:
234 return Expression::ICMPULT;
235 case ICmpInst::ICMP_ULE:
236 return Expression::ICMPULE;
237 case ICmpInst::ICMP_SGT:
238 return Expression::ICMPSGT;
239 case ICmpInst::ICMP_SGE:
240 return Expression::ICMPSGE;
241 case ICmpInst::ICMP_SLT:
242 return Expression::ICMPSLT;
243 case ICmpInst::ICMP_SLE:
244 return Expression::ICMPSLE;
246 // THIS SHOULD NEVER HAPPEN
248 assert(0 && "Comparison with unknown predicate?");
249 return Expression::ICMPEQ;
252 switch (C->getPredicate()) {
253 case FCmpInst::FCMP_OEQ:
254 return Expression::FCMPOEQ;
255 case FCmpInst::FCMP_OGT:
256 return Expression::FCMPOGT;
257 case FCmpInst::FCMP_OGE:
258 return Expression::FCMPOGE;
259 case FCmpInst::FCMP_OLT:
260 return Expression::FCMPOLT;
261 case FCmpInst::FCMP_OLE:
262 return Expression::FCMPOLE;
263 case FCmpInst::FCMP_ONE:
264 return Expression::FCMPONE;
265 case FCmpInst::FCMP_ORD:
266 return Expression::FCMPORD;
267 case FCmpInst::FCMP_UNO:
268 return Expression::FCMPUNO;
269 case FCmpInst::FCMP_UEQ:
270 return Expression::FCMPUEQ;
271 case FCmpInst::FCMP_UGT:
272 return Expression::FCMPUGT;
273 case FCmpInst::FCMP_UGE:
274 return Expression::FCMPUGE;
275 case FCmpInst::FCMP_ULT:
276 return Expression::FCMPULT;
277 case FCmpInst::FCMP_ULE:
278 return Expression::FCMPULE;
279 case FCmpInst::FCMP_UNE:
280 return Expression::FCMPUNE;
282 // THIS SHOULD NEVER HAPPEN
284 assert(0 && "Comparison with unknown predicate?");
285 return Expression::FCMPOEQ;
290 Expression::ExpressionOpcode
291 ValueTable::getOpcode(CastInst* C) {
292 switch(C->getOpcode()) {
293 case Instruction::Trunc:
294 return Expression::TRUNC;
295 case Instruction::ZExt:
296 return Expression::ZEXT;
297 case Instruction::SExt:
298 return Expression::SEXT;
299 case Instruction::FPToUI:
300 return Expression::FPTOUI;
301 case Instruction::FPToSI:
302 return Expression::FPTOSI;
303 case Instruction::UIToFP:
304 return Expression::UITOFP;
305 case Instruction::SIToFP:
306 return Expression::SITOFP;
307 case Instruction::FPTrunc:
308 return Expression::FPTRUNC;
309 case Instruction::FPExt:
310 return Expression::FPEXT;
311 case Instruction::PtrToInt:
312 return Expression::PTRTOINT;
313 case Instruction::IntToPtr:
314 return Expression::INTTOPTR;
315 case Instruction::BitCast:
316 return Expression::BITCAST;
318 // THIS SHOULD NEVER HAPPEN
320 assert(0 && "Cast operator with unknown opcode?");
321 return Expression::BITCAST;
325 Expression ValueTable::create_expression(BinaryOperator* BO) {
328 e.firstVN = lookup_or_add(BO->getOperand(0));
329 e.secondVN = lookup_or_add(BO->getOperand(1));
331 e.type = BO->getType();
332 e.opcode = getOpcode(BO);
337 Expression ValueTable::create_expression(CmpInst* C) {
340 e.firstVN = lookup_or_add(C->getOperand(0));
341 e.secondVN = lookup_or_add(C->getOperand(1));
343 e.type = C->getType();
344 e.opcode = getOpcode(C);
349 Expression ValueTable::create_expression(CastInst* C) {
352 e.firstVN = lookup_or_add(C->getOperand(0));
355 e.type = C->getType();
356 e.opcode = getOpcode(C);
361 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
364 e.firstVN = lookup_or_add(S->getOperand(0));
365 e.secondVN = lookup_or_add(S->getOperand(1));
366 e.thirdVN = lookup_or_add(S->getOperand(2));
367 e.type = S->getType();
368 e.opcode = Expression::SHUFFLE;
373 Expression ValueTable::create_expression(ExtractElementInst* E) {
376 e.firstVN = lookup_or_add(E->getOperand(0));
377 e.secondVN = lookup_or_add(E->getOperand(1));
379 e.type = E->getType();
380 e.opcode = Expression::EXTRACT;
385 Expression ValueTable::create_expression(InsertElementInst* I) {
388 e.firstVN = lookup_or_add(I->getOperand(0));
389 e.secondVN = lookup_or_add(I->getOperand(1));
390 e.thirdVN = lookup_or_add(I->getOperand(2));
391 e.type = I->getType();
392 e.opcode = Expression::INSERT;
397 Expression ValueTable::create_expression(SelectInst* I) {
400 e.firstVN = lookup_or_add(I->getCondition());
401 e.secondVN = lookup_or_add(I->getTrueValue());
402 e.thirdVN = lookup_or_add(I->getFalseValue());
403 e.type = I->getType();
404 e.opcode = Expression::SELECT;
409 Expression ValueTable::create_expression(GetElementPtrInst* G) {
412 e.firstVN = lookup_or_add(G->getPointerOperand());
415 e.type = G->getType();
416 e.opcode = Expression::GEP;
418 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
420 e.varargs.push_back(lookup_or_add(*I));
425 //===----------------------------------------------------------------------===//
426 // ValueTable External Functions
427 //===----------------------------------------------------------------------===//
429 /// lookup_or_add - Returns the value number for the specified value, assigning
430 /// it a new number if it did not have one before.
431 uint32_t ValueTable::lookup_or_add(Value* V) {
432 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
433 if (VI != valueNumbering.end())
437 if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
438 Expression e = create_expression(BO);
440 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
441 if (EI != expressionNumbering.end()) {
442 valueNumbering.insert(std::make_pair(V, EI->second));
445 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
446 valueNumbering.insert(std::make_pair(V, nextValueNumber));
448 return nextValueNumber++;
450 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
451 Expression e = create_expression(C);
453 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
454 if (EI != expressionNumbering.end()) {
455 valueNumbering.insert(std::make_pair(V, EI->second));
458 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
459 valueNumbering.insert(std::make_pair(V, nextValueNumber));
461 return nextValueNumber++;
463 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
464 Expression e = create_expression(U);
466 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
467 if (EI != expressionNumbering.end()) {
468 valueNumbering.insert(std::make_pair(V, EI->second));
471 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
472 valueNumbering.insert(std::make_pair(V, nextValueNumber));
474 return nextValueNumber++;
476 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
477 Expression e = create_expression(U);
479 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
480 if (EI != expressionNumbering.end()) {
481 valueNumbering.insert(std::make_pair(V, EI->second));
484 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
485 valueNumbering.insert(std::make_pair(V, nextValueNumber));
487 return nextValueNumber++;
489 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
490 Expression e = create_expression(U);
492 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
493 if (EI != expressionNumbering.end()) {
494 valueNumbering.insert(std::make_pair(V, EI->second));
497 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
498 valueNumbering.insert(std::make_pair(V, nextValueNumber));
500 return nextValueNumber++;
502 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
503 Expression e = create_expression(U);
505 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
506 if (EI != expressionNumbering.end()) {
507 valueNumbering.insert(std::make_pair(V, EI->second));
510 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
511 valueNumbering.insert(std::make_pair(V, nextValueNumber));
513 return nextValueNumber++;
515 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
516 Expression e = create_expression(U);
518 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
519 if (EI != expressionNumbering.end()) {
520 valueNumbering.insert(std::make_pair(V, EI->second));
523 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
524 valueNumbering.insert(std::make_pair(V, nextValueNumber));
526 return nextValueNumber++;
528 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
529 Expression e = create_expression(U);
531 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
532 if (EI != expressionNumbering.end()) {
533 valueNumbering.insert(std::make_pair(V, EI->second));
536 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
537 valueNumbering.insert(std::make_pair(V, nextValueNumber));
539 return nextValueNumber++;
542 valueNumbering.insert(std::make_pair(V, nextValueNumber));
543 return nextValueNumber++;
547 /// lookup - Returns the value number of the specified value. Fails if
548 /// the value has not yet been numbered.
549 uint32_t ValueTable::lookup(Value* V) const {
550 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
551 if (VI != valueNumbering.end())
554 assert(0 && "Value not numbered?");
559 /// clear - Remove all entries from the ValueTable
560 void ValueTable::clear() {
561 valueNumbering.clear();
562 expressionNumbering.clear();
566 /// erase - Remove a value from the value numbering
567 void ValueTable::erase(Value* V) {
568 valueNumbering.erase(V);
571 //===----------------------------------------------------------------------===//
572 // ValueNumberedSet Class
573 //===----------------------------------------------------------------------===//
575 class ValueNumberedSet {
577 SmallPtrSet<Value*, 8> contents;
580 ValueNumberedSet() { numbers.resize(1); }
581 ValueNumberedSet(const ValueNumberedSet& other) {
582 numbers = other.numbers;
583 contents = other.contents;
586 typedef SmallPtrSet<Value*, 8>::iterator iterator;
588 iterator begin() { return contents.begin(); }
589 iterator end() { return contents.end(); }
591 bool insert(Value* v) { return contents.insert(v); }
592 void insert(iterator I, iterator E) { contents.insert(I, E); }
593 void erase(Value* v) { contents.erase(v); }
594 unsigned count(Value* v) { return contents.count(v); }
595 size_t size() { return contents.size(); }
597 void set(unsigned i) {
598 if (i >= numbers.size())
604 void operator=(const ValueNumberedSet& other) {
605 contents = other.contents;
606 numbers = other.numbers;
609 void reset(unsigned i) {
610 if (i < numbers.size())
614 bool test(unsigned i) {
615 if (i >= numbers.size())
618 return numbers.test(i);
628 //===----------------------------------------------------------------------===//
630 //===----------------------------------------------------------------------===//
634 class VISIBILITY_HIDDEN GVN : public FunctionPass {
635 bool runOnFunction(Function &F);
637 static char ID; // Pass identification, replacement for typeid
638 GVN() : FunctionPass((intptr_t)&ID) { }
643 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
645 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
649 // This transformation requires dominator postdominator info
650 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
651 AU.setPreservesCFG();
652 AU.addRequired<DominatorTree>();
653 AU.addRequired<MemoryDependenceAnalysis>();
654 AU.addPreserved<MemoryDependenceAnalysis>();
658 // FIXME: eliminate or document these better
659 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
660 void val_insert(ValueNumberedSet& s, Value* v);
661 bool processLoad(LoadInst* L,
662 DenseMap<Value*, LoadInst*>& lastLoad,
663 SmallVector<Instruction*, 4>& toErase);
664 bool processInstruction(Instruction* I,
665 ValueNumberedSet& currAvail,
666 DenseMap<Value*, LoadInst*>& lastSeenLoad,
667 SmallVector<Instruction*, 4>& toErase);
668 bool processNonLocalLoad(LoadInst* L,
669 SmallVector<Instruction*, 4>& toErase);
670 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
671 DenseMap<BasicBlock*, Value*> &Phis,
672 bool top_level = false);
673 void dump(DenseMap<BasicBlock*, Value*>& d);
674 bool iterateOnFunction(Function &F);
675 Value* CollapsePhi(PHINode* p);
682 // createGVNPass - The public interface to this file...
683 FunctionPass *llvm::createGVNPass() { return new GVN(); }
685 static RegisterPass<GVN> X("gvn",
686 "Global Value Numbering");
688 STATISTIC(NumGVNInstr, "Number of instructions deleted");
689 STATISTIC(NumGVNLoad, "Number of loads deleted");
691 /// find_leader - Given a set and a value number, return the first
692 /// element of the set with that value number, or 0 if no such element
694 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
698 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
700 if (v == VN.lookup(*I))
703 assert(0 && "No leader found, but present bit is set?");
707 /// val_insert - Insert a value into a set only if there is not a value
708 /// with the same value number already in the set
709 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
710 uint32_t num = VN.lookup(v);
715 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
717 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
718 E = d.end(); I != E; ++I) {
719 if (I->second == MemoryDependenceAnalysis::None)
727 Value* GVN::CollapsePhi(PHINode* p) {
728 DominatorTree &DT = getAnalysis<DominatorTree>();
729 Value* constVal = p->hasConstantValue();
732 if (Instruction* inst = dyn_cast<Instruction>(constVal)) {
733 if (DT.dominates(inst, p))
743 /// GetValueForBlock - Get the value to use within the specified basic block.
744 /// available values are in Phis.
745 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
746 DenseMap<BasicBlock*, Value*> &Phis,
749 // If we have already computed this value, return the previously computed val.
750 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
751 if (V != Phis.end() && !top_level) return V->second;
753 BasicBlock* singlePred = BB->getSinglePredecessor();
755 Value *ret = GetValueForBlock(singlePred, orig, Phis);
759 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
760 // now, then get values to fill in the incoming values for the PHI.
761 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
763 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
765 if (Phis.count(BB) == 0)
766 Phis.insert(std::make_pair(BB, PN));
768 // Fill in the incoming values for the block.
769 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
770 Value* val = GetValueForBlock(*PI, orig, Phis);
772 PN->addIncoming(val, *PI);
775 // Attempt to collapse PHI nodes that are trivially redundant
776 Value* v = CollapsePhi(PN);
778 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
780 MD.removeInstruction(PN);
781 PN->replaceAllUsesWith(v);
783 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
784 E = Phis.end(); I != E; ++I)
788 PN->eraseFromParent();
795 // Cache our phi construction results
796 phiMap[orig->getPointerOperand()].insert(PN);
800 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
801 /// non-local by performing PHI construction.
802 bool GVN::processNonLocalLoad(LoadInst* L,
803 SmallVector<Instruction*, 4>& toErase) {
804 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
806 // Find the non-local dependencies of the load
807 DenseMap<BasicBlock*, Value*> deps;
808 MD.getNonLocalDependency(L, deps);
810 DenseMap<BasicBlock*, Value*> repl;
812 // Filter out useless results (non-locals, etc)
813 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
815 if (I->second == MemoryDependenceAnalysis::None) {
817 } else if (I->second == MemoryDependenceAnalysis::NonLocal) {
819 }else if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
820 if (S->getPointerOperand() == L->getPointerOperand())
821 repl[I->first] = S->getOperand(0);
824 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
825 if (LD->getPointerOperand() == L->getPointerOperand())
833 // Use cached PHI construction information from previous runs
834 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
835 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
837 if ((*I)->getParent() == L->getParent()) {
838 MD.removeInstruction(L);
839 L->replaceAllUsesWith(*I);
840 toErase.push_back(L);
845 repl.insert(std::make_pair((*I)->getParent(), *I));
849 // Perform PHI construction
850 SmallPtrSet<BasicBlock*, 4> visited;
851 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
853 MD.removeInstruction(L);
854 L->replaceAllUsesWith(v);
855 toErase.push_back(L);
861 /// processLoad - Attempt to eliminate a load, first by eliminating it
862 /// locally, and then attempting non-local elimination if that fails.
863 bool GVN::processLoad(LoadInst* L,
864 DenseMap<Value*, LoadInst*>& lastLoad,
865 SmallVector<Instruction*, 4>& toErase) {
866 if (L->isVolatile()) {
867 lastLoad[L->getPointerOperand()] = L;
871 Value* pointer = L->getPointerOperand();
872 LoadInst*& last = lastLoad[pointer];
874 // ... to a pointer that has been loaded from before...
875 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
876 bool removedNonLocal = false;
877 Instruction* dep = MD.getDependency(L);
878 if (dep == MemoryDependenceAnalysis::NonLocal &&
879 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
880 removedNonLocal = processNonLocalLoad(L, toErase);
882 if (!removedNonLocal)
885 return removedNonLocal;
889 bool deletedLoad = false;
891 // Walk up the dependency chain until we either find
892 // a dependency we can use, or we can't walk any further
893 while (dep != MemoryDependenceAnalysis::None &&
894 dep != MemoryDependenceAnalysis::NonLocal &&
895 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
896 // ... that depends on a store ...
897 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
898 if (S->getPointerOperand() == pointer) {
900 MD.removeInstruction(L);
902 L->replaceAllUsesWith(S->getOperand(0));
903 toErase.push_back(L);
908 // Whether we removed it or not, we can't
912 // If we don't depend on a store, and we haven't
913 // been loaded before, bail.
915 } else if (dep == last) {
917 MD.removeInstruction(L);
919 L->replaceAllUsesWith(last);
920 toErase.push_back(L);
926 dep = MD.getDependency(L, dep);
936 /// processInstruction - When calculating availability, handle an instruction
937 /// by inserting it into the appropriate sets
938 bool GVN::processInstruction(Instruction* I,
939 ValueNumberedSet& currAvail,
940 DenseMap<Value*, LoadInst*>& lastSeenLoad,
941 SmallVector<Instruction*, 4>& toErase) {
942 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
943 return processLoad(L, lastSeenLoad, toErase);
946 unsigned num = VN.lookup_or_add(I);
948 // Collapse PHI nodes
949 if (PHINode* p = dyn_cast<PHINode>(I)) {
950 Value* constVal = CollapsePhi(p);
953 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
955 if (PI->second.count(p))
958 p->replaceAllUsesWith(constVal);
959 toErase.push_back(p);
961 // Perform value-number based elimination
962 } else if (currAvail.test(num)) {
963 Value* repl = find_leader(currAvail, num);
966 I->replaceAllUsesWith(repl);
967 toErase.push_back(I);
969 } else if (!I->isTerminator()) {
977 // GVN::runOnFunction - This is the main transformation entry point for a
980 bool GVN::runOnFunction(Function& F) {
981 bool changed = false;
982 bool shouldContinue = true;
984 while (shouldContinue) {
985 shouldContinue = iterateOnFunction(F);
986 changed |= shouldContinue;
993 // GVN::iterateOnFunction - Executes one iteration of GVN
994 bool GVN::iterateOnFunction(Function &F) {
995 // Clean out global sets from any previous functions
997 availableOut.clear();
1000 bool changed_function = false;
1002 DominatorTree &DT = getAnalysis<DominatorTree>();
1004 SmallVector<Instruction*, 4> toErase;
1006 // Top-down walk of the dominator tree
1007 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1008 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1010 // Get the set to update for this block
1011 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1012 DenseMap<Value*, LoadInst*> lastSeenLoad;
1014 BasicBlock* BB = DI->getBlock();
1016 // A block inherits AVAIL_OUT from its dominator
1017 if (DI->getIDom() != 0)
1018 currAvail = availableOut[DI->getIDom()->getBlock()];
1020 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1022 changed_function |= processInstruction(BI, currAvail,
1023 lastSeenLoad, toErase);
1025 NumGVNInstr += toErase.size();
1027 // Avoid iterator invalidation
1030 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1031 E = toErase.end(); I != E; ++I)
1032 (*I)->eraseFromParent();
1038 return changed_function;