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/ParameterAttributes.h"
25 #include "llvm/Value.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/DepthFirstIterator.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/Analysis/Dominators.h"
33 #include "llvm/Analysis/AliasAnalysis.h"
34 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
35 #include "llvm/Support/CFG.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Target/TargetData.h"
40 //===----------------------------------------------------------------------===//
42 //===----------------------------------------------------------------------===//
44 /// This class holds the mapping between values and value numbers. It is used
45 /// as an efficient mechanism to determine the expression-wise equivalence of
48 struct VISIBILITY_HIDDEN Expression {
49 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
50 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
51 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
52 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
53 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
54 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
55 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
56 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
57 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
58 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
61 ExpressionOpcode opcode;
66 SmallVector<uint32_t, 4> varargs;
70 Expression(ExpressionOpcode o) : opcode(o) { }
72 bool operator==(const Expression &other) const {
73 if (opcode != other.opcode)
75 else if (opcode == EMPTY || opcode == TOMBSTONE)
77 else if (type != other.type)
79 else if (function != other.function)
81 else if (firstVN != other.firstVN)
83 else if (secondVN != other.secondVN)
85 else if (thirdVN != other.thirdVN)
88 if (varargs.size() != other.varargs.size())
91 for (size_t i = 0; i < varargs.size(); ++i)
92 if (varargs[i] != other.varargs[i])
99 bool operator!=(const Expression &other) const {
100 if (opcode != other.opcode)
102 else if (opcode == EMPTY || opcode == TOMBSTONE)
104 else if (type != other.type)
106 else if (function != other.function)
108 else if (firstVN != other.firstVN)
110 else if (secondVN != other.secondVN)
112 else if (thirdVN != other.thirdVN)
115 if (varargs.size() != other.varargs.size())
118 for (size_t i = 0; i < varargs.size(); ++i)
119 if (varargs[i] != other.varargs[i])
127 class VISIBILITY_HIDDEN ValueTable {
129 DenseMap<Value*, uint32_t> valueNumbering;
130 DenseMap<Expression, uint32_t> expressionNumbering;
133 uint32_t nextValueNumber;
135 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
136 Expression::ExpressionOpcode getOpcode(CmpInst* C);
137 Expression::ExpressionOpcode getOpcode(CastInst* C);
138 Expression create_expression(BinaryOperator* BO);
139 Expression create_expression(CmpInst* C);
140 Expression create_expression(ShuffleVectorInst* V);
141 Expression create_expression(ExtractElementInst* C);
142 Expression create_expression(InsertElementInst* V);
143 Expression create_expression(SelectInst* V);
144 Expression create_expression(CastInst* C);
145 Expression create_expression(GetElementPtrInst* G);
146 Expression create_expression(CallInst* C);
148 ValueTable() : nextValueNumber(1) { }
149 uint32_t lookup_or_add(Value* V);
150 uint32_t lookup(Value* V) const;
151 void add(Value* V, uint32_t num);
153 void erase(Value* v);
155 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
156 uint32_t hash_operand(Value* v);
161 template <> struct DenseMapInfo<Expression> {
162 static inline Expression getEmptyKey() {
163 return Expression(Expression::EMPTY);
166 static inline Expression getTombstoneKey() {
167 return Expression(Expression::TOMBSTONE);
170 static unsigned getHashValue(const Expression e) {
171 unsigned hash = e.opcode;
173 hash = e.firstVN + hash * 37;
174 hash = e.secondVN + hash * 37;
175 hash = e.thirdVN + hash * 37;
177 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
178 (unsigned)((uintptr_t)e.type >> 9)) +
181 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
182 E = e.varargs.end(); I != E; ++I)
183 hash = *I + hash * 37;
185 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
186 (unsigned)((uintptr_t)e.function >> 9)) +
191 static bool isEqual(const Expression &LHS, const Expression &RHS) {
194 static bool isPod() { return true; }
198 //===----------------------------------------------------------------------===//
199 // ValueTable Internal Functions
200 //===----------------------------------------------------------------------===//
201 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
202 switch(BO->getOpcode()) {
203 default: // THIS SHOULD NEVER HAPPEN
204 assert(0 && "Binary operator with unknown opcode?");
205 case Instruction::Add: return Expression::ADD;
206 case Instruction::Sub: return Expression::SUB;
207 case Instruction::Mul: return Expression::MUL;
208 case Instruction::UDiv: return Expression::UDIV;
209 case Instruction::SDiv: return Expression::SDIV;
210 case Instruction::FDiv: return Expression::FDIV;
211 case Instruction::URem: return Expression::UREM;
212 case Instruction::SRem: return Expression::SREM;
213 case Instruction::FRem: return Expression::FREM;
214 case Instruction::Shl: return Expression::SHL;
215 case Instruction::LShr: return Expression::LSHR;
216 case Instruction::AShr: return Expression::ASHR;
217 case Instruction::And: return Expression::AND;
218 case Instruction::Or: return Expression::OR;
219 case Instruction::Xor: return Expression::XOR;
223 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
224 if (isa<ICmpInst>(C)) {
225 switch (C->getPredicate()) {
226 default: // THIS SHOULD NEVER HAPPEN
227 assert(0 && "Comparison with unknown predicate?");
228 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
229 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
230 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
231 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
232 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
233 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
234 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
235 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
236 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
237 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
240 assert(isa<FCmpInst>(C) && "Unknown compare");
241 switch (C->getPredicate()) {
242 default: // THIS SHOULD NEVER HAPPEN
243 assert(0 && "Comparison with unknown predicate?");
244 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
245 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
246 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
247 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
248 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
249 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
250 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
251 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
252 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
253 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
254 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
255 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
256 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
257 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
261 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
262 switch(C->getOpcode()) {
263 default: // THIS SHOULD NEVER HAPPEN
264 assert(0 && "Cast operator with unknown opcode?");
265 case Instruction::Trunc: return Expression::TRUNC;
266 case Instruction::ZExt: return Expression::ZEXT;
267 case Instruction::SExt: return Expression::SEXT;
268 case Instruction::FPToUI: return Expression::FPTOUI;
269 case Instruction::FPToSI: return Expression::FPTOSI;
270 case Instruction::UIToFP: return Expression::UITOFP;
271 case Instruction::SIToFP: return Expression::SITOFP;
272 case Instruction::FPTrunc: return Expression::FPTRUNC;
273 case Instruction::FPExt: return Expression::FPEXT;
274 case Instruction::PtrToInt: return Expression::PTRTOINT;
275 case Instruction::IntToPtr: return Expression::INTTOPTR;
276 case Instruction::BitCast: return Expression::BITCAST;
280 uint32_t ValueTable::hash_operand(Value* v) {
281 if (CallInst* CI = dyn_cast<CallInst>(v))
282 if (!AA->doesNotAccessMemory(CI))
283 return nextValueNumber++;
285 return lookup_or_add(v);
288 Expression ValueTable::create_expression(CallInst* C) {
291 e.type = C->getType();
295 e.function = C->getCalledFunction();
296 e.opcode = Expression::CALL;
298 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
300 e.varargs.push_back(hash_operand(*I));
305 Expression ValueTable::create_expression(BinaryOperator* BO) {
308 e.firstVN = hash_operand(BO->getOperand(0));
309 e.secondVN = hash_operand(BO->getOperand(1));
312 e.type = BO->getType();
313 e.opcode = getOpcode(BO);
318 Expression ValueTable::create_expression(CmpInst* C) {
321 e.firstVN = hash_operand(C->getOperand(0));
322 e.secondVN = hash_operand(C->getOperand(1));
325 e.type = C->getType();
326 e.opcode = getOpcode(C);
331 Expression ValueTable::create_expression(CastInst* C) {
334 e.firstVN = hash_operand(C->getOperand(0));
338 e.type = C->getType();
339 e.opcode = getOpcode(C);
344 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
347 e.firstVN = hash_operand(S->getOperand(0));
348 e.secondVN = hash_operand(S->getOperand(1));
349 e.thirdVN = hash_operand(S->getOperand(2));
351 e.type = S->getType();
352 e.opcode = Expression::SHUFFLE;
357 Expression ValueTable::create_expression(ExtractElementInst* E) {
360 e.firstVN = hash_operand(E->getOperand(0));
361 e.secondVN = hash_operand(E->getOperand(1));
364 e.type = E->getType();
365 e.opcode = Expression::EXTRACT;
370 Expression ValueTable::create_expression(InsertElementInst* I) {
373 e.firstVN = hash_operand(I->getOperand(0));
374 e.secondVN = hash_operand(I->getOperand(1));
375 e.thirdVN = hash_operand(I->getOperand(2));
377 e.type = I->getType();
378 e.opcode = Expression::INSERT;
383 Expression ValueTable::create_expression(SelectInst* I) {
386 e.firstVN = hash_operand(I->getCondition());
387 e.secondVN = hash_operand(I->getTrueValue());
388 e.thirdVN = hash_operand(I->getFalseValue());
390 e.type = I->getType();
391 e.opcode = Expression::SELECT;
396 Expression ValueTable::create_expression(GetElementPtrInst* G) {
399 e.firstVN = hash_operand(G->getPointerOperand());
403 e.type = G->getType();
404 e.opcode = Expression::GEP;
406 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
408 e.varargs.push_back(hash_operand(*I));
413 //===----------------------------------------------------------------------===//
414 // ValueTable External Functions
415 //===----------------------------------------------------------------------===//
417 /// lookup_or_add - Returns the value number for the specified value, assigning
418 /// it a new number if it did not have one before.
419 uint32_t ValueTable::lookup_or_add(Value* V) {
420 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
421 if (VI != valueNumbering.end())
424 if (CallInst* C = dyn_cast<CallInst>(V)) {
425 if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
426 Expression e = create_expression(C);
428 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
429 if (EI != expressionNumbering.end()) {
430 valueNumbering.insert(std::make_pair(V, EI->second));
433 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
434 valueNumbering.insert(std::make_pair(V, nextValueNumber));
436 return nextValueNumber++;
439 valueNumbering.insert(std::make_pair(V, nextValueNumber));
440 return nextValueNumber++;
442 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
443 Expression e = create_expression(BO);
445 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
446 if (EI != expressionNumbering.end()) {
447 valueNumbering.insert(std::make_pair(V, EI->second));
450 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
451 valueNumbering.insert(std::make_pair(V, nextValueNumber));
453 return nextValueNumber++;
455 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
456 Expression e = create_expression(C);
458 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
459 if (EI != expressionNumbering.end()) {
460 valueNumbering.insert(std::make_pair(V, EI->second));
463 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
464 valueNumbering.insert(std::make_pair(V, nextValueNumber));
466 return nextValueNumber++;
468 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
469 Expression e = create_expression(U);
471 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
472 if (EI != expressionNumbering.end()) {
473 valueNumbering.insert(std::make_pair(V, EI->second));
476 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
477 valueNumbering.insert(std::make_pair(V, nextValueNumber));
479 return nextValueNumber++;
481 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
482 Expression e = create_expression(U);
484 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
485 if (EI != expressionNumbering.end()) {
486 valueNumbering.insert(std::make_pair(V, EI->second));
489 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
490 valueNumbering.insert(std::make_pair(V, nextValueNumber));
492 return nextValueNumber++;
494 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
495 Expression e = create_expression(U);
497 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
498 if (EI != expressionNumbering.end()) {
499 valueNumbering.insert(std::make_pair(V, EI->second));
502 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
503 valueNumbering.insert(std::make_pair(V, nextValueNumber));
505 return nextValueNumber++;
507 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
508 Expression e = create_expression(U);
510 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
511 if (EI != expressionNumbering.end()) {
512 valueNumbering.insert(std::make_pair(V, EI->second));
515 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
516 valueNumbering.insert(std::make_pair(V, nextValueNumber));
518 return nextValueNumber++;
520 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
521 Expression e = create_expression(U);
523 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
524 if (EI != expressionNumbering.end()) {
525 valueNumbering.insert(std::make_pair(V, EI->second));
528 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
529 valueNumbering.insert(std::make_pair(V, nextValueNumber));
531 return nextValueNumber++;
533 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
534 Expression e = create_expression(U);
536 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
537 if (EI != expressionNumbering.end()) {
538 valueNumbering.insert(std::make_pair(V, EI->second));
541 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
542 valueNumbering.insert(std::make_pair(V, nextValueNumber));
544 return nextValueNumber++;
547 valueNumbering.insert(std::make_pair(V, nextValueNumber));
548 return nextValueNumber++;
552 /// lookup - Returns the value number of the specified value. Fails if
553 /// the value has not yet been numbered.
554 uint32_t ValueTable::lookup(Value* V) const {
555 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
556 assert(VI != valueNumbering.end() && "Value not numbered?");
560 /// clear - Remove all entries from the ValueTable
561 void ValueTable::clear() {
562 valueNumbering.clear();
563 expressionNumbering.clear();
567 /// erase - Remove a value from the value numbering
568 void ValueTable::erase(Value* V) {
569 valueNumbering.erase(V);
572 //===----------------------------------------------------------------------===//
573 // ValueNumberedSet Class
574 //===----------------------------------------------------------------------===//
576 class VISIBILITY_HIDDEN ValueNumberedSet {
578 SmallPtrSet<Value*, 8> contents;
581 ValueNumberedSet() { numbers.resize(1); }
582 ValueNumberedSet(const ValueNumberedSet& other) {
583 numbers = other.numbers;
584 contents = other.contents;
587 typedef SmallPtrSet<Value*, 8>::iterator iterator;
589 iterator begin() { return contents.begin(); }
590 iterator end() { return contents.end(); }
592 bool insert(Value* v) { return contents.insert(v); }
593 void insert(iterator I, iterator E) { contents.insert(I, E); }
594 void erase(Value* v) { contents.erase(v); }
595 unsigned count(Value* v) { return contents.count(v); }
596 size_t size() { return contents.size(); }
598 void set(unsigned i) {
599 if (i >= numbers.size())
605 void operator=(const ValueNumberedSet& other) {
606 contents = other.contents;
607 numbers = other.numbers;
610 void reset(unsigned i) {
611 if (i < numbers.size())
615 bool test(unsigned i) {
616 if (i >= numbers.size())
619 return numbers.test(i);
629 //===----------------------------------------------------------------------===//
631 //===----------------------------------------------------------------------===//
635 class VISIBILITY_HIDDEN GVN : public FunctionPass {
636 bool runOnFunction(Function &F);
638 static char ID; // Pass identification, replacement for typeid
639 GVN() : FunctionPass((intptr_t)&ID) { }
644 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
646 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
650 // This transformation requires dominator postdominator info
651 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
652 AU.setPreservesCFG();
653 AU.addRequired<DominatorTree>();
654 AU.addRequired<MemoryDependenceAnalysis>();
655 AU.addRequired<AliasAnalysis>();
656 AU.addRequired<TargetData>();
657 AU.addPreserved<AliasAnalysis>();
658 AU.addPreserved<MemoryDependenceAnalysis>();
659 AU.addPreserved<TargetData>();
663 // FIXME: eliminate or document these better
664 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
665 void val_insert(ValueNumberedSet& s, Value* v);
666 bool processLoad(LoadInst* L,
667 DenseMap<Value*, LoadInst*> &lastLoad,
668 SmallVectorImpl<Instruction*> &toErase);
669 bool processInstruction(Instruction* I,
670 ValueNumberedSet& currAvail,
671 DenseMap<Value*, LoadInst*>& lastSeenLoad,
672 SmallVectorImpl<Instruction*> &toErase);
673 bool processNonLocalLoad(LoadInst* L,
674 SmallVectorImpl<Instruction*> &toErase);
675 bool processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
676 SmallVectorImpl<Instruction*> &toErase);
677 bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
678 SmallVectorImpl<Instruction*> &toErase);
679 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
680 DenseMap<BasicBlock*, Value*> &Phis,
681 bool top_level = false);
682 void dump(DenseMap<BasicBlock*, Value*>& d);
683 bool iterateOnFunction(Function &F);
684 Value* CollapsePhi(PHINode* p);
685 bool isSafeReplacement(PHINode* p, Instruction* inst);
691 // createGVNPass - The public interface to this file...
692 FunctionPass *llvm::createGVNPass() { return new GVN(); }
694 static RegisterPass<GVN> X("gvn",
695 "Global Value Numbering");
697 STATISTIC(NumGVNInstr, "Number of instructions deleted");
698 STATISTIC(NumGVNLoad, "Number of loads deleted");
700 /// find_leader - Given a set and a value number, return the first
701 /// element of the set with that value number, or 0 if no such element
703 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
707 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
709 if (v == VN.lookup(*I))
712 assert(0 && "No leader found, but present bit is set?");
716 /// val_insert - Insert a value into a set only if there is not a value
717 /// with the same value number already in the set
718 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
719 uint32_t num = VN.lookup(v);
724 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
726 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
727 E = d.end(); I != E; ++I) {
728 if (I->second == MemoryDependenceAnalysis::None)
736 Value* GVN::CollapsePhi(PHINode* p) {
737 DominatorTree &DT = getAnalysis<DominatorTree>();
738 Value* constVal = p->hasConstantValue();
740 if (!constVal) return 0;
742 Instruction* inst = dyn_cast<Instruction>(constVal);
746 if (DT.dominates(inst, p))
747 if (isSafeReplacement(p, inst))
752 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
753 if (!isa<PHINode>(inst))
756 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
758 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
759 if (use_phi->getParent() == inst->getParent())
765 /// GetValueForBlock - Get the value to use within the specified basic block.
766 /// available values are in Phis.
767 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
768 DenseMap<BasicBlock*, Value*> &Phis,
771 // If we have already computed this value, return the previously computed val.
772 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
773 if (V != Phis.end() && !top_level) return V->second;
775 BasicBlock* singlePred = BB->getSinglePredecessor();
777 Value *ret = GetValueForBlock(singlePred, orig, Phis);
782 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
783 // now, then get values to fill in the incoming values for the PHI.
784 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
786 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
788 if (Phis.count(BB) == 0)
789 Phis.insert(std::make_pair(BB, PN));
791 // Fill in the incoming values for the block.
792 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
793 Value* val = GetValueForBlock(*PI, orig, Phis);
794 PN->addIncoming(val, *PI);
797 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
798 AA.copyValue(orig, PN);
800 // Attempt to collapse PHI nodes that are trivially redundant
801 Value* v = CollapsePhi(PN);
803 // Cache our phi construction results
804 phiMap[orig->getPointerOperand()].insert(PN);
808 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
810 MD.removeInstruction(PN);
811 PN->replaceAllUsesWith(v);
813 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
814 E = Phis.end(); I != E; ++I)
818 PN->eraseFromParent();
824 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
825 /// non-local by performing PHI construction.
826 bool GVN::processNonLocalLoad(LoadInst* L,
827 SmallVectorImpl<Instruction*> &toErase) {
828 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
830 // Find the non-local dependencies of the load
831 DenseMap<BasicBlock*, Value*> deps;
832 MD.getNonLocalDependency(L, deps);
834 DenseMap<BasicBlock*, Value*> repl;
836 // Filter out useless results (non-locals, etc)
837 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
839 if (I->second == MemoryDependenceAnalysis::None)
842 if (I->second == MemoryDependenceAnalysis::NonLocal)
845 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
846 if (S->getPointerOperand() != L->getPointerOperand())
848 repl[I->first] = S->getOperand(0);
849 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
850 if (LD->getPointerOperand() != L->getPointerOperand())
858 // Use cached PHI construction information from previous runs
859 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
860 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
862 if ((*I)->getParent() == L->getParent()) {
863 MD.removeInstruction(L);
864 L->replaceAllUsesWith(*I);
865 toErase.push_back(L);
870 repl.insert(std::make_pair((*I)->getParent(), *I));
873 // Perform PHI construction
874 SmallPtrSet<BasicBlock*, 4> visited;
875 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
877 MD.removeInstruction(L);
878 L->replaceAllUsesWith(v);
879 toErase.push_back(L);
885 /// processLoad - Attempt to eliminate a load, first by eliminating it
886 /// locally, and then attempting non-local elimination if that fails.
887 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
888 SmallVectorImpl<Instruction*> &toErase) {
889 if (L->isVolatile()) {
890 lastLoad[L->getPointerOperand()] = L;
894 Value* pointer = L->getPointerOperand();
895 LoadInst*& last = lastLoad[pointer];
897 // ... to a pointer that has been loaded from before...
898 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
899 bool removedNonLocal = false;
900 Instruction* dep = MD.getDependency(L);
901 if (dep == MemoryDependenceAnalysis::NonLocal &&
902 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
903 removedNonLocal = processNonLocalLoad(L, toErase);
905 if (!removedNonLocal)
908 return removedNonLocal;
912 bool deletedLoad = false;
914 // Walk up the dependency chain until we either find
915 // a dependency we can use, or we can't walk any further
916 while (dep != MemoryDependenceAnalysis::None &&
917 dep != MemoryDependenceAnalysis::NonLocal &&
918 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
919 // ... that depends on a store ...
920 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
921 if (S->getPointerOperand() == pointer) {
923 MD.removeInstruction(L);
925 L->replaceAllUsesWith(S->getOperand(0));
926 toErase.push_back(L);
931 // Whether we removed it or not, we can't
935 // If we don't depend on a store, and we haven't
936 // been loaded before, bail.
938 } else if (dep == last) {
940 MD.removeInstruction(L);
942 L->replaceAllUsesWith(last);
943 toErase.push_back(L);
949 dep = MD.getDependency(L, dep);
953 if (dep != MemoryDependenceAnalysis::None &&
954 dep != MemoryDependenceAnalysis::NonLocal &&
955 isa<AllocationInst>(dep)) {
956 // Check that this load is actually from the
957 // allocation we found
958 Value* v = L->getOperand(0);
960 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
961 v = BC->getOperand(0);
962 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
963 v = GEP->getOperand(0);
968 // If this load depends directly on an allocation, there isn't
969 // anything stored there; therefore, we can optimize this load
971 MD.removeInstruction(L);
973 L->replaceAllUsesWith(UndefValue::get(L->getType()));
974 toErase.push_back(L);
986 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
987 /// and checks for the possibility of a call slot optimization by having
988 /// the call write its result directly into the destination of the memcpy.
989 bool GVN::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C,
990 SmallVectorImpl<Instruction*> &toErase) {
991 // The general transformation to keep in mind is
993 // call @func(..., src, ...)
994 // memcpy(dest, src, ...)
998 // memcpy(dest, src, ...)
999 // call @func(..., dest, ...)
1001 // Since moving the memcpy is technically awkward, we additionally check that
1002 // src only holds uninitialized values at the moment of the call, meaning that
1003 // the memcpy can be discarded rather than moved.
1005 // Deliberately get the source and destination with bitcasts stripped away,
1006 // because we'll need to do type comparisons based on the underlying type.
1007 Value* cpyDest = cpy->getDest();
1008 Value* cpySrc = cpy->getSource();
1009 CallSite CS = CallSite::get(C);
1011 // We need to be able to reason about the size of the memcpy, so we require
1012 // that it be a constant.
1013 ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
1017 // Require that src be an alloca. This simplifies the reasoning considerably.
1018 AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
1022 // Check that all of src is copied to dest.
1023 TargetData& TD = getAnalysis<TargetData>();
1025 ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
1029 uint64_t srcSize = TD.getABITypeSize(srcAlloca->getAllocatedType()) *
1030 srcArraySize->getZExtValue();
1032 if (cpyLength->getZExtValue() < srcSize)
1035 // Check that accessing the first srcSize bytes of dest will not cause a
1036 // trap. Otherwise the transform is invalid since it might cause a trap
1037 // to occur earlier than it otherwise would.
1038 if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
1039 // The destination is an alloca. Check it is larger than srcSize.
1040 ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
1044 uint64_t destSize = TD.getABITypeSize(A->getAllocatedType()) *
1045 destArraySize->getZExtValue();
1047 if (destSize < srcSize)
1049 } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
1050 // If the destination is an sret parameter then only accesses that are
1051 // outside of the returned struct type can trap.
1052 if (!A->hasStructRetAttr())
1055 const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
1056 uint64_t destSize = TD.getABITypeSize(StructTy);
1058 if (destSize < srcSize)
1064 // Check that src is not accessed except via the call and the memcpy. This
1065 // guarantees that it holds only undefined values when passed in (so the final
1066 // memcpy can be dropped), that it is not read or written between the call and
1067 // the memcpy, and that writing beyond the end of it is undefined.
1068 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
1069 srcAlloca->use_end());
1070 while (!srcUseList.empty()) {
1071 User* UI = srcUseList.back();
1072 srcUseList.pop_back();
1074 if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1075 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
1077 srcUseList.push_back(*I);
1078 } else if (UI != C && UI != cpy) {
1083 // Since we're changing the parameter to the callsite, we need to make sure
1084 // that what would be the new parameter dominates the callsite.
1085 DominatorTree& DT = getAnalysis<DominatorTree>();
1086 if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
1087 if (!DT.dominates(cpyDestInst, C))
1090 // In addition to knowing that the call does not access src in some
1091 // unexpected manner, for example via a global, which we deduce from
1092 // the use analysis, we also need to know that it does not sneakily
1093 // access dest. We rely on AA to figure this out for us.
1094 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1095 if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
1096 AliasAnalysis::NoModRef)
1099 // All the checks have passed, so do the transformation.
1100 for (unsigned i = 0; i < CS.arg_size(); ++i)
1101 if (CS.getArgument(i) == cpySrc) {
1102 if (cpySrc->getType() != cpyDest->getType())
1103 cpyDest = CastInst::createPointerCast(cpyDest, cpySrc->getType(),
1104 cpyDest->getName(), C);
1105 CS.setArgument(i, cpyDest);
1108 // Drop any cached information about the call, because we may have changed
1109 // its dependence information by changing its parameter.
1110 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1111 MD.dropInstruction(C);
1113 // Remove the memcpy
1114 MD.removeInstruction(cpy);
1115 toErase.push_back(cpy);
1120 /// processMemCpy - perform simplication of memcpy's. If we have memcpy A which
1121 /// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1122 /// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1123 /// This allows later passes to remove the first memcpy altogether.
1124 bool GVN::processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
1125 SmallVectorImpl<Instruction*> &toErase) {
1126 // We can only transforms memcpy's where the dest of one is the source of the
1128 if (M->getSource() != MDep->getDest())
1131 // Second, the length of the memcpy's must be the same, or the preceeding one
1132 // must be larger than the following one.
1133 ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1134 ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1138 uint64_t DepSize = C1->getValue().getZExtValue();
1139 uint64_t CpySize = C2->getValue().getZExtValue();
1141 if (DepSize < CpySize)
1144 // Finally, we have to make sure that the dest of the second does not
1145 // alias the source of the first
1146 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1147 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1148 AliasAnalysis::NoAlias)
1150 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1151 AliasAnalysis::NoAlias)
1153 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1154 != AliasAnalysis::NoAlias)
1157 // If all checks passed, then we can transform these memcpy's
1158 Function* MemCpyFun = Intrinsic::getDeclaration(
1159 M->getParent()->getParent()->getParent(),
1160 M->getIntrinsicID());
1162 std::vector<Value*> args;
1163 args.push_back(M->getRawDest());
1164 args.push_back(MDep->getRawSource());
1165 args.push_back(M->getLength());
1166 args.push_back(M->getAlignment());
1168 CallInst* C = new CallInst(MemCpyFun, args.begin(), args.end(), "", M);
1170 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1171 if (MD.getDependency(C) == MDep) {
1172 MD.dropInstruction(M);
1173 toErase.push_back(M);
1177 MD.removeInstruction(C);
1178 toErase.push_back(C);
1182 /// processInstruction - When calculating availability, handle an instruction
1183 /// by inserting it into the appropriate sets
1184 bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1185 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1186 SmallVectorImpl<Instruction*> &toErase) {
1187 if (LoadInst* L = dyn_cast<LoadInst>(I))
1188 return processLoad(L, lastSeenLoad, toErase);
1190 if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
1191 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1193 // The are two possible optimizations we can do for memcpy:
1194 // a) memcpy-memcpy xform which exposes redundance for DSE
1195 // b) call-memcpy xform for return slot optimization
1196 Instruction* dep = MD.getDependency(M);
1197 if (dep == MemoryDependenceAnalysis::None ||
1198 dep == MemoryDependenceAnalysis::NonLocal)
1200 if (MemCpyInst *MemCpy = dyn_cast<MemCpyInst>(dep))
1201 return processMemCpy(M, MemCpy, toErase);
1202 if (CallInst* C = dyn_cast<CallInst>(dep))
1203 return performCallSlotOptzn(M, C, toErase);
1207 unsigned num = VN.lookup_or_add(I);
1209 // Collapse PHI nodes
1210 if (PHINode* p = dyn_cast<PHINode>(I)) {
1211 Value* constVal = CollapsePhi(p);
1214 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1216 if (PI->second.count(p))
1217 PI->second.erase(p);
1219 p->replaceAllUsesWith(constVal);
1220 toErase.push_back(p);
1222 // Perform value-number based elimination
1223 } else if (currAvail.test(num)) {
1224 Value* repl = find_leader(currAvail, num);
1226 if (CallInst* CI = dyn_cast<CallInst>(I)) {
1227 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1228 if (!AA.doesNotAccessMemory(CI)) {
1229 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1230 if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1231 MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1232 // There must be an intervening may-alias store, so nothing from
1233 // this point on will be able to be replaced with the preceding call
1234 currAvail.erase(repl);
1235 currAvail.insert(I);
1243 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1244 MD.removeInstruction(I);
1247 I->replaceAllUsesWith(repl);
1248 toErase.push_back(I);
1250 } else if (!I->isTerminator()) {
1252 currAvail.insert(I);
1258 // GVN::runOnFunction - This is the main transformation entry point for a
1261 bool GVN::runOnFunction(Function& F) {
1262 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1264 bool changed = false;
1265 bool shouldContinue = true;
1267 while (shouldContinue) {
1268 shouldContinue = iterateOnFunction(F);
1269 changed |= shouldContinue;
1276 // GVN::iterateOnFunction - Executes one iteration of GVN
1277 bool GVN::iterateOnFunction(Function &F) {
1278 // Clean out global sets from any previous functions
1280 availableOut.clear();
1283 bool changed_function = false;
1285 DominatorTree &DT = getAnalysis<DominatorTree>();
1287 SmallVector<Instruction*, 4> toErase;
1288 DenseMap<Value*, LoadInst*> lastSeenLoad;
1290 // Top-down walk of the dominator tree
1291 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1292 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1294 // Get the set to update for this block
1295 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1296 lastSeenLoad.clear();
1298 BasicBlock* BB = DI->getBlock();
1300 // A block inherits AVAIL_OUT from its dominator
1301 if (DI->getIDom() != 0)
1302 currAvail = availableOut[DI->getIDom()->getBlock()];
1304 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1306 changed_function |= processInstruction(BI, currAvail,
1307 lastSeenLoad, toErase);
1309 NumGVNInstr += toErase.size();
1311 // Avoid iterator invalidation
1314 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1315 E = toErase.end(); I != E; ++I)
1316 (*I)->eraseFromParent();
1322 return changed_function;