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 AA->onlyReadsMemory(C->getCalledFunction()))) {
481 Expression e = create_expression(C);
483 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
484 if (EI != expressionNumbering.end()) {
485 valueNumbering.insert(std::make_pair(V, EI->second));
488 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
489 valueNumbering.insert(std::make_pair(V, nextValueNumber));
491 return nextValueNumber++;
494 valueNumbering.insert(std::make_pair(V, nextValueNumber));
495 return nextValueNumber++;
497 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
498 Expression e = create_expression(BO);
500 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
501 if (EI != expressionNumbering.end()) {
502 valueNumbering.insert(std::make_pair(V, EI->second));
505 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
506 valueNumbering.insert(std::make_pair(V, nextValueNumber));
508 return nextValueNumber++;
510 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
511 Expression e = create_expression(C);
513 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
514 if (EI != expressionNumbering.end()) {
515 valueNumbering.insert(std::make_pair(V, EI->second));
518 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
519 valueNumbering.insert(std::make_pair(V, nextValueNumber));
521 return nextValueNumber++;
523 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
524 Expression e = create_expression(U);
526 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
527 if (EI != expressionNumbering.end()) {
528 valueNumbering.insert(std::make_pair(V, EI->second));
531 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
532 valueNumbering.insert(std::make_pair(V, nextValueNumber));
534 return nextValueNumber++;
536 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
537 Expression e = create_expression(U);
539 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
540 if (EI != expressionNumbering.end()) {
541 valueNumbering.insert(std::make_pair(V, EI->second));
544 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
545 valueNumbering.insert(std::make_pair(V, nextValueNumber));
547 return nextValueNumber++;
549 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
550 Expression e = create_expression(U);
552 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
553 if (EI != expressionNumbering.end()) {
554 valueNumbering.insert(std::make_pair(V, EI->second));
557 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
558 valueNumbering.insert(std::make_pair(V, nextValueNumber));
560 return nextValueNumber++;
562 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
563 Expression e = create_expression(U);
565 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
566 if (EI != expressionNumbering.end()) {
567 valueNumbering.insert(std::make_pair(V, EI->second));
570 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
571 valueNumbering.insert(std::make_pair(V, nextValueNumber));
573 return nextValueNumber++;
575 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
576 Expression e = create_expression(U);
578 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
579 if (EI != expressionNumbering.end()) {
580 valueNumbering.insert(std::make_pair(V, EI->second));
583 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
584 valueNumbering.insert(std::make_pair(V, nextValueNumber));
586 return nextValueNumber++;
588 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
589 Expression e = create_expression(U);
591 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
592 if (EI != expressionNumbering.end()) {
593 valueNumbering.insert(std::make_pair(V, EI->second));
596 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
597 valueNumbering.insert(std::make_pair(V, nextValueNumber));
599 return nextValueNumber++;
602 valueNumbering.insert(std::make_pair(V, nextValueNumber));
603 return nextValueNumber++;
607 /// lookup - Returns the value number of the specified value. Fails if
608 /// the value has not yet been numbered.
609 uint32_t ValueTable::lookup(Value* V) const {
610 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
611 if (VI != valueNumbering.end())
614 assert(0 && "Value not numbered?");
619 /// clear - Remove all entries from the ValueTable
620 void ValueTable::clear() {
621 valueNumbering.clear();
622 expressionNumbering.clear();
626 /// erase - Remove a value from the value numbering
627 void ValueTable::erase(Value* V) {
628 valueNumbering.erase(V);
631 //===----------------------------------------------------------------------===//
632 // ValueNumberedSet Class
633 //===----------------------------------------------------------------------===//
635 class ValueNumberedSet {
637 SmallPtrSet<Value*, 8> contents;
640 ValueNumberedSet() { numbers.resize(1); }
641 ValueNumberedSet(const ValueNumberedSet& other) {
642 numbers = other.numbers;
643 contents = other.contents;
646 typedef SmallPtrSet<Value*, 8>::iterator iterator;
648 iterator begin() { return contents.begin(); }
649 iterator end() { return contents.end(); }
651 bool insert(Value* v) { return contents.insert(v); }
652 void insert(iterator I, iterator E) { contents.insert(I, E); }
653 void erase(Value* v) { contents.erase(v); }
654 unsigned count(Value* v) { return contents.count(v); }
655 size_t size() { return contents.size(); }
657 void set(unsigned i) {
658 if (i >= numbers.size())
664 void operator=(const ValueNumberedSet& other) {
665 contents = other.contents;
666 numbers = other.numbers;
669 void reset(unsigned i) {
670 if (i < numbers.size())
674 bool test(unsigned i) {
675 if (i >= numbers.size())
678 return numbers.test(i);
688 //===----------------------------------------------------------------------===//
690 //===----------------------------------------------------------------------===//
694 class VISIBILITY_HIDDEN GVN : public FunctionPass {
695 bool runOnFunction(Function &F);
697 static char ID; // Pass identification, replacement for typeid
698 GVN() : FunctionPass((intptr_t)&ID) { }
703 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
705 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
709 // This transformation requires dominator postdominator info
710 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
711 AU.setPreservesCFG();
712 AU.addRequired<DominatorTree>();
713 AU.addRequired<MemoryDependenceAnalysis>();
714 AU.addRequired<AliasAnalysis>();
715 AU.addPreserved<AliasAnalysis>();
716 AU.addPreserved<MemoryDependenceAnalysis>();
720 // FIXME: eliminate or document these better
721 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
722 void val_insert(ValueNumberedSet& s, Value* v);
723 bool processLoad(LoadInst* L,
724 DenseMap<Value*, LoadInst*>& lastLoad,
725 SmallVector<Instruction*, 4>& toErase);
726 bool processInstruction(Instruction* I,
727 ValueNumberedSet& currAvail,
728 DenseMap<Value*, LoadInst*>& lastSeenLoad,
729 SmallVector<Instruction*, 4>& toErase);
730 bool processNonLocalLoad(LoadInst* L,
731 SmallVector<Instruction*, 4>& toErase);
732 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
733 DenseMap<BasicBlock*, Value*> &Phis,
734 bool top_level = false);
735 void dump(DenseMap<BasicBlock*, Value*>& d);
736 bool iterateOnFunction(Function &F);
737 Value* CollapsePhi(PHINode* p);
738 bool isSafeReplacement(PHINode* p, Instruction* inst);
745 // createGVNPass - The public interface to this file...
746 FunctionPass *llvm::createGVNPass() { return new GVN(); }
748 static RegisterPass<GVN> X("gvn",
749 "Global Value Numbering");
751 STATISTIC(NumGVNInstr, "Number of instructions deleted");
752 STATISTIC(NumGVNLoad, "Number of loads deleted");
754 /// find_leader - Given a set and a value number, return the first
755 /// element of the set with that value number, or 0 if no such element
757 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
761 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
763 if (v == VN.lookup(*I))
766 assert(0 && "No leader found, but present bit is set?");
770 /// val_insert - Insert a value into a set only if there is not a value
771 /// with the same value number already in the set
772 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
773 uint32_t num = VN.lookup(v);
778 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
780 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
781 E = d.end(); I != E; ++I) {
782 if (I->second == MemoryDependenceAnalysis::None)
790 Value* GVN::CollapsePhi(PHINode* p) {
791 DominatorTree &DT = getAnalysis<DominatorTree>();
792 Value* constVal = p->hasConstantValue();
795 if (Instruction* inst = dyn_cast<Instruction>(constVal)) {
796 if (DT.dominates(inst, p))
797 if (isSafeReplacement(p, inst))
807 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
808 if (!isa<PHINode>(inst))
811 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
813 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
814 if (use_phi->getParent() == inst->getParent())
820 /// GetValueForBlock - Get the value to use within the specified basic block.
821 /// available values are in Phis.
822 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
823 DenseMap<BasicBlock*, Value*> &Phis,
826 // If we have already computed this value, return the previously computed val.
827 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
828 if (V != Phis.end() && !top_level) return V->second;
830 BasicBlock* singlePred = BB->getSinglePredecessor();
832 Value *ret = GetValueForBlock(singlePred, orig, Phis);
836 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
837 // now, then get values to fill in the incoming values for the PHI.
838 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
840 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
842 if (Phis.count(BB) == 0)
843 Phis.insert(std::make_pair(BB, PN));
845 // Fill in the incoming values for the block.
846 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
847 Value* val = GetValueForBlock(*PI, orig, Phis);
849 PN->addIncoming(val, *PI);
852 // Attempt to collapse PHI nodes that are trivially redundant
853 Value* v = CollapsePhi(PN);
855 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
857 MD.removeInstruction(PN);
858 PN->replaceAllUsesWith(v);
860 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
861 E = Phis.end(); I != E; ++I)
865 PN->eraseFromParent();
872 // Cache our phi construction results
873 phiMap[orig->getPointerOperand()].insert(PN);
877 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
878 /// non-local by performing PHI construction.
879 bool GVN::processNonLocalLoad(LoadInst* L,
880 SmallVector<Instruction*, 4>& toErase) {
881 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
883 // Find the non-local dependencies of the load
884 DenseMap<BasicBlock*, Value*> deps;
885 MD.getNonLocalDependency(L, deps);
887 DenseMap<BasicBlock*, Value*> repl;
889 // Filter out useless results (non-locals, etc)
890 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
892 if (I->second == MemoryDependenceAnalysis::None) {
894 } else if (I->second == MemoryDependenceAnalysis::NonLocal) {
896 } else if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
897 if (S->getPointerOperand() == L->getPointerOperand())
898 repl[I->first] = S->getOperand(0);
901 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
902 if (LD->getPointerOperand() == L->getPointerOperand())
910 // Use cached PHI construction information from previous runs
911 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
912 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
914 if ((*I)->getParent() == L->getParent()) {
915 MD.removeInstruction(L);
916 L->replaceAllUsesWith(*I);
917 toErase.push_back(L);
922 repl.insert(std::make_pair((*I)->getParent(), *I));
926 // Perform PHI construction
927 SmallPtrSet<BasicBlock*, 4> visited;
928 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
930 MD.removeInstruction(L);
931 L->replaceAllUsesWith(v);
932 toErase.push_back(L);
938 /// processLoad - Attempt to eliminate a load, first by eliminating it
939 /// locally, and then attempting non-local elimination if that fails.
940 bool GVN::processLoad(LoadInst* L,
941 DenseMap<Value*, LoadInst*>& lastLoad,
942 SmallVector<Instruction*, 4>& toErase) {
943 if (L->isVolatile()) {
944 lastLoad[L->getPointerOperand()] = L;
948 Value* pointer = L->getPointerOperand();
949 LoadInst*& last = lastLoad[pointer];
951 // ... to a pointer that has been loaded from before...
952 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
953 bool removedNonLocal = false;
954 Instruction* dep = MD.getDependency(L);
955 if (dep == MemoryDependenceAnalysis::NonLocal &&
956 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
957 removedNonLocal = processNonLocalLoad(L, toErase);
959 if (!removedNonLocal)
962 return removedNonLocal;
966 bool deletedLoad = false;
968 // Walk up the dependency chain until we either find
969 // a dependency we can use, or we can't walk any further
970 while (dep != MemoryDependenceAnalysis::None &&
971 dep != MemoryDependenceAnalysis::NonLocal &&
972 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
973 // ... that depends on a store ...
974 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
975 if (S->getPointerOperand() == pointer) {
977 MD.removeInstruction(L);
979 L->replaceAllUsesWith(S->getOperand(0));
980 toErase.push_back(L);
985 // Whether we removed it or not, we can't
989 // If we don't depend on a store, and we haven't
990 // been loaded before, bail.
992 } else if (dep == last) {
994 MD.removeInstruction(L);
996 L->replaceAllUsesWith(last);
997 toErase.push_back(L);
1003 dep = MD.getDependency(L, dep);
1013 /// processInstruction - When calculating availability, handle an instruction
1014 /// by inserting it into the appropriate sets
1015 bool GVN::processInstruction(Instruction* I,
1016 ValueNumberedSet& currAvail,
1017 DenseMap<Value*, LoadInst*>& lastSeenLoad,
1018 SmallVector<Instruction*, 4>& toErase) {
1019 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1020 return processLoad(L, lastSeenLoad, toErase);
1023 unsigned num = VN.lookup_or_add(I);
1025 // Collapse PHI nodes
1026 if (PHINode* p = dyn_cast<PHINode>(I)) {
1027 Value* constVal = CollapsePhi(p);
1030 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1032 if (PI->second.count(p))
1033 PI->second.erase(p);
1035 p->replaceAllUsesWith(constVal);
1036 toErase.push_back(p);
1038 // Perform value-number based elimination
1039 } else if (currAvail.test(num)) {
1040 Value* repl = find_leader(currAvail, num);
1042 if (CallInst* CI = dyn_cast<CallInst>(I)) {
1043 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1044 if (CI->getCalledFunction() &&
1045 !AA.doesNotAccessMemory(CI->getCalledFunction())) {
1046 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1047 if (MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1048 // There must be an intervening may-alias store, so nothing from
1049 // this point on will be able to be replaced with the preceding call
1050 currAvail.erase(repl);
1051 currAvail.insert(I);
1059 I->replaceAllUsesWith(repl);
1060 toErase.push_back(I);
1062 } else if (!I->isTerminator()) {
1064 currAvail.insert(I);
1070 // GVN::runOnFunction - This is the main transformation entry point for a
1073 bool GVN::runOnFunction(Function& F) {
1074 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1076 bool changed = false;
1077 bool shouldContinue = true;
1079 while (shouldContinue) {
1080 shouldContinue = iterateOnFunction(F);
1081 changed |= shouldContinue;
1088 // GVN::iterateOnFunction - Executes one iteration of GVN
1089 bool GVN::iterateOnFunction(Function &F) {
1090 // Clean out global sets from any previous functions
1092 availableOut.clear();
1095 bool changed_function = false;
1097 DominatorTree &DT = getAnalysis<DominatorTree>();
1099 SmallVector<Instruction*, 4> toErase;
1101 // Top-down walk of the dominator tree
1102 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1103 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1105 // Get the set to update for this block
1106 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1107 DenseMap<Value*, LoadInst*> lastSeenLoad;
1109 BasicBlock* BB = DI->getBlock();
1111 // A block inherits AVAIL_OUT from its dominator
1112 if (DI->getIDom() != 0)
1113 currAvail = availableOut[DI->getIDom()->getBlock()];
1115 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1117 changed_function |= processInstruction(BI, currAvail,
1118 lastSeenLoad, toErase);
1120 NumGVNInstr += toErase.size();
1122 // Avoid iterator invalidation
1125 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1126 E = toErase.end(); I != E; ++I)
1127 (*I)->eraseFromParent();
1133 return changed_function;