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/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/Support/Allocator.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/IRBuilder.h"
45 #include "llvm/Support/PatternMatch.h"
47 using namespace PatternMatch;
49 STATISTIC(NumGVNInstr, "Number of instructions deleted");
50 STATISTIC(NumGVNLoad, "Number of loads deleted");
51 STATISTIC(NumGVNPRE, "Number of instructions PRE'd");
52 STATISTIC(NumGVNBlocks, "Number of blocks merged");
53 STATISTIC(NumGVNSimpl, "Number of instructions simplified");
54 STATISTIC(NumGVNEqProp, "Number of equalities propagated");
55 STATISTIC(NumPRELoad, "Number of loads PRE'd");
57 static cl::opt<bool> EnablePRE("enable-pre",
58 cl::init(true), cl::Hidden);
59 static cl::opt<bool> EnableLoadPRE("enable-load-pre", cl::init(true));
61 //===----------------------------------------------------------------------===//
63 //===----------------------------------------------------------------------===//
65 /// This class holds the mapping between values and value numbers. It is used
66 /// as an efficient mechanism to determine the expression-wise equivalence of
72 SmallVector<uint32_t, 4> varargs;
74 Expression(uint32_t o = ~2U) : opcode(o) { }
76 bool operator==(const Expression &other) const {
77 if (opcode != other.opcode)
79 if (opcode == ~0U || opcode == ~1U)
81 if (type != other.type)
83 if (varargs != other.varargs)
90 DenseMap<Value*, uint32_t> valueNumbering;
91 DenseMap<Expression, uint32_t> expressionNumbering;
93 MemoryDependenceAnalysis *MD;
96 uint32_t nextValueNumber;
98 Expression create_expression(Instruction* I);
99 Expression create_extractvalue_expression(ExtractValueInst* EI);
100 uint32_t lookup_or_add_call(CallInst* C);
102 ValueTable() : nextValueNumber(1) { }
103 uint32_t lookup_or_add(Value *V);
104 uint32_t lookup(Value *V) const;
105 void add(Value *V, uint32_t num);
107 void erase(Value *v);
108 void setAliasAnalysis(AliasAnalysis* A) { AA = A; }
109 AliasAnalysis *getAliasAnalysis() const { return AA; }
110 void setMemDep(MemoryDependenceAnalysis* M) { MD = M; }
111 void setDomTree(DominatorTree* D) { DT = D; }
112 uint32_t getNextUnusedValueNumber() { return nextValueNumber; }
113 void verifyRemoved(const Value *) const;
118 template <> struct DenseMapInfo<Expression> {
119 static inline Expression getEmptyKey() {
123 static inline Expression getTombstoneKey() {
127 static unsigned getHashValue(const Expression e) {
128 unsigned hash = e.opcode;
130 hash = ((unsigned)((uintptr_t)e.type >> 4) ^
131 (unsigned)((uintptr_t)e.type >> 9));
133 for (SmallVector<uint32_t, 4>::const_iterator I = e.varargs.begin(),
134 E = e.varargs.end(); I != E; ++I)
135 hash = *I + hash * 37;
139 static bool isEqual(const Expression &LHS, const Expression &RHS) {
146 //===----------------------------------------------------------------------===//
147 // ValueTable Internal Functions
148 //===----------------------------------------------------------------------===//
150 Expression ValueTable::create_expression(Instruction *I) {
152 e.type = I->getType();
153 e.opcode = I->getOpcode();
154 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
156 e.varargs.push_back(lookup_or_add(*OI));
158 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
159 e.opcode = (C->getOpcode() << 8) | C->getPredicate();
160 } else if (InsertValueInst *E = dyn_cast<InsertValueInst>(I)) {
161 for (InsertValueInst::idx_iterator II = E->idx_begin(), IE = E->idx_end();
163 e.varargs.push_back(*II);
169 Expression ValueTable::create_extractvalue_expression(ExtractValueInst *EI) {
170 assert(EI != 0 && "Not an ExtractValueInst?");
172 e.type = EI->getType();
175 IntrinsicInst *I = dyn_cast<IntrinsicInst>(EI->getAggregateOperand());
176 if (I != 0 && EI->getNumIndices() == 1 && *EI->idx_begin() == 0 ) {
177 // EI might be an extract from one of our recognised intrinsics. If it
178 // is we'll synthesize a semantically equivalent expression instead on
179 // an extract value expression.
180 switch (I->getIntrinsicID()) {
181 case Intrinsic::sadd_with_overflow:
182 case Intrinsic::uadd_with_overflow:
183 e.opcode = Instruction::Add;
185 case Intrinsic::ssub_with_overflow:
186 case Intrinsic::usub_with_overflow:
187 e.opcode = Instruction::Sub;
189 case Intrinsic::smul_with_overflow:
190 case Intrinsic::umul_with_overflow:
191 e.opcode = Instruction::Mul;
198 // Intrinsic recognized. Grab its args to finish building the expression.
199 assert(I->getNumArgOperands() == 2 &&
200 "Expect two args for recognised intrinsics.");
201 e.varargs.push_back(lookup_or_add(I->getArgOperand(0)));
202 e.varargs.push_back(lookup_or_add(I->getArgOperand(1)));
207 // Not a recognised intrinsic. Fall back to producing an extract value
209 e.opcode = EI->getOpcode();
210 for (Instruction::op_iterator OI = EI->op_begin(), OE = EI->op_end();
212 e.varargs.push_back(lookup_or_add(*OI));
214 for (ExtractValueInst::idx_iterator II = EI->idx_begin(), IE = EI->idx_end();
216 e.varargs.push_back(*II);
221 //===----------------------------------------------------------------------===//
222 // ValueTable External Functions
223 //===----------------------------------------------------------------------===//
225 /// add - Insert a value into the table with a specified value number.
226 void ValueTable::add(Value *V, uint32_t num) {
227 valueNumbering.insert(std::make_pair(V, num));
230 uint32_t ValueTable::lookup_or_add_call(CallInst* C) {
231 if (AA->doesNotAccessMemory(C)) {
232 Expression exp = create_expression(C);
233 uint32_t& e = expressionNumbering[exp];
234 if (!e) e = nextValueNumber++;
235 valueNumbering[C] = e;
237 } else if (AA->onlyReadsMemory(C)) {
238 Expression exp = create_expression(C);
239 uint32_t& e = expressionNumbering[exp];
241 e = nextValueNumber++;
242 valueNumbering[C] = e;
246 e = nextValueNumber++;
247 valueNumbering[C] = e;
251 MemDepResult local_dep = MD->getDependency(C);
253 if (!local_dep.isDef() && !local_dep.isNonLocal()) {
254 valueNumbering[C] = nextValueNumber;
255 return nextValueNumber++;
258 if (local_dep.isDef()) {
259 CallInst* local_cdep = cast<CallInst>(local_dep.getInst());
261 if (local_cdep->getNumArgOperands() != C->getNumArgOperands()) {
262 valueNumbering[C] = nextValueNumber;
263 return nextValueNumber++;
266 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
267 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
268 uint32_t cd_vn = lookup_or_add(local_cdep->getArgOperand(i));
270 valueNumbering[C] = nextValueNumber;
271 return nextValueNumber++;
275 uint32_t v = lookup_or_add(local_cdep);
276 valueNumbering[C] = v;
281 const MemoryDependenceAnalysis::NonLocalDepInfo &deps =
282 MD->getNonLocalCallDependency(CallSite(C));
283 // FIXME: Move the checking logic to MemDep!
286 // Check to see if we have a single dominating call instruction that is
288 for (unsigned i = 0, e = deps.size(); i != e; ++i) {
289 const NonLocalDepEntry *I = &deps[i];
290 if (I->getResult().isNonLocal())
293 // We don't handle non-definitions. If we already have a call, reject
294 // instruction dependencies.
295 if (!I->getResult().isDef() || cdep != 0) {
300 CallInst *NonLocalDepCall = dyn_cast<CallInst>(I->getResult().getInst());
301 // FIXME: All duplicated with non-local case.
302 if (NonLocalDepCall && DT->properlyDominates(I->getBB(), C->getParent())){
303 cdep = NonLocalDepCall;
312 valueNumbering[C] = nextValueNumber;
313 return nextValueNumber++;
316 if (cdep->getNumArgOperands() != C->getNumArgOperands()) {
317 valueNumbering[C] = nextValueNumber;
318 return nextValueNumber++;
320 for (unsigned i = 0, e = C->getNumArgOperands(); i < e; ++i) {
321 uint32_t c_vn = lookup_or_add(C->getArgOperand(i));
322 uint32_t cd_vn = lookup_or_add(cdep->getArgOperand(i));
324 valueNumbering[C] = nextValueNumber;
325 return nextValueNumber++;
329 uint32_t v = lookup_or_add(cdep);
330 valueNumbering[C] = v;
334 valueNumbering[C] = nextValueNumber;
335 return nextValueNumber++;
339 /// lookup_or_add - Returns the value number for the specified value, assigning
340 /// it a new number if it did not have one before.
341 uint32_t ValueTable::lookup_or_add(Value *V) {
342 DenseMap<Value*, uint32_t>::iterator VI = valueNumbering.find(V);
343 if (VI != valueNumbering.end())
346 if (!isa<Instruction>(V)) {
347 valueNumbering[V] = nextValueNumber;
348 return nextValueNumber++;
351 Instruction* I = cast<Instruction>(V);
353 switch (I->getOpcode()) {
354 case Instruction::Call:
355 return lookup_or_add_call(cast<CallInst>(I));
356 case Instruction::Add:
357 case Instruction::FAdd:
358 case Instruction::Sub:
359 case Instruction::FSub:
360 case Instruction::Mul:
361 case Instruction::FMul:
362 case Instruction::UDiv:
363 case Instruction::SDiv:
364 case Instruction::FDiv:
365 case Instruction::URem:
366 case Instruction::SRem:
367 case Instruction::FRem:
368 case Instruction::Shl:
369 case Instruction::LShr:
370 case Instruction::AShr:
371 case Instruction::And:
372 case Instruction::Or :
373 case Instruction::Xor:
374 case Instruction::ICmp:
375 case Instruction::FCmp:
376 case Instruction::Trunc:
377 case Instruction::ZExt:
378 case Instruction::SExt:
379 case Instruction::FPToUI:
380 case Instruction::FPToSI:
381 case Instruction::UIToFP:
382 case Instruction::SIToFP:
383 case Instruction::FPTrunc:
384 case Instruction::FPExt:
385 case Instruction::PtrToInt:
386 case Instruction::IntToPtr:
387 case Instruction::BitCast:
388 case Instruction::Select:
389 case Instruction::ExtractElement:
390 case Instruction::InsertElement:
391 case Instruction::ShuffleVector:
392 case Instruction::InsertValue:
393 case Instruction::GetElementPtr:
394 exp = create_expression(I);
396 case Instruction::ExtractValue:
397 exp = create_extractvalue_expression(cast<ExtractValueInst>(I));
400 valueNumbering[V] = nextValueNumber;
401 return nextValueNumber++;
404 uint32_t& e = expressionNumbering[exp];
405 if (!e) e = nextValueNumber++;
406 valueNumbering[V] = e;
410 /// lookup - Returns the value number of the specified value. Fails if
411 /// the value has not yet been numbered.
412 uint32_t ValueTable::lookup(Value *V) const {
413 DenseMap<Value*, uint32_t>::const_iterator VI = valueNumbering.find(V);
414 assert(VI != valueNumbering.end() && "Value not numbered?");
418 /// clear - Remove all entries from the ValueTable.
419 void ValueTable::clear() {
420 valueNumbering.clear();
421 expressionNumbering.clear();
425 /// erase - Remove a value from the value numbering.
426 void ValueTable::erase(Value *V) {
427 valueNumbering.erase(V);
430 /// verifyRemoved - Verify that the value is removed from all internal data
432 void ValueTable::verifyRemoved(const Value *V) const {
433 for (DenseMap<Value*, uint32_t>::const_iterator
434 I = valueNumbering.begin(), E = valueNumbering.end(); I != E; ++I) {
435 assert(I->first != V && "Inst still occurs in value numbering map!");
439 //===----------------------------------------------------------------------===//
441 //===----------------------------------------------------------------------===//
445 class GVN : public FunctionPass {
447 MemoryDependenceAnalysis *MD;
449 const TargetData *TD;
450 const TargetLibraryInfo *TLI;
454 /// LeaderTable - A mapping from value numbers to lists of Value*'s that
455 /// have that value number. Use findLeader to query it.
456 struct LeaderTableEntry {
459 LeaderTableEntry *Next;
461 DenseMap<uint32_t, LeaderTableEntry> LeaderTable;
462 BumpPtrAllocator TableAllocator;
464 SmallVector<Instruction*, 8> InstrsToErase;
466 static char ID; // Pass identification, replacement for typeid
467 explicit GVN(bool noloads = false)
468 : FunctionPass(ID), NoLoads(noloads), MD(0) {
469 initializeGVNPass(*PassRegistry::getPassRegistry());
472 bool runOnFunction(Function &F);
474 /// markInstructionForDeletion - This removes the specified instruction from
475 /// our various maps and marks it for deletion.
476 void markInstructionForDeletion(Instruction *I) {
478 InstrsToErase.push_back(I);
481 const TargetData *getTargetData() const { return TD; }
482 DominatorTree &getDominatorTree() const { return *DT; }
483 AliasAnalysis *getAliasAnalysis() const { return VN.getAliasAnalysis(); }
484 MemoryDependenceAnalysis &getMemDep() const { return *MD; }
486 /// addToLeaderTable - Push a new Value to the LeaderTable onto the list for
487 /// its value number.
488 void addToLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
489 LeaderTableEntry &Curr = LeaderTable[N];
496 LeaderTableEntry *Node = TableAllocator.Allocate<LeaderTableEntry>();
499 Node->Next = Curr.Next;
503 /// removeFromLeaderTable - Scan the list of values corresponding to a given
504 /// value number, and remove the given value if encountered.
505 void removeFromLeaderTable(uint32_t N, Value *V, BasicBlock *BB) {
506 LeaderTableEntry* Prev = 0;
507 LeaderTableEntry* Curr = &LeaderTable[N];
509 while (Curr->Val != V || Curr->BB != BB) {
515 Prev->Next = Curr->Next;
521 LeaderTableEntry* Next = Curr->Next;
522 Curr->Val = Next->Val;
524 Curr->Next = Next->Next;
529 // List of critical edges to be split between iterations.
530 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> toSplit;
532 // This transformation requires dominator postdominator info
533 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
534 AU.addRequired<DominatorTree>();
535 AU.addRequired<TargetLibraryInfo>();
537 AU.addRequired<MemoryDependenceAnalysis>();
538 AU.addRequired<AliasAnalysis>();
540 AU.addPreserved<DominatorTree>();
541 AU.addPreserved<AliasAnalysis>();
546 // FIXME: eliminate or document these better
547 bool processLoad(LoadInst *L);
548 bool processInstruction(Instruction *I);
549 bool processNonLocalLoad(LoadInst *L);
550 bool processBlock(BasicBlock *BB);
551 void dump(DenseMap<uint32_t, Value*> &d);
552 bool iterateOnFunction(Function &F);
553 bool performPRE(Function &F);
554 Value *findLeader(BasicBlock *BB, uint32_t num);
555 void cleanupGlobalSets();
556 void verifyRemoved(const Instruction *I) const;
557 bool splitCriticalEdges();
558 unsigned replaceAllDominatedUsesWith(Value *From, Value *To,
560 bool propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root);
566 // createGVNPass - The public interface to this file...
567 FunctionPass *llvm::createGVNPass(bool NoLoads) {
568 return new GVN(NoLoads);
571 INITIALIZE_PASS_BEGIN(GVN, "gvn", "Global Value Numbering", false, false)
572 INITIALIZE_PASS_DEPENDENCY(MemoryDependenceAnalysis)
573 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
574 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
575 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
576 INITIALIZE_PASS_END(GVN, "gvn", "Global Value Numbering", false, false)
578 void GVN::dump(DenseMap<uint32_t, Value*>& d) {
580 for (DenseMap<uint32_t, Value*>::iterator I = d.begin(),
581 E = d.end(); I != E; ++I) {
582 errs() << I->first << "\n";
588 /// IsValueFullyAvailableInBlock - Return true if we can prove that the value
589 /// we're analyzing is fully available in the specified block. As we go, keep
590 /// track of which blocks we know are fully alive in FullyAvailableBlocks. This
591 /// map is actually a tri-state map with the following values:
592 /// 0) we know the block *is not* fully available.
593 /// 1) we know the block *is* fully available.
594 /// 2) we do not know whether the block is fully available or not, but we are
595 /// currently speculating that it will be.
596 /// 3) we are speculating for this block and have used that to speculate for
598 static bool IsValueFullyAvailableInBlock(BasicBlock *BB,
599 DenseMap<BasicBlock*, char> &FullyAvailableBlocks) {
600 // Optimistically assume that the block is fully available and check to see
601 // if we already know about this block in one lookup.
602 std::pair<DenseMap<BasicBlock*, char>::iterator, char> IV =
603 FullyAvailableBlocks.insert(std::make_pair(BB, 2));
605 // If the entry already existed for this block, return the precomputed value.
607 // If this is a speculative "available" value, mark it as being used for
608 // speculation of other blocks.
609 if (IV.first->second == 2)
610 IV.first->second = 3;
611 return IV.first->second != 0;
614 // Otherwise, see if it is fully available in all predecessors.
615 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
617 // If this block has no predecessors, it isn't live-in here.
619 goto SpeculationFailure;
621 for (; PI != PE; ++PI)
622 // If the value isn't fully available in one of our predecessors, then it
623 // isn't fully available in this block either. Undo our previous
624 // optimistic assumption and bail out.
625 if (!IsValueFullyAvailableInBlock(*PI, FullyAvailableBlocks))
626 goto SpeculationFailure;
630 // SpeculationFailure - If we get here, we found out that this is not, after
631 // all, a fully-available block. We have a problem if we speculated on this and
632 // used the speculation to mark other blocks as available.
634 char &BBVal = FullyAvailableBlocks[BB];
636 // If we didn't speculate on this, just return with it set to false.
642 // If we did speculate on this value, we could have blocks set to 1 that are
643 // incorrect. Walk the (transitive) successors of this block and mark them as
645 SmallVector<BasicBlock*, 32> BBWorklist;
646 BBWorklist.push_back(BB);
649 BasicBlock *Entry = BBWorklist.pop_back_val();
650 // Note that this sets blocks to 0 (unavailable) if they happen to not
651 // already be in FullyAvailableBlocks. This is safe.
652 char &EntryVal = FullyAvailableBlocks[Entry];
653 if (EntryVal == 0) continue; // Already unavailable.
655 // Mark as unavailable.
658 for (succ_iterator I = succ_begin(Entry), E = succ_end(Entry); I != E; ++I)
659 BBWorklist.push_back(*I);
660 } while (!BBWorklist.empty());
666 /// CanCoerceMustAliasedValueToLoad - Return true if
667 /// CoerceAvailableValueToLoadType will succeed.
668 static bool CanCoerceMustAliasedValueToLoad(Value *StoredVal,
670 const TargetData &TD) {
671 // If the loaded or stored value is an first class array or struct, don't try
672 // to transform them. We need to be able to bitcast to integer.
673 if (LoadTy->isStructTy() || LoadTy->isArrayTy() ||
674 StoredVal->getType()->isStructTy() ||
675 StoredVal->getType()->isArrayTy())
678 // The store has to be at least as big as the load.
679 if (TD.getTypeSizeInBits(StoredVal->getType()) <
680 TD.getTypeSizeInBits(LoadTy))
687 /// CoerceAvailableValueToLoadType - If we saw a store of a value to memory, and
688 /// then a load from a must-aliased pointer of a different type, try to coerce
689 /// the stored value. LoadedTy is the type of the load we want to replace and
690 /// InsertPt is the place to insert new instructions.
692 /// If we can't do it, return null.
693 static Value *CoerceAvailableValueToLoadType(Value *StoredVal,
695 Instruction *InsertPt,
696 const TargetData &TD) {
697 if (!CanCoerceMustAliasedValueToLoad(StoredVal, LoadedTy, TD))
700 // If this is already the right type, just return it.
701 Type *StoredValTy = StoredVal->getType();
703 uint64_t StoreSize = TD.getTypeSizeInBits(StoredValTy);
704 uint64_t LoadSize = TD.getTypeSizeInBits(LoadedTy);
706 // If the store and reload are the same size, we can always reuse it.
707 if (StoreSize == LoadSize) {
708 // Pointer to Pointer -> use bitcast.
709 if (StoredValTy->isPointerTy() && LoadedTy->isPointerTy())
710 return new BitCastInst(StoredVal, LoadedTy, "", InsertPt);
712 // Convert source pointers to integers, which can be bitcast.
713 if (StoredValTy->isPointerTy()) {
714 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
715 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
718 Type *TypeToCastTo = LoadedTy;
719 if (TypeToCastTo->isPointerTy())
720 TypeToCastTo = TD.getIntPtrType(StoredValTy->getContext());
722 if (StoredValTy != TypeToCastTo)
723 StoredVal = new BitCastInst(StoredVal, TypeToCastTo, "", InsertPt);
725 // Cast to pointer if the load needs a pointer type.
726 if (LoadedTy->isPointerTy())
727 StoredVal = new IntToPtrInst(StoredVal, LoadedTy, "", InsertPt);
732 // If the loaded value is smaller than the available value, then we can
733 // extract out a piece from it. If the available value is too small, then we
734 // can't do anything.
735 assert(StoreSize >= LoadSize && "CanCoerceMustAliasedValueToLoad fail");
737 // Convert source pointers to integers, which can be manipulated.
738 if (StoredValTy->isPointerTy()) {
739 StoredValTy = TD.getIntPtrType(StoredValTy->getContext());
740 StoredVal = new PtrToIntInst(StoredVal, StoredValTy, "", InsertPt);
743 // Convert vectors and fp to integer, which can be manipulated.
744 if (!StoredValTy->isIntegerTy()) {
745 StoredValTy = IntegerType::get(StoredValTy->getContext(), StoreSize);
746 StoredVal = new BitCastInst(StoredVal, StoredValTy, "", InsertPt);
749 // If this is a big-endian system, we need to shift the value down to the low
750 // bits so that a truncate will work.
751 if (TD.isBigEndian()) {
752 Constant *Val = ConstantInt::get(StoredVal->getType(), StoreSize-LoadSize);
753 StoredVal = BinaryOperator::CreateLShr(StoredVal, Val, "tmp", InsertPt);
756 // Truncate the integer to the right size now.
757 Type *NewIntTy = IntegerType::get(StoredValTy->getContext(), LoadSize);
758 StoredVal = new TruncInst(StoredVal, NewIntTy, "trunc", InsertPt);
760 if (LoadedTy == NewIntTy)
763 // If the result is a pointer, inttoptr.
764 if (LoadedTy->isPointerTy())
765 return new IntToPtrInst(StoredVal, LoadedTy, "inttoptr", InsertPt);
767 // Otherwise, bitcast.
768 return new BitCastInst(StoredVal, LoadedTy, "bitcast", InsertPt);
771 /// AnalyzeLoadFromClobberingWrite - This function is called when we have a
772 /// memdep query of a load that ends up being a clobbering memory write (store,
773 /// memset, memcpy, memmove). This means that the write *may* provide bits used
774 /// by the load but we can't be sure because the pointers don't mustalias.
776 /// Check this case to see if there is anything more we can do before we give
777 /// up. This returns -1 if we have to give up, or a byte number in the stored
778 /// value of the piece that feeds the load.
779 static int AnalyzeLoadFromClobberingWrite(Type *LoadTy, Value *LoadPtr,
781 uint64_t WriteSizeInBits,
782 const TargetData &TD) {
783 // If the loaded or stored value is a first class array or struct, don't try
784 // to transform them. We need to be able to bitcast to integer.
785 if (LoadTy->isStructTy() || LoadTy->isArrayTy())
788 int64_t StoreOffset = 0, LoadOffset = 0;
789 Value *StoreBase = GetPointerBaseWithConstantOffset(WritePtr, StoreOffset,TD);
790 Value *LoadBase = GetPointerBaseWithConstantOffset(LoadPtr, LoadOffset, TD);
791 if (StoreBase != LoadBase)
794 // If the load and store are to the exact same address, they should have been
795 // a must alias. AA must have gotten confused.
796 // FIXME: Study to see if/when this happens. One case is forwarding a memset
797 // to a load from the base of the memset.
799 if (LoadOffset == StoreOffset) {
800 dbgs() << "STORE/LOAD DEP WITH COMMON POINTER MISSED:\n"
801 << "Base = " << *StoreBase << "\n"
802 << "Store Ptr = " << *WritePtr << "\n"
803 << "Store Offs = " << StoreOffset << "\n"
804 << "Load Ptr = " << *LoadPtr << "\n";
809 // If the load and store don't overlap at all, the store doesn't provide
810 // anything to the load. In this case, they really don't alias at all, AA
811 // must have gotten confused.
812 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy);
814 if ((WriteSizeInBits & 7) | (LoadSize & 7))
816 uint64_t StoreSize = WriteSizeInBits >> 3; // Convert to bytes.
820 bool isAAFailure = false;
821 if (StoreOffset < LoadOffset)
822 isAAFailure = StoreOffset+int64_t(StoreSize) <= LoadOffset;
824 isAAFailure = LoadOffset+int64_t(LoadSize) <= StoreOffset;
828 dbgs() << "STORE LOAD DEP WITH COMMON BASE:\n"
829 << "Base = " << *StoreBase << "\n"
830 << "Store Ptr = " << *WritePtr << "\n"
831 << "Store Offs = " << StoreOffset << "\n"
832 << "Load Ptr = " << *LoadPtr << "\n";
838 // If the Load isn't completely contained within the stored bits, we don't
839 // have all the bits to feed it. We could do something crazy in the future
840 // (issue a smaller load then merge the bits in) but this seems unlikely to be
842 if (StoreOffset > LoadOffset ||
843 StoreOffset+StoreSize < LoadOffset+LoadSize)
846 // Okay, we can do this transformation. Return the number of bytes into the
847 // store that the load is.
848 return LoadOffset-StoreOffset;
851 /// AnalyzeLoadFromClobberingStore - This function is called when we have a
852 /// memdep query of a load that ends up being a clobbering store.
853 static int AnalyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr,
855 const TargetData &TD) {
856 // Cannot handle reading from store of first-class aggregate yet.
857 if (DepSI->getValueOperand()->getType()->isStructTy() ||
858 DepSI->getValueOperand()->getType()->isArrayTy())
861 Value *StorePtr = DepSI->getPointerOperand();
862 uint64_t StoreSize =TD.getTypeSizeInBits(DepSI->getValueOperand()->getType());
863 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
864 StorePtr, StoreSize, TD);
867 /// AnalyzeLoadFromClobberingLoad - This function is called when we have a
868 /// memdep query of a load that ends up being clobbered by another load. See if
869 /// the other load can feed into the second load.
870 static int AnalyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr,
871 LoadInst *DepLI, const TargetData &TD){
872 // Cannot handle reading from store of first-class aggregate yet.
873 if (DepLI->getType()->isStructTy() || DepLI->getType()->isArrayTy())
876 Value *DepPtr = DepLI->getPointerOperand();
877 uint64_t DepSize = TD.getTypeSizeInBits(DepLI->getType());
878 int R = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, DepSize, TD);
879 if (R != -1) return R;
881 // If we have a load/load clobber an DepLI can be widened to cover this load,
882 // then we should widen it!
883 int64_t LoadOffs = 0;
884 const Value *LoadBase =
885 GetPointerBaseWithConstantOffset(LoadPtr, LoadOffs, TD);
886 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
888 unsigned Size = MemoryDependenceAnalysis::
889 getLoadLoadClobberFullWidthSize(LoadBase, LoadOffs, LoadSize, DepLI, TD);
890 if (Size == 0) return -1;
892 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, DepPtr, Size*8, TD);
897 static int AnalyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr,
899 const TargetData &TD) {
900 // If the mem operation is a non-constant size, we can't handle it.
901 ConstantInt *SizeCst = dyn_cast<ConstantInt>(MI->getLength());
902 if (SizeCst == 0) return -1;
903 uint64_t MemSizeInBits = SizeCst->getZExtValue()*8;
905 // If this is memset, we just need to see if the offset is valid in the size
907 if (MI->getIntrinsicID() == Intrinsic::memset)
908 return AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr, MI->getDest(),
911 // If we have a memcpy/memmove, the only case we can handle is if this is a
912 // copy from constant memory. In that case, we can read directly from the
914 MemTransferInst *MTI = cast<MemTransferInst>(MI);
916 Constant *Src = dyn_cast<Constant>(MTI->getSource());
917 if (Src == 0) return -1;
919 GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Src, &TD));
920 if (GV == 0 || !GV->isConstant()) return -1;
922 // See if the access is within the bounds of the transfer.
923 int Offset = AnalyzeLoadFromClobberingWrite(LoadTy, LoadPtr,
924 MI->getDest(), MemSizeInBits, TD);
928 // Otherwise, see if we can constant fold a load from the constant with the
929 // offset applied as appropriate.
930 Src = ConstantExpr::getBitCast(Src,
931 llvm::Type::getInt8PtrTy(Src->getContext()));
932 Constant *OffsetCst =
933 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
934 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
935 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
936 if (ConstantFoldLoadFromConstPtr(Src, &TD))
942 /// GetStoreValueForLoad - This function is called when we have a
943 /// memdep query of a load that ends up being a clobbering store. This means
944 /// that the store provides bits used by the load but we the pointers don't
945 /// mustalias. Check this case to see if there is anything more we can do
946 /// before we give up.
947 static Value *GetStoreValueForLoad(Value *SrcVal, unsigned Offset,
949 Instruction *InsertPt, const TargetData &TD){
950 LLVMContext &Ctx = SrcVal->getType()->getContext();
952 uint64_t StoreSize = (TD.getTypeSizeInBits(SrcVal->getType()) + 7) / 8;
953 uint64_t LoadSize = (TD.getTypeSizeInBits(LoadTy) + 7) / 8;
955 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
957 // Compute which bits of the stored value are being used by the load. Convert
958 // to an integer type to start with.
959 if (SrcVal->getType()->isPointerTy())
960 SrcVal = Builder.CreatePtrToInt(SrcVal, TD.getIntPtrType(Ctx));
961 if (!SrcVal->getType()->isIntegerTy())
962 SrcVal = Builder.CreateBitCast(SrcVal, IntegerType::get(Ctx, StoreSize*8));
964 // Shift the bits to the least significant depending on endianness.
966 if (TD.isLittleEndian())
969 ShiftAmt = (StoreSize-LoadSize-Offset)*8;
972 SrcVal = Builder.CreateLShr(SrcVal, ShiftAmt);
974 if (LoadSize != StoreSize)
975 SrcVal = Builder.CreateTrunc(SrcVal, IntegerType::get(Ctx, LoadSize*8));
977 return CoerceAvailableValueToLoadType(SrcVal, LoadTy, InsertPt, TD);
980 /// GetLoadValueForLoad - This function is called when we have a
981 /// memdep query of a load that ends up being a clobbering load. This means
982 /// that the load *may* provide bits used by the load but we can't be sure
983 /// because the pointers don't mustalias. Check this case to see if there is
984 /// anything more we can do before we give up.
985 static Value *GetLoadValueForLoad(LoadInst *SrcVal, unsigned Offset,
986 Type *LoadTy, Instruction *InsertPt,
988 const TargetData &TD = *gvn.getTargetData();
989 // If Offset+LoadTy exceeds the size of SrcVal, then we must be wanting to
990 // widen SrcVal out to a larger load.
991 unsigned SrcValSize = TD.getTypeStoreSize(SrcVal->getType());
992 unsigned LoadSize = TD.getTypeStoreSize(LoadTy);
993 if (Offset+LoadSize > SrcValSize) {
994 assert(SrcVal->isSimple() && "Cannot widen volatile/atomic load!");
995 assert(SrcVal->getType()->isIntegerTy() && "Can't widen non-integer load");
996 // If we have a load/load clobber an DepLI can be widened to cover this
997 // load, then we should widen it to the next power of 2 size big enough!
998 unsigned NewLoadSize = Offset+LoadSize;
999 if (!isPowerOf2_32(NewLoadSize))
1000 NewLoadSize = NextPowerOf2(NewLoadSize);
1002 Value *PtrVal = SrcVal->getPointerOperand();
1004 // Insert the new load after the old load. This ensures that subsequent
1005 // memdep queries will find the new load. We can't easily remove the old
1006 // load completely because it is already in the value numbering table.
1007 IRBuilder<> Builder(SrcVal->getParent(), ++BasicBlock::iterator(SrcVal));
1009 IntegerType::get(LoadTy->getContext(), NewLoadSize*8);
1010 DestPTy = PointerType::get(DestPTy,
1011 cast<PointerType>(PtrVal->getType())->getAddressSpace());
1012 Builder.SetCurrentDebugLocation(SrcVal->getDebugLoc());
1013 PtrVal = Builder.CreateBitCast(PtrVal, DestPTy);
1014 LoadInst *NewLoad = Builder.CreateLoad(PtrVal);
1015 NewLoad->takeName(SrcVal);
1016 NewLoad->setAlignment(SrcVal->getAlignment());
1018 DEBUG(dbgs() << "GVN WIDENED LOAD: " << *SrcVal << "\n");
1019 DEBUG(dbgs() << "TO: " << *NewLoad << "\n");
1021 // Replace uses of the original load with the wider load. On a big endian
1022 // system, we need to shift down to get the relevant bits.
1023 Value *RV = NewLoad;
1024 if (TD.isBigEndian())
1025 RV = Builder.CreateLShr(RV,
1026 NewLoadSize*8-SrcVal->getType()->getPrimitiveSizeInBits());
1027 RV = Builder.CreateTrunc(RV, SrcVal->getType());
1028 SrcVal->replaceAllUsesWith(RV);
1030 // We would like to use gvn.markInstructionForDeletion here, but we can't
1031 // because the load is already memoized into the leader map table that GVN
1032 // tracks. It is potentially possible to remove the load from the table,
1033 // but then there all of the operations based on it would need to be
1034 // rehashed. Just leave the dead load around.
1035 gvn.getMemDep().removeInstruction(SrcVal);
1039 return GetStoreValueForLoad(SrcVal, Offset, LoadTy, InsertPt, TD);
1043 /// GetMemInstValueForLoad - This function is called when we have a
1044 /// memdep query of a load that ends up being a clobbering mem intrinsic.
1045 static Value *GetMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset,
1046 Type *LoadTy, Instruction *InsertPt,
1047 const TargetData &TD){
1048 LLVMContext &Ctx = LoadTy->getContext();
1049 uint64_t LoadSize = TD.getTypeSizeInBits(LoadTy)/8;
1051 IRBuilder<> Builder(InsertPt->getParent(), InsertPt);
1053 // We know that this method is only called when the mem transfer fully
1054 // provides the bits for the load.
1055 if (MemSetInst *MSI = dyn_cast<MemSetInst>(SrcInst)) {
1056 // memset(P, 'x', 1234) -> splat('x'), even if x is a variable, and
1057 // independently of what the offset is.
1058 Value *Val = MSI->getValue();
1060 Val = Builder.CreateZExt(Val, IntegerType::get(Ctx, LoadSize*8));
1062 Value *OneElt = Val;
1064 // Splat the value out to the right number of bits.
1065 for (unsigned NumBytesSet = 1; NumBytesSet != LoadSize; ) {
1066 // If we can double the number of bytes set, do it.
1067 if (NumBytesSet*2 <= LoadSize) {
1068 Value *ShVal = Builder.CreateShl(Val, NumBytesSet*8);
1069 Val = Builder.CreateOr(Val, ShVal);
1074 // Otherwise insert one byte at a time.
1075 Value *ShVal = Builder.CreateShl(Val, 1*8);
1076 Val = Builder.CreateOr(OneElt, ShVal);
1080 return CoerceAvailableValueToLoadType(Val, LoadTy, InsertPt, TD);
1083 // Otherwise, this is a memcpy/memmove from a constant global.
1084 MemTransferInst *MTI = cast<MemTransferInst>(SrcInst);
1085 Constant *Src = cast<Constant>(MTI->getSource());
1087 // Otherwise, see if we can constant fold a load from the constant with the
1088 // offset applied as appropriate.
1089 Src = ConstantExpr::getBitCast(Src,
1090 llvm::Type::getInt8PtrTy(Src->getContext()));
1091 Constant *OffsetCst =
1092 ConstantInt::get(Type::getInt64Ty(Src->getContext()), (unsigned)Offset);
1093 Src = ConstantExpr::getGetElementPtr(Src, OffsetCst);
1094 Src = ConstantExpr::getBitCast(Src, PointerType::getUnqual(LoadTy));
1095 return ConstantFoldLoadFromConstPtr(Src, &TD);
1100 struct AvailableValueInBlock {
1101 /// BB - The basic block in question.
1104 SimpleVal, // A simple offsetted value that is accessed.
1105 LoadVal, // A value produced by a load.
1106 MemIntrin // A memory intrinsic which is loaded from.
1109 /// V - The value that is live out of the block.
1110 PointerIntPair<Value *, 2, ValType> Val;
1112 /// Offset - The byte offset in Val that is interesting for the load query.
1115 static AvailableValueInBlock get(BasicBlock *BB, Value *V,
1116 unsigned Offset = 0) {
1117 AvailableValueInBlock Res;
1119 Res.Val.setPointer(V);
1120 Res.Val.setInt(SimpleVal);
1121 Res.Offset = Offset;
1125 static AvailableValueInBlock getMI(BasicBlock *BB, MemIntrinsic *MI,
1126 unsigned Offset = 0) {
1127 AvailableValueInBlock Res;
1129 Res.Val.setPointer(MI);
1130 Res.Val.setInt(MemIntrin);
1131 Res.Offset = Offset;
1135 static AvailableValueInBlock getLoad(BasicBlock *BB, LoadInst *LI,
1136 unsigned Offset = 0) {
1137 AvailableValueInBlock Res;
1139 Res.Val.setPointer(LI);
1140 Res.Val.setInt(LoadVal);
1141 Res.Offset = Offset;
1145 bool isSimpleValue() const { return Val.getInt() == SimpleVal; }
1146 bool isCoercedLoadValue() const { return Val.getInt() == LoadVal; }
1147 bool isMemIntrinValue() const { return Val.getInt() == MemIntrin; }
1149 Value *getSimpleValue() const {
1150 assert(isSimpleValue() && "Wrong accessor");
1151 return Val.getPointer();
1154 LoadInst *getCoercedLoadValue() const {
1155 assert(isCoercedLoadValue() && "Wrong accessor");
1156 return cast<LoadInst>(Val.getPointer());
1159 MemIntrinsic *getMemIntrinValue() const {
1160 assert(isMemIntrinValue() && "Wrong accessor");
1161 return cast<MemIntrinsic>(Val.getPointer());
1164 /// MaterializeAdjustedValue - Emit code into this block to adjust the value
1165 /// defined here to the specified type. This handles various coercion cases.
1166 Value *MaterializeAdjustedValue(Type *LoadTy, GVN &gvn) const {
1168 if (isSimpleValue()) {
1169 Res = getSimpleValue();
1170 if (Res->getType() != LoadTy) {
1171 const TargetData *TD = gvn.getTargetData();
1172 assert(TD && "Need target data to handle type mismatch case");
1173 Res = GetStoreValueForLoad(Res, Offset, LoadTy, BB->getTerminator(),
1176 DEBUG(dbgs() << "GVN COERCED NONLOCAL VAL:\nOffset: " << Offset << " "
1177 << *getSimpleValue() << '\n'
1178 << *Res << '\n' << "\n\n\n");
1180 } else if (isCoercedLoadValue()) {
1181 LoadInst *Load = getCoercedLoadValue();
1182 if (Load->getType() == LoadTy && Offset == 0) {
1185 Res = GetLoadValueForLoad(Load, Offset, LoadTy, BB->getTerminator(),
1188 DEBUG(dbgs() << "GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset << " "
1189 << *getCoercedLoadValue() << '\n'
1190 << *Res << '\n' << "\n\n\n");
1193 const TargetData *TD = gvn.getTargetData();
1194 assert(TD && "Need target data to handle type mismatch case");
1195 Res = GetMemInstValueForLoad(getMemIntrinValue(), Offset,
1196 LoadTy, BB->getTerminator(), *TD);
1197 DEBUG(dbgs() << "GVN COERCED NONLOCAL MEM INTRIN:\nOffset: " << Offset
1198 << " " << *getMemIntrinValue() << '\n'
1199 << *Res << '\n' << "\n\n\n");
1205 } // end anonymous namespace
1207 /// ConstructSSAForLoadSet - Given a set of loads specified by ValuesPerBlock,
1208 /// construct SSA form, allowing us to eliminate LI. This returns the value
1209 /// that should be used at LI's definition site.
1210 static Value *ConstructSSAForLoadSet(LoadInst *LI,
1211 SmallVectorImpl<AvailableValueInBlock> &ValuesPerBlock,
1213 // Check for the fully redundant, dominating load case. In this case, we can
1214 // just use the dominating value directly.
1215 if (ValuesPerBlock.size() == 1 &&
1216 gvn.getDominatorTree().properlyDominates(ValuesPerBlock[0].BB,
1218 return ValuesPerBlock[0].MaterializeAdjustedValue(LI->getType(), gvn);
1220 // Otherwise, we have to construct SSA form.
1221 SmallVector<PHINode*, 8> NewPHIs;
1222 SSAUpdater SSAUpdate(&NewPHIs);
1223 SSAUpdate.Initialize(LI->getType(), LI->getName());
1225 Type *LoadTy = LI->getType();
1227 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1228 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1229 BasicBlock *BB = AV.BB;
1231 if (SSAUpdate.HasValueForBlock(BB))
1234 SSAUpdate.AddAvailableValue(BB, AV.MaterializeAdjustedValue(LoadTy, gvn));
1237 // Perform PHI construction.
1238 Value *V = SSAUpdate.GetValueInMiddleOfBlock(LI->getParent());
1240 // If new PHI nodes were created, notify alias analysis.
1241 if (V->getType()->isPointerTy()) {
1242 AliasAnalysis *AA = gvn.getAliasAnalysis();
1244 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i)
1245 AA->copyValue(LI, NewPHIs[i]);
1247 // Now that we've copied information to the new PHIs, scan through
1248 // them again and inform alias analysis that we've added potentially
1249 // escaping uses to any values that are operands to these PHIs.
1250 for (unsigned i = 0, e = NewPHIs.size(); i != e; ++i) {
1251 PHINode *P = NewPHIs[i];
1252 for (unsigned ii = 0, ee = P->getNumIncomingValues(); ii != ee; ++ii) {
1253 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
1254 AA->addEscapingUse(P->getOperandUse(jj));
1262 static bool isLifetimeStart(const Instruction *Inst) {
1263 if (const IntrinsicInst* II = dyn_cast<IntrinsicInst>(Inst))
1264 return II->getIntrinsicID() == Intrinsic::lifetime_start;
1268 /// processNonLocalLoad - Attempt to eliminate a load whose dependencies are
1269 /// non-local by performing PHI construction.
1270 bool GVN::processNonLocalLoad(LoadInst *LI) {
1271 // Find the non-local dependencies of the load.
1272 SmallVector<NonLocalDepResult, 64> Deps;
1273 AliasAnalysis::Location Loc = VN.getAliasAnalysis()->getLocation(LI);
1274 MD->getNonLocalPointerDependency(Loc, true, LI->getParent(), Deps);
1275 //DEBUG(dbgs() << "INVESTIGATING NONLOCAL LOAD: "
1276 // << Deps.size() << *LI << '\n');
1278 // If we had to process more than one hundred blocks to find the
1279 // dependencies, this load isn't worth worrying about. Optimizing
1280 // it will be too expensive.
1281 unsigned NumDeps = Deps.size();
1285 // If we had a phi translation failure, we'll have a single entry which is a
1286 // clobber in the current block. Reject this early.
1288 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1290 dbgs() << "GVN: non-local load ";
1291 WriteAsOperand(dbgs(), LI);
1292 dbgs() << " has unknown dependencies\n";
1297 // Filter out useless results (non-locals, etc). Keep track of the blocks
1298 // where we have a value available in repl, also keep track of whether we see
1299 // dependencies that produce an unknown value for the load (such as a call
1300 // that could potentially clobber the load).
1301 SmallVector<AvailableValueInBlock, 64> ValuesPerBlock;
1302 SmallVector<BasicBlock*, 64> UnavailableBlocks;
1304 for (unsigned i = 0, e = NumDeps; i != e; ++i) {
1305 BasicBlock *DepBB = Deps[i].getBB();
1306 MemDepResult DepInfo = Deps[i].getResult();
1308 if (!DepInfo.isDef() && !DepInfo.isClobber()) {
1309 UnavailableBlocks.push_back(DepBB);
1313 if (DepInfo.isClobber()) {
1314 // The address being loaded in this non-local block may not be the same as
1315 // the pointer operand of the load if PHI translation occurs. Make sure
1316 // to consider the right address.
1317 Value *Address = Deps[i].getAddress();
1319 // If the dependence is to a store that writes to a superset of the bits
1320 // read by the load, we can extract the bits we need for the load from the
1322 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInfo.getInst())) {
1323 if (TD && Address) {
1324 int Offset = AnalyzeLoadFromClobberingStore(LI->getType(), Address,
1327 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1328 DepSI->getValueOperand(),
1335 // Check to see if we have something like this:
1338 // if we have this, replace the later with an extraction from the former.
1339 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInfo.getInst())) {
1340 // If this is a clobber and L is the first instruction in its block, then
1341 // we have the first instruction in the entry block.
1342 if (DepLI != LI && Address && TD) {
1343 int Offset = AnalyzeLoadFromClobberingLoad(LI->getType(),
1344 LI->getPointerOperand(),
1348 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB,DepLI,
1355 // If the clobbering value is a memset/memcpy/memmove, see if we can
1356 // forward a value on from it.
1357 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInfo.getInst())) {
1358 if (TD && Address) {
1359 int Offset = AnalyzeLoadFromClobberingMemInst(LI->getType(), Address,
1362 ValuesPerBlock.push_back(AvailableValueInBlock::getMI(DepBB, DepMI,
1369 UnavailableBlocks.push_back(DepBB);
1373 // DepInfo.isDef() here
1375 Instruction *DepInst = DepInfo.getInst();
1377 // Loading the allocation -> undef.
1378 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst) ||
1379 // Loading immediately after lifetime begin -> undef.
1380 isLifetimeStart(DepInst)) {
1381 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1382 UndefValue::get(LI->getType())));
1386 if (StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
1387 // Reject loads and stores that are to the same address but are of
1388 // different types if we have to.
1389 if (S->getValueOperand()->getType() != LI->getType()) {
1390 // If the stored value is larger or equal to the loaded value, we can
1392 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(S->getValueOperand(),
1393 LI->getType(), *TD)) {
1394 UnavailableBlocks.push_back(DepBB);
1399 ValuesPerBlock.push_back(AvailableValueInBlock::get(DepBB,
1400 S->getValueOperand()));
1404 if (LoadInst *LD = dyn_cast<LoadInst>(DepInst)) {
1405 // If the types mismatch and we can't handle it, reject reuse of the load.
1406 if (LD->getType() != LI->getType()) {
1407 // If the stored value is larger or equal to the loaded value, we can
1409 if (TD == 0 || !CanCoerceMustAliasedValueToLoad(LD, LI->getType(),*TD)){
1410 UnavailableBlocks.push_back(DepBB);
1414 ValuesPerBlock.push_back(AvailableValueInBlock::getLoad(DepBB, LD));
1418 UnavailableBlocks.push_back(DepBB);
1422 // If we have no predecessors that produce a known value for this load, exit
1424 if (ValuesPerBlock.empty()) return false;
1426 // If all of the instructions we depend on produce a known value for this
1427 // load, then it is fully redundant and we can use PHI insertion to compute
1428 // its value. Insert PHIs and remove the fully redundant value now.
1429 if (UnavailableBlocks.empty()) {
1430 DEBUG(dbgs() << "GVN REMOVING NONLOCAL LOAD: " << *LI << '\n');
1432 // Perform PHI construction.
1433 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1434 LI->replaceAllUsesWith(V);
1436 if (isa<PHINode>(V))
1438 if (V->getType()->isPointerTy())
1439 MD->invalidateCachedPointerInfo(V);
1440 markInstructionForDeletion(LI);
1445 if (!EnablePRE || !EnableLoadPRE)
1448 // Okay, we have *some* definitions of the value. This means that the value
1449 // is available in some of our (transitive) predecessors. Lets think about
1450 // doing PRE of this load. This will involve inserting a new load into the
1451 // predecessor when it's not available. We could do this in general, but
1452 // prefer to not increase code size. As such, we only do this when we know
1453 // that we only have to insert *one* load (which means we're basically moving
1454 // the load, not inserting a new one).
1456 SmallPtrSet<BasicBlock *, 4> Blockers;
1457 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1458 Blockers.insert(UnavailableBlocks[i]);
1460 // Let's find the first basic block with more than one predecessor. Walk
1461 // backwards through predecessors if needed.
1462 BasicBlock *LoadBB = LI->getParent();
1463 BasicBlock *TmpBB = LoadBB;
1465 bool isSinglePred = false;
1466 bool allSingleSucc = true;
1467 while (TmpBB->getSinglePredecessor()) {
1468 isSinglePred = true;
1469 TmpBB = TmpBB->getSinglePredecessor();
1470 if (TmpBB == LoadBB) // Infinite (unreachable) loop.
1472 if (Blockers.count(TmpBB))
1475 // If any of these blocks has more than one successor (i.e. if the edge we
1476 // just traversed was critical), then there are other paths through this
1477 // block along which the load may not be anticipated. Hoisting the load
1478 // above this block would be adding the load to execution paths along
1479 // which it was not previously executed.
1480 if (TmpBB->getTerminator()->getNumSuccessors() != 1)
1487 // FIXME: It is extremely unclear what this loop is doing, other than
1488 // artificially restricting loadpre.
1491 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i) {
1492 const AvailableValueInBlock &AV = ValuesPerBlock[i];
1493 if (AV.isSimpleValue())
1494 // "Hot" Instruction is in some loop (because it dominates its dep.
1496 if (Instruction *I = dyn_cast<Instruction>(AV.getSimpleValue()))
1497 if (DT->dominates(LI, I)) {
1503 // We are interested only in "hot" instructions. We don't want to do any
1504 // mis-optimizations here.
1509 // Check to see how many predecessors have the loaded value fully
1511 DenseMap<BasicBlock*, Value*> PredLoads;
1512 DenseMap<BasicBlock*, char> FullyAvailableBlocks;
1513 for (unsigned i = 0, e = ValuesPerBlock.size(); i != e; ++i)
1514 FullyAvailableBlocks[ValuesPerBlock[i].BB] = true;
1515 for (unsigned i = 0, e = UnavailableBlocks.size(); i != e; ++i)
1516 FullyAvailableBlocks[UnavailableBlocks[i]] = false;
1518 SmallVector<std::pair<TerminatorInst*, unsigned>, 4> NeedToSplit;
1519 for (pred_iterator PI = pred_begin(LoadBB), E = pred_end(LoadBB);
1521 BasicBlock *Pred = *PI;
1522 if (IsValueFullyAvailableInBlock(Pred, FullyAvailableBlocks)) {
1525 PredLoads[Pred] = 0;
1527 if (Pred->getTerminator()->getNumSuccessors() != 1) {
1528 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1529 DEBUG(dbgs() << "COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '"
1530 << Pred->getName() << "': " << *LI << '\n');
1534 if (LoadBB->isLandingPad()) {
1536 << "COULD NOT PRE LOAD BECAUSE OF LANDING PAD CRITICAL EDGE '"
1537 << Pred->getName() << "': " << *LI << '\n');
1541 unsigned SuccNum = GetSuccessorNumber(Pred, LoadBB);
1542 NeedToSplit.push_back(std::make_pair(Pred->getTerminator(), SuccNum));
1546 if (!NeedToSplit.empty()) {
1547 toSplit.append(NeedToSplit.begin(), NeedToSplit.end());
1551 // Decide whether PRE is profitable for this load.
1552 unsigned NumUnavailablePreds = PredLoads.size();
1553 assert(NumUnavailablePreds != 0 &&
1554 "Fully available value should be eliminated above!");
1556 // If this load is unavailable in multiple predecessors, reject it.
1557 // FIXME: If we could restructure the CFG, we could make a common pred with
1558 // all the preds that don't have an available LI and insert a new load into
1560 if (NumUnavailablePreds != 1)
1563 // Check if the load can safely be moved to all the unavailable predecessors.
1564 bool CanDoPRE = true;
1565 SmallVector<Instruction*, 8> NewInsts;
1566 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1567 E = PredLoads.end(); I != E; ++I) {
1568 BasicBlock *UnavailablePred = I->first;
1570 // Do PHI translation to get its value in the predecessor if necessary. The
1571 // returned pointer (if non-null) is guaranteed to dominate UnavailablePred.
1573 // If all preds have a single successor, then we know it is safe to insert
1574 // the load on the pred (?!?), so we can insert code to materialize the
1575 // pointer if it is not available.
1576 PHITransAddr Address(LI->getPointerOperand(), TD);
1578 if (allSingleSucc) {
1579 LoadPtr = Address.PHITranslateWithInsertion(LoadBB, UnavailablePred,
1582 Address.PHITranslateValue(LoadBB, UnavailablePred, DT);
1583 LoadPtr = Address.getAddr();
1586 // If we couldn't find or insert a computation of this phi translated value,
1589 DEBUG(dbgs() << "COULDN'T INSERT PHI TRANSLATED VALUE OF: "
1590 << *LI->getPointerOperand() << "\n");
1595 // Make sure it is valid to move this load here. We have to watch out for:
1596 // @1 = getelementptr (i8* p, ...
1597 // test p and branch if == 0
1599 // It is valid to have the getelementptr before the test, even if p can
1600 // be 0, as getelementptr only does address arithmetic.
1601 // If we are not pushing the value through any multiple-successor blocks
1602 // we do not have this case. Otherwise, check that the load is safe to
1603 // put anywhere; this can be improved, but should be conservatively safe.
1604 if (!allSingleSucc &&
1605 // FIXME: REEVALUTE THIS.
1606 !isSafeToLoadUnconditionally(LoadPtr,
1607 UnavailablePred->getTerminator(),
1608 LI->getAlignment(), TD)) {
1613 I->second = LoadPtr;
1617 while (!NewInsts.empty()) {
1618 Instruction *I = NewInsts.pop_back_val();
1619 if (MD) MD->removeInstruction(I);
1620 I->eraseFromParent();
1625 // Okay, we can eliminate this load by inserting a reload in the predecessor
1626 // and using PHI construction to get the value in the other predecessors, do
1628 DEBUG(dbgs() << "GVN REMOVING PRE LOAD: " << *LI << '\n');
1629 DEBUG(if (!NewInsts.empty())
1630 dbgs() << "INSERTED " << NewInsts.size() << " INSTS: "
1631 << *NewInsts.back() << '\n');
1633 // Assign value numbers to the new instructions.
1634 for (unsigned i = 0, e = NewInsts.size(); i != e; ++i) {
1635 // FIXME: We really _ought_ to insert these value numbers into their
1636 // parent's availability map. However, in doing so, we risk getting into
1637 // ordering issues. If a block hasn't been processed yet, we would be
1638 // marking a value as AVAIL-IN, which isn't what we intend.
1639 VN.lookup_or_add(NewInsts[i]);
1642 for (DenseMap<BasicBlock*, Value*>::iterator I = PredLoads.begin(),
1643 E = PredLoads.end(); I != E; ++I) {
1644 BasicBlock *UnavailablePred = I->first;
1645 Value *LoadPtr = I->second;
1647 Instruction *NewLoad = new LoadInst(LoadPtr, LI->getName()+".pre", false,
1649 UnavailablePred->getTerminator());
1651 // Transfer the old load's TBAA tag to the new load.
1652 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa))
1653 NewLoad->setMetadata(LLVMContext::MD_tbaa, Tag);
1655 // Transfer DebugLoc.
1656 NewLoad->setDebugLoc(LI->getDebugLoc());
1658 // Add the newly created load.
1659 ValuesPerBlock.push_back(AvailableValueInBlock::get(UnavailablePred,
1661 MD->invalidateCachedPointerInfo(LoadPtr);
1662 DEBUG(dbgs() << "GVN INSERTED " << *NewLoad << '\n');
1665 // Perform PHI construction.
1666 Value *V = ConstructSSAForLoadSet(LI, ValuesPerBlock, *this);
1667 LI->replaceAllUsesWith(V);
1668 if (isa<PHINode>(V))
1670 if (V->getType()->isPointerTy())
1671 MD->invalidateCachedPointerInfo(V);
1672 markInstructionForDeletion(LI);
1677 /// processLoad - Attempt to eliminate a load, first by eliminating it
1678 /// locally, and then attempting non-local elimination if that fails.
1679 bool GVN::processLoad(LoadInst *L) {
1686 if (L->use_empty()) {
1687 markInstructionForDeletion(L);
1691 // ... to a pointer that has been loaded from before...
1692 MemDepResult Dep = MD->getDependency(L);
1694 // If we have a clobber and target data is around, see if this is a clobber
1695 // that we can fix up through code synthesis.
1696 if (Dep.isClobber() && TD) {
1697 // Check to see if we have something like this:
1698 // store i32 123, i32* %P
1699 // %A = bitcast i32* %P to i8*
1700 // %B = gep i8* %A, i32 1
1703 // We could do that by recognizing if the clobber instructions are obviously
1704 // a common base + constant offset, and if the previous store (or memset)
1705 // completely covers this load. This sort of thing can happen in bitfield
1707 Value *AvailVal = 0;
1708 if (StoreInst *DepSI = dyn_cast<StoreInst>(Dep.getInst())) {
1709 int Offset = AnalyzeLoadFromClobberingStore(L->getType(),
1710 L->getPointerOperand(),
1713 AvailVal = GetStoreValueForLoad(DepSI->getValueOperand(), Offset,
1714 L->getType(), L, *TD);
1717 // Check to see if we have something like this:
1720 // if we have this, replace the later with an extraction from the former.
1721 if (LoadInst *DepLI = dyn_cast<LoadInst>(Dep.getInst())) {
1722 // If this is a clobber and L is the first instruction in its block, then
1723 // we have the first instruction in the entry block.
1727 int Offset = AnalyzeLoadFromClobberingLoad(L->getType(),
1728 L->getPointerOperand(),
1731 AvailVal = GetLoadValueForLoad(DepLI, Offset, L->getType(), L, *this);
1734 // If the clobbering value is a memset/memcpy/memmove, see if we can forward
1735 // a value on from it.
1736 if (MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(Dep.getInst())) {
1737 int Offset = AnalyzeLoadFromClobberingMemInst(L->getType(),
1738 L->getPointerOperand(),
1741 AvailVal = GetMemInstValueForLoad(DepMI, Offset, L->getType(), L, *TD);
1745 DEBUG(dbgs() << "GVN COERCED INST:\n" << *Dep.getInst() << '\n'
1746 << *AvailVal << '\n' << *L << "\n\n\n");
1748 // Replace the load!
1749 L->replaceAllUsesWith(AvailVal);
1750 if (AvailVal->getType()->isPointerTy())
1751 MD->invalidateCachedPointerInfo(AvailVal);
1752 markInstructionForDeletion(L);
1758 // If the value isn't available, don't do anything!
1759 if (Dep.isClobber()) {
1761 // fast print dep, using operator<< on instruction is too slow.
1762 dbgs() << "GVN: load ";
1763 WriteAsOperand(dbgs(), L);
1764 Instruction *I = Dep.getInst();
1765 dbgs() << " is clobbered by " << *I << '\n';
1770 // If it is defined in another block, try harder.
1771 if (Dep.isNonLocal())
1772 return processNonLocalLoad(L);
1776 // fast print dep, using operator<< on instruction is too slow.
1777 dbgs() << "GVN: load ";
1778 WriteAsOperand(dbgs(), L);
1779 dbgs() << " has unknown dependence\n";
1784 Instruction *DepInst = Dep.getInst();
1785 if (StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
1786 Value *StoredVal = DepSI->getValueOperand();
1788 // The store and load are to a must-aliased pointer, but they may not
1789 // actually have the same type. See if we know how to reuse the stored
1790 // value (depending on its type).
1791 if (StoredVal->getType() != L->getType()) {
1793 StoredVal = CoerceAvailableValueToLoadType(StoredVal, L->getType(),
1798 DEBUG(dbgs() << "GVN COERCED STORE:\n" << *DepSI << '\n' << *StoredVal
1799 << '\n' << *L << "\n\n\n");
1806 L->replaceAllUsesWith(StoredVal);
1807 if (StoredVal->getType()->isPointerTy())
1808 MD->invalidateCachedPointerInfo(StoredVal);
1809 markInstructionForDeletion(L);
1814 if (LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1815 Value *AvailableVal = DepLI;
1817 // The loads are of a must-aliased pointer, but they may not actually have
1818 // the same type. See if we know how to reuse the previously loaded value
1819 // (depending on its type).
1820 if (DepLI->getType() != L->getType()) {
1822 AvailableVal = CoerceAvailableValueToLoadType(DepLI, L->getType(),
1824 if (AvailableVal == 0)
1827 DEBUG(dbgs() << "GVN COERCED LOAD:\n" << *DepLI << "\n" << *AvailableVal
1828 << "\n" << *L << "\n\n\n");
1835 L->replaceAllUsesWith(AvailableVal);
1836 if (DepLI->getType()->isPointerTy())
1837 MD->invalidateCachedPointerInfo(DepLI);
1838 markInstructionForDeletion(L);
1843 // If this load really doesn't depend on anything, then we must be loading an
1844 // undef value. This can happen when loading for a fresh allocation with no
1845 // intervening stores, for example.
1846 if (isa<AllocaInst>(DepInst) || isMalloc(DepInst)) {
1847 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1848 markInstructionForDeletion(L);
1853 // If this load occurs either right after a lifetime begin,
1854 // then the loaded value is undefined.
1855 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(DepInst)) {
1856 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1857 L->replaceAllUsesWith(UndefValue::get(L->getType()));
1858 markInstructionForDeletion(L);
1867 // findLeader - In order to find a leader for a given value number at a
1868 // specific basic block, we first obtain the list of all Values for that number,
1869 // and then scan the list to find one whose block dominates the block in
1870 // question. This is fast because dominator tree queries consist of only
1871 // a few comparisons of DFS numbers.
1872 Value *GVN::findLeader(BasicBlock *BB, uint32_t num) {
1873 LeaderTableEntry Vals = LeaderTable[num];
1874 if (!Vals.Val) return 0;
1877 if (DT->dominates(Vals.BB, BB)) {
1879 if (isa<Constant>(Val)) return Val;
1882 LeaderTableEntry* Next = Vals.Next;
1884 if (DT->dominates(Next->BB, BB)) {
1885 if (isa<Constant>(Next->Val)) return Next->Val;
1886 if (!Val) Val = Next->Val;
1895 /// replaceAllDominatedUsesWith - Replace all uses of 'From' with 'To' if the
1896 /// use is dominated by the given basic block. Returns the number of uses that
1898 unsigned GVN::replaceAllDominatedUsesWith(Value *From, Value *To,
1901 for (Value::use_iterator UI = From->use_begin(), UE = From->use_end();
1903 Use &U = (UI++).getUse();
1904 if (DT->dominates(Root, cast<Instruction>(U.getUser())->getParent())) {
1912 /// propagateEquality - The given values are known to be equal in every block
1913 /// dominated by 'Root'. Exploit this, for example by replacing 'LHS' with
1914 /// 'RHS' everywhere in the scope. Returns whether a change was made.
1915 bool GVN::propagateEquality(Value *LHS, Value *RHS, BasicBlock *Root) {
1916 if (LHS == RHS) return false;
1917 assert(LHS->getType() == RHS->getType() && "Equal but types differ!");
1919 // Don't try to propagate equalities between constants.
1920 if (isa<Constant>(LHS) && isa<Constant>(RHS))
1923 // Make sure that any constants are on the right-hand side. In general the
1924 // best results are obtained by placing the longest lived value on the RHS.
1925 if (isa<Constant>(LHS))
1926 std::swap(LHS, RHS);
1928 // If neither term is constant then bail out. This is not for correctness,
1929 // it's just that the non-constant case is much less useful: it occurs just
1930 // as often as the constant case but handling it hardly ever results in an
1932 if (!isa<Constant>(RHS))
1935 // If value numbering later deduces that an instruction in the scope is equal
1936 // to 'LHS' then ensure it will be turned into 'RHS'.
1937 addToLeaderTable(VN.lookup_or_add(LHS), RHS, Root);
1939 // Replace all occurrences of 'LHS' with 'RHS' everywhere in the scope. As
1940 // LHS always has at least one use that is not dominated by Root, this will
1941 // never do anything if LHS has only one use.
1942 bool Changed = false;
1943 if (!LHS->hasOneUse()) {
1944 unsigned NumReplacements = replaceAllDominatedUsesWith(LHS, RHS, Root);
1945 Changed |= NumReplacements > 0;
1946 NumGVNEqProp += NumReplacements;
1949 // Now try to deduce additional equalities from this one. For example, if the
1950 // known equality was "(A != B)" == "false" then it follows that A and B are
1951 // equal in the scope. Only boolean equalities with an explicit true or false
1952 // RHS are currently supported.
1953 if (!RHS->getType()->isIntegerTy(1))
1954 // Not a boolean equality - bail out.
1956 ConstantInt *CI = dyn_cast<ConstantInt>(RHS);
1958 // RHS neither 'true' nor 'false' - bail out.
1960 // Whether RHS equals 'true'. Otherwise it equals 'false'.
1961 bool isKnownTrue = CI->isAllOnesValue();
1962 bool isKnownFalse = !isKnownTrue;
1964 // If "A && B" is known true then both A and B are known true. If "A || B"
1965 // is known false then both A and B are known false.
1967 if ((isKnownTrue && match(LHS, m_And(m_Value(A), m_Value(B)))) ||
1968 (isKnownFalse && match(LHS, m_Or(m_Value(A), m_Value(B))))) {
1969 Changed |= propagateEquality(A, RHS, Root);
1970 Changed |= propagateEquality(B, RHS, Root);
1974 // If we are propagating an equality like "(A == B)" == "true" then also
1975 // propagate the equality A == B.
1976 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(LHS)) {
1977 // Only equality comparisons are supported.
1978 if ((isKnownTrue && Cmp->getPredicate() == CmpInst::ICMP_EQ) ||
1979 (isKnownFalse && Cmp->getPredicate() == CmpInst::ICMP_NE)) {
1980 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
1981 Changed |= propagateEquality(Op0, Op1, Root);
1989 /// isOnlyReachableViaThisEdge - There is an edge from 'Src' to 'Dst'. Return
1990 /// true if every path from the entry block to 'Dst' passes via this edge. In
1991 /// particular 'Dst' must not be reachable via another edge from 'Src'.
1992 static bool isOnlyReachableViaThisEdge(BasicBlock *Src, BasicBlock *Dst,
1993 DominatorTree *DT) {
1994 // While in theory it is interesting to consider the case in which Dst has
1995 // more than one predecessor, because Dst might be part of a loop which is
1996 // only reachable from Src, in practice it is pointless since at the time
1997 // GVN runs all such loops have preheaders, which means that Dst will have
1998 // been changed to have only one predecessor, namely Src.
1999 BasicBlock *Pred = Dst->getSinglePredecessor();
2000 assert((!Pred || Pred == Src) && "No edge between these basic blocks!");
2005 /// processInstruction - When calculating availability, handle an instruction
2006 /// by inserting it into the appropriate sets
2007 bool GVN::processInstruction(Instruction *I) {
2008 // Ignore dbg info intrinsics.
2009 if (isa<DbgInfoIntrinsic>(I))
2012 // If the instruction can be easily simplified then do so now in preference
2013 // to value numbering it. Value numbering often exposes redundancies, for
2014 // example if it determines that %y is equal to %x then the instruction
2015 // "%z = and i32 %x, %y" becomes "%z = and i32 %x, %x" which we now simplify.
2016 if (Value *V = SimplifyInstruction(I, TD, TLI, DT)) {
2017 I->replaceAllUsesWith(V);
2018 if (MD && V->getType()->isPointerTy())
2019 MD->invalidateCachedPointerInfo(V);
2020 markInstructionForDeletion(I);
2025 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2026 if (processLoad(LI))
2029 unsigned Num = VN.lookup_or_add(LI);
2030 addToLeaderTable(Num, LI, LI->getParent());
2034 // For conditional branches, we can perform simple conditional propagation on
2035 // the condition value itself.
2036 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
2037 if (!BI->isConditional() || isa<Constant>(BI->getCondition()))
2040 Value *BranchCond = BI->getCondition();
2042 BasicBlock *TrueSucc = BI->getSuccessor(0);
2043 BasicBlock *FalseSucc = BI->getSuccessor(1);
2044 BasicBlock *Parent = BI->getParent();
2045 bool Changed = false;
2047 if (isOnlyReachableViaThisEdge(Parent, TrueSucc, DT))
2048 Changed |= propagateEquality(BranchCond,
2049 ConstantInt::getTrue(TrueSucc->getContext()),
2052 if (isOnlyReachableViaThisEdge(Parent, FalseSucc, DT))
2053 Changed |= propagateEquality(BranchCond,
2054 ConstantInt::getFalse(FalseSucc->getContext()),
2060 // For switches, propagate the case values into the case destinations.
2061 if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
2062 Value *SwitchCond = SI->getCondition();
2063 BasicBlock *Parent = SI->getParent();
2064 bool Changed = false;
2065 for (unsigned i = 0, e = SI->getNumCases(); i != e; ++i) {
2066 BasicBlock *Dst = SI->getCaseSuccessor(i);
2067 if (isOnlyReachableViaThisEdge(Parent, Dst, DT))
2068 Changed |= propagateEquality(SwitchCond, SI->getCaseValue(i), Dst);
2073 // Instructions with void type don't return a value, so there's
2074 // no point in trying to find redudancies in them.
2075 if (I->getType()->isVoidTy()) return false;
2077 uint32_t NextNum = VN.getNextUnusedValueNumber();
2078 unsigned Num = VN.lookup_or_add(I);
2080 // Allocations are always uniquely numbered, so we can save time and memory
2081 // by fast failing them.
2082 if (isa<AllocaInst>(I) || isa<TerminatorInst>(I) || isa<PHINode>(I)) {
2083 addToLeaderTable(Num, I, I->getParent());
2087 // If the number we were assigned was a brand new VN, then we don't
2088 // need to do a lookup to see if the number already exists
2089 // somewhere in the domtree: it can't!
2090 if (Num == NextNum) {
2091 addToLeaderTable(Num, I, I->getParent());
2095 // Perform fast-path value-number based elimination of values inherited from
2097 Value *repl = findLeader(I->getParent(), Num);
2099 // Failure, just remember this instance for future use.
2100 addToLeaderTable(Num, I, I->getParent());
2105 I->replaceAllUsesWith(repl);
2106 if (MD && repl->getType()->isPointerTy())
2107 MD->invalidateCachedPointerInfo(repl);
2108 markInstructionForDeletion(I);
2112 /// runOnFunction - This is the main transformation entry point for a function.
2113 bool GVN::runOnFunction(Function& F) {
2115 MD = &getAnalysis<MemoryDependenceAnalysis>();
2116 DT = &getAnalysis<DominatorTree>();
2117 TD = getAnalysisIfAvailable<TargetData>();
2118 TLI = &getAnalysis<TargetLibraryInfo>();
2119 VN.setAliasAnalysis(&getAnalysis<AliasAnalysis>());
2123 bool Changed = false;
2124 bool ShouldContinue = true;
2126 // Merge unconditional branches, allowing PRE to catch more
2127 // optimization opportunities.
2128 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ) {
2129 BasicBlock *BB = FI++;
2131 bool removedBlock = MergeBlockIntoPredecessor(BB, this);
2132 if (removedBlock) ++NumGVNBlocks;
2134 Changed |= removedBlock;
2137 unsigned Iteration = 0;
2138 while (ShouldContinue) {
2139 DEBUG(dbgs() << "GVN iteration: " << Iteration << "\n");
2140 ShouldContinue = iterateOnFunction(F);
2141 if (splitCriticalEdges())
2142 ShouldContinue = true;
2143 Changed |= ShouldContinue;
2148 bool PREChanged = true;
2149 while (PREChanged) {
2150 PREChanged = performPRE(F);
2151 Changed |= PREChanged;
2154 // FIXME: Should perform GVN again after PRE does something. PRE can move
2155 // computations into blocks where they become fully redundant. Note that
2156 // we can't do this until PRE's critical edge splitting updates memdep.
2157 // Actually, when this happens, we should just fully integrate PRE into GVN.
2159 cleanupGlobalSets();
2165 bool GVN::processBlock(BasicBlock *BB) {
2166 // FIXME: Kill off InstrsToErase by doing erasing eagerly in a helper function
2167 // (and incrementing BI before processing an instruction).
2168 assert(InstrsToErase.empty() &&
2169 "We expect InstrsToErase to be empty across iterations");
2170 bool ChangedFunction = false;
2172 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end();
2174 ChangedFunction |= processInstruction(BI);
2175 if (InstrsToErase.empty()) {
2180 // If we need some instructions deleted, do it now.
2181 NumGVNInstr += InstrsToErase.size();
2183 // Avoid iterator invalidation.
2184 bool AtStart = BI == BB->begin();
2188 for (SmallVector<Instruction*, 4>::iterator I = InstrsToErase.begin(),
2189 E = InstrsToErase.end(); I != E; ++I) {
2190 DEBUG(dbgs() << "GVN removed: " << **I << '\n');
2191 if (MD) MD->removeInstruction(*I);
2192 (*I)->eraseFromParent();
2193 DEBUG(verifyRemoved(*I));
2195 InstrsToErase.clear();
2203 return ChangedFunction;
2206 /// performPRE - Perform a purely local form of PRE that looks for diamond
2207 /// control flow patterns and attempts to perform simple PRE at the join point.
2208 bool GVN::performPRE(Function &F) {
2209 bool Changed = false;
2210 DenseMap<BasicBlock*, Value*> predMap;
2211 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
2212 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
2213 BasicBlock *CurrentBlock = *DI;
2215 // Nothing to PRE in the entry block.
2216 if (CurrentBlock == &F.getEntryBlock()) continue;
2218 // Don't perform PRE on a landing pad.
2219 if (CurrentBlock->isLandingPad()) continue;
2221 for (BasicBlock::iterator BI = CurrentBlock->begin(),
2222 BE = CurrentBlock->end(); BI != BE; ) {
2223 Instruction *CurInst = BI++;
2225 if (isa<AllocaInst>(CurInst) ||
2226 isa<TerminatorInst>(CurInst) || isa<PHINode>(CurInst) ||
2227 CurInst->getType()->isVoidTy() ||
2228 CurInst->mayReadFromMemory() || CurInst->mayHaveSideEffects() ||
2229 isa<DbgInfoIntrinsic>(CurInst))
2232 // We don't currently value number ANY inline asm calls.
2233 if (CallInst *CallI = dyn_cast<CallInst>(CurInst))
2234 if (CallI->isInlineAsm())
2237 uint32_t ValNo = VN.lookup(CurInst);
2239 // Look for the predecessors for PRE opportunities. We're
2240 // only trying to solve the basic diamond case, where
2241 // a value is computed in the successor and one predecessor,
2242 // but not the other. We also explicitly disallow cases
2243 // where the successor is its own predecessor, because they're
2244 // more complicated to get right.
2245 unsigned NumWith = 0;
2246 unsigned NumWithout = 0;
2247 BasicBlock *PREPred = 0;
2250 for (pred_iterator PI = pred_begin(CurrentBlock),
2251 PE = pred_end(CurrentBlock); PI != PE; ++PI) {
2252 BasicBlock *P = *PI;
2253 // We're not interested in PRE where the block is its
2254 // own predecessor, or in blocks with predecessors
2255 // that are not reachable.
2256 if (P == CurrentBlock) {
2259 } else if (!DT->dominates(&F.getEntryBlock(), P)) {
2264 Value* predV = findLeader(P, ValNo);
2268 } else if (predV == CurInst) {
2276 // Don't do PRE when it might increase code size, i.e. when
2277 // we would need to insert instructions in more than one pred.
2278 if (NumWithout != 1 || NumWith == 0)
2281 // Don't do PRE across indirect branch.
2282 if (isa<IndirectBrInst>(PREPred->getTerminator()))
2285 // We can't do PRE safely on a critical edge, so instead we schedule
2286 // the edge to be split and perform the PRE the next time we iterate
2288 unsigned SuccNum = GetSuccessorNumber(PREPred, CurrentBlock);
2289 if (isCriticalEdge(PREPred->getTerminator(), SuccNum)) {
2290 toSplit.push_back(std::make_pair(PREPred->getTerminator(), SuccNum));
2294 // Instantiate the expression in the predecessor that lacked it.
2295 // Because we are going top-down through the block, all value numbers
2296 // will be available in the predecessor by the time we need them. Any
2297 // that weren't originally present will have been instantiated earlier
2299 Instruction *PREInstr = CurInst->clone();
2300 bool success = true;
2301 for (unsigned i = 0, e = CurInst->getNumOperands(); i != e; ++i) {
2302 Value *Op = PREInstr->getOperand(i);
2303 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2306 if (Value *V = findLeader(PREPred, VN.lookup(Op))) {
2307 PREInstr->setOperand(i, V);
2314 // Fail out if we encounter an operand that is not available in
2315 // the PRE predecessor. This is typically because of loads which
2316 // are not value numbered precisely.
2319 DEBUG(verifyRemoved(PREInstr));
2323 PREInstr->insertBefore(PREPred->getTerminator());
2324 PREInstr->setName(CurInst->getName() + ".pre");
2325 PREInstr->setDebugLoc(CurInst->getDebugLoc());
2326 predMap[PREPred] = PREInstr;
2327 VN.add(PREInstr, ValNo);
2330 // Update the availability map to include the new instruction.
2331 addToLeaderTable(ValNo, PREInstr, PREPred);
2333 // Create a PHI to make the value available in this block.
2334 pred_iterator PB = pred_begin(CurrentBlock), PE = pred_end(CurrentBlock);
2335 PHINode* Phi = PHINode::Create(CurInst->getType(), std::distance(PB, PE),
2336 CurInst->getName() + ".pre-phi",
2337 CurrentBlock->begin());
2338 for (pred_iterator PI = PB; PI != PE; ++PI) {
2339 BasicBlock *P = *PI;
2340 Phi->addIncoming(predMap[P], P);
2344 addToLeaderTable(ValNo, Phi, CurrentBlock);
2345 Phi->setDebugLoc(CurInst->getDebugLoc());
2346 CurInst->replaceAllUsesWith(Phi);
2347 if (Phi->getType()->isPointerTy()) {
2348 // Because we have added a PHI-use of the pointer value, it has now
2349 // "escaped" from alias analysis' perspective. We need to inform
2351 for (unsigned ii = 0, ee = Phi->getNumIncomingValues(); ii != ee;
2353 unsigned jj = PHINode::getOperandNumForIncomingValue(ii);
2354 VN.getAliasAnalysis()->addEscapingUse(Phi->getOperandUse(jj));
2358 MD->invalidateCachedPointerInfo(Phi);
2361 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2363 DEBUG(dbgs() << "GVN PRE removed: " << *CurInst << '\n');
2364 if (MD) MD->removeInstruction(CurInst);
2365 CurInst->eraseFromParent();
2366 DEBUG(verifyRemoved(CurInst));
2371 if (splitCriticalEdges())
2377 /// splitCriticalEdges - Split critical edges found during the previous
2378 /// iteration that may enable further optimization.
2379 bool GVN::splitCriticalEdges() {
2380 if (toSplit.empty())
2383 std::pair<TerminatorInst*, unsigned> Edge = toSplit.pop_back_val();
2384 SplitCriticalEdge(Edge.first, Edge.second, this);
2385 } while (!toSplit.empty());
2386 if (MD) MD->invalidateCachedPredecessors();
2390 /// iterateOnFunction - Executes one iteration of GVN
2391 bool GVN::iterateOnFunction(Function &F) {
2392 cleanupGlobalSets();
2394 // Top-down walk of the dominator tree
2395 bool Changed = false;
2397 // Needed for value numbering with phi construction to work.
2398 ReversePostOrderTraversal<Function*> RPOT(&F);
2399 for (ReversePostOrderTraversal<Function*>::rpo_iterator RI = RPOT.begin(),
2400 RE = RPOT.end(); RI != RE; ++RI)
2401 Changed |= processBlock(*RI);
2403 for (df_iterator<DomTreeNode*> DI = df_begin(DT->getRootNode()),
2404 DE = df_end(DT->getRootNode()); DI != DE; ++DI)
2405 Changed |= processBlock(DI->getBlock());
2411 void GVN::cleanupGlobalSets() {
2413 LeaderTable.clear();
2414 TableAllocator.Reset();
2417 /// verifyRemoved - Verify that the specified instruction does not occur in our
2418 /// internal data structures.
2419 void GVN::verifyRemoved(const Instruction *Inst) const {
2420 VN.verifyRemoved(Inst);
2422 // Walk through the value number scope to make sure the instruction isn't
2423 // ferreted away in it.
2424 for (DenseMap<uint32_t, LeaderTableEntry>::const_iterator
2425 I = LeaderTable.begin(), E = LeaderTable.end(); I != E; ++I) {
2426 const LeaderTableEntry *Node = &I->second;
2427 assert(Node->Val != Inst && "Inst still in value numbering scope!");
2429 while (Node->Next) {
2431 assert(Node->Val != Inst && "Inst still in value numbering scope!");