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 // Note that this pass does the value numbering itself, it does not use the
14 // ValueNumbering analysis passes.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "gvn"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/BasicBlock.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Value.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/Dominators.h"
32 #include "llvm/Analysis/AliasAnalysis.h"
33 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
34 #include "llvm/Support/CFG.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 STATISTIC(NumGVNInstr, "Number of instructions deleted");
42 STATISTIC(NumGVNLoad, "Number of loads deleted");
43 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
45 static cl::opt<bool> DisablePRE("disable-pre",
46 cl::init(false), cl::Hidden);
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 /// This class holds the mapping between values and value numbers. It is used
53 /// as an efficient mechanism to determine the expression-wise equivalence of
56 struct VISIBILITY_HIDDEN Expression {
57 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
58 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
59 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
60 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
61 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
62 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
63 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
64 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
65 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
66 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
69 ExpressionOpcode opcode;
74 SmallVector<uint32_t, 4> varargs;
78 Expression(ExpressionOpcode o) : opcode(o) { }
80 bool operator==(const Expression &other) const {
81 if (opcode != other.opcode)
83 else if (opcode == EMPTY || opcode == TOMBSTONE)
85 else if (type != other.type)
87 else if (function != other.function)
89 else if (firstVN != other.firstVN)
91 else if (secondVN != other.secondVN)
93 else if (thirdVN != other.thirdVN)
96 if (varargs.size() != other.varargs.size())
99 for (size_t i = 0; i < varargs.size(); ++i)
100 if (varargs[i] != other.varargs[i])
107 bool operator!=(const Expression &other) const {
108 if (opcode != other.opcode)
110 else if (opcode == EMPTY || opcode == TOMBSTONE)
112 else if (type != other.type)
114 else if (function != other.function)
116 else if (firstVN != other.firstVN)
118 else if (secondVN != other.secondVN)
120 else if (thirdVN != other.thirdVN)
123 if (varargs.size() != other.varargs.size())
126 for (size_t i = 0; i < varargs.size(); ++i)
127 if (varargs[i] != other.varargs[i])
135 class VISIBILITY_HIDDEN ValueTable {
137 DenseMap<Value*, uint32_t> valueNumbering;
138 DenseMap<Expression, uint32_t> expressionNumbering;
140 MemoryDependenceAnalysis* MD;
143 uint32_t nextValueNumber;
145 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
146 Expression::ExpressionOpcode getOpcode(CmpInst* C);
147 Expression::ExpressionOpcode getOpcode(CastInst* C);
148 Expression create_expression(BinaryOperator* BO);
149 Expression create_expression(CmpInst* C);
150 Expression create_expression(ShuffleVectorInst* V);
151 Expression create_expression(ExtractElementInst* C);
152 Expression create_expression(InsertElementInst* V);
153 Expression create_expression(SelectInst* V);
154 Expression create_expression(CastInst* C);
155 Expression create_expression(GetElementPtrInst* G);
156 Expression create_expression(CallInst* C);
157 Expression create_expression(Constant* C);
159 ValueTable() : nextValueNumber(1) { }
160 uint32_t lookup_or_add(Value* V);
161 uint32_t lookup(Value* V) const;
162 void add(Value* V, uint32_t num);
164 void erase(Value* v);
166 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
167 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
168 void setDomTree(DominatorTree* D) { DT = D; }
173 template <> struct DenseMapInfo<Expression> {
174 static inline Expression getEmptyKey() {
175 return Expression(Expression::EMPTY);
178 static inline Expression getTombstoneKey() {
179 return Expression(Expression::TOMBSTONE);
182 static unsigned getHashValue(const Expression e) {
183 unsigned hash = e.opcode;
185 hash = e.firstVN + hash * 37;
186 hash = e.secondVN + hash * 37;
187 hash = e.thirdVN + hash * 37;
189 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
190 (unsigned)((uintptr_t)e.type >> 9)) +
193 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
194 E = e.varargs.end(); I != E; ++I)
195 hash = *I + hash * 37;
197 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
198 (unsigned)((uintptr_t)e.function >> 9)) +
203 static bool isEqual(const Expression &LHS, const Expression &RHS) {
206 static bool isPod() { return true; }
210 //===----------------------------------------------------------------------===//
211 // ValueTable Internal Functions
212 //===----------------------------------------------------------------------===//
213 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
214 switch(BO->getOpcode()) {
215 default: // THIS SHOULD NEVER HAPPEN
216 assert(0 && "Binary operator with unknown opcode?");
217 case Instruction::Add: return Expression::ADD;
218 case Instruction::Sub: return Expression::SUB;
219 case Instruction::Mul: return Expression::MUL;
220 case Instruction::UDiv: return Expression::UDIV;
221 case Instruction::SDiv: return Expression::SDIV;
222 case Instruction::FDiv: return Expression::FDIV;
223 case Instruction::URem: return Expression::UREM;
224 case Instruction::SRem: return Expression::SREM;
225 case Instruction::FRem: return Expression::FREM;
226 case Instruction::Shl: return Expression::SHL;
227 case Instruction::LShr: return Expression::LSHR;
228 case Instruction::AShr: return Expression::ASHR;
229 case Instruction::And: return Expression::AND;
230 case Instruction::Or: return Expression::OR;
231 case Instruction::Xor: return Expression::XOR;
235 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
236 if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
237 switch (C->getPredicate()) {
238 default: // THIS SHOULD NEVER HAPPEN
239 assert(0 && "Comparison with unknown predicate?");
240 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
241 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
242 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
243 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
244 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
245 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
246 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
247 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
248 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
249 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
252 assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
253 switch (C->getPredicate()) {
254 default: // THIS SHOULD NEVER HAPPEN
255 assert(0 && "Comparison with unknown predicate?");
256 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
257 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
258 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
259 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
260 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
261 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
262 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
263 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
264 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
265 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
266 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
267 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
268 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
269 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
273 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
274 switch(C->getOpcode()) {
275 default: // THIS SHOULD NEVER HAPPEN
276 assert(0 && "Cast operator with unknown opcode?");
277 case Instruction::Trunc: return Expression::TRUNC;
278 case Instruction::ZExt: return Expression::ZEXT;
279 case Instruction::SExt: return Expression::SEXT;
280 case Instruction::FPToUI: return Expression::FPTOUI;
281 case Instruction::FPToSI: return Expression::FPTOSI;
282 case Instruction::UIToFP: return Expression::UITOFP;
283 case Instruction::SIToFP: return Expression::SITOFP;
284 case Instruction::FPTrunc: return Expression::FPTRUNC;
285 case Instruction::FPExt: return Expression::FPEXT;
286 case Instruction::PtrToInt: return Expression::PTRTOINT;
287 case Instruction::IntToPtr: return Expression::INTTOPTR;
288 case Instruction::BitCast: return Expression::BITCAST;
292 Expression ValueTable::create_expression(CallInst* C) {
295 e.type = C->getType();
299 e.function = C->getCalledFunction();
300 e.opcode = Expression::CALL;
302 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
304 e.varargs.push_back(lookup_or_add(*I));
309 Expression ValueTable::create_expression(BinaryOperator* BO) {
312 e.firstVN = lookup_or_add(BO->getOperand(0));
313 e.secondVN = lookup_or_add(BO->getOperand(1));
316 e.type = BO->getType();
317 e.opcode = getOpcode(BO);
322 Expression ValueTable::create_expression(CmpInst* C) {
325 e.firstVN = lookup_or_add(C->getOperand(0));
326 e.secondVN = lookup_or_add(C->getOperand(1));
329 e.type = C->getType();
330 e.opcode = getOpcode(C);
335 Expression ValueTable::create_expression(CastInst* C) {
338 e.firstVN = lookup_or_add(C->getOperand(0));
342 e.type = C->getType();
343 e.opcode = getOpcode(C);
348 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
351 e.firstVN = lookup_or_add(S->getOperand(0));
352 e.secondVN = lookup_or_add(S->getOperand(1));
353 e.thirdVN = lookup_or_add(S->getOperand(2));
355 e.type = S->getType();
356 e.opcode = Expression::SHUFFLE;
361 Expression ValueTable::create_expression(ExtractElementInst* E) {
364 e.firstVN = lookup_or_add(E->getOperand(0));
365 e.secondVN = lookup_or_add(E->getOperand(1));
368 e.type = E->getType();
369 e.opcode = Expression::EXTRACT;
374 Expression ValueTable::create_expression(InsertElementInst* I) {
377 e.firstVN = lookup_or_add(I->getOperand(0));
378 e.secondVN = lookup_or_add(I->getOperand(1));
379 e.thirdVN = lookup_or_add(I->getOperand(2));
381 e.type = I->getType();
382 e.opcode = Expression::INSERT;
387 Expression ValueTable::create_expression(SelectInst* I) {
390 e.firstVN = lookup_or_add(I->getCondition());
391 e.secondVN = lookup_or_add(I->getTrueValue());
392 e.thirdVN = lookup_or_add(I->getFalseValue());
394 e.type = I->getType();
395 e.opcode = Expression::SELECT;
400 Expression ValueTable::create_expression(GetElementPtrInst* G) {
403 e.firstVN = lookup_or_add(G->getPointerOperand());
407 e.type = G->getType();
408 e.opcode = Expression::GEP;
410 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
412 e.varargs.push_back(lookup_or_add(*I));
417 //===----------------------------------------------------------------------===//
418 // ValueTable External Functions
419 //===----------------------------------------------------------------------===//
421 /// add - Insert a value into the table with a specified value number.
422 void ValueTable::add(Value* V, uint32_t num) {
423 valueNumbering.insert(std::make_pair(V, num));
426 /// lookup_or_add - Returns the value number for the specified value, assigning
427 /// it a new number if it did not have one before.
428 uint32_t ValueTable::lookup_or_add(Value* V) {
429 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
430 if (VI != valueNumbering.end())
433 if (CallInst* C = dyn_cast<CallInst>(V)) {
434 if (AA->doesNotAccessMemory(C)) {
435 Expression e = create_expression(C);
437 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
438 if (EI != expressionNumbering.end()) {
439 valueNumbering.insert(std::make_pair(V, EI->second));
442 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
443 valueNumbering.insert(std::make_pair(V, nextValueNumber));
445 return nextValueNumber++;
447 } else if (AA->onlyReadsMemory(C)) {
448 Expression e = create_expression(C);
450 if (expressionNumbering.find(e) == expressionNumbering.end()) {
451 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
452 valueNumbering.insert(std::make_pair(V, nextValueNumber));
453 return nextValueNumber++;
456 Instruction* local_dep = MD->getDependency(C);
458 if (local_dep == MemoryDependenceAnalysis::None) {
459 valueNumbering.insert(std::make_pair(V, nextValueNumber));
460 return nextValueNumber++;
461 } else if (local_dep != MemoryDependenceAnalysis::NonLocal) {
462 if (!isa<CallInst>(local_dep)) {
463 valueNumbering.insert(std::make_pair(V, nextValueNumber));
464 return nextValueNumber++;
467 CallInst* local_cdep = cast<CallInst>(local_dep);
469 if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
470 local_cdep->getNumOperands() != C->getNumOperands()) {
471 valueNumbering.insert(std::make_pair(V, nextValueNumber));
472 return nextValueNumber++;
473 } else if (!C->getCalledFunction()) {
474 valueNumbering.insert(std::make_pair(V, nextValueNumber));
475 return nextValueNumber++;
477 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
478 uint32_t c_vn = lookup_or_add(C->getOperand(i));
479 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
481 valueNumbering.insert(std::make_pair(V, nextValueNumber));
482 return nextValueNumber++;
486 uint32_t v = lookup_or_add(local_cdep);
487 valueNumbering.insert(std::make_pair(V, v));
493 DenseMap<BasicBlock*, Value*> deps;
494 MD->getNonLocalDependency(C, deps);
497 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(),
498 E = deps.end(); I != E; ++I) {
499 if (I->second == MemoryDependenceAnalysis::None) {
500 valueNumbering.insert(std::make_pair(V, nextValueNumber));
502 return nextValueNumber++;
503 } else if (I->second != MemoryDependenceAnalysis::NonLocal) {
504 if (DT->properlyDominates(I->first, C->getParent())) {
505 if (CallInst* CD = dyn_cast<CallInst>(I->second))
508 valueNumbering.insert(std::make_pair(V, nextValueNumber));
509 return nextValueNumber++;
512 valueNumbering.insert(std::make_pair(V, nextValueNumber));
513 return nextValueNumber++;
519 valueNumbering.insert(std::make_pair(V, nextValueNumber));
520 return nextValueNumber++;
523 if (cdep->getCalledFunction() != C->getCalledFunction() ||
524 cdep->getNumOperands() != C->getNumOperands()) {
525 valueNumbering.insert(std::make_pair(V, nextValueNumber));
526 return nextValueNumber++;
527 } else if (!C->getCalledFunction()) {
528 valueNumbering.insert(std::make_pair(V, nextValueNumber));
529 return nextValueNumber++;
531 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
532 uint32_t c_vn = lookup_or_add(C->getOperand(i));
533 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
535 valueNumbering.insert(std::make_pair(V, nextValueNumber));
536 return nextValueNumber++;
540 uint32_t v = lookup_or_add(cdep);
541 valueNumbering.insert(std::make_pair(V, v));
546 valueNumbering.insert(std::make_pair(V, nextValueNumber));
547 return nextValueNumber++;
549 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
550 Expression e = create_expression(BO);
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 (CmpInst* C = dyn_cast<CmpInst>(V)) {
563 Expression e = create_expression(C);
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 (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(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 (ExtractElementInst* U = dyn_cast<ExtractElementInst>(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++;
601 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
602 Expression e = create_expression(U);
604 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
605 if (EI != expressionNumbering.end()) {
606 valueNumbering.insert(std::make_pair(V, EI->second));
609 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
610 valueNumbering.insert(std::make_pair(V, nextValueNumber));
612 return nextValueNumber++;
614 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
615 Expression e = create_expression(U);
617 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
618 if (EI != expressionNumbering.end()) {
619 valueNumbering.insert(std::make_pair(V, EI->second));
622 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
623 valueNumbering.insert(std::make_pair(V, nextValueNumber));
625 return nextValueNumber++;
627 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
628 Expression e = create_expression(U);
630 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
631 if (EI != expressionNumbering.end()) {
632 valueNumbering.insert(std::make_pair(V, EI->second));
635 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
636 valueNumbering.insert(std::make_pair(V, nextValueNumber));
638 return nextValueNumber++;
640 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
641 Expression e = create_expression(U);
643 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
644 if (EI != expressionNumbering.end()) {
645 valueNumbering.insert(std::make_pair(V, EI->second));
648 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
649 valueNumbering.insert(std::make_pair(V, nextValueNumber));
651 return nextValueNumber++;
654 valueNumbering.insert(std::make_pair(V, nextValueNumber));
655 return nextValueNumber++;
659 /// lookup - Returns the value number of the specified value. Fails if
660 /// the value has not yet been numbered.
661 uint32_t ValueTable::lookup(Value* V) const {
662 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
663 assert(VI != valueNumbering.end() && "Value not numbered?");
667 /// clear - Remove all entries from the ValueTable
668 void ValueTable::clear() {
669 valueNumbering.clear();
670 expressionNumbering.clear();
674 /// erase - Remove a value from the value numbering
675 void ValueTable::erase(Value* V) {
676 valueNumbering.erase(V);
679 //===----------------------------------------------------------------------===//
681 //===----------------------------------------------------------------------===//
684 template<> struct DenseMapInfo<uint32_t> {
685 static inline uint32_t getEmptyKey() { return ~0; }
686 static inline uint32_t getTombstoneKey() { return ~0 - 1; }
687 static unsigned getHashValue(const uint32_t& Val) { return Val * 37; }
688 static bool isPod() { return true; }
689 static bool isEqual(const uint32_t& LHS, const uint32_t& RHS) {
697 class VISIBILITY_HIDDEN GVN : public FunctionPass {
698 bool runOnFunction(Function &F);
700 static char ID; // Pass identification, replacement for typeid
701 GVN() : FunctionPass((intptr_t)&ID) { }
705 DenseMap<BasicBlock*, DenseMap<uint32_t, Value*> > localAvail;
707 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
711 // This transformation requires dominator postdominator info
712 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
713 AU.setPreservesCFG();
714 AU.addRequired<DominatorTree>();
715 AU.addRequired<MemoryDependenceAnalysis>();
716 AU.addRequired<AliasAnalysis>();
717 AU.addPreserved<AliasAnalysis>();
718 AU.addPreserved<MemoryDependenceAnalysis>();
722 // FIXME: eliminate or document these better
723 bool processLoad(LoadInst* L,
724 DenseMap<Value*, LoadInst*> &lastLoad,
725 SmallVectorImpl<Instruction*> &toErase);
726 bool processInstruction(Instruction* I,
727 DenseMap<Value*, LoadInst*>& lastSeenLoad,
728 SmallVectorImpl<Instruction*> &toErase);
729 bool processNonLocalLoad(LoadInst* L,
730 SmallVectorImpl<Instruction*> &toErase);
731 bool processBlock(DomTreeNode* DTN);
732 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
733 DenseMap<BasicBlock*, Value*> &Phis,
734 bool top_level = false);
735 void dump(DenseMap<uint32_t, Value*>& d);
736 bool iterateOnFunction(Function &F);
737 Value* CollapsePhi(PHINode* p);
738 bool isSafeReplacement(PHINode* p, Instruction* inst);
739 bool performPRE(Function& F);
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 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
753 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
754 E = d.end(); I != E; ++I) {
755 printf("%d\n", I->first);
761 Value* GVN::CollapsePhi(PHINode* p) {
762 DominatorTree &DT = getAnalysis<DominatorTree>();
763 Value* constVal = p->hasConstantValue();
765 if (!constVal) return 0;
767 Instruction* inst = dyn_cast<Instruction>(constVal);
771 if (DT.dominates(inst, p))
772 if (isSafeReplacement(p, inst))
777 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
778 if (!isa<PHINode>(inst))
781 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
783 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
784 if (use_phi->getParent() == inst->getParent())
790 /// GetValueForBlock - Get the value to use within the specified basic block.
791 /// available values are in Phis.
792 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
793 DenseMap<BasicBlock*, Value*> &Phis,
796 // If we have already computed this value, return the previously computed val.
797 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
798 if (V != Phis.end() && !top_level) return V->second;
800 BasicBlock* singlePred = BB->getSinglePredecessor();
802 Value *ret = GetValueForBlock(singlePred, orig, Phis);
807 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
808 // now, then get values to fill in the incoming values for the PHI.
809 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
811 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
813 if (Phis.count(BB) == 0)
814 Phis.insert(std::make_pair(BB, PN));
816 // Fill in the incoming values for the block.
817 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
818 Value* val = GetValueForBlock(*PI, orig, Phis);
819 PN->addIncoming(val, *PI);
822 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
823 AA.copyValue(orig, PN);
825 // Attempt to collapse PHI nodes that are trivially redundant
826 Value* v = CollapsePhi(PN);
828 // Cache our phi construction results
829 phiMap[orig->getPointerOperand()].insert(PN);
833 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
835 MD.removeInstruction(PN);
836 PN->replaceAllUsesWith(v);
838 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
839 E = Phis.end(); I != E; ++I)
843 PN->eraseFromParent();
849 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
850 /// non-local by performing PHI construction.
851 bool GVN::processNonLocalLoad(LoadInst* L,
852 SmallVectorImpl<Instruction*> &toErase) {
853 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
855 // Find the non-local dependencies of the load
856 DenseMap<BasicBlock*, Value*> deps;
857 MD.getNonLocalDependency(L, deps);
859 DenseMap<BasicBlock*, Value*> repl;
861 // Filter out useless results (non-locals, etc)
862 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
864 if (I->second == MemoryDependenceAnalysis::None)
867 if (I->second == MemoryDependenceAnalysis::NonLocal)
870 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
871 if (S->getPointerOperand() != L->getPointerOperand())
873 repl[I->first] = S->getOperand(0);
874 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
875 if (LD->getPointerOperand() != L->getPointerOperand())
883 // Use cached PHI construction information from previous runs
884 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
885 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
887 if ((*I)->getParent() == L->getParent()) {
888 MD.removeInstruction(L);
889 L->replaceAllUsesWith(*I);
890 toErase.push_back(L);
895 repl.insert(std::make_pair((*I)->getParent(), *I));
898 // Perform PHI construction
899 SmallPtrSet<BasicBlock*, 4> visited;
900 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
902 MD.removeInstruction(L);
903 L->replaceAllUsesWith(v);
904 toErase.push_back(L);
910 /// processLoad - Attempt to eliminate a load, first by eliminating it
911 /// locally, and then attempting non-local elimination if that fails.
912 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
913 SmallVectorImpl<Instruction*> &toErase) {
914 if (L->isVolatile()) {
915 lastLoad[L->getPointerOperand()] = L;
919 Value* pointer = L->getPointerOperand();
920 LoadInst*& last = lastLoad[pointer];
922 // ... to a pointer that has been loaded from before...
923 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
924 bool removedNonLocal = false;
925 Instruction* dep = MD.getDependency(L);
926 if (dep == MemoryDependenceAnalysis::NonLocal &&
927 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
928 removedNonLocal = processNonLocalLoad(L, toErase);
930 if (!removedNonLocal)
933 return removedNonLocal;
937 bool deletedLoad = false;
939 // Walk up the dependency chain until we either find
940 // a dependency we can use, or we can't walk any further
941 while (dep != MemoryDependenceAnalysis::None &&
942 dep != MemoryDependenceAnalysis::NonLocal &&
943 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
944 // ... that depends on a store ...
945 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
946 if (S->getPointerOperand() == pointer) {
948 MD.removeInstruction(L);
950 L->replaceAllUsesWith(S->getOperand(0));
951 toErase.push_back(L);
956 // Whether we removed it or not, we can't
960 // If we don't depend on a store, and we haven't
961 // been loaded before, bail.
963 } else if (dep == last) {
965 MD.removeInstruction(L);
967 L->replaceAllUsesWith(last);
968 toErase.push_back(L);
974 dep = MD.getDependency(L, dep);
978 if (dep != MemoryDependenceAnalysis::None &&
979 dep != MemoryDependenceAnalysis::NonLocal &&
980 isa<AllocationInst>(dep)) {
981 // Check that this load is actually from the
982 // allocation we found
983 Value* v = L->getOperand(0);
985 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
986 v = BC->getOperand(0);
987 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
988 v = GEP->getOperand(0);
993 // If this load depends directly on an allocation, there isn't
994 // anything stored there; therefore, we can optimize this load
996 MD.removeInstruction(L);
998 L->replaceAllUsesWith(UndefValue::get(L->getType()));
999 toErase.push_back(L);
1011 /// processInstruction - When calculating availability, handle an instruction
1012 /// by inserting it into the appropriate sets
1013 bool GVN::processInstruction(Instruction *I,
1014 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1015 SmallVectorImpl<Instruction*> &toErase) {
1016 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1017 bool changed = processLoad(L, lastSeenLoad, toErase);
1020 unsigned num = VN.lookup_or_add(L);
1021 localAvail[I->getParent()].insert(std::make_pair(num, L));
1027 unsigned num = VN.lookup_or_add(I);
1029 // Allocations are always uniquely numbered, so we can save time and memory
1030 // by fast failing them.
1031 if (isa<AllocationInst>(I)) {
1032 localAvail[I->getParent()].insert(std::make_pair(num, I));
1036 // Collapse PHI nodes
1037 if (PHINode* p = dyn_cast<PHINode>(I)) {
1038 Value* constVal = CollapsePhi(p);
1041 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1043 if (PI->second.count(p))
1044 PI->second.erase(p);
1046 p->replaceAllUsesWith(constVal);
1047 toErase.push_back(p);
1049 localAvail[I->getParent()].insert(std::make_pair(num, I));
1051 // Perform value-number based elimination
1052 } else if (localAvail[I->getParent()].count(num)) {
1053 Value* repl = localAvail[I->getParent()][num];
1056 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1057 MD.removeInstruction(I);
1060 I->replaceAllUsesWith(repl);
1061 toErase.push_back(I);
1063 } else if (!I->isTerminator()) {
1064 localAvail[I->getParent()].insert(std::make_pair(num, I));
1070 // GVN::runOnFunction - This is the main transformation entry point for a
1073 bool GVN::runOnFunction(Function& F) {
1074 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1075 VN.setMemDep(&getAnalysis<MemoryDependenceAnalysis>());
1076 VN.setDomTree(&getAnalysis<DominatorTree>());
1078 bool changed = false;
1079 bool shouldContinue = true;
1081 while (shouldContinue) {
1082 shouldContinue = iterateOnFunction(F);
1083 changed |= shouldContinue;
1090 bool GVN::processBlock(DomTreeNode* DTN) {
1091 BasicBlock* BB = DTN->getBlock();
1093 SmallVector<Instruction*, 8> toErase;
1094 DenseMap<Value*, LoadInst*> lastSeenLoad;
1095 bool changed_function = false;
1098 localAvail.insert(std::make_pair(BB,
1099 localAvail[DTN->getIDom()->getBlock()]));
1101 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1103 changed_function |= processInstruction(BI, lastSeenLoad, toErase);
1104 if (toErase.empty()) {
1109 // If we need some instructions deleted, do it now.
1110 NumGVNInstr += toErase.size();
1112 // Avoid iterator invalidation.
1113 bool AtStart = BI == BB->begin();
1117 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1118 E = toErase.end(); I != E; ++I)
1119 (*I)->eraseFromParent();
1129 return changed_function;
1132 /// performPRE - Perform a purely local form of PRE that looks for diamond
1133 /// control flow patterns and attempts to perform simple PRE at the join point.
1134 bool GVN::performPRE(Function& F) {
1135 bool changed = false;
1136 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1137 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1138 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1139 BasicBlock* CurrentBlock = *DI;
1141 // Nothing to PRE in the entry block.
1142 if (CurrentBlock == &F.getEntryBlock()) continue;
1144 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1145 BE = CurrentBlock->end(); BI != BE; ) {
1146 if (isa<AllocaInst>(BI) || isa<TerminatorInst>(BI) ||
1147 isa<LoadInst>(BI) || isa<StoreInst>(BI) ||
1148 isa<CallInst>(BI) || isa<PHINode>(BI)) {
1153 uint32_t valno = VN.lookup(BI);
1155 // Look for the predecessors for PRE opportunities. We're
1156 // only trying to solve the basic diamond case, where
1157 // a value is computed in the successor and one predecessor,
1158 // but not the other. We also explicitly disallow cases
1159 // where the successor is its own predecessor, because they're
1160 // more complicated to get right.
1161 unsigned numWith = 0;
1162 unsigned numWithout = 0;
1163 BasicBlock* PREPred = 0;
1164 for (pred_iterator PI = pred_begin(CurrentBlock),
1165 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1166 // We're not interested in PRE where the block is its
1168 if (*PI == CurrentBlock)
1171 if (!localAvail[*PI].count(valno)) {
1174 } else if (localAvail[*PI][valno] == BI) {
1181 // Don't do PRE when it might increase code size, i.e. when
1182 // we would need to insert instructions in more than one pred.
1183 if (numWithout != 1 || numWith == 0) {
1188 // We can't do PRE safely on a critical edge, so instead we schedule
1189 // the edge to be split and perform the PRE the next time we iterate
1191 unsigned succNum = 0;
1192 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1194 if (PREPred->getTerminator()->getSuccessor(i) == PREPred) {
1199 if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1200 toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1206 // Instantiate the expression the in predecessor that lacked it.
1207 // Because we are going top-down through the block, all value numbers
1208 // will be available in the predecessor by the time we need them. Any
1209 // that weren't original present will have been instantiated earlier
1211 Instruction* PREInstr = BI->clone();
1212 bool success = true;
1213 for (unsigned i = 0; i < BI->getNumOperands(); ++i) {
1214 Value* op = BI->getOperand(i);
1215 if (isa<Argument>(op) || isa<Constant>(op) || isa<GlobalValue>(op))
1216 PREInstr->setOperand(i, op);
1217 else if (!localAvail[PREPred].count(VN.lookup(op))) {
1221 PREInstr->setOperand(i, localAvail[PREPred][VN.lookup(op)]);
1224 // Fail out if we encounter an operand that is not available in
1225 // the PRE predecessor. This is typically because of loads which
1226 // are not value numbered precisely.
1233 PREInstr->insertBefore(PREPred->getTerminator());
1234 PREInstr->setName(BI->getName() + ".pre");
1235 VN.add(PREInstr, valno);
1238 // Update the availability map to include the new instruction.
1239 localAvail[PREPred].insert(std::make_pair(valno, PREInstr));
1241 // Create a PHI to make the value available in this block.
1242 PHINode* Phi = PHINode::Create(BI->getType(),
1243 BI->getName() + ".pre-phi",
1244 CurrentBlock->begin());
1245 for (pred_iterator PI = pred_begin(CurrentBlock),
1246 PE = pred_end(CurrentBlock); PI != PE; ++PI)
1247 Phi->addIncoming(localAvail[*PI][valno], *PI);
1251 // The newly created PHI completely replaces the old instruction,
1252 // so we need to update the maps to reflect this.
1253 for (DenseMap<BasicBlock*, DenseMap<uint32_t, Value*> >::iterator
1254 UI = localAvail.begin(), UE = localAvail.end(); UI != UE; ++UI)
1255 for (DenseMap<uint32_t, Value*>::iterator UUI = UI->second.begin(),
1256 UUE = UI->second.end(); UUI != UUE; ++UUI)
1257 if (UUI->second == BI)
1260 BI->replaceAllUsesWith(Phi);
1263 Instruction* erase = BI;
1265 erase->eraseFromParent();
1271 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1272 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1273 SplitCriticalEdge(I->first, I->second, this);
1278 // GVN::iterateOnFunction - Executes one iteration of GVN
1279 bool GVN::iterateOnFunction(Function &F) {
1280 // Clean out global sets from any previous functions
1285 DominatorTree &DT = getAnalysis<DominatorTree>();
1287 // Top-down walk of the dominator tree
1288 bool changed = false;
1289 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1290 DE = df_end(DT.getRootNode()); DI != DE; ++DI)
1291 changed |= processBlock(*DI);
1294 changed |= performPRE(F);