25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/SmallVector.h"
28 using namespace clang;
38 return isa<EnumConstantDecl>(DR->
getDecl());
43 return isa<IntegerLiteral>(Ex) || isa<StringLiteral>(Ex) ||
44 isa<CXXBoolLiteralExpr>(Ex) || isa<ObjCBoolLiteralExpr>(Ex) ||
45 isa<CharacterLiteral>(Ex) ||
53 if (
const DoStmt *DS = dyn_cast<DoStmt>(Term)) {
71 if (
const ReturnStmt *RS = dyn_cast<ReturnStmt>(CS->getStmt())) {
74 if (
const Expr *RE = RS->getRetValue()) {
75 RE = RE->IgnoreParenCasts();
96 Current = *(Current->succ_begin() + 1);
112 llvm_unreachable(
"Broke out of infinite loop.");
128 bool IgnoreYES_NO =
false) {
142 if (MacroName ==
"YES" || MacroName ==
"NO")
162 bool IncludeIntegers =
true,
163 bool WrappedInParens =
false) {
167 if (
const Expr *Ex = dyn_cast<Expr>(S))
168 S = Ex->IgnoreCasts();
171 if (
const ParenExpr *PE = dyn_cast<ParenExpr>(S))
172 if (!PE->getLocStart().isMacroID())
174 IncludeIntegers,
true);
176 if (
const Expr *Ex = dyn_cast<Expr>(S))
177 S = Ex->IgnoreCasts();
179 bool IgnoreYES_NO =
false;
181 switch (S->getStmtClass()) {
182 case Stmt::CallExprClass: {
184 dyn_cast_or_null<FunctionDecl>(cast<CallExpr>(
S)->getCalleeDecl());
187 case Stmt::DeclRefExprClass:
189 case Stmt::ObjCBoolLiteralExprClass:
192 case Stmt::CXXBoolLiteralExprClass:
193 case Stmt::IntegerLiteralClass: {
194 const Expr *
E = cast<Expr>(
S);
195 if (IncludeIntegers) {
196 if (SilenceableCondVal && !SilenceableCondVal->getBegin().isValid())
197 *SilenceableCondVal = E->getSourceRange();
202 case Stmt::MemberExprClass:
204 case Stmt::UnaryExprOrTypeTraitExprClass:
206 case Stmt::BinaryOperatorClass: {
217 case Stmt::UnaryOperatorClass: {
219 if (SilenceableCondVal)
220 *SilenceableCondVal = UO->getSourceRange();
223 IncludeIntegers, WrappedInParens);
233 if (
const VarDecl *VD = dyn_cast<VarDecl>(D)) {
241 if (!VD->hasLocalStorage())
246 return VD->getType().isLocalConstQualified();
255 if (isa<SwitchStmt>(Term))
258 if (isa<BinaryOperator>(Term)) {
268 llvm::BitVector &Reachable,
270 bool IncludeSometimesUnreachableEdges) {
286 while (!WL.empty()) {
287 const CFGBlock *item = WL.pop_back_val();
296 if (!IncludeSometimesUnreachableEdges)
297 TreatAllSuccessorsAsReachable =
false;
303 const CFGBlock *UB =
I->getPossiblyUnreachableBlock();
307 if (!TreatAllSuccessorsAsReachable.hasValue()) {
309 TreatAllSuccessorsAsReachable =
313 if (TreatAllSuccessorsAsReachable.getValue()) {
322 if (!Reachable[blockID]) {
323 Reachable.set(blockID);
335 llvm::BitVector &Reachable) {
345 llvm::BitVector Visited;
346 llvm::BitVector &Reachable;
353 DeferredLocsTy DeferredLocs;
356 DeadCodeScan(llvm::BitVector &reachable,
Preprocessor &PP)
357 : Visited(reachable.size()),
358 Reachable(reachable),
361 void enqueue(
const CFGBlock *block);
362 unsigned scanBackwards(
const CFGBlock *Start,
365 bool isDeadCodeRoot(
const CFGBlock *Block);
369 void reportDeadCode(
const CFGBlock *B,
375 void DeadCodeScan::enqueue(
const CFGBlock *block) {
377 if (Reachable[blockID] || Visited[blockID])
379 Visited[blockID] =
true;
380 WorkList.push_back(block);
384 bool isDeadRoot =
true;
389 unsigned blockID = PredBlock->getBlockID();
390 if (Visited[blockID]) {
394 if (!Reachable[blockID]) {
396 Visited[blockID] =
true;
397 WorkList.push_back(PredBlock);
407 if (S->getLocStart().isInvalid())
410 return BO->getOpcode() != BO_Comma;
417 const Stmt *
S = CS->getStmt();
423 if (!T.isTemporaryDtorsBranch()) {
424 const Stmt *S = T.getStmt();
433 static int SrcCmp(
const std::pair<const CFGBlock *, const Stmt *> *p1,
434 const std::pair<const CFGBlock *, const Stmt *> *p2) {
435 if (p1->second->getLocStart() < p2->second->getLocStart())
437 if (p2->second->getLocStart() < p1->second->getLocStart())
448 while (!WorkList.empty()) {
449 const CFGBlock *Block = WorkList.pop_back_val();
457 const Stmt *S = findDeadCode(Block);
470 if (S->getLocStart().isMacroID()) {
475 if (isDeadCodeRoot(Block)) {
476 reportDeadCode(Block, S, CB);
483 DeferredLocs.push_back(std::make_pair(Block, S));
489 if (!DeferredLocs.empty()) {
490 llvm::array_pod_sort(DeferredLocs.begin(), DeferredLocs.end(),
SrcCmp);
492 E = DeferredLocs.end();
I !=
E; ++
I) {
496 reportDeadCode(Block,
I->second, CB);
509 if (
const Expr *Ex = dyn_cast<Expr>(S))
510 S = Ex->IgnoreParenImpCasts();
512 switch (S->getStmtClass()) {
513 case Expr::BinaryOperatorClass: {
517 case Expr::UnaryOperatorClass: {
522 case Expr::CompoundAssignOperatorClass: {
524 R1 = CAO->
getLHS()->getSourceRange();
525 R2 = CAO->
getRHS()->getSourceRange();
528 case Expr::BinaryConditionalOperatorClass:
529 case Expr::ConditionalOperatorClass: {
531 cast<AbstractConditionalOperator>(
S);
534 case Expr::MemberExprClass: {
536 R1 = ME->getSourceRange();
539 case Expr::ArraySubscriptExprClass: {
541 R1 = ASE->
getLHS()->getSourceRange();
542 R2 = ASE->
getRHS()->getSourceRange();
545 case Expr::CStyleCastExprClass: {
550 case Expr::CXXFunctionalCastExprClass: {
555 case Stmt::CXXTryStmtClass: {
556 return cast<CXXTryStmt>(
S)->getHandler(0)->getCatchLoc();
558 case Expr::ObjCBridgedCastExprClass: {
565 R1 = S->getSourceRange();
566 return S->getLocStart();
569 void DeadCodeScan::reportDeadCode(
const CFGBlock *B,
575 if (isa<BreakStmt>(S)) {
595 if (
const ForStmt *FS = dyn_cast<ForStmt>(LoopTarget)) {
596 const Expr *Inc = FS->getInc();
597 Loc = Inc->getLocStart();
598 R2 = Inc->getSourceRange();
611 if (
const CFGBlock *PredBlock = PI->getPossiblyUnreachableBlock()) {
612 const Stmt *TermCond =
613 PredBlock->getTerminatorCondition(
false);
628 namespace clang {
namespace reachable_code {
630 void Callback::anchor() { }
633 llvm::BitVector &Reachable) {
647 unsigned numReachable =
671 DeadCodeScan DS(reachable, PP);
672 numReachable += DS.scanBackwards(block, CB);
SourceManager & getSourceManager() const
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
static bool isValidDeadStmt(const Stmt *S)
virtual void HandleUnreachable(UnreachableKind UK, SourceLocation L, SourceRange ConditionVal, SourceRange R1, SourceRange R2)=0
succ_iterator succ_begin()
static int SrcCmp(const std::pair< const CFGBlock *, const Stmt * > *p1, const std::pair< const CFGBlock *, const Stmt * > *p2)
EnumConstantDecl - An instance of this object exists for each enum constant that is defined...
Defines the SourceManager interface.
static bool isEnumConstant(const Expr *Ex)
ParenExpr - This represents a parethesized expression, e.g.
SourceLocation getOperatorLoc() const
SourceLocation getLocStart() const LLVM_READONLY
VarDecl - An instance of this class is created to represent a variable declaration or definition...
unsigned succ_size() const
static bool isConfigurationValue(const ValueDecl *D, Preprocessor &PP)
SourceLocation getLParenLoc() const
Defines the clang::Expr interface and subclasses for C++ expressions.
AnalysisDeclContext contains the context data for the function or method under analysis.
const Stmt * getLoopTarget() const
std::vector< const CFGBlock * >::const_iterator try_block_iterator
ForStmt - This represents a 'for (init;cond;inc)' stmt.
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
unsigned pred_size() const
ElementList::const_iterator const_iterator
A builtin binary operation expression such as "x + y" or "x <= y".
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
static unsigned scanMaybeReachableFromBlock(const CFGBlock *Start, Preprocessor &PP, llvm::BitVector &Reachable)
detail::InMemoryDirectory::const_iterator I
static bool isDeadReturn(const CFGBlock *B, const Stmt *S)
static bool isTrivialExpression(const Expr *Ex)
CFGBlock - Represents a single basic block in a source-level CFG.
static SourceLocation GetUnreachableLoc(const Stmt *S, SourceRange &R1, SourceRange &R2)
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Expr - This represents one expression.
Stmt * getTerminatorCondition(bool StripParens=true)
CFG - Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt...
Defines the clang::Preprocessor interface.
void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP, Callback &CB)
unsigned ScanReachableFromBlock(const CFGBlock *Start, llvm::BitVector &Reachable)
ScanReachableFromBlock - Mark all blocks reachable from Start.
SourceLocation getQuestionLoc() const
AdjacentBlocks::const_iterator const_pred_iterator
Expr * getSubExpr() const
unsigned getBlockID() const
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr.cast]), which uses the syntax (Type)expr.
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
reverse_iterator rbegin()
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
DoStmt - This represents a 'do/while' stmt.
static bool isExpandedFromConfigurationMacro(const Stmt *S, Preprocessor &PP, bool IgnoreYES_NO=false)
Returns true if the statement is expanded from a configuration macro.
CFGTerminator getTerminator()
Stmt * getParent(Stmt *) const
Encodes a location in the source.
const TemplateArgument * iterator
bool isTemporaryDtorsBranch() const
static SourceLocation getTopMostMacro(SourceLocation Loc, SourceManager &SM)
static bool isLogicalOp(Opcode Opc)
AdjacentBlocks::const_iterator const_succ_iterator
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
SourceLocation getRBracketLoc() const
CompoundAssignOperator - For compound assignments (e.g.
An Objective-C "bridged" cast expression, which casts between Objective-C pointers and C pointers...
pred_iterator pred_begin()
SourceLocation getLParenLoc() const
CFG::BuildOptions & getCFGBuildOptions()
Return the build options used to construct the CFG.
static bool shouldTreatSuccessorsAsReachable(const CFGBlock *B, Preprocessor &PP)
Returns true if we should always explore all successors of a block.
detail::InMemoryDirectory::const_iterator E
try_block_iterator try_blocks_end() const
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'...
UnreachableKind
Classifications of unreachable code.
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
static unsigned scanFromBlock(const CFGBlock *Start, llvm::BitVector &Reachable, Preprocessor *PP, bool IncludeSometimesUnreachableEdges)
try_block_iterator try_blocks_begin() const
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Represents an explicit C++ type conversion that uses "functional" notation (C++ [expr.type.conv]).
CFGElement - Represents a top-level expression in a basic block.
CFGTerminator - Represents CFGBlock terminator statement.
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
A reference to a declared variable, function, enum, etc.
static bool isTrivialDoWhile(const CFGBlock *B, const Stmt *S)
A trivial tuple used to represent a source range.
unsigned getNumBlockIDs() const
getNumBlockIDs - Returns the total number of BlockIDs allocated (which start at 0).
static bool isComparisonOp(Opcode Opc)
This class handles loading and caching of source files into memory.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.