41 #define DEBUG_TYPE "dse"
43 STATISTIC(NumFastStores,
"Number of stores deleted");
44 STATISTIC(NumFastOther ,
"Number of other instrs removed");
58 bool runOnFunction(
Function &
F)
override {
59 if (skipOptnoneFunction(F))
62 AA = &getAnalysis<AliasAnalysis>();
63 MD = &getAnalysis<MemoryDependenceAnalysis>();
64 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
65 TLI = AA->getTargetLibraryInfo();
71 if (DT->isReachableFromEntry(
I))
72 Changed |= runOnBasicBlock(*
I);
74 AA =
nullptr; MD =
nullptr; DT =
nullptr;
149 if (ValueSet) ValueSet->
remove(DeadInst);
150 }
while (!NowDeadInsts.
empty());
157 if (isa<StoreInst>(I))
160 switch (II->getIntrinsicID()) {
163 case Intrinsic::memset:
164 case Intrinsic::memmove:
165 case Intrinsic::memcpy:
166 case Intrinsic::init_trampoline:
167 case Intrinsic::lifetime_end:
173 if (TLI && TLI->
has(LibFunc::strcpy) &&
177 if (TLI && TLI->
has(LibFunc::strncpy) &&
181 if (TLI && TLI->
has(LibFunc::strcat) &&
185 if (TLI && TLI->
has(LibFunc::strncat) &&
214 case Intrinsic::init_trampoline:
218 case Intrinsic::lifetime_end: {
219 uint64_t Len = cast<ConstantInt>(II->
getArgOperand(0))->getZExtValue();
229 "Unknown instruction case");
244 return SI->isUnordered();
247 switch (II->getIntrinsicID()) {
249 case Intrinsic::lifetime_end:
253 case Intrinsic::init_trampoline:
257 case Intrinsic::memset:
258 case Intrinsic::memmove:
259 case Intrinsic::memcpy:
266 return CS.getInstruction()->use_empty();
276 if (isa<StoreInst>(I))
280 switch (II->getIntrinsicID()) {
281 default:
return false;
282 case Intrinsic::memset:
283 case Intrinsic::memcpy:
297 return SI->getPointerOperand();
299 return MI->getDest();
302 switch (II->getIntrinsicID()) {
304 case Intrinsic::init_trampoline:
305 return II->getArgOperand(0);
340 int64_t &EarlierOff, int64_t &LaterOff) {
351 return OverwriteUnknown;
355 return OverwriteComplete;
362 return OverwriteUnknown;
373 return OverwriteUnknown;
378 if (ObjectSize == Later.
Size && ObjectSize >= Earlier.
Size)
379 return OverwriteComplete;
391 return OverwriteUnknown;
408 if (EarlierOff >= LaterOff &&
410 uint64_t(EarlierOff - LaterOff) + Earlier.
Size <= Later.
Size)
411 return OverwriteComplete;
421 if (LaterOff > EarlierOff &&
422 LaterOff < int64_t(EarlierOff + Earlier.
Size) &&
423 int64_t(LaterOff + Later.
Size) >= int64_t(EarlierOff + Earlier.
Size))
427 return OverwriteUnknown;
449 if (!InstReadLoc.
Ptr)
return false;
452 if (AA.
isNoAlias(InstReadLoc, InstStoreLoc))
return false;
478 bool MadeChange =
false;
486 MadeChange |= HandleFree(F);
503 if (
StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
505 if (
SI->getPointerOperand() == DepLoad->getPointerOperand() &&
507 DEBUG(
dbgs() <<
"DSE: Remove Store Of Load from same pointer:\n "
508 <<
"LOAD: " << *DepLoad <<
"\n STORE: " << *SI <<
'\n');
518 else if (BBI != BB.
begin())
553 int64_t InstWriteOffset, DepWriteOffset;
556 isOverwrite(Loc, DepLoc, DL, AA->getTargetLibraryInfo(),
557 DepWriteOffset, InstWriteOffset);
558 if (OR == OverwriteComplete) {
559 DEBUG(
dbgs() <<
"DSE: Remove Dead Store:\n DEAD: "
560 << *DepWrite <<
"\n KILLER: " << *Inst <<
'\n');
570 if (BBI != BB.
begin())
580 MemIntrinsic* DepIntrinsic = cast<MemIntrinsic>(DepWrite);
583 ((DepWriteAlign != 0) && InstWriteOffset % DepWriteAlign == 0)) {
585 DEBUG(
dbgs() <<
"DSE: Remove Dead Store:\n OW END: "
586 << *DepWrite <<
"\n KILLER (offset "
587 << InstWriteOffset <<
", "
588 << DepLoc.
Size <<
")"
609 if (DepWrite == &BB.
front())
break;
615 InstDep = MD->getPointerDependencyFrom(Loc,
false, DepWrite, &BB);
622 MadeChange |= handleEndBlock(BB);
633 if (Pred == BB)
continue;
646 bool MadeChange =
false;
653 while (!Blocks.empty()) {
658 MemDepResult Dep = MD->getPointerDependencyFrom(Loc,
false, InstPt, BB);
683 Dep = MD->getPointerDependencyFrom(Loc,
false, Next, BB);
700 bool MadeChange =
false;
709 if (isa<AllocaInst>(
I))
722 if (AI->hasByValOrInAllocaAttr())
723 DeadStackObjects.
insert(AI);
740 E = Pointers.
end();
I != E; ++
I)
741 if (!DeadStackObjects.
count(*
I)) {
749 DEBUG(
dbgs() <<
"DSE: Dead Store at End of Block:\n DEAD: "
750 << *Dead <<
"\n Objects: ";
752 E = Pointers.
end();
I != E; ++
I) {
754 if (std::next(
I) != E)
776 if (isa<AllocaInst>(BBI)) {
779 DeadStackObjects.
remove(BBI);
787 DeadStackObjects.
remove(BBI);
791 if (AA->doesNotAccessMemory(CS))
806 if (DeadStackObjects.
empty())
815 if (
LoadInst *L = dyn_cast<LoadInst>(BBI)) {
816 if (!L->isUnordered())
819 }
else if (
VAArgInst *V = dyn_cast<VAArgInst>(BBI)) {
823 }
else if (!BBI->mayReadFromMemory()) {
834 RemoveAccessedObjects(LoadedLoc, DeadStackObjects, DL);
838 if (DeadStackObjects.
empty())
854 if (isa<Constant>(UnderlyingPointer))
859 if (isa<AllocaInst>(UnderlyingPointer) || isa<Argument>(UnderlyingPointer)) {
860 DeadStackObjects.
remove(const_cast<Value*>(UnderlyingPointer));
869 return !AA->isNoAlias(StackLoc, LoadedLoc);
unsigned getAlignment() const
iplist< Instruction >::iterator eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing basic block and deletes it...
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static MemoryLocation getLocForWrite(Instruction *Inst, AliasAnalysis &AA)
getLocForWrite - Return a Location stored to by the specified instruction.
bool isDef() const
isDef - Return true if this MemDepResult represents a query that is an instruction definition depende...
STATISTIC(NumFunctions,"Total number of functions")
ValTy * getArgument(unsigned ArgNo) const
Intrinsic::ID getIntrinsicID() const
getIntrinsicID - Return the intrinsic ID of this intrinsic.
unsigned getNumOperands() const
bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, bool RoundToAlign=false)
Compute the size of the object pointed by Ptr.
CallInst - This class represents a function call, abstracting a target machine's calling convention...
static OverwriteResult isOverwrite(const MemoryLocation &Later, const MemoryLocation &Earlier, const DataLayout &DL, const TargetLibraryInfo *TLI, int64_t &EarlierOff, int64_t &LaterOff)
isOverwrite - Return 'OverwriteComplete' if a store to the 'Later' location completely overwrites a s...
static bool isPossibleSelfRead(Instruction *Inst, const MemoryLocation &InstStoreLoc, Instruction *DepWrite, AliasAnalysis &AA)
isPossibleSelfRead - If 'Inst' might be a self read (i.e.
const Function * getParent() const
Return the enclosing method, or null if none.
const Instruction & front() const
LoadInst - an instruction for reading from memory.
void initializeDSEPass(PassRegistry &)
static bool isShortenable(Instruction *I)
isShortenable - Returns true if this instruction can be safely shortened in length.
void GetUnderlyingObjects(Value *V, SmallVectorImpl< Value * > &Objects, const DataLayout &DL, LoopInfo *LI=nullptr, unsigned MaxLookup=6)
This method is similar to GetUnderlyingObject except that it can look through phi and select instruct...
bool isClobber() const
isClobber - Return true if this MemDepResult represents a query that is an instruction clobber depend...
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
StringRef getName() const
Return a constant reference to the value's name.
bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
isMustAlias - A convenience wrapper.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool has(LibFunc::Func F) const
Tests whether a library function is available.
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr it the function does no...
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
MemoryDependenceAnalysis - This is an analysis that determines, for a given memory operation...
bool remove(const value_type &X)
Remove an item from the set vector.
bool insert(const value_type &X)
Insert a new element into the SetVector.
static Value * getStoredPointerOperand(Instruction *I)
getStoredPointerOperand - Return the pointer that is being written to.
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
static MemoryLocation getForDest(const MemIntrinsic *MI)
Return a location representing the destination of a memory set or transfer.
Value handle that is nullable, but tries to track the Value.
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL)
GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if it can be expressed as a b...
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
static uint64_t getPointerSize(const Value *V, const DataLayout &DL, const TargetLibraryInfo *TLI)
bool empty() const
Determine if the SetVector is empty or not.
StoreInst - an instruction for storing to memory.
static bool hasMemoryWrite(Instruction *I, const TargetLibraryInfo *TLI)
hasMemoryWrite - Does this instruction write some memory? This only returns true for things that we c...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
Subclasses of this class are all able to terminate a basic block.
LLVM Basic Block Representation.
static MemoryLocation getLocForRead(Instruction *Inst, AliasAnalysis &AA)
getLocForRead - Return the location read by the specified "hasMemoryWrite" instruction if any...
machine Machine Common Subexpression Elimination
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
static void DeleteDeadInstruction(Instruction *I, MemoryDependenceAnalysis &MD, const TargetLibraryInfo *TLI, SmallSetVector< Value *, 16 > *ValueSet=nullptr)
DeleteDeadInstruction - Delete this instruction.
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
Interval::pred_iterator pred_end(Interval *I)
#define INITIALIZE_AG_DEPENDENCY(depName)
VAArgInst - This class represents the va_arg llvm instruction, which returns an argument of the speci...
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
GetUnderlyingObject - This method strips off any GEP address adjustments and pointer casts from the s...
MemDepResult - A memory dependence query can return one of three different answers, described below.
const Value * Ptr
The address of the start of the location.
Representation for a specific memory location.
A SetVector that performs no allocations if smaller than a certain size.
MemIntrinsic - This is the common base class for memset/memcpy/memmove.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
FunctionPass * createDeadStoreEliminationPass()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
Provides information about what library functions are available for the current target.
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Value * getLength() const
bool isNonLocal() const
isNonLocal - Return true if this MemDepResult represents a query that is transparent to the start of ...
Value * stripPointerCasts()
Strip off pointer casts, all-zero GEPs, and aliases.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static void FindUnconditionalPreds(SmallVectorImpl< BasicBlock * > &Blocks, BasicBlock *BB, DominatorTree *DT)
Find all blocks that will unconditionally lead to the block BB and append them to F...
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
bool isPowerOf2_64(uint64_t Value)
isPowerOf2_64 - This function returns true if the argument is a power of two 0 (64 bit edition...
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
MemTransferInst - This class wraps the llvm.memcpy/memmove intrinsics.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Instruction * getInst() const
getInst() - If this is a normal dependency, return the instruction that is depended on...
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
StringRef getName(LibFunc::Func F) const
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
isInstructionTriviallyDead - Return true if the result produced by the instruction is not used...
LLVM Value Representation.
ModRefResult
Simple mod/ref information...
bool remove_if(UnaryPredicate P)
Remove items from the set vector based on a predicate function.
static bool isRemovable(Instruction *I)
isRemovable - If the value of this instruction and the memory it writes to is unused, may we delete this instruction?
const TargetLibraryInfo * getTargetLibraryInfo() const
getTargetLibraryInfo - Return a pointer to the current TargetLibraryInfo object, or null if no Target...
bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
isNoAlias - A trivial helper function to check to see if the specified pointers are no-alias...
Legacy analysis pass which computes a DominatorTree.
static bool isVolatile(Instruction *Inst)
NodeTy * remove(iterator &IT)
const BasicBlock * getParent() const
void removeInstruction(Instruction *InstToRemove)
removeInstruction - Remove an instruction from the dependence analysis, updating the dependence of in...
IntrinsicInst - A useful wrapper class for inspecting calls to intrinsic functions.
uint64_t Size
The maximum size of the location, in address-units, or UnknownSize if the size is not known...
static MemoryLocation getForSource(const MemTransferInst *MTI)
Return a location representing the source of a memory transfer.