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"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Value.h"
25 #include "llvm/ADT/BitVector.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/Compiler.h"
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 /// This class holds the mapping between values and value numbers. It is used
43 /// as an efficient mechanism to determine the expression-wise equivalence of
46 struct VISIBILITY_HIDDEN Expression {
47 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
48 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
49 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
50 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
51 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
52 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
53 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
54 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
55 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
56 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
59 ExpressionOpcode opcode;
64 SmallVector<uint32_t, 4> varargs;
68 Expression(ExpressionOpcode o) : opcode(o) { }
70 bool operator==(const Expression &other) const {
71 if (opcode != other.opcode)
73 else if (opcode == EMPTY || opcode == TOMBSTONE)
75 else if (type != other.type)
77 else if (function != other.function)
79 else if (firstVN != other.firstVN)
81 else if (secondVN != other.secondVN)
83 else if (thirdVN != other.thirdVN)
86 if (varargs.size() != other.varargs.size())
89 for (size_t i = 0; i < varargs.size(); ++i)
90 if (varargs[i] != other.varargs[i])
97 bool operator!=(const Expression &other) const {
98 if (opcode != other.opcode)
100 else if (opcode == EMPTY || opcode == TOMBSTONE)
102 else if (type != other.type)
104 else if (function != other.function)
106 else if (firstVN != other.firstVN)
108 else if (secondVN != other.secondVN)
110 else if (thirdVN != other.thirdVN)
113 if (varargs.size() != other.varargs.size())
116 for (size_t i = 0; i < varargs.size(); ++i)
117 if (varargs[i] != other.varargs[i])
125 class VISIBILITY_HIDDEN ValueTable {
127 DenseMap<Value*, uint32_t> valueNumbering;
128 DenseMap<Expression, uint32_t> expressionNumbering;
131 uint32_t nextValueNumber;
133 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
134 Expression::ExpressionOpcode getOpcode(CmpInst* C);
135 Expression::ExpressionOpcode getOpcode(CastInst* C);
136 Expression create_expression(BinaryOperator* BO);
137 Expression create_expression(CmpInst* C);
138 Expression create_expression(ShuffleVectorInst* V);
139 Expression create_expression(ExtractElementInst* C);
140 Expression create_expression(InsertElementInst* V);
141 Expression create_expression(SelectInst* V);
142 Expression create_expression(CastInst* C);
143 Expression create_expression(GetElementPtrInst* G);
144 Expression create_expression(CallInst* C);
146 ValueTable() : nextValueNumber(1) { }
147 uint32_t lookup_or_add(Value* V);
148 uint32_t lookup(Value* V) const;
149 void add(Value* V, uint32_t num);
151 void erase(Value* v);
153 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
154 uint32_t hash_operand(Value* v);
159 template <> struct DenseMapInfo<Expression> {
160 static inline Expression getEmptyKey() {
161 return Expression(Expression::EMPTY);
164 static inline Expression getTombstoneKey() {
165 return Expression(Expression::TOMBSTONE);
168 static unsigned getHashValue(const Expression e) {
169 unsigned hash = e.opcode;
171 hash = e.firstVN + hash * 37;
172 hash = e.secondVN + hash * 37;
173 hash = e.thirdVN + hash * 37;
175 hash = (unsigned)((uintptr_t)e.type >> 4) ^
176 (unsigned)((uintptr_t)e.type >> 9) +
179 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
180 E = e.varargs.end(); I != E; ++I)
181 hash = *I + hash * 37;
183 hash = (unsigned)((uintptr_t)e.function >> 4) ^
184 (unsigned)((uintptr_t)e.function >> 9) +
189 static bool isEqual(const Expression &LHS, const Expression &RHS) {
192 static bool isPod() { return true; }
196 //===----------------------------------------------------------------------===//
197 // ValueTable Internal Functions
198 //===----------------------------------------------------------------------===//
199 Expression::ExpressionOpcode
200 ValueTable::getOpcode(BinaryOperator* BO) {
201 switch(BO->getOpcode()) {
202 case Instruction::Add:
203 return Expression::ADD;
204 case Instruction::Sub:
205 return Expression::SUB;
206 case Instruction::Mul:
207 return Expression::MUL;
208 case Instruction::UDiv:
209 return Expression::UDIV;
210 case Instruction::SDiv:
211 return Expression::SDIV;
212 case Instruction::FDiv:
213 return Expression::FDIV;
214 case Instruction::URem:
215 return Expression::UREM;
216 case Instruction::SRem:
217 return Expression::SREM;
218 case Instruction::FRem:
219 return Expression::FREM;
220 case Instruction::Shl:
221 return Expression::SHL;
222 case Instruction::LShr:
223 return Expression::LSHR;
224 case Instruction::AShr:
225 return Expression::ASHR;
226 case Instruction::And:
227 return Expression::AND;
228 case Instruction::Or:
229 return Expression::OR;
230 case Instruction::Xor:
231 return Expression::XOR;
233 // THIS SHOULD NEVER HAPPEN
235 assert(0 && "Binary operator with unknown opcode?");
236 return Expression::ADD;
240 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
241 if (C->getOpcode() == Instruction::ICmp) {
242 switch (C->getPredicate()) {
243 case ICmpInst::ICMP_EQ:
244 return Expression::ICMPEQ;
245 case ICmpInst::ICMP_NE:
246 return Expression::ICMPNE;
247 case ICmpInst::ICMP_UGT:
248 return Expression::ICMPUGT;
249 case ICmpInst::ICMP_UGE:
250 return Expression::ICMPUGE;
251 case ICmpInst::ICMP_ULT:
252 return Expression::ICMPULT;
253 case ICmpInst::ICMP_ULE:
254 return Expression::ICMPULE;
255 case ICmpInst::ICMP_SGT:
256 return Expression::ICMPSGT;
257 case ICmpInst::ICMP_SGE:
258 return Expression::ICMPSGE;
259 case ICmpInst::ICMP_SLT:
260 return Expression::ICMPSLT;
261 case ICmpInst::ICMP_SLE:
262 return Expression::ICMPSLE;
264 // THIS SHOULD NEVER HAPPEN
266 assert(0 && "Comparison with unknown predicate?");
267 return Expression::ICMPEQ;
270 switch (C->getPredicate()) {
271 case FCmpInst::FCMP_OEQ:
272 return Expression::FCMPOEQ;
273 case FCmpInst::FCMP_OGT:
274 return Expression::FCMPOGT;
275 case FCmpInst::FCMP_OGE:
276 return Expression::FCMPOGE;
277 case FCmpInst::FCMP_OLT:
278 return Expression::FCMPOLT;
279 case FCmpInst::FCMP_OLE:
280 return Expression::FCMPOLE;
281 case FCmpInst::FCMP_ONE:
282 return Expression::FCMPONE;
283 case FCmpInst::FCMP_ORD:
284 return Expression::FCMPORD;
285 case FCmpInst::FCMP_UNO:
286 return Expression::FCMPUNO;
287 case FCmpInst::FCMP_UEQ:
288 return Expression::FCMPUEQ;
289 case FCmpInst::FCMP_UGT:
290 return Expression::FCMPUGT;
291 case FCmpInst::FCMP_UGE:
292 return Expression::FCMPUGE;
293 case FCmpInst::FCMP_ULT:
294 return Expression::FCMPULT;
295 case FCmpInst::FCMP_ULE:
296 return Expression::FCMPULE;
297 case FCmpInst::FCMP_UNE:
298 return Expression::FCMPUNE;
300 // THIS SHOULD NEVER HAPPEN
302 assert(0 && "Comparison with unknown predicate?");
303 return Expression::FCMPOEQ;
308 Expression::ExpressionOpcode
309 ValueTable::getOpcode(CastInst* C) {
310 switch(C->getOpcode()) {
311 case Instruction::Trunc:
312 return Expression::TRUNC;
313 case Instruction::ZExt:
314 return Expression::ZEXT;
315 case Instruction::SExt:
316 return Expression::SEXT;
317 case Instruction::FPToUI:
318 return Expression::FPTOUI;
319 case Instruction::FPToSI:
320 return Expression::FPTOSI;
321 case Instruction::UIToFP:
322 return Expression::UITOFP;
323 case Instruction::SIToFP:
324 return Expression::SITOFP;
325 case Instruction::FPTrunc:
326 return Expression::FPTRUNC;
327 case Instruction::FPExt:
328 return Expression::FPEXT;
329 case Instruction::PtrToInt:
330 return Expression::PTRTOINT;
331 case Instruction::IntToPtr:
332 return Expression::INTTOPTR;
333 case Instruction::BitCast:
334 return Expression::BITCAST;
336 // THIS SHOULD NEVER HAPPEN
338 assert(0 && "Cast operator with unknown opcode?");
339 return Expression::BITCAST;
343 uint32_t ValueTable::hash_operand(Value* v) {
344 if (CallInst* CI = dyn_cast<CallInst>(v))
345 if (!AA->doesNotAccessMemory(CI))
346 return nextValueNumber++;
348 return lookup_or_add(v);
351 Expression ValueTable::create_expression(CallInst* C) {
354 e.type = C->getType();
358 e.function = C->getCalledFunction();
359 e.opcode = Expression::CALL;
361 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
363 e.varargs.push_back(hash_operand(*I));
368 Expression ValueTable::create_expression(BinaryOperator* BO) {
371 e.firstVN = hash_operand(BO->getOperand(0));
372 e.secondVN = hash_operand(BO->getOperand(1));
375 e.type = BO->getType();
376 e.opcode = getOpcode(BO);
381 Expression ValueTable::create_expression(CmpInst* C) {
384 e.firstVN = hash_operand(C->getOperand(0));
385 e.secondVN = hash_operand(C->getOperand(1));
388 e.type = C->getType();
389 e.opcode = getOpcode(C);
394 Expression ValueTable::create_expression(CastInst* C) {
397 e.firstVN = hash_operand(C->getOperand(0));
401 e.type = C->getType();
402 e.opcode = getOpcode(C);
407 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
410 e.firstVN = hash_operand(S->getOperand(0));
411 e.secondVN = hash_operand(S->getOperand(1));
412 e.thirdVN = hash_operand(S->getOperand(2));
414 e.type = S->getType();
415 e.opcode = Expression::SHUFFLE;
420 Expression ValueTable::create_expression(ExtractElementInst* E) {
423 e.firstVN = hash_operand(E->getOperand(0));
424 e.secondVN = hash_operand(E->getOperand(1));
427 e.type = E->getType();
428 e.opcode = Expression::EXTRACT;
433 Expression ValueTable::create_expression(InsertElementInst* I) {
436 e.firstVN = hash_operand(I->getOperand(0));
437 e.secondVN = hash_operand(I->getOperand(1));
438 e.thirdVN = hash_operand(I->getOperand(2));
440 e.type = I->getType();
441 e.opcode = Expression::INSERT;
446 Expression ValueTable::create_expression(SelectInst* I) {
449 e.firstVN = hash_operand(I->getCondition());
450 e.secondVN = hash_operand(I->getTrueValue());
451 e.thirdVN = hash_operand(I->getFalseValue());
453 e.type = I->getType();
454 e.opcode = Expression::SELECT;
459 Expression ValueTable::create_expression(GetElementPtrInst* G) {
462 e.firstVN = hash_operand(G->getPointerOperand());
466 e.type = G->getType();
467 e.opcode = Expression::GEP;
469 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
471 e.varargs.push_back(hash_operand(*I));
476 //===----------------------------------------------------------------------===//
477 // ValueTable External Functions
478 //===----------------------------------------------------------------------===//
480 /// lookup_or_add - Returns the value number for the specified value, assigning
481 /// it a new number if it did not have one before.
482 uint32_t ValueTable::lookup_or_add(Value* V) {
483 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
484 if (VI != valueNumbering.end())
487 if (CallInst* C = dyn_cast<CallInst>(V)) {
488 if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
489 Expression e = create_expression(C);
491 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
492 if (EI != expressionNumbering.end()) {
493 valueNumbering.insert(std::make_pair(V, EI->second));
496 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
497 valueNumbering.insert(std::make_pair(V, nextValueNumber));
499 return nextValueNumber++;
502 valueNumbering.insert(std::make_pair(V, nextValueNumber));
503 return nextValueNumber++;
505 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
506 Expression e = create_expression(BO);
508 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
509 if (EI != expressionNumbering.end()) {
510 valueNumbering.insert(std::make_pair(V, EI->second));
513 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
514 valueNumbering.insert(std::make_pair(V, nextValueNumber));
516 return nextValueNumber++;
518 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
519 Expression e = create_expression(C);
521 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
522 if (EI != expressionNumbering.end()) {
523 valueNumbering.insert(std::make_pair(V, EI->second));
526 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
527 valueNumbering.insert(std::make_pair(V, nextValueNumber));
529 return nextValueNumber++;
531 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
532 Expression e = create_expression(U);
534 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
535 if (EI != expressionNumbering.end()) {
536 valueNumbering.insert(std::make_pair(V, EI->second));
539 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
540 valueNumbering.insert(std::make_pair(V, nextValueNumber));
542 return nextValueNumber++;
544 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
545 Expression e = create_expression(U);
547 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
548 if (EI != expressionNumbering.end()) {
549 valueNumbering.insert(std::make_pair(V, EI->second));
552 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
553 valueNumbering.insert(std::make_pair(V, nextValueNumber));
555 return nextValueNumber++;
557 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
558 Expression e = create_expression(U);
560 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
561 if (EI != expressionNumbering.end()) {
562 valueNumbering.insert(std::make_pair(V, EI->second));
565 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
566 valueNumbering.insert(std::make_pair(V, nextValueNumber));
568 return nextValueNumber++;
570 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
571 Expression e = create_expression(U);
573 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
574 if (EI != expressionNumbering.end()) {
575 valueNumbering.insert(std::make_pair(V, EI->second));
578 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
579 valueNumbering.insert(std::make_pair(V, nextValueNumber));
581 return nextValueNumber++;
583 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
584 Expression e = create_expression(U);
586 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
587 if (EI != expressionNumbering.end()) {
588 valueNumbering.insert(std::make_pair(V, EI->second));
591 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
592 valueNumbering.insert(std::make_pair(V, nextValueNumber));
594 return nextValueNumber++;
596 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
597 Expression e = create_expression(U);
599 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
600 if (EI != expressionNumbering.end()) {
601 valueNumbering.insert(std::make_pair(V, EI->second));
604 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
605 valueNumbering.insert(std::make_pair(V, nextValueNumber));
607 return nextValueNumber++;
610 valueNumbering.insert(std::make_pair(V, nextValueNumber));
611 return nextValueNumber++;
615 /// lookup - Returns the value number of the specified value. Fails if
616 /// the value has not yet been numbered.
617 uint32_t ValueTable::lookup(Value* V) const {
618 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
619 if (VI != valueNumbering.end())
622 assert(0 && "Value not numbered?");
627 /// clear - Remove all entries from the ValueTable
628 void ValueTable::clear() {
629 valueNumbering.clear();
630 expressionNumbering.clear();
634 /// erase - Remove a value from the value numbering
635 void ValueTable::erase(Value* V) {
636 valueNumbering.erase(V);
639 //===----------------------------------------------------------------------===//
640 // ValueNumberedSet Class
641 //===----------------------------------------------------------------------===//
643 class ValueNumberedSet {
645 SmallPtrSet<Value*, 8> contents;
648 ValueNumberedSet() { numbers.resize(1); }
649 ValueNumberedSet(const ValueNumberedSet& other) {
650 numbers = other.numbers;
651 contents = other.contents;
654 typedef SmallPtrSet<Value*, 8>::iterator iterator;
656 iterator begin() { return contents.begin(); }
657 iterator end() { return contents.end(); }
659 bool insert(Value* v) { return contents.insert(v); }
660 void insert(iterator I, iterator E) { contents.insert(I, E); }
661 void erase(Value* v) { contents.erase(v); }
662 unsigned count(Value* v) { return contents.count(v); }
663 size_t size() { return contents.size(); }
665 void set(unsigned i) {
666 if (i >= numbers.size())
672 void operator=(const ValueNumberedSet& other) {
673 contents = other.contents;
674 numbers = other.numbers;
677 void reset(unsigned i) {
678 if (i < numbers.size())
682 bool test(unsigned i) {
683 if (i >= numbers.size())
686 return numbers.test(i);
696 //===----------------------------------------------------------------------===//
698 //===----------------------------------------------------------------------===//
702 class VISIBILITY_HIDDEN GVN : public FunctionPass {
703 bool runOnFunction(Function &F);
705 static char ID; // Pass identification, replacement for typeid
706 GVN() : FunctionPass((intptr_t)&ID) { }
711 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
713 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
717 // This transformation requires dominator postdominator info
718 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
719 AU.setPreservesCFG();
720 AU.addRequired<DominatorTree>();
721 AU.addRequired<MemoryDependenceAnalysis>();
722 AU.addRequired<AliasAnalysis>();
723 AU.addPreserved<AliasAnalysis>();
724 AU.addPreserved<MemoryDependenceAnalysis>();
728 // FIXME: eliminate or document these better
729 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
730 void val_insert(ValueNumberedSet& s, Value* v);
731 bool processLoad(LoadInst* L,
732 DenseMap<Value*, LoadInst*>& lastLoad,
733 SmallVector<Instruction*, 4>& toErase);
734 bool processInstruction(Instruction* I,
735 ValueNumberedSet& currAvail,
736 DenseMap<Value*, LoadInst*>& lastSeenLoad,
737 SmallVector<Instruction*, 4>& toErase);
738 bool processNonLocalLoad(LoadInst* L,
739 SmallVector<Instruction*, 4>& toErase);
740 bool processMemCpy(MemCpyInst* M, SmallVector<Instruction*, 4>& toErase);
741 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
742 DenseMap<BasicBlock*, Value*> &Phis,
743 bool top_level = false);
744 void dump(DenseMap<BasicBlock*, Value*>& d);
745 bool iterateOnFunction(Function &F);
746 Value* CollapsePhi(PHINode* p);
747 bool isSafeReplacement(PHINode* p, Instruction* inst);
754 // createGVNPass - The public interface to this file...
755 FunctionPass *llvm::createGVNPass() { return new GVN(); }
757 static RegisterPass<GVN> X("gvn",
758 "Global Value Numbering");
760 STATISTIC(NumGVNInstr, "Number of instructions deleted");
761 STATISTIC(NumGVNLoad, "Number of loads deleted");
763 /// find_leader - Given a set and a value number, return the first
764 /// element of the set with that value number, or 0 if no such element
766 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
770 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
772 if (v == VN.lookup(*I))
775 assert(0 && "No leader found, but present bit is set?");
779 /// val_insert - Insert a value into a set only if there is not a value
780 /// with the same value number already in the set
781 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
782 uint32_t num = VN.lookup(v);
787 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
789 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
790 E = d.end(); I != E; ++I) {
791 if (I->second == MemoryDependenceAnalysis::None)
799 Value* GVN::CollapsePhi(PHINode* p) {
800 DominatorTree &DT = getAnalysis<DominatorTree>();
801 Value* constVal = p->hasConstantValue();
804 if (Instruction* inst = dyn_cast<Instruction>(constVal)) {
805 if (DT.dominates(inst, p))
806 if (isSafeReplacement(p, inst))
816 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
817 if (!isa<PHINode>(inst))
820 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
822 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
823 if (use_phi->getParent() == inst->getParent())
829 /// GetValueForBlock - Get the value to use within the specified basic block.
830 /// available values are in Phis.
831 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
832 DenseMap<BasicBlock*, Value*> &Phis,
835 // If we have already computed this value, return the previously computed val.
836 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
837 if (V != Phis.end() && !top_level) return V->second;
839 BasicBlock* singlePred = BB->getSinglePredecessor();
841 Value *ret = GetValueForBlock(singlePred, orig, Phis);
845 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
846 // now, then get values to fill in the incoming values for the PHI.
847 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
849 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
851 if (Phis.count(BB) == 0)
852 Phis.insert(std::make_pair(BB, PN));
854 // Fill in the incoming values for the block.
855 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
856 Value* val = GetValueForBlock(*PI, orig, Phis);
858 PN->addIncoming(val, *PI);
860 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
861 AA.copyValue(orig, PN);
863 // Attempt to collapse PHI nodes that are trivially redundant
864 Value* v = CollapsePhi(PN);
866 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
868 MD.removeInstruction(PN);
869 PN->replaceAllUsesWith(v);
871 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
872 E = Phis.end(); I != E; ++I)
876 PN->eraseFromParent();
883 // Cache our phi construction results
884 phiMap[orig->getPointerOperand()].insert(PN);
888 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
889 /// non-local by performing PHI construction.
890 bool GVN::processNonLocalLoad(LoadInst* L,
891 SmallVector<Instruction*, 4>& toErase) {
892 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
894 // Find the non-local dependencies of the load
895 DenseMap<BasicBlock*, Value*> deps;
896 MD.getNonLocalDependency(L, deps);
898 DenseMap<BasicBlock*, Value*> repl;
900 // Filter out useless results (non-locals, etc)
901 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
903 if (I->second == MemoryDependenceAnalysis::None) {
905 } else if (I->second == MemoryDependenceAnalysis::NonLocal) {
907 } else if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
908 if (S->getPointerOperand() == L->getPointerOperand())
909 repl[I->first] = S->getOperand(0);
912 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
913 if (LD->getPointerOperand() == L->getPointerOperand())
921 // Use cached PHI construction information from previous runs
922 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
923 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
925 if ((*I)->getParent() == L->getParent()) {
926 MD.removeInstruction(L);
927 L->replaceAllUsesWith(*I);
928 toErase.push_back(L);
933 repl.insert(std::make_pair((*I)->getParent(), *I));
937 // Perform PHI construction
938 SmallPtrSet<BasicBlock*, 4> visited;
939 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
941 MD.removeInstruction(L);
942 L->replaceAllUsesWith(v);
943 toErase.push_back(L);
949 /// processLoad - Attempt to eliminate a load, first by eliminating it
950 /// locally, and then attempting non-local elimination if that fails.
951 bool GVN::processLoad(LoadInst* L,
952 DenseMap<Value*, LoadInst*>& lastLoad,
953 SmallVector<Instruction*, 4>& toErase) {
954 if (L->isVolatile()) {
955 lastLoad[L->getPointerOperand()] = L;
959 Value* pointer = L->getPointerOperand();
960 LoadInst*& last = lastLoad[pointer];
962 // ... to a pointer that has been loaded from before...
963 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
964 bool removedNonLocal = false;
965 Instruction* dep = MD.getDependency(L);
966 if (dep == MemoryDependenceAnalysis::NonLocal &&
967 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
968 removedNonLocal = processNonLocalLoad(L, toErase);
970 if (!removedNonLocal)
973 return removedNonLocal;
977 bool deletedLoad = false;
979 // Walk up the dependency chain until we either find
980 // a dependency we can use, or we can't walk any further
981 while (dep != MemoryDependenceAnalysis::None &&
982 dep != MemoryDependenceAnalysis::NonLocal &&
983 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
984 // ... that depends on a store ...
985 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
986 if (S->getPointerOperand() == pointer) {
988 MD.removeInstruction(L);
990 L->replaceAllUsesWith(S->getOperand(0));
991 toErase.push_back(L);
996 // Whether we removed it or not, we can't
1000 // If we don't depend on a store, and we haven't
1001 // been loaded before, bail.
1003 } else if (dep == last) {
1005 MD.removeInstruction(L);
1007 L->replaceAllUsesWith(last);
1008 toErase.push_back(L);
1014 dep = MD.getDependency(L, dep);
1018 if (dep != MemoryDependenceAnalysis::None &&
1019 dep != MemoryDependenceAnalysis::NonLocal &&
1020 isa<AllocationInst>(dep)) {
1021 // Check that this load is actually from the
1022 // allocation we found
1023 Value* v = L->getOperand(0);
1025 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
1026 v = BC->getOperand(0);
1027 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
1028 v = GEP->getOperand(0);
1033 // If this load depends directly on an allocation, there isn't
1034 // anything stored there; therefore, we can optimize this load
1036 MD.removeInstruction(L);
1038 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1039 toErase.push_back(L);
1051 /// processMemCpy - perform simplication of memcpy's. If we have memcpy A which
1052 /// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1053 /// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1054 /// This allows later passes to remove the first memcpy altogether.
1055 bool GVN::processMemCpy(MemCpyInst* M,
1056 SmallVector<Instruction*, 4>& toErase) {
1057 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1059 // First, we have to check that the dependency is another memcpy
1060 Instruction* dep = MD.getDependency(M);
1061 if (dep == MemoryDependenceAnalysis::None ||
1062 dep == MemoryDependenceAnalysis::NonLocal ||
1063 !isa<MemCpyInst>(dep))
1066 // We can only transforms memcpy's where the dest of one is the source of the
1068 MemCpyInst* MDep = cast<MemCpyInst>(dep);
1069 if (M->getSource() != MDep->getDest())
1072 // Second, the length of the memcpy's must be the same, or the preceeding one
1073 // must be larger than the following one.
1074 ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1075 ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1079 uint64_t CpySize = C1->getValue().getZExtValue();
1080 uint64_t DepSize = C2->getValue().getZExtValue();
1082 if (DepSize < CpySize)
1085 // Finally, we have to make sure that the dest of the second does not
1086 // alias the source of the first
1087 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1088 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1089 AliasAnalysis::NoAlias)
1091 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1092 AliasAnalysis::NoAlias)
1094 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1095 != AliasAnalysis::NoAlias)
1098 // If all checks passed, then we can transform these memcpy's
1099 bool is32bit = M->getIntrinsicID() == Intrinsic::memcpy_i32;
1100 Function* MemMoveFun = Intrinsic::getDeclaration(
1101 M->getParent()->getParent()->getParent(),
1102 is32bit ? Intrinsic::memcpy_i32 :
1103 Intrinsic::memcpy_i64);
1105 std::vector<Value*> args;
1106 args.push_back(M->getRawDest());
1107 args.push_back(MDep->getRawSource());
1108 args.push_back(M->getLength());
1109 args.push_back(M->getAlignment());
1111 CallInst* C = new CallInst(MemMoveFun, args.begin(), args.end(), "", M);
1113 if (MD.getDependency(C) == MDep) {
1114 MD.dropInstruction(M);
1115 toErase.push_back(M);
1118 MD.removeInstruction(C);
1119 toErase.push_back(C);
1124 /// processInstruction - When calculating availability, handle an instruction
1125 /// by inserting it into the appropriate sets
1126 bool GVN::processInstruction(Instruction* I,
1127 ValueNumberedSet& currAvail,
1128 DenseMap<Value*, LoadInst*>& lastSeenLoad,
1129 SmallVector<Instruction*, 4>& toErase) {
1130 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1131 return processLoad(L, lastSeenLoad, toErase);
1132 } else if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
1133 return processMemCpy(M, toErase);
1136 unsigned num = VN.lookup_or_add(I);
1138 // Collapse PHI nodes
1139 if (PHINode* p = dyn_cast<PHINode>(I)) {
1140 Value* constVal = CollapsePhi(p);
1143 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1145 if (PI->second.count(p))
1146 PI->second.erase(p);
1148 p->replaceAllUsesWith(constVal);
1149 toErase.push_back(p);
1151 // Perform value-number based elimination
1152 } else if (currAvail.test(num)) {
1153 Value* repl = find_leader(currAvail, num);
1155 if (CallInst* CI = dyn_cast<CallInst>(I)) {
1156 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1157 if (!AA.doesNotAccessMemory(CI)) {
1158 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1159 if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1160 MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1161 // There must be an intervening may-alias store, so nothing from
1162 // this point on will be able to be replaced with the preceding call
1163 currAvail.erase(repl);
1164 currAvail.insert(I);
1172 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1173 MD.removeInstruction(I);
1176 I->replaceAllUsesWith(repl);
1177 toErase.push_back(I);
1179 } else if (!I->isTerminator()) {
1181 currAvail.insert(I);
1187 // GVN::runOnFunction - This is the main transformation entry point for a
1190 bool GVN::runOnFunction(Function& F) {
1191 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1193 bool changed = false;
1194 bool shouldContinue = true;
1196 while (shouldContinue) {
1197 shouldContinue = iterateOnFunction(F);
1198 changed |= shouldContinue;
1205 // GVN::iterateOnFunction - Executes one iteration of GVN
1206 bool GVN::iterateOnFunction(Function &F) {
1207 // Clean out global sets from any previous functions
1209 availableOut.clear();
1212 bool changed_function = false;
1214 DominatorTree &DT = getAnalysis<DominatorTree>();
1216 SmallVector<Instruction*, 4> toErase;
1218 // Top-down walk of the dominator tree
1219 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1220 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1222 // Get the set to update for this block
1223 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1224 DenseMap<Value*, LoadInst*> lastSeenLoad;
1226 BasicBlock* BB = DI->getBlock();
1228 // A block inherits AVAIL_OUT from its dominator
1229 if (DI->getIDom() != 0)
1230 currAvail = availableOut[DI->getIDom()->getBlock()];
1232 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1234 changed_function |= processInstruction(BI, currAvail,
1235 lastSeenLoad, toErase);
1237 NumGVNInstr += toErase.size();
1239 // Avoid iterator invalidation
1242 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1243 E = toErase.end(); I != E; ++I) {
1244 (*I)->eraseFromParent();
1251 return changed_function;