Charusso updated this revision to Diff 216023.
Charusso edited the summary of this revision.
Charusso added a comment.

- Use a set factory to store a dynamic cast information set per memory region.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D66325/new/

https://reviews.llvm.org/D66325

Files:
  clang/include/clang/AST/Type.h
  clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h
  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-state-dump.cpp
  clang/test/Analysis/cast-value.cpp
  clang/test/Analysis/dump_egraph.cpp
  clang/test/Analysis/expr-inspection.c

Index: clang/test/Analysis/expr-inspection.c
===================================================================
--- clang/test/Analysis/expr-inspection.c
+++ clang/test/Analysis/expr-inspection.c
@@ -38,6 +38,7 @@
 // CHECK-NEXT:     { "symbol": "reg_$0<int x>", "range": "{ [-2147483648, 13] }" }
 // CHECK-NEXT:   ],
 // CHECK-NEXT:   "dynamic_types": null,
+// CHECK-NEXT:   "dynamic_casts": null,
 // CHECK-NEXT:   "constructing_objects": null,
 // CHECK-NEXT:   "checker_messages": null
 // CHECK-NEXT: }
Index: clang/test/Analysis/dump_egraph.cpp
===================================================================
--- clang/test/Analysis/dump_egraph.cpp
+++ clang/test/Analysis/dump_egraph.cpp
@@ -24,4 +24,5 @@
 
 // CHECK: \"cluster\": \"t\", \"pointer\": \"{{0x[0-9a-f]+}}\", \"items\": [\l&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\{ \"kind\": \"Default\", \"offset\": 0, \"value\": \"conj_$2\{int, LC5, no stmt, #1\}\"
 
-// CHECK: \"dynamic_types\": [\l\{ \"region\": \"HeapSymRegion\{conj_$1\{struct S *, LC1, S{{[0-9]+}}, #1\}\}\", \"dyn_type\": \"struct S\", \"sub_classable\": false\}\l
+// CHECK: \"dynamic_types\": [\l&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\{ \"region\": \"HeapSymRegion\{conj_$1\{struct S *, LC1, S{{[0-9]+}}, #1\}\}\", \"dyn_type\": \"struct S\", \"sub_classable\": false \}\l
+
Index: clang/test/Analysis/cast-value-state-dump.cpp
===================================================================
--- /dev/null
+++ clang/test/Analysis/cast-value-state-dump.cpp
@@ -0,0 +1,68 @@
+// RUN: %clang_analyze_cc1 \
+// RUN:  -analyzer-checker=core,apiModeling.llvm.CastValue,debug.ExprInspection\
+// RUN:  -analyzer-output=text -verify %s 2>&1 | FileCheck %s
+
+void clang_analyzer_printState();
+
+namespace llvm {
+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 {};
+class Triangle : public Shape {};
+class Circle : public Shape {};
+class Square : public Shape {};
+} // namespace clang
+
+using namespace llvm;
+using namespace clang;
+
+void evalNonNullParamNonNullReturnReference(const Shape &S) {
+  const auto *C = dyn_cast_or_null<Circle>(S);
+  // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Circle' succeeds}}
+  // expected-note@-2 {{'C' initialized here}}
+
+  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;
+  }
+
+  if (dyn_cast_or_null<Square>(C)) {
+    // expected-note@-1 {{Assuming dynamic cast from 'Circle' to 'Square' fails}}
+    // expected-note@-2 {{Taking false branch}}
+    return;
+  }
+
+  if (dyn_cast_or_null<Square>(S)) {
+    // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Square' fails}}
+    // expected-note@-2 {{Taking false branch}}
+    return;
+  }
+
+  clang_analyzer_printState();
+
+  // CHECK:      "dynamic_types": [
+  // CHECK-NEXT:   { "region": "SymRegion{reg_$0<const struct clang::Shape & S>}", "dyn_type": "const class clang::Circle", "sub_classable": true }
+  // CHECK-NEXT: ],
+  // CHECK-NEXT: "dynamic_casts": [
+  // CHECK:        { "region": "SymRegion{reg_$0<const struct clang::Shape & S>}", "casts": [
+  // CHECK-NEXT:     { "from": "struct clang::Shape", "to": "class clang::Circle", "kind": "success" },
+  // CHECK-NEXT:     { "from": "struct clang::Shape", "to": "class clang::Square", "kind": "fail" }
+  // CHECK-NEXT:   ]}
+
+  (void)(1 / !C);
+  // expected-note@-1 {{'C' is non-null}}
+  // expected-note@-2 {{Division by zero}}
+  // expected-warning@-3 {{Division by zero}}
+}
Index: clang/test/Analysis/cast-value-notes.cpp
===================================================================
--- clang/test/Analysis/cast-value-notes.cpp
+++ clang/test/Analysis/cast-value-notes.cpp
@@ -1,14 +1,7 @@
 // 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
 
