1 //===- GVN.cpp - Eliminate redundant values and loads ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/BasicBlock.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Value.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/DepthFirstIterator.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/SparseBitVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
38 STATISTIC(NumGVNInstr, "Number of instructions deleted");
39 STATISTIC(NumGVNLoad, "Number of loads deleted");
41 //===----------------------------------------------------------------------===//
43 //===----------------------------------------------------------------------===//
45 /// This class holds the mapping between values and value numbers. It is used
46 /// as an efficient mechanism to determine the expression-wise equivalence of
49 struct VISIBILITY_HIDDEN Expression {
50 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
51 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
52 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
53 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
54 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
55 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
56 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
57 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
58 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
59 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
62 ExpressionOpcode opcode;
67 SmallVector<uint32_t, 4> varargs;
71 Expression(ExpressionOpcode o) : opcode(o) { }
73 bool operator==(const Expression &other) const {
74 if (opcode != other.opcode)
76 else if (opcode == EMPTY || opcode == TOMBSTONE)
78 else if (type != other.type)
80 else if (function != other.function)
82 else if (firstVN != other.firstVN)
84 else if (secondVN != other.secondVN)
86 else if (thirdVN != other.thirdVN)
89 if (varargs.size() != other.varargs.size())
92 for (size_t i = 0; i < varargs.size(); ++i)
93 if (varargs[i] != other.varargs[i])
100 bool operator!=(const Expression &other) const {
101 if (opcode != other.opcode)
103 else if (opcode == EMPTY || opcode == TOMBSTONE)
105 else if (type != other.type)
107 else if (function != other.function)
109 else if (firstVN != other.firstVN)
111 else if (secondVN != other.secondVN)
113 else if (thirdVN != other.thirdVN)
116 if (varargs.size() != other.varargs.size())
119 for (size_t i = 0; i < varargs.size(); ++i)
120 if (varargs[i] != other.varargs[i])
128 class VISIBILITY_HIDDEN ValueTable {
130 DenseMap<Value*, uint32_t> valueNumbering;
131 DenseMap<Expression, uint32_t> expressionNumbering;
133 MemoryDependenceAnalysis* MD;
136 uint32_t nextValueNumber;
138 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
139 Expression::ExpressionOpcode getOpcode(CmpInst* C);
140 Expression::ExpressionOpcode getOpcode(CastInst* C);
141 Expression create_expression(BinaryOperator* BO);
142 Expression create_expression(CmpInst* C);
143 Expression create_expression(ShuffleVectorInst* V);
144 Expression create_expression(ExtractElementInst* C);
145 Expression create_expression(InsertElementInst* V);
146 Expression create_expression(SelectInst* V);
147 Expression create_expression(CastInst* C);
148 Expression create_expression(GetElementPtrInst* G);
149 Expression create_expression(CallInst* C);
150 Expression create_expression(Constant* C);
152 ValueTable() : nextValueNumber(1) { }
153 uint32_t lookup_or_add(Value* V);
154 uint32_t lookup(Value* V) const;
155 void add(Value* V, uint32_t num);
157 void erase(Value* v);
159 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
160 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
161 void setDomTree(DominatorTree* D) { DT = D; }
166 template <> struct DenseMapInfo<Expression> {
167 static inline Expression getEmptyKey() {
168 return Expression(Expression::EMPTY);
171 static inline Expression getTombstoneKey() {
172 return Expression(Expression::TOMBSTONE);
175 static unsigned getHashValue(const Expression e) {
176 unsigned hash = e.opcode;
178 hash = e.firstVN + hash * 37;
179 hash = e.secondVN + hash * 37;
180 hash = e.thirdVN + hash * 37;
182 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
183 (unsigned)((uintptr_t)e.type >> 9)) +
186 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
187 E = e.varargs.end(); I != E; ++I)
188 hash = *I + hash * 37;
190 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
191 (unsigned)((uintptr_t)e.function >> 9)) +
196 static bool isEqual(const Expression &LHS, const Expression &RHS) {
199 static bool isPod() { return true; }
203 //===----------------------------------------------------------------------===//
204 // ValueTable Internal Functions
205 //===----------------------------------------------------------------------===//
206 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
207 switch(BO->getOpcode()) {
208 default: // THIS SHOULD NEVER HAPPEN
209 assert(0 && "Binary operator with unknown opcode?");
210 case Instruction::Add: return Expression::ADD;
211 case Instruction::Sub: return Expression::SUB;
212 case Instruction::Mul: return Expression::MUL;
213 case Instruction::UDiv: return Expression::UDIV;
214 case Instruction::SDiv: return Expression::SDIV;
215 case Instruction::FDiv: return Expression::FDIV;
216 case Instruction::URem: return Expression::UREM;
217 case Instruction::SRem: return Expression::SREM;
218 case Instruction::FRem: return Expression::FREM;
219 case Instruction::Shl: return Expression::SHL;
220 case Instruction::LShr: return Expression::LSHR;
221 case Instruction::AShr: return Expression::ASHR;
222 case Instruction::And: return Expression::AND;
223 case Instruction::Or: return Expression::OR;
224 case Instruction::Xor: return Expression::XOR;
228 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
229 if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
230 switch (C->getPredicate()) {
231 default: // THIS SHOULD NEVER HAPPEN
232 assert(0 && "Comparison with unknown predicate?");
233 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
234 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
235 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
236 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
237 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
238 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
239 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
240 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
241 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
242 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
245 assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
246 switch (C->getPredicate()) {
247 default: // THIS SHOULD NEVER HAPPEN
248 assert(0 && "Comparison with unknown predicate?");
249 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
250 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
251 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
252 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
253 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
254 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
255 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
256 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
257 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
258 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
259 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
260 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
261 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
262 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
266 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
267 switch(C->getOpcode()) {
268 default: // THIS SHOULD NEVER HAPPEN
269 assert(0 && "Cast operator with unknown opcode?");
270 case Instruction::Trunc: return Expression::TRUNC;
271 case Instruction::ZExt: return Expression::ZEXT;
272 case Instruction::SExt: return Expression::SEXT;
273 case Instruction::FPToUI: return Expression::FPTOUI;
274 case Instruction::FPToSI: return Expression::FPTOSI;
275 case Instruction::UIToFP: return Expression::UITOFP;
276 case Instruction::SIToFP: return Expression::SITOFP;
277 case Instruction::FPTrunc: return Expression::FPTRUNC;
278 case Instruction::FPExt: return Expression::FPEXT;
279 case Instruction::PtrToInt: return Expression::PTRTOINT;
280 case Instruction::IntToPtr: return Expression::INTTOPTR;
281 case Instruction::BitCast: return Expression::BITCAST;
285 Expression ValueTable::create_expression(CallInst* C) {
288 e.type = C->getType();
292 e.function = C->getCalledFunction();
293 e.opcode = Expression::CALL;
295 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
297 e.varargs.push_back(lookup_or_add(*I));
302 Expression ValueTable::create_expression(BinaryOperator* BO) {
305 e.firstVN = lookup_or_add(BO->getOperand(0));
306 e.secondVN = lookup_or_add(BO->getOperand(1));
309 e.type = BO->getType();
310 e.opcode = getOpcode(BO);
315 Expression ValueTable::create_expression(CmpInst* C) {
318 e.firstVN = lookup_or_add(C->getOperand(0));
319 e.secondVN = lookup_or_add(C->getOperand(1));
322 e.type = C->getType();
323 e.opcode = getOpcode(C);
328 Expression ValueTable::create_expression(CastInst* C) {
331 e.firstVN = lookup_or_add(C->getOperand(0));
335 e.type = C->getType();
336 e.opcode = getOpcode(C);
341 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
344 e.firstVN = lookup_or_add(S->getOperand(0));
345 e.secondVN = lookup_or_add(S->getOperand(1));
346 e.thirdVN = lookup_or_add(S->getOperand(2));
348 e.type = S->getType();
349 e.opcode = Expression::SHUFFLE;
354 Expression ValueTable::create_expression(ExtractElementInst* E) {
357 e.firstVN = lookup_or_add(E->getOperand(0));
358 e.secondVN = lookup_or_add(E->getOperand(1));
361 e.type = E->getType();
362 e.opcode = Expression::EXTRACT;
367 Expression ValueTable::create_expression(InsertElementInst* I) {
370 e.firstVN = lookup_or_add(I->getOperand(0));
371 e.secondVN = lookup_or_add(I->getOperand(1));
372 e.thirdVN = lookup_or_add(I->getOperand(2));
374 e.type = I->getType();
375 e.opcode = Expression::INSERT;
380 Expression ValueTable::create_expression(SelectInst* I) {
383 e.firstVN = lookup_or_add(I->getCondition());
384 e.secondVN = lookup_or_add(I->getTrueValue());
385 e.thirdVN = lookup_or_add(I->getFalseValue());
387 e.type = I->getType();
388 e.opcode = Expression::SELECT;
393 Expression ValueTable::create_expression(GetElementPtrInst* G) {
396 e.firstVN = lookup_or_add(G->getPointerOperand());
400 e.type = G->getType();
401 e.opcode = Expression::GEP;
403 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
405 e.varargs.push_back(lookup_or_add(*I));
410 //===----------------------------------------------------------------------===//
411 // ValueTable External Functions
412 //===----------------------------------------------------------------------===//
414 /// lookup_or_add - Returns the value number for the specified value, assigning
415 /// it a new number if it did not have one before.
416 uint32_t ValueTable::lookup_or_add(Value* V) {
417 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
418 if (VI != valueNumbering.end())
421 if (CallInst* C = dyn_cast<CallInst>(V)) {
422 if (AA->doesNotAccessMemory(C)) {
423 Expression e = create_expression(C);
425 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
426 if (EI != expressionNumbering.end()) {
427 valueNumbering.insert(std::make_pair(V, EI->second));
430 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
431 valueNumbering.insert(std::make_pair(V, nextValueNumber));
433 return nextValueNumber++;
435 } else if (AA->onlyReadsMemory(C)) {
436 Expression e = create_expression(C);
438 if (expressionNumbering.find(e) == expressionNumbering.end()) {
439 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
440 valueNumbering.insert(std::make_pair(V, nextValueNumber));
441 return nextValueNumber++;
444 Instruction* local_dep = MD->getDependency(C);
446 if (local_dep == MemoryDependenceAnalysis::None) {
447 valueNumbering.insert(std::make_pair(V, nextValueNumber));
448 return nextValueNumber++;
449 } else if (local_dep != MemoryDependenceAnalysis::NonLocal) {
450 if (!isa<CallInst>(local_dep)) {
451 valueNumbering.insert(std::make_pair(V, nextValueNumber));
452 return nextValueNumber++;
455 CallInst* local_cdep = cast<CallInst>(local_dep);
457 if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
458 local_cdep->getNumOperands() != C->getNumOperands()) {
459 valueNumbering.insert(std::make_pair(V, nextValueNumber));
460 return nextValueNumber++;
461 } else if (!C->getCalledFunction()) {
462 valueNumbering.insert(std::make_pair(V, nextValueNumber));
463 return nextValueNumber++;
465 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
466 uint32_t c_vn = lookup_or_add(C->getOperand(i));
467 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
469 valueNumbering.insert(std::make_pair(V, nextValueNumber));
470 return nextValueNumber++;
474 uint32_t v = lookup_or_add(local_cdep);
475 valueNumbering.insert(std::make_pair(V, v));
481 DenseMap<BasicBlock*, Value*> deps;
482 MD->getNonLocalDependency(C, deps);
485 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(),
486 E = deps.end(); I != E; ++I) {
487 if (I->second == MemoryDependenceAnalysis::None) {
488 valueNumbering.insert(std::make_pair(V, nextValueNumber));
490 return nextValueNumber++;
491 } else if (I->second != MemoryDependenceAnalysis::NonLocal) {
492 if (DT->dominates(I->first, C->getParent())) {
493 if (CallInst* CD = dyn_cast<CallInst>(I->second))
496 valueNumbering.insert(std::make_pair(V, nextValueNumber));
497 return nextValueNumber++;
500 valueNumbering.insert(std::make_pair(V, nextValueNumber));
501 return nextValueNumber++;
507 valueNumbering.insert(std::make_pair(V, nextValueNumber));
508 return nextValueNumber++;
511 if (cdep->getCalledFunction() != C->getCalledFunction() ||
512 cdep->getNumOperands() != C->getNumOperands()) {
513 valueNumbering.insert(std::make_pair(V, nextValueNumber));
514 return nextValueNumber++;
515 } else if (!C->getCalledFunction()) {
516 valueNumbering.insert(std::make_pair(V, nextValueNumber));
517 return nextValueNumber++;
519 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
520 uint32_t c_vn = lookup_or_add(C->getOperand(i));
521 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
523 valueNumbering.insert(std::make_pair(V, nextValueNumber));
524 return nextValueNumber++;
528 uint32_t v = lookup_or_add(cdep);
529 valueNumbering.insert(std::make_pair(V, v));
534 valueNumbering.insert(std::make_pair(V, nextValueNumber));
535 return nextValueNumber++;
537 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
538 Expression e = create_expression(BO);
540 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
541 if (EI != expressionNumbering.end()) {
542 valueNumbering.insert(std::make_pair(V, EI->second));
545 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
546 valueNumbering.insert(std::make_pair(V, nextValueNumber));
548 return nextValueNumber++;
550 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
551 Expression e = create_expression(C);
553 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
554 if (EI != expressionNumbering.end()) {
555 valueNumbering.insert(std::make_pair(V, EI->second));
558 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
559 valueNumbering.insert(std::make_pair(V, nextValueNumber));
561 return nextValueNumber++;
563 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
564 Expression e = create_expression(U);
566 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
567 if (EI != expressionNumbering.end()) {
568 valueNumbering.insert(std::make_pair(V, EI->second));
571 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
572 valueNumbering.insert(std::make_pair(V, nextValueNumber));
574 return nextValueNumber++;
576 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
577 Expression e = create_expression(U);
579 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
580 if (EI != expressionNumbering.end()) {
581 valueNumbering.insert(std::make_pair(V, EI->second));
584 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
585 valueNumbering.insert(std::make_pair(V, nextValueNumber));
587 return nextValueNumber++;
589 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
590 Expression e = create_expression(U);
592 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
593 if (EI != expressionNumbering.end()) {
594 valueNumbering.insert(std::make_pair(V, EI->second));
597 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
598 valueNumbering.insert(std::make_pair(V, nextValueNumber));
600 return nextValueNumber++;
602 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
603 Expression e = create_expression(U);
605 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
606 if (EI != expressionNumbering.end()) {
607 valueNumbering.insert(std::make_pair(V, EI->second));
610 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
611 valueNumbering.insert(std::make_pair(V, nextValueNumber));
613 return nextValueNumber++;
615 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
616 Expression e = create_expression(U);
618 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
619 if (EI != expressionNumbering.end()) {
620 valueNumbering.insert(std::make_pair(V, EI->second));
623 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
624 valueNumbering.insert(std::make_pair(V, nextValueNumber));
626 return nextValueNumber++;
628 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
629 Expression e = create_expression(U);
631 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
632 if (EI != expressionNumbering.end()) {
633 valueNumbering.insert(std::make_pair(V, EI->second));
636 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
637 valueNumbering.insert(std::make_pair(V, nextValueNumber));
639 return nextValueNumber++;
642 valueNumbering.insert(std::make_pair(V, nextValueNumber));
643 return nextValueNumber++;
647 /// lookup - Returns the value number of the specified value. Fails if
648 /// the value has not yet been numbered.
649 uint32_t ValueTable::lookup(Value* V) const {
650 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
651 assert(VI != valueNumbering.end() && "Value not numbered?");
655 /// clear - Remove all entries from the ValueTable
656 void ValueTable::clear() {
657 valueNumbering.clear();
658 expressionNumbering.clear();
662 /// erase - Remove a value from the value numbering
663 void ValueTable::erase(Value* V) {
664 valueNumbering.erase(V);
667 //===----------------------------------------------------------------------===//
668 // ValueNumberedSet Class
669 //===----------------------------------------------------------------------===//
671 class VISIBILITY_HIDDEN ValueNumberedSet {
673 SmallPtrSet<Value*, 8> contents;
674 SparseBitVector<64> numbers;
676 ValueNumberedSet() { }
677 ValueNumberedSet(const ValueNumberedSet& other) {
678 numbers = other.numbers;
679 contents = other.contents;
682 typedef SmallPtrSet<Value*, 8>::iterator iterator;
684 iterator begin() { return contents.begin(); }
685 iterator end() { return contents.end(); }
687 bool insert(Value* v) { return contents.insert(v); }
688 void insert(iterator I, iterator E) { contents.insert(I, E); }
689 void erase(Value* v) { contents.erase(v); }
690 unsigned count(Value* v) { return contents.count(v); }
691 size_t size() { return contents.size(); }
693 void set(unsigned i) {
697 void operator=(const ValueNumberedSet& other) {
698 contents = other.contents;
699 numbers = other.numbers;
702 void reset(unsigned i) {
706 bool test(unsigned i) {
707 return numbers.test(i);
712 //===----------------------------------------------------------------------===//
714 //===----------------------------------------------------------------------===//
718 class VISIBILITY_HIDDEN GVN : public FunctionPass {
719 bool runOnFunction(Function &F);
721 static char ID; // Pass identification, replacement for typeid
722 GVN() : FunctionPass((intptr_t)&ID) { }
727 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
729 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
733 // This transformation requires dominator postdominator info
734 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
735 AU.setPreservesCFG();
736 AU.addRequired<DominatorTree>();
737 AU.addRequired<MemoryDependenceAnalysis>();
738 AU.addRequired<AliasAnalysis>();
739 AU.addPreserved<AliasAnalysis>();
740 AU.addPreserved<MemoryDependenceAnalysis>();
744 // FIXME: eliminate or document these better
745 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
746 void val_insert(ValueNumberedSet& s, Value* v);
747 bool processLoad(LoadInst* L,
748 DenseMap<Value*, LoadInst*> &lastLoad,
749 SmallVectorImpl<Instruction*> &toErase);
750 bool processInstruction(Instruction* I,
751 ValueNumberedSet& currAvail,
752 DenseMap<Value*, LoadInst*>& lastSeenLoad,
753 SmallVectorImpl<Instruction*> &toErase);
754 bool processNonLocalLoad(LoadInst* L,
755 SmallVectorImpl<Instruction*> &toErase);
756 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
757 DenseMap<BasicBlock*, Value*> &Phis,
758 bool top_level = false);
759 void dump(DenseMap<BasicBlock*, Value*>& d);
760 bool iterateOnFunction(Function &F);
761 Value* CollapsePhi(PHINode* p);
762 bool isSafeReplacement(PHINode* p, Instruction* inst);
768 // createGVNPass - The public interface to this file...
769 FunctionPass *llvm::createGVNPass() { return new GVN(); }
771 static RegisterPass<GVN> X("gvn",
772 "Global Value Numbering");
774 /// find_leader - Given a set and a value number, return the first
775 /// element of the set with that value number, or 0 if no such element
777 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
781 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
783 if (v == VN.lookup(*I))
786 assert(0 && "No leader found, but present bit is set?");
790 /// val_insert - Insert a value into a set only if there is not a value
791 /// with the same value number already in the set
792 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
793 uint32_t num = VN.lookup(v);
798 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
800 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
801 E = d.end(); I != E; ++I) {
802 if (I->second == MemoryDependenceAnalysis::None)
810 Value* GVN::CollapsePhi(PHINode* p) {
811 DominatorTree &DT = getAnalysis<DominatorTree>();
812 Value* constVal = p->hasConstantValue();
814 if (!constVal) return 0;
816 Instruction* inst = dyn_cast<Instruction>(constVal);
820 if (DT.dominates(inst, p))
821 if (isSafeReplacement(p, inst))
826 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
827 if (!isa<PHINode>(inst))
830 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
832 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
833 if (use_phi->getParent() == inst->getParent())
839 /// GetValueForBlock - Get the value to use within the specified basic block.
840 /// available values are in Phis.
841 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
842 DenseMap<BasicBlock*, Value*> &Phis,
845 // If we have already computed this value, return the previously computed val.
846 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
847 if (V != Phis.end() && !top_level) return V->second;
849 BasicBlock* singlePred = BB->getSinglePredecessor();
851 Value *ret = GetValueForBlock(singlePred, orig, Phis);
856 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
857 // now, then get values to fill in the incoming values for the PHI.
858 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
860 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
862 if (Phis.count(BB) == 0)
863 Phis.insert(std::make_pair(BB, PN));
865 // Fill in the incoming values for the block.
866 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
867 Value* val = GetValueForBlock(*PI, orig, Phis);
868 PN->addIncoming(val, *PI);
871 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
872 AA.copyValue(orig, PN);
874 // Attempt to collapse PHI nodes that are trivially redundant
875 Value* v = CollapsePhi(PN);
877 // Cache our phi construction results
878 phiMap[orig->getPointerOperand()].insert(PN);
882 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
884 MD.removeInstruction(PN);
885 PN->replaceAllUsesWith(v);
887 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
888 E = Phis.end(); I != E; ++I)
892 PN->eraseFromParent();
898 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
899 /// non-local by performing PHI construction.
900 bool GVN::processNonLocalLoad(LoadInst* L,
901 SmallVectorImpl<Instruction*> &toErase) {
902 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
904 // Find the non-local dependencies of the load
905 DenseMap<BasicBlock*, Value*> deps;
906 MD.getNonLocalDependency(L, deps);
908 DenseMap<BasicBlock*, Value*> repl;
910 // Filter out useless results (non-locals, etc)
911 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
913 if (I->second == MemoryDependenceAnalysis::None)
916 if (I->second == MemoryDependenceAnalysis::NonLocal)
919 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
920 if (S->getPointerOperand() != L->getPointerOperand())
922 repl[I->first] = S->getOperand(0);
923 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
924 if (LD->getPointerOperand() != L->getPointerOperand())
932 // Use cached PHI construction information from previous runs
933 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
934 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
936 if ((*I)->getParent() == L->getParent()) {
937 MD.removeInstruction(L);
938 L->replaceAllUsesWith(*I);
939 toErase.push_back(L);
944 repl.insert(std::make_pair((*I)->getParent(), *I));
947 // Perform PHI construction
948 SmallPtrSet<BasicBlock*, 4> visited;
949 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
951 MD.removeInstruction(L);
952 L->replaceAllUsesWith(v);
953 toErase.push_back(L);
959 /// processLoad - Attempt to eliminate a load, first by eliminating it
960 /// locally, and then attempting non-local elimination if that fails.
961 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
962 SmallVectorImpl<Instruction*> &toErase) {
963 if (L->isVolatile()) {
964 lastLoad[L->getPointerOperand()] = L;
968 Value* pointer = L->getPointerOperand();
969 LoadInst*& last = lastLoad[pointer];
971 // ... to a pointer that has been loaded from before...
972 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
973 bool removedNonLocal = false;
974 Instruction* dep = MD.getDependency(L);
975 if (dep == MemoryDependenceAnalysis::NonLocal &&
976 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
977 removedNonLocal = processNonLocalLoad(L, toErase);
979 if (!removedNonLocal)
982 return removedNonLocal;
986 bool deletedLoad = false;
988 // Walk up the dependency chain until we either find
989 // a dependency we can use, or we can't walk any further
990 while (dep != MemoryDependenceAnalysis::None &&
991 dep != MemoryDependenceAnalysis::NonLocal &&
992 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
993 // ... that depends on a store ...
994 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
995 if (S->getPointerOperand() == pointer) {
997 MD.removeInstruction(L);
999 L->replaceAllUsesWith(S->getOperand(0));
1000 toErase.push_back(L);
1005 // Whether we removed it or not, we can't
1009 // If we don't depend on a store, and we haven't
1010 // been loaded before, bail.
1012 } else if (dep == last) {
1014 MD.removeInstruction(L);
1016 L->replaceAllUsesWith(last);
1017 toErase.push_back(L);
1023 dep = MD.getDependency(L, dep);
1027 if (dep != MemoryDependenceAnalysis::None &&
1028 dep != MemoryDependenceAnalysis::NonLocal &&
1029 isa<AllocationInst>(dep)) {
1030 // Check that this load is actually from the
1031 // allocation we found
1032 Value* v = L->getOperand(0);
1034 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
1035 v = BC->getOperand(0);
1036 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
1037 v = GEP->getOperand(0);
1042 // If this load depends directly on an allocation, there isn't
1043 // anything stored there; therefore, we can optimize this load
1045 MD.removeInstruction(L);
1047 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1048 toErase.push_back(L);
1060 /// processInstruction - When calculating availability, handle an instruction
1061 /// by inserting it into the appropriate sets
1062 bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1063 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1064 SmallVectorImpl<Instruction*> &toErase) {
1065 if (LoadInst* L = dyn_cast<LoadInst>(I))
1066 return processLoad(L, lastSeenLoad, toErase);
1068 // Allocations are always uniquely numbered, so we can save time and memory
1069 // by fast failing them.
1070 if (isa<AllocationInst>(I))
1073 unsigned num = VN.lookup_or_add(I);
1075 // Collapse PHI nodes
1076 if (PHINode* p = dyn_cast<PHINode>(I)) {
1077 Value* constVal = CollapsePhi(p);
1080 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1082 if (PI->second.count(p))
1083 PI->second.erase(p);
1085 p->replaceAllUsesWith(constVal);
1086 toErase.push_back(p);
1088 // Perform value-number based elimination
1089 } else if (currAvail.test(num)) {
1090 Value* repl = find_leader(currAvail, num);
1093 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1094 MD.removeInstruction(I);
1097 I->replaceAllUsesWith(repl);
1098 toErase.push_back(I);
1100 } else if (!I->isTerminator()) {
1102 currAvail.insert(I);
1108 // GVN::runOnFunction - This is the main transformation entry point for a
1111 bool GVN::runOnFunction(Function& F) {
1112 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1113 VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1114 VN.setDomTree(&getAnalysis<DominatorTree>());
1116 bool changed = false;
1117 bool shouldContinue = true;
1119 while (shouldContinue) {
1120 shouldContinue = iterateOnFunction(F);
1121 changed |= shouldContinue;
1128 // GVN::iterateOnFunction - Executes one iteration of GVN
1129 bool GVN::iterateOnFunction(Function &F) {
1130 // Clean out global sets from any previous functions
1132 availableOut.clear();
1135 bool changed_function = false;
1137 DominatorTree &DT = getAnalysis<DominatorTree>();
1139 SmallVector<Instruction*, 8> toErase;
1140 DenseMap<Value*, LoadInst*> lastSeenLoad;
1141 DenseMap<DomTreeNode*, size_t> numChildrenVisited;
1143 // Top-down walk of the dominator tree
1144 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1145 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1147 // Get the set to update for this block
1148 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1149 lastSeenLoad.clear();
1151 BasicBlock* BB = DI->getBlock();
1153 // A block inherits AVAIL_OUT from its dominator
1154 if (DI->getIDom() != 0) {
1155 currAvail = availableOut[DI->getIDom()->getBlock()];
1157 numChildrenVisited[DI->getIDom()]++;
1159 if (numChildrenVisited[DI->getIDom()] == DI->getIDom()->getNumChildren()) {
1160 availableOut.erase(DI->getIDom()->getBlock());
1161 numChildrenVisited.erase(DI->getIDom());
1165 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1167 changed_function |= processInstruction(BI, currAvail,
1168 lastSeenLoad, toErase);
1169 if (toErase.empty()) {
1174 // If we need some instructions deleted, do it now.
1175 NumGVNInstr += toErase.size();
1177 // Avoid iterator invalidation.
1178 bool AtStart = BI == BB->begin();
1182 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1183 E = toErase.end(); I != E; ++I)
1184 (*I)->eraseFromParent();
1195 return changed_function;