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/ADT/BitVector.h"
25 #include "llvm/ADT/DenseMap.h"
26 #include "llvm/ADT/DepthFirstIterator.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Analysis/Dominators.h"
31 #include "llvm/Analysis/AliasAnalysis.h"
32 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Compiler.h"
37 //===----------------------------------------------------------------------===//
39 //===----------------------------------------------------------------------===//
41 /// This class holds the mapping between values and value numbers. It is used
42 /// as an efficient mechanism to determine the expression-wise equivalence of
45 struct VISIBILITY_HIDDEN Expression {
46 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
47 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
48 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
49 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
50 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
51 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
52 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
53 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
54 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
55 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
58 ExpressionOpcode opcode;
63 SmallVector<uint32_t, 4> varargs;
67 Expression(ExpressionOpcode o) : opcode(o) { }
69 bool operator==(const Expression &other) const {
70 if (opcode != other.opcode)
72 else if (opcode == EMPTY || opcode == TOMBSTONE)
74 else if (type != other.type)
76 else if (function != other.function)
78 else if (firstVN != other.firstVN)
80 else if (secondVN != other.secondVN)
82 else if (thirdVN != other.thirdVN)
85 if (varargs.size() != other.varargs.size())
88 for (size_t i = 0; i < varargs.size(); ++i)
89 if (varargs[i] != other.varargs[i])
96 bool operator!=(const Expression &other) const {
97 if (opcode != other.opcode)
99 else if (opcode == EMPTY || opcode == TOMBSTONE)
101 else if (type != other.type)
103 else if (function != other.function)
105 else if (firstVN != other.firstVN)
107 else if (secondVN != other.secondVN)
109 else if (thirdVN != other.thirdVN)
112 if (varargs.size() != other.varargs.size())
115 for (size_t i = 0; i < varargs.size(); ++i)
116 if (varargs[i] != other.varargs[i])
124 class VISIBILITY_HIDDEN ValueTable {
126 DenseMap<Value*, uint32_t> valueNumbering;
127 DenseMap<Expression, uint32_t> expressionNumbering;
130 uint32_t nextValueNumber;
132 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
133 Expression::ExpressionOpcode getOpcode(CmpInst* C);
134 Expression::ExpressionOpcode getOpcode(CastInst* C);
135 Expression create_expression(BinaryOperator* BO);
136 Expression create_expression(CmpInst* C);
137 Expression create_expression(ShuffleVectorInst* V);
138 Expression create_expression(ExtractElementInst* C);
139 Expression create_expression(InsertElementInst* V);
140 Expression create_expression(SelectInst* V);
141 Expression create_expression(CastInst* C);
142 Expression create_expression(GetElementPtrInst* G);
143 Expression create_expression(CallInst* C);
145 ValueTable() : nextValueNumber(1) { }
146 uint32_t lookup_or_add(Value* V);
147 uint32_t lookup(Value* V) const;
148 void add(Value* V, uint32_t num);
150 void erase(Value* v);
152 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
157 template <> struct DenseMapInfo<Expression> {
158 static inline Expression getEmptyKey() {
159 return Expression(Expression::EMPTY);
162 static inline Expression getTombstoneKey() {
163 return Expression(Expression::TOMBSTONE);
166 static unsigned getHashValue(const Expression e) {
167 unsigned hash = e.opcode;
169 hash = e.firstVN + hash * 37;
170 hash = e.secondVN + hash * 37;
171 hash = e.thirdVN + hash * 37;
173 hash = (unsigned)((uintptr_t)e.type >> 4) ^
174 (unsigned)((uintptr_t)e.type >> 9) +
177 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
178 E = e.varargs.end(); I != E; ++I)
179 hash = *I + hash * 37;
181 hash = (unsigned)((uintptr_t)e.function >> 4) ^
182 (unsigned)((uintptr_t)e.function >> 9) +
187 static bool isEqual(const Expression &LHS, const Expression &RHS) {
190 static bool isPod() { return true; }
194 //===----------------------------------------------------------------------===//
195 // ValueTable Internal Functions
196 //===----------------------------------------------------------------------===//
197 Expression::ExpressionOpcode
198 ValueTable::getOpcode(BinaryOperator* BO) {
199 switch(BO->getOpcode()) {
200 case Instruction::Add:
201 return Expression::ADD;
202 case Instruction::Sub:
203 return Expression::SUB;
204 case Instruction::Mul:
205 return Expression::MUL;
206 case Instruction::UDiv:
207 return Expression::UDIV;
208 case Instruction::SDiv:
209 return Expression::SDIV;
210 case Instruction::FDiv:
211 return Expression::FDIV;
212 case Instruction::URem:
213 return Expression::UREM;
214 case Instruction::SRem:
215 return Expression::SREM;
216 case Instruction::FRem:
217 return Expression::FREM;
218 case Instruction::Shl:
219 return Expression::SHL;
220 case Instruction::LShr:
221 return Expression::LSHR;
222 case Instruction::AShr:
223 return Expression::ASHR;
224 case Instruction::And:
225 return Expression::AND;
226 case Instruction::Or:
227 return Expression::OR;
228 case Instruction::Xor:
229 return Expression::XOR;
231 // THIS SHOULD NEVER HAPPEN
233 assert(0 && "Binary operator with unknown opcode?");
234 return Expression::ADD;
238 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
239 if (C->getOpcode() == Instruction::ICmp) {
240 switch (C->getPredicate()) {
241 case ICmpInst::ICMP_EQ:
242 return Expression::ICMPEQ;
243 case ICmpInst::ICMP_NE:
244 return Expression::ICMPNE;
245 case ICmpInst::ICMP_UGT:
246 return Expression::ICMPUGT;
247 case ICmpInst::ICMP_UGE:
248 return Expression::ICMPUGE;
249 case ICmpInst::ICMP_ULT:
250 return Expression::ICMPULT;
251 case ICmpInst::ICMP_ULE:
252 return Expression::ICMPULE;
253 case ICmpInst::ICMP_SGT:
254 return Expression::ICMPSGT;
255 case ICmpInst::ICMP_SGE:
256 return Expression::ICMPSGE;
257 case ICmpInst::ICMP_SLT:
258 return Expression::ICMPSLT;
259 case ICmpInst::ICMP_SLE:
260 return Expression::ICMPSLE;
262 // THIS SHOULD NEVER HAPPEN
264 assert(0 && "Comparison with unknown predicate?");
265 return Expression::ICMPEQ;
268 switch (C->getPredicate()) {
269 case FCmpInst::FCMP_OEQ:
270 return Expression::FCMPOEQ;
271 case FCmpInst::FCMP_OGT:
272 return Expression::FCMPOGT;
273 case FCmpInst::FCMP_OGE:
274 return Expression::FCMPOGE;
275 case FCmpInst::FCMP_OLT:
276 return Expression::FCMPOLT;
277 case FCmpInst::FCMP_OLE:
278 return Expression::FCMPOLE;
279 case FCmpInst::FCMP_ONE:
280 return Expression::FCMPONE;
281 case FCmpInst::FCMP_ORD:
282 return Expression::FCMPORD;
283 case FCmpInst::FCMP_UNO:
284 return Expression::FCMPUNO;
285 case FCmpInst::FCMP_UEQ:
286 return Expression::FCMPUEQ;
287 case FCmpInst::FCMP_UGT:
288 return Expression::FCMPUGT;
289 case FCmpInst::FCMP_UGE:
290 return Expression::FCMPUGE;
291 case FCmpInst::FCMP_ULT:
292 return Expression::FCMPULT;
293 case FCmpInst::FCMP_ULE:
294 return Expression::FCMPULE;
295 case FCmpInst::FCMP_UNE:
296 return Expression::FCMPUNE;
298 // THIS SHOULD NEVER HAPPEN
300 assert(0 && "Comparison with unknown predicate?");
301 return Expression::FCMPOEQ;
306 Expression::ExpressionOpcode
307 ValueTable::getOpcode(CastInst* C) {
308 switch(C->getOpcode()) {
309 case Instruction::Trunc:
310 return Expression::TRUNC;
311 case Instruction::ZExt:
312 return Expression::ZEXT;
313 case Instruction::SExt:
314 return Expression::SEXT;
315 case Instruction::FPToUI:
316 return Expression::FPTOUI;
317 case Instruction::FPToSI:
318 return Expression::FPTOSI;
319 case Instruction::UIToFP:
320 return Expression::UITOFP;
321 case Instruction::SIToFP:
322 return Expression::SITOFP;
323 case Instruction::FPTrunc:
324 return Expression::FPTRUNC;
325 case Instruction::FPExt:
326 return Expression::FPEXT;
327 case Instruction::PtrToInt:
328 return Expression::PTRTOINT;
329 case Instruction::IntToPtr:
330 return Expression::INTTOPTR;
331 case Instruction::BitCast:
332 return Expression::BITCAST;
334 // THIS SHOULD NEVER HAPPEN
336 assert(0 && "Cast operator with unknown opcode?");
337 return Expression::BITCAST;
341 Expression ValueTable::create_expression(CallInst* C) {
344 e.type = C->getType();
348 e.function = C->getCalledFunction();
349 e.opcode = Expression::CALL;
351 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
353 e.varargs.push_back(lookup_or_add(*I));
358 Expression ValueTable::create_expression(BinaryOperator* BO) {
361 e.firstVN = lookup_or_add(BO->getOperand(0));
362 e.secondVN = lookup_or_add(BO->getOperand(1));
365 e.type = BO->getType();
366 e.opcode = getOpcode(BO);
371 Expression ValueTable::create_expression(CmpInst* C) {
374 e.firstVN = lookup_or_add(C->getOperand(0));
375 e.secondVN = lookup_or_add(C->getOperand(1));
378 e.type = C->getType();
379 e.opcode = getOpcode(C);
384 Expression ValueTable::create_expression(CastInst* C) {
387 e.firstVN = lookup_or_add(C->getOperand(0));
391 e.type = C->getType();
392 e.opcode = getOpcode(C);
397 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
400 e.firstVN = lookup_or_add(S->getOperand(0));
401 e.secondVN = lookup_or_add(S->getOperand(1));
402 e.thirdVN = lookup_or_add(S->getOperand(2));
404 e.type = S->getType();
405 e.opcode = Expression::SHUFFLE;
410 Expression ValueTable::create_expression(ExtractElementInst* E) {
413 e.firstVN = lookup_or_add(E->getOperand(0));
414 e.secondVN = lookup_or_add(E->getOperand(1));
417 e.type = E->getType();
418 e.opcode = Expression::EXTRACT;
423 Expression ValueTable::create_expression(InsertElementInst* I) {
426 e.firstVN = lookup_or_add(I->getOperand(0));
427 e.secondVN = lookup_or_add(I->getOperand(1));
428 e.thirdVN = lookup_or_add(I->getOperand(2));
430 e.type = I->getType();
431 e.opcode = Expression::INSERT;
436 Expression ValueTable::create_expression(SelectInst* I) {
439 e.firstVN = lookup_or_add(I->getCondition());
440 e.secondVN = lookup_or_add(I->getTrueValue());
441 e.thirdVN = lookup_or_add(I->getFalseValue());
443 e.type = I->getType();
444 e.opcode = Expression::SELECT;
449 Expression ValueTable::create_expression(GetElementPtrInst* G) {
452 e.firstVN = lookup_or_add(G->getPointerOperand());
456 e.type = G->getType();
457 e.opcode = Expression::GEP;
459 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
461 e.varargs.push_back(lookup_or_add(*I));
466 //===----------------------------------------------------------------------===//
467 // ValueTable External Functions
468 //===----------------------------------------------------------------------===//
470 /// lookup_or_add - Returns the value number for the specified value, assigning
471 /// it a new number if it did not have one before.
472 uint32_t ValueTable::lookup_or_add(Value* V) {
473 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
474 if (VI != valueNumbering.end())
477 if (CallInst* C = dyn_cast<CallInst>(V)) {
478 if (C->getCalledFunction() &&
479 AA->doesNotAccessMemory(C->getCalledFunction())) {
480 Expression e = create_expression(C);
482 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
483 if (EI != expressionNumbering.end()) {
484 valueNumbering.insert(std::make_pair(V, EI->second));
487 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
488 valueNumbering.insert(std::make_pair(V, nextValueNumber));
490 return nextValueNumber++;
493 valueNumbering.insert(std::make_pair(V, nextValueNumber));
494 return nextValueNumber++;
496 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
497 Expression e = create_expression(BO);
499 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
500 if (EI != expressionNumbering.end()) {
501 valueNumbering.insert(std::make_pair(V, EI->second));
504 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
505 valueNumbering.insert(std::make_pair(V, nextValueNumber));
507 return nextValueNumber++;
509 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
510 Expression e = create_expression(C);
512 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
513 if (EI != expressionNumbering.end()) {
514 valueNumbering.insert(std::make_pair(V, EI->second));
517 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
518 valueNumbering.insert(std::make_pair(V, nextValueNumber));
520 return nextValueNumber++;
522 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
523 Expression e = create_expression(U);
525 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
526 if (EI != expressionNumbering.end()) {
527 valueNumbering.insert(std::make_pair(V, EI->second));
530 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
531 valueNumbering.insert(std::make_pair(V, nextValueNumber));
533 return nextValueNumber++;
535 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
536 Expression e = create_expression(U);
538 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
539 if (EI != expressionNumbering.end()) {
540 valueNumbering.insert(std::make_pair(V, EI->second));
543 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
544 valueNumbering.insert(std::make_pair(V, nextValueNumber));
546 return nextValueNumber++;
548 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
549 Expression e = create_expression(U);
551 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
552 if (EI != expressionNumbering.end()) {
553 valueNumbering.insert(std::make_pair(V, EI->second));
556 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
557 valueNumbering.insert(std::make_pair(V, nextValueNumber));
559 return nextValueNumber++;
561 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
562 Expression e = create_expression(U);
564 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
565 if (EI != expressionNumbering.end()) {
566 valueNumbering.insert(std::make_pair(V, EI->second));
569 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
570 valueNumbering.insert(std::make_pair(V, nextValueNumber));
572 return nextValueNumber++;
574 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
575 Expression e = create_expression(U);
577 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
578 if (EI != expressionNumbering.end()) {
579 valueNumbering.insert(std::make_pair(V, EI->second));
582 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
583 valueNumbering.insert(std::make_pair(V, nextValueNumber));
585 return nextValueNumber++;
587 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
588 Expression e = create_expression(U);
590 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
591 if (EI != expressionNumbering.end()) {
592 valueNumbering.insert(std::make_pair(V, EI->second));
595 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
596 valueNumbering.insert(std::make_pair(V, nextValueNumber));
598 return nextValueNumber++;
601 valueNumbering.insert(std::make_pair(V, nextValueNumber));
602 return nextValueNumber++;
606 /// lookup - Returns the value number of the specified value. Fails if
607 /// the value has not yet been numbered.
608 uint32_t ValueTable::lookup(Value* V) const {
609 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
610 if (VI != valueNumbering.end())
613 assert(0 && "Value not numbered?");
618 /// clear - Remove all entries from the ValueTable
619 void ValueTable::clear() {
620 valueNumbering.clear();
621 expressionNumbering.clear();
625 /// erase - Remove a value from the value numbering
626 void ValueTable::erase(Value* V) {
627 valueNumbering.erase(V);
630 //===----------------------------------------------------------------------===//
631 // ValueNumberedSet Class
632 //===----------------------------------------------------------------------===//
634 class ValueNumberedSet {
636 SmallPtrSet<Value*, 8> contents;
639 ValueNumberedSet() { numbers.resize(1); }
640 ValueNumberedSet(const ValueNumberedSet& other) {
641 numbers = other.numbers;
642 contents = other.contents;
645 typedef SmallPtrSet<Value*, 8>::iterator iterator;
647 iterator begin() { return contents.begin(); }
648 iterator end() { return contents.end(); }
650 bool insert(Value* v) { return contents.insert(v); }
651 void insert(iterator I, iterator E) { contents.insert(I, E); }
652 void erase(Value* v) { contents.erase(v); }
653 unsigned count(Value* v) { return contents.count(v); }
654 size_t size() { return contents.size(); }
656 void set(unsigned i) {
657 if (i >= numbers.size())
663 void operator=(const ValueNumberedSet& other) {
664 contents = other.contents;
665 numbers = other.numbers;
668 void reset(unsigned i) {
669 if (i < numbers.size())
673 bool test(unsigned i) {
674 if (i >= numbers.size())
677 return numbers.test(i);
687 //===----------------------------------------------------------------------===//
689 //===----------------------------------------------------------------------===//
693 class VISIBILITY_HIDDEN GVN : public FunctionPass {
694 bool runOnFunction(Function &F);
696 static char ID; // Pass identification, replacement for typeid
697 GVN() : FunctionPass((intptr_t)&ID) { }
702 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
704 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
708 // This transformation requires dominator postdominator info
709 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
710 AU.setPreservesCFG();
711 AU.addRequired<DominatorTree>();
712 AU.addRequired<MemoryDependenceAnalysis>();
713 AU.addRequired<AliasAnalysis>();
714 AU.addPreserved<AliasAnalysis>();
715 AU.addPreserved<MemoryDependenceAnalysis>();
719 // FIXME: eliminate or document these better
720 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
721 void val_insert(ValueNumberedSet& s, Value* v);
722 bool processLoad(LoadInst* L,
723 DenseMap<Value*, LoadInst*>& lastLoad,
724 SmallVector<Instruction*, 4>& toErase);
725 bool processInstruction(Instruction* I,
726 ValueNumberedSet& currAvail,
727 DenseMap<Value*, LoadInst*>& lastSeenLoad,
728 SmallVector<Instruction*, 4>& toErase);
729 bool processNonLocalLoad(LoadInst* L,
730 SmallVector<Instruction*, 4>& toErase);
731 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
732 DenseMap<BasicBlock*, Value*> &Phis,
733 bool top_level = false);
734 void dump(DenseMap<BasicBlock*, Value*>& d);
735 bool iterateOnFunction(Function &F);
736 Value* CollapsePhi(PHINode* p);
737 bool isSafeReplacement(PHINode* p, Instruction* inst);
744 // createGVNPass - The public interface to this file...
745 FunctionPass *llvm::createGVNPass() { return new GVN(); }
747 static RegisterPass<GVN> X("gvn",
748 "Global Value Numbering");
750 STATISTIC(NumGVNInstr, "Number of instructions deleted");
751 STATISTIC(NumGVNLoad, "Number of loads deleted");
753 /// find_leader - Given a set and a value number, return the first
754 /// element of the set with that value number, or 0 if no such element
756 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
760 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
762 if (v == VN.lookup(*I))
765 assert(0 && "No leader found, but present bit is set?");
769 /// val_insert - Insert a value into a set only if there is not a value
770 /// with the same value number already in the set
771 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
772 uint32_t num = VN.lookup(v);
777 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
779 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
780 E = d.end(); I != E; ++I) {
781 if (I->second == MemoryDependenceAnalysis::None)
789 Value* GVN::CollapsePhi(PHINode* p) {
790 DominatorTree &DT = getAnalysis<DominatorTree>();
791 Value* constVal = p->hasConstantValue();
794 if (Instruction* inst = dyn_cast<Instruction>(constVal)) {
795 if (DT.dominates(inst, p))
796 if (isSafeReplacement(p, inst))
806 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
807 if (!isa<PHINode>(inst))
810 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
812 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
813 if (use_phi->getParent() == inst->getParent())
819 /// GetValueForBlock - Get the value to use within the specified basic block.
820 /// available values are in Phis.
821 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
822 DenseMap<BasicBlock*, Value*> &Phis,
825 // If we have already computed this value, return the previously computed val.
826 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
827 if (V != Phis.end() && !top_level) return V->second;
829 BasicBlock* singlePred = BB->getSinglePredecessor();
831 Value *ret = GetValueForBlock(singlePred, orig, Phis);
835 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
836 // now, then get values to fill in the incoming values for the PHI.
837 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
839 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
841 if (Phis.count(BB) == 0)
842 Phis.insert(std::make_pair(BB, PN));
844 // Fill in the incoming values for the block.
845 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
846 Value* val = GetValueForBlock(*PI, orig, Phis);
848 PN->addIncoming(val, *PI);
851 // Attempt to collapse PHI nodes that are trivially redundant
852 Value* v = CollapsePhi(PN);
854 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
856 MD.removeInstruction(PN);
857 PN->replaceAllUsesWith(v);
859 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
860 E = Phis.end(); I != E; ++I)
864 PN->eraseFromParent();
871 // Cache our phi construction results
872 phiMap[orig->getPointerOperand()].insert(PN);
876 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
877 /// non-local by performing PHI construction.
878 bool GVN::processNonLocalLoad(LoadInst* L,
879 SmallVector<Instruction*, 4>& toErase) {
880 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
882 // Find the non-local dependencies of the load
883 DenseMap<BasicBlock*, Value*> deps;
884 MD.getNonLocalDependency(L, deps);
886 DenseMap<BasicBlock*, Value*> repl;
888 // Filter out useless results (non-locals, etc)
889 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
891 if (I->second == MemoryDependenceAnalysis::None) {
893 } else if (I->second == MemoryDependenceAnalysis::NonLocal) {
895 } else if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
896 if (S->getPointerOperand() == L->getPointerOperand())
897 repl[I->first] = S->getOperand(0);
900 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
901 if (LD->getPointerOperand() == L->getPointerOperand())
909 // Use cached PHI construction information from previous runs
910 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
911 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
913 if ((*I)->getParent() == L->getParent()) {
914 MD.removeInstruction(L);
915 L->replaceAllUsesWith(*I);
916 toErase.push_back(L);
921 repl.insert(std::make_pair((*I)->getParent(), *I));
925 // Perform PHI construction
926 SmallPtrSet<BasicBlock*, 4> visited;
927 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
929 MD.removeInstruction(L);
930 L->replaceAllUsesWith(v);
931 toErase.push_back(L);
937 /// processLoad - Attempt to eliminate a load, first by eliminating it
938 /// locally, and then attempting non-local elimination if that fails.
939 bool GVN::processLoad(LoadInst* L,
940 DenseMap<Value*, LoadInst*>& lastLoad,
941 SmallVector<Instruction*, 4>& toErase) {
942 if (L->isVolatile()) {
943 lastLoad[L->getPointerOperand()] = L;
947 Value* pointer = L->getPointerOperand();
948 LoadInst*& last = lastLoad[pointer];
950 // ... to a pointer that has been loaded from before...
951 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
952 bool removedNonLocal = false;
953 Instruction* dep = MD.getDependency(L);
954 if (dep == MemoryDependenceAnalysis::NonLocal &&
955 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
956 removedNonLocal = processNonLocalLoad(L, toErase);
958 if (!removedNonLocal)
961 return removedNonLocal;
965 bool deletedLoad = false;
967 // Walk up the dependency chain until we either find
968 // a dependency we can use, or we can't walk any further
969 while (dep != MemoryDependenceAnalysis::None &&
970 dep != MemoryDependenceAnalysis::NonLocal &&
971 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
972 // ... that depends on a store ...
973 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
974 if (S->getPointerOperand() == pointer) {
976 MD.removeInstruction(L);
978 L->replaceAllUsesWith(S->getOperand(0));
979 toErase.push_back(L);
984 // Whether we removed it or not, we can't
988 // If we don't depend on a store, and we haven't
989 // been loaded before, bail.
991 } else if (dep == last) {
993 MD.removeInstruction(L);
995 L->replaceAllUsesWith(last);
996 toErase.push_back(L);
1002 dep = MD.getDependency(L, dep);
1012 /// processInstruction - When calculating availability, handle an instruction
1013 /// by inserting it into the appropriate sets
1014 bool GVN::processInstruction(Instruction* I,
1015 ValueNumberedSet& currAvail,
1016 DenseMap<Value*, LoadInst*>& lastSeenLoad,
1017 SmallVector<Instruction*, 4>& toErase) {
1018 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1019 return processLoad(L, lastSeenLoad, toErase);
1022 unsigned num = VN.lookup_or_add(I);
1024 // Collapse PHI nodes
1025 if (PHINode* p = dyn_cast<PHINode>(I)) {
1026 Value* constVal = CollapsePhi(p);
1029 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1031 if (PI->second.count(p))
1032 PI->second.erase(p);
1034 p->replaceAllUsesWith(constVal);
1035 toErase.push_back(p);
1037 // Perform value-number based elimination
1038 } else if (currAvail.test(num)) {
1039 Value* repl = find_leader(currAvail, num);
1042 I->replaceAllUsesWith(repl);
1043 toErase.push_back(I);
1045 } else if (!I->isTerminator()) {
1047 currAvail.insert(I);
1053 // GVN::runOnFunction - This is the main transformation entry point for a
1056 bool GVN::runOnFunction(Function& F) {
1057 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1059 bool changed = false;
1060 bool shouldContinue = true;
1062 while (shouldContinue) {
1063 shouldContinue = iterateOnFunction(F);
1064 changed |= shouldContinue;
1071 // GVN::iterateOnFunction - Executes one iteration of GVN
1072 bool GVN::iterateOnFunction(Function &F) {
1073 // Clean out global sets from any previous functions
1075 availableOut.clear();
1078 bool changed_function = false;
1080 DominatorTree &DT = getAnalysis<DominatorTree>();
1082 SmallVector<Instruction*, 4> toErase;
1084 // Top-down walk of the dominator tree
1085 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1086 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1088 // Get the set to update for this block
1089 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1090 DenseMap<Value*, LoadInst*> lastSeenLoad;
1092 BasicBlock* BB = DI->getBlock();
1094 // A block inherits AVAIL_OUT from its dominator
1095 if (DI->getIDom() != 0)
1096 currAvail = availableOut[DI->getIDom()->getBlock()];
1098 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1100 changed_function |= processInstruction(BI, currAvail,
1101 lastSeenLoad, toErase);
1103 NumGVNInstr += toErase.size();
1105 // Avoid iterator invalidation
1108 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1109 E = toErase.end(); I != E; ++I)
1110 (*I)->eraseFromParent();
1116 return changed_function;