Check dynamic_cast is not used with -fno-rtti, unless it is a noop or can be resolved statically.

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@187564 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/include/clang/Basic/DiagnosticSemaKinds.td b/include/clang/Basic/DiagnosticSemaKinds.td
index f6a3515..6438008 100644
--- a/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5036,6 +5036,8 @@
 
 def err_no_typeid_with_fno_rtti : Error<
   "cannot use typeid with -fno-rtti">;
+def err_no_dynamic_cast_with_fno_rtti : Error<
+  "cannot use dynamic_cast with -fno-rtti">;
 
 def err_cannot_form_pointer_to_member_of_reference_type : Error<
   "cannot form a pointer-to-member to member %0 of reference type %1">;
diff --git a/lib/Sema/SemaCast.cpp b/lib/Sema/SemaCast.cpp
index 1adb037..888c14e 100644
--- a/lib/Sema/SemaCast.cpp
+++ b/lib/Sema/SemaCast.cpp
@@ -667,6 +667,13 @@
   Self.MarkVTableUsed(OpRange.getBegin(), 
                       cast<CXXRecordDecl>(SrcRecord->getDecl()));
 
+  // dynamic_cast is not available with fno-rtti
+  if (!Self.getLangOpts().RTTI) {
+    Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
+    SrcExpr = ExprError();
+    return;
+  }
+
   // Done. Everything else is run-time checks.
   Kind = CK_Dynamic;
 }
diff --git a/test/CodeGenCXX/dynamic_cast-no-rtti.cpp b/test/CodeGenCXX/dynamic_cast-no-rtti.cpp
new file mode 100644
index 0000000..2060e1d
--- /dev/null
+++ b/test/CodeGenCXX/dynamic_cast-no-rtti.cpp
@@ -0,0 +1,26 @@
+// RUN: %clang_cc1 -emit-llvm %s -verify -fno-rtti -o - | FileCheck %s
+// expected-no-diagnostics
+
+struct A {
+  virtual ~A(){};
+};
+
+struct B : public A {
+  B() : A() {}
+};
+
+// An upcast can be resolved statically and can be used with -fno-rtti, iff it
+// does not use runtime support.
+A *upcast(B *b) {
+  return dynamic_cast<A *>(b);
+// CHECK: define %struct.A* @_Z6upcastP1B
+// CHECK-NOT: call i8* @__dynamic_cast
+}
+
+// A NoOp dynamic_cast can be used with -fno-rtti iff it does not use
+// runtime support.
+B *samecast(B *b) {
+  return dynamic_cast<B *>(b);
+// CHECK: define %struct.B* @_Z8samecastP1B
+// CHECK-NOT: call i8* @__dynamic_cast
+}
diff --git a/test/SemaCXX/no-rtti.cpp b/test/SemaCXX/no-rtti.cpp
index 75167050..3d6e109 100644
--- a/test/SemaCXX/no-rtti.cpp
+++ b/test/SemaCXX/no-rtti.cpp
@@ -8,3 +8,17 @@
 {
   (void)typeid(int); // expected-error {{cannot use typeid with -fno-rtti}}
 }
+
+namespace {
+struct A {
+  virtual ~A(){};
+};
+
+struct B : public A {
+  B() : A() {}
+};
+}
+
+bool isa_B(A *a) {
+  return dynamic_cast<B *>(a) != 0; // expected-error {{cannot use dynamic_cast with -fno-rtti}}
+}