-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);
@@ -42,111 +35,25 @@
 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 evalContradiction(const Shape *S) {
+  const auto *C = dyn_cast_or_null<Circle>(S);
+  // no-note: 'Assuming dynamic cast from 'Shape' to 'Circle' succeeds'
+
+  if (dyn_cast_or_null<Circle>(C)) {
+    // no-note: 'Dynamic cast from 'Circle' to 'Circle' fails'
+    return;
+  }
+
+  (void)(1 / !C);
+  // no-note: "'C' is non-null"
+  // no-warning: Division by zero
 }
 
 void evalNonNullParamNonNullReturnReference(const Shape &S) {
@@ -154,11 +61,28 @@
   // 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<Circle>(C)) {
+    // expected-note@-1 {{Dynamic cast from 'Circle' to 'Circle' succeeds}}
+    // expected-note@-2 {{Taking false branch}}
+    return;
+  }
+
+  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 +90,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 +116,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 +127,48 @@
   (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<Triangle>(S)) {
+    // expected-note@-1 {{Assuming dynamic cast from 'Shape' to 'Triangle' succeeds}}
+    // expected-note@-2 {{Taking false branch}}
+    return;
+  }
+
+  if (!dyn_cast_or_null<Triangle>(S)) {
+    // expected-note@-1 {{Dynamic cast from 'Shape' to 'Triangle' 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,139 @@
+// 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,40 +44,129 @@
   return {};
 }
 
-ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *Reg,
+const DynamicCastInfo *getDynamicCastInfo(ProgramStateRef State,
+                                          QualType CastFromTy,
+                                          QualType CastToTy) {
+  for (const auto &Elem : State->get<DynamicCastMap>())
+    for (const DynamicCastInfo &Cast : Elem.second)
+      if (Cast.equals(CastFromTy, CastToTy))
+        return &Cast;
+
+  return nullptr;
+}
+
+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;
 }
 
-void printDynamicTypeInfoJson(raw_ostream &Out, ProgramStateRef State,
-                              const char *NL, unsigned int Space, bool IsDot) {
+ProgramStateRef setDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR,
+                                   QualType NewTy, bool CanBeSubClassed) {
+  return setDynamicTypeInfo(State, MR, DynamicTypeInfo(NewTy, CanBeSubClassed));
+}
+
+ProgramStateRef setDynamicTypeAndCastInfo(ProgramStateRef State,
+                                          const MemRegion *MR,
+                                          QualType CastFromTy,
+                                          QualType CastToTy, QualType ResultTy,
+                                          bool IsCastSucceeds) {
+  if (IsCastSucceeds)
+    State = State->set<DynamicTypeMap>(MR, ResultTy);
+
+  DynamicCastInfo::CastKind Kind = IsCastSucceeds
+                                       ? DynamicCastInfo::CastKind::Success
+                                       : DynamicCastInfo::CastKind::Fail;
+
+  CastSet::Factory &F = State->get_context<CastSet>();
+  CastSet Set = F.getEmptySet();
+
+  if (const CastSet *TempSet = State->get<DynamicCastMap>(MR))
+    Set = *TempSet;
+
+  Set = F.add(Set, {CastFromTy, CastToTy, Kind});
+  State = State->set<DynamicCastMap>(MR, Set);
+
+  assert(State);
+  return State;
+}
+
+static void printDynamicTypesJson(raw_ostream &Out, ProgramStateRef State,
+                                  const char *NL, unsigned int Space,
+                                  bool IsDot) {
   Indent(Out, Space, IsDot) << "\"dynamic_types\": ";
 
-  const DynamicTypeMapTy &DTM = State->get<DynamicTypeMap>();
-  if (DTM.isEmpty()) {
+  const DynamicTypeMapTy &Map = State->get<DynamicTypeMap>();
+  if (Map.isEmpty()) {
     Out << "null," << NL;
     return;
   }
 
   ++Space;
   Out << '[' << NL;
-  for (DynamicTypeMapTy::iterator I = DTM.begin(); I != DTM.end(); ++I) {
+  for (DynamicTypeMapTy::iterator I = Map.begin(); I != Map.end(); ++I) {
     const MemRegion *MR = I->first;
     const DynamicTypeInfo &DTI = I->second;
-    Out << "{ \"region\": \"" << MR << "\", \"dyn_type\": ";
-    if (DTI.isValid()) {
+    Indent(Out, Space, IsDot)
+        << "{ \"region\": \"" << MR << "\", \"dyn_type\": ";
+    if (!DTI.isValid()) {
+      Out << "null";
+    } else {
       Out << '\"' << DTI.getType()->getPointeeType().getAsString()
           << "\", \"sub_classable\": "
           << (DTI.canBeASubClass() ? "true" : "false");
+    }
+    Out << " }";
+
+    if (std::next(I) != Map.end())
+      Out << ',';
+    Out << NL;
+  }
+
+  --Space;
+  Indent(Out, Space, IsDot) << "]," << NL;
+}
+
+static void printDynamicCastsJson(raw_ostream &Out, ProgramStateRef State,
+                                  const char *NL, unsigned int Space,
+                                  bool IsDot) {
+  Indent(Out, Space, IsDot) << "\"dynamic_casts\": ";
+
+  const DynamicCastMapTy &Map = State->get<DynamicCastMap>();
+  if (Map.isEmpty()) {
+    Out << "null," << NL;
+    return;
+  }
+
+  ++Space;
+  Out << '[' << NL;
+  for (DynamicCastMapTy::iterator I = Map.begin(); I != Map.end(); ++I) {
+    const MemRegion *MR = I->first;
+    const CastSet &Set = I->second;
+
+    Indent(Out, Space, IsDot) << "{ \"region\": \"" << MR << "\", \"casts\": ";
+    if (Set.isEmpty()) {
+      Out << "null ";
     } else {
-      Out << "null"; // Invalid type info
+      ++Space;
+      Out << '[' << NL;
+      for (CastSet::iterator SI = Set.begin(); SI != Set.end(); ++SI) {
+        Indent(Out, Space, IsDot)
+            << "{ \"from\": \"" << SI->from().getAsString() << "\", \"to\": \""
+            << SI->to().getAsString() << "\", \"kind\": \""
+            << (SI->isSucceeds() ? "success" : "fail") << "\" }";
+
+        if (std::next(SI) != Set.end())
+          Out << ',';
+        Out << NL;
+      }
+      --Space;
+      Indent(Out, Space, IsDot) << ']';
     }
-    Out << "}";
+    Out << '}';
 
-    if (std::next(I) != DTM.end())
+    if (std::next(I) != Map.end())
       Out << ',';
     Out << NL;
   }
@@ -88,9 +175,10 @@
   Indent(Out, Space, IsDot) << "]," << NL;
 }
 
-void *ProgramStateTrait<DynamicTypeMap>::GDMIndex() {
-  static int index = 0;
-  return &index;
+void printDynamicTypeInfoJson(raw_ostream &Out, ProgramStateRef State,
+                              const char *NL, unsigned int Space, bool IsDot) {
+  printDynamicTypesJson(Out, State, NL, Space, IsDot);
+  printDynamicCastsJson(Out, State, NL, Space, IsDot);
 }
 
 } // namespace ento
Index: clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
===================================================================
--- clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
+++ clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp
@@ -6,7 +6,13 @@
 //
 //===----------------------------------------------------------------------===//
 //
-// This defines CastValueChecker which models casts of custom RTTIs.
+//  This defines CastValueChecker which models casts of custom RTTIs.
+//
+// TODO list:
+// - It only allows one succesful cast between two types however in the wild
+//   the object could be casted to multiple types.
+// - It needs to check the most likely type information from the dynamic type
+//   map to increase precision of dynamic casting.
 //
 //===----------------------------------------------------------------------===//
 
@@ -15,6 +21,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,210 +30,246 @@
 
 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 *,
+      std::function<void(const CastValueChecker *, const CallEvent &Call,
                          DefinedOrUnknownSVal, CheckerContext &)>;
 
-  using CheckKindPair = std::pair<CastCheck, CastKind>;
-
 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;
+  void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
 
 private:
   // These are known in the LLVM project. The pairs are in the following form:
   // {{{namespace, call}, argument-count}, {callback, kind}}
-  const CallDescriptionMap<CheckKindPair> CDM = {
+  const CallDescriptionMap<std::pair<CastCheck, CallKind>> 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,
+  void evalCast(const CallEvent &Call, DefinedOrUnknownSVal DV,
                 CheckerContext &C) const;
-  void evalDynCast(const CallExpr *CE, DefinedOrUnknownSVal DV,
+  void evalDynCast(const CallEvent &Call, DefinedOrUnknownSVal DV,
                    CheckerContext &C) const;
-  void evalCastOrNull(const CallExpr *CE, DefinedOrUnknownSVal DV,
+  void evalCastOrNull(const CallEvent &Call, DefinedOrUnknownSVal DV,
                       CheckerContext &C) const;
-  void evalDynCastOrNull(const CallExpr *CE, DefinedOrUnknownSVal DV,
+  void evalDynCastOrNull(const CallEvent &Call, DefinedOrUnknownSVal DV,
                          CheckerContext &C) const;
-  void evalCastAs(const CallExpr *CE, DefinedOrUnknownSVal DV,
+  void evalCastAs(const CallEvent &Call, DefinedOrUnknownSVal DV,
                   CheckerContext &C) const;
-  void evalGetAs(const CallExpr *CE, DefinedOrUnknownSVal DV,
+  void evalGetAs(const CallEvent &Call, DefinedOrUnknownSVal DV,
                  CheckerContext &C) const;
 };
 } // namespace
 
-static std::string getCastName(const Expr *Cast) {
-  QualType Ty = Cast->getType();
-  if (const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl())
-    return RD->getNameAsString();
+static QualType getRecordType(QualType Ty) {
+  Ty = Ty.getCanonicalType();
+
+  if (Ty->isPointerType())
+    return getRecordType(Ty->getPointeeType());
 
-  return Ty->getPointeeCXXRecordDecl()->getNameAsString();
+  if (Ty->isReferenceType())
+    return getRecordType(Ty.getNonReferenceType());
+
+  return Ty.getUnqualifiedType();
 }
 
-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>();
-  std::string CastToName = getCastName(CE);
-
-  return C.getNoteTag(
-      [CastFromName, CastToName, IsNullReturn,
-       IsCheckedCast](BugReport &) -> std::string {
+//===----------------------------------------------------------------------===//
+// Main logic to evaluate a cast.
+//===----------------------------------------------------------------------===//
+
+static void addCastTransition(const CallEvent &Call, DefinedOrUnknownSVal DV,
+                              CheckerContext &C, bool IsNonNullParam,
+                              bool IsNonNullReturn,
+                              bool IsCheckedCast = false) {
+  ProgramStateRef State = C.getState()->assume(DV, IsNonNullParam);
+  if (!State)
+    return;
+
+  QualType RawCastFromTy =
+      (Call.getNumArgs() > 0)
+          ? Call.parameters()[0]->getType()
+          : cast<CXXInstanceCall>(&Call)->getCXXThisExpr()->getType();
+
+  QualType CastFromTy = getRecordType(RawCastFromTy);
+  QualType CastToTy = getRecordType(Call.getResultType());
+
+  const DynamicCastInfo *Cast = getDynamicCastInfo(State, CastFromTy, CastToTy);
+
+  // We assume that every checked cast succeeds.
+  bool IsCastSucceeds;
+  if (Cast)
+    IsCastSucceeds = IsCheckedCast || (IsNonNullReturn && Cast->isSucceeds());
+  else
+    IsCastSucceeds = IsCheckedCast || IsNonNullReturn || CastFromTy == CastToTy;
+
+  // Check for infeasible casts.
+  if (!IsCheckedCast && Cast) {
+    if ((IsCastSucceeds && Cast->isFails()) ||
+        (!IsCastSucceeds && Cast->isSucceeds())) {
+      C.generateSink(State, C.getPredecessor());
+      return;
+    }
+  }
+
+  // Store the type and the cast information.
+  const MemRegion *MR = DV.getAsRegion();
+  bool IsKnownCast = Cast || CastFromTy == CastToTy;
+  if (!IsKnownCast)
+    State = setDynamicTypeAndCastInfo(State, MR, CastFromTy, CastToTy,
+                                      Call.getResultType(), IsCastSucceeds);
+
+  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 << (IsKnownCast ? "Dynamic cast" : "Assuming dynamic cast");
+        else
+          Out << "Checked cast";
 
-        Out << "to '" << CastToName << "' "
-            << (!IsNullReturn ? "succeeds" : "fails");
+        Out << " from '" << CastFromTy->getAsCXXRecordDecl()->getNameAsString()
+            << "' to '" << CastToTy->getAsCXXRecordDecl()->getNameAsString()
+            << "' " << (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(Call.getOriginExpr(), C.getLocationContext(), V, false),
+      Tag);
 }
 
 //===----------------------------------------------------------------------===//
 // Evaluating cast, dyn_cast, cast_or_null, dyn_cast_or_null.
 //===----------------------------------------------------------------------===//
 
-static void evalNonNullParamNonNullReturn(const CallExpr *CE,
+static void evalNonNullParamNonNullReturn(const CallEvent &Call,
                                           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(Call, DV, C, /*IsNonNullParam=*/true,
+                    /*IsNonNullReturn=*/true, IsCheckedCast);
 }
 
-static void evalNonNullParamNullReturn(const CallExpr *CE,
+static void evalNonNullParamNullReturn(const CallEvent &Call,
                                        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(Call, DV, C, /*IsNonNullParam=*/true,
+                    /*IsNonNullReturn=*/false);
 }
 
-static void evalNullParamNullReturn(const CallExpr *CE, DefinedOrUnknownSVal DV,
+static void evalNullParamNullReturn(const CallEvent &Call,
+                                    DefinedOrUnknownSVal DV,
                                     CheckerContext &C) {
   if (ProgramStateRef State = C.getState()->assume(DV, false))
-    C.addTransition(getState(/*IsNullReturn=*/true, DV, CE, State, C),
+    C.addTransition(State->BindExpr(Call.getOriginExpr(),
+                                    C.getLocationContext(),
+                                    C.getSValBuilder().makeNull(), false),
                     C.getNoteTag("Assuming null pointer is passed into cast",
                                  /*IsPrunable=*/true));
 }
 
-void CastValueChecker::evalCast(const CallExpr *CE, DefinedOrUnknownSVal DV,
+void CastValueChecker::evalCast(const CallEvent &Call, DefinedOrUnknownSVal DV,
                                 CheckerContext &C) const {
-  evalNonNullParamNonNullReturn(CE, DV, C, /*IsCheckedCast=*/true);
+  evalNonNullParamNonNullReturn(Call, DV, C, /*IsCheckedCast=*/true);
 }
 
-void CastValueChecker::evalDynCast(const CallExpr *CE, DefinedOrUnknownSVal DV,
+void CastValueChecker::evalDynCast(const CallEvent &Call,
+                                   DefinedOrUnknownSVal DV,
                                    CheckerContext &C) const {
-  evalNonNullParamNonNullReturn(CE, DV, C);
-  evalNonNullParamNullReturn(CE, DV, C);
+  evalNonNullParamNonNullReturn(Call, DV, C);
+  evalNonNullParamNullReturn(Call, DV, C);
 }
 
-void CastValueChecker::evalCastOrNull(const CallExpr *CE,
+void CastValueChecker::evalCastOrNull(const CallEvent &Call,
                                       DefinedOrUnknownSVal DV,
                                       CheckerContext &C) const {
-  evalNonNullParamNonNullReturn(CE, DV, C);
-  evalNullParamNullReturn(CE, DV, C);
+  evalNonNullParamNonNullReturn(Call, DV, C);
+  evalNullParamNullReturn(Call, DV, C);
 }
 
-void CastValueChecker::evalDynCastOrNull(const CallExpr *CE,
+void CastValueChecker::evalDynCastOrNull(const CallEvent &Call,
                                          DefinedOrUnknownSVal DV,
                                          CheckerContext &C) const {
-  evalNonNullParamNonNullReturn(CE, DV, C);
-  evalNonNullParamNullReturn(CE, DV, C);
-  evalNullParamNullReturn(CE, DV, C);
+  evalNonNullParamNonNullReturn(Call, DV, C);
+  evalNonNullParamNullReturn(Call, DV, C);
+  evalNullParamNullReturn(Call, DV, C);
 }
 
 //===----------------------------------------------------------------------===//
 // Evaluating castAs, getAs.
 //===----------------------------------------------------------------------===//
 
-static void evalZeroParamNonNullReturn(const CallExpr *CE,
+static void evalZeroParamNonNullReturn(const CallEvent &Call,
                                        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(Call, DV, C, /*IsNonNullParam=*/true,
+                    /*IsNonNullReturn=*/true, IsCheckedCast);
 }
 
-static void evalZeroParamNullReturn(const CallExpr *CE, DefinedOrUnknownSVal DV,
+static void evalZeroParamNullReturn(const CallEvent &Call,
+                                    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(Call, DV, C, /*IsNonNullParam=*/true,
+                    /*IsNonNullReturn=*/false);
 }
 
-void CastValueChecker::evalCastAs(const CallExpr *CE, DefinedOrUnknownSVal DV,
+void CastValueChecker::evalCastAs(const CallEvent &Call,
+                                  DefinedOrUnknownSVal DV,
                                   CheckerContext &C) const {
-  evalZeroParamNonNullReturn(CE, DV, C, /*IsCheckedCast=*/true);
+  evalZeroParamNonNullReturn(Call, DV, C, /*IsCheckedCast=*/true);
 }
 
-void CastValueChecker::evalGetAs(const CallExpr *CE, DefinedOrUnknownSVal DV,
+void CastValueChecker::evalGetAs(const CallEvent &Call, DefinedOrUnknownSVal DV,
                                  CheckerContext &C) const {
-  evalZeroParamNonNullReturn(CE, DV, C);
-  evalZeroParamNullReturn(CE, DV, C);
+  evalZeroParamNonNullReturn(Call, DV, C);
+  evalZeroParamNullReturn(Call, DV, C);
 }
 
+//===----------------------------------------------------------------------===//
+// Main logic to evaluate a call.
+//===----------------------------------------------------------------------===//
+
 bool CastValueChecker::evalCall(const CallEvent &Call,
                                 CheckerContext &C) const {
   const auto *Lookup = CDM.lookup(Call);
   if (!Lookup)
     return false;
 
-  // If we cannot obtain the call's class we cannot be sure how to model it.
-  QualType ResultTy = Call.getResultType();
-  if (!ResultTy->getPointeeCXXRecordDecl())
+  // We need to obtain the record type of the call's result to model it.
+  if (!Call.getResultType()->getPointeeCXXRecordDecl())
     return false;
 
   const CastCheck &Check = Lookup->first;
-  CastKind Kind = Lookup->second;
-
-  const auto *CE = cast<CallExpr>(Call.getOriginExpr());
+  CallKind Kind = Lookup->second;
   Optional<DefinedOrUnknownSVal> DV;
 
   switch (Kind) {
-  case CastKind::Function: {
-    // If we cannot obtain the arg's class we cannot be sure how to model it.
+  case CallKind::Function: {
+    // We need to obtain the record type of the call's parameter to model it.
     QualType ArgTy = Call.parameters()[0]->getType();
     if (!ArgTy->getAsCXXRecordDecl() && !ArgTy->getPointeeCXXRecordDecl())
       return false;
@@ -234,8 +277,7 @@
     DV = Call.getArgSVal(0).getAs<DefinedOrUnknownSVal>();
     break;
   }
-  case CastKind::Method:
-    // If we cannot obtain the 'InstanceCall' we cannot be sure how to model it.
+  case CallKind::Method:
     const auto *InstanceCall = dyn_cast<CXXInstanceCall>(&Call);
     if (!InstanceCall)
       return false;
@@ -247,10 +289,22 @@
   if (!DV)
     return false;
 
-  Check(this, CE, *DV, C);
+  Check(this, Call, *DV, C);
   return true;
 }
 
+void CastValueChecker::checkDeadSymbols(SymbolReaper &SR,
+                                        CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+
+  DynamicCastMapTy SucceedMap = State->get<DynamicCastMap>();
+  for (const auto &Elem : SucceedMap)
+    if (!SR.isLiveRegion(Elem.first))
+      State = State->remove<DynamicCastMap>(Elem.first);
+
+  C.addTransition(State);
+}
+
 void ento::registerCastValueChecker(CheckerManager &Mgr) {
   Mgr.registerChecker<CastValueChecker>();
 }
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,45 +13,53 @@
 #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/DynamicCastInfo.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 {
-
-class MemRegion;
+#include "llvm/ADT/Optional.h"
+#include <utility>
 
 /// The GDM component containing the dynamic type info. This is a map from a
 /// symbol to its most likely type.
-struct DynamicTypeMap {};
+REGISTER_MAP_WITH_PROGRAMSTATE(DynamicTypeMap, const clang::ento::MemRegion *,
+                               clang::ento::DynamicTypeInfo)
+
+/// A set factory of dynamic cast informations.
+REGISTER_SET_FACTORY_WITH_PROGRAMSTATE(CastSet, clang::ento::DynamicCastInfo)
+
+/// A map from symbols to cast informations.
+REGISTER_MAP_WITH_PROGRAMSTATE(DynamicCastMap, const clang::ento::MemRegion *,
+                               CastSet)
 
-using DynamicTypeMapTy = llvm::ImmutableMap<const MemRegion *, DynamicTypeInfo>;
+namespace clang {
+namespace ento {
 
-template <>
-struct ProgramStateTrait<DynamicTypeMap>
-    : public ProgramStatePartialTrait<DynamicTypeMapTy> {
-  static void *GDMIndex();
-};
+/// Get dynamic type information for the region \p MR.
+DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State, const MemRegion *MR);
 
-/// Get dynamic type information for a region.
-DynamicTypeInfo getDynamicTypeInfo(ProgramStateRef State,
-                                   const MemRegion *Reg);
+/// Get dynamic cast information from \p CastFromTy type to \p CastToTy type.
+const DynamicCastInfo *getDynamicCastInfo(ProgramStateRef State,
+                                          QualType CastFromTy,
+                                          QualType CastToTy);
 
 /// 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 and cast information of the region; return the new state.
+ProgramStateRef setDynamicTypeAndCastInfo(ProgramStateRef State,
+                                          const MemRegion *MR,
+                                          QualType CastFromTy,
+                                          QualType CastToTy, QualType ResultTy,
+                                          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
@@ -1,10 +1,11 @@
-//== DynamicTypeInfo.h - Runtime type information ----------------*- C++ -*--=//
+//===- DynamicTypeInfo.h - Runtime type information -------------*- C++ -*-===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===----------------------------------------------------------------------===//
+
 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEINFO_H
 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEINFO_H
 
@@ -16,36 +17,37 @@
 /// Stores the currently inferred strictest bound on the runtime type
 /// of a region in a given state along the analysis path.
 class DynamicTypeInfo {
-private:
-  QualType T;
-  bool CanBeASubClass;
-
 public:
+  DynamicTypeInfo() : DynTy(QualType()) {}
 
-  DynamicTypeInfo() : T(QualType()) {}
-  DynamicTypeInfo(QualType WithType, bool CanBeSub = true)
-    : T(WithType), CanBeASubClass(CanBeSub) {}
+  DynamicTypeInfo(QualType Ty, bool CanBeSub = true)
+      : DynTy(Ty), CanBeASubClass(CanBeSub) {}
+
+  /// 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; }
 
-  /// Return false if no dynamic type info is available.
-  bool isValid() const { return !T.isNull(); }
+  /// 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 T; }
+  QualType getType() const { return DynTy; }
 
-  /// Returns false if the type information is precise (the type T is
-  /// the only type in the lattice), true otherwise.
-  bool canBeASubClass() const { return CanBeASubClass; }
+  bool operator==(const DynamicTypeInfo &RHS) const {
+    return DynTy == RHS.DynTy && CanBeASubClass == RHS.CanBeASubClass;
+  }
 
   void Profile(llvm::FoldingSetNodeID &ID) const {
-    ID.Add(T);
-    ID.AddInteger((unsigned)CanBeASubClass);
-  }
-  bool operator==(const DynamicTypeInfo &X) const {
-    return T == X.T && CanBeASubClass == X.CanBeASubClass;
+    ID.Add(DynTy);
+    ID.AddBoolean(CanBeASubClass);
   }
+
+private:
+  QualType DynTy;
+  bool CanBeASubClass;
 };
 
-} // end ento
-} // end clang
+} // namespace ento
+} // namespace clang
 
-#endif
+#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICTYPEINFO_H
Index: clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h
===================================================================
--- /dev/null
+++ clang/include/clang/StaticAnalyzer/Core/PathSensitive/DynamicCastInfo.h
@@ -0,0 +1,55 @@
+//===- DynamicCastInfo.h - Runtime cast information -------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICCASTINFO_H
+#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICCASTINFO_H
+
+#include "clang/AST/Type.h"
+
+namespace clang {
+namespace ento {
+
+class DynamicCastInfo {
+public:
+  enum CastKind { Success, Fail };
+
+  DynamicCastInfo(QualType from, QualType to, CastKind kind)
+      : From(from), To(to), Kind(kind) {}
+
+  QualType from() const { return From; }
+  QualType to() const { return To; }
+
+  bool equals(QualType from, QualType to) const {
+    return From == from && To == to;
+  }
+
+  bool isSucceeds() const { return Kind == CastKind::Success; }
+  bool isFails() const { return Kind == CastKind::Fail; }
+
+  bool operator==(const DynamicCastInfo &RHS) const {
+    return From == RHS.From && To == RHS.To;
+  }
+  bool operator<(const DynamicCastInfo &RHS) const {
+    return From < RHS.From && To < RHS.To;
+  }
+
+  void Profile(llvm::FoldingSetNodeID &ID) const {
+    ID.Add(From);
+    ID.Add(To);
+    ID.AddInteger(Kind);
+  }
+
+private:
+  QualType From, To;
+  CastKind Kind;
+};
+
+} // namespace ento
+} // namespace clang
+
+#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_DYNAMICCASTINFO_H
Index: clang/include/clang/AST/Type.h
===================================================================
--- clang/include/clang/AST/Type.h
+++ clang/include/clang/AST/Type.h
@@ -972,6 +972,9 @@
   friend bool operator!=(const QualType &LHS, const QualType &RHS) {
     return LHS.Value != RHS.Value;
   }
+  friend bool operator<(const QualType &LHS, const QualType &RHS) {
+    return LHS.Value < RHS.Value;
+  }
 
   static std::string getAsString(SplitQualType split,
                                  const PrintingPolicy &Policy) {
_______________________________________________
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to