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"
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
43 /// This class holds the mapping between values and value numbers. It is used
44 /// as an efficient mechanism to determine the expression-wise equivalence of
47 struct VISIBILITY_HIDDEN Expression {
48 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
49 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
50 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
51 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
52 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
53 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
54 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
55 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
56 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
57 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
60 ExpressionOpcode opcode;
65 SmallVector<uint32_t, 4> varargs;
69 Expression(ExpressionOpcode o) : opcode(o) { }
71 bool operator==(const Expression &other) const {
72 if (opcode != other.opcode)
74 else if (opcode == EMPTY || opcode == TOMBSTONE)
76 else if (type != other.type)
78 else if (function != other.function)
80 else if (firstVN != other.firstVN)
82 else if (secondVN != other.secondVN)
84 else if (thirdVN != other.thirdVN)
87 if (varargs.size() != other.varargs.size())
90 for (size_t i = 0; i < varargs.size(); ++i)
91 if (varargs[i] != other.varargs[i])
98 bool operator!=(const Expression &other) const {
99 if (opcode != other.opcode)
101 else if (opcode == EMPTY || opcode == TOMBSTONE)
103 else if (type != other.type)
105 else if (function != other.function)
107 else if (firstVN != other.firstVN)
109 else if (secondVN != other.secondVN)
111 else if (thirdVN != other.thirdVN)
114 if (varargs.size() != other.varargs.size())
117 for (size_t i = 0; i < varargs.size(); ++i)
118 if (varargs[i] != other.varargs[i])
126 class VISIBILITY_HIDDEN ValueTable {
128 DenseMap<Value*, uint32_t> valueNumbering;
129 DenseMap<Expression, uint32_t> expressionNumbering;
132 uint32_t nextValueNumber;
134 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
135 Expression::ExpressionOpcode getOpcode(CmpInst* C);
136 Expression::ExpressionOpcode getOpcode(CastInst* C);
137 Expression create_expression(BinaryOperator* BO);
138 Expression create_expression(CmpInst* C);
139 Expression create_expression(ShuffleVectorInst* V);
140 Expression create_expression(ExtractElementInst* C);
141 Expression create_expression(InsertElementInst* V);
142 Expression create_expression(SelectInst* V);
143 Expression create_expression(CastInst* C);
144 Expression create_expression(GetElementPtrInst* G);
145 Expression create_expression(CallInst* C);
147 ValueTable() : nextValueNumber(1) { }
148 uint32_t lookup_or_add(Value* V);
149 uint32_t lookup(Value* V) const;
150 void add(Value* V, uint32_t num);
152 void erase(Value* v);
154 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
155 uint32_t hash_operand(Value* v);
160 template <> struct DenseMapInfo<Expression> {
161 static inline Expression getEmptyKey() {
162 return Expression(Expression::EMPTY);
165 static inline Expression getTombstoneKey() {
166 return Expression(Expression::TOMBSTONE);
169 static unsigned getHashValue(const Expression e) {
170 unsigned hash = e.opcode;
172 hash = e.firstVN + hash * 37;
173 hash = e.secondVN + hash * 37;
174 hash = e.thirdVN + hash * 37;
176 hash = (unsigned)((uintptr_t)e.type >> 4) ^
177 (unsigned)((uintptr_t)e.type >> 9) +
180 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
181 E = e.varargs.end(); I != E; ++I)
182 hash = *I + hash * 37;
184 hash = (unsigned)((uintptr_t)e.function >> 4) ^
185 (unsigned)((uintptr_t)e.function >> 9) +
190 static bool isEqual(const Expression &LHS, const Expression &RHS) {
193 static bool isPod() { return true; }
197 //===----------------------------------------------------------------------===//
198 // ValueTable Internal Functions
199 //===----------------------------------------------------------------------===//
200 Expression::ExpressionOpcode
201 ValueTable::getOpcode(BinaryOperator* BO) {
202 switch(BO->getOpcode()) {
203 case Instruction::Add:
204 return Expression::ADD;
205 case Instruction::Sub:
206 return Expression::SUB;
207 case Instruction::Mul:
208 return Expression::MUL;
209 case Instruction::UDiv:
210 return Expression::UDIV;
211 case Instruction::SDiv:
212 return Expression::SDIV;
213 case Instruction::FDiv:
214 return Expression::FDIV;
215 case Instruction::URem:
216 return Expression::UREM;
217 case Instruction::SRem:
218 return Expression::SREM;
219 case Instruction::FRem:
220 return Expression::FREM;
221 case Instruction::Shl:
222 return Expression::SHL;
223 case Instruction::LShr:
224 return Expression::LSHR;
225 case Instruction::AShr:
226 return Expression::ASHR;
227 case Instruction::And:
228 return Expression::AND;
229 case Instruction::Or:
230 return Expression::OR;
231 case Instruction::Xor:
232 return Expression::XOR;
234 // THIS SHOULD NEVER HAPPEN
236 assert(0 && "Binary operator with unknown opcode?");
237 return Expression::ADD;
241 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
242 if (C->getOpcode() == Instruction::ICmp) {
243 switch (C->getPredicate()) {
244 case ICmpInst::ICMP_EQ:
245 return Expression::ICMPEQ;
246 case ICmpInst::ICMP_NE:
247 return Expression::ICMPNE;
248 case ICmpInst::ICMP_UGT:
249 return Expression::ICMPUGT;
250 case ICmpInst::ICMP_UGE:
251 return Expression::ICMPUGE;
252 case ICmpInst::ICMP_ULT:
253 return Expression::ICMPULT;
254 case ICmpInst::ICMP_ULE:
255 return Expression::ICMPULE;
256 case ICmpInst::ICMP_SGT:
257 return Expression::ICMPSGT;
258 case ICmpInst::ICMP_SGE:
259 return Expression::ICMPSGE;
260 case ICmpInst::ICMP_SLT:
261 return Expression::ICMPSLT;
262 case ICmpInst::ICMP_SLE:
263 return Expression::ICMPSLE;
265 // THIS SHOULD NEVER HAPPEN
267 assert(0 && "Comparison with unknown predicate?");
268 return Expression::ICMPEQ;
271 switch (C->getPredicate()) {
272 case FCmpInst::FCMP_OEQ:
273 return Expression::FCMPOEQ;
274 case FCmpInst::FCMP_OGT:
275 return Expression::FCMPOGT;
276 case FCmpInst::FCMP_OGE:
277 return Expression::FCMPOGE;
278 case FCmpInst::FCMP_OLT:
279 return Expression::FCMPOLT;
280 case FCmpInst::FCMP_OLE:
281 return Expression::FCMPOLE;
282 case FCmpInst::FCMP_ONE:
283 return Expression::FCMPONE;
284 case FCmpInst::FCMP_ORD:
285 return Expression::FCMPORD;
286 case FCmpInst::FCMP_UNO:
287 return Expression::FCMPUNO;
288 case FCmpInst::FCMP_UEQ:
289 return Expression::FCMPUEQ;
290 case FCmpInst::FCMP_UGT:
291 return Expression::FCMPUGT;
292 case FCmpInst::FCMP_UGE:
293 return Expression::FCMPUGE;
294 case FCmpInst::FCMP_ULT:
295 return Expression::FCMPULT;
296 case FCmpInst::FCMP_ULE:
297 return Expression::FCMPULE;
298 case FCmpInst::FCMP_UNE:
299 return Expression::FCMPUNE;
301 // THIS SHOULD NEVER HAPPEN
303 assert(0 && "Comparison with unknown predicate?");
304 return Expression::FCMPOEQ;
309 Expression::ExpressionOpcode
310 ValueTable::getOpcode(CastInst* C) {
311 switch(C->getOpcode()) {
312 case Instruction::Trunc:
313 return Expression::TRUNC;
314 case Instruction::ZExt:
315 return Expression::ZEXT;
316 case Instruction::SExt:
317 return Expression::SEXT;
318 case Instruction::FPToUI:
319 return Expression::FPTOUI;
320 case Instruction::FPToSI:
321 return Expression::FPTOSI;
322 case Instruction::UIToFP:
323 return Expression::UITOFP;
324 case Instruction::SIToFP:
325 return Expression::SITOFP;
326 case Instruction::FPTrunc:
327 return Expression::FPTRUNC;
328 case Instruction::FPExt:
329 return Expression::FPEXT;
330 case Instruction::PtrToInt:
331 return Expression::PTRTOINT;
332 case Instruction::IntToPtr:
333 return Expression::INTTOPTR;
334 case Instruction::BitCast:
335 return Expression::BITCAST;
337 // THIS SHOULD NEVER HAPPEN
339 assert(0 && "Cast operator with unknown opcode?");
340 return Expression::BITCAST;
344 uint32_t ValueTable::hash_operand(Value* v) {
345 if (CallInst* CI = dyn_cast<CallInst>(v))
346 if (!AA->doesNotAccessMemory(CI))
347 return nextValueNumber++;
349 return lookup_or_add(v);
352 Expression ValueTable::create_expression(CallInst* C) {
355 e.type = C->getType();
359 e.function = C->getCalledFunction();
360 e.opcode = Expression::CALL;
362 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
364 e.varargs.push_back(hash_operand(*I));
369 Expression ValueTable::create_expression(BinaryOperator* BO) {
372 e.firstVN = hash_operand(BO->getOperand(0));
373 e.secondVN = hash_operand(BO->getOperand(1));
376 e.type = BO->getType();
377 e.opcode = getOpcode(BO);
382 Expression ValueTable::create_expression(CmpInst* C) {
385 e.firstVN = hash_operand(C->getOperand(0));
386 e.secondVN = hash_operand(C->getOperand(1));
389 e.type = C->getType();
390 e.opcode = getOpcode(C);
395 Expression ValueTable::create_expression(CastInst* C) {
398 e.firstVN = hash_operand(C->getOperand(0));
402 e.type = C->getType();
403 e.opcode = getOpcode(C);
408 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
411 e.firstVN = hash_operand(S->getOperand(0));
412 e.secondVN = hash_operand(S->getOperand(1));
413 e.thirdVN = hash_operand(S->getOperand(2));
415 e.type = S->getType();
416 e.opcode = Expression::SHUFFLE;
421 Expression ValueTable::create_expression(ExtractElementInst* E) {
424 e.firstVN = hash_operand(E->getOperand(0));
425 e.secondVN = hash_operand(E->getOperand(1));
428 e.type = E->getType();
429 e.opcode = Expression::EXTRACT;
434 Expression ValueTable::create_expression(InsertElementInst* I) {
437 e.firstVN = hash_operand(I->getOperand(0));
438 e.secondVN = hash_operand(I->getOperand(1));
439 e.thirdVN = hash_operand(I->getOperand(2));
441 e.type = I->getType();
442 e.opcode = Expression::INSERT;
447 Expression ValueTable::create_expression(SelectInst* I) {
450 e.firstVN = hash_operand(I->getCondition());
451 e.secondVN = hash_operand(I->getTrueValue());
452 e.thirdVN = hash_operand(I->getFalseValue());
454 e.type = I->getType();
455 e.opcode = Expression::SELECT;
460 Expression ValueTable::create_expression(GetElementPtrInst* G) {
463 e.firstVN = hash_operand(G->getPointerOperand());
467 e.type = G->getType();
468 e.opcode = Expression::GEP;
470 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
472 e.varargs.push_back(hash_operand(*I));
477 //===----------------------------------------------------------------------===//
478 // ValueTable External Functions
479 //===----------------------------------------------------------------------===//
481 /// lookup_or_add - Returns the value number for the specified value, assigning
482 /// it a new number if it did not have one before.
483 uint32_t ValueTable::lookup_or_add(Value* V) {
484 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
485 if (VI != valueNumbering.end())
488 if (CallInst* C = dyn_cast<CallInst>(V)) {
489 if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
490 Expression e = create_expression(C);
492 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
493 if (EI != expressionNumbering.end()) {
494 valueNumbering.insert(std::make_pair(V, EI->second));
497 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
498 valueNumbering.insert(std::make_pair(V, nextValueNumber));
500 return nextValueNumber++;
503 valueNumbering.insert(std::make_pair(V, nextValueNumber));
504 return nextValueNumber++;
506 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
507 Expression e = create_expression(BO);
509 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
510 if (EI != expressionNumbering.end()) {
511 valueNumbering.insert(std::make_pair(V, EI->second));
514 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
515 valueNumbering.insert(std::make_pair(V, nextValueNumber));
517 return nextValueNumber++;
519 } else if (CmpInst* C = dyn_cast<CmpInst>(V)) {
520 Expression e = create_expression(C);
522 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
523 if (EI != expressionNumbering.end()) {
524 valueNumbering.insert(std::make_pair(V, EI->second));
527 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
528 valueNumbering.insert(std::make_pair(V, nextValueNumber));
530 return nextValueNumber++;
532 } else if (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(V)) {
533 Expression e = create_expression(U);
535 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
536 if (EI != expressionNumbering.end()) {
537 valueNumbering.insert(std::make_pair(V, EI->second));
540 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
541 valueNumbering.insert(std::make_pair(V, nextValueNumber));
543 return nextValueNumber++;
545 } else if (ExtractElementInst* U = dyn_cast<ExtractElementInst>(V)) {
546 Expression e = create_expression(U);
548 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
549 if (EI != expressionNumbering.end()) {
550 valueNumbering.insert(std::make_pair(V, EI->second));
553 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
554 valueNumbering.insert(std::make_pair(V, nextValueNumber));
556 return nextValueNumber++;
558 } else if (InsertElementInst* U = dyn_cast<InsertElementInst>(V)) {
559 Expression e = create_expression(U);
561 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
562 if (EI != expressionNumbering.end()) {
563 valueNumbering.insert(std::make_pair(V, EI->second));
566 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
567 valueNumbering.insert(std::make_pair(V, nextValueNumber));
569 return nextValueNumber++;
571 } else if (SelectInst* U = dyn_cast<SelectInst>(V)) {
572 Expression e = create_expression(U);
574 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
575 if (EI != expressionNumbering.end()) {
576 valueNumbering.insert(std::make_pair(V, EI->second));
579 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
580 valueNumbering.insert(std::make_pair(V, nextValueNumber));
582 return nextValueNumber++;
584 } else if (CastInst* U = dyn_cast<CastInst>(V)) {
585 Expression e = create_expression(U);
587 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
588 if (EI != expressionNumbering.end()) {
589 valueNumbering.insert(std::make_pair(V, EI->second));
592 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
593 valueNumbering.insert(std::make_pair(V, nextValueNumber));
595 return nextValueNumber++;
597 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
598 Expression e = create_expression(U);
600 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
601 if (EI != expressionNumbering.end()) {
602 valueNumbering.insert(std::make_pair(V, EI->second));
605 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
606 valueNumbering.insert(std::make_pair(V, nextValueNumber));
608 return nextValueNumber++;
611 valueNumbering.insert(std::make_pair(V, nextValueNumber));
612 return nextValueNumber++;
616 /// lookup - Returns the value number of the specified value. Fails if
617 /// the value has not yet been numbered.
618 uint32_t ValueTable::lookup(Value* V) const {
619 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
620 if (VI != valueNumbering.end())
623 assert(0 && "Value not numbered?");
628 /// clear - Remove all entries from the ValueTable
629 void ValueTable::clear() {
630 valueNumbering.clear();
631 expressionNumbering.clear();
635 /// erase - Remove a value from the value numbering
636 void ValueTable::erase(Value* V) {
637 valueNumbering.erase(V);
640 //===----------------------------------------------------------------------===//
641 // ValueNumberedSet Class
642 //===----------------------------------------------------------------------===//
644 class ValueNumberedSet {
646 SmallPtrSet<Value*, 8> contents;
649 ValueNumberedSet() { numbers.resize(1); }
650 ValueNumberedSet(const ValueNumberedSet& other) {
651 numbers = other.numbers;
652 contents = other.contents;
655 typedef SmallPtrSet<Value*, 8>::iterator iterator;
657 iterator begin() { return contents.begin(); }
658 iterator end() { return contents.end(); }
660 bool insert(Value* v) { return contents.insert(v); }
661 void insert(iterator I, iterator E) { contents.insert(I, E); }
662 void erase(Value* v) { contents.erase(v); }
663 unsigned count(Value* v) { return contents.count(v); }
664 size_t size() { return contents.size(); }
666 void set(unsigned i) {
667 if (i >= numbers.size())
673 void operator=(const ValueNumberedSet& other) {
674 contents = other.contents;
675 numbers = other.numbers;
678 void reset(unsigned i) {
679 if (i < numbers.size())
683 bool test(unsigned i) {
684 if (i >= numbers.size())
687 return numbers.test(i);
697 //===----------------------------------------------------------------------===//
699 //===----------------------------------------------------------------------===//
703 class VISIBILITY_HIDDEN GVN : public FunctionPass {
704 bool runOnFunction(Function &F);
706 static char ID; // Pass identification, replacement for typeid
707 GVN() : FunctionPass((intptr_t)&ID) { }
712 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
714 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
718 // This transformation requires dominator postdominator info
719 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
720 AU.setPreservesCFG();
721 AU.addRequired<DominatorTree>();
722 AU.addRequired<MemoryDependenceAnalysis>();
723 AU.addRequired<AliasAnalysis>();
724 AU.addPreserved<AliasAnalysis>();
725 AU.addPreserved<MemoryDependenceAnalysis>();
729 // FIXME: eliminate or document these better
730 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
731 void val_insert(ValueNumberedSet& s, Value* v);
732 bool processLoad(LoadInst* L,
733 DenseMap<Value*, LoadInst*>& lastLoad,
734 SmallVector<Instruction*, 4>& toErase);
735 bool processInstruction(Instruction* I,
736 ValueNumberedSet& currAvail,
737 DenseMap<Value*, LoadInst*>& lastSeenLoad,
738 SmallVector<Instruction*, 4>& toErase);
739 bool processNonLocalLoad(LoadInst* L,
740 SmallVector<Instruction*, 4>& toErase);
741 bool processMemCpy(MemCpyInst* M, SmallVector<Instruction*, 4>& toErase);
742 bool performReturnSlotOptzn(MemCpyInst* cpy, CallInst* C,
743 SmallVector<Instruction*, 4>& toErase);
744 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
745 DenseMap<BasicBlock*, Value*> &Phis,
746 bool top_level = false);
747 void dump(DenseMap<BasicBlock*, Value*>& d);
748 bool iterateOnFunction(Function &F);
749 Value* CollapsePhi(PHINode* p);
750 bool isSafeReplacement(PHINode* p, Instruction* inst);
757 // createGVNPass - The public interface to this file...
758 FunctionPass *llvm::createGVNPass() { return new GVN(); }
760 static RegisterPass<GVN> X("gvn",
761 "Global Value Numbering");
763 STATISTIC(NumGVNInstr, "Number of instructions deleted");
764 STATISTIC(NumGVNLoad, "Number of loads deleted");
766 /// find_leader - Given a set and a value number, return the first
767 /// element of the set with that value number, or 0 if no such element
769 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
773 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
775 if (v == VN.lookup(*I))
778 assert(0 && "No leader found, but present bit is set?");
782 /// val_insert - Insert a value into a set only if there is not a value
783 /// with the same value number already in the set
784 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
785 uint32_t num = VN.lookup(v);
790 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
792 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
793 E = d.end(); I != E; ++I) {
794 if (I->second == MemoryDependenceAnalysis::None)
802 Value* GVN::CollapsePhi(PHINode* p) {
803 DominatorTree &DT = getAnalysis<DominatorTree>();
804 Value* constVal = p->hasConstantValue();
807 if (Instruction* inst = dyn_cast<Instruction>(constVal)) {
808 if (DT.dominates(inst, p))
809 if (isSafeReplacement(p, inst))
819 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
820 if (!isa<PHINode>(inst))
823 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
825 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
826 if (use_phi->getParent() == inst->getParent())
832 /// GetValueForBlock - Get the value to use within the specified basic block.
833 /// available values are in Phis.
834 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
835 DenseMap<BasicBlock*, Value*> &Phis,
838 // If we have already computed this value, return the previously computed val.
839 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
840 if (V != Phis.end() && !top_level) return V->second;
842 BasicBlock* singlePred = BB->getSinglePredecessor();
844 Value *ret = GetValueForBlock(singlePred, orig, Phis);
848 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
849 // now, then get values to fill in the incoming values for the PHI.
850 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
852 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
854 if (Phis.count(BB) == 0)
855 Phis.insert(std::make_pair(BB, PN));
857 // Fill in the incoming values for the block.
858 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
859 Value* val = GetValueForBlock(*PI, orig, Phis);
861 PN->addIncoming(val, *PI);
863 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
864 AA.copyValue(orig, PN);
866 // Attempt to collapse PHI nodes that are trivially redundant
867 Value* v = CollapsePhi(PN);
869 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
871 MD.removeInstruction(PN);
872 PN->replaceAllUsesWith(v);
874 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
875 E = Phis.end(); I != E; ++I)
879 PN->eraseFromParent();
886 // Cache our phi construction results
887 phiMap[orig->getPointerOperand()].insert(PN);
891 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
892 /// non-local by performing PHI construction.
893 bool GVN::processNonLocalLoad(LoadInst* L,
894 SmallVector<Instruction*, 4>& toErase) {
895 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
897 // Find the non-local dependencies of the load
898 DenseMap<BasicBlock*, Value*> deps;
899 MD.getNonLocalDependency(L, deps);
901 DenseMap<BasicBlock*, Value*> repl;
903 // Filter out useless results (non-locals, etc)
904 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
906 if (I->second == MemoryDependenceAnalysis::None) {
908 } else if (I->second == MemoryDependenceAnalysis::NonLocal) {
910 } else if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
911 if (S->getPointerOperand() == L->getPointerOperand())
912 repl[I->first] = S->getOperand(0);
915 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
916 if (LD->getPointerOperand() == L->getPointerOperand())
924 // Use cached PHI construction information from previous runs
925 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
926 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
928 if ((*I)->getParent() == L->getParent()) {
929 MD.removeInstruction(L);
930 L->replaceAllUsesWith(*I);
931 toErase.push_back(L);
936 repl.insert(std::make_pair((*I)->getParent(), *I));
940 // Perform PHI construction
941 SmallPtrSet<BasicBlock*, 4> visited;
942 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
944 MD.removeInstruction(L);
945 L->replaceAllUsesWith(v);
946 toErase.push_back(L);
952 /// processLoad - Attempt to eliminate a load, first by eliminating it
953 /// locally, and then attempting non-local elimination if that fails.
954 bool GVN::processLoad(LoadInst* L,
955 DenseMap<Value*, LoadInst*>& lastLoad,
956 SmallVector<Instruction*, 4>& toErase) {
957 if (L->isVolatile()) {
958 lastLoad[L->getPointerOperand()] = L;
962 Value* pointer = L->getPointerOperand();
963 LoadInst*& last = lastLoad[pointer];
965 // ... to a pointer that has been loaded from before...
966 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
967 bool removedNonLocal = false;
968 Instruction* dep = MD.getDependency(L);
969 if (dep == MemoryDependenceAnalysis::NonLocal &&
970 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
971 removedNonLocal = processNonLocalLoad(L, toErase);
973 if (!removedNonLocal)
976 return removedNonLocal;
980 bool deletedLoad = false;
982 // Walk up the dependency chain until we either find
983 // a dependency we can use, or we can't walk any further
984 while (dep != MemoryDependenceAnalysis::None &&
985 dep != MemoryDependenceAnalysis::NonLocal &&
986 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
987 // ... that depends on a store ...
988 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
989 if (S->getPointerOperand() == pointer) {
991 MD.removeInstruction(L);
993 L->replaceAllUsesWith(S->getOperand(0));
994 toErase.push_back(L);
999 // Whether we removed it or not, we can't
1003 // If we don't depend on a store, and we haven't
1004 // been loaded before, bail.
1006 } else if (dep == last) {
1008 MD.removeInstruction(L);
1010 L->replaceAllUsesWith(last);
1011 toErase.push_back(L);
1017 dep = MD.getDependency(L, dep);
1021 if (dep != MemoryDependenceAnalysis::None &&
1022 dep != MemoryDependenceAnalysis::NonLocal &&
1023 isa<AllocationInst>(dep)) {
1024 // Check that this load is actually from the
1025 // allocation we found
1026 Value* v = L->getOperand(0);
1028 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
1029 v = BC->getOperand(0);
1030 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
1031 v = GEP->getOperand(0);
1036 // If this load depends directly on an allocation, there isn't
1037 // anything stored there; therefore, we can optimize this load
1039 MD.removeInstruction(L);
1041 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1042 toErase.push_back(L);
1054 /// performReturnSlotOptzn - takes a memcpy and a call that it depends on,
1055 /// and checks for the possibility of a return slot optimization by having
1056 /// the call write its result directly into the callees return parameter
1057 /// rather than using memcpy
1058 bool GVN::performReturnSlotOptzn(MemCpyInst* cpy, CallInst* C,
1059 SmallVector<Instruction*, 4>& toErase) {
1060 // Check that we're copying to an argument...
1061 Value* cpyDest = cpy->getDest();
1062 if (!isa<Argument>(cpyDest))
1065 // And that the argument is the return slot
1066 Argument* sretArg = cast<Argument>(cpyDest);
1067 if (!sretArg->hasStructRetAttr())
1070 // Make sure the return slot is otherwise dead
1071 std::set<User*> useList(sretArg->use_begin(), sretArg->use_end());
1072 while (!useList.empty()) {
1073 User* UI = *useList.begin();
1075 if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1076 useList.insert(UI->use_begin(), UI->use_end());
1078 } else if (UI == cpy)
1084 // Make sure the call cannot modify the return slot in some unpredicted way
1085 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1086 if (AA.getModRefInfo(C, cpy->getRawDest(), ~0UL) != AliasAnalysis::NoModRef)
1089 // If all checks passed, then we can perform the transformation
1090 CallSite CS = CallSite::get(C);
1091 for (unsigned i = 0; i < CS.arg_size(); ++i) {
1092 if (CS.paramHasAttr(i+1, ParamAttr::StructRet)) {
1093 if (CS.getArgument(i)->getType() != cpyDest->getType())
1096 CS.setArgument(i, cpyDest);
1101 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1102 MD.dropInstruction(C);
1104 // Remove the memcpy
1105 toErase.push_back(cpy);
1110 /// processMemCpy - perform simplication of memcpy's. If we have memcpy A which
1111 /// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1112 /// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1113 /// This allows later passes to remove the first memcpy altogether.
1114 bool GVN::processMemCpy(MemCpyInst* M,
1115 SmallVector<Instruction*, 4>& toErase) {
1116 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1118 // First, we have to check that the dependency is another memcpy
1119 Instruction* dep = MD.getDependency(M);
1120 if (dep == MemoryDependenceAnalysis::None ||
1121 dep == MemoryDependenceAnalysis::NonLocal)
1123 else if (CallInst* C = dyn_cast<CallInst>(dep))
1124 if (!isa<MemCpyInst>(C))
1125 return performReturnSlotOptzn(M, C, toErase);
1126 else if (!isa<MemCpyInst>(dep))
1129 // We can only transforms memcpy's where the dest of one is the source of the
1131 MemCpyInst* MDep = cast<MemCpyInst>(dep);
1132 if (M->getSource() != MDep->getDest())
1135 // Second, the length of the memcpy's must be the same, or the preceeding one
1136 // must be larger than the following one.
1137 ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1138 ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1142 uint64_t CpySize = C1->getValue().getZExtValue();
1143 uint64_t DepSize = C2->getValue().getZExtValue();
1145 if (DepSize < CpySize)
1148 // Finally, we have to make sure that the dest of the second does not
1149 // alias the source of the first
1150 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1151 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1152 AliasAnalysis::NoAlias)
1154 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1155 AliasAnalysis::NoAlias)
1157 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1158 != AliasAnalysis::NoAlias)
1161 // If all checks passed, then we can transform these memcpy's
1162 bool is32bit = M->getIntrinsicID() == Intrinsic::memcpy_i32;
1163 Function* MemMoveFun = Intrinsic::getDeclaration(
1164 M->getParent()->getParent()->getParent(),
1165 is32bit ? Intrinsic::memcpy_i32 :
1166 Intrinsic::memcpy_i64);
1168 std::vector<Value*> args;
1169 args.push_back(M->getRawDest());
1170 args.push_back(MDep->getRawSource());
1171 args.push_back(M->getLength());
1172 args.push_back(M->getAlignment());
1174 CallInst* C = new CallInst(MemMoveFun, args.begin(), args.end(), "", M);
1176 if (MD.getDependency(C) == MDep) {
1177 MD.dropInstruction(M);
1178 toErase.push_back(M);
1181 MD.removeInstruction(C);
1182 toErase.push_back(C);
1187 /// processInstruction - When calculating availability, handle an instruction
1188 /// by inserting it into the appropriate sets
1189 bool GVN::processInstruction(Instruction* I,
1190 ValueNumberedSet& currAvail,
1191 DenseMap<Value*, LoadInst*>& lastSeenLoad,
1192 SmallVector<Instruction*, 4>& toErase) {
1193 if (LoadInst* L = dyn_cast<LoadInst>(I)) {
1194 return processLoad(L, lastSeenLoad, toErase);
1195 } else if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
1196 return processMemCpy(M, toErase);
1199 unsigned num = VN.lookup_or_add(I);
1201 // Collapse PHI nodes
1202 if (PHINode* p = dyn_cast<PHINode>(I)) {
1203 Value* constVal = CollapsePhi(p);
1206 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1208 if (PI->second.count(p))
1209 PI->second.erase(p);
1211 p->replaceAllUsesWith(constVal);
1212 toErase.push_back(p);
1214 // Perform value-number based elimination
1215 } else if (currAvail.test(num)) {
1216 Value* repl = find_leader(currAvail, num);
1218 if (CallInst* CI = dyn_cast<CallInst>(I)) {
1219 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1220 if (!AA.doesNotAccessMemory(CI)) {
1221 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1222 if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1223 MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1224 // There must be an intervening may-alias store, so nothing from
1225 // this point on will be able to be replaced with the preceding call
1226 currAvail.erase(repl);
1227 currAvail.insert(I);
1235 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1236 MD.removeInstruction(I);
1239 I->replaceAllUsesWith(repl);
1240 toErase.push_back(I);
1242 } else if (!I->isTerminator()) {
1244 currAvail.insert(I);
1250 // GVN::runOnFunction - This is the main transformation entry point for a
1253 bool GVN::runOnFunction(Function& F) {
1254 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1256 bool changed = false;
1257 bool shouldContinue = true;
1259 while (shouldContinue) {
1260 shouldContinue = iterateOnFunction(F);
1261 changed |= shouldContinue;
1268 // GVN::iterateOnFunction - Executes one iteration of GVN
1269 bool GVN::iterateOnFunction(Function &F) {
1270 // Clean out global sets from any previous functions
1272 availableOut.clear();
1275 bool changed_function = false;
1277 DominatorTree &DT = getAnalysis<DominatorTree>();
1279 SmallVector<Instruction*, 4> toErase;
1281 // Top-down walk of the dominator tree
1282 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1283 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1285 // Get the set to update for this block
1286 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1287 DenseMap<Value*, LoadInst*> lastSeenLoad;
1289 BasicBlock* BB = DI->getBlock();
1291 // A block inherits AVAIL_OUT from its dominator
1292 if (DI->getIDom() != 0)
1293 currAvail = availableOut[DI->getIDom()->getBlock()];
1295 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1297 changed_function |= processInstruction(BI, currAvail,
1298 lastSeenLoad, toErase);
1300 NumGVNInstr += toErase.size();
1302 // Avoid iterator invalidation
1305 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1306 E = toErase.end(); I != E; ++I) {
1307 (*I)->eraseFromParent();
1314 return changed_function;