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"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/BasicBlock.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/ParameterAttributes.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/CommandLine.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Target/TargetData.h"
42 STATISTIC(NumGVNInstr, "Number of instructions deleted");
43 STATISTIC(NumGVNLoad, "Number of loads deleted");
44 STATISTIC(NumMemSetInfer, "Number of memsets inferred");
48 FormMemSet("form-memset-from-stores",
49 cl::desc("Transform straight-line stores to memsets"),
50 cl::init(false), cl::Hidden);
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
57 /// This class holds the mapping between values and value numbers. It is used
58 /// as an efficient mechanism to determine the expression-wise equivalence of
61 struct VISIBILITY_HIDDEN Expression {
62 enum ExpressionOpcode { ADD, SUB, MUL, UDIV, SDIV, FDIV, UREM, SREM,
63 FREM, SHL, LSHR, ASHR, AND, OR, XOR, ICMPEQ,
64 ICMPNE, ICMPUGT, ICMPUGE, ICMPULT, ICMPULE,
65 ICMPSGT, ICMPSGE, ICMPSLT, ICMPSLE, FCMPOEQ,
66 FCMPOGT, FCMPOGE, FCMPOLT, FCMPOLE, FCMPONE,
67 FCMPORD, FCMPUNO, FCMPUEQ, FCMPUGT, FCMPUGE,
68 FCMPULT, FCMPULE, FCMPUNE, EXTRACT, INSERT,
69 SHUFFLE, SELECT, TRUNC, ZEXT, SEXT, FPTOUI,
70 FPTOSI, UITOFP, SITOFP, FPTRUNC, FPEXT,
71 PTRTOINT, INTTOPTR, BITCAST, GEP, CALL, EMPTY,
74 ExpressionOpcode opcode;
79 SmallVector<uint32_t, 4> varargs;
83 Expression(ExpressionOpcode o) : opcode(o) { }
85 bool operator==(const Expression &other) const {
86 if (opcode != other.opcode)
88 else if (opcode == EMPTY || opcode == TOMBSTONE)
90 else if (type != other.type)
92 else if (function != other.function)
94 else if (firstVN != other.firstVN)
96 else if (secondVN != other.secondVN)
98 else if (thirdVN != other.thirdVN)
101 if (varargs.size() != other.varargs.size())
104 for (size_t i = 0; i < varargs.size(); ++i)
105 if (varargs[i] != other.varargs[i])
112 bool operator!=(const Expression &other) const {
113 if (opcode != other.opcode)
115 else if (opcode == EMPTY || opcode == TOMBSTONE)
117 else if (type != other.type)
119 else if (function != other.function)
121 else if (firstVN != other.firstVN)
123 else if (secondVN != other.secondVN)
125 else if (thirdVN != other.thirdVN)
128 if (varargs.size() != other.varargs.size())
131 for (size_t i = 0; i < varargs.size(); ++i)
132 if (varargs[i] != other.varargs[i])
140 class VISIBILITY_HIDDEN ValueTable {
142 DenseMap<Value*, uint32_t> valueNumbering;
143 DenseMap<Expression, uint32_t> expressionNumbering;
146 uint32_t nextValueNumber;
148 Expression::ExpressionOpcode getOpcode(BinaryOperator* BO);
149 Expression::ExpressionOpcode getOpcode(CmpInst* C);
150 Expression::ExpressionOpcode getOpcode(CastInst* C);
151 Expression create_expression(BinaryOperator* BO);
152 Expression create_expression(CmpInst* C);
153 Expression create_expression(ShuffleVectorInst* V);
154 Expression create_expression(ExtractElementInst* C);
155 Expression create_expression(InsertElementInst* V);
156 Expression create_expression(SelectInst* V);
157 Expression create_expression(CastInst* C);
158 Expression create_expression(GetElementPtrInst* G);
159 Expression create_expression(CallInst* C);
161 ValueTable() : nextValueNumber(1) { }
162 uint32_t lookup_or_add(Value* V);
163 uint32_t lookup(Value* V) const;
164 void add(Value* V, uint32_t num);
166 void erase(Value* v);
168 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
169 uint32_t hash_operand(Value* v);
174 template <> struct DenseMapInfo<Expression> {
175 static inline Expression getEmptyKey() {
176 return Expression(Expression::EMPTY);
179 static inline Expression getTombstoneKey() {
180 return Expression(Expression::TOMBSTONE);
183 static unsigned getHashValue(const Expression e) {
184 unsigned hash = e.opcode;
186 hash = e.firstVN + hash * 37;
187 hash = e.secondVN + hash * 37;
188 hash = e.thirdVN + hash * 37;
190 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
191 (unsigned)((uintptr_t)e.type >> 9)) +
194 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
195 E = e.varargs.end(); I != E; ++I)
196 hash = *I + hash * 37;
198 hash = ((unsigned)((uintptr_t)e.function >> 4) ^
199 (unsigned)((uintptr_t)e.function >> 9)) +
204 static bool isEqual(const Expression &LHS, const Expression &RHS) {
207 static bool isPod() { return true; }
211 //===----------------------------------------------------------------------===//
212 // ValueTable Internal Functions
213 //===----------------------------------------------------------------------===//
214 Expression::ExpressionOpcode ValueTable::getOpcode(BinaryOperator* BO) {
215 switch(BO->getOpcode()) {
216 default: // THIS SHOULD NEVER HAPPEN
217 assert(0 && "Binary operator with unknown opcode?");
218 case Instruction::Add: return Expression::ADD;
219 case Instruction::Sub: return Expression::SUB;
220 case Instruction::Mul: return Expression::MUL;
221 case Instruction::UDiv: return Expression::UDIV;
222 case Instruction::SDiv: return Expression::SDIV;
223 case Instruction::FDiv: return Expression::FDIV;
224 case Instruction::URem: return Expression::UREM;
225 case Instruction::SRem: return Expression::SREM;
226 case Instruction::FRem: return Expression::FREM;
227 case Instruction::Shl: return Expression::SHL;
228 case Instruction::LShr: return Expression::LSHR;
229 case Instruction::AShr: return Expression::ASHR;
230 case Instruction::And: return Expression::AND;
231 case Instruction::Or: return Expression::OR;
232 case Instruction::Xor: return Expression::XOR;
236 Expression::ExpressionOpcode ValueTable::getOpcode(CmpInst* C) {
237 if (isa<ICmpInst>(C)) {
238 switch (C->getPredicate()) {
239 default: // THIS SHOULD NEVER HAPPEN
240 assert(0 && "Comparison with unknown predicate?");
241 case ICmpInst::ICMP_EQ: return Expression::ICMPEQ;
242 case ICmpInst::ICMP_NE: return Expression::ICMPNE;
243 case ICmpInst::ICMP_UGT: return Expression::ICMPUGT;
244 case ICmpInst::ICMP_UGE: return Expression::ICMPUGE;
245 case ICmpInst::ICMP_ULT: return Expression::ICMPULT;
246 case ICmpInst::ICMP_ULE: return Expression::ICMPULE;
247 case ICmpInst::ICMP_SGT: return Expression::ICMPSGT;
248 case ICmpInst::ICMP_SGE: return Expression::ICMPSGE;
249 case ICmpInst::ICMP_SLT: return Expression::ICMPSLT;
250 case ICmpInst::ICMP_SLE: return Expression::ICMPSLE;
253 assert(isa<FCmpInst>(C) && "Unknown compare");
254 switch (C->getPredicate()) {
255 default: // THIS SHOULD NEVER HAPPEN
256 assert(0 && "Comparison with unknown predicate?");
257 case FCmpInst::FCMP_OEQ: return Expression::FCMPOEQ;
258 case FCmpInst::FCMP_OGT: return Expression::FCMPOGT;
259 case FCmpInst::FCMP_OGE: return Expression::FCMPOGE;
260 case FCmpInst::FCMP_OLT: return Expression::FCMPOLT;
261 case FCmpInst::FCMP_OLE: return Expression::FCMPOLE;
262 case FCmpInst::FCMP_ONE: return Expression::FCMPONE;
263 case FCmpInst::FCMP_ORD: return Expression::FCMPORD;
264 case FCmpInst::FCMP_UNO: return Expression::FCMPUNO;
265 case FCmpInst::FCMP_UEQ: return Expression::FCMPUEQ;
266 case FCmpInst::FCMP_UGT: return Expression::FCMPUGT;
267 case FCmpInst::FCMP_UGE: return Expression::FCMPUGE;
268 case FCmpInst::FCMP_ULT: return Expression::FCMPULT;
269 case FCmpInst::FCMP_ULE: return Expression::FCMPULE;
270 case FCmpInst::FCMP_UNE: return Expression::FCMPUNE;
274 Expression::ExpressionOpcode ValueTable::getOpcode(CastInst* C) {
275 switch(C->getOpcode()) {
276 default: // THIS SHOULD NEVER HAPPEN
277 assert(0 && "Cast operator with unknown opcode?");
278 case Instruction::Trunc: return Expression::TRUNC;
279 case Instruction::ZExt: return Expression::ZEXT;
280 case Instruction::SExt: return Expression::SEXT;
281 case Instruction::FPToUI: return Expression::FPTOUI;
282 case Instruction::FPToSI: return Expression::FPTOSI;
283 case Instruction::UIToFP: return Expression::UITOFP;
284 case Instruction::SIToFP: return Expression::SITOFP;
285 case Instruction::FPTrunc: return Expression::FPTRUNC;
286 case Instruction::FPExt: return Expression::FPEXT;
287 case Instruction::PtrToInt: return Expression::PTRTOINT;
288 case Instruction::IntToPtr: return Expression::INTTOPTR;
289 case Instruction::BitCast: return Expression::BITCAST;
293 uint32_t ValueTable::hash_operand(Value* v) {
294 if (CallInst* CI = dyn_cast<CallInst>(v))
295 if (!AA->doesNotAccessMemory(CI))
296 return nextValueNumber++;
298 return lookup_or_add(v);
301 Expression ValueTable::create_expression(CallInst* C) {
304 e.type = C->getType();
308 e.function = C->getCalledFunction();
309 e.opcode = Expression::CALL;
311 for (CallInst::op_iterator I = C->op_begin()+1, E = C->op_end();
313 e.varargs.push_back(hash_operand(*I));
318 Expression ValueTable::create_expression(BinaryOperator* BO) {
321 e.firstVN = hash_operand(BO->getOperand(0));
322 e.secondVN = hash_operand(BO->getOperand(1));
325 e.type = BO->getType();
326 e.opcode = getOpcode(BO);
331 Expression ValueTable::create_expression(CmpInst* C) {
334 e.firstVN = hash_operand(C->getOperand(0));
335 e.secondVN = hash_operand(C->getOperand(1));
338 e.type = C->getType();
339 e.opcode = getOpcode(C);
344 Expression ValueTable::create_expression(CastInst* C) {
347 e.firstVN = hash_operand(C->getOperand(0));
351 e.type = C->getType();
352 e.opcode = getOpcode(C);
357 Expression ValueTable::create_expression(ShuffleVectorInst* S) {
360 e.firstVN = hash_operand(S->getOperand(0));
361 e.secondVN = hash_operand(S->getOperand(1));
362 e.thirdVN = hash_operand(S->getOperand(2));
364 e.type = S->getType();
365 e.opcode = Expression::SHUFFLE;
370 Expression ValueTable::create_expression(ExtractElementInst* E) {
373 e.firstVN = hash_operand(E->getOperand(0));
374 e.secondVN = hash_operand(E->getOperand(1));
377 e.type = E->getType();
378 e.opcode = Expression::EXTRACT;
383 Expression ValueTable::create_expression(InsertElementInst* I) {
386 e.firstVN = hash_operand(I->getOperand(0));
387 e.secondVN = hash_operand(I->getOperand(1));
388 e.thirdVN = hash_operand(I->getOperand(2));
390 e.type = I->getType();
391 e.opcode = Expression::INSERT;
396 Expression ValueTable::create_expression(SelectInst* I) {
399 e.firstVN = hash_operand(I->getCondition());
400 e.secondVN = hash_operand(I->getTrueValue());
401 e.thirdVN = hash_operand(I->getFalseValue());
403 e.type = I->getType();
404 e.opcode = Expression::SELECT;
409 Expression ValueTable::create_expression(GetElementPtrInst* G) {
412 e.firstVN = hash_operand(G->getPointerOperand());
416 e.type = G->getType();
417 e.opcode = Expression::GEP;
419 for (GetElementPtrInst::op_iterator I = G->idx_begin(), E = G->idx_end();
421 e.varargs.push_back(hash_operand(*I));
426 //===----------------------------------------------------------------------===//
427 // ValueTable External Functions
428 //===----------------------------------------------------------------------===//
430 /// lookup_or_add - Returns the value number for the specified value, assigning
431 /// it a new number if it did not have one before.
432 uint32_t ValueTable::lookup_or_add(Value* V) {
433 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
434 if (VI != valueNumbering.end())
437 if (CallInst* C = dyn_cast<CallInst>(V)) {
438 if (AA->onlyReadsMemory(C)) { // includes doesNotAccessMemory
439 Expression e = create_expression(C);
441 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
442 if (EI != expressionNumbering.end()) {
443 valueNumbering.insert(std::make_pair(V, EI->second));
446 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
447 valueNumbering.insert(std::make_pair(V, nextValueNumber));
449 return nextValueNumber++;
452 valueNumbering.insert(std::make_pair(V, nextValueNumber));
453 return nextValueNumber++;
455 } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(V)) {
456 Expression e = create_expression(BO);
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 (CmpInst* C = dyn_cast<CmpInst>(V)) {
469 Expression e = create_expression(C);
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 (ShuffleVectorInst* U = dyn_cast<ShuffleVectorInst>(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 (ExtractElementInst* U = dyn_cast<ExtractElementInst>(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 (InsertElementInst* U = dyn_cast<InsertElementInst>(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 (SelectInst* U = dyn_cast<SelectInst>(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 (CastInst* U = dyn_cast<CastInst>(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++;
546 } else if (GetElementPtrInst* U = dyn_cast<GetElementPtrInst>(V)) {
547 Expression e = create_expression(U);
549 DenseMap<Expression, uint32_t>::iterator EI = expressionNumbering.find(e);
550 if (EI != expressionNumbering.end()) {
551 valueNumbering.insert(std::make_pair(V, EI->second));
554 expressionNumbering.insert(std::make_pair(e, nextValueNumber));
555 valueNumbering.insert(std::make_pair(V, nextValueNumber));
557 return nextValueNumber++;
560 valueNumbering.insert(std::make_pair(V, nextValueNumber));
561 return nextValueNumber++;
565 /// lookup - Returns the value number of the specified value. Fails if
566 /// the value has not yet been numbered.
567 uint32_t ValueTable::lookup(Value* V) const {
568 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
569 assert(VI != valueNumbering.end() && "Value not numbered?");
573 /// clear - Remove all entries from the ValueTable
574 void ValueTable::clear() {
575 valueNumbering.clear();
576 expressionNumbering.clear();
580 /// erase - Remove a value from the value numbering
581 void ValueTable::erase(Value* V) {
582 valueNumbering.erase(V);
585 //===----------------------------------------------------------------------===//
586 // ValueNumberedSet Class
587 //===----------------------------------------------------------------------===//
589 class VISIBILITY_HIDDEN ValueNumberedSet {
591 SmallPtrSet<Value*, 8> contents;
594 ValueNumberedSet() { numbers.resize(1); }
595 ValueNumberedSet(const ValueNumberedSet& other) {
596 numbers = other.numbers;
597 contents = other.contents;
600 typedef SmallPtrSet<Value*, 8>::iterator iterator;
602 iterator begin() { return contents.begin(); }
603 iterator end() { return contents.end(); }
605 bool insert(Value* v) { return contents.insert(v); }
606 void insert(iterator I, iterator E) { contents.insert(I, E); }
607 void erase(Value* v) { contents.erase(v); }
608 unsigned count(Value* v) { return contents.count(v); }
609 size_t size() { return contents.size(); }
611 void set(unsigned i) {
612 if (i >= numbers.size())
618 void operator=(const ValueNumberedSet& other) {
619 contents = other.contents;
620 numbers = other.numbers;
623 void reset(unsigned i) {
624 if (i < numbers.size())
628 bool test(unsigned i) {
629 if (i >= numbers.size())
632 return numbers.test(i);
642 //===----------------------------------------------------------------------===//
644 //===----------------------------------------------------------------------===//
648 class VISIBILITY_HIDDEN GVN : public FunctionPass {
649 bool runOnFunction(Function &F);
651 static char ID; // Pass identification, replacement for typeid
652 GVN() : FunctionPass((intptr_t)&ID) { }
657 DenseMap<BasicBlock*, ValueNumberedSet> availableOut;
659 typedef DenseMap<Value*, SmallPtrSet<Instruction*, 4> > PhiMapType;
663 // This transformation requires dominator postdominator info
664 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
665 AU.setPreservesCFG();
666 AU.addRequired<DominatorTree>();
667 AU.addRequired<MemoryDependenceAnalysis>();
668 AU.addRequired<AliasAnalysis>();
669 AU.addRequired<TargetData>();
670 AU.addPreserved<AliasAnalysis>();
671 AU.addPreserved<MemoryDependenceAnalysis>();
672 AU.addPreserved<TargetData>();
676 // FIXME: eliminate or document these better
677 Value* find_leader(ValueNumberedSet& vals, uint32_t v) ;
678 void val_insert(ValueNumberedSet& s, Value* v);
679 bool processLoad(LoadInst* L,
680 DenseMap<Value*, LoadInst*> &lastLoad,
681 SmallVectorImpl<Instruction*> &toErase);
682 bool processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase);
683 bool processInstruction(Instruction* I,
684 ValueNumberedSet& currAvail,
685 DenseMap<Value*, LoadInst*>& lastSeenLoad,
686 SmallVectorImpl<Instruction*> &toErase);
687 bool processNonLocalLoad(LoadInst* L,
688 SmallVectorImpl<Instruction*> &toErase);
689 bool processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
690 SmallVectorImpl<Instruction*> &toErase);
691 bool performCallSlotOptzn(MemCpyInst* cpy, CallInst* C,
692 SmallVectorImpl<Instruction*> &toErase);
693 Value *GetValueForBlock(BasicBlock *BB, LoadInst* orig,
694 DenseMap<BasicBlock*, Value*> &Phis,
695 bool top_level = false);
696 void dump(DenseMap<BasicBlock*, Value*>& d);
697 bool iterateOnFunction(Function &F);
698 Value* CollapsePhi(PHINode* p);
699 bool isSafeReplacement(PHINode* p, Instruction* inst);
705 // createGVNPass - The public interface to this file...
706 FunctionPass *llvm::createGVNPass() { return new GVN(); }
708 static RegisterPass<GVN> X("gvn",
709 "Global Value Numbering");
711 /// find_leader - Given a set and a value number, return the first
712 /// element of the set with that value number, or 0 if no such element
714 Value* GVN::find_leader(ValueNumberedSet& vals, uint32_t v) {
718 for (ValueNumberedSet::iterator I = vals.begin(), E = vals.end();
720 if (v == VN.lookup(*I))
723 assert(0 && "No leader found, but present bit is set?");
727 /// val_insert - Insert a value into a set only if there is not a value
728 /// with the same value number already in the set
729 void GVN::val_insert(ValueNumberedSet& s, Value* v) {
730 uint32_t num = VN.lookup(v);
735 void GVN::dump(DenseMap<BasicBlock*, Value*>& d) {
737 for (DenseMap<BasicBlock*, Value*>::iterator I = d.begin(),
738 E = d.end(); I != E; ++I) {
739 if (I->second == MemoryDependenceAnalysis::None)
747 Value* GVN::CollapsePhi(PHINode* p) {
748 DominatorTree &DT = getAnalysis<DominatorTree>();
749 Value* constVal = p->hasConstantValue();
751 if (!constVal) return 0;
753 Instruction* inst = dyn_cast<Instruction>(constVal);
757 if (DT.dominates(inst, p))
758 if (isSafeReplacement(p, inst))
763 bool GVN::isSafeReplacement(PHINode* p, Instruction* inst) {
764 if (!isa<PHINode>(inst))
767 for (Instruction::use_iterator UI = p->use_begin(), E = p->use_end();
769 if (PHINode* use_phi = dyn_cast<PHINode>(UI))
770 if (use_phi->getParent() == inst->getParent())
776 /// GetValueForBlock - Get the value to use within the specified basic block.
777 /// available values are in Phis.
778 Value *GVN::GetValueForBlock(BasicBlock *BB, LoadInst* orig,
779 DenseMap<BasicBlock*, Value*> &Phis,
782 // If we have already computed this value, return the previously computed val.
783 DenseMap<BasicBlock*, Value*>::iterator V = Phis.find(BB);
784 if (V != Phis.end() && !top_level) return V->second;
786 BasicBlock* singlePred = BB->getSinglePredecessor();
788 Value *ret = GetValueForBlock(singlePred, orig, Phis);
793 // Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
794 // now, then get values to fill in the incoming values for the PHI.
795 PHINode *PN = new PHINode(orig->getType(), orig->getName()+".rle",
797 PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
799 if (Phis.count(BB) == 0)
800 Phis.insert(std::make_pair(BB, PN));
802 // Fill in the incoming values for the block.
803 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
804 Value* val = GetValueForBlock(*PI, orig, Phis);
805 PN->addIncoming(val, *PI);
808 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
809 AA.copyValue(orig, PN);
811 // Attempt to collapse PHI nodes that are trivially redundant
812 Value* v = CollapsePhi(PN);
814 // Cache our phi construction results
815 phiMap[orig->getPointerOperand()].insert(PN);
819 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
821 MD.removeInstruction(PN);
822 PN->replaceAllUsesWith(v);
824 for (DenseMap<BasicBlock*, Value*>::iterator I = Phis.begin(),
825 E = Phis.end(); I != E; ++I)
829 PN->eraseFromParent();
835 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
836 /// non-local by performing PHI construction.
837 bool GVN::processNonLocalLoad(LoadInst* L,
838 SmallVectorImpl<Instruction*> &toErase) {
839 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
841 // Find the non-local dependencies of the load
842 DenseMap<BasicBlock*, Value*> deps;
843 MD.getNonLocalDependency(L, deps);
845 DenseMap<BasicBlock*, Value*> repl;
847 // Filter out useless results (non-locals, etc)
848 for (DenseMap<BasicBlock*, Value*>::iterator I = deps.begin(), E = deps.end();
850 if (I->second == MemoryDependenceAnalysis::None)
853 if (I->second == MemoryDependenceAnalysis::NonLocal)
856 if (StoreInst* S = dyn_cast<StoreInst>(I->second)) {
857 if (S->getPointerOperand() != L->getPointerOperand())
859 repl[I->first] = S->getOperand(0);
860 } else if (LoadInst* LD = dyn_cast<LoadInst>(I->second)) {
861 if (LD->getPointerOperand() != L->getPointerOperand())
869 // Use cached PHI construction information from previous runs
870 SmallPtrSet<Instruction*, 4>& p = phiMap[L->getPointerOperand()];
871 for (SmallPtrSet<Instruction*, 4>::iterator I = p.begin(), E = p.end();
873 if ((*I)->getParent() == L->getParent()) {
874 MD.removeInstruction(L);
875 L->replaceAllUsesWith(*I);
876 toErase.push_back(L);
881 repl.insert(std::make_pair((*I)->getParent(), *I));
884 // Perform PHI construction
885 SmallPtrSet<BasicBlock*, 4> visited;
886 Value* v = GetValueForBlock(L->getParent(), L, repl, true);
888 MD.removeInstruction(L);
889 L->replaceAllUsesWith(v);
890 toErase.push_back(L);
896 /// processLoad - Attempt to eliminate a load, first by eliminating it
897 /// locally, and then attempting non-local elimination if that fails.
898 bool GVN::processLoad(LoadInst *L, DenseMap<Value*, LoadInst*> &lastLoad,
899 SmallVectorImpl<Instruction*> &toErase) {
900 if (L->isVolatile()) {
901 lastLoad[L->getPointerOperand()] = L;
905 Value* pointer = L->getPointerOperand();
906 LoadInst*& last = lastLoad[pointer];
908 // ... to a pointer that has been loaded from before...
909 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
910 bool removedNonLocal = false;
911 Instruction* dep = MD.getDependency(L);
912 if (dep == MemoryDependenceAnalysis::NonLocal &&
913 L->getParent() != &L->getParent()->getParent()->getEntryBlock()) {
914 removedNonLocal = processNonLocalLoad(L, toErase);
916 if (!removedNonLocal)
919 return removedNonLocal;
923 bool deletedLoad = false;
925 // Walk up the dependency chain until we either find
926 // a dependency we can use, or we can't walk any further
927 while (dep != MemoryDependenceAnalysis::None &&
928 dep != MemoryDependenceAnalysis::NonLocal &&
929 (isa<LoadInst>(dep) || isa<StoreInst>(dep))) {
930 // ... that depends on a store ...
931 if (StoreInst* S = dyn_cast<StoreInst>(dep)) {
932 if (S->getPointerOperand() == pointer) {
934 MD.removeInstruction(L);
936 L->replaceAllUsesWith(S->getOperand(0));
937 toErase.push_back(L);
942 // Whether we removed it or not, we can't
946 // If we don't depend on a store, and we haven't
947 // been loaded before, bail.
949 } else if (dep == last) {
951 MD.removeInstruction(L);
953 L->replaceAllUsesWith(last);
954 toErase.push_back(L);
960 dep = MD.getDependency(L, dep);
964 if (dep != MemoryDependenceAnalysis::None &&
965 dep != MemoryDependenceAnalysis::NonLocal &&
966 isa<AllocationInst>(dep)) {
967 // Check that this load is actually from the
968 // allocation we found
969 Value* v = L->getOperand(0);
971 if (BitCastInst *BC = dyn_cast<BitCastInst>(v))
972 v = BC->getOperand(0);
973 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(v))
974 v = GEP->getOperand(0);
979 // If this load depends directly on an allocation, there isn't
980 // anything stored there; therefore, we can optimize this load
982 MD.removeInstruction(L);
984 L->replaceAllUsesWith(UndefValue::get(L->getType()));
985 toErase.push_back(L);
997 /// isBytewiseValue - If the specified value can be set by repeating the same
998 /// byte in memory, return the i8 value that it is represented with. This is
999 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
1000 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
1001 /// byte store (e.g. i16 0x1234), return null.
1002 static Value *isBytewiseValue(Value *V) {
1003 // All byte-wide stores are splatable, even of arbitrary variables.
1004 if (V->getType() == Type::Int8Ty) return V;
1006 // Constant float and double values can be handled as integer values if the
1007 // corresponding integer value is "byteable". An important case is 0.0.
1008 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
1009 if (CFP->getType() == Type::FloatTy)
1010 V = ConstantExpr::getBitCast(CFP, Type::Int32Ty);
1011 if (CFP->getType() == Type::DoubleTy)
1012 V = ConstantExpr::getBitCast(CFP, Type::Int64Ty);
1013 // Don't handle long double formats, which have strange constraints.
1016 // We can handle constant integers that are power of two in size and a
1017 // multiple of 8 bits.
1018 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1019 unsigned Width = CI->getBitWidth();
1020 if (isPowerOf2_32(Width) && Width > 8) {
1021 // We can handle this value if the recursive binary decomposition is the
1022 // same at all levels.
1023 APInt Val = CI->getValue();
1025 while (Val.getBitWidth() != 8) {
1026 unsigned NextWidth = Val.getBitWidth()/2;
1027 Val2 = Val.lshr(NextWidth);
1028 Val2.trunc(Val.getBitWidth()/2);
1029 Val.trunc(Val.getBitWidth()/2);
1031 // If the top/bottom halves aren't the same, reject it.
1035 return ConstantInt::get(Val);
1039 // Conceptually, we could handle things like:
1040 // %a = zext i8 %X to i16
1041 // %b = shl i16 %a, 8
1042 // %c = or i16 %a, %b
1043 // but until there is an example that actually needs this, it doesn't seem
1044 // worth worrying about.
1048 static int64_t GetOffsetFromIndex(const GetElementPtrInst *GEP, unsigned Idx,
1049 bool &VariableIdxFound, TargetData &TD) {
1050 // Skip over the first indices.
1051 gep_type_iterator GTI = gep_type_begin(GEP);
1052 for (unsigned i = 1; i != Idx; ++i, ++GTI)
1055 // Compute the offset implied by the rest of the indices.
1057 for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
1058 ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i));
1060 return VariableIdxFound = true;
1061 if (OpC->isZero()) continue; // No offset.
1063 // Handle struct indices, which add their field offset to the pointer.
1064 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1065 Offset += TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
1069 // Otherwise, we have a sequential type like an array or vector. Multiply
1070 // the index by the ElementSize.
1071 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
1072 Offset += Size*OpC->getSExtValue();
1078 /// IsPointerOffset - Return true if Ptr1 is provably equal to Ptr2 plus a
1079 /// constant offset, and return that constant offset. For example, Ptr1 might
1080 /// be &A[42], and Ptr2 might be &A[40]. In this case offset would be -8.
1081 static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset,
1083 // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical
1084 // base. After that base, they may have some number of common (and
1085 // potentially variable) indices. After that they handle some constant
1086 // offset, which determines their offset from each other. At this point, we
1087 // handle no other case.
1088 GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
1089 GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
1090 if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0))
1093 // Skip any common indices and track the GEP types.
1095 for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx)
1096 if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx))
1099 bool VariableIdxFound = false;
1100 int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, TD);
1101 int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, TD);
1102 if (VariableIdxFound) return false;
1104 Offset = Offset2-Offset1;
1109 /// MemsetRange - Represents a range of memset'd bytes with the ByteVal value.
1110 /// This allows us to analyze stores like:
1115 /// which sometimes happens with stores to arrays of structs etc. When we see
1116 /// the first store, we make a range [1, 2). The second store extends the range
1117 /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
1118 /// two ranges into [0, 3) which is memset'able.
1120 struct MemsetRange {
1121 // Start/End - A semi range that describes the span that this range covers.
1122 // The range is closed at the start and open at the end: [Start, End).
1125 /// StartPtr - The getelementptr instruction that points to the start of the
1129 /// Alignment - The known alignment of the first store.
1132 /// TheStores - The actual stores that make up this range.
1133 SmallVector<StoreInst*, 16> TheStores;
1137 class MemsetRanges {
1138 /// Ranges - A sorted list of the memset ranges. We use std::list here
1139 /// because each element is relatively large and expensive to copy.
1140 std::list<MemsetRange> Ranges;
1141 typedef std::list<MemsetRange>::iterator range_iterator;
1144 MemsetRanges(TargetData &td) : TD(td) {}
1146 typedef std::list<MemsetRange>::const_iterator const_iterator;
1147 const_iterator begin() const { return Ranges.begin(); }
1148 const_iterator end() const { return Ranges.end(); }
1151 void addStore(int64_t OffsetFromFirst, StoreInst *SI);
1156 /// addStore - Add a new store to the MemsetRanges data structure. This adds a
1157 /// new range for the specified store at the specified offset, merging into
1158 /// existing ranges as appropriate.
1159 void MemsetRanges::addStore(int64_t Start, StoreInst *SI) {
1160 int64_t End = Start+TD.getTypeStoreSize(SI->getOperand(0)->getType());
1162 // Do a linear search of the ranges to see if this can be joined and/or to
1163 // find the insertion point in the list. We keep the ranges sorted for
1164 // simplicity here. This is a linear search of a linked list, which is ugly,
1165 // however the number of ranges is limited, so this won't get crazy slow.
1166 range_iterator I = Ranges.begin(), E = Ranges.end();
1168 while (I != E && Start > I->End)
1171 // We now know that I == E, in which case we didn't find anything to merge
1172 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
1173 // to insert a new range. Handle this now.
1174 if (I == E || End < I->Start) {
1175 MemsetRange &R = *Ranges.insert(I, MemsetRange());
1178 R.StartPtr = SI->getPointerOperand();
1179 R.Alignment = SI->getAlignment();
1180 R.TheStores.push_back(SI);
1184 // This store overlaps with I, add it.
1185 I->TheStores.push_back(SI);
1187 // At this point, we may have an interval that completely contains our store.
1188 // If so, just add it to the interval and return.
1189 if (I->Start <= Start && I->End >= End)
1192 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
1193 // but is not entirely contained within the range.
1195 // See if the range extends the start of the range. In this case, it couldn't
1196 // possibly cause it to join the prior range, because otherwise we would have
1198 if (Start < I->Start)
1201 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
1202 // is in or right at the end of I), and that End >= I->Start. Extend I out to
1206 range_iterator NextI = I;;
1207 while (++NextI != E && End >= NextI->Start) {
1208 // Merge the range in.
1209 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
1210 if (NextI->End > I->End)
1211 I->End = NextI->End;
1212 Ranges.erase(NextI);
1220 /// processStore - When GVN is scanning forward over instructions, we look for
1221 /// some other patterns to fold away. In particular, this looks for stores to
1222 /// neighboring locations of memory. If it sees enough consequtive ones
1223 /// (currently 4) it attempts to merge them together into a memcpy/memset.
1224 bool GVN::processStore(StoreInst *SI, SmallVectorImpl<Instruction*> &toErase) {
1225 if (!FormMemSet) return false;
1226 if (SI->isVolatile()) return false;
1228 // There are two cases that are interesting for this code to handle: memcpy
1229 // and memset. Right now we only handle memset.
1231 // Ensure that the value being stored is something that can be memset'able a
1232 // byte at a time like "0" or "-1" or any width, as well as things like
1233 // 0xA0A0A0A0 and 0.0.
1234 Value *ByteVal = isBytewiseValue(SI->getOperand(0));
1238 TargetData &TD = getAnalysis<TargetData>();
1239 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
1241 // Okay, so we now have a single store that can be splatable. Scan to find
1242 // all subsequent stores of the same value to offset from the same pointer.
1243 // Join these together into ranges, so we can decide whether contiguous blocks
1245 MemsetRanges Ranges(TD);
1247 // Add our first pointer.
1248 Ranges.addStore(0, SI);
1249 Value *StartPtr = SI->getPointerOperand();
1251 BasicBlock::iterator BI = SI;
1252 for (++BI; !isa<TerminatorInst>(BI); ++BI) {
1253 if (isa<CallInst>(BI) || isa<InvokeInst>(BI)) {
1254 // If the call is readnone, ignore it, otherwise bail out. We don't even
1255 // allow readonly here because we don't want something like:
1256 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
1257 if (AA.getModRefBehavior(CallSite::get(BI)) ==
1258 AliasAnalysis::DoesNotAccessMemory)
1261 // TODO: If this is a memset, try to join it in.
1264 } else if (isa<VAArgInst>(BI) || isa<LoadInst>(BI))
1267 // If this is a non-store instruction it is fine, ignore it.
1268 StoreInst *NextStore = dyn_cast<StoreInst>(BI);
1269 if (NextStore == 0) continue;
1271 // If this is a store, see if we can merge it in.
1272 if (NextStore->isVolatile()) break;
1274 // Check to see if this stored value is of the same byte-splattable value.
1275 if (ByteVal != isBytewiseValue(NextStore->getOperand(0)))
1278 // Check to see if this store is to a constant offset from the start ptr.
1280 if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, TD))
1283 Ranges.addStore(Offset, NextStore);
1286 Function *MemSetF = 0;
1288 // Now that we have full information about ranges, loop over the ranges and
1289 // emit memset's for anything big enough to be worthwhile.
1290 bool MadeChange = false;
1291 for (MemsetRanges::const_iterator I = Ranges.begin(), E = Ranges.end();
1293 const MemsetRange &Range = *I;
1295 // If we found less than 4 stores to merge, ignore the subrange: it isn't
1296 // worth losing type information in llvm IR to do the transformation.
1297 if (Range.TheStores.size() < 4)
1300 // Otherwise, we do want to transform this! Create a new memset. We put
1301 // the memset right after the first store that we found in this block. This
1302 // ensures that the caller will increment the iterator to the memset before
1303 // it deletes all the stores.
1304 BasicBlock::iterator InsertPt = SI; ++InsertPt;
1307 MemSetF = Intrinsic::getDeclaration(SI->getParent()->getParent()
1308 ->getParent(), Intrinsic::memset_i64);
1310 // StartPtr may not dominate the starting point. Instead of using it, base
1311 // the destination pointer off the input to the first store in the block.
1312 StartPtr = SI->getPointerOperand();
1314 // Cast the start ptr to be i8* as memset requires.
1315 const Type *i8Ptr = PointerType::getUnqual(Type::Int8Ty);
1316 if (StartPtr->getType() != i8Ptr)
1317 StartPtr = new BitCastInst(StartPtr, i8Ptr, StartPtr->getNameStart(),
1320 // Offset the pointer if needed.
1322 StartPtr = new GetElementPtrInst(StartPtr, ConstantInt::get(Type::Int64Ty,
1324 "ptroffset", InsertPt);
1327 StartPtr, ByteVal, // Start, value
1328 ConstantInt::get(Type::Int64Ty, Range.End-Range.Start), // size
1329 ConstantInt::get(Type::Int32Ty, Range.Alignment) // align
1331 new CallInst(MemSetF, Ops, Ops+4, "", InsertPt);
1333 // Zap all the stores.
1334 toErase.append(Range.TheStores.begin(), Range.TheStores.end());
1343 /// performCallSlotOptzn - takes a memcpy and a call that it depends on,
1344 /// and checks for the possibility of a call slot optimization by having
1345 /// the call write its result directly into the destination of the memcpy.
1346 bool GVN::performCallSlotOptzn(MemCpyInst *cpy, CallInst *C,
1347 SmallVectorImpl<Instruction*> &toErase) {
1348 // The general transformation to keep in mind is
1350 // call @func(..., src, ...)
1351 // memcpy(dest, src, ...)
1355 // memcpy(dest, src, ...)
1356 // call @func(..., dest, ...)
1358 // Since moving the memcpy is technically awkward, we additionally check that
1359 // src only holds uninitialized values at the moment of the call, meaning that
1360 // the memcpy can be discarded rather than moved.
1362 // Deliberately get the source and destination with bitcasts stripped away,
1363 // because we'll need to do type comparisons based on the underlying type.
1364 Value* cpyDest = cpy->getDest();
1365 Value* cpySrc = cpy->getSource();
1366 CallSite CS = CallSite::get(C);
1368 // We need to be able to reason about the size of the memcpy, so we require
1369 // that it be a constant.
1370 ConstantInt* cpyLength = dyn_cast<ConstantInt>(cpy->getLength());
1374 // Require that src be an alloca. This simplifies the reasoning considerably.
1375 AllocaInst* srcAlloca = dyn_cast<AllocaInst>(cpySrc);
1379 // Check that all of src is copied to dest.
1380 TargetData& TD = getAnalysis<TargetData>();
1382 ConstantInt* srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
1386 uint64_t srcSize = TD.getABITypeSize(srcAlloca->getAllocatedType()) *
1387 srcArraySize->getZExtValue();
1389 if (cpyLength->getZExtValue() < srcSize)
1392 // Check that accessing the first srcSize bytes of dest will not cause a
1393 // trap. Otherwise the transform is invalid since it might cause a trap
1394 // to occur earlier than it otherwise would.
1395 if (AllocaInst* A = dyn_cast<AllocaInst>(cpyDest)) {
1396 // The destination is an alloca. Check it is larger than srcSize.
1397 ConstantInt* destArraySize = dyn_cast<ConstantInt>(A->getArraySize());
1401 uint64_t destSize = TD.getABITypeSize(A->getAllocatedType()) *
1402 destArraySize->getZExtValue();
1404 if (destSize < srcSize)
1406 } else if (Argument* A = dyn_cast<Argument>(cpyDest)) {
1407 // If the destination is an sret parameter then only accesses that are
1408 // outside of the returned struct type can trap.
1409 if (!A->hasStructRetAttr())
1412 const Type* StructTy = cast<PointerType>(A->getType())->getElementType();
1413 uint64_t destSize = TD.getABITypeSize(StructTy);
1415 if (destSize < srcSize)
1421 // Check that src is not accessed except via the call and the memcpy. This
1422 // guarantees that it holds only undefined values when passed in (so the final
1423 // memcpy can be dropped), that it is not read or written between the call and
1424 // the memcpy, and that writing beyond the end of it is undefined.
1425 SmallVector<User*, 8> srcUseList(srcAlloca->use_begin(),
1426 srcAlloca->use_end());
1427 while (!srcUseList.empty()) {
1428 User* UI = srcUseList.back();
1429 srcUseList.pop_back();
1431 if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
1432 for (User::use_iterator I = UI->use_begin(), E = UI->use_end();
1434 srcUseList.push_back(*I);
1435 } else if (UI != C && UI != cpy) {
1440 // Since we're changing the parameter to the callsite, we need to make sure
1441 // that what would be the new parameter dominates the callsite.
1442 DominatorTree& DT = getAnalysis<DominatorTree>();
1443 if (Instruction* cpyDestInst = dyn_cast<Instruction>(cpyDest))
1444 if (!DT.dominates(cpyDestInst, C))
1447 // In addition to knowing that the call does not access src in some
1448 // unexpected manner, for example via a global, which we deduce from
1449 // the use analysis, we also need to know that it does not sneakily
1450 // access dest. We rely on AA to figure this out for us.
1451 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1452 if (AA.getModRefInfo(C, cpy->getRawDest(), srcSize) !=
1453 AliasAnalysis::NoModRef)
1456 // All the checks have passed, so do the transformation.
1457 for (unsigned i = 0; i < CS.arg_size(); ++i)
1458 if (CS.getArgument(i) == cpySrc) {
1459 if (cpySrc->getType() != cpyDest->getType())
1460 cpyDest = CastInst::createPointerCast(cpyDest, cpySrc->getType(),
1461 cpyDest->getName(), C);
1462 CS.setArgument(i, cpyDest);
1465 // Drop any cached information about the call, because we may have changed
1466 // its dependence information by changing its parameter.
1467 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1468 MD.dropInstruction(C);
1470 // Remove the memcpy
1471 MD.removeInstruction(cpy);
1472 toErase.push_back(cpy);
1477 /// processMemCpy - perform simplication of memcpy's. If we have memcpy A which
1478 /// copies X to Y, and memcpy B which copies Y to Z, then we can rewrite B to be
1479 /// a memcpy from X to Z (or potentially a memmove, depending on circumstances).
1480 /// This allows later passes to remove the first memcpy altogether.
1481 bool GVN::processMemCpy(MemCpyInst* M, MemCpyInst* MDep,
1482 SmallVectorImpl<Instruction*> &toErase) {
1483 // We can only transforms memcpy's where the dest of one is the source of the
1485 if (M->getSource() != MDep->getDest())
1488 // Second, the length of the memcpy's must be the same, or the preceeding one
1489 // must be larger than the following one.
1490 ConstantInt* C1 = dyn_cast<ConstantInt>(MDep->getLength());
1491 ConstantInt* C2 = dyn_cast<ConstantInt>(M->getLength());
1495 uint64_t DepSize = C1->getValue().getZExtValue();
1496 uint64_t CpySize = C2->getValue().getZExtValue();
1498 if (DepSize < CpySize)
1501 // Finally, we have to make sure that the dest of the second does not
1502 // alias the source of the first
1503 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1504 if (AA.alias(M->getRawDest(), CpySize, MDep->getRawSource(), DepSize) !=
1505 AliasAnalysis::NoAlias)
1507 else if (AA.alias(M->getRawDest(), CpySize, M->getRawSource(), CpySize) !=
1508 AliasAnalysis::NoAlias)
1510 else if (AA.alias(MDep->getRawDest(), DepSize, MDep->getRawSource(), DepSize)
1511 != AliasAnalysis::NoAlias)
1514 // If all checks passed, then we can transform these memcpy's
1515 Function* MemCpyFun = Intrinsic::getDeclaration(
1516 M->getParent()->getParent()->getParent(),
1517 M->getIntrinsicID());
1519 std::vector<Value*> args;
1520 args.push_back(M->getRawDest());
1521 args.push_back(MDep->getRawSource());
1522 args.push_back(M->getLength());
1523 args.push_back(M->getAlignment());
1525 CallInst* C = new CallInst(MemCpyFun, args.begin(), args.end(), "", M);
1527 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1528 if (MD.getDependency(C) == MDep) {
1529 MD.dropInstruction(M);
1530 toErase.push_back(M);
1534 MD.removeInstruction(C);
1535 toErase.push_back(C);
1539 /// processInstruction - When calculating availability, handle an instruction
1540 /// by inserting it into the appropriate sets
1541 bool GVN::processInstruction(Instruction *I, ValueNumberedSet &currAvail,
1542 DenseMap<Value*, LoadInst*> &lastSeenLoad,
1543 SmallVectorImpl<Instruction*> &toErase) {
1544 if (LoadInst* L = dyn_cast<LoadInst>(I))
1545 return processLoad(L, lastSeenLoad, toErase);
1547 if (StoreInst *SI = dyn_cast<StoreInst>(I))
1548 return processStore(SI, toErase);
1550 if (MemCpyInst* M = dyn_cast<MemCpyInst>(I)) {
1551 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1553 // The are two possible optimizations we can do for memcpy:
1554 // a) memcpy-memcpy xform which exposes redundance for DSE
1555 // b) call-memcpy xform for return slot optimization
1556 Instruction* dep = MD.getDependency(M);
1557 if (dep == MemoryDependenceAnalysis::None ||
1558 dep == MemoryDependenceAnalysis::NonLocal)
1560 if (MemCpyInst *MemCpy = dyn_cast<MemCpyInst>(dep))
1561 return processMemCpy(M, MemCpy, toErase);
1562 if (CallInst* C = dyn_cast<CallInst>(dep))
1563 return performCallSlotOptzn(M, C, toErase);
1567 unsigned num = VN.lookup_or_add(I);
1569 // Collapse PHI nodes
1570 if (PHINode* p = dyn_cast<PHINode>(I)) {
1571 Value* constVal = CollapsePhi(p);
1574 for (PhiMapType::iterator PI = phiMap.begin(), PE = phiMap.end();
1576 if (PI->second.count(p))
1577 PI->second.erase(p);
1579 p->replaceAllUsesWith(constVal);
1580 toErase.push_back(p);
1582 // Perform value-number based elimination
1583 } else if (currAvail.test(num)) {
1584 Value* repl = find_leader(currAvail, num);
1586 if (CallInst* CI = dyn_cast<CallInst>(I)) {
1587 AliasAnalysis& AA = getAnalysis<AliasAnalysis>();
1588 if (!AA.doesNotAccessMemory(CI)) {
1589 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1590 if (cast<Instruction>(repl)->getParent() != CI->getParent() ||
1591 MD.getDependency(CI) != MD.getDependency(cast<CallInst>(repl))) {
1592 // There must be an intervening may-alias store, so nothing from
1593 // this point on will be able to be replaced with the preceding call
1594 currAvail.erase(repl);
1595 currAvail.insert(I);
1603 MemoryDependenceAnalysis& MD = getAnalysis<MemoryDependenceAnalysis>();
1604 MD.removeInstruction(I);
1607 I->replaceAllUsesWith(repl);
1608 toErase.push_back(I);
1610 } else if (!I->isTerminator()) {
1612 currAvail.insert(I);
1618 // GVN::runOnFunction - This is the main transformation entry point for a
1621 bool GVN::runOnFunction(Function& F) {
1622 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
1624 bool changed = false;
1625 bool shouldContinue = true;
1627 while (shouldContinue) {
1628 shouldContinue = iterateOnFunction(F);
1629 changed |= shouldContinue;
1636 // GVN::iterateOnFunction - Executes one iteration of GVN
1637 bool GVN::iterateOnFunction(Function &F) {
1638 // Clean out global sets from any previous functions
1640 availableOut.clear();
1643 bool changed_function = false;
1645 DominatorTree &DT = getAnalysis<DominatorTree>();
1647 SmallVector<Instruction*, 4> toErase;
1648 DenseMap<Value*, LoadInst*> lastSeenLoad;
1650 // Top-down walk of the dominator tree
1651 for (df_iterator<DomTreeNode*> DI = df_begin(DT.getRootNode()),
1652 E = df_end(DT.getRootNode()); DI != E; ++DI) {
1654 // Get the set to update for this block
1655 ValueNumberedSet& currAvail = availableOut[DI->getBlock()];
1656 lastSeenLoad.clear();
1658 BasicBlock* BB = DI->getBlock();
1660 // A block inherits AVAIL_OUT from its dominator
1661 if (DI->getIDom() != 0)
1662 currAvail = availableOut[DI->getIDom()->getBlock()];
1664 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
1666 changed_function |= processInstruction(BI, currAvail,
1667 lastSeenLoad, toErase);
1669 NumGVNInstr += toErase.size();
1671 // Avoid iterator invalidation
1674 for (SmallVector<Instruction*, 4>::iterator I = toErase.begin(),
1675 E = toErase.end(); I != E; ++I)
1676 (*I)->eraseFromParent();
1682 return changed_function;