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/GlobalVariable.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/Loads.h"
28 #include "llvm/Analysis/MemoryBuiltins.h"
29 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
30 #include "llvm/Analysis/PHITransAddr.h"
31 #include "llvm/Analysis/ValueTracking.h"
32 #include "llvm/Assembly/Writer.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetLibraryInfo.h"
35 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
36 #include "llvm/Transforms/Utils/SSAUpdater.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/DepthFirstIterator.h"
39 #include "llvm/ADT/Hashing.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/Support/Allocator.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/IRBuilder.h"
46 #include "llvm/Support/PatternMatch.h"
48 using namespace PatternMatch;
50 STATISTIC(NumGVNInstr, "Number of instructions deleted");
51 STATISTIC(NumGVNLoad, "Number of loads deleted");
52 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
53 STATISTIC(NumGVNBlocks, "Number of blocks merged");
54 STATISTIC(NumGVNSimpl, "Number of instructions simplified");
55 STATISTIC(NumGVNEqProp, "Number of equalities propagated");
56 STATISTIC(NumPRELoad, "Number of loads PRE'd");
58 static cl::opt<bool> EnablePRE("enable-pre",
59 cl::init(true), cl::Hidden);
60 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
62 //===----------------------------------------------------------------------===//
64 //===----------------------------------------------------------------------===//
66 /// This class holds the mapping between values and value numbers. It is used
67 /// as an efficient mechanism to determine the expression-wise equivalence of
73 SmallVector<uint32_t, 4> varargs;
75 Expression(uint32_t o = ~2U) : opcode(o) { }
77 bool operator==(const Expression &other) const {
78 if (opcode != other.opcode)
80 if (opcode == ~0U || opcode == ~1U)
82 if (type != other.type)
84 if (varargs != other.varargs)
89 friend hash_code hash_value(const Expression &Value) {
90 // Optimize for the common case.
91 if (Value.varargs.empty())
92 return hash_combine(Value.opcode, Value.type);
94 return hash_combine(Value.opcode, Value.type,
95 hash_combine_range(Value.varargs.begin(),
96 Value.varargs.end()));
101 DenseMap<Value*, uint32_t> valueNumbering;
102 DenseMap<Expression, uint32_t> expressionNumbering;
104 MemoryDependenceAnalysis *MD;
107 uint32_t nextValueNumber;
109 Expression create_expression(Instruction* I);
110 Expression create_cmp_expression(unsigned Opcode,
111 CmpInst::Predicate Predicate,
112 Value *LHS, Value *RHS);
113 Expression create_extractvalue_expression(ExtractValueInst* EI);
114 uint32_t lookup_or_add_call(CallInst* C);
116 ValueTable() : nextValueNumber(1) { }
117 uint32_t lookup_or_add(Value *V);
118 uint32_t lookup(Value *V) const;
119 uint32_t lookup_or_add_cmp(unsigned Opcode, CmpInst::Predicate Pred,
120 Value *LHS, Value *RHS);
121 void add(Value *V, uint32_t num);
123 void erase(Value *v);
124 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
125 AliasAnalysis *getAliasAnalysis() const { return AA; }
126 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
127 void setDomTree(DominatorTree* D) { DT = D; }
128 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
129 void verifyRemoved(const Value *) const;
134 template <> struct DenseMapInfo<Expression> {
135 static inline Expression getEmptyKey() {
139 static inline Expression getTombstoneKey() {
143 static unsigned getHashValue(const Expression e) {
144 using llvm::hash_value;
145 return static_cast<unsigned>(hash_value(e));
147 static bool isEqual(const Expression &LHS, const Expression &RHS) {
154 //===----------------------------------------------------------------------===//
155 // ValueTable Internal Functions
156 //===----------------------------------------------------------------------===//
158 Expression ValueTable::create_expression(Instruction *I) {
160 e.type = I->getType();
161 e.opcode = I->getOpcode();
162 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
164 e.varargs.push_back(lookup_or_add(*OI));
165 if (I->isCommutative()) {
166 // Ensure that commutative instructions that only differ by a permutation
167 // of their operands get the same value number by sorting the operand value
168 // numbers. Since all commutative instructions have two operands it is more
169 // efficient to sort by hand rather than using, say, std::sort.
170 assert(I->getNumOperands() == 2 && "Unsupported commutative instruction!");
171 if (e.varargs[0] > e.varargs[1])
172 std::swap(e.varargs[0], e.varargs[1]);
175 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
176 // Sort the operand value numbers so x<y and y>x get the same value number.
177 CmpInst::Predicate Predicate = C->getPredicate();
178 if (e.varargs[0] > e.varargs[1]) {
179 std::swap(e.varargs[0], e.varargs[1]);
180 Predicate = CmpInst::getSwappedPredicate(Predicate);
182 e.opcode = (C->getOpcode() << 8) | Predicate;
183 } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
184 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
186 e.varargs.push_back(*II);
192 Expression ValueTable::create_cmp_expression(unsigned Opcode,
193 CmpInst::Predicate Predicate,
194 Value *LHS, Value *RHS) {
195 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
196 "Not a comparison!");
198 e.type = CmpInst::makeCmpResultType(LHS->getType());
199 e.varargs.push_back(lookup_or_add(LHS));
200 e.varargs.push_back(lookup_or_add(RHS));
202 // Sort the operand value numbers so x<y and y>x get the same value number.
203 if (e.varargs[0] > e.varargs[1]) {
204 std::swap(e.varargs[0], e.varargs[1]);
205 Predicate = CmpInst::getSwappedPredicate(Predicate);
207 e.opcode = (Opcode << 8) | Predicate;
211 Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
212 assert(EI != 0 && "Not an ExtractValueInst?");
214 e.type = EI->getType();
217 IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
218 if (I != 0 && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
219 // EI might be an extract from one of our recognised intrinsics. If it
220 // is we'll synthesize a semantically equivalent expression instead on
221 // an extract value expression.
222 switch (I->getIntrinsicID()) {
223 case Intrinsic::sadd_with_overflow:
224 case Intrinsic::uadd_with_overflow:
225 e.opcode = Instruction::Add;
227 case Intrinsic::ssub_with_overflow:
228 case Intrinsic::usub_with_overflow:
229 e.opcode = Instruction::Sub;
231 case Intrinsic::smul_with_overflow:
232 case Intrinsic::umul_with_overflow:
233 e.opcode = Instruction::Mul;
240 // Intrinsic recognized. Grab its args to finish building the expression.
241 assert(I->getNumArgOperands() == 2 &&
242 "Expect two args for recognised intrinsics.");
243 e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
244 e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
249 // Not a recognised intrinsic. Fall back to producing an extract value
251 e.opcode = EI->getOpcode();
252 for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
254 e.varargs.push_back(lookup_or_add(*OI));
256 for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
258 e.varargs.push_back(*II);
263 //===----------------------------------------------------------------------===//
264 // ValueTable External Functions
265 //===----------------------------------------------------------------------===//
267 /// add - Insert a value into the table with a specified value number.
268 void ValueTable::add(Value *V, uint32_t num) {
269 valueNumbering.insert(std::make_pair(V, num));
272 uint32_t ValueTable::lookup_or_add_call(CallInst* C) {
273 if (AA->doesNotAccessMemory(C)) {
274 Expression exp = create_expression(C);
275 uint32_t& e = expressionNumbering[exp];
276 if (!e) e = nextValueNumber++;
277 valueNumbering[C] = e;
279 } else if (AA->onlyReadsMemory(C)) {
280 Expression exp = create_expression(C);
281 uint32_t& e = expressionNumbering[exp];
283 e = nextValueNumber++;
284 valueNumbering[C] = e;
288 e = nextValueNumber++;
289 valueNumbering[C] = e;
293 MemDepResult local_dep = MD->getDependency(C);
295 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
296 valueNumbering[C] = nextValueNumber;
297 return nextValueNumber++;
300 if (local_dep.isDef()) {
301 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
303 if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
304 valueNumbering[C] = nextValueNumber;
305 return nextValueNumber++;
308 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
309 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
310 uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
312 valueNumbering[C] = nextValueNumber;
313 return nextValueNumber++;
317 uint32_t v = lookup_or_add(local_cdep);
318 valueNumbering[C] = v;
323 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
324 MD->getNonLocalCallDependency(CallSite(C));
325 // FIXME: Move the checking logic to MemDep!
328 // Check to see if we have a single dominating call instruction that is
330 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
331 const NonLocalDepEntry *I = &deps[i];
332 if (I->getResult().isNonLocal())
335 // We don't handle non-definitions. If we already have a call, reject
336 // instruction dependencies.
337 if (!I->getResult().isDef() || cdep != 0) {
342 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
343 // FIXME: All duplicated with non-local case.
344 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
345 cdep = NonLocalDepCall;
354 valueNumbering[C] = nextValueNumber;
355 return nextValueNumber++;
358 if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
359 valueNumbering[C] = nextValueNumber;
360 return nextValueNumber++;
362 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
363 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
364 uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
366 valueNumbering[C] = nextValueNumber;
367 return nextValueNumber++;
371 uint32_t v = lookup_or_add(cdep);
372 valueNumbering[C] = v;
376 valueNumbering[C] = nextValueNumber;
377 return nextValueNumber++;
381 /// lookup_or_add - Returns the value number for the specified value, assigning
382 /// it a new number if it did not have one before.
383 uint32_t ValueTable::lookup_or_add(Value *V) {
384 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
385 if (VI != valueNumbering.end())
388 if (!isa<Instruction>(V)) {
389 valueNumbering[V] = nextValueNumber;
390 return nextValueNumber++;
393 Instruction* I = cast<Instruction>(V);
395 switch (I->getOpcode()) {
396 case Instruction::Call:
397 return lookup_or_add_call(cast<CallInst>(I));
398 case Instruction::Add:
399 case Instruction::FAdd:
400 case Instruction::Sub:
401 case Instruction::FSub:
402 case Instruction::Mul:
403 case Instruction::FMul:
404 case Instruction::UDiv:
405 case Instruction::SDiv:
406 case Instruction::FDiv:
407 case Instruction::URem:
408 case Instruction::SRem:
409 case Instruction::FRem:
410 case Instruction::Shl:
411 case Instruction::LShr:
412 case Instruction::AShr:
413 case Instruction::And:
414 case Instruction::Or :
415 case Instruction::Xor:
416 case Instruction::ICmp:
417 case Instruction::FCmp:
418 case Instruction::Trunc:
419 case Instruction::ZExt:
420 case Instruction::SExt:
421 case Instruction::FPToUI:
422 case Instruction::FPToSI:
423 case Instruction::UIToFP:
424 case Instruction::SIToFP:
425 case Instruction::FPTrunc:
426 case Instruction::FPExt:
427 case Instruction::PtrToInt:
428 case Instruction::IntToPtr:
429 case Instruction::BitCast:
430 case Instruction::Select:
431 case Instruction::ExtractElement:
432 case Instruction::InsertElement:
433 case Instruction::ShuffleVector:
434 case Instruction::InsertValue:
435 case Instruction::GetElementPtr:
436 exp = create_expression(I);
438 case Instruction::ExtractValue:
439 exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
442 valueNumbering[V] = nextValueNumber;
443 return nextValueNumber++;
446 uint32_t& e = expressionNumbering[exp];
447 if (!e) e = nextValueNumber++;
448 valueNumbering[V] = e;
452 /// lookup - Returns the value number of the specified value. Fails if
453 /// the value has not yet been numbered.
454 uint32_t ValueTable::lookup(Value *V) const {
455 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
456 assert(VI != valueNumbering.end() && "Value not numbered?");
460 /// lookup_or_add_cmp - Returns the value number of the given comparison,
461 /// assigning it a new number if it did not have one before. Useful when
462 /// we deduced the result of a comparison, but don't immediately have an
463 /// instruction realizing that comparison to hand.
464 uint32_t ValueTable::lookup_or_add_cmp(unsigned Opcode,
465 CmpInst::Predicate Predicate,
466 Value *LHS, Value *RHS) {
467 Expression exp = create_cmp_expression(Opcode, Predicate, LHS, RHS);
468 uint32_t& e = expressionNumbering[exp];
469 if (!e) e = nextValueNumber++;
473 /// clear - Remove all entries from the ValueTable.
474 void ValueTable::clear() {
475 valueNumbering.clear();
476 expressionNumbering.clear();
480 /// erase - Remove a value from the value numbering.
481 void ValueTable::erase(Value *V) {
482 valueNumbering.erase(V);
485 /// verifyRemoved - Verify that the value is removed from all internal data
487 void ValueTable::verifyRemoved(const Value *V) const {
488 for (DenseMap<Value*, uint32_t>::const_iterator
489 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
490 assert(I->first != V && "Inst still occurs in value numbering map!");
494 //===----------------------------------------------------------------------===//
496 //===----------------------------------------------------------------------===//
500 class GVN : public FunctionPass {
502 MemoryDependenceAnalysis *MD;
504 const TargetData *TD;
505 const TargetLibraryInfo *TLI;
509 /// LeaderTable - A mapping from value numbers to lists of Value*'s that
510 /// have that value number. Use findLeader to query it.
511 struct LeaderTableEntry {
514 LeaderTableEntry *Next;
516 DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
517 BumpPtrAllocator TableAllocator;
519 SmallVector<Instruction*, 8> InstrsToErase;
521 static char ID; // Pass identification, replacement for typeid
522 explicit GVN(bool noloads = false)
523 : FunctionPass(ID), NoLoads(noloads), MD(0) {
524 initializeGVNPass(*PassRegistry::getPassRegistry());
527 bool runOnFunction(Function &F);
529 /// markInstructionForDeletion - This removes the specified instruction from
530 /// our various maps and marks it for deletion.
531 void markInstructionForDeletion(Instruction *I) {
533 InstrsToErase.push_back(I);
536 const TargetData *getTargetData() const { return TD; }
537 DominatorTree &getDominatorTree() const { return *DT; }
538 AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
539 MemoryDependenceAnalysis &getMemDep() const { return *MD; }
541 /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
542 /// its value number.
543 void addToLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
544 LeaderTableEntry &Curr = LeaderTable[N];
551 LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
554 Node->Next = Curr.Next;
558 /// removeFromLeaderTable - Scan the list of values corresponding to a given
559 /// value number, and remove the given value if encountered.
560 void removeFromLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
561 LeaderTableEntry* Prev = 0;
562 LeaderTableEntry* Curr = &LeaderTable[N];
564 while (Curr->Val != V || Curr->BB != BB) {
570 Prev->Next = Curr->Next;
576 LeaderTableEntry* Next = Curr->Next;
577 Curr->Val = Next->Val;
579 Curr->Next = Next->Next;
584 // List of critical edges to be split between iterations.
585 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
587 // This transformation requires dominator postdominator info
588 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
589 AU.addRequired<DominatorTree>();
590 AU.addRequired<TargetLibraryInfo>();
592 AU.addRequired<MemoryDependenceAnalysis>();
593 AU.addRequired<AliasAnalysis>();
595 AU.addPreserved<DominatorTree>();
596 AU.addPreserved<AliasAnalysis>();
601 // FIXME: eliminate or document these better
602 bool processLoad(LoadInst *L);
603 bool processInstruction(Instruction *I);
604 bool processNonLocalLoad(LoadInst *L);
605 bool processBlock(BasicBlock *BB);
606 void dump(DenseMap<uint32_t, Value*> &d);
607 bool iterateOnFunction(Function &F);
608 bool performPRE(Function &F);
609 Value *findLeader(BasicBlock *BB, uint32_t num);
610 void cleanupGlobalSets();
611 void verifyRemoved(const Instruction *I) const;
612 bool splitCriticalEdges();
613 unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
615 bool propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root);
621 // createGVNPass - The public interface to this file...
622 FunctionPass *llvm::createGVNPass(bool NoLoads) {
623 return new GVN(NoLoads);
626 INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
627 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
628 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
629 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
630 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
631 INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
633 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
635 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
636 E = d.end(); I != E; ++I) {
637 errs() << I->first << "\n";
643 /// IsValueFullyAvailableInBlock - Return true if we can prove that the value
644 /// we're analyzing is fully available in the specified block. As we go, keep
645 /// track of which blocks we know are fully alive in FullyAvailableBlocks. This
646 /// map is actually a tri-state map with the following values:
647 /// 0) we know the block *is not* fully available.
648 /// 1) we know the block *is* fully available.
649 /// 2) we do not know whether the block is fully available or not, but we are
650 /// currently speculating that it will be.
651 /// 3) we are speculating for this block and have used that to speculate for
653 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
654 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
655 // Optimistically assume that the block is fully available and check to see
656 // if we already know about this block in one lookup.
657 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
658 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
660 // If the entry already existed for this block, return the precomputed value.
662 // If this is a speculative "available" value, mark it as being used for
663 // speculation of other blocks.
664 if (IV.first->second == 2)
665 IV.first->second = 3;
666 return IV.first->second != 0;
669 // Otherwise, see if it is fully available in all predecessors.
670 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
672 // If this block has no predecessors, it isn't live-in here.
674 goto SpeculationFailure;
676 for (; PI != PE; ++PI)
677 // If the value isn't fully available in one of our predecessors, then it
678 // isn't fully available in this block either. Undo our previous
679 // optimistic assumption and bail out.
680 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
681 goto SpeculationFailure;
685 // SpeculationFailure - If we get here, we found out that this is not, after
686 // all, a fully-available block. We have a problem if we speculated on this and
687 // used the speculation to mark other blocks as available.
689 char &BBVal = FullyAvailableBlocks[BB];
691 // If we didn't speculate on this, just return with it set to false.
697 // If we did speculate on this value, we could have blocks set to 1 that are
698 // incorrect. Walk the (transitive) successors of this block and mark them as
700 SmallVector<BasicBlock*, 32> BBWorklist;
701 BBWorklist.push_back(BB);
704 BasicBlock *Entry = BBWorklist.pop_back_val();
705 // Note that this sets blocks to 0 (unavailable) if they happen to not
706 // already be in FullyAvailableBlocks. This is safe.
707 char &EntryVal = FullyAvailableBlocks[Entry];
708 if (EntryVal == 0) continue; // Already unavailable.
710 // Mark as unavailable.
713 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
714 BBWorklist.push_back(*I);
715 } while (!BBWorklist.empty());
721 /// CanCoerceMustAliasedValueToLoad - Return true if
722 /// CoerceAvailableValueToLoadType will succeed.
723 static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
725 const TargetData &TD) {
726 // If the loaded or stored value is an first class array or struct, don't try
727 // to transform them. We need to be able to bitcast to integer.
728 if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
729 StoredVal->getType()->isStructTy() ||
730 StoredVal->getType()->isArrayTy())
733 // The store has to be at least as big as the load.
734 if (TD.getTypeSizeInBits(StoredVal->getType()) <
735 TD.getTypeSizeInBits(LoadTy))
742 /// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
743 /// then a load from a must-aliased pointer of a different type, try to coerce
744 /// the stored value. LoadedTy is the type of the load we want to replace and
745 /// InsertPt is the place to insert new instructions.
747 /// If we can't do it, return null.
748 static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
750 Instruction *InsertPt,
751 const TargetData &TD) {
752 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
755 // If this is already the right type, just return it.
756 Type *StoredValTy = StoredVal->getType();
758 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
759 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
761 // If the store and reload are the same size, we can always reuse it.
762 if (StoreSize == LoadSize) {
763 // Pointer to Pointer -> use bitcast.
764 if (StoredValTy->isPointerTy() && LoadedTy->isPointerTy())
765 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
767 // Convert source pointers to integers, which can be bitcast.
768 if (StoredValTy->isPointerTy()) {
769 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
770 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
773 Type *TypeToCastTo = LoadedTy;
774 if (TypeToCastTo->isPointerTy())
775 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
777 if (StoredValTy != TypeToCastTo)
778 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
780 // Cast to pointer if the load needs a pointer type.
781 if (LoadedTy->isPointerTy())
782 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
787 // If the loaded value is smaller than the available value, then we can
788 // extract out a piece from it. If the available value is too small, then we
789 // can't do anything.
790 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
792 // Convert source pointers to integers, which can be manipulated.
793 if (StoredValTy->isPointerTy()) {
794 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
795 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
798 // Convert vectors and fp to integer, which can be manipulated.
799 if (!StoredValTy->isIntegerTy()) {
800 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
801 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
804 // If this is a big-endian system, we need to shift the value down to the low
805 // bits so that a truncate will work.
806 if (TD.isBigEndian()) {
807 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
808 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
811 // Truncate the integer to the right size now.
812 Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
813 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
815 if (LoadedTy == NewIntTy)
818 // If the result is a pointer, inttoptr.
819 if (LoadedTy->isPointerTy())
820 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
822 // Otherwise, bitcast.
823 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
826 /// AnalyzeLoadFromClobberingWrite - This function is called when we have a
827 /// memdep query of a load that ends up being a clobbering memory write (store,
828 /// memset, memcpy, memmove). This means that the write *may* provide bits used
829 /// by the load but we can't be sure because the pointers don't mustalias.
831 /// Check this case to see if there is anything more we can do before we give
832 /// up. This returns -1 if we have to give up, or a byte number in the stored
833 /// value of the piece that feeds the load.
834 static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
836 uint64_t WriteSizeInBits,
837 const TargetData &TD) {
838 // If the loaded or stored value is a first class array or struct, don't try
839 // to transform them. We need to be able to bitcast to integer.
840 if (LoadTy->isStructTy() || LoadTy->isArrayTy())
843 int64_t StoreOffset = 0, LoadOffset = 0;
844 Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr, StoreOffset,TD);
845 Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, TD);
846 if (StoreBase != LoadBase)
849 // If the load and store are to the exact same address, they should have been
850 // a must alias. AA must have gotten confused.
851 // FIXME: Study to see if/when this happens. One case is forwarding a memset
852 // to a load from the base of the memset.
854 if (LoadOffset == StoreOffset) {
855 dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
856 << "Base = " << *StoreBase << "\n"
857 << "Store Ptr = " << *WritePtr << "\n"
858 << "Store Offs = " << StoreOffset << "\n"
859 << "Load Ptr = " << *LoadPtr << "\n";
864 // If the load and store don't overlap at all, the store doesn't provide
865 // anything to the load. In this case, they really don't alias at all, AA
866 // must have gotten confused.
867 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy);
869 if ((WriteSizeInBits & 7) | (LoadSize & 7))
871 uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
875 bool isAAFailure = false;
876 if (StoreOffset < LoadOffset)
877 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
879 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
883 dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
884 << "Base = " << *StoreBase << "\n"
885 << "Store Ptr = " << *WritePtr << "\n"
886 << "Store Offs = " << StoreOffset << "\n"
887 << "Load Ptr = " << *LoadPtr << "\n";
893 // If the Load isn't completely contained within the stored bits, we don't
894 // have all the bits to feed it. We could do something crazy in the future
895 // (issue a smaller load then merge the bits in) but this seems unlikely to be
897 if (StoreOffset > LoadOffset ||
898 StoreOffset+StoreSize < LoadOffset+LoadSize)
901 // Okay, we can do this transformation. Return the number of bytes into the
902 // store that the load is.
903 return LoadOffset-StoreOffset;
906 /// AnalyzeLoadFromClobberingStore - This function is called when we have a
907 /// memdep query of a load that ends up being a clobbering store.
908 static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
910 const TargetData &TD) {
911 // Cannot handle reading from store of first-class aggregate yet.
912 if (DepSI->getValueOperand()->getType()->isStructTy() ||
913 DepSI->getValueOperand()->getType()->isArrayTy())
916 Value *StorePtr = DepSI->getPointerOperand();
917 uint64_t StoreSize =TD.getTypeSizeInBits(DepSI->getValueOperand()->getType());
918 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
919 StorePtr, StoreSize, TD);
922 /// AnalyzeLoadFromClobberingLoad - This function is called when we have a
923 /// memdep query of a load that ends up being clobbered by another load. See if
924 /// the other load can feed into the second load.
925 static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
926 LoadInst *DepLI, const TargetData &TD){
927 // Cannot handle reading from store of first-class aggregate yet.
928 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
931 Value *DepPtr = DepLI->getPointerOperand();
932 uint64_t DepSize = TD.getTypeSizeInBits(DepLI->getType());
933 int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, TD);
934 if (R != -1) return R;
936 // If we have a load/load clobber an DepLI can be widened to cover this load,
937 // then we should widen it!
938 int64_t LoadOffs = 0;
939 const Value *LoadBase =
940 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, TD);
941 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
943 unsigned Size = MemoryDependenceAnalysis::
944 getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, TD);
945 if (Size == 0) return -1;
947 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, TD);
952 static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
954 const TargetData &TD) {
955 // If the mem operation is a non-constant size, we can't handle it.
956 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
957 if (SizeCst == 0) return -1;
958 uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
960 // If this is memset, we just need to see if the offset is valid in the size
962 if (MI->getIntrinsicID() == Intrinsic::memset)
963 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
966 // If we have a memcpy/memmove, the only case we can handle is if this is a
967 // copy from constant memory. In that case, we can read directly from the
969 MemTransferInst *MTI = cast<MemTransferInst>(MI);
971 Constant *Src = dyn_cast<Constant>(MTI->getSource());
972 if (Src == 0) return -1;
974 GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &TD));
975 if (GV == 0 || !GV->isConstant()) return -1;
977 // See if the access is within the bounds of the transfer.
978 int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
979 MI->getDest(), MemSizeInBits, TD);
983 // Otherwise, see if we can constant fold a load from the constant with the
984 // offset applied as appropriate.
985 Src = ConstantExpr::getBitCast(Src,
986 llvm::Type::getInt8PtrTy(Src->getContext()));
987 Constant *OffsetCst =
988 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
989 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
990 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
991 if (ConstantFoldLoadFromConstPtr(Src, &TD))
997 /// GetStoreValueForLoad - This function is called when we have a
998 /// memdep query of a load that ends up being a clobbering store. This means
999 /// that the store provides bits used by the load but we the pointers don't
1000 /// mustalias. Check this case to see if there is anything more we can do
1001 /// before we give up.
1002 static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
1004 Instruction *InsertPt, const TargetData &TD){
1005 LLVMContext &Ctx = SrcVal->getType()->getContext();
1007 uint64_t StoreSize = (TD.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
1008 uint64_t LoadSize = (TD.getTypeSizeInBits(LoadTy) + 7) / 8;
1010 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1012 // Compute which bits of the stored value are being used by the load. Convert
1013 // to an integer type to start with.
1014 if (SrcVal->getType()->isPointerTy())
1015 SrcVal = Builder.CreatePtrToInt(SrcVal, TD.getIntPtrType(Ctx));
1016 if (!SrcVal->getType()->isIntegerTy())
1017 SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
1019 // Shift the bits to the least significant depending on endianness.
1021 if (TD.isLittleEndian())
1022 ShiftAmt = Offset*8;
1024 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
1027 SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
1029 if (LoadSize != StoreSize)
1030 SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
1032 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
1035 /// GetLoadValueForLoad - This function is called when we have a
1036 /// memdep query of a load that ends up being a clobbering load. This means
1037 /// that the load *may* provide bits used by the load but we can't be sure
1038 /// because the pointers don't mustalias. Check this case to see if there is
1039 /// anything more we can do before we give up.
1040 static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
1041 Type *LoadTy, Instruction *InsertPt,
1043 const TargetData &TD = *gvn.getTargetData();
1044 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
1045 // widen SrcVal out to a larger load.
1046 unsigned SrcValSize = TD.getTypeStoreSize(SrcVal->getType());
1047 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
1048 if (Offset+LoadSize > SrcValSize) {
1049 assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
1050 assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
1051 // If we have a load/load clobber an DepLI can be widened to cover this
1052 // load, then we should widen it to the next power of 2 size big enough!
1053 unsigned NewLoadSize = Offset+LoadSize;
1054 if (!isPowerOf2_32(NewLoadSize))
1055 NewLoadSize = NextPowerOf2(NewLoadSize);
1057 Value *PtrVal = SrcVal->getPointerOperand();
1059 // Insert the new load after the old load. This ensures that subsequent
1060 // memdep queries will find the new load. We can't easily remove the old
1061 // load completely because it is already in the value numbering table.
1062 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
1064 IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1065 DestPTy = PointerType::get(DestPTy,
1066 cast<PointerType>(PtrVal->getType())->getAddressSpace());
1067 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
1068 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1069 LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1070 NewLoad->takeName(SrcVal);
1071 NewLoad->setAlignment(SrcVal->getAlignment());
1073 DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1074 DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1076 // Replace uses of the original load with the wider load. On a big endian
1077 // system, we need to shift down to get the relevant bits.
1078 Value *RV = NewLoad;
1079 if (TD.isBigEndian())
1080 RV = Builder.CreateLShr(RV,
1081 NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
1082 RV = Builder.CreateTrunc(RV, SrcVal->getType());
1083 SrcVal->replaceAllUsesWith(RV);
1085 // We would like to use gvn.markInstructionForDeletion here, but we can't
1086 // because the load is already memoized into the leader map table that GVN
1087 // tracks. It is potentially possible to remove the load from the table,
1088 // but then there all of the operations based on it would need to be
1089 // rehashed. Just leave the dead load around.
1090 gvn.getMemDep().removeInstruction(SrcVal);
1094 return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, TD);
1098 /// GetMemInstValueForLoad - This function is called when we have a
1099 /// memdep query of a load that ends up being a clobbering mem intrinsic.
1100 static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
1101 Type *LoadTy, Instruction *InsertPt,
1102 const TargetData &TD){
1103 LLVMContext &Ctx = LoadTy->getContext();
1104 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
1106 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1108 // We know that this method is only called when the mem transfer fully
1109 // provides the bits for the load.
1110 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1111 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1112 // independently of what the offset is.
1113 Value *Val = MSI->getValue();
1115 Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1117 Value *OneElt = Val;
1119 // Splat the value out to the right number of bits.
1120 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1121 // If we can double the number of bytes set, do it.
1122 if (NumBytesSet*2 <= LoadSize) {
1123 Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1124 Val = Builder.CreateOr(Val, ShVal);
1129 // Otherwise insert one byte at a time.
1130 Value *ShVal = Builder.CreateShl(Val, 1*8);
1131 Val = Builder.CreateOr(OneElt, ShVal);
1135 return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, TD);
1138 // Otherwise, this is a memcpy/memmove from a constant global.
1139 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1140 Constant *Src = cast<Constant>(MTI->getSource());
1142 // Otherwise, see if we can constant fold a load from the constant with the
1143 // offset applied as appropriate.
1144 Src = ConstantExpr::getBitCast(Src,
1145 llvm::Type::getInt8PtrTy(Src->getContext()));
1146 Constant *OffsetCst =
1147 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1148 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
1149 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
1150 return ConstantFoldLoadFromConstPtr(Src, &TD);
1155 struct AvailableValueInBlock {
1156 /// BB - The basic block in question.
1159 SimpleVal, // A simple offsetted value that is accessed.
1160 LoadVal, // A value produced by a load.
1161 MemIntrin // A memory intrinsic which is loaded from.
1164 /// V - The value that is live out of the block.
1165 PointerIntPair<Value *, 2, ValType> Val;
1167 /// Offset - The byte offset in Val that is interesting for the load query.
1170 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1171 unsigned Offset = 0) {
1172 AvailableValueInBlock Res;
1174 Res.Val.setPointer(V);
1175 Res.Val.setInt(SimpleVal);
1176 Res.Offset = Offset;
1180 static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
1181 unsigned Offset = 0) {
1182 AvailableValueInBlock Res;
1184 Res.Val.setPointer(MI);
1185 Res.Val.setInt(MemIntrin);
1186 Res.Offset = Offset;
1190 static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
1191 unsigned Offset = 0) {
1192 AvailableValueInBlock Res;
1194 Res.Val.setPointer(LI);
1195 Res.Val.setInt(LoadVal);
1196 Res.Offset = Offset;
1200 bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
1201 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
1202 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
1204 Value *getSimpleValue() const {
1205 assert(isSimpleValue() && "Wrong accessor");
1206 return Val.getPointer();
1209 LoadInst *getCoercedLoadValue() const {
1210 assert(isCoercedLoadValue() && "Wrong accessor");
1211 return cast<LoadInst>(Val.getPointer());
1214 MemIntrinsic *getMemIntrinValue() const {
1215 assert(isMemIntrinValue() && "Wrong accessor");
1216 return cast<MemIntrinsic>(Val.getPointer());
1219 /// MaterializeAdjustedValue - Emit code into this block to adjust the value
1220 /// defined here to the specified type. This handles various coercion cases.
1221 Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
1223 if (isSimpleValue()) {
1224 Res = getSimpleValue();
1225 if (Res->getType() != LoadTy) {
1226 const TargetData *TD = gvn.getTargetData();
1227 assert(TD && "Need target data to handle type mismatch case");
1228 Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1231 DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
1232 << *getSimpleValue() << '\n'
1233 << *Res << '\n' << "\n\n\n");
1235 } else if (isCoercedLoadValue()) {
1236 LoadInst *Load = getCoercedLoadValue();
1237 if (Load->getType() == LoadTy && Offset == 0) {
1240 Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
1243 DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
1244 << *getCoercedLoadValue() << '\n'
1245 << *Res << '\n' << "\n\n\n");
1248 const TargetData *TD = gvn.getTargetData();
1249 assert(TD && "Need target data to handle type mismatch case");
1250 Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1251 LoadTy, BB->getTerminator(), *TD);
1252 DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1253 << " " << *getMemIntrinValue() << '\n'
1254 << *Res << '\n' << "\n\n\n");
1260 } // end anonymous namespace
1262 /// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1263 /// construct SSA form, allowing us to eliminate LI. This returns the value
1264 /// that should be used at LI's definition site.
1265 static Value *ConstructSSAForLoadSet(LoadInst *LI,
1266 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1268 // Check for the fully redundant, dominating load case. In this case, we can
1269 // just use the dominating value directly.
1270 if (ValuesPerBlock.size() == 1 &&
1271 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1273 return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
1275 // Otherwise, we have to construct SSA form.
1276 SmallVector<PHINode*, 8> NewPHIs;
1277 SSAUpdater SSAUpdate(&NewPHIs);
1278 SSAUpdate.Initialize(LI->getType(), LI->getName());
1280 Type *LoadTy = LI->getType();
1282 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1283 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1284 BasicBlock *BB = AV.BB;
1286 if (SSAUpdate.HasValueForBlock(BB))
1289 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
1292 // Perform PHI construction.
1293 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1295 // If new PHI nodes were created, notify alias analysis.
1296 if (V->getType()->isPointerTy()) {
1297 AliasAnalysis *AA = gvn.getAliasAnalysis();
1299 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1300 AA->copyValue(LI, NewPHIs[i]);
1302 // Now that we've copied information to the new PHIs, scan through
1303 // them again and inform alias analysis that we've added potentially
1304 // escaping uses to any values that are operands to these PHIs.
1305 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1306 PHINode *P = NewPHIs[i];
1307 for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
1308 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
1309 AA->addEscapingUse(P->getOperandUse(jj));
1317 static bool isLifetimeStart(const Instruction *Inst) {
1318 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1319 return II->getIntrinsicID() == Intrinsic::lifetime_start;
1323 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1324 /// non-local by performing PHI construction.
1325 bool GVN::processNonLocalLoad(LoadInst *LI) {
1326 // Find the non-local dependencies of the load.
1327 SmallVector<NonLocalDepResult, 64> Deps;
1328 AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1329 MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
1330 //DEBUG(dbgs() << "INVESTIGATING NONLOCAL LOAD: "
1331 // << Deps.size() << *LI << '\n');
1333 // If we had to process more than one hundred blocks to find the
1334 // dependencies, this load isn't worth worrying about. Optimizing
1335 // it will be too expensive.
1336 unsigned NumDeps = Deps.size();
1340 // If we had a phi translation failure, we'll have a single entry which is a
1341 // clobber in the current block. Reject this early.
1343 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1345 dbgs() << "GVN: non-local load ";
1346 WriteAsOperand(dbgs(), LI);
1347 dbgs() << " has unknown dependencies\n";
1352 // Filter out useless results (non-locals, etc). Keep track of the blocks
1353 // where we have a value available in repl, also keep track of whether we see
1354 // dependencies that produce an unknown value for the load (such as a call
1355 // that could potentially clobber the load).
1356 SmallVector<AvailableValueInBlock, 64> ValuesPerBlock;
1357 SmallVector<BasicBlock*, 64> UnavailableBlocks;
1359 for (unsigned i = 0, e = NumDeps; i != e; ++i) {
1360 BasicBlock *DepBB = Deps[i].getBB();
1361 MemDepResult DepInfo = Deps[i].getResult();
1363 if (!DepInfo.isDef() && !DepInfo.isClobber()) {
1364 UnavailableBlocks.push_back(DepBB);
1368 if (DepInfo.isClobber()) {
1369 // The address being loaded in this non-local block may not be the same as
1370 // the pointer operand of the load if PHI translation occurs. Make sure
1371 // to consider the right address.
1372 Value *Address = Deps[i].getAddress();
1374 // If the dependence is to a store that writes to a superset of the bits
1375 // read by the load, we can extract the bits we need for the load from the
1377 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1378 if (TD && Address) {
1379 int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
1382 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1383 DepSI->getValueOperand(),
1390 // Check to see if we have something like this:
1393 // if we have this, replace the later with an extraction from the former.
1394 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1395 // If this is a clobber and L is the first instruction in its block, then
1396 // we have the first instruction in the entry block.
1397 if (DepLI != LI && Address && TD) {
1398 int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1399 LI->getPointerOperand(),
1403 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1410 // If the clobbering value is a memset/memcpy/memmove, see if we can
1411 // forward a value on from it.
1412 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
1413 if (TD && Address) {
1414 int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
1417 ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1424 UnavailableBlocks.push_back(DepBB);
1428 // DepInfo.isDef() here
1430 Instruction *DepInst = DepInfo.getInst();
1432 // Loading the allocation -> undef.
1433 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst) ||
1434 // Loading immediately after lifetime begin -> undef.
1435 isLifetimeStart(DepInst)) {
1436 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1437 UndefValue::get(LI->getType())));
1441 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1442 // Reject loads and stores that are to the same address but are of
1443 // different types if we have to.
1444 if (S->getValueOperand()->getType() != LI->getType()) {
1445 // If the stored value is larger or equal to the loaded value, we can
1447 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
1448 LI->getType(), *TD)) {
1449 UnavailableBlocks.push_back(DepBB);
1454 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1455 S->getValueOperand()));
1459 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1460 // If the types mismatch and we can't handle it, reject reuse of the load.
1461 if (LD->getType() != LI->getType()) {
1462 // If the stored value is larger or equal to the loaded value, we can
1464 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
1465 UnavailableBlocks.push_back(DepBB);
1469 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
1473 UnavailableBlocks.push_back(DepBB);
1477 // If we have no predecessors that produce a known value for this load, exit
1479 if (ValuesPerBlock.empty()) return false;
1481 // If all of the instructions we depend on produce a known value for this
1482 // load, then it is fully redundant and we can use PHI insertion to compute
1483 // its value. Insert PHIs and remove the fully redundant value now.
1484 if (UnavailableBlocks.empty()) {
1485 DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1487 // Perform PHI construction.
1488 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1489 LI->replaceAllUsesWith(V);
1491 if (isa<PHINode>(V))
1493 if (V->getType()->isPointerTy())
1494 MD->invalidateCachedPointerInfo(V);
1495 markInstructionForDeletion(LI);
1500 if (!EnablePRE || !EnableLoadPRE)
1503 // Okay, we have *some* definitions of the value. This means that the value
1504 // is available in some of our (transitive) predecessors. Lets think about
1505 // doing PRE of this load. This will involve inserting a new load into the
1506 // predecessor when it's not available. We could do this in general, but
1507 // prefer to not increase code size. As such, we only do this when we know
1508 // that we only have to insert *one* load (which means we're basically moving
1509 // the load, not inserting a new one).
1511 SmallPtrSet<BasicBlock *, 4> Blockers;
1512 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1513 Blockers.insert(UnavailableBlocks[i]);
1515 // Let's find the first basic block with more than one predecessor. Walk
1516 // backwards through predecessors if needed.
1517 BasicBlock *LoadBB = LI->getParent();
1518 BasicBlock *TmpBB = LoadBB;
1520 bool isSinglePred = false;
1521 bool allSingleSucc = true;
1522 while (TmpBB->getSinglePredecessor()) {
1523 isSinglePred = true;
1524 TmpBB = TmpBB->getSinglePredecessor();
1525 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1527 if (Blockers.count(TmpBB))
1530 // If any of these blocks has more than one successor (i.e. if the edge we
1531 // just traversed was critical), then there are other paths through this
1532 // block along which the load may not be anticipated. Hoisting the load
1533 // above this block would be adding the load to execution paths along
1534 // which it was not previously executed.
1535 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1542 // FIXME: It is extremely unclear what this loop is doing, other than
1543 // artificially restricting loadpre.
1546 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1547 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1548 if (AV.isSimpleValue())
1549 // "Hot" Instruction is in some loop (because it dominates its dep.
1551 if (Instruction *I = dyn_cast<Instruction>(AV.getSimpleValue()))
1552 if (DT->dominates(LI, I)) {
1558 // We are interested only in "hot" instructions. We don't want to do any
1559 // mis-optimizations here.
1564 // Check to see how many predecessors have the loaded value fully
1566 DenseMap<BasicBlock*, Value*> PredLoads;
1567 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1568 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1569 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
1570 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1571 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1573 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> NeedToSplit;
1574 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1576 BasicBlock *Pred = *PI;
1577 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
1580 PredLoads[Pred] = 0;
1582 if (Pred->getTerminator()->getNumSuccessors() != 1) {
1583 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1584 DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1585 << Pred->getName() << "': " << *LI << '\n');
1589 if (LoadBB->isLandingPad()) {
1591 << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
1592 << Pred->getName() << "': " << *LI << '\n');
1596 unsigned SuccNum = GetSuccessorNumber(Pred, LoadBB);
1597 NeedToSplit.push_back(std::make_pair(Pred->getTerminator(), SuccNum));
1601 if (!NeedToSplit.empty()) {
1602 toSplit.append(NeedToSplit.begin(), NeedToSplit.end());
1606 // Decide whether PRE is profitable for this load.
1607 unsigned NumUnavailablePreds = PredLoads.size();
1608 assert(NumUnavailablePreds != 0 &&
1609 "Fully available value should be eliminated above!");
1611 // If this load is unavailable in multiple predecessors, reject it.
1612 // FIXME: If we could restructure the CFG, we could make a common pred with
1613 // all the preds that don't have an available LI and insert a new load into
1615 if (NumUnavailablePreds != 1)
1618 // Check if the load can safely be moved to all the unavailable predecessors.
1619 bool CanDoPRE = true;
1620 SmallVector<Instruction*, 8> NewInsts;
1621 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1622 E = PredLoads.end(); I != E; ++I) {
1623 BasicBlock *UnavailablePred = I->first;
1625 // Do PHI translation to get its value in the predecessor if necessary. The
1626 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1628 // If all preds have a single successor, then we know it is safe to insert
1629 // the load on the pred (?!?), so we can insert code to materialize the
1630 // pointer if it is not available.
1631 PHITransAddr Address(LI->getPointerOperand(), TD);
1633 if (allSingleSucc) {
1634 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1637 Address.PHITranslateValue(LoadBB, UnavailablePred, DT);
1638 LoadPtr = Address.getAddr();
1641 // If we couldn't find or insert a computation of this phi translated value,
1644 DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1645 << *LI->getPointerOperand() << "\n");
1650 // Make sure it is valid to move this load here. We have to watch out for:
1651 // @1 = getelementptr (i8* p, ...
1652 // test p and branch if == 0
1654 // It is valid to have the getelementptr before the test, even if p can
1655 // be 0, as getelementptr only does address arithmetic.
1656 // If we are not pushing the value through any multiple-successor blocks
1657 // we do not have this case. Otherwise, check that the load is safe to
1658 // put anywhere; this can be improved, but should be conservatively safe.
1659 if (!allSingleSucc &&
1660 // FIXME: REEVALUTE THIS.
1661 !isSafeToLoadUnconditionally(LoadPtr,
1662 UnavailablePred->getTerminator(),
1663 LI->getAlignment(), TD)) {
1668 I->second = LoadPtr;
1672 while (!NewInsts.empty()) {
1673 Instruction *I = NewInsts.pop_back_val();
1674 if (MD) MD->removeInstruction(I);
1675 I->eraseFromParent();
1680 // Okay, we can eliminate this load by inserting a reload in the predecessor
1681 // and using PHI construction to get the value in the other predecessors, do
1683 DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1684 DEBUG(if (!NewInsts.empty())
1685 dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
1686 << *NewInsts.back() << '\n');
1688 // Assign value numbers to the new instructions.
1689 for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
1690 // FIXME: We really _ought_ to insert these value numbers into their
1691 // parent's availability map. However, in doing so, we risk getting into
1692 // ordering issues. If a block hasn't been processed yet, we would be
1693 // marking a value as AVAIL-IN, which isn't what we intend.
1694 VN.lookup_or_add(NewInsts[i]);
1697 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1698 E = PredLoads.end(); I != E; ++I) {
1699 BasicBlock *UnavailablePred = I->first;
1700 Value *LoadPtr = I->second;
1702 Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1704 UnavailablePred->getTerminator());
1706 // Transfer the old load's TBAA tag to the new load.
1707 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1708 NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1710 // Transfer DebugLoc.
1711 NewLoad->setDebugLoc(LI->getDebugLoc());
1713 // Add the newly created load.
1714 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1716 MD->invalidateCachedPointerInfo(LoadPtr);
1717 DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1720 // Perform PHI construction.
1721 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1722 LI->replaceAllUsesWith(V);
1723 if (isa<PHINode>(V))
1725 if (V->getType()->isPointerTy())
1726 MD->invalidateCachedPointerInfo(V);
1727 markInstructionForDeletion(LI);
1732 /// processLoad - Attempt to eliminate a load, first by eliminating it
1733 /// locally, and then attempting non-local elimination if that fails.
1734 bool GVN::processLoad(LoadInst *L) {
1741 if (L->use_empty()) {
1742 markInstructionForDeletion(L);
1746 // ... to a pointer that has been loaded from before...
1747 MemDepResult Dep = MD->getDependency(L);
1749 // If we have a clobber and target data is around, see if this is a clobber
1750 // that we can fix up through code synthesis.
1751 if (Dep.isClobber() && TD) {
1752 // Check to see if we have something like this:
1753 // store i32 123, i32* %P
1754 // %A = bitcast i32* %P to i8*
1755 // %B = gep i8* %A, i32 1
1758 // We could do that by recognizing if the clobber instructions are obviously
1759 // a common base + constant offset, and if the previous store (or memset)
1760 // completely covers this load. This sort of thing can happen in bitfield
1762 Value *AvailVal = 0;
1763 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1764 int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1765 L->getPointerOperand(),
1768 AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1769 L->getType(), L, *TD);
1772 // Check to see if we have something like this:
1775 // if we have this, replace the later with an extraction from the former.
1776 if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1777 // If this is a clobber and L is the first instruction in its block, then
1778 // we have the first instruction in the entry block.
1782 int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1783 L->getPointerOperand(),
1786 AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
1789 // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1790 // a value on from it.
1791 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
1792 int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1793 L->getPointerOperand(),
1796 AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *TD);
1800 DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
1801 << *AvailVal << '\n' << *L << "\n\n\n");
1803 // Replace the load!
1804 L->replaceAllUsesWith(AvailVal);
1805 if (AvailVal->getType()->isPointerTy())
1806 MD->invalidateCachedPointerInfo(AvailVal);
1807 markInstructionForDeletion(L);
1813 // If the value isn't available, don't do anything!
1814 if (Dep.isClobber()) {
1816 // fast print dep, using operator<< on instruction is too slow.
1817 dbgs() << "GVN: load ";
1818 WriteAsOperand(dbgs(), L);
1819 Instruction *I = Dep.getInst();
1820 dbgs() << " is clobbered by " << *I << '\n';
1825 // If it is defined in another block, try harder.
1826 if (Dep.isNonLocal())
1827 return processNonLocalLoad(L);
1831 // fast print dep, using operator<< on instruction is too slow.
1832 dbgs() << "GVN: load ";
1833 WriteAsOperand(dbgs(), L);
1834 dbgs() << " has unknown dependence\n";
1839 Instruction *DepInst = Dep.getInst();
1840 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1841 Value *StoredVal = DepSI->getValueOperand();
1843 // The store and load are to a must-aliased pointer, but they may not
1844 // actually have the same type. See if we know how to reuse the stored
1845 // value (depending on its type).
1846 if (StoredVal->getType() != L->getType()) {
1848 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1853 DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1854 << '\n' << *L << "\n\n\n");
1861 L->replaceAllUsesWith(StoredVal);
1862 if (StoredVal->getType()->isPointerTy())
1863 MD->invalidateCachedPointerInfo(StoredVal);
1864 markInstructionForDeletion(L);
1869 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1870 Value *AvailableVal = DepLI;
1872 // The loads are of a must-aliased pointer, but they may not actually have
1873 // the same type. See if we know how to reuse the previously loaded value
1874 // (depending on its type).
1875 if (DepLI->getType() != L->getType()) {
1877 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1879 if (AvailableVal == 0)
1882 DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1883 << "\n" << *L << "\n\n\n");
1890 L->replaceAllUsesWith(AvailableVal);
1891 if (DepLI->getType()->isPointerTy())
1892 MD->invalidateCachedPointerInfo(DepLI);
1893 markInstructionForDeletion(L);
1898 // If this load really doesn't depend on anything, then we must be loading an
1899 // undef value. This can happen when loading for a fresh allocation with no
1900 // intervening stores, for example.
1901 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
1902 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1903 markInstructionForDeletion(L);
1908 // If this load occurs either right after a lifetime begin,
1909 // then the loaded value is undefined.
1910 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
1911 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1912 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1913 markInstructionForDeletion(L);
1922 // findLeader - In order to find a leader for a given value number at a
1923 // specific basic block, we first obtain the list of all Values for that number,
1924 // and then scan the list to find one whose block dominates the block in
1925 // question. This is fast because dominator tree queries consist of only
1926 // a few comparisons of DFS numbers.
1927 Value *GVN::findLeader(BasicBlock *BB, uint32_t num) {
1928 LeaderTableEntry Vals = LeaderTable[num];
1929 if (!Vals.Val) return 0;
1932 if (DT->dominates(Vals.BB, BB)) {
1934 if (isa<Constant>(Val)) return Val;
1937 LeaderTableEntry* Next = Vals.Next;
1939 if (DT->dominates(Next->BB, BB)) {
1940 if (isa<Constant>(Next->Val)) return Next->Val;
1941 if (!Val) Val = Next->Val;
1950 /// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
1951 /// use is dominated by the given basic block. Returns the number of uses that
1953 unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
1956 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1958 Use &U = (UI++).getUse();
1960 // If From occurs as a phi node operand then the use implicitly lives in the
1961 // corresponding incoming block. Otherwise it is the block containing the
1962 // user that must be dominated by Root.
1963 BasicBlock *UsingBlock;
1964 if (PHINode *PN = dyn_cast<PHINode>(U.getUser()))
1965 UsingBlock = PN->getIncomingBlock(U);
1967 UsingBlock = cast<Instruction>(U.getUser())->getParent();
1969 if (DT->dominates(Root, UsingBlock)) {
1977 /// propagateEquality - The given values are known to be equal in every block
1978 /// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
1979 /// 'RHS' everywhere in the scope. Returns whether a change was made.
1980 bool GVN::propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root) {
1981 if (LHS == RHS) return false;
1982 assert(LHS->getType() == RHS->getType() && "Equal but types differ!");
1984 // Don't try to propagate equalities between constants.
1985 if (isa<Constant>(LHS) && isa<Constant>(RHS))
1988 // Prefer a constant on the right-hand side, or an Argument if no constants.
1989 if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
1990 std::swap(LHS, RHS);
1991 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) && "Unexpected value!");
1993 // If there is no obvious reason to prefer the left-hand side over the right-
1994 // hand side, ensure the longest lived term is on the right-hand side, so the
1995 // shortest lived term will be replaced by the longest lived. This tends to
1996 // expose more simplifications.
1997 uint32_t LVN = VN.lookup_or_add(LHS);
1998 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
1999 (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
2000 // Move the 'oldest' value to the right-hand side, using the value number as
2002 uint32_t RVN = VN.lookup_or_add(RHS);
2004 std::swap(LHS, RHS);
2009 // If value numbering later deduces that an instruction in the scope is equal
2010 // to 'LHS' then ensure it will be turned into 'RHS'.
2011 addToLeaderTable(LVN, RHS, Root);
2013 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
2014 // LHS always has at least one use that is not dominated by Root, this will
2015 // never do anything if LHS has only one use.
2016 bool Changed = false;
2017 if (!LHS->hasOneUse()) {
2018 unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
2019 Changed |= NumReplacements > 0;
2020 NumGVNEqProp += NumReplacements;
2023 // Now try to deduce additional equalities from this one. For example, if the
2024 // known equality was "(A != B)" == "false" then it follows that A and B are
2025 // equal in the scope. Only boolean equalities with an explicit true or false
2026 // RHS are currently supported.
2027 if (!RHS->getType()->isIntegerTy(1))
2028 // Not a boolean equality - bail out.
2030 ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
2032 // RHS neither 'true' nor 'false' - bail out.
2034 // Whether RHS equals 'true'. Otherwise it equals 'false'.
2035 bool isKnownTrue = CI->isAllOnesValue();
2036 bool isKnownFalse = !isKnownTrue;
2038 // If "A && B" is known true then both A and B are known true. If "A || B"
2039 // is known false then both A and B are known false.
2041 if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
2042 (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
2043 Changed |= propagateEquality(A, RHS, Root);
2044 Changed |= propagateEquality(B, RHS, Root);
2048 // If we are propagating an equality like "(A == B)" == "true" then also
2049 // propagate the equality A == B. When propagating a comparison such as
2050 // "(A >= B)" == "true", replace all instances of "A < B" with "false".
2051 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
2052 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
2054 // If "A == B" is known true, or "A != B" is known false, then replace
2055 // A with B everywhere in the scope.
2056 if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
2057 (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE))
2058 Changed |= propagateEquality(Op0, Op1, Root);
2060 // If "A >= B" is known true, replace "A < B" with false everywhere.
2061 CmpInst::Predicate NotPred = Cmp->getInversePredicate();
2062 Constant *NotVal = ConstantInt::get(Cmp->getType(), isKnownFalse);
2063 // Since we don't have the instruction "A < B" immediately to hand, work out
2064 // the value number that it would have and use that to find an appropriate
2065 // instruction (if any).
2066 uint32_t NextNum = VN.getNextUnusedValueNumber();
2067 uint32_t Num = VN.lookup_or_add_cmp(Cmp->getOpcode(), NotPred, Op0, Op1);
2068 // If the number we were assigned was brand new then there is no point in
2069 // looking for an instruction realizing it: there cannot be one!
2070 if (Num < NextNum) {
2071 Value *NotCmp = findLeader(Root, Num);
2072 if (NotCmp && isa<Instruction>(NotCmp)) {
2073 unsigned NumReplacements =
2074 replaceAllDominatedUsesWith(NotCmp, NotVal, Root);
2075 Changed |= NumReplacements > 0;
2076 NumGVNEqProp += NumReplacements;
2079 // Ensure that any instruction in scope that gets the "A < B" value number
2080 // is replaced with false.
2081 addToLeaderTable(Num, NotVal, Root);
2089 /// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'. Return
2090 /// true if every path from the entry block to 'Dst' passes via this edge. In
2091 /// particular 'Dst' must not be reachable via another edge from 'Src'.
2092 static bool isOnlyReachableViaThisEdge(BasicBlock *Src, BasicBlock *Dst,
2093 DominatorTree *DT) {
2094 // While in theory it is interesting to consider the case in which Dst has
2095 // more than one predecessor, because Dst might be part of a loop which is
2096 // only reachable from Src, in practice it is pointless since at the time
2097 // GVN runs all such loops have preheaders, which means that Dst will have
2098 // been changed to have only one predecessor, namely Src.
2099 BasicBlock *Pred = Dst->getSinglePredecessor();
2100 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
2105 /// processInstruction - When calculating availability, handle an instruction
2106 /// by inserting it into the appropriate sets
2107 bool GVN::processInstruction(Instruction *I) {
2108 // Ignore dbg info intrinsics.
2109 if (isa<DbgInfoIntrinsic>(I))
2112 // If the instruction can be easily simplified then do so now in preference
2113 // to value numbering it. Value numbering often exposes redundancies, for
2114 // example if it determines that %y is equal to %x then the instruction
2115 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
2116 if (Value *V = SimplifyInstruction(I, TD, TLI, DT)) {
2117 I->replaceAllUsesWith(V);
2118 if (MD && V->getType()->isPointerTy())
2119 MD->invalidateCachedPointerInfo(V);
2120 markInstructionForDeletion(I);
2125 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2126 if (processLoad(LI))
2129 unsigned Num = VN.lookup_or_add(LI);
2130 addToLeaderTable(Num, LI, LI->getParent());
2134 // For conditional branches, we can perform simple conditional propagation on
2135 // the condition value itself.
2136 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
2137 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
2140 Value *BranchCond = BI->getCondition();
2142 BasicBlock *TrueSucc = BI->getSuccessor(0);
2143 BasicBlock *FalseSucc = BI->getSuccessor(1);
2144 BasicBlock *Parent = BI->getParent();
2145 bool Changed = false;
2147 if (isOnlyReachableViaThisEdge(Parent, TrueSucc, DT))
2148 Changed |= propagateEquality(BranchCond,
2149 ConstantInt::getTrue(TrueSucc->getContext()),
2152 if (isOnlyReachableViaThisEdge(Parent, FalseSucc, DT))
2153 Changed |= propagateEquality(BranchCond,
2154 ConstantInt::getFalse(FalseSucc->getContext()),
2160 // For switches, propagate the case values into the case destinations.
2161 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2162 Value *SwitchCond = SI->getCondition();
2163 BasicBlock *Parent = SI->getParent();
2164 bool Changed = false;
2165 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
2166 BasicBlock *Dst = SI->getCaseSuccessor(i);
2167 if (isOnlyReachableViaThisEdge(Parent, Dst, DT))
2168 Changed |= propagateEquality(SwitchCond, SI->getCaseValue(i), Dst);
2173 // Instructions with void type don't return a value, so there's
2174 // no point in trying to find redundancies in them.
2175 if (I->getType()->isVoidTy()) return false;
2177 uint32_t NextNum = VN.getNextUnusedValueNumber();
2178 unsigned Num = VN.lookup_or_add(I);
2180 // Allocations are always uniquely numbered, so we can save time and memory
2181 // by fast failing them.
2182 if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
2183 addToLeaderTable(Num, I, I->getParent());
2187 // If the number we were assigned was a brand new VN, then we don't
2188 // need to do a lookup to see if the number already exists
2189 // somewhere in the domtree: it can't!
2190 if (Num >= NextNum) {
2191 addToLeaderTable(Num, I, I->getParent());
2195 // Perform fast-path value-number based elimination of values inherited from
2197 Value *repl = findLeader(I->getParent(), Num);
2199 // Failure, just remember this instance for future use.
2200 addToLeaderTable(Num, I, I->getParent());
2205 I->replaceAllUsesWith(repl);
2206 if (MD && repl->getType()->isPointerTy())
2207 MD->invalidateCachedPointerInfo(repl);
2208 markInstructionForDeletion(I);
2212 /// runOnFunction - This is the main transformation entry point for a function.
2213 bool GVN::runOnFunction(Function& F) {
2215 MD = &getAnalysis<MemoryDependenceAnalysis>();
2216 DT = &getAnalysis<DominatorTree>();
2217 TD = getAnalysisIfAvailable<TargetData>();
2218 TLI = &getAnalysis<TargetLibraryInfo>();
2219 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
2223 bool Changed = false;
2224 bool ShouldContinue = true;
2226 // Merge unconditional branches, allowing PRE to catch more
2227 // optimization opportunities.
2228 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
2229 BasicBlock *BB = FI++;
2231 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
2232 if (removedBlock) ++NumGVNBlocks;
2234 Changed |= removedBlock;
2237 unsigned Iteration = 0;
2238 while (ShouldContinue) {
2239 DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
2240 ShouldContinue = iterateOnFunction(F);
2241 if (splitCriticalEdges())
2242 ShouldContinue = true;
2243 Changed |= ShouldContinue;
2248 bool PREChanged = true;
2249 while (PREChanged) {
2250 PREChanged = performPRE(F);
2251 Changed |= PREChanged;
2254 // FIXME: Should perform GVN again after PRE does something. PRE can move
2255 // computations into blocks where they become fully redundant. Note that
2256 // we can't do this until PRE's critical edge splitting updates memdep.
2257 // Actually, when this happens, we should just fully integrate PRE into GVN.
2259 cleanupGlobalSets();
2265 bool GVN::processBlock(BasicBlock *BB) {
2266 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2267 // (and incrementing BI before processing an instruction).
2268 assert(InstrsToErase.empty() &&
2269 "We expect InstrsToErase to be empty across iterations");
2270 bool ChangedFunction = false;
2272 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2274 ChangedFunction |= processInstruction(BI);
2275 if (InstrsToErase.empty()) {
2280 // If we need some instructions deleted, do it now.
2281 NumGVNInstr += InstrsToErase.size();
2283 // Avoid iterator invalidation.
2284 bool AtStart = BI == BB->begin();
2288 for (SmallVector<Instruction*, 4>::iterator I = InstrsToErase.begin(),
2289 E = InstrsToErase.end(); I != E; ++I) {
2290 DEBUG(dbgs() << "GVN removed: " << **I << '\n');
2291 if (MD) MD->removeInstruction(*I);
2292 (*I)->eraseFromParent();
2293 DEBUG(verifyRemoved(*I));
2295 InstrsToErase.clear();
2303 return ChangedFunction;
2306 /// performPRE - Perform a purely local form of PRE that looks for diamond
2307 /// control flow patterns and attempts to perform simple PRE at the join point.
2308 bool GVN::performPRE(Function &F) {
2309 bool Changed = false;
2310 DenseMap<BasicBlock*, Value*> predMap;
2311 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2312 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
2313 BasicBlock *CurrentBlock = *DI;
2315 // Nothing to PRE in the entry block.
2316 if (CurrentBlock == &F.getEntryBlock()) continue;
2318 // Don't perform PRE on a landing pad.
2319 if (CurrentBlock->isLandingPad()) continue;
2321 for (BasicBlock::iterator BI = CurrentBlock->begin(),
2322 BE = CurrentBlock->end(); BI != BE; ) {
2323 Instruction *CurInst = BI++;
2325 if (isa<AllocaInst>(CurInst) ||
2326 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
2327 CurInst->getType()->isVoidTy() ||
2328 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
2329 isa<DbgInfoIntrinsic>(CurInst))
2332 // We don't currently value number ANY inline asm calls.
2333 if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2334 if (CallI->isInlineAsm())
2337 uint32_t ValNo = VN.lookup(CurInst);
2339 // Look for the predecessors for PRE opportunities. We're
2340 // only trying to solve the basic diamond case, where
2341 // a value is computed in the successor and one predecessor,
2342 // but not the other. We also explicitly disallow cases
2343 // where the successor is its own predecessor, because they're
2344 // more complicated to get right.
2345 unsigned NumWith = 0;
2346 unsigned NumWithout = 0;
2347 BasicBlock *PREPred = 0;
2350 for (pred_iterator PI = pred_begin(CurrentBlock),
2351 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
2352 BasicBlock *P = *PI;
2353 // We're not interested in PRE where the block is its
2354 // own predecessor, or in blocks with predecessors
2355 // that are not reachable.
2356 if (P == CurrentBlock) {
2359 } else if (!DT->dominates(&F.getEntryBlock(), P)) {
2364 Value* predV = findLeader(P, ValNo);
2368 } else if (predV == CurInst) {
2376 // Don't do PRE when it might increase code size, i.e. when
2377 // we would need to insert instructions in more than one pred.
2378 if (NumWithout != 1 || NumWith == 0)
2381 // Don't do PRE across indirect branch.
2382 if (isa<IndirectBrInst>(PREPred->getTerminator()))
2385 // We can't do PRE safely on a critical edge, so instead we schedule
2386 // the edge to be split and perform the PRE the next time we iterate
2388 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2389 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2390 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2394 // Instantiate the expression in the predecessor that lacked it.
2395 // Because we are going top-down through the block, all value numbers
2396 // will be available in the predecessor by the time we need them. Any
2397 // that weren't originally present will have been instantiated earlier
2399 Instruction *PREInstr = CurInst->clone();
2400 bool success = true;
2401 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2402 Value *Op = PREInstr->getOperand(i);
2403 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2406 if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
2407 PREInstr->setOperand(i, V);
2414 // Fail out if we encounter an operand that is not available in
2415 // the PRE predecessor. This is typically because of loads which
2416 // are not value numbered precisely.
2419 DEBUG(verifyRemoved(PREInstr));
2423 PREInstr->insertBefore(PREPred->getTerminator());
2424 PREInstr->setName(CurInst->getName() + ".pre");
2425 PREInstr->setDebugLoc(CurInst->getDebugLoc());
2426 predMap[PREPred] = PREInstr;
2427 VN.add(PREInstr, ValNo);
2430 // Update the availability map to include the new instruction.
2431 addToLeaderTable(ValNo, PREInstr, PREPred);
2433 // Create a PHI to make the value available in this block.
2434 pred_iterator PB = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
2435 PHINode* Phi = PHINode::Create(CurInst->getType(), std::distance(PB, PE),
2436 CurInst->getName() + ".pre-phi",
2437 CurrentBlock->begin());
2438 for (pred_iterator PI = PB; PI != PE; ++PI) {
2439 BasicBlock *P = *PI;
2440 Phi->addIncoming(predMap[P], P);
2444 addToLeaderTable(ValNo, Phi, CurrentBlock);
2445 Phi->setDebugLoc(CurInst->getDebugLoc());
2446 CurInst->replaceAllUsesWith(Phi);
2447 if (Phi->getType()->isPointerTy()) {
2448 // Because we have added a PHI-use of the pointer value, it has now
2449 // "escaped" from alias analysis' perspective. We need to inform
2451 for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
2453 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
2454 VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
2458 MD->invalidateCachedPointerInfo(Phi);
2461 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2463 DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2464 if (MD) MD->removeInstruction(CurInst);
2465 CurInst->eraseFromParent();
2466 DEBUG(verifyRemoved(CurInst));
2471 if (splitCriticalEdges())
2477 /// splitCriticalEdges - Split critical edges found during the previous
2478 /// iteration that may enable further optimization.
2479 bool GVN::splitCriticalEdges() {
2480 if (toSplit.empty())
2483 std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2484 SplitCriticalEdge(Edge.first, Edge.second, this);
2485 } while (!toSplit.empty());
2486 if (MD) MD->invalidateCachedPredecessors();
2490 /// iterateOnFunction - Executes one iteration of GVN
2491 bool GVN::iterateOnFunction(Function &F) {
2492 cleanupGlobalSets();
2494 // Top-down walk of the dominator tree
2495 bool Changed = false;
2497 // Needed for value numbering with phi construction to work.
2498 ReversePostOrderTraversal<Function*> RPOT(&F);
2499 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2500 RE = RPOT.end(); RI != RE; ++RI)
2501 Changed |= processBlock(*RI);
2503 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2504 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
2505 Changed |= processBlock(DI->getBlock());
2511 void GVN::cleanupGlobalSets() {
2513 LeaderTable.clear();
2514 TableAllocator.Reset();
2517 /// verifyRemoved - Verify that the specified instruction does not occur in our
2518 /// internal data structures.
2519 void GVN::verifyRemoved(const Instruction *Inst) const {
2520 VN.verifyRemoved(Inst);
2522 // Walk through the value number scope to make sure the instruction isn't
2523 // ferreted away in it.
2524 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
2525 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
2526 const LeaderTableEntry *Node = &I->second;
2527 assert(Node->Val != Inst && "Inst still in value numbering scope!");
2529 while (Node->Next) {
2531 assert(Node->Val != Inst && "Inst still in value numbering scope!");