46 STATISTIC(NumRemoved,
"Number of unreachable basic blocks removed");
65 if (
BranchInst *BI = dyn_cast<BranchInst>(T)) {
66 if (BI->isUnconditional())
return false;
70 if (
ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
73 BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
74 BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
96 assert(BI->getParent() &&
"Terminator not inserted in block!");
101 Value *Cond = BI->getCondition();
102 BI->eraseFromParent();
103 if (DeleteDeadConditions)
110 if (
SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
114 BasicBlock *TheOnlyDest = SI->getDefaultDest();
121 if (i.getCaseValue() == CI) {
122 TheOnlyDest = i.getCaseSuccessor();
128 if (i.getCaseSuccessor() == DefaultDest) {
141 unsigned idx = i.getCaseIndex();
142 Weights[0] += Weights[idx+1];
148 createBranchWeights(Weights));
160 if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = 0;
163 if (CI && !TheOnlyDest) {
166 TheOnlyDest = SI->getDefaultDest();
177 for (
unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
180 if (Succ == TheOnlyDest)
187 Value *Cond = SI->getCondition();
188 SI->eraseFromParent();
189 if (DeleteDeadConditions)
194 if (SI->getNumCases() == 1) {
204 SI->getDefaultDest());
209 assert(SICase && SIDef);
214 SIDef->getValue().getZExtValue()));
218 SI->eraseFromParent();
227 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
228 BasicBlock *TheOnlyDest = BA->getBasicBlock();
232 for (
unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
233 if (IBI->getDestination(i) == TheOnlyDest)
238 Value *Address = IBI->getAddress();
239 IBI->eraseFromParent();
240 if (DeleteDeadConditions)
268 if (!I->
use_empty() || isa<TerminatorInst>(
I))
return false;
271 if (isa<LandingPadInst>(I))
277 if (DDI->getAddress())
299 return isa<UndefValue>(II->getArgOperand(1));
305 if (
Constant *
C = dyn_cast<Constant>(CI->getArgOperand(0)))
306 return C->isNullValue() || isa<UndefValue>(
C);
345 }
while (!DeadInsts.
empty());
361 for (++UI; UI != UE; ++UI) {
377 I = cast<Instruction>(*
I->use_begin())) {
400 bool MadeChange =
false;
411 assert(!BI->isTerminator());
448 if (!isa<PHINode>(BB->
begin()))
457 while (
PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
459 Value *OldPhiIt = PhiIt;
467 if (PhiIt != OldPhiIt) PhiIt = &BB->
front();
479 while (
PHINode *PN = dyn_cast<PHINode>(DestBB->
begin())) {
480 Value *NewVal = PN->getIncomingValue(0);
484 PN->eraseFromParent();
488 assert(PredBB &&
"Block doesn't have a single predecessor!");
524 return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
533 assert(*
succ_begin(BB) == Succ &&
"Succ is not successor of BB!");
553 if (BBPN && BBPN->getParent() == BB) {
556 if (BBPreds.
count(IBB) &&
560 << Succ->
getName() <<
" is conflicting with "
561 << BBPN->getName() <<
" with regard to common predecessor "
573 if (BBPreds.
count(IBB) &&
576 << Succ->
getName() <<
" is conflicting with regard to common "
577 <<
"predecessor " << IBB->
getName() <<
"\n");
604 if (!isa<UndefValue>(OldVal)) {
605 assert((!IncomingValues.
count(BB) ||
606 IncomingValues.
find(BB)->second == OldVal) &&
607 "Expected OldVal to match incoming value from BB!");
609 IncomingValues.
insert(std::make_pair(BB, OldVal));
614 if (It != IncomingValues.
end())
return It->second;
633 if (!isa<UndefValue>(V))
634 IncomingValues.
insert(std::make_pair(BB, V));
648 if (!isa<UndefValue>(V))
continue;
652 if (It == IncomingValues.
end())
continue;
669 assert(OldVal &&
"No entry in PHI for Pred BB!");
686 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->
getParent() == BB) {
687 PHINode *OldValPN = cast<PHINode>(OldVal);
704 for (
unsigned i = 0, e = BBPreds.
size(); i != e; ++i) {
727 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
731 if (BB == Succ)
return false;
749 if (!Succ->getSinglePredecessor()) {
751 while (isa<PHINode>(*BBI)) {
754 if (
PHINode* PN = dyn_cast<PHINode>(*UI)) {
755 if (PN->getIncomingBlock(UI) != BB)
765 DEBUG(
dbgs() <<
"Killing Trivial BB: \n" << *BB);
767 if (isa<PHINode>(Succ->begin())) {
781 if (Succ->getSinglePredecessor()) {
787 Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->
getInstList());
791 assert(PN->use_empty() &&
"There shouldn't be any uses here!");
792 PN->eraseFromParent();
798 if (!Succ->hasName()) Succ->takeName(BB);
809 bool Changed =
false;
833 Hash ^=
reinterpret_cast<uintptr_t
>(
static_cast<Value *
>(*I));
834 Hash = (Hash << 7) | (Hash >> (
sizeof(uintptr_t) * CHAR_BIT - 7));
838 Hash ^=
reinterpret_cast<uintptr_t
>(
static_cast<BasicBlock *
>(*I));
839 Hash = (Hash << 7) | (Hash >> (
sizeof(uintptr_t) * CHAR_BIT - 7));
844 std::pair<DenseMap<uintptr_t, PHINode *>::iterator,
bool> Pair =
845 HashMap.
insert(std::make_pair(Hash, PN));
846 if (Pair.second)
continue;
848 for (
PHINode *OtherPN = Pair.first->second; ; ) {
849 if (OtherPN->isIdenticalTo(PN)) {
858 if (I == CollisionMap.
end()) {
860 PHINode *Old = Pair.first->second;
861 Pair.first->second = PN;
862 CollisionMap[PN] = Old;
883 if (
AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
889 if (AI->getAlignment() >= PrefAlign)
890 return AI->getAlignment();
891 AI->setAlignment(PrefAlign);
898 if (GV->isDeclaration())
return Align;
902 if (GV->isWeakForLinker())
return Align;
904 if (GV->getAlignment() >= PrefAlign)
905 return GV->getAlignment();
910 if (!GV->hasSection() || GV->getAlignment() == 0)
911 GV->setAlignment(PrefAlign);
912 return GV->getAlignment();
925 "getOrEnforceKnownAlignment expects a pointer!");
928 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
930 unsigned TrailZ = KnownZero.countTrailingOnes();
934 TrailZ = std::min(TrailZ,
unsigned(
sizeof(
unsigned) * CHAR_BIT - 1));
936 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
941 if (PrefAlign > Align)
962 DVI->getOffset() == 0 &&
963 DVI->getVariable() == DIVar)
974 assert((!DIVar || DIVar.isVariable()) &&
975 "Variable in DbgDeclareInst should be either null or a DIVariable.");
1010 assert((!DIVar || DIVar.isVariable()) &&
1011 "Variable in DbgDeclareInst should be either null or a DIVariable.");
1046 E = Dbgs.end();
I != E; ++
I) {
1055 bool RemoveDDI =
true;
1058 if (
StoreInst *SI = dyn_cast<StoreInst>(*UI))
1060 else if (
LoadInst *
LI = dyn_cast<LoadInst>(*UI))
1076 E = DebugNode->use_end(); UI != E; ++UI)
1089 assert((!DIVar || DIVar.isVariable()) &&
1090 "Variable in DbgDeclareInst should be either null or a DIVariable.");
1100 if (DIVar.hasComplexAddress()) {
1101 for (
unsigned i = 0, n = DIVar.getNumAddrElements(); i < n; ++i) {
1108 DIVar.getTag(), DIVar.getContext(), DIVar.getName(),
1109 DIVar.getFile(), DIVar.getLineNumber(), DIVar.getType(),
1110 NewDIVarAddress, DIVar.getArgNumber());
1141 while (BBI != BBE) {
1142 if (!BBI->use_empty())
1152 NewCall->takeName(II);
1172 bool Changed =
false;
1180 if (
CallInst *CI = dyn_cast<CallInst>(BBI)) {
1181 if (CI->doesNotReturn()) {
1186 if (!isa<UnreachableInst>(BBI)) {
1198 if (
StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
1200 if (SI->isVolatile())
continue;
1202 Value *Ptr = SI->getOperand(1);
1204 if (isa<UndefValue>(Ptr) ||
1205 (isa<ConstantPointerNull>(Ptr) &&
1206 SI->getPointerAddressSpace() == 0)) {
1216 Value *Callee = II->getCalledValue();
1217 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1220 }
else if (II->doesNotThrow()) {
1221 if (II->use_empty() && II->onlyReadsMemory()) {
1224 II->getUnwindDest()->removePredecessor(II->getParent());
1234 if (Reachable.
insert(*SI))
1236 }
while (!Worklist.
empty());
1251 assert(Reachable.
size() < F.
size());
1252 NumRemoved += F.
size()-Reachable.
size();
1257 if (Reachable.
count(BB))
1261 if (Reachable.
count(*SI))
1262 (*SI)->removePredecessor(BB);
1263 BB->dropAllReferences();
STATISTIC(NumRemoved,"Number of unreachable basic blocks removed")
void push_back(const T &Elt)
DomTreeNode * getNode(BasicBlock *BB) const
ConstantIntTy * getCaseValue()
Resolves case value for current case.
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
void addIncoming(Value *V, BasicBlock *BB)
LLVM Argument representation.
uint64_t getZExtValue() const
Get zero extended value.
static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ)
DbgDeclareInst * FindAllocaDbgDeclare(Value *V)
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
This class represents zero extension of integer types.
unsigned getNumOperands() const
unsigned getNumOperands() const
getNumOperands - Return number of MDNode operands.
unsigned getPointerTypeSizeInBits(Type *) const
DIVariable createComplexVariable(unsigned Tag, DIDescriptor Scope, StringRef Name, DIFile F, unsigned LineNo, DIType Ty, ArrayRef< Value * > Addr, unsigned ArgNo=0)
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=0)
void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, Pass *P=0)
void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred, DataLayout *TD=0)
bool mayHaveSideEffects() const
const Function * getParent() const
Return the enclosing method, or null if none.
static void replaceUndefValuesInPhi(PHINode *PN, const IncomingValueMap &IncomingValues)
Replace the incoming undef values to a phi with the values from a block-to-value map.
const Instruction & front() const
MDNode - a tuple of other values.
This class represents a sign extension of integer types.
static IntegerType * getInt64Ty(LLVMContext &C)
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
static Value * selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB, IncomingValueMap &IncomingValues)
Determines the value to use as the phi node input for a block.
static unsigned enforceKnownAlignment(Value *V, unsigned Align, unsigned PrefAlign, const DataLayout *TD)
void setDebugLoc(const DebugLoc &Loc)
setDebugLoc - Set the debug location information for this instruction.
LoopInfoBase< BlockT, LoopT > * LI
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
block_iterator block_end()
Value * getOperand(unsigned i) const LLVM_READONLY
getOperand - Return specified operand.
bool isArrayAllocation() const
DomTreeNodeBase< NodeT > * getIDom() const
bool isUnknown() const
isUnknown - Return true if this is an unknown location.
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
const APInt & getValue() const
Return the constant's value.
static bool markAliveBlocks(BasicBlock *BB, SmallPtrSet< BasicBlock *, 128 > &Reachable)
AnalysisType * getAnalysisIfAvailable() const
T LLVM_ATTRIBUTE_UNUSED_RESULT pop_back_val()
void changeImmediateDominator(BasicBlock *N, BasicBlock *NewIDom)
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=0)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=0)
const Value * getCalledValue() const
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc. to it.
static const unsigned MaximumAlignment
block_iterator block_begin()
bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder)
Interval::succ_iterator succ_begin(Interval *I)
bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=0)
static void changeToCall(InvokeInst *II)
changeToCall - Convert the specified invoke into a normal call.
bool count(PtrType Ptr) const
count - Return true if the specified pointer is in the set.
void eraseNode(BasicBlock *BB)
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
static bool areAllUsesEqual(Instruction *I)
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
void replaceAllUsesWith(Value *V)
bool EliminateDuplicatePHINodes(BasicBlock *BB)
static void gatherIncomingValuesToPhi(PHINode *PN, IncomingValueMap &IncomingValues)
Create a map from block to value for the operands of a given phi.
static Constant * getIntToPtr(Constant *C, Type *Ty)
MDNode * getVariable() const
BasicBlock * getNormalDest() const
void ComputeMaskedBits(Value *V, APInt &KnownZero, APInt &KnownOne, const DataLayout *TD=0, unsigned Depth=0)
Interval::succ_iterator succ_end(Interval *I)
unsigned getNumIncomingValues() const
bool SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0)
DenseMap< BasicBlock *, Value * > IncomingValueMap
LLVM Basic Block Representation.
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB)
static BlockAddress * get(Function *F, BasicBlock *BB)
get - Return a BlockAddress for the specified function and basic block.
LLVM Constant Representation.
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=0)
Interval::pred_iterator pred_begin(Interval *I)
Instruction * insertDbgValueIntrinsic(llvm::Value *Val, uint64_t Offset, DIVariable VarInfo, BasicBlock *InsertAtEnd)
insertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
const DebugLoc & getDebugLoc() const
getDebugLoc - Return the debug location for this node as a DebugLoc.
static bool CanMergeValues(Value *First, Value *Second)
BasicBlock * getIncomingBlock(unsigned i) const
const InstListType & getInstList() const
Return the underlying instruction list container.
Value * getOperand(unsigned i) const
Interval::pred_iterator pred_end(Interval *I)
bool count(const KeyT &Val) const
count - Return true if the specified key is in the map.
static UndefValue * get(Type *T)
LLVMContext & getContext() const
All values hold a context through their type.
bool LowerDbgDeclare(Function &F)
Instruction * insertDeclare(llvm::Value *Storage, DIVariable VarInfo, BasicBlock *InsertAtEnd)
insertDeclare - Insert a new llvm.dbg.declare intrinsic call.
iterator erase(iterator where)
void setMetadata(unsigned KindID, MDNode *Node)
CallingConv::ID getCallingConv() const
static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB, const PredBlockVector &BBPreds, PHINode *PN)
Replace a value flowing from a block to a phi with potentially multiple instances of that value flowi...
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, const Twine &NameStr="", Instruction *InsertBefore=0)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
static void changeToUnreachable(Instruction *I, bool UseLLVMTrap)
const BasicBlockListType & getBasicBlockList() const
BasicBlock * getUnwindDest() const
Class for constant integers.
Value * getIncomingValue(unsigned i) const
bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI, StoreInst *SI, DIBuilder &Builder)
static MDNode * getIfExists(LLVMContext &Context, ArrayRef< Value * > Vals)
void eraseFromParent()
Unlink 'this' from the containing function and delete it.
static bool LdStHasDebugValue(DIVariable &DIVar, Instruction *I)
See if there is a dbg.value intrinsic for DIVar before I.
BasicBlockTy * getCaseSuccessor()
Resolves successor for current case.
Value * stripPointerCasts()
Strips off any unneeded pointer casts, all-zero GEPs and aliases from the specified value...
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
const BasicBlock & getEntryBlock() const
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=0)
SmallVector< BasicBlock *, 16 > PredBlockVector
void splice(iterator where, iplist &L2)
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Class for arbitrary precision integers.
bool exceedsNaturalStackAlignment(unsigned Align) const
Returns true if the given alignment exceeds the natural stack alignment.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getSinglePredecessor()
Return this block if it has a single predecessor block. Otherwise return a null pointer.
static cl::opt< AlignMode > Align(cl::desc("Load/store alignment support"), cl::Hidden, cl::init(DefaultAlign), cl::values(clEnumValN(DefaultAlign,"arm-default-align","Generate unaligned accesses only on hardware/OS ""combinations that are known to support them"), clEnumValN(StrictAlign,"arm-strict-align","Disallow all unaligned memory accesses"), clEnumValN(NoStrictAlign,"arm-no-strict-align","Allow unaligned memory accesses"), clEnumValEnd))
unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, const DataLayout *TD=0)
const AttributeSet & getAttributes() const
static IntegerType * getInt32Ty(LLVMContext &C)
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...
virtual void destroyConstant()
LLVMContext & getContext() const
Get the context in which this basic block lives.
LLVM Value Representation.
Value * getAddress() const
static const Function * getParent(const Value *V)
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
bool removeUnreachableBlocks(Function &F)
Remove all blocks that can not be reached from the function's entry.
void setIncomingValue(unsigned i, Value *V)
iterator find(const KeyT &Val)
const BasicBlock * getParent() const
InstListType::iterator iterator
Instruction iterators...
INITIALIZE_PASS(GlobalMerge,"global-merge","Global Merge", false, false) bool GlobalMerge const DataLayout * TD
bool recursivelySimplifyInstruction(Instruction *I, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0, const DominatorTree *DT=0)
Recursively attempt to simplify an instruction.