Charusso created this revision.
Charusso added reviewers: NoQ, xazax.hun.
Charusso added a project: clang.
Herald added subscribers: cfe-commits, dkrupp, donat.nagy, Szelethus,
mikhail.ramalho, a.sidorin, rnkovacs, szepet, baloghadamsoftware.
Charusso added a comment.
Charusso added a parent revision: D66267: [analyzer] TrackConstraintBRVisitor:
Do not track unknown values.
@xazax.hun It is somehow performance critical code as we have too many casts in
the LLVM. I would really appreciate it if you could review it.
This patch extends the `DynamicTypeInfo` to hold information about the
dynamic type what could not be due to failed casts. With that improvement
the checker could use the `DynamicTypeMap` to store information about the
dynamic types. It improves the path-feasibility to prevent false positives.
Repository:
rC Clang
https://reviews.llvm.org/D66325
Files:
clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h
clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h
clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp
clang/test/Analysis/cast-value-logic.cpp
clang/test/Analysis/cast-value-notes.cpp
clang/test/Analysis/cast-value.cpp
Index: clang/test/Analysis/cast-value-notes.cpp
===================================================================
--- clang/test/Analysis/cast-value-notes.cpp
+++ clang/test/Analysis/cast-value-notes.cpp
@@ -1,7 +1,4 @@
// RUN: %clang_analyze_cc1 \
-// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
-// RUN: -verify=logic %s
-// RUN: %clang_analyze_cc1 \
// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue \
// RUN: -analyzer-output=text -verify %s
@@ -42,111 +39,12 @@
using namespace llvm;
using namespace clang;
-namespace test_cast {
-void evalLogic(const Shape *S) {
- const Circle *C = cast<Circle>(S);
- clang_analyzer_numTimesReached(); // logic-warning {{1}}
-
- if (S && C)
- clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
-
- if (S && !C)
- clang_analyzer_warnIfReached(); // no-warning
-
- if (!S)
- clang_analyzer_warnIfReached(); // no-warning
-}
-} // namespace test_cast
-
-namespace test_dyn_cast {
-void evalLogic(const Shape *S) {
- const Circle *C = dyn_cast<Circle>(S);
- clang_analyzer_numTimesReached(); // logic-warning {{2}}
-
- if (S && C)
- clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
-
- if (S && !C)
- clang_analyzer_warnIfReached(); // logic-warning {{REACHABLE}}
-
- if (!S)
- clang_analyzer_warnIfReached(); // no-warning
-}
-} // namespace test_dyn_cast
-
-namespace test_cast_or_null {
-void evalLogic(const Shape *S) {
- const Circle *C = cast_or_null<Circle>(S);
- clang_analyzer_numTimesReached(); // logic-warning {{2}}
-
- if (S && C)
- clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
-
- if (S && !C)
- clang_analyzer_warnIfReached(); // no-warning
-
- if (!S)
- clang_analyzer_eval(!C); // logic-warning {{TRUE}}
-}
-} // namespace test_cast_or_null
-
-namespace test_dyn_cast_or_null {
-void evalLogic(const Shape *S) {
- const Circle *C = dyn_cast_or_null<Circle>(S);
- clang_analyzer_numTimesReached(); // logic-warning {{3}}
-
- if (S && C)
- clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
-
- if (S && !C)
- clang_analyzer_warnIfReached(); // logic-warning {{REACHABLE}}
-
- if (!S)
- clang_analyzer_eval(!C); // logic-warning {{TRUE}}
-}
-} // namespace test_dyn_cast_or_null
-
-namespace test_cast_as {
-void evalLogic(const Shape *S) {
- const Circle *C = S->castAs<Circle>();
- clang_analyzer_numTimesReached(); // logic-warning {{1}}
-
- if (S && C)
- clang_analyzer_eval(C == S);
- // logic-warning@-1 {{TRUE}}
-
- if (S && !C)
- clang_analyzer_warnIfReached(); // no-warning
-
- if (!S)
- clang_analyzer_warnIfReached(); // no-warning
-}
-} // namespace test_cast_as
-
-namespace test_get_as {
-void evalLogic(const Shape *S) {
- const Circle *C = S->getAs<Circle>();
- clang_analyzer_numTimesReached(); // logic-warning {{2}}
-
- if (S && C)
- clang_analyzer_eval(C == S);
- // logic-warning@-1 {{TRUE}}
-
- if (S && !C)
- clang_analyzer_warnIfReached(); // logic-warning {{REACHABLE}}
-
- if (!S)
- clang_analyzer_warnIfReached(); // no-warning
-}
-} // namespace test_get_as
-
namespace test_notes {
void evalReferences(const Shape &S) {
const auto &C = dyn_cast<Circle>(S);
// expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Circle' fails}}
// expected-note@-2 {{Dereference of null pointer}}
// expected-warning@-3 {{Dereference of null pointer}}
- // logic-warning@-4 {{Dereference of null pointer}}
}
void evalNonNullParamNonNullReturnReference(const Shape &S) {
@@ -154,11 +52,22 @@
// expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Circle' succeeds}}
// expected-note@-2 {{'C' initialized here}}
- (void)(1 / !(bool)C);
+ if (dyn_cast_or_null<Triangle>(C)) {
+ // expected-note@-1 {{Assuming dynamic cast from 'Circle' to 'Triangle' fails}}
+ // expected-note@-2 {{Taking false branch}}
+ return;
+ }
+
+ if (dyn_cast_or_null<Triangle>(C)) {
+ // expected-note@-1 {{Dynamic cast from 'Circle' to 'Triangle' fails}}
+ // expected-note@-2 {{Taking false branch}}
+ return;
+ }
+
+ (void)(1 / !C);
// expected-note@-1 {{'C' is non-null}}
// expected-note@-2 {{Division by zero}}
// expected-warning@-3 {{Division by zero}}
- // logic-warning@-4 {{Division by zero}}
}
void evalNonNullParamNonNullReturn(const Shape *S) {
@@ -166,11 +75,16 @@
// expected-note@-1 {{Checked cast from 'Shape' to 'Circle' succeeds}}
// expected-note@-2 {{'C' initialized here}}
- (void)(1 / !(bool)C);
+ if (!cast<Triangle>(C)) {
+ // expected-note@-1 {{Checked cast from 'Circle' to 'Triangle' succeeds}}
+ // expected-note@-2 {{Taking false branch}}
+ return;
+ }
+
+ (void)(1 / !C);
// expected-note@-1 {{'C' is non-null}}
// expected-note@-2 {{Division by zero}}
// expected-warning@-3 {{Division by zero}}
- // logic-warning@-4 {{Division by zero}}
}
void evalNonNullParamNullReturn(const Shape *S) {
@@ -187,7 +101,6 @@
// expected-note@-1 {{'T' is non-null}}
// expected-note@-2 {{Division by zero}}
// expected-warning@-3 {{Division by zero}}
- // logic-warning@-4 {{Division by zero}}
}
}
@@ -199,41 +112,49 @@
(void)(1 / (bool)C);
// expected-note@-1 {{Division by zero}}
// expected-warning@-2 {{Division by zero}}
- // logic-warning@-3 {{Division by zero}}
}
void evalZeroParamNonNullReturnPointer(const Shape *S) {
const auto *C = S->castAs<Circle>();
- // expected-note@-1 {{Checked cast to 'Circle' succeeds}}
+ // expected-note@-1 {{Checked cast from 'Shape' to 'Circle' succeeds}}
// expected-note@-2 {{'C' initialized here}}
- (void)(1 / !(bool)C);
+ (void)(1 / !C);
// expected-note@-1 {{'C' is non-null}}
// expected-note@-2 {{Division by zero}}
// expected-warning@-3 {{Division by zero}}
- // logic-warning@-4 {{Division by zero}}
}
void evalZeroParamNonNullReturn(const Shape &S) {
const auto *C = S.castAs<Circle>();
- // expected-note@-1 {{Checked cast to 'Circle' succeeds}}
+ // expected-note@-1 {{Checked cast from 'Shape' to 'Circle' succeeds}}
// expected-note@-2 {{'C' initialized here}}
- (void)(1 / !(bool)C);
+ (void)(1 / !C);
// expected-note@-1 {{'C' is non-null}}
// expected-note@-2 {{Division by zero}}
// expected-warning@-3 {{Division by zero}}
- // logic-warning@-4 {{Division by zero}}
}
void evalZeroParamNullReturn(const Shape &S) {
const auto *C = S.getAs<Circle>();
- // expected-note@-1 {{Assuming dynamic cast to 'Circle' fails}}
+ // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Circle' fails}}
// expected-note@-2 {{'C' initialized to a null pointer value}}
+ if (!dyn_cast_or_null<Circle>(S)) {
+ // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Circle' succeeds}}
+ // expected-note@-2 {{Taking false branch}}
+ return;
+ }
+
+ if (!dyn_cast_or_null<Circle>(S)) {
+ // expected-note@-1 {{Dynamic cast from 'Shape' to 'Circle' succeeds}}
+ // expected-note@-2 {{Taking false branch}}
+ return;
+ }
+
(void)(1 / (bool)C);
// expected-note@-1 {{Division by zero}}
// expected-warning@-2 {{Division by zero}}
- // logic-warning@-3 {{Division by zero}}
}
} // namespace test_notes
Index: clang/test/Analysis/cast-value-logic.cpp
===================================================================
--- /dev/null
+++ clang/test/Analysis/cast-value-logic.cpp
@@ -0,0 +1,138 @@
+// RUN: %clang_analyze_cc1 \
+// RUN: -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN: -verify=logic %s
+
+void clang_analyzer_numTimesReached();
+void clang_analyzer_warnIfReached();
+void clang_analyzer_eval(bool);
+
+namespace llvm {
+template <class X, class Y>
+const X *cast(Y Value);
+
+template <class X, class Y>
+const X *dyn_cast(Y *Value);
+template <class X, class Y>
+const X &dyn_cast(Y &Value);
+
+template <class X, class Y>
+const X *cast_or_null(Y Value);
+
+template <class X, class Y>
+const X *dyn_cast_or_null(Y *Value);
+template <class X, class Y>
+const X *dyn_cast_or_null(Y &Value);
+} // namespace llvm
+
+namespace clang {
+struct Shape {
+ template <typename T>
+ const T *castAs() const;
+
+ template <typename T>
+ const T *getAs() const;
+};
+class Triangle : public Shape {};
+class Circle : public Shape {};
+} // namespace clang
+
+using namespace llvm;
+using namespace clang;
+
+namespace test_cast {
+void evalLogic(const Shape *S) {
+ const Circle *C = cast<Circle>(S);
+ clang_analyzer_numTimesReached(); // logic-warning {{1}}
+
+ if (S && C)
+ clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
+
+ if (S && !C)
+ clang_analyzer_warnIfReached(); // no-warning
+
+ if (!S)
+ clang_analyzer_warnIfReached(); // no-warning
+}
+} // namespace test_cast
+
+namespace test_dyn_cast {
+void evalLogic(const Shape *S) {
+ const Circle *C = dyn_cast<Circle>(S);
+ clang_analyzer_numTimesReached(); // logic-warning {{2}}
+
+ if (S && C)
+ clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
+
+ if (S && !C)
+ clang_analyzer_warnIfReached(); // logic-warning {{REACHABLE}}
+
+ if (!S)
+ clang_analyzer_warnIfReached(); // no-warning
+}
+} // namespace test_dyn_cast
+
+namespace test_cast_or_null {
+void evalLogic(const Shape *S) {
+ const Circle *C = cast_or_null<Circle>(S);
+ clang_analyzer_numTimesReached(); // logic-warning {{2}}
+
+ if (S && C)
+ clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
+
+ if (S && !C)
+ clang_analyzer_warnIfReached(); // no-warning
+
+ if (!S)
+ clang_analyzer_eval(!C); // logic-warning {{TRUE}}
+}
+} // namespace test_cast_or_null
+
+namespace test_dyn_cast_or_null {
+void evalLogic(const Shape *S) {
+ const Circle *C = dyn_cast_or_null<Circle>(S);
+ clang_analyzer_numTimesReached(); // logic-warning {{3}}
+
+ if (S && C)
+ clang_analyzer_eval(C == S); // logic-warning {{TRUE}}
+
+ if (S && !C)
+ clang_analyzer_warnIfReached(); // logic-warning {{REACHABLE}}
+
+ if (!S)
+ clang_analyzer_eval(!C); // logic-warning {{TRUE}}
+}
+} // namespace test_dyn_cast_or_null
+
+namespace test_cast_as {
+void evalLogic(const Shape *S) {
+ const Circle *C = S->castAs<Circle>();
+ clang_analyzer_numTimesReached(); // logic-warning {{1}}
+
+ if (S && C)
+ clang_analyzer_eval(C == S);
+ // logic-warning@-1 {{TRUE}}
+
+ if (S && !C)
+ clang_analyzer_warnIfReached(); // no-warning
+
+ if (!S)
+ clang_analyzer_warnIfReached(); // no-warning
+}
+} // namespace test_cast_as
+
+namespace test_get_as {
+void evalLogic(const Shape *S) {
+ const Circle *C = S->getAs<Circle>();
+ clang_analyzer_numTimesReached(); // logic-warning {{2}}
+
+ if (S && C)
+ clang_analyzer_eval(C == S);
+ // logic-warning@-1 {{TRUE}}
+
+ if (S && !C)
+ clang_analyzer_warnIfReached(); // logic-warning {{REACHABLE}}
+
+ if (!S)
+ clang_analyzer_warnIfReached(); // no-warning
+}
+} // namespace test_get_as
Index: clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp
===================================================================
--- clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp
+++ clang/lib/StaticAnalyzer/Core/DynamicTypeMap.cpp
@@ -25,20 +25,18 @@
namespace clang {
namespace ento {
-DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State,
- const MemRegion *Reg) {
- Reg = Reg->StripCasts();
+DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR) {
+ MR = MR->StripCasts();
// Look up the dynamic type in the GDM.
- const DynamicTypeInfo *GDMType = State->get<DynamicTypeMap>(Reg);
- if (GDMType)
- return *GDMType;
+ if (const DynamicTypeInfo *DTI = State->get<DynamicTypeMap>(MR))
+ return *DTI;
// Otherwise, fall back to what we know about the region.
- if (const auto *TR = dyn_cast<TypedRegion>(Reg))
+ if (const auto *TR = dyn_cast<TypedRegion>(MR))
return DynamicTypeInfo(TR->getLocationType(), /*CanBeSub=*/false);
- if (const auto *SR = dyn_cast<SymbolicRegion>(Reg)) {
+ if (const auto *SR = dyn_cast<SymbolicRegion>(MR)) {
SymbolRef Sym = SR->getSymbol();
return DynamicTypeInfo(Sym->getType());
}
@@ -46,12 +44,52 @@
return {};
}
-ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *Reg,
+const DynamicTypeInfo *getRawDynamicTypeInfo(ProgramStateRef State,
+ const MemRegion *MR) {
+ return State->get<DynamicTypeMap>(MR);
+}
+
+ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR,
DynamicTypeInfo NewTy) {
- Reg = Reg->StripCasts();
- ProgramStateRef NewState = State->set<DynamicTypeMap>(Reg, NewTy);
- assert(NewState);
- return NewState;
+ State = State->set<DynamicTypeMap>(MR->StripCasts(), NewTy);
+ assert(State);
+ return State;
+}
+
+ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR,
+ QualType NewTy, bool CanBeSubClassed) {
+ return setDynamicTypeInfo(State, MR, DynamicTypeInfo(NewTy, CanBeSubClassed));
+}
+
+ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR,
+ const DynamicTypeInfo *DynTy, QualType RawTy,
+ bool IsCastSucceeds) {
+ if (IsCastSucceeds) {
+ // If the cast succeeds and the 'DynTy' already made it means we have
+ // failed casts available so we need to store the 'RawTy' successful cast.
+ if (DynTy) {
+ State = State->set<DynamicTypeMap>(
+ MR, {*DynTy, RawTy, DynamicTypeInfo::CastKind::Success});
+ } else {
+ // Otherwise we create the 'DynTy' with the 'RawTy' successful cast.
+ State = State->set<DynamicTypeMap>(
+ MR, {RawTy, DynamicTypeInfo::CastKind::Success});
+ }
+ } else {
+ // If the cast fails and the 'DynTy' already made it means we have the
+ // succeesful cast available so we need to store the 'RawTy' failed cast.
+ if (DynTy) {
+ State = State->set<DynamicTypeMap>(
+ MR, {*DynTy, RawTy, DynamicTypeInfo::CastKind::Fail});
+ } else {
+ // Otherwise we create the 'DynTy' with the 'RawTy' failed cast.
+ State = State->set<DynamicTypeMap>(
+ MR, {RawTy, DynamicTypeInfo::CastKind::Fail});
+ }
+ }
+
+ assert(State);
+ return State;
}
void printDynamicTypeInfoJson(raw_ostream &Out, ProgramStateRef State,
@@ -75,7 +113,7 @@
<< "\", \"sub_classable\": "
<< (DTI.canBeASubClass() ? "true" : "false");
} else {
- Out << "null"; // Invalid type info
+ Out << "null "; // Invalid type info
}
Out << "}";
Index: clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
===================================================================
--- clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
@@ -15,6 +15,7 @@
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
#include "llvm/ADT/Optional.h"
#include <utility>
@@ -23,23 +24,23 @@
namespace {
class CastValueChecker : public Checker<eval::Call> {
- enum class CastKind { Function, Method };
+ enum class CallKind { Function, Method };
using CastCheck =
std::function<void(const CastValueChecker *, const CallExpr *,
DefinedOrUnknownSVal, CheckerContext &)>;
- using CheckKindPair = std::pair<CastCheck, CastKind>;
+ using CheckKindPair = std::pair<CastCheck, CallKind>;
public:
// We have five cases to evaluate a cast:
- // 1) The parameter is non-null, the return value is non-null
- // 2) The parameter is non-null, the return value is null
- // 3) The parameter is null, the return value is null
+ // 1) The parameter is non-null, the return value is non-null.
+ // 2) The parameter is non-null, the return value is null.
+ // 3) The parameter is null, the return value is null.
// cast: 1; dyn_cast: 1, 2; cast_or_null: 1, 3; dyn_cast_or_null: 1, 2, 3.
//
- // 4) castAs: has no parameter, the return value is non-null.
- // 5) getAs: has no parameter, the return value is null or non-null.
+ // 4) castAs: Has no parameter, the return value is non-null.
+ // 5) getAs: Has no parameter, the return value is null or non-null.
bool evalCall(const CallEvent &Call, CheckerContext &C) const;
private:
@@ -47,17 +48,17 @@
// {{{namespace, call}, argument-count}, {callback, kind}}
const CallDescriptionMap<CheckKindPair> CDM = {
{{{"llvm", "cast"}, 1},
- {&CastValueChecker::evalCast, CastKind::Function}},
+ {&CastValueChecker::evalCast, CallKind::Function}},
{{{"llvm", "dyn_cast"}, 1},
- {&CastValueChecker::evalDynCast, CastKind::Function}},
+ {&CastValueChecker::evalDynCast, CallKind::Function}},
{{{"llvm", "cast_or_null"}, 1},
- {&CastValueChecker::evalCastOrNull, CastKind::Function}},
+ {&CastValueChecker::evalCastOrNull, CallKind::Function}},
{{{"llvm", "dyn_cast_or_null"}, 1},
- {&CastValueChecker::evalDynCastOrNull, CastKind::Function}},
+ {&CastValueChecker::evalDynCastOrNull, CallKind::Function}},
{{{"clang", "castAs"}, 0},
- {&CastValueChecker::evalCastAs, CastKind::Method}},
+ {&CastValueChecker::evalCastAs, CallKind::Method}},
{{{"clang", "getAs"}, 0},
- {&CastValueChecker::evalGetAs, CastKind::Method}}};
+ {&CastValueChecker::evalGetAs, CallKind::Method}}};
void evalCast(const CallExpr *CE, DefinedOrUnknownSVal DV,
CheckerContext &C) const;
@@ -82,39 +83,85 @@
return Ty->getPointeeCXXRecordDecl()->getNameAsString();
}
-static const NoteTag *getCastTag(bool IsNullReturn, const CallExpr *CE,
- CheckerContext &C,
- bool IsCheckedCast = false) {
- Optional<std::string> CastFromName = (CE->getNumArgs() > 0)
- ? getCastName(CE->getArg(0))
- : Optional<std::string>();
+//===----------------------------------------------------------------------===//
+// Main logic to evaluate a cast.
+//===----------------------------------------------------------------------===//
+
+static void addCastTransition(const CallExpr *CE, DefinedOrUnknownSVal DV,
+ CheckerContext &C, bool IsNonNullParam,
+ bool IsNonNullReturn,
+ bool IsCheckedCast = false) {
+ ProgramStateRef State = C.getState()->assume(DV, IsNonNullParam);
+ if (!State)
+ return;
+
+ // Handle 'evalNullParamNullReturn()' specially.
+ if (!IsNonNullParam && !IsNonNullReturn) {
+ C.addTransition(State->BindExpr(CE, C.getLocationContext(),
+ C.getSValBuilder().makeNull(), false),
+ C.getNoteTag("Assuming null pointer is passed into cast",
+ /*IsPrunable=*/true));
+ return;
+ }
+
+ const MemRegion *MR = DV.getAsRegion();
+ const DynamicTypeInfo *DynTy = getRawDynamicTypeInfo(State, MR);
+
+ QualType RawTy = CE->getType();
+ if (RawTy->isPointerType()) {
+ RawTy = RawTy->getPointeeType();
+ }
+ RawTy = RawTy.getUnqualifiedType();
+
+ // We assume that every checked cast succeeds.
+ bool IsCastSucceeds = IsCheckedCast;
+ if (!IsCastSucceeds) {
+ // If we know the dynamic type, see whether the current cast succeeds.
+ if (DynTy) {
+ IsCastSucceeds = IsNonNullReturn && DynTy->isCastSucceeds(RawTy);
+ } else {
+ // If it is the first dynamic cast it succeeds if the return is non-null.
+ IsCastSucceeds = IsNonNullReturn;
+ }
+ }
+
+ // Check whether we have seen that dynamic type.
+ bool IsDynTypeFound = DynTy && DynTy->isCastFound(RawTy);
+
+ // Store the type information if we have not seen this dynamic type yet.
+ if (!IsDynTypeFound) {
+ State = setDynamicTypeInfo(State, MR, DynTy, RawTy, IsCastSucceeds);
+ }
+
std::string CastToName = getCastName(CE);
+ std::string CastFromName = "";
+ if (CE->getNumArgs() > 0) {
+ CastFromName = getCastName(CE->getArg(0));
+ } else {
+ QualType CastFromTy = DV.getAsSymbol()->getType();
+ CastFromName = CastFromTy->getPointeeCXXRecordDecl()->getNameAsString();
+ }
- return C.getNoteTag(
- [CastFromName, CastToName, IsNullReturn,
- IsCheckedCast](BugReport &) -> std::string {
+ const NoteTag *Tag = C.getNoteTag(
+ [=](BugReport &) -> std::string {
SmallString<128> Msg;
llvm::raw_svector_ostream Out(Msg);
- Out << (!IsCheckedCast ? "Assuming dynamic cast " : "Checked cast ");
- if (CastFromName)
- Out << "from '" << *CastFromName << "' ";
+ if (!IsCheckedCast) {
+ Out << (IsDynTypeFound ? "Dynamic cast" : "Assuming dynamic cast");
+ } else {
+ Out << "Checked cast";
+ }
- Out << "to '" << CastToName << "' "
- << (!IsNullReturn ? "succeeds" : "fails");
+ Out << " from '" << CastFromName << "' to '" << CastToName << "' "
+ << (IsCastSucceeds ? "succeeds" : "fails");
return Out.str();
},
/*IsPrunable=*/true);
-}
-static ProgramStateRef getState(bool IsNullReturn,
- DefinedOrUnknownSVal ReturnDV,
- const CallExpr *CE, ProgramStateRef State,
- CheckerContext &C) {
- return State->BindExpr(
- CE, C.getLocationContext(),
- IsNullReturn ? C.getSValBuilder().makeNull() : ReturnDV, false);
+ SVal V = IsCastSucceeds ? DV : C.getSValBuilder().makeNull();
+ C.addTransition(State->BindExpr(CE, C.getLocationContext(), V, false), Tag);
}
//===----------------------------------------------------------------------===//
@@ -125,27 +172,21 @@
DefinedOrUnknownSVal DV,
CheckerContext &C,
bool IsCheckedCast = false) {
- bool IsNullReturn = false;
- if (ProgramStateRef State = C.getState()->assume(DV, true))
- C.addTransition(getState(IsNullReturn, DV, CE, State, C),
- getCastTag(IsNullReturn, CE, C, IsCheckedCast));
+ addCastTransition(CE, DV, C, /*IsNonNullParam=*/true,
+ /*IsNonNullReturn=*/true, IsCheckedCast);
}
static void evalNonNullParamNullReturn(const CallExpr *CE,
DefinedOrUnknownSVal DV,
CheckerContext &C) {
- bool IsNullReturn = true;
- if (ProgramStateRef State = C.getState()->assume(DV, true))
- C.addTransition(getState(IsNullReturn, DV, CE, State, C),
- getCastTag(IsNullReturn, CE, C));
+ addCastTransition(CE, DV, C, /*IsNonNullParam=*/true,
+ /*IsNonNullReturn=*/false);
}
static void evalNullParamNullReturn(const CallExpr *CE, DefinedOrUnknownSVal DV,
CheckerContext &C) {
- if (ProgramStateRef State = C.getState()->assume(DV, false))
- C.addTransition(getState(/*IsNullReturn=*/true, DV, CE, State, C),
- C.getNoteTag("Assuming null pointer is passed into cast",
- /*IsPrunable=*/true));
+ addCastTransition(CE, DV, C, /*IsNonNullParam=*/false,
+ /*IsNonNullReturn=*/false);
}
void CastValueChecker::evalCast(const CallExpr *CE, DefinedOrUnknownSVal DV,
@@ -182,18 +223,14 @@
DefinedOrUnknownSVal DV,
CheckerContext &C,
bool IsCheckedCast = false) {
- bool IsNullReturn = false;
- if (ProgramStateRef State = C.getState()->assume(DV, true))
- C.addTransition(getState(IsNullReturn, DV, CE, C.getState(), C),
- getCastTag(IsNullReturn, CE, C, IsCheckedCast));
+ addCastTransition(CE, DV, C, /*IsNonNullParam=*/true,
+ /*IsNonNullReturn=*/true, IsCheckedCast);
}
static void evalZeroParamNullReturn(const CallExpr *CE, DefinedOrUnknownSVal DV,
CheckerContext &C) {
- bool IsNullReturn = true;
- if (ProgramStateRef State = C.getState()->assume(DV, true))
- C.addTransition(getState(IsNullReturn, DV, CE, C.getState(), C),
- getCastTag(IsNullReturn, CE, C));
+ addCastTransition(CE, DV, C, /*IsNonNullParam=*/true,
+ /*IsNonNullReturn=*/false);
}
void CastValueChecker::evalCastAs(const CallExpr *CE, DefinedOrUnknownSVal DV,
@@ -207,6 +244,10 @@
evalZeroParamNullReturn(CE, DV, C);
}
+//===----------------------------------------------------------------------===//
+// Main logic to evaluate a call.
+//===----------------------------------------------------------------------===//
+
bool CastValueChecker::evalCall(const CallEvent &Call,
CheckerContext &C) const {
const auto *Lookup = CDM.lookup(Call);
@@ -219,13 +260,13 @@
return false;
const CastCheck &Check = Lookup->first;
- CastKind Kind = Lookup->second;
+ CallKind Kind = Lookup->second;
const auto *CE = cast<CallExpr>(Call.getOriginExpr());
Optional<DefinedOrUnknownSVal> DV;
switch (Kind) {
- case CastKind::Function: {
+ case CallKind::Function: {
// If we cannot obtain the arg's class we cannot be sure how to model it.
QualType ArgTy = Call.parameters()[0]->getType();
if (!ArgTy->getAsCXXRecordDecl() && !ArgTy->getPointeeCXXRecordDecl())
@@ -234,7 +275,7 @@
DV = Call.getArgSVal(0).getAs<DefinedOrUnknownSVal>();
break;
}
- case CastKind::Method:
+ case CallKind::Method:
// If we cannot obtain the 'InstanceCall' we cannot be sure how to model it.
const auto *InstanceCall = dyn_cast<CXXInstanceCall>(&Call);
if (!InstanceCall)
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h
===================================================================
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h
@@ -13,12 +13,12 @@
#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEMAP_H
#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEMAP_H
+#include "clang/AST/Type.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
#include "llvm/ADT/ImmutableMap.h"
-#include "clang/AST/Type.h"
namespace clang {
namespace ento {
@@ -37,21 +37,25 @@
static void *GDMIndex();
};
-/// Get dynamic type information for a region.
-DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State,
- const MemRegion *Reg);
+/// Get dynamic type information for the region \p MR.
+DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR);
+
+/// Get the raw dynamic type information for the region \p MR.
+const DynamicTypeInfo *getRawDynamicTypeInfo(ProgramStateRef State,
+ const MemRegion *MR);
/// Set dynamic type information of the region; return the new state.
-ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *Reg,
+ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR,
DynamicTypeInfo NewTy);
/// Set dynamic type information of the region; return the new state.
-inline ProgramStateRef setDynamicTypeInfo(ProgramStateRef State,
- const MemRegion *Reg, QualType NewTy,
- bool CanBeSubClassed = true) {
- return setDynamicTypeInfo(State, Reg,
- DynamicTypeInfo(NewTy, CanBeSubClassed));
-}
+ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR,
+ QualType NewTy, bool CanBeSubClassed = true);
+
+/// Set dynamic type information of the region; return the new state.
+ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR,
+ const DynamicTypeInfo *DynTy, QualType RawTy,
+ bool IsCastSucceeds);
void printDynamicTypeInfoJson(raw_ostream &Out, ProgramStateRef State,
const char *NL = "\n", unsigned int Space = 0,
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h
===================================================================
--- clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h
@@ -9,43 +9,111 @@
#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEINFO_H
#include "clang/AST/Type.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallVector.h"
namespace clang {
namespace ento {
/// Stores the currently inferred strictest bound on the runtime type
/// of a region in a given state along the analysis path.
+/// Also stores what runtime types it could not be due to failed casts.
class DynamicTypeInfo {
-private:
- QualType T;
- bool CanBeASubClass;
-
public:
+ enum class CastKind { Success, Fail };
- DynamicTypeInfo() : T(QualType()) {}
- DynamicTypeInfo(QualType WithType, bool CanBeSub = true)
- : T(WithType), CanBeASubClass(CanBeSub) {}
+ DynamicTypeInfo() : DynTy(QualType()) {}
- /// Return false if no dynamic type info is available.
- bool isValid() const { return !T.isNull(); }
+ DynamicTypeInfo(QualType Ty, bool CanBeSub = true)
+ : DynTy(Ty), CanBeASubClass(CanBeSub) {}
- /// Returns the currently inferred upper bound on the runtime type.
- QualType getType() const { return T; }
+ DynamicTypeInfo(QualType Ty, CastKind Kind) {
+ switch (Kind) {
+ case CastKind::Success:
+ DynTy = Ty;
+ break;
+ case CastKind::Fail:
+ FailedCastVector.push_back(Ty);
+ break;
+ }
+ }
+
+ DynamicTypeInfo(const DynamicTypeInfo &DTI, QualType Ty, CastKind Kind) {
+ switch (Kind) {
+ case CastKind::Success:
+ assert(!isValid() && "Only one successful dynamic cast is allowed.");
+ DynTy = Ty;
+ FailedCastVector = DTI.FailedCastVector;
+ break;
+ case CastKind::Fail:
+ DynTy = DTI.DynTy;
+ FailedCastVector = DTI.FailedCastVector;
+ FailedCastVector.push_back(Ty);
+ break;
+ }
+ }
- /// Returns false if the type information is precise (the type T is
+ /// Returns false if the type information is precise (the type 'DynTy' is
/// the only type in the lattice), true otherwise.
bool canBeASubClass() const { return CanBeASubClass; }
- void Profile(llvm::FoldingSetNodeID &ID) const {
- ID.Add(T);
- ID.AddInteger((unsigned)CanBeASubClass);
+ /// Returns true if the dynamic type info is available.
+ bool isValid() const { return !DynTy.isNull(); }
+
+ /// Returns the currently inferred upper bound on the runtime type.
+ QualType getType() const { return DynTy; }
+
+ /// Returns whether the dynamic cast to \p Ty type succeeds.
+ bool isCastSucceeds(QualType Ty) const {
+ if (isValid())
+ return DynTy == Ty;
+
+ return llvm::find(FailedCastVector, Ty) == FailedCastVector.end();
+ }
+
+ /// Returns whether we already have information about the \p Ty type.
+ bool isCastFound(QualType Ty) const {
+ if (isValid())
+ if (DynTy == Ty)
+ return true;
+
+ return llvm::find(FailedCastVector, Ty) != FailedCastVector.end();
}
+
bool operator==(const DynamicTypeInfo &X) const {
- return T == X.T && CanBeASubClass == X.CanBeASubClass;
+ return DynTy == X.DynTy && CanBeASubClass == X.CanBeASubClass &&
+ FailedCastVector == X.FailedCastVector;
}
+
+ void Profile(llvm::FoldingSetNodeID &ID) const {
+ ID.Add(DynTy);
+ ID.AddBoolean(CanBeASubClass);
+ }
+
+ void dump(raw_ostream &Out) const {
+ Out << "\nThe dynamic type is '" << DynTy.getAsString() << "'.";
+ Out << "\nCan be a sub class?: '" << CanBeASubClass << "'.";
+ Out << "\nThe failed casts:";
+ if (FailedCastVector.empty()) {
+ Out << " empty.\n\n";
+ return;
+ }
+
+ Out << '\n';
+ for (const QualType Ty : FailedCastVector)
+ Out << Ty.getAsString() << '\n';
+ Out << '\n';
+ }
+
+ LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
+
+private:
+ QualType DynTy;
+ bool CanBeASubClass;
+ llvm::SmallVector<QualType, 64> FailedCastVector;
};
-} // end ento
-} // end clang
+} // namespace ento
+} // namespace clang
-#endif
+#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEINFO_H
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits