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"
42 STATISTIC(NumGVNInstr, "Number of instructions deleted");
43 STATISTIC(NumGVNLoad, "Number of loads deleted");
44 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
45 STATISTIC(NumGVNBlocks, "Number of blocks merged");
47 static cl::opt<bool> EnablePRE("enable-pre",
48 cl::init(true), cl::Hidden);
50 //===----------------------------------------------------------------------===//
52 //===----------------------------------------------------------------------===//
54 /// This class holds the mapping between values and value numbers. It is used
55 /// as an efficient mechanism to determine the expression-wise equivalence of
58 struct VISIBILITY_HIDDEN Expression {
59 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
60 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
61 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
62 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
63 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
64 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
65 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
66 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
67 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
68 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, CONSTANT,
71 ExpressionOpcode opcode;
76 SmallVector<uint32_t, 4> varargs;
80 Expression(ExpressionOpcode o) : opcode(o) { }
82 bool operator==(const Expression &other) const {
83 if (opcode != other.opcode)
85 else if (opcode == EMPTY || opcode == TOMBSTONE)
87 else if (type != other.type)
89 else if (function != other.function)
91 else if (firstVN != other.firstVN)
93 else if (secondVN != other.secondVN)
95 else if (thirdVN != other.thirdVN)
98 if (varargs.size() != other.varargs.size())
101 for (size_t i = 0; i < varargs.size(); ++i)
102 if (varargs[i] != other.varargs[i])
109 bool operator!=(const Expression &other) const {
110 if (opcode != other.opcode)
112 else if (opcode == EMPTY || opcode == TOMBSTONE)
114 else if (type != other.type)
116 else if (function != other.function)
118 else if (firstVN != other.firstVN)
120 else if (secondVN != other.secondVN)
122 else if (thirdVN != other.thirdVN)
125 if (varargs.size() != other.varargs.size())
128 for (size_t i = 0; i < varargs.size(); ++i)
129 if (varargs[i] != other.varargs[i])
137 class VISIBILITY_HIDDEN ValueTable {
139 DenseMap<Value*, uint32_t> valueNumbering;
140 DenseMap<Expression, uint32_t> expressionNumbering;
142 MemoryDependenceAnalysis* MD;
145 uint32_t nextValueNumber;
147 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
148 Expression::ExpressionOpcode getOpcode(CmpInst* C);
149 Expression::ExpressionOpcode getOpcode(CastInst* C);
150 Expression create_expression(BinaryOperator* BO);
151 Expression create_expression(CmpInst* C);
152 Expression create_expression(ShuffleVectorInst* V);
153 Expression create_expression(ExtractElementInst* C);
154 Expression create_expression(InsertElementInst* V);
155 Expression create_expression(SelectInst* V);
156 Expression create_expression(CastInst* C);
157 Expression create_expression(GetElementPtrInst* G);
158 Expression create_expression(CallInst* C);
159 Expression create_expression(Constant* C);
161 ValueTable() : nextValueNumber(1) { }
162 uint32_t lookup_or_add(Value* V);
163 uint32_t lookup(Value* V) const;
164 void add(Value* V, uint32_t num);
166 void erase(Value* v);
168 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
169 AliasAnalysis *getAliasAnalysis() const { return AA; }
170 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
171 void setDomTree(DominatorTree* D) { DT = D; }
172 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
177 template <> struct DenseMapInfo<Expression> {
178 static inline Expression getEmptyKey() {
179 return Expression(Expression::EMPTY);
182 static inline Expression getTombstoneKey() {
183 return Expression(Expression::TOMBSTONE);
186 static unsigned getHashValue(const Expression e) {
187 unsigned hash = e.opcode;
189 hash = e.firstVN + hash * 37;
190 hash = e.secondVN + hash * 37;
191 hash = e.thirdVN + hash * 37;
193 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
194 (unsigned)((uintptr_t)e.type >> 9)) +
197 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
198 E = e.varargs.end(); I != E; ++I)
199 hash = *I + hash * 37;
201 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
202 (unsigned)((uintptr_t)e.function >> 9)) +
207 static bool isEqual(const Expression &LHS, const Expression &RHS) {
210 static bool isPod() { return true; }
214 //===----------------------------------------------------------------------===//
215 // ValueTable Internal Functions
216 //===----------------------------------------------------------------------===//
217 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
218 switch(BO->getOpcode()) {
219 default: // THIS SHOULD NEVER HAPPEN
220 assert(0 && "Binary operator with unknown opcode?");
221 case Instruction::Add: return Expression::ADD;
222 case Instruction::Sub: return Expression::SUB;
223 case Instruction::Mul: return Expression::MUL;
224 case Instruction::UDiv: return Expression::UDIV;
225 case Instruction::SDiv: return Expression::SDIV;
226 case Instruction::FDiv: return Expression::FDIV;
227 case Instruction::URem: return Expression::UREM;
228 case Instruction::SRem: return Expression::SREM;
229 case Instruction::FRem: return Expression::FREM;
230 case Instruction::Shl: return Expression::SHL;
231 case Instruction::LShr: return Expression::LSHR;
232 case Instruction::AShr: return Expression::ASHR;
233 case Instruction::And: return Expression::AND;
234 case Instruction::Or: return Expression::OR;
235 case Instruction::Xor: return Expression::XOR;
239 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
240 if (isa<ICmpInst>(C) || isa<VICmpInst>(C)) {
241 switch (C->getPredicate()) {
242 default: // THIS SHOULD NEVER HAPPEN
243 assert(0 && "Comparison with unknown predicate?");
244 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
245 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
246 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
247 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
248 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
249 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
250 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
251 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
252 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
253 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
256 assert((isa<FCmpInst>(C) || isa<VFCmpInst>(C)) && "Unknown compare");
257 switch (C->getPredicate()) {
258 default: // THIS SHOULD NEVER HAPPEN
259 assert(0 && "Comparison with unknown predicate?");
260 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
261 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
262 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
263 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
264 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
265 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
266 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
267 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
268 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
269 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
270 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
271 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
272 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
273 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
277 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
278 switch(C->getOpcode()) {
279 default: // THIS SHOULD NEVER HAPPEN
280 assert(0 && "Cast operator with unknown opcode?");
281 case Instruction::Trunc: return Expression::TRUNC;
282 case Instruction::ZExt: return Expression::ZEXT;
283 case Instruction::SExt: return Expression::SEXT;
284 case Instruction::FPToUI: return Expression::FPTOUI;
285 case Instruction::FPToSI: return Expression::FPTOSI;
286 case Instruction::UIToFP: return Expression::UITOFP;
287 case Instruction::SIToFP: return Expression::SITOFP;
288 case Instruction::FPTrunc: return Expression::FPTRUNC;
289 case Instruction::FPExt: return Expression::FPEXT;
290 case Instruction::PtrToInt: return Expression::PTRTOINT;
291 case Instruction::IntToPtr: return Expression::INTTOPTR;
292 case Instruction::BitCast: return Expression::BITCAST;
296 Expression ValueTable::create_expression(CallInst* C) {
299 e.type = C->getType();
303 e.function = C->getCalledFunction();
304 e.opcode = Expression::CALL;
306 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
308 e.varargs.push_back(lookup_or_add(*I));
313 Expression ValueTable::create_expression(BinaryOperator* BO) {
316 e.firstVN = lookup_or_add(BO->getOperand(0));
317 e.secondVN = lookup_or_add(BO->getOperand(1));
320 e.type = BO->getType();
321 e.opcode = getOpcode(BO);
326 Expression ValueTable::create_expression(CmpInst* C) {
329 e.firstVN = lookup_or_add(C->getOperand(0));
330 e.secondVN = lookup_or_add(C->getOperand(1));
333 e.type = C->getType();
334 e.opcode = getOpcode(C);
339 Expression ValueTable::create_expression(CastInst* C) {
342 e.firstVN = lookup_or_add(C->getOperand(0));
346 e.type = C->getType();
347 e.opcode = getOpcode(C);
352 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
355 e.firstVN = lookup_or_add(S->getOperand(0));
356 e.secondVN = lookup_or_add(S->getOperand(1));
357 e.thirdVN = lookup_or_add(S->getOperand(2));
359 e.type = S->getType();
360 e.opcode = Expression::SHUFFLE;
365 Expression ValueTable::create_expression(ExtractElementInst* E) {
368 e.firstVN = lookup_or_add(E->getOperand(0));
369 e.secondVN = lookup_or_add(E->getOperand(1));
372 e.type = E->getType();
373 e.opcode = Expression::EXTRACT;
378 Expression ValueTable::create_expression(InsertElementInst* I) {
381 e.firstVN = lookup_or_add(I->getOperand(0));
382 e.secondVN = lookup_or_add(I->getOperand(1));
383 e.thirdVN = lookup_or_add(I->getOperand(2));
385 e.type = I->getType();
386 e.opcode = Expression::INSERT;
391 Expression ValueTable::create_expression(SelectInst* I) {
394 e.firstVN = lookup_or_add(I->getCondition());
395 e.secondVN = lookup_or_add(I->getTrueValue());
396 e.thirdVN = lookup_or_add(I->getFalseValue());
398 e.type = I->getType();
399 e.opcode = Expression::SELECT;
404 Expression ValueTable::create_expression(GetElementPtrInst* G) {
407 e.firstVN = lookup_or_add(G->getPointerOperand());
411 e.type = G->getType();
412 e.opcode = Expression::GEP;
414 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
416 e.varargs.push_back(lookup_or_add(*I));
421 //===----------------------------------------------------------------------===//
422 // ValueTable External Functions
423 //===----------------------------------------------------------------------===//
425 /// add - Insert a value into the table with a specified value number.
426 void ValueTable::add(Value* V, uint32_t num) {
427 valueNumbering.insert(std::make_pair(V, num));
430 /// lookup_or_add - Returns the value number for the specified value, assigning
431 /// it a new number if it did not have one before.
432 uint32_t ValueTable::lookup_or_add(Value* V) {
433 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
434 if (VI != valueNumbering.end())
437 if (CallInst* C = dyn_cast<CallInst>(V)) {
438 if (AA->doesNotAccessMemory(C)) {
439 Expression e = create_expression(C);
441 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
442 if (EI != expressionNumbering.end()) {
443 valueNumbering.insert(std::make_pair(V, EI->second));
446 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
447 valueNumbering.insert(std::make_pair(V, nextValueNumber));
449 return nextValueNumber++;
451 } else if (AA->onlyReadsMemory(C)) {
452 Expression e = create_expression(C);
454 if (expressionNumbering.find(e) == expressionNumbering.end()) {
455 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
456 valueNumbering.insert(std::make_pair(V, nextValueNumber));
457 return nextValueNumber++;
460 MemDepResult local_dep = MD->getDependency(C);
462 if (local_dep.isNone()) {
463 valueNumbering.insert(std::make_pair(V, nextValueNumber));
464 return nextValueNumber++;
467 if (Instruction *LocalDepInst = local_dep.getInst()) {
468 if (!isa<CallInst>(LocalDepInst)) {
469 valueNumbering.insert(std::make_pair(V, nextValueNumber));
470 return nextValueNumber++;
473 CallInst* local_cdep = cast<CallInst>(LocalDepInst);
475 if (local_cdep->getCalledFunction() != C->getCalledFunction() ||
476 local_cdep->getNumOperands() != C->getNumOperands()) {
477 valueNumbering.insert(std::make_pair(V, nextValueNumber));
478 return nextValueNumber++;
481 if (!C->getCalledFunction()) {
482 valueNumbering.insert(std::make_pair(V, nextValueNumber));
483 return nextValueNumber++;
486 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
487 uint32_t c_vn = lookup_or_add(C->getOperand(i));
488 uint32_t cd_vn = lookup_or_add(local_cdep->getOperand(i));
490 valueNumbering.insert(std::make_pair(V, nextValueNumber));
491 return nextValueNumber++;
495 uint32_t v = lookup_or_add(local_cdep);
496 valueNumbering.insert(std::make_pair(V, v));
501 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
502 MD->getNonLocalDependency(C);
505 // Check to see if we have a single dominating call instruction that is
507 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
508 const MemoryDependenceAnalysis::NonLocalDepEntry *I = &deps[i];
509 // Ignore non-local dependencies.
510 if (I->second.isNonLocal())
513 // We don't handle non-depedencies. If we already have a call, reject
514 // instruction dependencies.
515 if (I->second.isNone() || cdep != 0) {
520 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->second.getInst());
521 // FIXME: All duplicated with non-local case.
522 if (NonLocalDepCall && DT->properlyDominates(I->first, C->getParent())){
523 cdep = NonLocalDepCall;
532 valueNumbering.insert(std::make_pair(V, nextValueNumber));
533 return nextValueNumber++;
536 if (cdep->getCalledFunction() != C->getCalledFunction() ||
537 cdep->getNumOperands() != C->getNumOperands()) {
538 valueNumbering.insert(std::make_pair(V, nextValueNumber));
539 return nextValueNumber++;
541 if (!C->getCalledFunction()) {
542 valueNumbering.insert(std::make_pair(V, nextValueNumber));
543 return nextValueNumber++;
545 for (unsigned i = 1; i < C->getNumOperands(); ++i) {
546 uint32_t c_vn = lookup_or_add(C->getOperand(i));
547 uint32_t cd_vn = lookup_or_add(cdep->getOperand(i));
549 valueNumbering.insert(std::make_pair(V, nextValueNumber));
550 return nextValueNumber++;
554 uint32_t v = lookup_or_add(cdep);
555 valueNumbering.insert(std::make_pair(V, v));
559 valueNumbering.insert(std::make_pair(V, nextValueNumber));
560 return nextValueNumber++;
562 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
563 Expression e = create_expression(BO);
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 (CmpInst* C = dyn_cast<CmpInst>(V)) {
576 Expression e = create_expression(C);
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 (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(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 (ExtractElementInst* U = dyn_cast<ExtractElementInst>(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 (InsertElementInst* U = dyn_cast<InsertElementInst>(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 (SelectInst* U = dyn_cast<SelectInst>(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 (CastInst* U = dyn_cast<CastInst>(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++;
653 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
654 Expression e = create_expression(U);
656 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
657 if (EI != expressionNumbering.end()) {
658 valueNumbering.insert(std::make_pair(V, EI->second));
661 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
662 valueNumbering.insert(std::make_pair(V, nextValueNumber));
664 return nextValueNumber++;
667 valueNumbering.insert(std::make_pair(V, nextValueNumber));
668 return nextValueNumber++;
672 /// lookup - Returns the value number of the specified value. Fails if
673 /// the value has not yet been numbered.
674 uint32_t ValueTable::lookup(Value* V) const {
675 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
676 assert(VI != valueNumbering.end() && "Value not numbered?");
680 /// clear - Remove all entries from the ValueTable
681 void ValueTable::clear() {
682 valueNumbering.clear();
683 expressionNumbering.clear();
687 /// erase - Remove a value from the value numbering
688 void ValueTable::erase(Value* V) {
689 valueNumbering.erase(V);
692 //===----------------------------------------------------------------------===//
694 //===----------------------------------------------------------------------===//
697 struct VISIBILITY_HIDDEN ValueNumberScope {
698 ValueNumberScope* parent;
699 DenseMap<uint32_t, Value*> table;
701 ValueNumberScope(ValueNumberScope* p) : parent(p) { }
707 class VISIBILITY_HIDDEN GVN : public FunctionPass {
708 bool runOnFunction(Function &F);
710 static char ID; // Pass identification, replacement for typeid
711 GVN() : FunctionPass(&ID) { }
714 MemoryDependenceAnalysis *MD;
718 DenseMap<BasicBlock*, ValueNumberScope*> localAvail;
720 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
724 // This transformation requires dominator postdominator info
725 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
726 AU.addRequired<DominatorTree>();
727 AU.addRequired<MemoryDependenceAnalysis>();
728 AU.addRequired<AliasAnalysis>();
730 AU.addPreserved<DominatorTree>();
731 AU.addPreserved<AliasAnalysis>();
735 // FIXME: eliminate or document these better
736 bool processLoad(LoadInst* L,
737 DenseMap<Value*, LoadInst*> &lastLoad,
738 SmallVectorImpl<Instruction*> &toErase);
739 bool processInstruction(Instruction* I,
740 DenseMap<Value*, LoadInst*>& lastSeenLoad,
741 SmallVectorImpl<Instruction*> &toErase);
742 bool processNonLocalLoad(LoadInst* L,
743 SmallVectorImpl<Instruction*> &toErase);
744 bool processBlock(DomTreeNode* DTN);
745 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
746 DenseMap<BasicBlock*, Value*> &Phis,
747 bool top_level = false);
748 void dump(DenseMap<uint32_t, Value*>& d);
749 bool iterateOnFunction(Function &F);
750 Value* CollapsePhi(PHINode* p);
751 bool isSafeReplacement(PHINode* p, Instruction* inst);
752 bool performPRE(Function& F);
753 Value* lookupNumber(BasicBlock* BB, uint32_t num);
754 bool mergeBlockIntoPredecessor(BasicBlock* BB);
755 void cleanupGlobalSets();
761 // createGVNPass - The public interface to this file...
762 FunctionPass *llvm::createGVNPass() { return new GVN(); }
764 static RegisterPass<GVN> X("gvn",
765 "Global Value Numbering");
767 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
769 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
770 E = d.end(); I != E; ++I) {
771 printf("%d\n", I->first);
777 Value* GVN::CollapsePhi(PHINode* p) {
778 Value* constVal = p->hasConstantValue();
779 if (!constVal) return 0;
781 Instruction* inst = dyn_cast<Instruction>(constVal);
785 if (DT->dominates(inst, p))
786 if (isSafeReplacement(p, inst))
791 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
792 if (!isa<PHINode>(inst))
795 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
797 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
798 if (use_phi->getParent() == inst->getParent())
804 /// GetValueForBlock - Get the value to use within the specified basic block.
805 /// available values are in Phis.
806 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
807 DenseMap<BasicBlock*, Value*> &Phis,
810 // If we have already computed this value, return the previously computed val.
811 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
812 if (V != Phis.end() && !top_level) return V->second;
814 // If the block is unreachable, just return undef, since this path
815 // can't actually occur at runtime.
816 if (!DT->isReachableFromEntry(BB))
817 return Phis[BB] = UndefValue::get(orig->getType());
819 BasicBlock* singlePred = BB->getSinglePredecessor();
821 Value *ret = GetValueForBlock(singlePred, orig, Phis);
826 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
827 // now, then get values to fill in the incoming values for the PHI.
828 PHINode *PN = PHINode::Create(orig->getType(), orig->getName()+".rle",
830 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
832 if (Phis.count(BB) == 0)
833 Phis.insert(std::make_pair(BB, PN));
835 // Fill in the incoming values for the block.
836 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
837 Value* val = GetValueForBlock(*PI, orig, Phis);
838 PN->addIncoming(val, *PI);
841 VN.getAliasAnalysis()->copyValue(orig, PN);
843 // Attempt to collapse PHI nodes that are trivially redundant
844 Value* v = CollapsePhi(PN);
846 // Cache our phi construction results
847 phiMap[orig->getPointerOperand()].insert(PN);
851 PN->replaceAllUsesWith(v);
853 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
854 E = Phis.end(); I != E; ++I)
858 DEBUG(cerr << "GVN removed: " << *PN);
859 MD->removeInstruction(PN);
860 PN->eraseFromParent();
866 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
867 /// non-local by performing PHI construction.
868 bool GVN::processNonLocalLoad(LoadInst* L,
869 SmallVectorImpl<Instruction*> &toErase) {
870 // Find the non-local dependencies of the load
871 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
872 MD->getNonLocalDependency(L);
873 DEBUG(cerr << "INVESTIGATING NONLOCAL LOAD: " << deps.size() << *L);
875 DEBUG(for (unsigned i = 0, e = deps.size(); i != e; ++i) {
876 cerr << " " << deps[i].first->getName();
877 if (Instruction *I = deps[i].second.getInst())
884 // If we had to process more than one hundred blocks to find the
885 // dependencies, this load isn't worth worrying about. Optimizing
886 // it will be too expensive.
887 if (deps.size() > 100)
890 BasicBlock *EntryBlock = &L->getParent()->getParent()->getEntryBlock();
892 DenseMap<BasicBlock*, Value*> repl;
894 // Filter out useless results (non-locals, etc)
895 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
896 BasicBlock *DepBB = deps[i].first;
897 MemDepResult DepInfo = deps[i].second;
899 if (DepInfo.isNonLocal()) {
900 // If this is a non-local dependency in the entry block, then we depend on
901 // the value live-in at the start of the function. We could insert a load
902 // in the entry block to get this, but for now we'll just bail out.
904 // FIXME: Consider emitting a load in the entry block to catch this case!
905 // Tricky part is to sink so that it doesn't execute in places where it
907 if (DepBB == EntryBlock)
912 if (DepInfo.isNone()) {
913 repl[DepBB] = UndefValue::get(L->getType());
917 if (StoreInst* S = dyn_cast<StoreInst>(DepInfo.getInst())) {
918 // Reject loads and stores that are to the same address but are of
920 // NOTE: 403.gcc does have this case (e.g. in readonly_fields_p) because
921 // of bitfield access, it would be interesting to optimize for it at some
923 if (S->getOperand(0)->getType() != L->getType())
926 if (S->getPointerOperand() != L->getPointerOperand() &&
927 VN.getAliasAnalysis()->alias(S->getPointerOperand(), 1,
928 L->getPointerOperand(), 1)
929 != AliasAnalysis::MustAlias)
931 repl[DepBB] = S->getOperand(0);
932 } else if (LoadInst* LD = dyn_cast<LoadInst>(DepInfo.getInst())) {
933 if (LD->getType() != L->getType())
936 if (LD->getPointerOperand() != L->getPointerOperand() &&
937 VN.getAliasAnalysis()->alias(LD->getPointerOperand(), 1,
938 L->getPointerOperand(), 1)
939 != AliasAnalysis::MustAlias)
947 // Use cached PHI construction information from previous runs
948 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
949 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
951 if ((*I)->getParent() == L->getParent()) {
952 L->replaceAllUsesWith(*I);
953 toErase.push_back(L);
958 repl.insert(std::make_pair((*I)->getParent(), *I));
961 DEBUG(cerr << "GVN REMOVING NONLOCAL LOAD: " << *L);
963 // Perform PHI construction
964 SmallPtrSet<BasicBlock*, 4> visited;
965 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
966 L->replaceAllUsesWith(v);
967 toErase.push_back(L);
972 /// processLoad - Attempt to eliminate a load, first by eliminating it
973 /// locally, and then attempting non-local elimination if that fails.
974 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
975 SmallVectorImpl<Instruction*> &toErase) {
976 if (L->isVolatile()) {
977 lastLoad[L->getPointerOperand()] = L;
981 Value* pointer = L->getPointerOperand();
982 LoadInst*& last = lastLoad[pointer];
984 // ... to a pointer that has been loaded from before...
985 bool removedNonLocal = false;
986 MemDepResult dep = MD->getDependency(L);
987 if (dep.isNonLocal() &&
988 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
989 removedNonLocal = processNonLocalLoad(L, toErase);
991 if (!removedNonLocal)
994 return removedNonLocal;
998 bool deletedLoad = false;
1000 // Walk up the dependency chain until we either find
1001 // a dependency we can use, or we can't walk any further
1002 while (Instruction *DepInst = dep.getInst()) {
1003 // ... that depends on a store ...
1004 if (StoreInst* S = dyn_cast<StoreInst>(DepInst)) {
1005 if (S->getPointerOperand() == pointer) {
1007 L->replaceAllUsesWith(S->getOperand(0));
1008 toErase.push_back(L);
1013 // Whether we removed it or not, we can't
1016 } else if (!isa<LoadInst>(DepInst)) {
1017 // Only want to handle loads below.
1020 // If we don't depend on a store, and we haven't
1021 // been loaded before, bail.
1023 } else if (DepInst == last) {
1025 L->replaceAllUsesWith(last);
1026 toErase.push_back(L);
1031 dep = MD->getDependencyFrom(L, DepInst, DepInst->getParent());
1035 // If this load really doesn't depend on anything, then we must be loading an
1036 // undef value. This can happen when loading for a fresh allocation with no
1037 // intervening stores, for example.
1039 // If this load depends directly on an allocation, there isn't
1040 // anything stored there; therefore, we can optimize this load
1042 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1043 toErase.push_back(L);
1054 Value* GVN::lookupNumber(BasicBlock* BB, uint32_t num) {
1055 DenseMap<BasicBlock*, ValueNumberScope*>::iterator I = localAvail.find(BB);
1056 if (I == localAvail.end())
1059 ValueNumberScope* locals = I->second;
1062 DenseMap<uint32_t, Value*>::iterator I = locals->table.find(num);
1063 if (I != locals->table.end())
1066 locals = locals->parent;
1072 /// processInstruction - When calculating availability, handle an instruction
1073 /// by inserting it into the appropriate sets
1074 bool GVN::processInstruction(Instruction *I,
1075 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1076 SmallVectorImpl<Instruction*> &toErase) {
1077 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1078 bool changed = processLoad(L, lastSeenLoad, toErase);
1081 unsigned num = VN.lookup_or_add(L);
1082 localAvail[I->getParent()]->table.insert(std::make_pair(num, L));
1088 uint32_t nextNum = VN.getNextUnusedValueNumber();
1089 unsigned num = VN.lookup_or_add(I);
1091 // Allocations are always uniquely numbered, so we can save time and memory
1092 // by fast failing them.
1093 if (isa<AllocationInst>(I) || isa<TerminatorInst>(I)) {
1094 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1098 // Collapse PHI nodes
1099 if (PHINode* p = dyn_cast<PHINode>(I)) {
1100 Value* constVal = CollapsePhi(p);
1103 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1105 if (PI->second.count(p))
1106 PI->second.erase(p);
1108 p->replaceAllUsesWith(constVal);
1109 toErase.push_back(p);
1111 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1114 // If the number we were assigned was a brand new VN, then we don't
1115 // need to do a lookup to see if the number already exists
1116 // somewhere in the domtree: it can't!
1117 } else if (num == nextNum) {
1118 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1120 // Perform value-number based elimination
1121 } else if (Value* repl = lookupNumber(I->getParent(), num)) {
1124 I->replaceAllUsesWith(repl);
1125 toErase.push_back(I);
1128 localAvail[I->getParent()]->table.insert(std::make_pair(num, I));
1134 // GVN::runOnFunction - This is the main transformation entry point for a
1137 bool GVN::runOnFunction(Function& F) {
1138 MD = &getAnalysis<MemoryDependenceAnalysis>();
1139 DT = &getAnalysis<DominatorTree>();
1140 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1144 bool changed = false;
1145 bool shouldContinue = true;
1147 // Merge unconditional branches, allowing PRE to catch more
1148 // optimization opportunities.
1149 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
1150 BasicBlock* BB = FI;
1152 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
1153 if (removedBlock) NumGVNBlocks++;
1155 changed |= removedBlock;
1158 while (shouldContinue) {
1159 shouldContinue = iterateOnFunction(F);
1160 changed |= shouldContinue;
1164 bool PREChanged = true;
1165 while (PREChanged) {
1166 PREChanged = performPRE(F);
1167 changed |= PREChanged;
1171 cleanupGlobalSets();
1177 bool GVN::processBlock(DomTreeNode* DTN) {
1178 BasicBlock* BB = DTN->getBlock();
1179 SmallVector<Instruction*, 8> toErase;
1180 DenseMap<Value*, LoadInst*> lastSeenLoad;
1181 bool changed_function = false;
1185 new ValueNumberScope(localAvail[DTN->getIDom()->getBlock()]);
1187 localAvail[BB] = new ValueNumberScope(0);
1189 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1191 changed_function |= processInstruction(BI, lastSeenLoad, toErase);
1192 if (toErase.empty()) {
1197 // If we need some instructions deleted, do it now.
1198 NumGVNInstr += toErase.size();
1200 // Avoid iterator invalidation.
1201 bool AtStart = BI == BB->begin();
1205 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1206 E = toErase.end(); I != E; ++I) {
1207 DEBUG(cerr << "GVN removed: " << **I);
1208 MD->removeInstruction(*I);
1209 (*I)->eraseFromParent();
1220 return changed_function;
1223 /// performPRE - Perform a purely local form of PRE that looks for diamond
1224 /// control flow patterns and attempts to perform simple PRE at the join point.
1225 bool GVN::performPRE(Function& F) {
1226 bool changed = false;
1227 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
1228 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
1229 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
1230 BasicBlock* CurrentBlock = *DI;
1232 // Nothing to PRE in the entry block.
1233 if (CurrentBlock == &F.getEntryBlock()) continue;
1235 for (BasicBlock::iterator BI = CurrentBlock->begin(),
1236 BE = CurrentBlock->end(); BI != BE; ) {
1237 if (isa<AllocationInst>(BI) || isa<TerminatorInst>(BI) ||
1238 isa<PHINode>(BI) || BI->mayReadFromMemory() ||
1239 BI->mayWriteToMemory()) {
1244 uint32_t valno = VN.lookup(BI);
1246 // Look for the predecessors for PRE opportunities. We're
1247 // only trying to solve the basic diamond case, where
1248 // a value is computed in the successor and one predecessor,
1249 // but not the other. We also explicitly disallow cases
1250 // where the successor is its own predecessor, because they're
1251 // more complicated to get right.
1252 unsigned numWith = 0;
1253 unsigned numWithout = 0;
1254 BasicBlock* PREPred = 0;
1255 DenseMap<BasicBlock*, Value*> predMap;
1256 for (pred_iterator PI = pred_begin(CurrentBlock),
1257 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
1258 // We're not interested in PRE where the block is its
1259 // own predecessor, on in blocks with predecessors
1260 // that are not reachable.
1261 if (*PI == CurrentBlock) {
1264 } else if (!localAvail.count(*PI)) {
1269 DenseMap<uint32_t, Value*>::iterator predV =
1270 localAvail[*PI]->table.find(valno);
1271 if (predV == localAvail[*PI]->table.end()) {
1274 } else if (predV->second == BI) {
1277 predMap[*PI] = predV->second;
1282 // Don't do PRE when it might increase code size, i.e. when
1283 // we would need to insert instructions in more than one pred.
1284 if (numWithout != 1 || numWith == 0) {
1289 // We can't do PRE safely on a critical edge, so instead we schedule
1290 // the edge to be split and perform the PRE the next time we iterate
1292 unsigned succNum = 0;
1293 for (unsigned i = 0, e = PREPred->getTerminator()->getNumSuccessors();
1295 if (PREPred->getTerminator()->getSuccessor(i) == CurrentBlock) {
1300 if (isCriticalEdge(PREPred->getTerminator(), succNum)) {
1301 toSplit.push_back(std::make_pair(PREPred->getTerminator(), succNum));
1307 // Instantiate the expression the in predecessor that lacked it.
1308 // Because we are going top-down through the block, all value numbers
1309 // will be available in the predecessor by the time we need them. Any
1310 // that weren't original present will have been instantiated earlier
1312 Instruction* PREInstr = BI->clone();
1313 bool success = true;
1314 for (unsigned i = 0; i < BI->getNumOperands(); ++i) {
1315 Value* op = BI->getOperand(i);
1316 if (isa<Argument>(op) || isa<Constant>(op) || isa<GlobalValue>(op))
1317 PREInstr->setOperand(i, op);
1319 Value* V = lookupNumber(PREPred, VN.lookup(op));
1324 PREInstr->setOperand(i, V);
1328 // Fail out if we encounter an operand that is not available in
1329 // the PRE predecessor. This is typically because of loads which
1330 // are not value numbered precisely.
1337 PREInstr->insertBefore(PREPred->getTerminator());
1338 PREInstr->setName(BI->getName() + ".pre");
1339 predMap[PREPred] = PREInstr;
1340 VN.add(PREInstr, valno);
1343 // Update the availability map to include the new instruction.
1344 localAvail[PREPred]->table.insert(std::make_pair(valno, PREInstr));
1346 // Create a PHI to make the value available in this block.
1347 PHINode* Phi = PHINode::Create(BI->getType(),
1348 BI->getName() + ".pre-phi",
1349 CurrentBlock->begin());
1350 for (pred_iterator PI = pred_begin(CurrentBlock),
1351 PE = pred_end(CurrentBlock); PI != PE; ++PI)
1352 Phi->addIncoming(predMap[*PI], *PI);
1355 localAvail[CurrentBlock]->table[valno] = Phi;
1357 BI->replaceAllUsesWith(Phi);
1360 Instruction* erase = BI;
1362 DEBUG(cerr << "GVN removed: " << *erase);
1363 MD->removeInstruction(erase);
1364 erase->eraseFromParent();
1369 for (SmallVector<std::pair<TerminatorInst*, unsigned>, 4>::iterator
1370 I = toSplit.begin(), E = toSplit.end(); I != E; ++I)
1371 SplitCriticalEdge(I->first, I->second, this);
1373 return changed || toSplit.size();
1376 // iterateOnFunction - Executes one iteration of GVN
1377 bool GVN::iterateOnFunction(Function &F) {
1378 cleanupGlobalSets();
1380 // Top-down walk of the dominator tree
1381 bool changed = false;
1382 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
1383 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
1384 changed |= processBlock(*DI);
1389 void GVN::cleanupGlobalSets() {
1393 for (DenseMap<BasicBlock*, ValueNumberScope*>::iterator
1394 I = localAvail.begin(), E = localAvail.end(); I != E; ++I)