1 //===- GVN.cpp - Eliminate redundant values and loads ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs global value numbering to eliminate fully redundant
11 // instructions. It also performs simple dead load elimination.
13 // Note that this pass does the value numbering itself; it does not use the
14 // ValueNumbering analysis passes.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "gvn"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/Hashing.h"
23 #include "llvm/ADT/SetVector.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/CFG.h"
28 #include "llvm/Analysis/ConstantFolding.h"
29 #include "llvm/Analysis/InstructionSimplify.h"
30 #include "llvm/Analysis/Loads.h"
31 #include "llvm/Analysis/MemoryBuiltins.h"
32 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
33 #include "llvm/Analysis/PHITransAddr.h"
34 #include "llvm/Analysis/ValueTracking.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/Dominators.h"
37 #include "llvm/IR/GlobalVariable.h"
38 #include "llvm/IR/IRBuilder.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/LLVMContext.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/PatternMatch.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Target/TargetLibraryInfo.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/SSAUpdater.h"
51 using namespace PatternMatch;
53 STATISTIC(NumGVNInstr, "Number of instructions deleted");
54 STATISTIC(NumGVNLoad, "Number of loads deleted");
55 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
56 STATISTIC(NumGVNBlocks, "Number of blocks merged");
57 STATISTIC(NumGVNSimpl, "Number of instructions simplified");
58 STATISTIC(NumGVNEqProp, "Number of equalities propagated");
59 STATISTIC(NumPRELoad, "Number of loads PRE'd");
61 static cl::opt<bool> EnablePRE("enable-pre",
62 cl::init(true), cl::Hidden);
63 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
65 // Maximum allowed recursion depth.
66 static cl::opt<uint32_t>
67 MaxRecurseDepth("max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore,
68 cl::desc("Max recurse depth (default = 1000)"));
70 //===----------------------------------------------------------------------===//
72 //===----------------------------------------------------------------------===//
74 /// This class holds the mapping between values and value numbers. It is used
75 /// as an efficient mechanism to determine the expression-wise equivalence of
81 SmallVector<uint32_t, 4> varargs;
83 Expression(uint32_t o = ~2U) : opcode(o) { }
85 bool operator==(const Expression &other) const {
86 if (opcode != other.opcode)
88 if (opcode == ~0U || opcode == ~1U)
90 if (type != other.type)
92 if (varargs != other.varargs)
97 friend hash_code hash_value(const Expression &Value) {
98 return hash_combine(Value.opcode, Value.type,
99 hash_combine_range(Value.varargs.begin(),
100 Value.varargs.end()));
105 DenseMap<Value*, uint32_t> valueNumbering;
106 DenseMap<Expression, uint32_t> expressionNumbering;
108 MemoryDependenceAnalysis *MD;
111 uint32_t nextValueNumber;
113 Expression create_expression(Instruction* I);
114 Expression create_intrinsic_expression(CallInst *C, uint32_t opcode,
116 Expression create_cmp_expression(unsigned Opcode,
117 CmpInst::Predicate Predicate,
118 Value *LHS, Value *RHS);
119 uint32_t lookup_or_add_call(CallInst* C);
121 ValueTable() : nextValueNumber(1) { }
122 uint32_t lookup_or_add(Value *V);
123 uint32_t lookup(Value *V) const;
124 uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
125 Value *LHS, Value *RHS);
126 void add(Value *V, uint32_t num);
128 void erase(Value *v);
129 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
130 AliasAnalysis *getAliasAnalysis() const { return AA; }
131 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
132 void setDomTree(DominatorTree* D) { DT = D; }
133 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
134 void verifyRemoved(const Value *) const;
139 template <> struct DenseMapInfo<Expression> {
140 static inline Expression getEmptyKey() {
144 static inline Expression getTombstoneKey() {
148 static unsigned getHashValue(const Expression e) {
149 using llvm::hash_value;
150 return static_cast<unsigned>(hash_value(e));
152 static bool isEqual(const Expression &LHS, const Expression &RHS) {
159 //===----------------------------------------------------------------------===//
160 // ValueTable Internal Functions
161 //===----------------------------------------------------------------------===//
163 Expression ValueTable::create_expression(Instruction *I) {
165 e.type = I->getType();
166 e.opcode = I->getOpcode();
167 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
169 e.varargs.push_back(lookup_or_add(*OI));
170 if (I->isCommutative()) {
171 // Ensure that commutative instructions that only differ by a permutation
172 // of their operands get the same value number by sorting the operand value
173 // numbers. Since all commutative instructions have two operands it is more
174 // efficient to sort by hand rather than using, say, std::sort.
175 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
176 if (e.varargs[0] > e.varargs[1])
177 std::swap(e.varargs[0], e.varargs[1]);
180 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
181 // Sort the operand value numbers so x<y and y>x get the same value number.
182 CmpInst::Predicate Predicate = C->getPredicate();
183 if (e.varargs[0] > e.varargs[1]) {
184 std::swap(e.varargs[0], e.varargs[1]);
185 Predicate = CmpInst::getSwappedPredicate(Predicate);
187 e.opcode = (C->getOpcode() << 8) | Predicate;
188 } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
189 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
191 e.varargs.push_back(*II);
192 } else if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
193 for (ExtractValueInst::idx_iterator II = EVI->idx_begin(),
194 IE = EVI->idx_end(); II != IE; ++II)
195 e.varargs.push_back(*II);
201 Expression ValueTable::create_intrinsic_expression(CallInst *C, uint32_t opcode,
202 bool IsCommutative) {
205 StructType *ST = cast<StructType>(C->getType());
207 e.type = *ST->element_begin();
209 for (unsigned i = 0, ei = C->getNumArgOperands(); i < ei; ++i)
210 e.varargs.push_back(lookup_or_add(C->getArgOperand(i)));
212 // Ensure that commutative instructions that only differ by a permutation
213 // of their operands get the same value number by sorting the operand value
214 // numbers. Since all commutative instructions have two operands it is more
215 // efficient to sort by hand rather than using, say, std::sort.
216 assert(C->getNumArgOperands() == 2 && "Unsupported commutative instruction!");
217 if (e.varargs[0] > e.varargs[1])
218 std::swap(e.varargs[0], e.varargs[1]);
224 Expression ValueTable::create_cmp_expression(unsigned Opcode,
225 CmpInst::Predicate Predicate,
226 Value *LHS, Value *RHS) {
227 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
228 "Not a comparison!");
230 e.type = CmpInst::makeCmpResultType(LHS->getType());
231 e.varargs.push_back(lookup_or_add(LHS));
232 e.varargs.push_back(lookup_or_add(RHS));
234 // Sort the operand value numbers so x<y and y>x get the same value number.
235 if (e.varargs[0] > e.varargs[1]) {
236 std::swap(e.varargs[0], e.varargs[1]);
237 Predicate = CmpInst::getSwappedPredicate(Predicate);
239 e.opcode = (Opcode << 8) | Predicate;
243 //===----------------------------------------------------------------------===//
244 // ValueTable External Functions
245 //===----------------------------------------------------------------------===//
247 /// add - Insert a value into the table with a specified value number.
248 void ValueTable::add(Value *V, uint32_t num) {
249 valueNumbering.insert(std::make_pair(V, num));
252 uint32_t ValueTable::lookup_or_add_call(CallInst *C) {
253 if (AA->doesNotAccessMemory(C)) {
254 Expression exp = create_expression(C);
255 uint32_t &e = expressionNumbering[exp];
256 if (!e) e = nextValueNumber++;
257 valueNumbering[C] = e;
259 } else if (AA->onlyReadsMemory(C)) {
260 Expression exp = create_expression(C);
261 uint32_t &e = expressionNumbering[exp];
263 e = nextValueNumber++;
264 valueNumbering[C] = e;
268 e = nextValueNumber++;
269 valueNumbering[C] = e;
273 MemDepResult local_dep = MD->getDependency(C);
275 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
276 valueNumbering[C] = nextValueNumber;
277 return nextValueNumber++;
280 if (local_dep.isDef()) {
281 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
283 if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
284 valueNumbering[C] = nextValueNumber;
285 return nextValueNumber++;
288 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
289 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
290 uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
292 valueNumbering[C] = nextValueNumber;
293 return nextValueNumber++;
297 uint32_t v = lookup_or_add(local_cdep);
298 valueNumbering[C] = v;
303 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
304 MD->getNonLocalCallDependency(CallSite(C));
305 // FIXME: Move the checking logic to MemDep!
308 // Check to see if we have a single dominating call instruction that is
310 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
311 const NonLocalDepEntry *I = &deps[i];
312 if (I->getResult().isNonLocal())
315 // We don't handle non-definitions. If we already have a call, reject
316 // instruction dependencies.
317 if (!I->getResult().isDef() || cdep != 0) {
322 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
323 // FIXME: All duplicated with non-local case.
324 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
325 cdep = NonLocalDepCall;
334 valueNumbering[C] = nextValueNumber;
335 return nextValueNumber++;
338 if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
339 valueNumbering[C] = nextValueNumber;
340 return nextValueNumber++;
342 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
343 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
344 uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
346 valueNumbering[C] = nextValueNumber;
347 return nextValueNumber++;
351 uint32_t v = lookup_or_add(cdep);
352 valueNumbering[C] = v;
356 valueNumbering[C] = nextValueNumber;
357 return nextValueNumber++;
361 /// lookup_or_add - Returns the value number for the specified value, assigning
362 /// it a new number if it did not have one before.
363 uint32_t ValueTable::lookup_or_add(Value *V) {
364 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
365 if (VI != valueNumbering.end())
368 if (!isa<Instruction>(V)) {
369 valueNumbering[V] = nextValueNumber;
370 return nextValueNumber++;
373 Instruction* I = cast<Instruction>(V);
375 switch (I->getOpcode()) {
376 case Instruction::Call: {
377 CallInst *C = cast<CallInst>(I);
378 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(C)) {
379 switch (II->getIntrinsicID()) {
380 case Intrinsic::sadd_with_overflow:
381 case Intrinsic::uadd_with_overflow:
382 exp = create_intrinsic_expression(C, Instruction::Add, true);
384 case Intrinsic::ssub_with_overflow:
385 case Intrinsic::usub_with_overflow:
386 exp = create_intrinsic_expression(C, Instruction::Sub, false);
388 case Intrinsic::smul_with_overflow:
389 case Intrinsic::umul_with_overflow:
390 exp = create_intrinsic_expression(C, Instruction::Mul, true);
393 return lookup_or_add_call(C);
396 return lookup_or_add_call(C);
399 case Instruction::Add:
400 case Instruction::FAdd:
401 case Instruction::Sub:
402 case Instruction::FSub:
403 case Instruction::Mul:
404 case Instruction::FMul:
405 case Instruction::UDiv:
406 case Instruction::SDiv:
407 case Instruction::FDiv:
408 case Instruction::URem:
409 case Instruction::SRem:
410 case Instruction::FRem:
411 case Instruction::Shl:
412 case Instruction::LShr:
413 case Instruction::AShr:
414 case Instruction::And:
415 case Instruction::Or:
416 case Instruction::Xor:
417 case Instruction::ICmp:
418 case Instruction::FCmp:
419 case Instruction::Trunc:
420 case Instruction::ZExt:
421 case Instruction::SExt:
422 case Instruction::FPToUI:
423 case Instruction::FPToSI:
424 case Instruction::UIToFP:
425 case Instruction::SIToFP:
426 case Instruction::FPTrunc:
427 case Instruction::FPExt:
428 case Instruction::PtrToInt:
429 case Instruction::IntToPtr:
430 case Instruction::BitCast:
431 case Instruction::Select:
432 case Instruction::ExtractElement:
433 case Instruction::InsertElement:
434 case Instruction::ShuffleVector:
435 case Instruction::InsertValue:
436 case Instruction::GetElementPtr:
437 case Instruction::ExtractValue:
438 exp = create_expression(I);
441 valueNumbering[V] = nextValueNumber;
442 return nextValueNumber++;
445 uint32_t& e = expressionNumbering[exp];
446 if (!e) e = nextValueNumber++;
447 valueNumbering[V] = e;
451 /// lookup - Returns the value number of the specified value. Fails if
452 /// the value has not yet been numbered.
453 uint32_t ValueTable::lookup(Value *V) const {
454 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
455 assert(VI != valueNumbering.end() && "Value not numbered?");
459 /// lookup_or_add_cmp - Returns the value number of the given comparison,
460 /// assigning it a new number if it did not have one before. Useful when
461 /// we deduced the result of a comparison, but don't immediately have an
462 /// instruction realizing that comparison to hand.
463 uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
464 CmpInst::Predicate Predicate,
465 Value *LHS, Value *RHS) {
466 Expression exp = create_cmp_expression(Opcode, Predicate, LHS, RHS);
467 uint32_t& e = expressionNumbering[exp];
468 if (!e) e = nextValueNumber++;
472 /// clear - Remove all entries from the ValueTable.
473 void ValueTable::clear() {
474 valueNumbering.clear();
475 expressionNumbering.clear();
479 /// erase - Remove a value from the value numbering.
480 void ValueTable::erase(Value *V) {
481 valueNumbering.erase(V);
484 /// verifyRemoved - Verify that the value is removed from all internal data
486 void ValueTable::verifyRemoved(const Value *V) const {
487 for (DenseMap<Value*, uint32_t>::const_iterator
488 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
489 assert(I->first != V && "Inst still occurs in value numbering map!");
493 //===----------------------------------------------------------------------===//
495 //===----------------------------------------------------------------------===//
499 struct AvailableValueInBlock {
500 /// BB - The basic block in question.
503 SimpleVal, // A simple offsetted value that is accessed.
504 LoadVal, // A value produced by a load.
505 MemIntrin, // A memory intrinsic which is loaded from.
506 UndefVal // A UndefValue representing a value from dead block (which
507 // is not yet physically removed from the CFG).
510 /// V - The value that is live out of the block.
511 PointerIntPair<Value *, 2, ValType> Val;
513 /// Offset - The byte offset in Val that is interesting for the load query.
516 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
517 unsigned Offset = 0) {
518 AvailableValueInBlock Res;
520 Res.Val.setPointer(V);
521 Res.Val.setInt(SimpleVal);
526 static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
527 unsigned Offset = 0) {
528 AvailableValueInBlock Res;
530 Res.Val.setPointer(MI);
531 Res.Val.setInt(MemIntrin);
536 static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
537 unsigned Offset = 0) {
538 AvailableValueInBlock Res;
540 Res.Val.setPointer(LI);
541 Res.Val.setInt(LoadVal);
546 static AvailableValueInBlock getUndef(BasicBlock *BB) {
547 AvailableValueInBlock Res;
549 Res.Val.setPointer(0);
550 Res.Val.setInt(UndefVal);
555 bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
556 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
557 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
558 bool isUndefValue() const { return Val.getInt() == UndefVal; }
560 Value *getSimpleValue() const {
561 assert(isSimpleValue() && "Wrong accessor");
562 return Val.getPointer();
565 LoadInst *getCoercedLoadValue() const {
566 assert(isCoercedLoadValue() && "Wrong accessor");
567 return cast<LoadInst>(Val.getPointer());
570 MemIntrinsic *getMemIntrinValue() const {
571 assert(isMemIntrinValue() && "Wrong accessor");
572 return cast<MemIntrinsic>(Val.getPointer());
575 /// MaterializeAdjustedValue - Emit code into this block to adjust the value
576 /// defined here to the specified type. This handles various coercion cases.
577 Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const;
580 class GVN : public FunctionPass {
582 MemoryDependenceAnalysis *MD;
584 const DataLayout *DL;
585 const TargetLibraryInfo *TLI;
586 SetVector<BasicBlock *> DeadBlocks;
590 /// LeaderTable - A mapping from value numbers to lists of Value*'s that
591 /// have that value number. Use findLeader to query it.
592 struct LeaderTableEntry {
594 const BasicBlock *BB;
595 LeaderTableEntry *Next;
597 DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
598 BumpPtrAllocator TableAllocator;
600 SmallVector<Instruction*, 8> InstrsToErase;
602 typedef SmallVector<NonLocalDepResult, 64> LoadDepVect;
603 typedef SmallVector<AvailableValueInBlock, 64> AvailValInBlkVect;
604 typedef SmallVector<BasicBlock*, 64> UnavailBlkVect;
607 static char ID; // Pass identification, replacement for typeid
608 explicit GVN(bool noloads = false)
609 : FunctionPass(ID), NoLoads(noloads), MD(0) {
610 initializeGVNPass(*PassRegistry::getPassRegistry());
613 bool runOnFunction(Function &F) override;
615 /// markInstructionForDeletion - This removes the specified instruction from
616 /// our various maps and marks it for deletion.
617 void markInstructionForDeletion(Instruction *I) {
619 InstrsToErase.push_back(I);
622 const DataLayout *getDataLayout() const { return DL; }
623 DominatorTree &getDominatorTree() const { return *DT; }
624 AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
625 MemoryDependenceAnalysis &getMemDep() const { return *MD; }
627 /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
628 /// its value number.
629 void addToLeaderTable(uint32_t N, Value *V, const BasicBlock *BB) {
630 LeaderTableEntry &Curr = LeaderTable[N];
637 LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
640 Node->Next = Curr.Next;
644 /// removeFromLeaderTable - Scan the list of values corresponding to a given
645 /// value number, and remove the given instruction if encountered.
646 void removeFromLeaderTable(uint32_t N, Instruction *I, BasicBlock *BB) {
647 LeaderTableEntry* Prev = 0;
648 LeaderTableEntry* Curr = &LeaderTable[N];
650 while (Curr->Val != I || Curr->BB != BB) {
656 Prev->Next = Curr->Next;
662 LeaderTableEntry* Next = Curr->Next;
663 Curr->Val = Next->Val;
665 Curr->Next = Next->Next;
670 // List of critical edges to be split between iterations.
671 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
673 // This transformation requires dominator postdominator info
674 void getAnalysisUsage(AnalysisUsage &AU) const override {
675 AU.addRequired<DominatorTreeWrapperPass>();
676 AU.addRequired<TargetLibraryInfo>();
678 AU.addRequired<MemoryDependenceAnalysis>();
679 AU.addRequired<AliasAnalysis>();
681 AU.addPreserved<DominatorTreeWrapperPass>();
682 AU.addPreserved<AliasAnalysis>();
686 // Helper fuctions of redundant load elimination
687 bool processLoad(LoadInst *L);
688 bool processNonLocalLoad(LoadInst *L);
689 void AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
690 AvailValInBlkVect &ValuesPerBlock,
691 UnavailBlkVect &UnavailableBlocks);
692 bool PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
693 UnavailBlkVect &UnavailableBlocks);
695 // Other helper routines
696 bool processInstruction(Instruction *I);
697 bool processBlock(BasicBlock *BB);
698 void dump(DenseMap<uint32_t, Value*> &d);
699 bool iterateOnFunction(Function &F);
700 bool performPRE(Function &F);
701 Value *findLeader(const BasicBlock *BB, uint32_t num);
702 void cleanupGlobalSets();
703 void verifyRemoved(const Instruction *I) const;
704 bool splitCriticalEdges();
705 BasicBlock *splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ);
706 unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
707 const BasicBlockEdge &Root);
708 bool propagateEquality(Value *LHS, Value *RHS, const BasicBlockEdge &Root);
709 bool processFoldableCondBr(BranchInst *BI);
710 void addDeadBlock(BasicBlock *BB);
711 void assignValNumForDeadCode();
717 // createGVNPass - The public interface to this file...
718 FunctionPass *llvm::createGVNPass(bool NoLoads) {
719 return new GVN(NoLoads);
722 INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
723 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
724 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
725 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
726 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
727 INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
729 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
730 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
732 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
733 E = d.end(); I != E; ++I) {
734 errs() << I->first << "\n";
741 /// IsValueFullyAvailableInBlock - Return true if we can prove that the value
742 /// we're analyzing is fully available in the specified block. As we go, keep
743 /// track of which blocks we know are fully alive in FullyAvailableBlocks. This
744 /// map is actually a tri-state map with the following values:
745 /// 0) we know the block *is not* fully available.
746 /// 1) we know the block *is* fully available.
747 /// 2) we do not know whether the block is fully available or not, but we are
748 /// currently speculating that it will be.
749 /// 3) we are speculating for this block and have used that to speculate for
751 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
752 DenseMap<BasicBlock*, char> &FullyAvailableBlocks,
753 uint32_t RecurseDepth) {
754 if (RecurseDepth > MaxRecurseDepth)
757 // Optimistically assume that the block is fully available and check to see
758 // if we already know about this block in one lookup.
759 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
760 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
762 // If the entry already existed for this block, return the precomputed value.
764 // If this is a speculative "available" value, mark it as being used for
765 // speculation of other blocks.
766 if (IV.first->second == 2)
767 IV.first->second = 3;
768 return IV.first->second != 0;
771 // Otherwise, see if it is fully available in all predecessors.
772 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
774 // If this block has no predecessors, it isn't live-in here.
776 goto SpeculationFailure;
778 for (; PI != PE; ++PI)
779 // If the value isn't fully available in one of our predecessors, then it
780 // isn't fully available in this block either. Undo our previous
781 // optimistic assumption and bail out.
782 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks,RecurseDepth+1))
783 goto SpeculationFailure;
787 // SpeculationFailure - If we get here, we found out that this is not, after
788 // all, a fully-available block. We have a problem if we speculated on this and
789 // used the speculation to mark other blocks as available.
791 char &BBVal = FullyAvailableBlocks[BB];
793 // If we didn't speculate on this, just return with it set to false.
799 // If we did speculate on this value, we could have blocks set to 1 that are
800 // incorrect. Walk the (transitive) successors of this block and mark them as
802 SmallVector<BasicBlock*, 32> BBWorklist;
803 BBWorklist.push_back(BB);
806 BasicBlock *Entry = BBWorklist.pop_back_val();
807 // Note that this sets blocks to 0 (unavailable) if they happen to not
808 // already be in FullyAvailableBlocks. This is safe.
809 char &EntryVal = FullyAvailableBlocks[Entry];
810 if (EntryVal == 0) continue; // Already unavailable.
812 // Mark as unavailable.
815 BBWorklist.append(succ_begin(Entry), succ_end(Entry));
816 } while (!BBWorklist.empty());
822 /// CanCoerceMustAliasedValueToLoad - Return true if
823 /// CoerceAvailableValueToLoadType will succeed.
824 static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
826 const DataLayout &DL) {
827 // If the loaded or stored value is an first class array or struct, don't try
828 // to transform them. We need to be able to bitcast to integer.
829 if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
830 StoredVal->getType()->isStructTy() ||
831 StoredVal->getType()->isArrayTy())
834 // The store has to be at least as big as the load.
835 if (DL.getTypeSizeInBits(StoredVal->getType()) <
836 DL.getTypeSizeInBits(LoadTy))
842 /// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
843 /// then a load from a must-aliased pointer of a different type, try to coerce
844 /// the stored value. LoadedTy is the type of the load we want to replace and
845 /// InsertPt is the place to insert new instructions.
847 /// If we can't do it, return null.
848 static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
850 Instruction *InsertPt,
851 const DataLayout &DL) {
852 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, DL))
855 // If this is already the right type, just return it.
856 Type *StoredValTy = StoredVal->getType();
858 uint64_t StoreSize = DL.getTypeSizeInBits(StoredValTy);
859 uint64_t LoadSize = DL.getTypeSizeInBits(LoadedTy);
861 // If the store and reload are the same size, we can always reuse it.
862 if (StoreSize == LoadSize) {
863 // Pointer to Pointer -> use bitcast.
864 if (StoredValTy->getScalarType()->isPointerTy() &&
865 LoadedTy->getScalarType()->isPointerTy())
866 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
868 // Convert source pointers to integers, which can be bitcast.
869 if (StoredValTy->getScalarType()->isPointerTy()) {
870 StoredValTy = DL.getIntPtrType(StoredValTy);
871 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
874 Type *TypeToCastTo = LoadedTy;
875 if (TypeToCastTo->getScalarType()->isPointerTy())
876 TypeToCastTo = DL.getIntPtrType(TypeToCastTo);
878 if (StoredValTy != TypeToCastTo)
879 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
881 // Cast to pointer if the load needs a pointer type.
882 if (LoadedTy->getScalarType()->isPointerTy())
883 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
888 // If the loaded value is smaller than the available value, then we can
889 // extract out a piece from it. If the available value is too small, then we
890 // can't do anything.
891 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
893 // Convert source pointers to integers, which can be manipulated.
894 if (StoredValTy->getScalarType()->isPointerTy()) {
895 StoredValTy = DL.getIntPtrType(StoredValTy);
896 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
899 // Convert vectors and fp to integer, which can be manipulated.
900 if (!StoredValTy->isIntegerTy()) {
901 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
902 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
905 // If this is a big-endian system, we need to shift the value down to the low
906 // bits so that a truncate will work.
907 if (DL.isBigEndian()) {
908 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
909 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
912 // Truncate the integer to the right size now.
913 Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
914 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
916 if (LoadedTy == NewIntTy)
919 // If the result is a pointer, inttoptr.
920 if (LoadedTy->getScalarType()->isPointerTy())
921 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
923 // Otherwise, bitcast.
924 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
927 /// AnalyzeLoadFromClobberingWrite - This function is called when we have a
928 /// memdep query of a load that ends up being a clobbering memory write (store,
929 /// memset, memcpy, memmove). This means that the write *may* provide bits used
930 /// by the load but we can't be sure because the pointers don't mustalias.
932 /// Check this case to see if there is anything more we can do before we give
933 /// up. This returns -1 if we have to give up, or a byte number in the stored
934 /// value of the piece that feeds the load.
935 static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
937 uint64_t WriteSizeInBits,
938 const DataLayout &DL) {
939 // If the loaded or stored value is a first class array or struct, don't try
940 // to transform them. We need to be able to bitcast to integer.
941 if (LoadTy->isStructTy() || LoadTy->isArrayTy())
944 int64_t StoreOffset = 0, LoadOffset = 0;
945 Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr,StoreOffset,&DL);
946 Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, &DL);
947 if (StoreBase != LoadBase)
950 // If the load and store are to the exact same address, they should have been
951 // a must alias. AA must have gotten confused.
952 // FIXME: Study to see if/when this happens. One case is forwarding a memset
953 // to a load from the base of the memset.
955 if (LoadOffset == StoreOffset) {
956 dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
957 << "Base = " << *StoreBase << "\n"
958 << "Store Ptr = " << *WritePtr << "\n"
959 << "Store Offs = " << StoreOffset << "\n"
960 << "Load Ptr = " << *LoadPtr << "\n";
965 // If the load and store don't overlap at all, the store doesn't provide
966 // anything to the load. In this case, they really don't alias at all, AA
967 // must have gotten confused.
968 uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy);
970 if ((WriteSizeInBits & 7) | (LoadSize & 7))
972 uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
976 bool isAAFailure = false;
977 if (StoreOffset < LoadOffset)
978 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
980 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
984 dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
985 << "Base = " << *StoreBase << "\n"
986 << "Store Ptr = " << *WritePtr << "\n"
987 << "Store Offs = " << StoreOffset << "\n"
988 << "Load Ptr = " << *LoadPtr << "\n";
994 // If the Load isn't completely contained within the stored bits, we don't
995 // have all the bits to feed it. We could do something crazy in the future
996 // (issue a smaller load then merge the bits in) but this seems unlikely to be
998 if (StoreOffset > LoadOffset ||
999 StoreOffset+StoreSize < LoadOffset+LoadSize)
1002 // Okay, we can do this transformation. Return the number of bytes into the
1003 // store that the load is.
1004 return LoadOffset-StoreOffset;
1007 /// AnalyzeLoadFromClobberingStore - This function is called when we have a
1008 /// memdep query of a load that ends up being a clobbering store.
1009 static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
1011 const DataLayout &DL) {
1012 // Cannot handle reading from store of first-class aggregate yet.
1013 if (DepSI->getValueOperand()->getType()->isStructTy() ||
1014 DepSI->getValueOperand()->getType()->isArrayTy())
1017 Value *StorePtr = DepSI->getPointerOperand();
1018 uint64_t StoreSize =DL.getTypeSizeInBits(DepSI->getValueOperand()->getType());
1019 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
1020 StorePtr, StoreSize, DL);
1023 /// AnalyzeLoadFromClobberingLoad - This function is called when we have a
1024 /// memdep query of a load that ends up being clobbered by another load. See if
1025 /// the other load can feed into the second load.
1026 static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
1027 LoadInst *DepLI, const DataLayout &DL){
1028 // Cannot handle reading from store of first-class aggregate yet.
1029 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
1032 Value *DepPtr = DepLI->getPointerOperand();
1033 uint64_t DepSize = DL.getTypeSizeInBits(DepLI->getType());
1034 int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, DL);
1035 if (R != -1) return R;
1037 // If we have a load/load clobber an DepLI can be widened to cover this load,
1038 // then we should widen it!
1039 int64_t LoadOffs = 0;
1040 const Value *LoadBase =
1041 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, &DL);
1042 unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
1044 unsigned Size = MemoryDependenceAnalysis::
1045 getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, DL);
1046 if (Size == 0) return -1;
1048 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, DL);
1053 static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
1055 const DataLayout &DL) {
1056 // If the mem operation is a non-constant size, we can't handle it.
1057 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
1058 if (SizeCst == 0) return -1;
1059 uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
1061 // If this is memset, we just need to see if the offset is valid in the size
1063 if (MI->getIntrinsicID() == Intrinsic::memset)
1064 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
1067 // If we have a memcpy/memmove, the only case we can handle is if this is a
1068 // copy from constant memory. In that case, we can read directly from the
1070 MemTransferInst *MTI = cast<MemTransferInst>(MI);
1072 Constant *Src = dyn_cast<Constant>(MTI->getSource());
1073 if (Src == 0) return -1;
1075 GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &DL));
1076 if (GV == 0 || !GV->isConstant()) return -1;
1078 // See if the access is within the bounds of the transfer.
1079 int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
1080 MI->getDest(), MemSizeInBits, DL);
1084 unsigned AS = Src->getType()->getPointerAddressSpace();
1085 // Otherwise, see if we can constant fold a load from the constant with the
1086 // offset applied as appropriate.
1087 Src = ConstantExpr::getBitCast(Src,
1088 Type::getInt8PtrTy(Src->getContext(), AS));
1089 Constant *OffsetCst =
1090 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1091 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
1092 Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
1093 if (ConstantFoldLoadFromConstPtr(Src, &DL))
1099 /// GetStoreValueForLoad - This function is called when we have a
1100 /// memdep query of a load that ends up being a clobbering store. This means
1101 /// that the store provides bits used by the load but we the pointers don't
1102 /// mustalias. Check this case to see if there is anything more we can do
1103 /// before we give up.
1104 static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
1106 Instruction *InsertPt, const DataLayout &DL){
1107 LLVMContext &Ctx = SrcVal->getType()->getContext();
1109 uint64_t StoreSize = (DL.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
1110 uint64_t LoadSize = (DL.getTypeSizeInBits(LoadTy) + 7) / 8;
1112 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1114 // Compute which bits of the stored value are being used by the load. Convert
1115 // to an integer type to start with.
1116 if (SrcVal->getType()->getScalarType()->isPointerTy())
1117 SrcVal = Builder.CreatePtrToInt(SrcVal,
1118 DL.getIntPtrType(SrcVal->getType()));
1119 if (!SrcVal->getType()->isIntegerTy())
1120 SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
1122 // Shift the bits to the least significant depending on endianness.
1124 if (DL.isLittleEndian())
1125 ShiftAmt = Offset*8;
1127 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
1130 SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
1132 if (LoadSize != StoreSize)
1133 SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
1135 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, DL);
1138 /// GetLoadValueForLoad - This function is called when we have a
1139 /// memdep query of a load that ends up being a clobbering load. This means
1140 /// that the load *may* provide bits used by the load but we can't be sure
1141 /// because the pointers don't mustalias. Check this case to see if there is
1142 /// anything more we can do before we give up.
1143 static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
1144 Type *LoadTy, Instruction *InsertPt,
1146 const DataLayout &DL = *gvn.getDataLayout();
1147 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
1148 // widen SrcVal out to a larger load.
1149 unsigned SrcValSize = DL.getTypeStoreSize(SrcVal->getType());
1150 unsigned LoadSize = DL.getTypeStoreSize(LoadTy);
1151 if (Offset+LoadSize > SrcValSize) {
1152 assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
1153 assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
1154 // If we have a load/load clobber an DepLI can be widened to cover this
1155 // load, then we should widen it to the next power of 2 size big enough!
1156 unsigned NewLoadSize = Offset+LoadSize;
1157 if (!isPowerOf2_32(NewLoadSize))
1158 NewLoadSize = NextPowerOf2(NewLoadSize);
1160 Value *PtrVal = SrcVal->getPointerOperand();
1162 // Insert the new load after the old load. This ensures that subsequent
1163 // memdep queries will find the new load. We can't easily remove the old
1164 // load completely because it is already in the value numbering table.
1165 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
1167 IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1168 DestPTy = PointerType::get(DestPTy,
1169 PtrVal->getType()->getPointerAddressSpace());
1170 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
1171 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1172 LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1173 NewLoad->takeName(SrcVal);
1174 NewLoad->setAlignment(SrcVal->getAlignment());
1176 DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1177 DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1179 // Replace uses of the original load with the wider load. On a big endian
1180 // system, we need to shift down to get the relevant bits.
1181 Value *RV = NewLoad;
1182 if (DL.isBigEndian())
1183 RV = Builder.CreateLShr(RV,
1184 NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
1185 RV = Builder.CreateTrunc(RV, SrcVal->getType());
1186 SrcVal->replaceAllUsesWith(RV);
1188 // We would like to use gvn.markInstructionForDeletion here, but we can't
1189 // because the load is already memoized into the leader map table that GVN
1190 // tracks. It is potentially possible to remove the load from the table,
1191 // but then there all of the operations based on it would need to be
1192 // rehashed. Just leave the dead load around.
1193 gvn.getMemDep().removeInstruction(SrcVal);
1197 return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, DL);
1201 /// GetMemInstValueForLoad - This function is called when we have a
1202 /// memdep query of a load that ends up being a clobbering mem intrinsic.
1203 static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
1204 Type *LoadTy, Instruction *InsertPt,
1205 const DataLayout &DL){
1206 LLVMContext &Ctx = LoadTy->getContext();
1207 uint64_t LoadSize = DL.getTypeSizeInBits(LoadTy)/8;
1209 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1211 // We know that this method is only called when the mem transfer fully
1212 // provides the bits for the load.
1213 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1214 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1215 // independently of what the offset is.
1216 Value *Val = MSI->getValue();
1218 Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1220 Value *OneElt = Val;
1222 // Splat the value out to the right number of bits.
1223 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1224 // If we can double the number of bytes set, do it.
1225 if (NumBytesSet*2 <= LoadSize) {
1226 Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1227 Val = Builder.CreateOr(Val, ShVal);
1232 // Otherwise insert one byte at a time.
1233 Value *ShVal = Builder.CreateShl(Val, 1*8);
1234 Val = Builder.CreateOr(OneElt, ShVal);
1238 return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, DL);
1241 // Otherwise, this is a memcpy/memmove from a constant global.
1242 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1243 Constant *Src = cast<Constant>(MTI->getSource());
1244 unsigned AS = Src->getType()->getPointerAddressSpace();
1246 // Otherwise, see if we can constant fold a load from the constant with the
1247 // offset applied as appropriate.
1248 Src = ConstantExpr::getBitCast(Src,
1249 Type::getInt8PtrTy(Src->getContext(), AS));
1250 Constant *OffsetCst =
1251 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1252 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
1253 Src = ConstantExpr::getBitCast(Src, PointerType::get(LoadTy, AS));
1254 return ConstantFoldLoadFromConstPtr(Src, &DL);
1258 /// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1259 /// construct SSA form, allowing us to eliminate LI. This returns the value
1260 /// that should be used at LI's definition site.
1261 static Value *ConstructSSAForLoadSet(LoadInst *LI,
1262 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1264 // Check for the fully redundant, dominating load case. In this case, we can
1265 // just use the dominating value directly.
1266 if (ValuesPerBlock.size() == 1 &&
1267 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1269 assert(!ValuesPerBlock[0].isUndefValue() && "Dead BB dominate this block");
1270 return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
1273 // Otherwise, we have to construct SSA form.
1274 SmallVector<PHINode*, 8> NewPHIs;
1275 SSAUpdater SSAUpdate(&NewPHIs);
1276 SSAUpdate.Initialize(LI->getType(), LI->getName());
1278 Type *LoadTy = LI->getType();
1280 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1281 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1282 BasicBlock *BB = AV.BB;
1284 if (SSAUpdate.HasValueForBlock(BB))
1287 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
1290 // Perform PHI construction.
1291 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1293 // If new PHI nodes were created, notify alias analysis.
1294 if (V->getType()->getScalarType()->isPointerTy()) {
1295 AliasAnalysis *AA = gvn.getAliasAnalysis();
1297 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1298 AA->copyValue(LI, NewPHIs[i]);
1300 // Now that we've copied information to the new PHIs, scan through
1301 // them again and inform alias analysis that we've added potentially
1302 // escaping uses to any values that are operands to these PHIs.
1303 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1304 PHINode *P = NewPHIs[i];
1305 for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
1306 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
1307 AA->addEscapingUse(P->getOperandUse(jj));
1315 Value *AvailableValueInBlock::MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
1317 if (isSimpleValue()) {
1318 Res = getSimpleValue();
1319 if (Res->getType() != LoadTy) {
1320 const DataLayout *DL = gvn.getDataLayout();
1321 assert(DL && "Need target data to handle type mismatch case");
1322 Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1325 DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
1326 << *getSimpleValue() << '\n'
1327 << *Res << '\n' << "\n\n\n");
1329 } else if (isCoercedLoadValue()) {
1330 LoadInst *Load = getCoercedLoadValue();
1331 if (Load->getType() == LoadTy && Offset == 0) {
1334 Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
1337 DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
1338 << *getCoercedLoadValue() << '\n'
1339 << *Res << '\n' << "\n\n\n");
1341 } else if (isMemIntrinValue()) {
1342 const DataLayout *DL = gvn.getDataLayout();
1343 assert(DL && "Need target data to handle type mismatch case");
1344 Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1345 LoadTy, BB->getTerminator(), *DL);
1346 DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1347 << " " << *getMemIntrinValue() << '\n'
1348 << *Res << '\n' << "\n\n\n");
1350 assert(isUndefValue() && "Should be UndefVal");
1351 DEBUG(dbgs() << "GVN COERCED NONLOCAL Undef:\n";);
1352 return UndefValue::get(LoadTy);
1357 static bool isLifetimeStart(const Instruction *Inst) {
1358 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1359 return II->getIntrinsicID() == Intrinsic::lifetime_start;
1363 void GVN::AnalyzeLoadAvailability(LoadInst *LI, LoadDepVect &Deps,
1364 AvailValInBlkVect &ValuesPerBlock,
1365 UnavailBlkVect &UnavailableBlocks) {
1367 // Filter out useless results (non-locals, etc). Keep track of the blocks
1368 // where we have a value available in repl, also keep track of whether we see
1369 // dependencies that produce an unknown value for the load (such as a call
1370 // that could potentially clobber the load).
1371 unsigned NumDeps = Deps.size();
1372 for (unsigned i = 0, e = NumDeps; i != e; ++i) {
1373 BasicBlock *DepBB = Deps[i].getBB();
1374 MemDepResult DepInfo = Deps[i].getResult();
1376 if (DeadBlocks.count(DepBB)) {
1377 // Dead dependent mem-op disguise as a load evaluating the same value
1378 // as the load in question.
1379 ValuesPerBlock.push_back(AvailableValueInBlock::getUndef(DepBB));
1383 if (!DepInfo.isDef() && !DepInfo.isClobber()) {
1384 UnavailableBlocks.push_back(DepBB);
1388 if (DepInfo.isClobber()) {
1389 // The address being loaded in this non-local block may not be the same as
1390 // the pointer operand of the load if PHI translation occurs. Make sure
1391 // to consider the right address.
1392 Value *Address = Deps[i].getAddress();
1394 // If the dependence is to a store that writes to a superset of the bits
1395 // read by the load, we can extract the bits we need for the load from the
1397 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1398 if (DL && Address) {
1399 int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
1402 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1403 DepSI->getValueOperand(),
1410 // Check to see if we have something like this:
1413 // if we have this, replace the later with an extraction from the former.
1414 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1415 // If this is a clobber and L is the first instruction in its block, then
1416 // we have the first instruction in the entry block.
1417 if (DepLI != LI && Address && DL) {
1418 int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1419 LI->getPointerOperand(),
1423 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1430 // If the clobbering value is a memset/memcpy/memmove, see if we can
1431 // forward a value on from it.
1432 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
1433 if (DL && Address) {
1434 int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
1437 ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1444 UnavailableBlocks.push_back(DepBB);
1448 // DepInfo.isDef() here
1450 Instruction *DepInst = DepInfo.getInst();
1452 // Loading the allocation -> undef.
1453 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI) ||
1454 // Loading immediately after lifetime begin -> undef.
1455 isLifetimeStart(DepInst)) {
1456 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1457 UndefValue::get(LI->getType())));
1461 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1462 // Reject loads and stores that are to the same address but are of
1463 // different types if we have to.
1464 if (S->getValueOperand()->getType() != LI->getType()) {
1465 // If the stored value is larger or equal to the loaded value, we can
1467 if (DL == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
1468 LI->getType(), *DL)) {
1469 UnavailableBlocks.push_back(DepBB);
1474 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1475 S->getValueOperand()));
1479 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1480 // If the types mismatch and we can't handle it, reject reuse of the load.
1481 if (LD->getType() != LI->getType()) {
1482 // If the stored value is larger or equal to the loaded value, we can
1484 if (DL == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*DL)){
1485 UnavailableBlocks.push_back(DepBB);
1489 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
1493 UnavailableBlocks.push_back(DepBB);
1497 bool GVN::PerformLoadPRE(LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
1498 UnavailBlkVect &UnavailableBlocks) {
1499 // Okay, we have *some* definitions of the value. This means that the value
1500 // is available in some of our (transitive) predecessors. Lets think about
1501 // doing PRE of this load. This will involve inserting a new load into the
1502 // predecessor when it's not available. We could do this in general, but
1503 // prefer to not increase code size. As such, we only do this when we know
1504 // that we only have to insert *one* load (which means we're basically moving
1505 // the load, not inserting a new one).
1507 SmallPtrSet<BasicBlock *, 4> Blockers;
1508 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1509 Blockers.insert(UnavailableBlocks[i]);
1511 // Let's find the first basic block with more than one predecessor. Walk
1512 // backwards through predecessors if needed.
1513 BasicBlock *LoadBB = LI->getParent();
1514 BasicBlock *TmpBB = LoadBB;
1516 while (TmpBB->getSinglePredecessor()) {
1517 TmpBB = TmpBB->getSinglePredecessor();
1518 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1520 if (Blockers.count(TmpBB))
1523 // If any of these blocks has more than one successor (i.e. if the edge we
1524 // just traversed was critical), then there are other paths through this
1525 // block along which the load may not be anticipated. Hoisting the load
1526 // above this block would be adding the load to execution paths along
1527 // which it was not previously executed.
1528 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1535 // Check to see how many predecessors have the loaded value fully
1537 DenseMap<BasicBlock*, Value*> PredLoads;
1538 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1539 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1540 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
1541 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1542 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1544 SmallVector<BasicBlock *, 4> CriticalEdgePred;
1545 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1547 BasicBlock *Pred = *PI;
1548 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks, 0)) {
1551 PredLoads[Pred] = 0;
1553 if (Pred->getTerminator()->getNumSuccessors() != 1) {
1554 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1555 DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1556 << Pred->getName() << "': " << *LI << '\n');
1560 if (LoadBB->isLandingPad()) {
1562 << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
1563 << Pred->getName() << "': " << *LI << '\n');
1567 CriticalEdgePred.push_back(Pred);
1571 // Decide whether PRE is profitable for this load.
1572 unsigned NumUnavailablePreds = PredLoads.size();
1573 assert(NumUnavailablePreds != 0 &&
1574 "Fully available value should already be eliminated!");
1576 // If this load is unavailable in multiple predecessors, reject it.
1577 // FIXME: If we could restructure the CFG, we could make a common pred with
1578 // all the preds that don't have an available LI and insert a new load into
1580 if (NumUnavailablePreds != 1)
1583 // Split critical edges, and update the unavailable predecessors accordingly.
1584 for (SmallVectorImpl<BasicBlock *>::iterator I = CriticalEdgePred.begin(),
1585 E = CriticalEdgePred.end(); I != E; I++) {
1586 BasicBlock *OrigPred = *I;
1587 BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
1588 PredLoads.erase(OrigPred);
1589 PredLoads[NewPred] = 0;
1590 DEBUG(dbgs() << "Split critical edge " << OrigPred->getName() << "->"
1591 << LoadBB->getName() << '\n');
1594 // Check if the load can safely be moved to all the unavailable predecessors.
1595 bool CanDoPRE = true;
1596 SmallVector<Instruction*, 8> NewInsts;
1597 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1598 E = PredLoads.end(); I != E; ++I) {
1599 BasicBlock *UnavailablePred = I->first;
1601 // Do PHI translation to get its value in the predecessor if necessary. The
1602 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1604 // If all preds have a single successor, then we know it is safe to insert
1605 // the load on the pred (?!?), so we can insert code to materialize the
1606 // pointer if it is not available.
1607 PHITransAddr Address(LI->getPointerOperand(), DL);
1609 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1612 // If we couldn't find or insert a computation of this phi translated value,
1615 DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1616 << *LI->getPointerOperand() << "\n");
1621 I->second = LoadPtr;
1625 while (!NewInsts.empty()) {
1626 Instruction *I = NewInsts.pop_back_val();
1627 if (MD) MD->removeInstruction(I);
1628 I->eraseFromParent();
1630 // HINT:Don't revert the edge-splitting as following transformation may
1631 // also need to split these critial edges.
1632 return !CriticalEdgePred.empty();
1635 // Okay, we can eliminate this load by inserting a reload in the predecessor
1636 // and using PHI construction to get the value in the other predecessors, do
1638 DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1639 DEBUG(if (!NewInsts.empty())
1640 dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
1641 << *NewInsts.back() << '\n');
1643 // Assign value numbers to the new instructions.
1644 for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
1645 // FIXME: We really _ought_ to insert these value numbers into their
1646 // parent's availability map. However, in doing so, we risk getting into
1647 // ordering issues. If a block hasn't been processed yet, we would be
1648 // marking a value as AVAIL-IN, which isn't what we intend.
1649 VN.lookup_or_add(NewInsts[i]);
1652 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1653 E = PredLoads.end(); I != E; ++I) {
1654 BasicBlock *UnavailablePred = I->first;
1655 Value *LoadPtr = I->second;
1657 Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1659 UnavailablePred->getTerminator());
1661 // Transfer the old load's TBAA tag to the new load.
1662 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1663 NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1665 // Transfer DebugLoc.
1666 NewLoad->setDebugLoc(LI->getDebugLoc());
1668 // Add the newly created load.
1669 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1671 MD->invalidateCachedPointerInfo(LoadPtr);
1672 DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1675 // Perform PHI construction.
1676 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1677 LI->replaceAllUsesWith(V);
1678 if (isa<PHINode>(V))
1680 if (V->getType()->getScalarType()->isPointerTy())
1681 MD->invalidateCachedPointerInfo(V);
1682 markInstructionForDeletion(LI);
1687 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1688 /// non-local by performing PHI construction.
1689 bool GVN::processNonLocalLoad(LoadInst *LI) {
1690 // Step 1: Find the non-local dependencies of the load.
1692 AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1693 MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
1695 // If we had to process more than one hundred blocks to find the
1696 // dependencies, this load isn't worth worrying about. Optimizing
1697 // it will be too expensive.
1698 unsigned NumDeps = Deps.size();
1702 // If we had a phi translation failure, we'll have a single entry which is a
1703 // clobber in the current block. Reject this early.
1705 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1707 dbgs() << "GVN: non-local load ";
1708 LI->printAsOperand(dbgs());
1709 dbgs() << " has unknown dependencies\n";
1714 // Step 2: Analyze the availability of the load
1715 AvailValInBlkVect ValuesPerBlock;
1716 UnavailBlkVect UnavailableBlocks;
1717 AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
1719 // If we have no predecessors that produce a known value for this load, exit
1721 if (ValuesPerBlock.empty())
1724 // Step 3: Eliminate fully redundancy.
1726 // If all of the instructions we depend on produce a known value for this
1727 // load, then it is fully redundant and we can use PHI insertion to compute
1728 // its value. Insert PHIs and remove the fully redundant value now.
1729 if (UnavailableBlocks.empty()) {
1730 DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1732 // Perform PHI construction.
1733 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1734 LI->replaceAllUsesWith(V);
1736 if (isa<PHINode>(V))
1738 if (V->getType()->getScalarType()->isPointerTy())
1739 MD->invalidateCachedPointerInfo(V);
1740 markInstructionForDeletion(LI);
1745 // Step 4: Eliminate partial redundancy.
1746 if (!EnablePRE || !EnableLoadPRE)
1749 return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
1753 static void patchReplacementInstruction(Instruction *I, Value *Repl) {
1754 // Patch the replacement so that it is not more restrictive than the value
1756 BinaryOperator *Op = dyn_cast<BinaryOperator>(I);
1757 BinaryOperator *ReplOp = dyn_cast<BinaryOperator>(Repl);
1758 if (Op && ReplOp && isa<OverflowingBinaryOperator>(Op) &&
1759 isa<OverflowingBinaryOperator>(ReplOp)) {
1760 if (ReplOp->hasNoSignedWrap() && !Op->hasNoSignedWrap())
1761 ReplOp->setHasNoSignedWrap(false);
1762 if (ReplOp->hasNoUnsignedWrap() && !Op->hasNoUnsignedWrap())
1763 ReplOp->setHasNoUnsignedWrap(false);
1765 if (Instruction *ReplInst = dyn_cast<Instruction>(Repl)) {
1766 SmallVector<std::pair<unsigned, MDNode*>, 4> Metadata;
1767 ReplInst->getAllMetadataOtherThanDebugLoc(Metadata);
1768 for (int i = 0, n = Metadata.size(); i < n; ++i) {
1769 unsigned Kind = Metadata[i].first;
1770 MDNode *IMD = I->getMetadata(Kind);
1771 MDNode *ReplMD = Metadata[i].second;
1774 ReplInst->setMetadata(Kind, NULL); // Remove unknown metadata
1776 case LLVMContext::MD_dbg:
1777 llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
1778 case LLVMContext::MD_tbaa:
1779 ReplInst->setMetadata(Kind, MDNode::getMostGenericTBAA(IMD, ReplMD));
1781 case LLVMContext::MD_range:
1782 ReplInst->setMetadata(Kind, MDNode::getMostGenericRange(IMD, ReplMD));
1784 case LLVMContext::MD_prof:
1785 llvm_unreachable("MD_prof in a non-terminator instruction");
1787 case LLVMContext::MD_fpmath:
1788 ReplInst->setMetadata(Kind, MDNode::getMostGenericFPMath(IMD, ReplMD));
1795 static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl) {
1796 patchReplacementInstruction(I, Repl);
1797 I->replaceAllUsesWith(Repl);
1800 /// processLoad - Attempt to eliminate a load, first by eliminating it
1801 /// locally, and then attempting non-local elimination if that fails.
1802 bool GVN::processLoad(LoadInst *L) {
1809 if (L->use_empty()) {
1810 markInstructionForDeletion(L);
1814 // ... to a pointer that has been loaded from before...
1815 MemDepResult Dep = MD->getDependency(L);
1817 // If we have a clobber and target data is around, see if this is a clobber
1818 // that we can fix up through code synthesis.
1819 if (Dep.isClobber() && DL) {
1820 // Check to see if we have something like this:
1821 // store i32 123, i32* %P
1822 // %A = bitcast i32* %P to i8*
1823 // %B = gep i8* %A, i32 1
1826 // We could do that by recognizing if the clobber instructions are obviously
1827 // a common base + constant offset, and if the previous store (or memset)
1828 // completely covers this load. This sort of thing can happen in bitfield
1830 Value *AvailVal = 0;
1831 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1832 int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1833 L->getPointerOperand(),
1836 AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1837 L->getType(), L, *DL);
1840 // Check to see if we have something like this:
1843 // if we have this, replace the later with an extraction from the former.
1844 if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1845 // If this is a clobber and L is the first instruction in its block, then
1846 // we have the first instruction in the entry block.
1850 int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1851 L->getPointerOperand(),
1854 AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
1857 // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1858 // a value on from it.
1859 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
1860 int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1861 L->getPointerOperand(),
1864 AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *DL);
1868 DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
1869 << *AvailVal << '\n' << *L << "\n\n\n");
1871 // Replace the load!
1872 L->replaceAllUsesWith(AvailVal);
1873 if (AvailVal->getType()->getScalarType()->isPointerTy())
1874 MD->invalidateCachedPointerInfo(AvailVal);
1875 markInstructionForDeletion(L);
1881 // If the value isn't available, don't do anything!
1882 if (Dep.isClobber()) {
1884 // fast print dep, using operator<< on instruction is too slow.
1885 dbgs() << "GVN: load ";
1886 L->printAsOperand(dbgs());
1887 Instruction *I = Dep.getInst();
1888 dbgs() << " is clobbered by " << *I << '\n';
1893 // If it is defined in another block, try harder.
1894 if (Dep.isNonLocal())
1895 return processNonLocalLoad(L);
1899 // fast print dep, using operator<< on instruction is too slow.
1900 dbgs() << "GVN: load ";
1901 L->printAsOperand(dbgs());
1902 dbgs() << " has unknown dependence\n";
1907 Instruction *DepInst = Dep.getInst();
1908 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1909 Value *StoredVal = DepSI->getValueOperand();
1911 // The store and load are to a must-aliased pointer, but they may not
1912 // actually have the same type. See if we know how to reuse the stored
1913 // value (depending on its type).
1914 if (StoredVal->getType() != L->getType()) {
1916 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1921 DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1922 << '\n' << *L << "\n\n\n");
1929 L->replaceAllUsesWith(StoredVal);
1930 if (StoredVal->getType()->getScalarType()->isPointerTy())
1931 MD->invalidateCachedPointerInfo(StoredVal);
1932 markInstructionForDeletion(L);
1937 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1938 Value *AvailableVal = DepLI;
1940 // The loads are of a must-aliased pointer, but they may not actually have
1941 // the same type. See if we know how to reuse the previously loaded value
1942 // (depending on its type).
1943 if (DepLI->getType() != L->getType()) {
1945 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1947 if (AvailableVal == 0)
1950 DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1951 << "\n" << *L << "\n\n\n");
1958 patchAndReplaceAllUsesWith(L, AvailableVal);
1959 if (DepLI->getType()->getScalarType()->isPointerTy())
1960 MD->invalidateCachedPointerInfo(DepLI);
1961 markInstructionForDeletion(L);
1966 // If this load really doesn't depend on anything, then we must be loading an
1967 // undef value. This can happen when loading for a fresh allocation with no
1968 // intervening stores, for example.
1969 if (isa<AllocaInst>(DepInst) || isMallocLikeFn(DepInst, TLI)) {
1970 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1971 markInstructionForDeletion(L);
1976 // If this load occurs either right after a lifetime begin,
1977 // then the loaded value is undefined.
1978 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
1979 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1980 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1981 markInstructionForDeletion(L);
1990 // findLeader - In order to find a leader for a given value number at a
1991 // specific basic block, we first obtain the list of all Values for that number,
1992 // and then scan the list to find one whose block dominates the block in
1993 // question. This is fast because dominator tree queries consist of only
1994 // a few comparisons of DFS numbers.
1995 Value *GVN::findLeader(const BasicBlock *BB, uint32_t num) {
1996 LeaderTableEntry Vals = LeaderTable[num];
1997 if (!Vals.Val) return 0;
2000 if (DT->dominates(Vals.BB, BB)) {
2002 if (isa<Constant>(Val)) return Val;
2005 LeaderTableEntry* Next = Vals.Next;
2007 if (DT->dominates(Next->BB, BB)) {
2008 if (isa<Constant>(Next->Val)) return Next->Val;
2009 if (!Val) Val = Next->Val;
2018 /// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
2019 /// use is dominated by the given basic block. Returns the number of uses that
2021 unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
2022 const BasicBlockEdge &Root) {
2024 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
2028 if (DT->dominates(Root, U)) {
2036 /// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'. Return
2037 /// true if every path from the entry block to 'Dst' passes via this edge. In
2038 /// particular 'Dst' must not be reachable via another edge from 'Src'.
2039 static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E,
2040 DominatorTree *DT) {
2041 // While in theory it is interesting to consider the case in which Dst has
2042 // more than one predecessor, because Dst might be part of a loop which is
2043 // only reachable from Src, in practice it is pointless since at the time
2044 // GVN runs all such loops have preheaders, which means that Dst will have
2045 // been changed to have only one predecessor, namely Src.
2046 const BasicBlock *Pred = E.getEnd()->getSinglePredecessor();
2047 const BasicBlock *Src = E.getStart();
2048 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
2053 /// propagateEquality - The given values are known to be equal in every block
2054 /// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
2055 /// 'RHS' everywhere in the scope. Returns whether a change was made.
2056 bool GVN::propagateEquality(Value *LHS, Value *RHS,
2057 const BasicBlockEdge &Root) {
2058 SmallVector<std::pair<Value*, Value*>, 4> Worklist;
2059 Worklist.push_back(std::make_pair(LHS, RHS));
2060 bool Changed = false;
2061 // For speed, compute a conservative fast approximation to
2062 // DT->dominates(Root, Root.getEnd());
2063 bool RootDominatesEnd = isOnlyReachableViaThisEdge(Root, DT);
2065 while (!Worklist.empty()) {
2066 std::pair<Value*, Value*> Item = Worklist.pop_back_val();
2067 LHS = Item.first; RHS = Item.second;
2069 if (LHS == RHS) continue;
2070 assert(LHS->getType() == RHS->getType() && "Equality but unequal types!");
2072 // Don't try to propagate equalities between constants.
2073 if (isa<Constant>(LHS) && isa<Constant>(RHS)) continue;
2075 // Prefer a constant on the right-hand side, or an Argument if no constants.
2076 if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
2077 std::swap(LHS, RHS);
2078 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
2080 // If there is no obvious reason to prefer the left-hand side over the right-
2081 // hand side, ensure the longest lived term is on the right-hand side, so the
2082 // shortest lived term will be replaced by the longest lived. This tends to
2083 // expose more simplifications.
2084 uint32_t LVN = VN.lookup_or_add(LHS);
2085 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
2086 (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
2087 // Move the 'oldest' value to the right-hand side, using the value number as
2089 uint32_t RVN = VN.lookup_or_add(RHS);
2091 std::swap(LHS, RHS);
2096 // If value numbering later sees that an instruction in the scope is equal
2097 // to 'LHS' then ensure it will be turned into 'RHS'. In order to preserve
2098 // the invariant that instructions only occur in the leader table for their
2099 // own value number (this is used by removeFromLeaderTable), do not do this
2100 // if RHS is an instruction (if an instruction in the scope is morphed into
2101 // LHS then it will be turned into RHS by the next GVN iteration anyway, so
2102 // using the leader table is about compiling faster, not optimizing better).
2103 // The leader table only tracks basic blocks, not edges. Only add to if we
2104 // have the simple case where the edge dominates the end.
2105 if (RootDominatesEnd && !isa<Instruction>(RHS))
2106 addToLeaderTable(LVN, RHS, Root.getEnd());
2108 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
2109 // LHS always has at least one use that is not dominated by Root, this will
2110 // never do anything if LHS has only one use.
2111 if (!LHS->hasOneUse()) {
2112 unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
2113 Changed |= NumReplacements > 0;
2114 NumGVNEqProp += NumReplacements;
2117 // Now try to deduce additional equalities from this one. For example, if the
2118 // known equality was "(A != B)" == "false" then it follows that A and B are
2119 // equal in the scope. Only boolean equalities with an explicit true or false
2120 // RHS are currently supported.
2121 if (!RHS->getType()->isIntegerTy(1))
2122 // Not a boolean equality - bail out.
2124 ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
2126 // RHS neither 'true' nor 'false' - bail out.
2128 // Whether RHS equals 'true'. Otherwise it equals 'false'.
2129 bool isKnownTrue = CI->isAllOnesValue();
2130 bool isKnownFalse = !isKnownTrue;
2132 // If "A && B" is known true then both A and B are known true. If "A || B"
2133 // is known false then both A and B are known false.
2135 if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
2136 (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
2137 Worklist.push_back(std::make_pair(A, RHS));
2138 Worklist.push_back(std::make_pair(B, RHS));
2142 // If we are propagating an equality like "(A == B)" == "true" then also
2143 // propagate the equality A == B. When propagating a comparison such as
2144 // "(A >= B)" == "true", replace all instances of "A < B" with "false".
2145 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
2146 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
2148 // If "A == B" is known true, or "A != B" is known false, then replace
2149 // A with B everywhere in the scope.
2150 if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
2151 (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
2152 Worklist.push_back(std::make_pair(Op0, Op1));
2154 // If "A >= B" is known true, replace "A < B" with false everywhere.
2155 CmpInst::Predicate NotPred = Cmp->getInversePredicate();
2156 Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
2157 // Since we don't have the instruction "A < B" immediately to hand, work out
2158 // the value number that it would have and use that to find an appropriate
2159 // instruction (if any).
2160 uint32_t NextNum = VN.getNextUnusedValueNumber();
2161 uint32_t Num = VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0, Op1);
2162 // If the number we were assigned was brand new then there is no point in
2163 // looking for an instruction realizing it: there cannot be one!
2164 if (Num < NextNum) {
2165 Value *NotCmp = findLeader(Root.getEnd(), Num);
2166 if (NotCmp && isa<Instruction>(NotCmp)) {
2167 unsigned NumReplacements =
2168 replaceAllDominatedUsesWith(NotCmp, NotVal, Root);
2169 Changed |= NumReplacements > 0;
2170 NumGVNEqProp += NumReplacements;
2173 // Ensure that any instruction in scope that gets the "A < B" value number
2174 // is replaced with false.
2175 // The leader table only tracks basic blocks, not edges. Only add to if we
2176 // have the simple case where the edge dominates the end.
2177 if (RootDominatesEnd)
2178 addToLeaderTable(Num, NotVal, Root.getEnd());
2187 static bool normalOpAfterIntrinsic(Instruction *I, Value *Repl)
2189 switch (I->getOpcode()) {
2190 case Instruction::Add:
2191 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Repl))
2192 return II->getIntrinsicID() == Intrinsic::sadd_with_overflow
2193 || II->getIntrinsicID() == Intrinsic::uadd_with_overflow;
2195 case Instruction::Sub:
2196 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Repl))
2197 return II->getIntrinsicID() == Intrinsic::ssub_with_overflow
2198 || II->getIntrinsicID() == Intrinsic::usub_with_overflow;
2200 case Instruction::Mul:
2201 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Repl))
2202 return II->getIntrinsicID() == Intrinsic::smul_with_overflow
2203 || II->getIntrinsicID() == Intrinsic::umul_with_overflow;
2210 static bool intrinsicAterNormalOp(Instruction *I, Value *Repl)
2212 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2216 Instruction *RI = dyn_cast<Instruction>(Repl);
2220 switch (RI->getOpcode()) {
2221 case Instruction::Add:
2222 return II->getIntrinsicID() == Intrinsic::sadd_with_overflow
2223 || II->getIntrinsicID() == Intrinsic::uadd_with_overflow;
2224 case Instruction::Sub:
2225 return II->getIntrinsicID() == Intrinsic::ssub_with_overflow
2226 || II->getIntrinsicID() == Intrinsic::usub_with_overflow;
2227 case Instruction::Mul:
2228 return II->getIntrinsicID() == Intrinsic::smul_with_overflow
2229 || II->getIntrinsicID() == Intrinsic::umul_with_overflow;
2235 /// processInstruction - When calculating availability, handle an instruction
2236 /// by inserting it into the appropriate sets
2237 bool GVN::processInstruction(Instruction *I) {
2238 // Ignore dbg info intrinsics.
2239 if (isa<DbgInfoIntrinsic>(I))
2242 // If the instruction can be easily simplified then do so now in preference
2243 // to value numbering it. Value numbering often exposes redundancies, for
2244 // example if it determines that %y is equal to %x then the instruction
2245 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
2246 if (Value *V = SimplifyInstruction(I, DL, TLI, DT)) {
2247 I->replaceAllUsesWith(V);
2248 if (MD && V->getType()->getScalarType()->isPointerTy())
2249 MD->invalidateCachedPointerInfo(V);
2250 markInstructionForDeletion(I);
2255 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2256 if (processLoad(LI))
2259 unsigned Num = VN.lookup_or_add(LI);
2260 addToLeaderTable(Num, LI, LI->getParent());
2264 // For conditional branches, we can perform simple conditional propagation on
2265 // the condition value itself.
2266 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
2267 if (!BI->isConditional())
2270 if (isa<Constant>(BI->getCondition()))
2271 return processFoldableCondBr(BI);
2273 Value *BranchCond = BI->getCondition();
2274 BasicBlock *TrueSucc = BI->getSuccessor(0);
2275 BasicBlock *FalseSucc = BI->getSuccessor(1);
2276 // Avoid multiple edges early.
2277 if (TrueSucc == FalseSucc)
2280 BasicBlock *Parent = BI->getParent();
2281 bool Changed = false;
2283 Value *TrueVal = ConstantInt::getTrue(TrueSucc->getContext());
2284 BasicBlockEdge TrueE(Parent, TrueSucc);
2285 Changed |= propagateEquality(BranchCond, TrueVal, TrueE);
2287 Value *FalseVal = ConstantInt::getFalse(FalseSucc->getContext());
2288 BasicBlockEdge FalseE(Parent, FalseSucc);
2289 Changed |= propagateEquality(BranchCond, FalseVal, FalseE);
2294 // For switches, propagate the case values into the case destinations.
2295 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2296 Value *SwitchCond = SI->getCondition();
2297 BasicBlock *Parent = SI->getParent();
2298 bool Changed = false;
2300 // Remember how many outgoing edges there are to every successor.
2301 SmallDenseMap<BasicBlock *, unsigned, 16> SwitchEdges;
2302 for (unsigned i = 0, n = SI->getNumSuccessors(); i != n; ++i)
2303 ++SwitchEdges[SI->getSuccessor(i)];
2305 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2307 BasicBlock *Dst = i.getCaseSuccessor();
2308 // If there is only a single edge, propagate the case value into it.
2309 if (SwitchEdges.lookup(Dst) == 1) {
2310 BasicBlockEdge E(Parent, Dst);
2311 Changed |= propagateEquality(SwitchCond, i.getCaseValue(), E);
2317 // Instructions with void type don't return a value, so there's
2318 // no point in trying to find redundancies in them.
2319 if (I->getType()->isVoidTy()) return false;
2321 uint32_t NextNum = VN.getNextUnusedValueNumber();
2322 unsigned Num = VN.lookup_or_add(I);
2324 // Allocations are always uniquely numbered, so we can save time and memory
2325 // by fast failing them.
2326 if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
2327 addToLeaderTable(Num, I, I->getParent());
2331 // If the number we were assigned was a brand new VN, then we don't
2332 // need to do a lookup to see if the number already exists
2333 // somewhere in the domtree: it can't!
2334 if (Num >= NextNum) {
2335 addToLeaderTable(Num, I, I->getParent());
2339 // Perform fast-path value-number based elimination of values inherited from
2341 Value *repl = findLeader(I->getParent(), Num);
2343 // Failure, just remember this instance for future use.
2344 addToLeaderTable(Num, I, I->getParent());
2348 if (normalOpAfterIntrinsic(I, repl)) {
2349 // An intrinsic followed by a normal operation (e.g. sadd_with_overflow
2350 // followed by a sadd): replace the second instruction with an extract.
2351 IntrinsicInst *II = cast<IntrinsicInst>(repl);
2353 repl = ExtractValueInst::Create(II, 0, I->getName() + ".repl", I);
2354 } else if (intrinsicAterNormalOp(I, repl)) {
2355 // A normal operation followed by an intrinsic (e.g. sadd followed by a
2356 // sadd_with_overflow).
2357 // Clone the intrinsic, and insert it before the replacing instruction. Then
2358 // replace the (current) instruction with the cloned one. In a subsequent
2359 // run, the original replacement (the non-intrinsic) will be be replaced by
2360 // the new intrinsic.
2361 Instruction *RI = dyn_cast<Instruction>(repl);
2363 Instruction *newIntrinsic = I->clone();
2364 newIntrinsic->setName(I->getName() + ".repl");
2365 newIntrinsic->insertBefore(RI);
2366 repl = newIntrinsic;
2370 patchAndReplaceAllUsesWith(I, repl);
2371 if (MD && repl->getType()->getScalarType()->isPointerTy())
2372 MD->invalidateCachedPointerInfo(repl);
2373 markInstructionForDeletion(I);
2377 /// runOnFunction - This is the main transformation entry point for a function.
2378 bool GVN::runOnFunction(Function& F) {
2379 if (skipOptnoneFunction(F))
2383 MD = &getAnalysis<MemoryDependenceAnalysis>();
2384 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2385 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
2386 DL = DLP ? &DLP->getDataLayout() : 0;
2387 TLI = &getAnalysis<TargetLibraryInfo>();
2388 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
2392 bool Changed = false;
2393 bool ShouldContinue = true;
2395 // Merge unconditional branches, allowing PRE to catch more
2396 // optimization opportunities.
2397 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
2398 BasicBlock *BB = FI++;
2400 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
2401 if (removedBlock) ++NumGVNBlocks;
2403 Changed |= removedBlock;
2406 unsigned Iteration = 0;
2407 while (ShouldContinue) {
2408 DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
2409 ShouldContinue = iterateOnFunction(F);
2410 Changed |= ShouldContinue;
2415 // Fabricate val-num for dead-code in order to suppress assertion in
2417 assignValNumForDeadCode();
2418 bool PREChanged = true;
2419 while (PREChanged) {
2420 PREChanged = performPRE(F);
2421 Changed |= PREChanged;
2425 // FIXME: Should perform GVN again after PRE does something. PRE can move
2426 // computations into blocks where they become fully redundant. Note that
2427 // we can't do this until PRE's critical edge splitting updates memdep.
2428 // Actually, when this happens, we should just fully integrate PRE into GVN.
2430 cleanupGlobalSets();
2431 // Do not cleanup DeadBlocks in cleanupGlobalSets() as it's called for each
2439 bool GVN::processBlock(BasicBlock *BB) {
2440 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2441 // (and incrementing BI before processing an instruction).
2442 assert(InstrsToErase.empty() &&
2443 "We expect InstrsToErase to be empty across iterations");
2444 if (DeadBlocks.count(BB))
2447 bool ChangedFunction = false;
2449 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2451 ChangedFunction |= processInstruction(BI);
2452 if (InstrsToErase.empty()) {
2457 // If we need some instructions deleted, do it now.
2458 NumGVNInstr += InstrsToErase.size();
2460 // Avoid iterator invalidation.
2461 bool AtStart = BI == BB->begin();
2465 for (SmallVectorImpl<Instruction *>::iterator I = InstrsToErase.begin(),
2466 E = InstrsToErase.end(); I != E; ++I) {
2467 DEBUG(dbgs() << "GVN removed: " << **I << '\n');
2468 if (MD) MD->removeInstruction(*I);
2469 DEBUG(verifyRemoved(*I));
2470 (*I)->eraseFromParent();
2472 InstrsToErase.clear();
2480 return ChangedFunction;
2483 /// performPRE - Perform a purely local form of PRE that looks for diamond
2484 /// control flow patterns and attempts to perform simple PRE at the join point.
2485 bool GVN::performPRE(Function &F) {
2486 bool Changed = false;
2487 SmallVector<std::pair<Value*, BasicBlock*>, 8> predMap;
2488 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2489 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
2490 BasicBlock *CurrentBlock = *DI;
2492 // Nothing to PRE in the entry block.
2493 if (CurrentBlock == &F.getEntryBlock()) continue;
2495 // Don't perform PRE on a landing pad.
2496 if (CurrentBlock->isLandingPad()) continue;
2498 for (BasicBlock::iterator BI = CurrentBlock->begin(),
2499 BE = CurrentBlock->end(); BI != BE; ) {
2500 Instruction *CurInst = BI++;
2502 if (isa<AllocaInst>(CurInst) ||
2503 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
2504 CurInst->getType()->isVoidTy() ||
2505 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
2506 isa<DbgInfoIntrinsic>(CurInst))
2509 // Don't do PRE on compares. The PHI would prevent CodeGenPrepare from
2510 // sinking the compare again, and it would force the code generator to
2511 // move the i1 from processor flags or predicate registers into a general
2512 // purpose register.
2513 if (isa<CmpInst>(CurInst))
2516 // We don't currently value number ANY inline asm calls.
2517 if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2518 if (CallI->isInlineAsm())
2521 uint32_t ValNo = VN.lookup(CurInst);
2523 // Look for the predecessors for PRE opportunities. We're
2524 // only trying to solve the basic diamond case, where
2525 // a value is computed in the successor and one predecessor,
2526 // but not the other. We also explicitly disallow cases
2527 // where the successor is its own predecessor, because they're
2528 // more complicated to get right.
2529 unsigned NumWith = 0;
2530 unsigned NumWithout = 0;
2531 BasicBlock *PREPred = 0;
2534 for (pred_iterator PI = pred_begin(CurrentBlock),
2535 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
2536 BasicBlock *P = *PI;
2537 // We're not interested in PRE where the block is its
2538 // own predecessor, or in blocks with predecessors
2539 // that are not reachable.
2540 if (P == CurrentBlock) {
2543 } else if (!DT->isReachableFromEntry(P)) {
2548 Value* predV = findLeader(P, ValNo);
2550 predMap.push_back(std::make_pair(static_cast<Value *>(0), P));
2553 } else if (predV->getType() != CurInst->getType()) {
2555 } else if (predV == CurInst) {
2556 /* CurInst dominates this predecessor. */
2560 predMap.push_back(std::make_pair(predV, P));
2565 // Don't do PRE when it might increase code size, i.e. when
2566 // we would need to insert instructions in more than one pred.
2567 if (NumWithout != 1 || NumWith == 0)
2570 // Don't do PRE across indirect branch.
2571 if (isa<IndirectBrInst>(PREPred->getTerminator()))
2574 // We can't do PRE safely on a critical edge, so instead we schedule
2575 // the edge to be split and perform the PRE the next time we iterate
2577 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2578 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2579 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2583 // Instantiate the expression in the predecessor that lacked it.
2584 // Because we are going top-down through the block, all value numbers
2585 // will be available in the predecessor by the time we need them. Any
2586 // that weren't originally present will have been instantiated earlier
2588 Instruction *PREInstr = CurInst->clone();
2589 bool success = true;
2590 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2591 Value *Op = PREInstr->getOperand(i);
2592 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2595 if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
2596 PREInstr->setOperand(i, V);
2603 // Fail out if we encounter an operand that is not available in
2604 // the PRE predecessor. This is typically because of loads which
2605 // are not value numbered precisely.
2607 DEBUG(verifyRemoved(PREInstr));
2612 PREInstr->insertBefore(PREPred->getTerminator());
2613 PREInstr->setName(CurInst->getName() + ".pre");
2614 PREInstr->setDebugLoc(CurInst->getDebugLoc());
2615 VN.add(PREInstr, ValNo);
2618 // Update the availability map to include the new instruction.
2619 addToLeaderTable(ValNo, PREInstr, PREPred);
2621 // Create a PHI to make the value available in this block.
2622 PHINode* Phi = PHINode::Create(CurInst->getType(), predMap.size(),
2623 CurInst->getName() + ".pre-phi",
2624 CurrentBlock->begin());
2625 for (unsigned i = 0, e = predMap.size(); i != e; ++i) {
2626 if (Value *V = predMap[i].first)
2627 Phi->addIncoming(V, predMap[i].second);
2629 Phi->addIncoming(PREInstr, PREPred);
2633 addToLeaderTable(ValNo, Phi, CurrentBlock);
2634 Phi->setDebugLoc(CurInst->getDebugLoc());
2635 CurInst->replaceAllUsesWith(Phi);
2636 if (Phi->getType()->getScalarType()->isPointerTy()) {
2637 // Because we have added a PHI-use of the pointer value, it has now
2638 // "escaped" from alias analysis' perspective. We need to inform
2640 for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
2642 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
2643 VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
2647 MD->invalidateCachedPointerInfo(Phi);
2650 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2652 DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2653 if (MD) MD->removeInstruction(CurInst);
2654 DEBUG(verifyRemoved(CurInst));
2655 CurInst->eraseFromParent();
2660 if (splitCriticalEdges())
2666 /// Split the critical edge connecting the given two blocks, and return
2667 /// the block inserted to the critical edge.
2668 BasicBlock *GVN::splitCriticalEdges(BasicBlock *Pred, BasicBlock *Succ) {
2669 BasicBlock *BB = SplitCriticalEdge(Pred, Succ, this);
2671 MD->invalidateCachedPredecessors();
2675 /// splitCriticalEdges - Split critical edges found during the previous
2676 /// iteration that may enable further optimization.
2677 bool GVN::splitCriticalEdges() {
2678 if (toSplit.empty())
2681 std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2682 SplitCriticalEdge(Edge.first, Edge.second, this);
2683 } while (!toSplit.empty());
2684 if (MD) MD->invalidateCachedPredecessors();
2688 /// iterateOnFunction - Executes one iteration of GVN
2689 bool GVN::iterateOnFunction(Function &F) {
2690 cleanupGlobalSets();
2692 // Top-down walk of the dominator tree
2693 bool Changed = false;
2695 // Needed for value numbering with phi construction to work.
2696 ReversePostOrderTraversal<Function*> RPOT(&F);
2697 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2698 RE = RPOT.end(); RI != RE; ++RI)
2699 Changed |= processBlock(*RI);
2701 // Save the blocks this function have before transformation begins. GVN may
2702 // split critical edge, and hence may invalidate the RPO/DT iterator.
2704 std::vector<BasicBlock *> BBVect;
2705 BBVect.reserve(256);
2706 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2707 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
2708 BBVect.push_back(DI->getBlock());
2710 for (std::vector<BasicBlock *>::iterator I = BBVect.begin(), E = BBVect.end();
2712 Changed |= processBlock(*I);
2718 void GVN::cleanupGlobalSets() {
2720 LeaderTable.clear();
2721 TableAllocator.Reset();
2724 /// verifyRemoved - Verify that the specified instruction does not occur in our
2725 /// internal data structures.
2726 void GVN::verifyRemoved(const Instruction *Inst) const {
2727 VN.verifyRemoved(Inst);
2729 // Walk through the value number scope to make sure the instruction isn't
2730 // ferreted away in it.
2731 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
2732 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
2733 const LeaderTableEntry *Node = &I->second;
2734 assert(Node->Val != Inst && "Inst still in value numbering scope!");
2736 while (Node->Next) {
2738 assert(Node->Val != Inst && "Inst still in value numbering scope!");
2743 // BB is declared dead, which implied other blocks become dead as well. This
2744 // function is to add all these blocks to "DeadBlocks". For the dead blocks'
2745 // live successors, update their phi nodes by replacing the operands
2746 // corresponding to dead blocks with UndefVal.
2748 void GVN::addDeadBlock(BasicBlock *BB) {
2749 SmallVector<BasicBlock *, 4> NewDead;
2750 SmallSetVector<BasicBlock *, 4> DF;
2752 NewDead.push_back(BB);
2753 while (!NewDead.empty()) {
2754 BasicBlock *D = NewDead.pop_back_val();
2755 if (DeadBlocks.count(D))
2758 // All blocks dominated by D are dead.
2759 SmallVector<BasicBlock *, 8> Dom;
2760 DT->getDescendants(D, Dom);
2761 DeadBlocks.insert(Dom.begin(), Dom.end());
2763 // Figure out the dominance-frontier(D).
2764 for (SmallVectorImpl<BasicBlock *>::iterator I = Dom.begin(),
2765 E = Dom.end(); I != E; I++) {
2767 for (succ_iterator SI = succ_begin(B), SE = succ_end(B); SI != SE; SI++) {
2768 BasicBlock *S = *SI;
2769 if (DeadBlocks.count(S))
2772 bool AllPredDead = true;
2773 for (pred_iterator PI = pred_begin(S), PE = pred_end(S); PI != PE; PI++)
2774 if (!DeadBlocks.count(*PI)) {
2775 AllPredDead = false;
2780 // S could be proved dead later on. That is why we don't update phi
2781 // operands at this moment.
2784 // While S is not dominated by D, it is dead by now. This could take
2785 // place if S already have a dead predecessor before D is declared
2787 NewDead.push_back(S);
2793 // For the dead blocks' live successors, update their phi nodes by replacing
2794 // the operands corresponding to dead blocks with UndefVal.
2795 for(SmallSetVector<BasicBlock *, 4>::iterator I = DF.begin(), E = DF.end();
2798 if (DeadBlocks.count(B))
2801 SmallVector<BasicBlock *, 4> Preds(pred_begin(B), pred_end(B));
2802 for (SmallVectorImpl<BasicBlock *>::iterator PI = Preds.begin(),
2803 PE = Preds.end(); PI != PE; PI++) {
2804 BasicBlock *P = *PI;
2806 if (!DeadBlocks.count(P))
2809 if (isCriticalEdge(P->getTerminator(), GetSuccessorNumber(P, B))) {
2810 if (BasicBlock *S = splitCriticalEdges(P, B))
2811 DeadBlocks.insert(P = S);
2814 for (BasicBlock::iterator II = B->begin(); isa<PHINode>(II); ++II) {
2815 PHINode &Phi = cast<PHINode>(*II);
2816 Phi.setIncomingValue(Phi.getBasicBlockIndex(P),
2817 UndefValue::get(Phi.getType()));
2823 // If the given branch is recognized as a foldable branch (i.e. conditional
2824 // branch with constant condition), it will perform following analyses and
2826 // 1) If the dead out-coming edge is a critical-edge, split it. Let
2827 // R be the target of the dead out-coming edge.
2828 // 1) Identify the set of dead blocks implied by the branch's dead outcoming
2829 // edge. The result of this step will be {X| X is dominated by R}
2830 // 2) Identify those blocks which haves at least one dead prodecessor. The
2831 // result of this step will be dominance-frontier(R).
2832 // 3) Update the PHIs in DF(R) by replacing the operands corresponding to
2833 // dead blocks with "UndefVal" in an hope these PHIs will optimized away.
2835 // Return true iff *NEW* dead code are found.
2836 bool GVN::processFoldableCondBr(BranchInst *BI) {
2837 if (!BI || BI->isUnconditional())
2840 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
2844 BasicBlock *DeadRoot = Cond->getZExtValue() ?
2845 BI->getSuccessor(1) : BI->getSuccessor(0);
2846 if (DeadBlocks.count(DeadRoot))
2849 if (!DeadRoot->getSinglePredecessor())
2850 DeadRoot = splitCriticalEdges(BI->getParent(), DeadRoot);
2852 addDeadBlock(DeadRoot);
2856 // performPRE() will trigger assert if it come across an instruciton without
2857 // associated val-num. As it normally has far more live instructions than dead
2858 // instructions, it makes more sense just to "fabricate" a val-number for the
2859 // dead code than checking if instruction involved is dead or not.
2860 void GVN::assignValNumForDeadCode() {
2861 for (SetVector<BasicBlock *>::iterator I = DeadBlocks.begin(),
2862 E = DeadBlocks.end(); I != E; I++) {
2863 BasicBlock *BB = *I;
2864 for (BasicBlock::iterator II = BB->begin(), EE = BB->end();
2866 Instruction *Inst = &*II;
2867 unsigned ValNum = VN.lookup_or_add(Inst);
2868 addToLeaderTable(ValNum, Inst, BB);